From 1fe96a1f5273a3ed9a47d8bcebdadb53e17baf78 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:35:24 -0500 Subject: [PATCH 001/159] Spec: split backfill by date, pack message-ids, seal files into blobs, auto compact Co-Authored-By: Claude Opus 5.5 --- ...-faster-backfill-smaller-storage-design.md | 165 ++++++++++++++++++ 1 file changed, 165 insertions(+) create mode 100644 docs/superpowers/specs/2026-10-05-faster-backfill-smaller-storage-design.md diff --git a/docs/superpowers/specs/2026-10-05-faster-backfill-smaller-storage-design.md b/docs/superpowers/specs/2026-10-05-faster-backfill-smaller-storage-design.md new file mode 100644 index 00000000..eff77b4e --- /dev/null +++ b/docs/superpowers/specs/2026-10-05-faster-backfill-smaller-storage-design.md @@ -0,0 +1,165 @@ +# Faster backfill and smaller storage: design + +Date: 2026-10-05. Status: approved in chat, pending spec review. + +## Context + +Atlas indexes about 220k headers/s across 7 usenet servers. The database is 8 SQLite shards (`atlas.s0.db` .. `atlas.s7.db`, split by group) plus `atlas.db` (group cursors, id counter); see `src/store.rs`. Each article is a `segments` row: `(file_id, local BLOB, domain, part, bytes)`, keyed `(file_id, local, domain)` in a WITHOUT ROWID table. `local` is the message-id's local part (hex packed into bytes, anything else stored as text) and `domain` points at a shared `domains` row (0 = the whole message-id stored in `local`). One shard holds about 9.8M files and 221M segments, the average `local` is 32 bytes, and the shards total 138.5 GB. + +Two limits remain: + +- **Speed:** each group is pinned to one server (cursors are per server because article numbers differ by provider). Big groups and groups only a small server carries pile onto that server (super.newsgroupdirect.com, 15 connections, is always full) while other servers have idle connections. +- **Storage:** about 80 bytes per article, which full retention multiplies into many terabytes. + +This design adds four things, built in this order: + +1. Split big groups' backfill across servers by date +2. Pack message-id local parts by shape +3. Seal finished files into one compressed blob each +4. `auto_run_compact` in config.json + +## 1. Split backfill by date + +### Behavior + +A group is **split** when at least 2 indexing servers carry it and its home server still has more than `SPLIT_MIN_BACKLOG` (10,000,000) article numbers of backfill left. Its remaining history is cut into **day chunks** (UTC days). Any worker on a server that carries the group may claim the next pending chunk, index that day's articles on its own server, and mark the chunk done. Live indexing (new posts) stays on the group's home server, unchanged. + +Workers prefer their own groups. A worker with nothing of its own to do (all its groups busy, resting or caught up) claims a chunk instead. The newest pending chunk goes first, so history fills in from the present backwards like normal backfill. + +### Chunk table (atlas.db) + +```sql +create table if not exists backfill_chunks ( + grp TEXT NOT NULL, + day INTEGER NOT NULL, -- unix day (days since 1970-01-01 UTC) + state INTEGER NOT NULL, -- 0 pending, 1 claimed, 2 done + server TEXT, -- host that claimed / did it + claimed_at INTEGER, -- unix seconds + primary key (grp, day) +) without rowid; +``` + +- **Creating chunks:** when a group first qualifies, Atlas creates its chunks from the day of its home backfill frontier (the post date at the home cursor, from `groups.low_posted`, or now if unknown) back to the oldest day any carrying server retains. That oldest day is the post date of the article at the server's GROUP low-water mark, found with a single-article XOVER. +- **Stale claims:** a claim older than `CHUNK_CLAIM_TIMEOUT` (30 min) is pending again (its worker died or the indexer was stopped). +- **Home cursor:** once a group is split, the home server's backfill cursor no longer drives backfill. Its passes take chunks like any other server's. + +### Day to article numbers + +`Pool::article_at(server, group, unix_time) -> u64` finds the first article posted at or after `unix_time`. It binary-searches the server's article range with `XOVER n-n` (one article). Missing article numbers (423) are skipped forward to the next article that exists, up to 100 at a time. Results are cached in memory per `(server, group, day)`. + +A chunk for day D covers articles posted from `D - 1 hour` to `D + 1 day + 1 hour`. Post dates aren't perfectly ordered by article number, so the overlap avoids gaps at the edges; duplicates are rejected by the segments key. The chunk's number range is fetched and saved with the existing `stream_headers` and `save_slice` path, in `request_size` slices. + +### Failure handling + +- **A server dies mid-chunk:** the chunk stays claimed until it times out, then is retried. Articles already saved stay and are deduplicated on the retry. +- **The binary search fails** (server error): the chunk is released and the error counted like a pass error. +- **A server doesn't carry the group** (411): that server is skipped for the group's chunks. + +### Dashboard + +On the Backfill page, a split group's progress counts done chunks. The "days per day" figure uses chunks done per hour across all servers. + +## 2. Pack message-id locals by shape + +`store::pack_local` picks the smallest alphabet the local part fits and stores `[tag][len][bytes]`, where `bytes` is the local part read as a base-N big number: + +| Tag | Alphabet | N | +|---|---|---| +| 1 | `0-9a-f` (existing hex, no length byte, kept for compatibility) | 16 | +| 2 | `0-9A-F` (existing) | 16 | +| 3 | `0-9` | 10 | +| 4 | `0-9a-z` | 36 | +| 5 | `0-9A-Z` | 36 | +| 6 | `0-9A-Za-z` (Nyuu: letters plus timestamp) | 62 | +| 7 | `0-9A-Za-z-_` | 64 | +| 0 | anything else, stored as text (existing) | n/a | + +- **Length byte:** it restores leading zero-digits, and the local part must be 1–255 characters. Longer ones fall back to tag 0. +- **Hex:** tags 1 and 2 stay as they are, so existing rows don't change meaning. +- **Odd-length hex:** goes to tag 4 or 5. +- **Encoding is deterministic:** the same message-id always encodes the same way. + +**Duplicates across encodings:** a row saved before this change may hold the same message-id as text (tag 0). When `add_segment` packs a local into tag 3–7, it also checks for the tag-0 form under the same `(file_id, domain)`, the way it already checks the whole-id form. + +**Existing data:** `--compact` re-encodes every local part into the new form. Expected saving: about 20–25% of the `local` column, around 8 bytes per article on base62 and base64 IDs. + +## 3. Seal finished files into blobs + +### Schema (each shard) + +```sql +alter table files add column blob BLOB; -- null until sealed +alter table files add column touched_at INTEGER; -- unix seconds of the last article added +``` + +`touched_at` is set by `put_file` whenever articles are added. Existing rows start with null, meaning untouched since the upgrade. + +### Blob format v1 + +The blob is zstd (level 6) over: + +``` +u8 version = 1 +varint count +for each segment, sorted by (part with a missing part first, message-id): + varint part_plus_one -- 0 = no part number + zigzag varint bytes_delta -- bytes minus the previous segment's bytes (first: minus 0) + varint domain + varint local_len, local bytes -- the packed local from section 2 +``` + +The order is exactly the order NZBs list segments in, so a blob decodes straight into `ArticleRow`s. Only part numbers, sizes and message-ids are needed; the subject, poster and date come from the `files` and `releases` rows, as today. + +### Sealing + +A file is eligible when it isn't sealed yet and either: + +- it's complete: its `seen` bitmap is exactly parts 1..`expected`, or +- `touched_at` is older than 3 days. A null `touched_at` counts as old, so existing data seals in the first compaction. + +To seal: read the file's segment rows, encode the blob, write `files.blob`, and delete the file's segment rows, all in one transaction. + +Sealing happens in two places: + +- **Online:** each shard writer, between save transactions, seals up to `SEAL_PER_TICK` (2,000) eligible files. It picks them from files touched in its recent transactions (complete ones) and from a cursor walking the `files` table by id (aged ones), so it never scans everything at once. Sealing time counts toward writer busy time and shows on the Bottleneck page. +- **Offline:** `--compact` seals every eligible file in its copy pass. + +### Reading + +`store::articles` decodes the blob, if there is one, and merges it with any segment rows for the file, which are articles that arrived after sealing. It then sorts by (filename, part, message-id) as today. + +### Late articles + +`add_segment` for a sealed file decodes the blob once per writer transaction (cached per file id) and skips any article already in it. New articles become ordinary segment rows. A sealed file with late rows is eligible again 3 days after its last touch and is resealed into a single blob. + +### Size + +Expected about 15–27 bytes per article inside blobs, versus about 55–70 as rows. The 138 GB total should drop to roughly 60 GB once compacted. + +## 4. auto_run_compact + +- **Setting:** `config.json` gains `"auto_run_compact": false` (the default, `Config::auto_run_compact()`). +- **When it runs:** when true, the background indexer checks once a minute whether 24 hours have passed since the last compaction. The time is stored in `atlas.db` as `meta('last_compact', unix seconds)`; without a stored time, it counts from when the indexer started. When the time is due: + 1. Set wind-down: workers finish their passes and start no new ones, as on a config change. + 2. Once `run_servers` returns (writers and checkpointer closed), run `compact::run` in the same process. The status label shows `compacting the database`, plus `compact::run`'s progress lines. + 3. Store `last_compact` and resume indexing. +- **Errors:** a compaction error is logged and counted. The originals are untouched by design, indexing resumes, and the next try is 24 hours later. +- **Manual runs:** `atlas --compact` still refuses to run while the indexer is running. + +## Testing + +- **Codec:** round trips for every tag over real-shaped message-ids (Nyuu, ngPost hex, JBinUp, camelsystem, random alphanumeric, odd lengths, longer than 255, empty), plus a check that encoding is deterministic. +- **Blob:** encode/decode round trips; NZBs byte for byte equal before and after sealing on generated releases, including ties, missing parts and missing filenames. +- **Late articles:** a sealed file plus a late article gives no duplicate and a correct NZB. A re-sent article that is already in the blob isn't saved. +- **Legacy duplicates:** a tag-0 row plus the same article re-sent packed gives no duplicate. +- **article_at:** against a mock server whose articles have known post dates, including gaps (423) and out-of-order dates. +- **Chunk queue:** two mock servers carry the same group with different article numbering, and the group is split. Both servers do chunks. Every article is indexed exactly once, and stale claims are taken over. +- **Compact:** re-encodes and seals. NZBs, row counts and stats are checked against the original (extends the existing `compact` test). +- **auto_run_compact:** with a 24-hour interval injected as a short duration in the test, the indexer winds down, compacts, records `last_compact`, and resumes. +- Everything passes `just format`, `just lint`, `just test`. + +## Out of scope + +- Pooling connections across servers that share article numbering (news.newsgroupdirect and viper do, but viper has 3 connections, so it's a small gain). +- Pipelining, XZVER, and request-size changes (measured: little gain under server-side latency). +- Dropping incomplete old releases (conflicts with keeping all history). From 384ca8f6bc8e83d2542a1e814c66fdad08c21fc5 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:41:30 -0500 Subject: [PATCH 002/159] Plan: split backfill, packed message-ids, sealed blobs, auto compact Co-Authored-By: Claude Opus 5.5 --- ...6-10-05-faster-backfill-smaller-storage.md | 1947 +++++++++++++++++ 1 file changed, 1947 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-05-faster-backfill-smaller-storage.md diff --git a/docs/superpowers/plans/2026-10-05-faster-backfill-smaller-storage.md b/docs/superpowers/plans/2026-10-05-faster-backfill-smaller-storage.md new file mode 100644 index 00000000..2340234c --- /dev/null +++ b/docs/superpowers/plans/2026-10-05-faster-backfill-smaller-storage.md @@ -0,0 +1,1947 @@ +# Faster Backfill and Smaller Storage Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Split big groups' backfill across usenet servers by day, pack message-id locals by shape, seal finished files into zstd blobs, and add an opt-in 24 hour auto compaction. + +**Architecture:** Day chunks of a split group live in a `backfill_chunks` table in `atlas.db`; idle workers on any carrying server claim one, map the day to that server's article numbers by binary search (`Pool::article_at`), and index it through the existing `process_range` path. Storage changes stay inside the shard layer (`src/store.rs` plus a new `src/blob.rs` codec): a new local-part packing, and a `blob` column on `files` that replaces a file's `segments` rows once it's complete or untouched for 3 days. `atlas --compact` gains re-encoding and sealing; the background indexer can run it every 24 hours. + +**Tech Stack:** Rust 1.99 (edition 2024), tokio, rusqlite 0.40 (bundled SQLite), new dependency `zstd = "0.13"`. + +**Spec:** `docs/superpowers/specs/2026-10-05-faster-backfill-smaller-storage-design.md` + +## Global Constraints + +- Rust toolchain 1.99.0 (pinned in `rust-toolchain.toml`). Run commands through `just` (`just test`, `just lint`, `just format`) so the pinned toolchain is used. +- `just lint` is `cargo clippy --all-targets --locked -- -D warnings`: no warnings allowed. Clippy lints seen in this repo: `manual_is_multiple_of`, `type_complexity` (use type aliases), `needless_borrow`, `unnecessary_cast`. +- `--locked`: adding the `zstd` dependency (Task 7) must update `Cargo.lock` in the same commit. +- Comment style: short lowercase-start comments, plain words, matching the surrounding code. Doc comments on public items. +- Never touch the user's live data: `atlas.db`, `atlas.s*.db`, `config.json`, `news.txt` in the repo root. Tests use `tempfile::tempdir()` and `ATLAS_HOME`; integration tests that set env vars are the only test in their binary. +- Commits: `git commit` as the configured user (xbmc4lyfe, SSH signed); end every message with `Co-Authored-By: Claude Opus 5.5 `. Don't push. +- Constants (verbatim from the spec): `SPLIT_MIN_BACKLOG = 10_000_000`, `CHUNK_CLAIM_TIMEOUT = 30 min`, chunk overlap 1 hour, `SEAL_PER_TICK = 2_000`, seal age 3 days, zstd level 6, compact interval 24 hours, `auto_run_compact` default `false`. + +## Model routing (for the controller) + +| Task | Model | Why | +|---|---|---| +| 1 article_at | sonnet | protocol code + mock change, clear spec | +| 2 chunk table | haiku | plain SQL functions + unit tests | +| 3 run_chunk | sonnet | joins existing pass machinery | +| 4 scheduler split | opus | concurrency, scheduling, e2e test | +| 5 dashboard progress | haiku | small read-only change | +| 6 local packing | sonnet | codec with exactness requirements | +| 7 blob codec | sonnet | self-contained codec | +| 8 sealing in store | opus | schema, read path, dedupe correctness | +| 9 online sealing | sonnet | writer loop integration | +| 10 compact re-encode + seal | sonnet | extends existing tool + check | +| 11 auto_run_compact | sonnet | supervise loop + config | +| 12 docs + full verification | haiku | README + run the suite | + +--- + +## Part A: split backfill by date + +### Task 1: `Pool::article_at` (day to article number) and mock post dates + +**Files:** +- Modify: `src/nntp.rs` (add `posted_at` and `article_at` to `impl Pool`, near `select_group_on`) +- Modify: `tests/common/mod.rs` (`Post` gets a `date`, the mock's XOVER uses it) +- Test: `tests/date_search.rs` (new) + +**Interfaces:** +- Consumes: `Pool::xover_on(&self, i: usize, group: &str, start: u64, end: u64) -> Result>` (private, same impl), `crate::dates::posted_timestamp(&str) -> Option`. +- Produces: `pub async fn article_at(&self, i: usize, group: &str, low: u64, high: u64, when: i64) -> Result`. Returns the first article number in `low..=high` posted at or after `when` (unix seconds), or `high + 1` if none. Also `pub fn post_at(number: u64, subject: &str, date: &str) -> Post` in `tests/common/mod.rs`. + +- [ ] **Step 1: Give mock posts a date** + +In `tests/common/mod.rs`, add `pub date: String` to `struct Post`. Update `post()` so every existing test keeps the old date: + +```rust +pub fn post(number: u64, subject: &str, bytes: u64, body: Vec>) -> Post { + Post { + number, + subject: subject.into(), + message_id: format!(""), + bytes, + body, + date: "Fri, 02 Oct 2026 10:11:12 +0000".into(), + } +} + +/// A post with its own date (rfc 2822), for date based tests. +pub fn post_at(number: u64, subject: &str, date: &str) -> Post { + Post { date: date.into(), ..post(number, subject, 10, vec![]) } +} +``` + +In the XOVER row `format!`, replace the literal `Fri, 02 Oct 2026 10:11:12 +0000` with `{}` and pass `p.date`. Run `grep -rn "Post {" tests/` and fix any struct literal that now lacks `date`. + +- [ ] **Step 2: Write the failing test** + +Create `tests/date_search.rs`: + +```rust +//! Finding the article posted at a given time by binary search over one +//! article XOVERs, with gaps in the numbering and slightly out of order dates. + +mod common; + +use atlas::nntp::BlockingPool; +use common::{GROUP, Server, mock, post_at, spawn_server}; + +/// posts 1..=1000, one per hour from 2026-01-01 00:00 UTC, with every 10th +/// number missing and number 500 dated an hour too early +fn hourly() -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (1..=1000u64) + .filter(|n| n % 10 != 0) + .map(|n| { + let hours = if n == 500 { n as i64 - 2 } else { n as i64 - 1 }; + let when = start + chrono::Duration::hours(hours); + post_at(n, &format!(r#""p{n}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() +} + +#[test] +fn finds_the_first_article_at_or_after_a_time() { + let port = spawn_server(Server::new(hourly())); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + let at = |rfc3339: &str| { + let t = chrono::DateTime::parse_from_rfc3339(rfc3339).unwrap().timestamp(); + pool.block_on(pool.pool.article_at(0, GROUP, 1, 1000, t)).unwrap() + }; + + assert_eq!(at("2025-12-01T00:00:00+00:00"), 1, "before everything: the first article"); + assert_eq!(at("2026-01-01T04:00:00+00:00"), 5, "exactly on an article"); + assert_eq!(at("2026-01-01T08:30:00+00:00"), 11, "number 10 is missing, 11 is next"); + assert_eq!(at("2026-03-01T00:00:00+00:00"), 1001, "after everything: high + 1"); +} +``` + +- [ ] **Step 3: Run it to see it fail** + +Run: `cargo test --test date_search` +Expected: compile error, `no method named article_at`. + +- [ ] **Step 4: Implement** + +In `src/nntp.rs`, inside `impl Pool`: + +```rust +/// The first article at or after `number` within the next `look` numbers on +/// server `i`, with its post time: (number, unix seconds). None when there is +/// none (a gap in the numbering). +async fn posted_at(&self, i: usize, group: &str, number: u64, look: u64) -> Result> { + match self.xover_on(i, group, number, number + look - 1).await { + Ok(rows) => Ok(rows + .iter() + .filter_map(|r| crate::dates::posted_timestamp(&r.date).map(|t| (r.number, t))) + .min_by_key(|(n, _)| *n)), + Err(e) if e.code() == Some(423) => Ok(None), + Err(e) => Err(e), + } +} + +/// The first article number in `low..=high` on server `i` posted at or after +/// `when` (unix seconds), `high + 1` when there is none. A binary search over +/// one article requests (about 35 for a billion numbers). Post dates are +/// only roughly in order, soo the answer is approximate near the edges: +/// callers overlap their ranges. +pub async fn article_at(&self, i: usize, group: &str, low: u64, high: u64, when: i64) -> Result { + const LOOK: u64 = 100; + let (mut lo, mut hi) = (low, high + 1); + while lo < hi { + let mid = lo + (hi - lo) / 2; + match self.posted_at(i, group, mid, LOOK).await? { + Some((n, t)) if t < when => lo = n + 1, + Some(_) => hi = mid, + // a gap: nothing to compare, keep searching to the left of it + None => hi = mid, + } + } + Ok(lo) +} +``` + +`Overview` has a public `date` field and `number` (check with `grep -n "pub struct Overview" -A10 src/nntp.rs`). If the mock group's articles are not selected on the connection yet, `xover_on` already selects the group. Make sure `xover_on` is reachable from `article_at`; it's in the same `impl`. + +- [ ] **Step 5: Run the tests** + +Run: `cargo test --test date_search && just test` +Expected: PASS, and every other test still passes (the mock date default is unchanged). + +- [ ] **Step 6: Commit** + +```bash +git add src/nntp.rs tests/common/mod.rs tests/date_search.rs +git commit -m "Find the article posted at a time by binary search + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +### Task 2: `backfill_chunks` table and its functions + +**Files:** +- Create: `src/chunks.rs` +- Modify: `src/lib.rs` (`pub mod chunks;`) +- Modify: `src/store.rs` (`create_main` creates the table) +- Test: unit tests in `src/chunks.rs` + +**Interfaces:** +- Consumes: `rusqlite::Connection` on the main database (`atlas.db`). +- Produces (all `pub`, in `atlas::chunks`): + - `pub const CLAIM_TIMEOUT: i64 = 30 * 60;` + - `pub fn create(conn: &Connection) -> Result<()>` + - `pub fn unix_day(t: i64) -> i64` (days since epoch, UTC) + - `pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> Result` (inserts pending days from newest to oldest that don't exist yet; returns how many were added) + - `pub fn is_split(conn: &Connection, group: &str) -> Result` + - `pub fn claim(conn: &Connection, groups: &[String], host: &str, now: i64) -> Result>` (newest pending, or stale claimed, chunk among `groups`; marks it claimed by `host`) + - `pub fn finish(conn: &Connection, group: &str, day: i64) -> Result<()>` + - `pub fn release(conn: &Connection, group: &str, day: i64) -> Result<()>` + - `pub fn progress(conn: &Connection, group: &str) -> Result<(i64, i64)>` (done, total) + - `pub fn split_groups(conn: &Connection) -> Result>` (groups with any pending or claimed chunk) + +- [ ] **Step 1: Write the failing tests** + +Create `src/chunks.rs` with only the test module first: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + fn conn() -> Connection { + let c = Connection::open_in_memory().unwrap(); + create(&c).unwrap(); + c + } + + #[test] + fn days_are_claimed_newest_first_and_once() { + let c = conn(); + assert_eq!(add(&c, "g", 20_000, 19_998).unwrap(), 3); + assert_eq!(add(&c, "g", 20_000, 19_998).unwrap(), 0, "adding again adds nothing"); + assert!(is_split(&c, "g").unwrap()); + let groups = vec!["g".to_string()]; + + assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), Some(("g".into(), 20_000))); + assert_eq!(claim(&c, &groups, "b", 1000).unwrap(), Some(("g".into(), 19_999))); + finish(&c, "g", 20_000).unwrap(); + release(&c, "g", 19_999).unwrap(); + assert_eq!(claim(&c, &groups, "b", 1000).unwrap(), Some(("g".into(), 19_999)), "released goes back"); + assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), Some(("g".into(), 19_998))); + assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), None); + assert_eq!(progress(&c, "g").unwrap(), (1, 3)); + } + + #[test] + fn stale_claims_are_taken_over() { + let c = conn(); + add(&c, "g", 5, 5).unwrap(); + let groups = vec!["g".to_string()]; + assert!(claim(&c, &groups, "a", 1000).unwrap().is_some()); + assert_eq!(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT - 1).unwrap(), None); + assert_eq!(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT + 1).unwrap(), Some(("g".into(), 5))); + } + + #[test] + fn only_listed_groups_and_unsplit_groups() { + let c = conn(); + add(&c, "g", 5, 5).unwrap(); + assert_eq!(claim(&c, &["other".to_string()], "a", 0).unwrap(), None); + assert!(!is_split(&c, "other").unwrap()); + assert_eq!(split_groups(&c).unwrap(), vec!["g".to_string()]); + assert_eq!(unix_day(86_400 * 3 + 5), 3); + } +} +``` + +Add `pub mod chunks;` to `src/lib.rs` (alphabetical, after `pub mod app;`... keep the existing order style). + +- [ ] **Step 2: Run them to see them fail** + +Run: `cargo test --lib chunks` +Expected: compile errors for missing functions. + +- [ ] **Step 3: Implement** + +Above the test module in `src/chunks.rs`: + +```rust +//! Day chunks of a group's backfill that any server carrying the group can +//! take (see docs/superpowers/specs/2026-10-05-faster-backfill-smaller-storage-design.md). +//! Lives in the main database. + +use rusqlite::{Connection, OptionalExtension, Result, params}; + +/// a claim older than this is taken over (its worker died or was stopped) +pub const CLAIM_TIMEOUT: i64 = 30 * 60; + +const PENDING: i64 = 0; +const CLAIMED: i64 = 1; +const DONE: i64 = 2; + +pub fn create(conn: &Connection) -> Result<()> { + conn.execute_batch( + "create table if not exists backfill_chunks ( + grp TEXT NOT NULL, + day INTEGER NOT NULL, + state INTEGER NOT NULL, + server TEXT, + claimed_at INTEGER, + primary key (grp, day) + ) without rowid;", + ) +} + +/// days since 1970-01-01 UTC +pub fn unix_day(t: i64) -> i64 { + t.div_euclid(86_400) +} + +/// Pending chunks for `newest_day` down to `oldest_day`, keeping any that exist. +pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> Result { + let mut insert = + conn.prepare_cached("insert or ignore into backfill_chunks (grp, day, state) values (?, ?, ?)")?; + let mut added = 0; + for day in (oldest_day..=newest_day).rev() { + added += insert.execute(params![group, day, PENDING])?; + } + Ok(added) +} + +pub fn is_split(conn: &Connection, group: &str) -> Result { + conn.prepare_cached("select 1 from backfill_chunks where grp = ? limit 1")?.exists([group]) +} + +/// The newest chunk of `groups` that is pending or whose claim went stale, +/// claimed for `host`. +pub fn claim(conn: &Connection, groups: &[String], host: &str, now: i64) -> Result> { + if groups.is_empty() { + return Ok(None); + } + let marks = vec!["?"; groups.len()].join(","); + let sql = format!( + "select grp, day from backfill_chunks + where grp in ({marks}) and (state = {PENDING} or (state = {CLAIMED} and claimed_at < ?)) + order by day desc limit 1" + ); + let mut values: Vec = groups.iter().map(|g| g.clone().into()).collect(); + values.push((now - CLAIM_TIMEOUT).into()); + let found: Option<(String, i64)> = conn + .prepare(&sql)? + .query_row(rusqlite::params_from_iter(values), |r| Ok((r.get(0)?, r.get(1)?))) + .optional()?; + if let Some((group, day)) = &found { + conn.execute( + "update backfill_chunks set state = ?, server = ?, claimed_at = ? where grp = ? and day = ?", + params![CLAIMED, host, now, group, day], + )?; + } + Ok(found) +} + +pub fn finish(conn: &Connection, group: &str, day: i64) -> Result<()> { + conn.execute("update backfill_chunks set state = ? where grp = ? and day = ?", params![DONE, group, day])?; + Ok(()) +} + +pub fn release(conn: &Connection, group: &str, day: i64) -> Result<()> { + conn.execute( + "update backfill_chunks set state = ?, server = null, claimed_at = null where grp = ? and day = ?", + params![PENDING, group, day], + )?; + Ok(()) +} + +/// (done, total) chunks of a group +pub fn progress(conn: &Connection, group: &str) -> Result<(i64, i64)> { + conn.query_row( + "select coalesce(sum(state = 2), 0), count(*) from backfill_chunks where grp = ?", + [group], + |r| Ok((r.get(0)?, r.get(1)?)), + ) +} + +/// groups with chunks still to do +pub fn split_groups(conn: &Connection) -> Result> { + conn.prepare("select distinct grp from backfill_chunks where state != 2 order by grp")? + .query_map([], |r| r.get(0))? + .collect() +} +``` + +The callers (Task 4) serialize access through the indexer's single main connection, so claim's select-then-update is safe without a transaction. Add the doc line "the indexer's main connection is the only writer, soo select then update is safe" above `claim`. + +In `src/store.rs` `create_main`, append `crate::chunks::create(conn)?;` before `Ok(())` (convert `create_main` from an expression to a block if needed). + +- [ ] **Step 4: Run the tests** + +Run: `cargo test --lib chunks && just test` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add src/chunks.rs src/lib.rs src/store.rs +git commit -m "Day chunks of backfill in the main database + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +### Task 3: `run_chunk`: index one day of a group on one server + +**Files:** +- Modify: `src/indexer.rs` (new `pub async fn run_chunk` beside `run_pass`; `Pass::process_range` reused) +- Test: `tests/date_search.rs` (add a test; it already has a date mock) + +**Interfaces:** +- Consumes: `Pool::select_group_on`, `Pool::article_at` (Task 1), `chunks::{finish, release}` (Task 2), `Pass::process_range(&self, start, end, kind, progress) -> Result<(Progress, bool)>`, `on_db`, `cursor_key`. +- Produces: + - `pub const CHUNK_OVERLAP: i64 = 3600;` + - `pub async fn run_chunk

(ctx: &PassContext, settings: &PassSettings, db: &Db, group: &str, server: usize, day: i64, progress: &mut P) -> Result where P: FnMut(&Progress) + ?Sized`. On success it calls `chunks::finish`; when stopped part way, or on error, it calls `chunks::release` and returns the error (stopped: `Ok` with what was saved). + - Errors: if `select_group_on(server, group)` answers from a different server, return `Err(anyhow!("{group} isnt on {host}"))` after releasing the chunk. + +- [ ] **Step 1: Write the failing test** + +Append to `tests/date_search.rs`: + +```rust +/// One day of a group indexed on one server: exactly that day's posts, the +/// chunk marked done. +#[test] +fn a_day_chunk_indexes_that_day() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let port = spawn_server(Server::new(hourly())); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + let day = atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-02T00:00:00+00:00").unwrap().timestamp()); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let saved = pool + .block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})) + .unwrap(); + + // hours 24..47 are articles 25..48, plus an hour of overlap each side + // (24 and 49); 30 and 40 don't exist. 24..=49 minus 2 = 24 articles + assert_eq!(saved.articles, 24); + let conn = atlas::db::open_at(&main).unwrap(); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); +} +``` + +`PassContext` fields are public; check `RunStates` implements `Default` (`grep -n "struct RunStates" -B2 src/indexer.rs`). If `PassSettings` doesn't implement `Default` publicly, use `atlas::indexer::PassSettings::default()`; it exists. + +- [ ] **Step 2: Run it to see it fail** + +Run: `cargo test --test date_search a_day_chunk` +Expected: compile error, `run_chunk` not found. + +- [ ] **Step 3: Implement** + +In `src/indexer.rs`, after `run_pass`: + +```rust +/// a day chunk also takes this much on each side: post dates are only +/// roughly in article number order, duplicates are dropped when saved +pub const CHUNK_OVERLAP: i64 = 3600; + +/// Index one day (`day`, unix days) of `group` on `server`, for a group whose +/// backfill is split into day chunks (see chunks.rs). The chunk is marked done +/// when the whole day is in, released again if stopped part way or failing. +pub async fn run_chunk

( + ctx: &PassContext, + settings: &PassSettings, + db: &Db, + group: &str, + server: usize, + day: i64, + progress: &mut P, +) -> Result +where + P: FnMut(&Progress) + ?Sized, +{ + let release = |db: &Db, group: &str| { + let g = group.to_string(); + on_db(db, move |conn| Ok(crate::chunks::release(conn, &g, day)?)) + }; + + let found = match ctx.pool.select_group_on(server, group).await { + Ok((s, info)) if s == server => info, + Ok(_) | Err(_) => { + release(db, group).await?; + return Err(anyhow!("{group} isnt on {}", ctx.pool.host(server))); + } + }; + let (_count, first, last, _name) = found; + + let from = day * 86_400 - CHUNK_OVERLAP; + let to = (day + 1) * 86_400 + CHUNK_OVERLAP; + let start = match ctx.pool.article_at(server, group, first, last, from).await { + Ok(n) => n, + Err(e) => { + release(db, group).await?; + return Err(e.into()); + } + }; + let end = match ctx.pool.article_at(server, group, start.max(first), last, to).await { + Ok(n) => n.saturating_sub(1), + Err(e) => { + release(db, group).await?; + return Err(e.into()); + } + }; + if start > end { + let g = group.to_string(); + on_db(db, move |conn| Ok(crate::chunks::finish(conn, &g, day)?)).await?; + return Ok(Progress::default()); + } + + let pass = Pass { ctx, settings, db, group, server, key: cursor_key(&ctx.pool, server, group) }; + match pass.process_range(start as i64, end as i64, "CHUNK", progress).await { + Ok((saved, true)) => { + let g = group.to_string(); + on_db(db, move |conn| Ok(crate::chunks::finish(conn, &g, day)?)).await?; + Ok(saved) + } + Ok((saved, false)) => { + release(db, group).await?; + Ok(saved) + } + Err(e) => { + release(db, group).await?; + Err(e) + } + } +} +``` + +`NntpError` converts into `anyhow::Error` through `?`/`.into()` (it implements `std::error::Error`). `make_slices` reverses only for `"BACKFILL"`, so `"CHUNK"` slices run oldest first, which is fine. + +- [ ] **Step 4: Run the tests** + +Run: `cargo test --test date_search && just test` +Expected: PASS. + +- [ ] **Step 5: Commit** + +```bash +git add src/indexer.rs tests/date_search.rs +git commit -m "Index one day chunk of a group on one server + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +### Task 4: Split big groups and let idle workers take chunks + +**Files:** +- Modify: `src/indexer.rs` (`run_pass` splits a qualifying group; a split group's backfill pass runs a chunk instead of the cursor) +- Modify: `src/bg_indexer.rs` (`worker` claims chunks when it has nothing of its own; the scheduler remembers which servers don't carry a split group) +- Modify: `src/config.rs` (optional `split_min_backlog` in config.json, default 10,000,000, for tests and tuning) +- Test: `tests/split_backfill.rs` (new; the only test in its binary) + +**Interfaces:** +- Consumes: Task 1 `article_at`, Task 2 `chunks::*`, Task 3 `run_chunk`, `CHUNK_OVERLAP`. +- Produces: + - `PassSettings` gains `pub split_min_backlog: i64` (default `SPLIT_MIN_BACKLOG = 10_000_000`, from `config.split_min_backlog()`). + - `pub const SPLIT_MIN_BACKLOG: i64 = 10_000_000;` in `src/config.rs`, `Config::split_min_backlog(&self) -> i64`, read from optional JSON key `split_min_backlog`. + - In `src/indexer.rs`: `async fn maybe_split(ctx, db, group, home: usize, first: u64, cursor: u64) -> Result` (private). + - In `src/bg_indexer.rs`: `async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option<(String, i64)>`. + +- [ ] **Step 1: Write the failing end-to-end test** + +Create `tests/split_backfill.rs`: + +```rust +//! A big group's backfill split across two servers that number the same +//! posts differently: both servers index day chunks, every post is saved +//! exactly once, and every chunk ends done. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days, numbered from `offset` +fn posts(offset: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (0..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at(offset + i, &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), &when.to_rfc2822()); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn a_split_group_is_shared_by_both_servers() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + let a = Server::new(posts(1)); + let b = Server::new(posts(500_001)); + let (pa, pb) = (spawn_server(a.clone()), spawn_server(b.clone())); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pa, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": pb, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 500 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(120); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let split = atlas::chunks::is_split(&conn, GROUP).unwrap_or(false); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + if split && total > 0 && done == total && articles >= 1200 { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}, split {split}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once, overlaps deduplicated"); + assert!(a.xovers.load(Ordering::SeqCst) > 0 && b.xovers.load(Ordering::SeqCst) > 0, "both servers worked"); +} +``` + +`Post.message_id` is a `pub` field (Task 1 kept it). If `Server` has `any_group`, leave it false: both carry `GROUP`. + +- [ ] **Step 2: Run it to see it fail** + +Run: `cargo test --test split_backfill` +Expected: compile error for the `split_min_backlog` key not existing. Or, if config ignores unknown keys, a timeout panic with `split false`. + +- [ ] **Step 3: Config and settings** + +In `src/config.rs`: add `pub const SPLIT_MIN_BACKLOG: i64 = 10_000_000;` beside the other defaults, a field `pub split_min_backlog: Option` on `Config` (default `None`), parse it from the JSON key `split_min_backlog` the same way `batch_size` is parsed, write it back in `save_config` only if `Some`, and add: + +```rust +/// article numbers of backfill left before a group's backfill is split +/// over every server that carries it +pub fn split_min_backlog(&self) -> i64 { + self.split_min_backlog.unwrap_or(SPLIT_MIN_BACKLOG).max(1) +} +``` + +In `src/indexer.rs` `PassSettings`, add `pub split_min_backlog: i64,` and set it in `Default` to `crate::config::SPLIT_MIN_BACKLOG`. In `src/bg_indexer.rs` `settings_of`, set `split_min_backlog: config.split_min_backlog()`. Fix any other `PassSettings { .. }` literals (`grep -rn "PassSettings {" src tests`). + +- [ ] **Step 4: Split in `run_pass`** + +In `src/indexer.rs`, add: + +```rust +/// Split `group`'s backfill into day chunks when its home server still has +/// more than `split_min_backlog` article numbers to go and another indexing +/// server carries it too. Chunks run from the day at the home cursor back to +/// the oldest day any carrying server has. True when the group is split. +async fn maybe_split(ctx: &PassContext, settings: &PassSettings, db: &Db, group: &str, home: usize, first: u64, cursor: u64) -> Result { + let g = group.to_string(); + if on_db(db, move |conn| Ok(crate::chunks::is_split(conn, &g)?)).await? { + return Ok(true); + } + if (cursor.saturating_sub(first) as i64) < settings.split_min_backlog { + return Ok(false); + } + + // the newest day still to do: the post date at the home cursor + let newest = ctx.pool.article_at(home, group, cursor, cursor, i64::MIN).await.ok(); + let newest_day = match ctx.pool.posted_date(home, group, newest.unwrap_or(cursor)).await? { + Some(t) => crate::chunks::unix_day(t), + None => return Ok(false), + }; + + // the oldest day any other carrying server has + let mut oldest_day = newest_day; + let mut carriers = 1; + for other in ctx.pool.indexing_servers().into_iter().filter(|&s| s != home) { + let Ok((s, (_, low, _, _))) = ctx.pool.select_group_on(other, group).await else { continue }; + if s != other { + continue; + } + if let Some(t) = ctx.pool.posted_date(other, group, low).await? { + carriers += 1; + oldest_day = oldest_day.min(crate::chunks::unix_day(t)); + } + } + if let Some(t) = ctx.pool.posted_date(home, group, first).await? { + oldest_day = oldest_day.min(crate::chunks::unix_day(t)); + } + if carriers < 2 { + return Ok(false); + } + + let g = group.to_string(); + let added = on_db(db, move |conn| Ok(crate::chunks::add(conn, &g, newest_day, oldest_day)?)).await?; + println!("[SPLIT] {group}: backfill split into {added} day chunks over {carriers} servers"); + Ok(true) +} +``` + +Also add to `impl Pool` in `src/nntp.rs` (reuses Task 1's `posted_at`): + +```rust +/// When the first article at or after `number` on server `i` was posted (unix seconds). +pub async fn posted_date(&self, i: usize, group: &str, number: u64) -> Result> { + Ok(self.posted_at(i, group, number, 100).await?.map(|(_, t)| t)) +} +``` + +Drop the unused `newest` probe line in `maybe_split` if clippy flags it; `posted_date(home, group, cursor)` is enough. Keep the function minimal. + +In `run_pass`, right before `let pass = Pass { ... }`, decide the backfill route. Only when this pass would backfill (`settings.mode == "backfill"`, or dynamic in the backfill phase): + +```rust +let backfilling = settings.mode == "backfill" || (settings.mode != "live" && phase_is_backfill); +if backfilling && maybe_split(ctx, settings, db, group, server, first as u64, state.backfill_cursor.max(0) as u64).await? { + // a split group's backfill is day chunks, this server takes the next one + let host = ctx.pool.host(server); + let g = group.to_string(); + let claimed = on_db(db, move |conn| { + Ok(crate::chunks::claim(conn, std::slice::from_ref(&g), &host, chrono::Utc::now().timestamp())?) + }) + .await?; + return match claimed { + Some((_, day)) => run_chunk(ctx, settings, db, group, server, day, progress).await, + None => { + ctx.states.with(group, |st| st.backfilling = false); + Ok(Progress::default()) + } + }; +} +``` + +Read `phase` before this block, as the existing code already does (`let phase = ctx.states.with(group, |st| st.phase);`), and use `phase == Phase::Backfill` for `phase_is_backfill`. Live passes are untouched. + +- [ ] **Step 5: Idle workers take chunks** + +In `src/bg_indexer.rs`, add to `Scheduler` a field `skip: Mutex>` (group, server pairs that answered "not on this server"), initialized empty. Add: + +```rust +/// A day chunk of any split group for an idle worker on `server`: the newest +/// one pending, among the groups this server hasnt said it lacks. +async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option<(String, i64)> { + let host = sched.ctx.pool.host(server); + let skip: Vec = sched.skip.lock().unwrap().iter().filter(|(_, s)| *s == server).map(|(g, _)| g.clone()).collect(); + crate::indexer::claim_chunk(db, host, skip).await.ok().flatten() +} +``` + +and in `src/indexer.rs` a public helper that reaches the main connection through `on_db`: + +```rust +/// Claim the newest chunk of any split group for `host`, except `skip`. +pub async fn claim_chunk(db: &Db, host: String, skip: Vec) -> Result> { + on_db(db, move |conn| { + let groups: Vec = crate::chunks::split_groups(conn)?.into_iter().filter(|g| !skip.contains(g)).collect(); + Ok(crate::chunks::claim(conn, &groups, &host, chrono::Utc::now().timestamp())?) + }) + .await +} +``` + +In `worker`, when `take_group` returns `None`, try a chunk before napping: + +```rust +let Some(group) = sched.take_group(server) else { + if let Some((group, day)) = take_chunk(&sched, server, &db).await { + let settings = sched.settings.read().unwrap().clone(); + let stats = sched.stats.clone(); + let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); + let chunk = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &group, server, day, &mut progress); + match unless_stopped(&sched.ctx.stop, chunk).await { + None => break, + Some(Err(e)) if e.to_string().contains("isnt on") => { + sched.skip.lock().unwrap().insert((group, server)); + } + Some(Err(e)) => ui::error(&format!("Indexing error ({group}, day chunk): {e}")), + Some(Ok(_)) => {} + } + continue; + } + nap(Duration::from_secs(1), || sched.stopping()).await; + continue; +}; +``` + +Don't mark the group busy for chunks: chunks of one group run on several servers at once by design. + +- [ ] **Step 6: Run the tests** + +Run: `cargo test --test split_backfill && just test` +Expected: PASS. If the split test times out, print `bg_index.log` from the temp home in the assertion message to debug. Check that `[SPLIT]` appears and that both servers' `xovers` counters move. + +- [ ] **Step 7: Lint and commit** + +Run: `just format && just lint` + +```bash +git add src/indexer.rs src/bg_indexer.rs src/config.rs src/nntp.rs tests/split_backfill.rs +git commit -m "Split big groups' backfill into day chunks across servers + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +### Task 5: Backfill page counts chunk progress + +**Files:** +- Modify: `src/stats_dashboard.rs` (`load_quick` reads chunk progress; `draw_backfill` shows it) +- Test: unit test in `src/stats_dashboard.rs` + +**Interfaces:** +- Consumes: `chunks::{split_groups, progress}` (Task 2). +- Produces: `Quick` gains `chunks: Vec<(String, i64, i64)>` (group, done, total). The Backfill page adds a line "split groups: N, day chunks D of T done". + +- [ ] **Step 1: Write the failing test** + +In the `tests` module of `src/stats_dashboard.rs`, extend `pages_render` (or add a test) to build `Quick { chunks: vec![("alt.binaries.x".into(), 3, 10)], ..Quick::default() }` in the app's `quick`, render page 1 (Backfill) with `TestBackend`, and assert the text contains `day chunks 3 of 10 done`. + +- [ ] **Step 2: Run it to see it fail** + +Run: `cargo test --lib stats_dashboard` +Expected: compile error, no `chunks` field. + +- [ ] **Step 3: Implement** + +- Add `chunks: Vec<(String, i64, i64)>` to `Quick` (it derives `Default`). +- In `load_quick`, after `group_progress`: + +```rust +q.chunks = crate::chunks::split_groups(&conn) + .unwrap_or_default() + .into_iter() + .filter_map(|g| crate::chunks::progress(&conn, &g).ok().map(|(d, t)| (g, d, t))) + .collect(); +``` + +- In `draw_backfill`, after the "groups not started" line: + +```rust +if !quick.chunks.is_empty() { + let (done, total) = quick.chunks.iter().fold((0, 0), |(d, t), c| (d + c.1, t + c.2)); + progress.push(kv("split groups", format!("{}, day chunks {done} of {total} done", quick.chunks.len()))); +} +``` + +- [ ] **Step 4: Run the tests** + +Run: `cargo test --lib stats_dashboard && just lint` +Expected: PASS, no warnings. + +- [ ] **Step 5: Commit** + +```bash +git add src/stats_dashboard.rs +git commit -m "Backfill page shows day chunk progress of split groups + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +## Part B: pack message-id locals + +### Task 6: Pack locals by alphabet + +**Files:** +- Modify: `src/store.rs` (`pack_local`, `unpack_local`, `add_segment`) +- Test: unit tests in `src/store.rs` + +**Interfaces:** +- Consumes: nothing new. +- Produces: + - `pub(crate) fn pack_local(local: &str) -> Vec`: same signature, new tags. + - `pub(crate) fn unpack_local(blob: &[u8]) -> String`: now `pub(crate)`, decodes tags 0–7. + - `pub(crate) fn repack(local: &[u8]) -> Vec`, `= pack_local(&unpack_local(local))` (used by compact, Task 10). + - Tags (verbatim from the spec): 0 text, 1 hex lower, 2 hex upper (both without a length byte), 3 `0-9`, 4 `0-9a-z`, 5 `0-9A-Z`, 6 `0-9A-Za-z`, 7 `0-9A-Za-z-_`. Tags 3–7 are `[tag][len][base-N big-endian number bytes]`; `len` is the character count (1–255). + +- [ ] **Step 1: Write the failing tests** + +Add to `src/store.rs` tests: + +```rust +#[test] +fn locals_pack_by_shape_and_come_back_exactly() { + let cases = [ + ("1064b678f3f54e28a5afd48a3a986076", 1u8), // ngPost hex + ("ABCDEF0123", 2), + ("0001234", 3), // digits (odd length, so not hex), leading zeros kept + ("0abc9xyz", 4), + ("0ABC9XYZ", 5), + ("hotfTpetaZRIbOYuTuQ31", 6), // JBinUp + ("DR59tDkIGMDKQS1YflogRq2MTqVgoHslO", 6), + ("ZjPsQyLgOjNtQvXbHeKaXyCm1730295651235", 6), // Nyuu: letters + ms timestamp + ("a-b_c-9", 7), + ("abc", 4), // odd length hex-looking goes base36 + ("nnd$009a5634$43be2fd7", 0), // anything else stays text + ("", 0), + ]; + for (local, tag) in cases { + let packed = pack_local(local); + assert_eq!(packed[0], tag, "{local}"); + assert_eq!(unpack_local(&packed), local, "{local}"); + assert_eq!(pack_local(local), packed, "deterministic: {local}"); + } + let long = "a".repeat(300); + assert_eq!(pack_local(&long)[0], 0, "longer than 255 stays text"); + assert!(pack_local("ZjPsQyLgOjNtQvXbHeKaXyCm1730295651235").len() < 30, "base62 is smaller than text"); +} +``` + +and to the existing `only_shared_domains_get_rows_and_nothing_is_saved_twice` test (or a new one), a legacy duplicate check: insert a segment row by hand with `local = [0] ++ b"hotfTpetaZRIbOYuTuQ31"` and a shared domain id, then `add_segment` the same message-id `` after the domain is shared, and assert it returns `false`. + +- [ ] **Step 2: Run them to see them fail** + +Run: `cargo test --lib store` +Expected: FAIL on tag assertions. + +- [ ] **Step 3: Implement** + +Replace `pack_local` and `unpack_local`: + +```rust +const DIGITS: u8 = 3; +const BASE36_LOWER: u8 = 4; +const BASE36_UPPER: u8 = 5; +const BASE62: u8 = 6; +const BASE64_URL: u8 = 7; + +/// the alphabet of each packed tag, by digit value +fn alphabet(tag: u8) -> &'static [u8] { + match tag { + DIGITS => b"0123456789", + BASE36_LOWER => b"0123456789abcdefghijklmnopqrstuvwxyz", + BASE36_UPPER => b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", + BASE62 => b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", + BASE64_URL => b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_", + _ => b"", + } +} + +/// big-endian base-256 bytes of a base-`n` number given as digit values +fn to_bytes(digits: &[u8], n: u32) -> Vec { + let mut out: Vec = Vec::new(); // little endian while building + for &d in digits { + let mut carry = u32::from(d); + for b in out.iter_mut() { + let v = u32::from(*b) * n + carry; + *b = (v & 0xff) as u8; + carry = v >> 8; + } + while carry > 0 { + out.push((carry & 0xff) as u8); + carry >>= 8; + } + } + out.reverse(); + out +} + +/// `len` base-`n` digit values of a big-endian base-256 number +fn from_bytes(bytes: &[u8], n: u32, len: usize) -> Vec { + let mut num: Vec = bytes.to_vec(); + let mut digits = Vec::with_capacity(len); + for _ in 0..len { + let mut rem = 0u32; + for b in num.iter_mut() { + let v = (rem << 8) | u32::from(*b); + *b = (v / n) as u8; + rem = v % n; + } + digits.push(rem as u8); + } + digits.reverse(); + digits +} + +pub(crate) fn pack_local(local: &str) -> Vec { + let bytes = local.as_bytes(); + let even = !bytes.is_empty() && bytes.len().is_multiple_of(2); + let lower = even && bytes.iter().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(b)); + let upper = even && !lower && bytes.iter().all(|b| b.is_ascii_digit() || (b'A'..=b'F').contains(b)); + if lower || upper { + let nibble = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8; + let mut out = Vec::with_capacity(1 + bytes.len() / 2); + out.push(if lower { HEX_LOWER } else { HEX_UPPER }); + out.extend(bytes.chunks(2).map(|p| (nibble(p[0]) << 4) | nibble(p[1]))); + return out; + } + if (1..=255).contains(&bytes.len()) { + for tag in [DIGITS, BASE36_LOWER, BASE36_UPPER, BASE62, BASE64_URL] { + let abc = alphabet(tag); + let values: Option> = bytes.iter().map(|b| abc.iter().position(|a| a == b).map(|p| p as u8)).collect(); + if let Some(values) = values { + let mut out = vec![tag, bytes.len() as u8]; + out.extend(to_bytes(&values, abc.len() as u32)); + return out; + } + } + } + let mut out = Vec::with_capacity(1 + bytes.len()); + out.push(TEXT); + out.extend_from_slice(bytes); + out +} + +pub(crate) fn unpack_local(blob: &[u8]) -> String { + match blob.first() { + Some(&HEX_LOWER) => blob[1..].iter().map(|b| format!("{b:02x}")).collect(), + Some(&HEX_UPPER) => blob[1..].iter().map(|b| format!("{b:02X}")).collect(), + Some(&tag) if (DIGITS..=BASE64_URL).contains(&tag) && blob.len() >= 2 => { + let abc = alphabet(tag); + from_bytes(&blob[2..], abc.len() as u32, blob[1] as usize).iter().map(|&d| abc[d as usize] as char).collect() + } + _ => String::from_utf8_lossy(blob.get(1..).unwrap_or_default()).into_owned(), + } +} + +/// a local packed the current way, whatever way it was packed before +pub(crate) fn repack(local: &[u8]) -> Vec { + pack_local(&unpack_local(local)) +} +``` + +Precedence is hex first (even length, so `"00012345"` would be tag 1), then tags 3, 4, 5, 6, 7 in that order. The test table follows it. + +In `add_segment`, after the existing whole-id check, also check the legacy text form when the new local is packed with tags 3–7: + +```rust +// a row from before this packing has the same local stored as text +if (3..=7).contains(&local[0]) { + let mut legacy = vec![0u8]; + legacy.extend_from_slice(unpack_local(&local).as_bytes()); + let stored_legacy = conn + .prepare_cached("select 1 from segments where file_id = ? and local = ? and domain = ?")? + .exists(params![file_id, legacy, domain])?; + if stored_legacy { + return Ok(false); + } +} +``` + +- [ ] **Step 4: Run the tests** + +Run: `cargo test --lib store && just test` +Expected: PASS. NZB equality tests elsewhere (`tests/convert.rs`, `compact` tests) must still pass, because reads decode both forms. + +- [ ] **Step 5: Lint and commit** + +Run: `just format && just lint` + +```bash +git add src/store.rs +git commit -m "Pack message-id locals by alphabet + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +## Part C: seal finished files into blobs + +### Task 7: Blob codec + +**Files:** +- Create: `src/blob.rs` +- Modify: `src/lib.rs` (`pub mod blob;`), `Cargo.toml` (`zstd = "0.13"`), `Cargo.lock` +- Test: unit tests in `src/blob.rs` + +**Interfaces:** +- Produces (in `atlas::blob`): + - `#[derive(Clone, Debug, PartialEq, Eq)] pub struct Seg { pub part: Option, pub bytes: i64, pub domain: i64, pub local: Vec }` + - `pub fn encode(segs: &[Seg]) -> Vec` (sorts a copy by `(part.is_some(), part, local)` for compression; zstd level 6) + - `pub fn decode(blob: &[u8]) -> std::io::Result>` + +- [ ] **Step 1: Add the dependency** + +Add `zstd = "0.13"` under `[dependencies]` in `Cargo.toml` (alphabetical). Run `cargo build` so `Cargo.lock` updates. + +- [ ] **Step 2: Write the failing tests** + +Create `src/blob.rs` with tests: + +```rust +#[cfg(test)] +mod tests { + use super::*; + + fn seg(part: Option, bytes: i64, domain: i64, local: &[u8]) -> Seg { + Seg { part, bytes, domain, local: local.to_vec() } + } + + #[test] + fn segments_come_back_exactly() { + let segs = vec![ + seg(Some(2), 750_000, 3, b"\x06\x05abc"), + seg(Some(1), 750_123, 3, b"\x01\xde\xad"), + seg(None, 0, 0, b"\x00"), + seg(Some(3), 12, 9, b""), + ]; + let mut back = decode(&encode(&segs)).unwrap(); + let mut want = segs.clone(); + back.sort_by(|a, b| (a.part, &a.local).cmp(&(b.part, &b.local))); + want.sort_by(|a, b| (a.part, &a.local).cmp(&(b.part, &b.local))); + assert_eq!(back, want); + assert!(decode(&encode(&[])).unwrap().is_empty()); + } + + #[test] + fn a_big_file_is_small() { + let segs: Vec = (1..=1000) + .map(|p| seg(Some(p), 768_000, 1, &[1, (p % 251) as u8, (p * 7 % 251) as u8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9])) + .collect(); + let size = encode(&segs).len(); + assert!(size < 1000 * 20, "{size} bytes for 1000 segments"); + } + + #[test] + fn garbage_is_an_error() { + assert!(decode(b"not zstd").is_err()); + } +} +``` + +- [ ] **Step 3: Run them to see them fail** + +Run: `cargo test --lib blob` +Expected: compile errors. + +- [ ] **Step 4: Implement** + +Above the tests in `src/blob.rs`: + +```rust +//! A sealed file's articles in one compressed value (files.blob), see the +//! storage spec. Format v1, zstd compressed: +//! u8 version, varint count, then per segment: varint part+1 (0 = none), +//! zigzag varint bytes minus the previous segment's, varint domain, varint +//! local length, local bytes. + +use std::io::{Error, ErrorKind, Result}; + +const VERSION: u8 = 1; +const LEVEL: i32 = 6; + +/// One article of a sealed file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Seg { + pub part: Option, + pub bytes: i64, + pub domain: i64, + pub local: Vec, +} + +fn put_varint(out: &mut Vec, mut v: u64) { + while v >= 0x80 { + out.push((v as u8) | 0x80); + v >>= 7; + } + out.push(v as u8); +} + +fn get_varint(buf: &[u8], pos: &mut usize) -> Result { + let mut v = 0u64; + for shift in (0..64).step_by(7) { + let b = *buf.get(*pos).ok_or_else(|| Error::new(ErrorKind::UnexpectedEof, "blob cut short"))?; + *pos += 1; + v |= u64::from(b & 0x7f) << shift; + if b & 0x80 == 0 { + return Ok(v); + } + } + Err(Error::new(ErrorKind::InvalidData, "varint too long")) +} + +fn zigzag(v: i64) -> u64 { + ((v << 1) ^ (v >> 63)) as u64 +} + +fn unzigzag(v: u64) -> i64 { + ((v >> 1) as i64) ^ -((v & 1) as i64) +} + +pub fn encode(segs: &[Seg]) -> Vec { + let mut sorted: Vec<&Seg> = segs.iter().collect(); + sorted.sort_by(|a, b| (a.part.is_some(), a.part, &a.local).cmp(&(b.part.is_some(), b.part, &b.local))); + let mut raw = vec![VERSION]; + put_varint(&mut raw, sorted.len() as u64); + let mut prev_bytes = 0i64; + for s in sorted { + put_varint(&mut raw, s.part.map_or(0, |p| p as u64 + 1)); + put_varint(&mut raw, zigzag(s.bytes - prev_bytes)); + prev_bytes = s.bytes; + put_varint(&mut raw, s.domain as u64); + put_varint(&mut raw, s.local.len() as u64); + raw.extend_from_slice(&s.local); + } + zstd::bulk::compress(&raw, LEVEL).expect("zstd compress of an in memory buffer") +} + +pub fn decode(blob: &[u8]) -> Result> { + let raw = zstd::stream::decode_all(blob)?; + if raw.first() != Some(&VERSION) { + return Err(Error::new(ErrorKind::InvalidData, "unknown blob version")); + } + let mut pos = 1; + let count = get_varint(&raw, &mut pos)? as usize; + let mut segs = Vec::with_capacity(count.min(1 << 20)); + let mut prev_bytes = 0i64; + for _ in 0..count { + let part = match get_varint(&raw, &mut pos)? { + 0 => None, + p => Some(p as i64 - 1), + }; + let bytes = prev_bytes + unzigzag(get_varint(&raw, &mut pos)?); + prev_bytes = bytes; + let domain = get_varint(&raw, &mut pos)? as i64; + let len = get_varint(&raw, &mut pos)? as usize; + let local = raw.get(pos..pos + len).ok_or_else(|| Error::new(ErrorKind::UnexpectedEof, "blob cut short"))?.to_vec(); + pos += len; + segs.push(Seg { part, bytes, domain, local }); + } + Ok(segs) +} +``` + +Add `pub mod blob;` to `src/lib.rs`. + +- [ ] **Step 5: Run the tests** + +Run: `cargo test --lib blob && just lint` +Expected: PASS. + +- [ ] **Step 6: Commit** + +```bash +git add Cargo.toml Cargo.lock src/blob.rs src/lib.rs +git commit -m "Compressed per-file segment blob codec + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +### Task 8: Sealing in the store: schema, seal, read, late articles + +**Files:** +- Modify: `src/store.rs` +- Test: unit tests in `src/store.rs` + +**Interfaces:** +- Consumes: `blob::{Seg, encode, decode}` (Task 7), `pack_local`/`unpack_local` (Task 6). +- Produces: + - Schema: `files.blob BLOB`, `files.touched_at INTEGER`, added in `create_shard` for new shards. `pub fn migrate_shard(conn: &Connection) -> Result<()>` adds them to existing shards with `alter table` when missing; `create_shard` calls it. + - `FileState` gains `pub sealed: bool` (`blob is not null`), set in `file()`. + - `put_file` also sets `touched_at = unixepoch()`. + - `pub const SEAL_AGE: i64 = 3 * 86_400;` + - `pub(crate) fn seal_file(conn: &Connection, file_id: i64) -> Result` (number of segments in the new blob; 0 if the file had no rows) + - `pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) -> Result<(Vec, i64)>` (eligible file ids after `after_id`, plus the last id looked at, for walking the table) + - `pub(crate) struct SealedCache` with `fn new() -> Self` and `fn contains(&mut self, conn, file_id, local: &[u8], domain: i64) -> Result` (decodes a file's blob once per cache lifetime) + - `add_segment` signature becomes `add_segment(conn, domains, f: &FileState, a: &Article, sealed: &mut SealedCache) -> Result`, and it skips articles already in the blob. + - `articles()` merges blob segments with loose rows. + - `pub fn article_count(conn: &Connection, schema: &str) -> Result` (loose rows plus blob segments), used by compact's check (Task 10). + +- [ ] **Step 1: Write the failing tests** + +Add to `src/store.rs` tests: + +```rust +/// a shard with one release: file a.rar (3 parts) and b.rar (2 parts) +fn sealed_fixture() -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let art = |file: &str, part: i64, total: i64, id: &str| Article { + message_id: id.into(), + subject: format!("\"{file}\" yEnc ({part}/{total})"), + filename: Some(file.into()), + part: Some(part), + total_parts: Some(total), + bytes: 100 + part, + ..Default::default() + }; + let release = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![ + art("a.rar", 1, 3, ""), + art("a.rar", 2, 3, "<0abc12def34@ngPost>"), + art("a.rar", 3, 3, ""), + art("b.rar", 1, 2, ""), + ], + ..Default::default() + }; + save(&main, &[release]).unwrap(); + (dir, main) +} + +#[test] +fn sealing_keeps_every_nzb_and_late_articles_merge() { + let (_dir, main) = sealed_fixture(); + let shard = shard_path(&main, shard_of("alt.binaries.t")); + let read = || { + let conn = db::open_with_shards(&main).unwrap(); + let id: i64 = conn.query_row("select id from releases", [], |r| r.get(0)).unwrap(); + articles(&conn, id).unwrap() + }; + let before = read(); + + let conn = db::open_at(&shard).unwrap(); + let ids: Vec = conn.prepare("select id from files").unwrap().query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect(); + for id in &ids { + seal_file(&conn, *id).unwrap(); + } + let loose: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(loose, 0, "sealed files have no rows left"); + assert_eq!(read(), before, "same articles back from the blobs"); + assert_eq!(article_count(&db::open_with_shards(&main).unwrap(), &format!("s{}", shard_of("alt.binaries.t"))).unwrap(), 4); + + // a late article for a sealed file is saved once, one already sealed isnt + let late = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![ + Article { message_id: "".into(), filename: Some("b.rar".into()), part: Some(2), total_parts: Some(2), bytes: 102, ..Default::default() }, + Article { message_id: "".into(), filename: Some("a.rar".into()), part: Some(1), total_parts: Some(3), bytes: 101, ..Default::default() }, + ], + ..Default::default() + }; + save(&main, &[late]).unwrap(); + let after = read(); + assert_eq!(after.len(), 5); + assert_eq!(after.iter().filter(|a| a.message_id == "").count(), 1); + + // resealing folds the late row in + let b: i64 = conn.query_row("select id from files where filename = 'b.rar'", [], |r| r.get(0)).unwrap(); + assert_eq!(seal_file(&conn, b).unwrap(), 2); + assert_eq!(read(), after); +} + +#[test] +fn complete_or_stale_files_are_sealable() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let now = 2_000_000_000; + // a.rar is complete (1..=3), b.rar has 1 of 2 and was just touched + let (ids, _) = sealable(&conn, 0, 100, now).unwrap(); + let name = |id: i64| -> String { conn.query_row("select filename from files where id = ?", [id], |r| r.get(0)).unwrap() }; + assert_eq!(ids.iter().map(|&i| name(i)).collect::>(), vec!["a.rar".to_string()]); + conn.execute("update files set touched_at = ? where filename = 'b.rar'", [now - SEAL_AGE - 1]).unwrap(); + assert_eq!(sealable(&conn, 0, 100, now).unwrap().0.len(), 2, "b.rar went stale"); +} +``` + +`put_file` stamps `touched_at` with the real clock. `sealable` takes `now` as a parameter, so the test sets `touched_at` relative to it. + +- [ ] **Step 2: Run them to see them fail** + +Run: `cargo test --lib store` +Expected: compile errors. + +- [ ] **Step 3: Schema and FileState** + +- In `create_shard`'s `create table if not exists files (...)`, add `blob BLOB, touched_at INTEGER` columns. After the `execute_batch`, call `migrate_shard(&conn)?`. +- `migrate_shard`: read `pragma table_info(files)` (see `db::columns`; add a small local helper) and `alter table files add column blob BLOB` / `alter table files add column touched_at INTEGER` for any that are missing. +- `FileState`: add `pub sealed: bool`. In `file()`, select `blob is not null` as a 7th column and set `sealed`. New files get `sealed: false`. +- `put_file`: add `touched_at = unixepoch()` to the update. + +- [ ] **Step 4: Seal, sealable, read, cache** + +```rust +/// files untouched this long get sealed even when incomplete +pub const SEAL_AGE: i64 = 3 * 86_400; + +/// Seal a file: its rows (and any blob it already has) become one blob, the +/// rows go. Returns the segments in the blob. +pub(crate) fn seal_file(conn: &Connection, file_id: i64) -> Result { + let mut segs: Vec = match conn + .query_row("select blob from files where id = ? and blob is not null", [file_id], |r| r.get::<_, Vec>(0)) + .optional()? + { + Some(b) => crate::blob::decode(&b).map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?, + None => Vec::new(), + }; + let rows: Vec = conn + .prepare_cached("select part, bytes, domain, local from segments where file_id = ?")? + .query_map([file_id], |r| { + Ok(crate::blob::Seg { part: r.get(0)?, bytes: r.get::<_, Option>(1)?.unwrap_or(0), domain: r.get(2)?, local: r.get(3)? }) + })? + .collect::>()?; + if rows.is_empty() && !segs.is_empty() { + return Ok(segs.len()); + } + segs.extend(rows); + if segs.is_empty() { + return Ok(0); + } + conn.prepare_cached("update files set blob = ? where id = ?")?.execute(params![crate::blob::encode(&segs), file_id])?; + conn.prepare_cached("delete from segments where file_id = ?")?.execute([file_id])?; + Ok(segs.len()) +} + +/// Files after `after_id` with rows to seal: complete, or untouched for +/// `SEAL_AGE` (never touched since the upgrade counts as old). Returns the +/// ids and the last id looked at. +pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) -> Result<(Vec, i64)> { + let mut stmt = conn.prepare_cached( + "select f.id, f.expected, f.seen, f.touched_at from files f + where f.id > ? and exists (select 1 from segments s where s.file_id = f.id) + order by f.id limit ?", + )?; + let mut ids = Vec::new(); + let mut last = after_id; + let mut rows = stmt.query(params![after_id, limit as i64])?; + while let Some(r) = rows.next()? { + let (id, expected, seen, touched): (i64, Option, Vec, Option) = (r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?); + last = id; + let complete = expected.is_some_and(|e| is_exactly(&seen, e)); + if complete || touched.is_none_or(|t| t < now - SEAL_AGE) { + ids.push(id); + } + } + Ok((ids, last)) +} + +/// Blobs of sealed files, decoded once each, for checking late articles. +#[derive(Default)] +pub(crate) struct SealedCache { + files: HashMap, i64)>>, +} + +impl SealedCache { + pub(crate) fn new() -> Self { + Self::default() + } + + /// the article (local, domain) is already in file `file_id`'s blob + pub(crate) fn contains(&mut self, conn: &Connection, file_id: i64, local: &[u8], domain: i64) -> Result { + if !self.files.contains_key(&file_id) { + let set = match conn + .query_row("select blob from files where id = ? and blob is not null", [file_id], |r| r.get::<_, Vec>(0)) + .optional()? + { + Some(b) => crate::blob::decode(&b) + .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))? + .into_iter() + .map(|s| (s.local, s.domain)) + .collect(), + None => Default::default(), + }; + self.files.insert(file_id, set); + } + Ok(self.files[&file_id].contains(&(local.to_vec(), domain))) + } +} +``` + +Change `add_segment` to take `f: &FileState` and `sealed: &mut SealedCache` (`file_id` becomes `f.id`). Before inserting, add: + +```rust +if f.sealed && sealed.contains(conn, f.id, &local, domain)? { + return Ok(false); +} +``` + +Also check the whole-id form against the blob when `domain != 0` (`sealed.contains(conn, f.id, &whole(&a.message_id), 0)`) for sealed files. Update the caller in `ShardWriter::save`: create `let mut sealed = SealedCache::new();` at the start of `save` and pass `&f` / `&mut sealed`. Update tests that call `add_segment` directly (the domain test) to build a `FileState` via `file()` and pass `&mut SealedCache::new()`. + +In `articles()`, after collecting the loose rows, add blob rows: + +```rust +let mut sealed = conn.prepare(&format!( + "select f.blob, f.filename, f.expected, f.subject, r.poster, r.posted_date + from s{s}.files f join s{s}.releases r on r.id = f.release_id + where f.release_id = ? and f.blob is not null" +))?; +let mut suffixes: HashMap> = HashMap::new(); +let mut blob_rows = sealed.query([release_id])?; +while let Some(r) = blob_rows.next()? { + let blob: Vec = r.get(0)?; + let filename: String = r.get(1)?; + for seg in crate::blob::decode(&blob).map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))? { + if !suffixes.contains_key(&seg.domain) { + let suffix: Option = conn + .query_row(&format!("select suffix from s{s}.domains where id = ?"), [seg.domain], |r| r.get(0)) + .optional()?; + suffixes.insert(seg.domain, suffix); + } + rows.push(ArticleRow { + message_id: decode(&seg.local, suffixes[&seg.domain].as_deref()), + filename: (!filename.is_empty()).then(|| filename.clone()), + part: seg.part, + total_parts: r.get(2)?, + bytes: Some(seg.bytes), + subject: r.get(3)?, + poster: r.get(4)?, + posted_date: r.get(5)?, + }); + } +} +``` + +The existing final sort covers the merged rows. `rows` must be `let mut rows: Vec` before this block. + +`article_count`: + +```rust +/// articles in shard `schema` (`s3`, or `main` for a shard opened on its +/// own): loose rows plus every sealed blob's segments +pub fn article_count(conn: &Connection, schema: &str) -> Result { + let loose: i64 = conn.query_row(&format!("select count(*) from {schema}.segments"), [], |r| r.get(0))?; + let mut sealed = 0i64; + let mut stmt = conn.prepare(&format!("select blob from {schema}.files where blob is not null"))?; + let mut rows = stmt.query([])?; + while let Some(r) = rows.next()? { + let b: Vec = r.get(0)?; + sealed += crate::blob::decode(&b).map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?.len() as i64; + } + Ok(loose + sealed) +} +``` + +- [ ] **Step 5: Run the tests** + +Run: `cargo test --lib store && just test` +Expected: PASS, including `tests/convert.rs` and the compact test. + +- [ ] **Step 6: Lint and commit** + +Run: `just format && just lint` (use a type alias if clippy flags `type_complexity` on the tuple in `sealable`). + +```bash +git add src/store.rs +git commit -m "Seal a file's articles into one blob; reads and late articles see it + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +### Task 9: Shard writers seal as they go + +**Files:** +- Modify: `src/store.rs` (`ShardWriter` keeps a seal cursor; `seal_some`) +- Modify: `src/indexer.rs` (the writer thread calls it between transactions) +- Modify: `src/profile.rs` (`writer_seal_ns` load counter) +- Test: unit test in `src/store.rs` + +**Interfaces:** +- Consumes: `sealable`, `seal_file` (Task 8). +- Produces: + - `pub const SEAL_PER_TICK: usize = 2_000;` + - `ShardWriter::seal_some(&mut self, conn: &mut Connection, now: i64) -> Result` (seals up to `SEAL_PER_TICK` files in one transaction; walks `files` by id from where it stopped, wrapping to 0 at the end; returns the files sealed). + - `LOAD.writer_seal_ns` in `src/profile.rs`, reported in the load snapshot as `writer_seal_ns`. + +- [ ] **Step 1: Write the failing test** + +```rust +#[test] +fn a_writer_seals_what_is_due_a_tick_at_a_time() { + let (_dir, main) = sealed_fixture(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + let mut writer = ShardWriter::new(shard); + let now = 2_000_000_000; + conn.execute("update files set touched_at = ?", [now]).unwrap(); + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1, "only the complete file"); + conn.execute("update files set touched_at = ?", [now - SEAL_AGE - 1]).unwrap(); + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1, "the stale one, after wrapping around"); + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 0); +} +``` + +- [ ] **Step 2: Run it to see it fail** + +Run: `cargo test --lib a_writer_seals` +Expected: compile error. + +- [ ] **Step 3: Implement** + +Add `seal_after: i64` (starts at 0) to `ShardWriter`, plus: + +```rust +/// files sealed per writer tick at most +pub const SEAL_PER_TICK: usize = 2_000; + +impl ShardWriter { + /// Seal up to SEAL_PER_TICK files that are due, walking the files table by + /// id from where the last tick stopped (back to the start at the end). + pub fn seal_some(&mut self, conn: &mut Connection, now: i64) -> Result { + let tx = conn.transaction()?; + let (mut ids, last) = sealable(&tx, self.seal_after, SEAL_PER_TICK * 4, now)?; + ids.truncate(SEAL_PER_TICK); + if ids.len() == SEAL_PER_TICK { + self.seal_after = *ids.last().unwrap(); + } else if last == self.seal_after { + self.seal_after = 0; + } else { + self.seal_after = last; + } + for id in &ids { + seal_file(&tx, *id)?; + } + tx.commit()?; + Ok(ids.len()) + } +} +``` + +The test expects the second call to find the stale file even though the cursor moved past it, so the wrap must happen within the same call when nothing was found. Adjust the logic: if `ids.is_empty()` and `self.seal_after != 0`, reset `seal_after = 0` and search once more before returning. Keep the test as the source of truth. + +In `src/profile.rs`, add `pub writer_seal_ns: AtomicU64` to `Load` (initialize it in `LOAD`, add `"writer_seal_ns"` to `snapshot`). + +In `src/indexer.rs` `writer()`, after `store.save(...)` and before `finish_checkpoint`: + +```rust +let t = std::time::Instant::now(); +let _ = store.seal_some(conn, chrono::Utc::now().timestamp()); +Load::add_since(&LOAD.writer_seal_ns, t); +``` + +- [ ] **Step 4: Run the tests** + +Run: `cargo test --lib store && just test` +Expected: PASS. + +- [ ] **Step 5: Lint and commit** + +Run: `just format && just lint` + +```bash +git add src/store.rs src/indexer.rs src/profile.rs +git commit -m "Shard writers seal due files between transactions + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +### Task 10: `--compact` re-encodes locals and seals + +**Files:** +- Modify: `src/compact.rs` +- Test: the existing test module in `src/compact.rs` + +**Interfaces:** +- Consumes: `store::repack` (Task 6), `store::{sealable, seal_file, article_count}` (Task 8), `blob` (Task 7). +- Produces: `compact_shard` writes locals repacked with the current packing, then seals every eligible file in the copy. `check()` compares `article_count` instead of raw `segments` row counts, and samples NZBs as before. + +- [ ] **Step 1: Write the failing test** + +Extend `compacting_drops_single_use_domains_and_keeps_every_nzb` (or add a test) so the fixture's shared-domain rows are stored with legacy text locals. Then, after `run`, assert: + +```rust +for path in store::shard_paths(&main) { + let conn = db::open_at(&path).unwrap(); + let loose: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(loose, 0, "every file was due (never touched since the upgrade), so all are sealed"); +} +assert_eq!(all_articles(&main), before, "every NZB reads back the same"); +``` + +Also assert that `article_count` over all shards equals the article count before compaction. + +- [ ] **Step 2: Run it to see it fail** + +Run: `cargo test --lib compact` +Expected: FAIL, `loose` is not 0. + +- [ ] **Step 3: Implement** + +In the article copy loop, for kept rows (`domain == 0 || shared(domain)`), use `store::repack(&local)` for packed shared-domain locals (`domain != 0`). Whole ids (domain 0) stay as they are. Before the `insert or ignore`, normalize: for `domain != 0`, `let local = store::repack(&local);`. + +After copying segments and before `building indexes`, seal everything due in the copy: + +```rust +say("sealing files"); +let now = chrono::Utc::now().timestamp(); +let mut after = 0; +loop { + let tx = conn.transaction()?; + let (ids, last) = store::sealable(&tx, after, 50_000, now)?; + for id in &ids { + store::seal_file(&tx, *id)?; + } + tx.commit()?; + if last == after { + break; + } + after = last; +} +``` + +`sealable` and `seal_file` must be reachable: make them `pub` (not `pub(crate)`) if `compact.rs` can't see them; it's in the same crate, so `pub(crate)` works. + +In `check()`, replace the `segments` count comparison with `store::article_count(&old, &format!("s{shard}"))? == store::article_count(&new, &format!("s{shard}"))?`, and replace `copied != count(&new, "segments")` with a comparison of `copied` against the new `article_count` (allowing for nothing lost: the counts must be equal). Keep the `releases` and `files` row checks. + +- [ ] **Step 4: Run the tests** + +Run: `cargo test --lib compact && just test` +Expected: PASS. + +- [ ] **Step 5: Lint and commit** + +Run: `just format && just lint` + +```bash +git add src/compact.rs src/store.rs +git commit -m "Compact re-encodes locals and seals due files + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +## Part D: auto compaction + +### Task 11: `auto_run_compact` + +**Files:** +- Modify: `src/config.rs` (`auto_run_compact` key) +- Modify: `src/bg_indexer.rs` (timer task, run compaction between `run_servers` rounds) +- Modify: `src/store.rs` (`get_meta`/`set_meta` on the main database) +- Test: `tests/auto_compact.rs` (new; only test in its binary) + +**Interfaces:** +- Produces: + - `Config.auto_run_compact: bool` (JSON `auto_run_compact`, default `false`, written back only when true). + - `pub fn get_meta(conn: &Connection, key: &str) -> Result>`, `pub fn set_meta(conn: &Connection, key: &str, value: i64) -> Result<()>` in `store`. + - `pub const COMPACT_EVERY: Duration = Duration::from_secs(24 * 3600);` in `bg_indexer`, overridable in tests through env `ATLAS_COMPACT_EVERY_SECS`. + +- [ ] **Step 1: Write the failing test** + +Create `tests/auto_compact.rs`: + +```rust +//! With auto_run_compact on, the indexer stops for a compaction once the +//! interval has passed, records it, and goes back to indexing. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post, spawn_server}; + +#[test] +fn compacts_on_schedule_and_keeps_indexing() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + std::env::set_var("ATLAS_COMPACT_EVERY_SECS", "2"); + } + let posts: Vec = (1..=200).map(|n| post(n, &format!(r#""r{}.part{}.rar" yEnc (1/1)"#, n / 20, n % 20 + 1), 10, vec![])).collect(); + let port = spawn_server(Server::new(posts)); + let config = serde_json::json!({ + "usenet_servers": [{"host": "127.0.0.1", "username": "bob", "password": "secret", "port": port, "ssl": false, "connections": 2, "priority": 1}], + "groups": [GROUP], "index_mode": "backfill", "request_size": 50, "auto_run_compact": true + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + assert!(cfg.auto_run_compact); + let runner = { let stop = stop.clone(); std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(60); + let compacted = loop { + let conn = atlas::db::open_at(&main).unwrap(); + if let Some(t) = atlas::store::get_meta(&conn, "last_compact").unwrap() { + break t; + } + assert!(Instant::now() < deadline, "never compacted"); + std::thread::sleep(Duration::from_millis(200)); + }; + assert!(compacted > 0); + + // indexing goes on after it: everything gets indexed + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + if atlas::store::totals(&conn).unwrap().1 >= 200 { break; } + assert!(Instant::now() < deadline, "indexing didnt resume"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); +} +``` + +- [ ] **Step 2: Run it to see it fail** + +Run: `cargo test --test auto_compact` +Expected: compile error, no `auto_run_compact` field. + +- [ ] **Step 3: Config and meta** + +- `src/config.rs`: `pub auto_run_compact: bool` on `Config` (default `false`), parsed from `auto_run_compact` (bool), written back by `save_config` only when `true`. +- `src/store.rs`: + +```rust +pub fn get_meta(conn: &Connection, key: &str) -> Result> { + conn.query_row("select value from main.meta where key = ?", [key], |r| r.get(0)).optional() +} + +pub fn set_meta(conn: &Connection, key: &str, value: i64) -> Result<()> { + conn.execute("insert or replace into main.meta (key, value) values (?, ?)", params![key, value])?; + Ok(()) +} +``` + +- [ ] **Step 4: Schedule in the indexer** + +In `src/bg_indexer.rs`: + +```rust +/// how often auto_run_compact compacts (ATLAS_COMPACT_EVERY_SECS for tests) +fn compact_every() -> Duration { + std::env::var("ATLAS_COMPACT_EVERY_SECS") + .ok() + .and_then(|v| v.parse().ok()) + .map(Duration::from_secs) + .unwrap_or(Duration::from_secs(24 * 3600)) +} +``` + +- Add `compact_due: AtomicBool` to `Scheduler`. +- In `run_servers`, if `config.auto_run_compact`, spawn a task that naps in 1 s steps until `due` (computed from `get_meta(main, "last_compact")` plus `compact_every()`, or from the indexer start when there's none). When due, it sets `compact_due` and `wind_down` and returns. +- `run_servers` returns `bool` (compaction due). +- In `supervise`, after `run_servers(...)` and `pool.close()`, if it returned true: + +```rust +write_status(true, "compacting the database", &config.index_mode, false, "running", false, 0); +let main = paths::database(); +let started = std::time::Instant::now(); +let report = |msg: &str| println!("{msg}"); +match crate::compact::run(&main, &report) { + Ok(_) => println!("compacted in {}", crate::dashboard::human_time(started.elapsed().as_secs() as i64)), + Err(e) => { + ui::error(&format!("auto compaction failed, the originals were kept: {e:#}")); + stats.lock().unwrap().error_count += 1; + } +} +if let Ok(conn) = db::open_at(&main) { + let _ = crate::store::set_meta(&conn, "last_compact", chrono::Utc::now().timestamp()); +} +``` + +`compact::run` takes `&(dyn Fn(&str) + Sync)`; a closure that only prints is `Sync`. The loop continues and rebuilds the pool as for a config change. Record `last_compact` even on failure, so a failing compaction is retried 24 hours later, not every minute. + +- [ ] **Step 5: Run the tests** + +Run: `cargo test --test auto_compact && just test` +Expected: PASS. + +- [ ] **Step 6: Lint and commit** + +Run: `just format && just lint` + +```bash +git add src/config.rs src/bg_indexer.rs src/store.rs tests/auto_compact.rs +git commit -m "auto_run_compact: compact every 24 hours from the indexer + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +### Task 12: Documentation and full verification + +**Files:** +- Modify: `README.md`, `config.example.json` + +- [ ] **Step 1: README** + +In `README.md`, using the same Google developer style as the rest of the file (second person, present tense, sentence-case headings, no "e.g."): + +- **Top-level keys table:** add rows for `split_min_backlog` (default `10000000`: "Article numbers of backfill left before a group's backfill is split into day chunks that every server carrying the group can take") and `auto_run_compact` (default `false`: "Compact the database every 24 hours; indexing pauses while it runs"). +- **"How the database is stored":** add one paragraph on sealed files ("a file's articles are sealed into one compressed blob once it's complete or untouched for 3 days") and one on packed message-ids. +- **Indexing section:** add a short "Splitting big groups" paragraph: chunks by day, idle workers on any carrying server take the newest, live indexing stays on the home server. +- **Converting an older database / compact text:** `--compact` also re-encodes message-ids and seals due files. + +- [ ] **Step 2: config.example.json** + +Add `"auto_run_compact": false` at the top level. + +- [ ] **Step 3: Full verification** + +Run: `just format && just format-check && just lint && just test` +Expected: all clean and every test passing. Record the test count. + +- [ ] **Step 4: Commit** + +```bash +git add README.md config.example.json +git commit -m "Document split backfill, sealed files, packed message-ids, auto_run_compact + +Co-Authored-By: Claude Opus 5.5 " +``` + +--- + +## Self-review notes + +- **Spec coverage:** Part 1 maps to Tasks 1–5 (`article_at`, table, `run_chunk`, scheduling, dashboard). Part 2 maps to Task 6. Part 3 maps to Tasks 7–10 (codec, store sealing plus reads plus late articles, online sealing, compact). Part 4 maps to Task 11. Testing items are spread through the tasks; docs are in Task 12. +- **Deviation from the spec:** the blob format sorts segments by `(part, local)` for compression instead of by message-id. Reads sort after decoding (`articles()` already does), so NZB output is unchanged. +- **Type consistency:** + - `add_segment` changes signature in Task 8 (`&FileState`, `&mut SealedCache`). Task 6 adds a check inside it first, and Task 8 must keep that check. + - `PassSettings.split_min_backlog` is added in Task 4; any `PassSettings` literal in tests must add it or use `..Default::default()`. From e8277c6f132e47be41bdfefa4b02b241c2a922de Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:41:51 -0500 Subject: [PATCH 003/159] Spread groups over servers, bigger header requests - A server is article only after 3 GROUP refusals in a row, not one (news.frugalusenet.com was switched off by one odd group name). - Groups their first server doesnt carry fall back by connection weighted rendezvous hashing instead of the first server in the list, and remember where they live. - request_size 10000 / batch_size 500000 by default: measured 3-6x the headers/s per connection on old articles (examples/probe_xover.rs). Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++-- examples/probe_xover.rs | 82 +++++++++++++++++++++++++++++++++++++ src/config.rs | 11 +++-- src/nntp.rs | 91 +++++++++++++++++++++++++++++++++-------- tests/server_quirks.rs | 22 ++++++++++ 5 files changed, 190 insertions(+), 24 deletions(-) create mode 100644 examples/probe_xover.rs diff --git a/README.md b/README.md index ade09b07..e8b3ff2f 100644 --- a/README.md +++ b/README.md @@ -115,8 +115,8 @@ On first run, Atlas asks for one server (host, username, password, and port) and "group": "alt.binaries.example", "groups": ["alt.binaries.example", "alt.binaries.another"], "index_mode": "dynamic", - "batch_size": 50000, - "request_size": 1000, + "batch_size": 500000, + "request_size": 10000, "parallel_groups": 20, "api_host": "0.0.0.0", "api_port": 9090, @@ -132,8 +132,8 @@ On first run, Atlas asks for one server (host, username, password, and port) and | `groups` | `[]` | Newsgroups to index. Add them from the Groups menu or edit the list. | | `group` | | The current group, used by the menu's current-group search. | | `index_mode` | `dynamic` | `dynamic` alternates backfill and live passes, `backfill` indexes older posts only, and `live` indexes new posts only. | -| `batch_size` | `50000` | Article numbers per indexing pass over a group. The cursor moves only after a whole pass finishes. | -| `request_size` | `1000` | Article numbers per header request, which is one connection's slice of a pass. | +| `batch_size` | `500000` | Article numbers per indexing pass over a group. The cursor moves only after a whole pass finishes. | +| `request_size` | `10000` | Article numbers per header request, which is one connection's slice of a pass. Providers spend most of a request's time on their side, so on old articles 10,000 per request is 3–6 times faster per connection than 1,000. | | `parallel_groups` | 1 per 5 connections | Total groups indexed at the same time, shared between servers by their `connections`. Every server gets at least one. | | `api_host` | `127.0.0.1` | Address the Newznab API listens on. Use `0.0.0.0` to reach it from other machines. | | `api_port` | `9090` | Newznab API port. | diff --git a/examples/probe_xover.rs b/examples/probe_xover.rs new file mode 100644 index 00000000..fb16746d --- /dev/null +++ b/examples/probe_xover.rs @@ -0,0 +1,82 @@ +//! How header request size changes speed on one connection: times XOVER for +//! ranges of different sizes on each usenet server in config.json, plus the +//! round trip of a DATE (what pipelining could hide at most). +//! +//! ATLAS_HOME=. cargo run --release --example probe_xover -- --group alt.binaries.boneless \ +//! [--sizes 1000,10000,50000] [--only host] [--back articles] [--rounds n] +//! +//! Read only (GROUP, XOVER, DATE). Prints no passwords. + +use std::time::{Duration, Instant}; + +use atlas::config::load_config; +use atlas::nntp::Conn; + +fn arg(name: &str) -> Option { + std::env::args().skip_while(|a| a != name).nth(1) +} + +fn main() { + tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap().block_on(run()); +} + +async fn run() { + let group = arg("--group").unwrap_or_else(|| "alt.binaries.boneless".into()); + let sizes: Vec = + arg("--sizes").unwrap_or_else(|| "1000,10000,50000".into()).split(',').filter_map(|s| s.parse().ok()).collect(); + let only = arg("--only"); + // start this many articles back from the newest (backfill reads old ones) + let back: u64 = arg("--back").and_then(|v| v.parse().ok()).unwrap_or(0); + let rounds: usize = arg("--rounds").and_then(|v| v.parse().ok()).unwrap_or(2); + + let cfg = load_config().expect("no config.json (set ATLAS_HOME)"); + for server in cfg.servers.iter().filter(|s| s.indexes()) { + if only.as_ref().is_some_and(|o| !server.host.contains(o.as_str())) { + continue; + } + let mut conn = match Conn::open(server, Duration::from_secs(60), server.compress.unwrap_or(true)).await { + Ok(c) => c, + Err(e) => { + println!("{:32} couldnt connect: {e}", server.host); + continue; + } + }; + let Ok((_, _, last, _)) = conn.select_group(&group).await else { + println!("{:32} no {group}", server.host); + continue; + }; + + let mut rtts = Vec::new(); + for _ in 0..5 { + let t = Instant::now(); + let _ = conn.command("DATE", None).await; + rtts.push(t.elapsed().as_secs_f64() * 1000.0); + } + rtts.sort_by(|a, b| a.total_cmp(b)); + println!("{:32} DATE round trip {:.0}ms (median of 5), compressed {}", server.host, rtts[2], conn.compressed); + + // each size on its own range, going back from the newest articles + let mut end = last.saturating_sub(back); + for &size in &sizes { + for round in 0..rounds { + let start = end.saturating_sub(size - 1); + let t = Instant::now(); + match conn.xover(start, end).await { + Ok(rows) => { + let secs = t.elapsed().as_secs_f64(); + println!( + "{:32} {size:>7} articles (round {round}): {:>6.0}ms, {:>6} rows, {:>8.0} headers/s", + "", + secs * 1000.0, + rows.len(), + rows.len() as f64 / secs + ); + } + Err(e) => println!("{:32} {size:>7} articles: {e}", ""), + } + end = start.saturating_sub(1); + } + } + conn.quit().await; + } +} diff --git a/src/config.rs b/src/config.rs index 21d17226..d6c2a9cd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -14,14 +14,17 @@ pub const DEFAULT_API_HOST: &str = "127.0.0.1"; pub const DEFAULT_CONNECTIONS: u32 = 10; /// servers without a priority go after the ones that have one pub const DEFAULT_PRIORITY: i64 = 99; -/// article numbers the indexer takes on per pass over a group -pub const DEFAULT_BATCH_SIZE: u64 = 50_000; +/// article numbers the indexer takes on per pass over a group (50 requests) +pub const DEFAULT_BATCH_SIZE: u64 = 500_000; /// with `parallel_groups` unset, one group runs per this many connections pub const CONNECTIONS_PER_GROUP: usize = 5; /// sanity cap on groups indexed at once pub const MAX_PARALLEL_GROUPS: usize = 256; -/// article numbers per XOVER request (one connection's slice of a batch) -pub const DEFAULT_REQUEST_SIZE: u64 = 1_000; +/// article numbers per XOVER request (one connection's slice of a batch). +/// providers spend most of a request's time on their side, not the network: +/// measured on old articles, 10k per request got 3-6x the headers/s of 1k on +/// one connection, and 50k was no better on most servers and erratic +pub const DEFAULT_REQUEST_SIZE: u64 = 10_000; /// One usenet provider. Lower `priority` is tried first. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/src/nntp.rs b/src/nntp.rs index c4364324..f093ff55 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1,6 +1,7 @@ //! Async NNTP client (tokio): just what atlas needs (GROUP, XOVER, BODY, LIST), //! with a connection pool per usenet server soo many requests are in flight at once. +use std::collections::HashMap; use std::fmt; use std::future::Future; use std::io; @@ -155,6 +156,8 @@ fn refusal(e: &NntpError) -> Refusal { const STREAM_END_WAIT: Duration = Duration::from_secs(2); /// after a failed connect a server is skipped for this long (connect() still tries it) const DOWN_FOR: Duration = Duration::from_secs(60); +/// GROUPs refused with 500/501 in a row before a server counts as article only +const GROUP_REFUSALS: usize = 3; /// how often a request in flight looks at the stop flag const STOP_POLL: Duration = Duration::from_millis(50); @@ -662,6 +665,8 @@ struct Server { /// server answered GROUP with 500/501: an article only server (fill / bonus), /// used for article lookups but not for indexing no_index: AtomicBool, + /// GROUPs answered 500/501 in a row; a real server can reject one odd group name + group_refusals: AtomicUsize, /// login rejected or limit shrunk messages already printed warned_auth: AtomicBool, warned_limit: AtomicBool, @@ -767,6 +772,8 @@ pub struct Pool { ready: AtomicBool, failed_over_at: Mutex>, timeout: Duration, + /// groups their first choice server doesnt carry: the server that does + homes: Mutex>, } impl Pool { @@ -782,6 +789,7 @@ impl Pool { down_until: Mutex::new(None), no_compress: AtomicBool::new(false), no_index: AtomicBool::new(false), + group_refusals: AtomicUsize::new(0), warned_auth: AtomicBool::new(false), warned_limit: AtomicBool::new(false), limit: AtomicUsize::new(cfg.connections().max(1) as usize), @@ -795,6 +803,7 @@ impl Pool { ready: AtomicBool::new(false), failed_over_at: Mutex::new(None), timeout: DEFAULT_TIMEOUT, + homes: Mutex::new(HashMap::new()), } } @@ -864,6 +873,13 @@ impl Pool { /// in proportion to each server's connections, and a group keeps its /// server (its cursors are per server) as long as that server is healthy. pub fn pick_server_in(&self, tier: &[usize], group: &str) -> usize { + // a group its first choice doesnt carry lives where it was found + if let Some(&home) = self.homes.lock().unwrap().get(group) + && tier.contains(&home) + { + return home; + } + let total: u64 = tier.iter().map(|&i| self.connections(i) as u64).sum(); if total == 0 { return tier.first().copied().unwrap_or(0); @@ -884,6 +900,33 @@ impl Pool { tier[0] } + /// `candidates` in the order a group should try them: rendezvous hashing + /// weighted by connections, soo groups that need another server spread + /// over all of them in proportion (not all onto the first in the list), + /// and the same group always gets the same order. + fn ranked(&self, candidates: &[usize], group: &str) -> Vec { + let fnv = |bytes: &[u8]| { + bytes.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) + }; + let mut scored: Vec<(f64, usize)> = candidates + .iter() + .map(|&i| { + let key = format!("{group}\0{}", self.servers[i].cfg.host); + // splitmix64's finalizer: fnv alone barely changes between hosts + let mut z = fnv(key.as_bytes()); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^= z >> 31; + // a well mixed number in (0, 1] + let h = ((z >> 11) + 1) as f64 / (1u64 << 53) as f64; + let weight = self.connections(i).max(1) as f64; + (-(h.max(f64::MIN_POSITIVE)).ln() / weight, i) + }) + .collect(); + scored.sort_by(|a, b| a.0.total_cmp(&b.0)); + scored.into_iter().map(|(_, i)| i).collect() + } + /// requests the active server takes at once pub fn concurrency(&self) -> usize { self.servers.get(self.active_index()).map(|s| s.cfg.connections() as usize).unwrap_or(1) @@ -1055,14 +1098,19 @@ impl Pool { let mut lease = self.lease_for(i, Some(group), false).await?; let r = lease.begin().select_group(group).await; - // GROUP not supported at all: an article only (fill / bonus) server - if let Err(e) = &r - && matches!(e.code(), Some(500 | 501)) - { - let server = &self.servers[i]; - if !server.no_index.swap(true, Ordering::Relaxed) { - println!("{}: doesnt support GROUP ({e}), using it for article lookups only", server.cfg.host); + // GROUP not supported at all: an article only (fill / bonus) server. one + // refusal can be a group name the server doesnt like, soo it takes + // GROUP_REFUSALS in a row with no GROUP working in between + let server = &self.servers[i]; + match &r { + Err(e) if matches!(e.code(), Some(500 | 501)) => { + let refusals = server.group_refusals.fetch_add(1, Ordering::Relaxed) + 1; + if refusals >= GROUP_REFUSALS && !server.no_index.swap(true, Ordering::Relaxed) { + println!("{}: doesnt support GROUP ({e}), using it for article lookups only", server.cfg.host); + } } + Ok(_) => server.group_refusals.store(0, Ordering::Relaxed), + Err(_) => {} } lease.check(r) @@ -1088,21 +1136,18 @@ impl Pool { Err(e) => return Err(e), }; + let usable = |i: &usize| *i != prefer && !self.servers[*i].no_index.load(Ordering::Relaxed); + let indexing: Vec = self.indexing_servers().into_iter().filter(usable).collect(); let candidates: Vec = self - .indexing_servers() + .ranked(&indexing, group) .into_iter() - .chain(0..self.servers.len()) - .filter(|&i| i != prefer && !self.servers[i].no_index.load(Ordering::Relaxed)) - .fold(Vec::new(), |mut v, i| { - if !v.contains(&i) { - v.push(i); - } - v - }); + .chain((0..self.servers.len()).filter(|i| usable(i) && !indexing.contains(i))) + .collect(); for i in candidates { if let Ok(r) = self.select_on(i, group).await { println!("{group} not on {}, using {}", self.servers[prefer].cfg.host, self.servers[i].cfg.host); + self.homes.lock().unwrap().insert(group.to_string(), i); return Ok((i, r)); } } @@ -1746,6 +1791,20 @@ mod tests { // stable: same group, same server assert_eq!(pool.pick_server("alt.binaries.x"), pool.pick_server("alt.binaries.x")); + + // groups that need another server spread over the others by connections, + // not all onto the first in the list + let mut first = [0usize; 4]; + for i in 0..5000 { + first[pool.ranked(&[1, 2], &format!("alt.binaries.group{i}"))[0]] += 1; + } + let share_c = first[2] as f64 / 5000.0; + assert!((share_c - 0.75).abs() < 0.05, "10:30 connections -> about 25% / 75%: {first:?}"); + assert_eq!(pool.ranked(&[1, 2], "alt.binaries.x"), pool.ranked(&[1, 2], "alt.binaries.x"), "stable order"); + + // once found elsewhere, a group is picked there + pool.homes.lock().unwrap().insert("alt.binaries.moved".into(), 1); + assert_eq!(pool.pick_server("alt.binaries.moved"), 1); } #[test] diff --git a/tests/server_quirks.rs b/tests/server_quirks.rs index 9e7b4539..88f66b2b 100644 --- a/tests/server_quirks.rs +++ b/tests/server_quirks.rs @@ -61,6 +61,28 @@ fn article_only_servers_stop_indexing() { let (server, info) = pool.block_on(pool.pool.select_group_on(0, GROUP)).unwrap(); assert_eq!(server, 1, "the group should move to the server that has GROUP"); assert_eq!(info.2, 50); + // one refusal can be a group name a real server doesnt like + assert_eq!(pool.pool.indexing_servers(), vec![0, 1], "one refusal isnt enough"); + + // refused again and again: an article only server + for _ in 0..2 { + pool.block_on(pool.pool.select_group_on(0, GROUP)).unwrap(); + } assert_eq!(pool.pool.indexing_servers(), vec![1], "the fill server is out of indexing"); assert_eq!(pool.pool.pick_server("alt.binaries.anything"), 1); } + +/// A real server that rejects one odd group name keeps indexing the others. +#[test] +fn one_rejected_group_doesnt_take_a_server_out() { + let normal = Server::new(posts(50)); + let port = spawn_server(normal.clone()); + let pool = BlockingPool::new(&[mock(port, "secret", 4, 1)]); + + // the mock answers 411 for unknown groups; a 501 for one name, then GROUP works + for _ in 0..2 { + let _ = pool.block_on(pool.pool.select_group_on(0, "alt.binaries.missing")); + } + assert!(pool.block_on(pool.pool.select_group_on(0, GROUP)).is_ok()); + assert_eq!(pool.pool.indexing_servers(), vec![0]); +} From 538ac992625caab491e97df55ee0656591f34692 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:42:20 -0500 Subject: [PATCH 004/159] Ignore .worktrees Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index e5d6f45c..9b0ba58d 100644 --- a/.gitignore +++ b/.gitignore @@ -66,3 +66,6 @@ __pycache__/ *.pyc mock_nntp_server.py dev_nntp_server.py + +# git worktrees for isolated work +/.worktrees/ From 60fee3b7929675494b71f14ce95696c409b06e22 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:46:02 -0500 Subject: [PATCH 005/159] Ignore .superpowers scratch Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 9b0ba58d..d8750886 100644 --- a/.gitignore +++ b/.gitignore @@ -69,3 +69,4 @@ dev_nntp_server.py # git worktrees for isolated work /.worktrees/ +/.superpowers/ From a7f4dffce52301c4fe6ded0d1cc3b47b1eefb01a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:50:16 -0500 Subject: [PATCH 006/159] Find the article posted at a time by binary search Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 44 ++++++++++++++++++++++++++++++++++++++++++++ tests/common/mod.rs | 20 +++++++++++++++++--- tests/date_search.rs | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 98 insertions(+), 3 deletions(-) create mode 100644 tests/date_search.rs diff --git a/src/nntp.rs b/src/nntp.rs index f093ff55..7e48a60b 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1155,6 +1155,50 @@ impl Pool { Err(first_err) } + /// The first article at or after `number` within the next `look` numbers on + /// server `i`, with its post time: (number, unix seconds). None when there is + /// none (a gap in the numbering). + async fn posted_at(&self, i: usize, group: &str, number: u64, look: u64) -> Result> { + match self.xover_on(i, group, number, number + look - 1).await { + Ok(rows) => Ok(rows + .iter() + .filter_map(|r| crate::dates::posted_timestamp(&r.date).map(|t| (r.number, t))) + .min_by_key(|(n, _)| *n)), + Err(e) if e.code() == Some(423) => Ok(None), + Err(e) => Err(e), + } + } + + /// The first article number in `low..=high` on server `i` posted at or after + /// `when` (unix seconds), `high + 1` when there is none. A binary search over + /// small article requests (about 35 for a billion numbers, plus one to settle). Post dates are + /// only roughly in order, so the answer is approximate near the edges: + /// callers overlap their ranges. + pub async fn article_at(&self, i: usize, group: &str, low: u64, high: u64, when: i64) -> Result { + const LOOK: u64 = 100; + let (mut lo, mut hi) = (low, high + 1); + while lo < hi { + let mid = lo + (hi - lo) / 2; + match self.posted_at(i, group, mid, LOOK).await? { + Some((n, t)) if t < when => lo = n + 1, + Some(_) => hi = mid, + // a gap: nothing to compare, keep searching to the left of it + None => hi = mid, + } + } + if lo > high { + return Ok(lo); + } + // lo may be a number missing from the group: settle on the article that exists + let look = LOOK.min(high + 1 - lo); + Ok(match self.posted_at(i, group, lo, look).await? { + Some((n, _)) => n, + // nothing up to the end of the range + None if look == high + 1 - lo => high + 1, + None => lo, + }) + } + async fn xover_on(&self, i: usize, group: &str, start: u64, end: u64) -> Result> { match self.xover_once(i, group, start, end).await { Err(NntpError::Decompress(e)) => { diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 8aff3fd1..2afeb1e3 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -20,6 +20,8 @@ pub struct Post { pub message_id: String, pub bytes: u64, pub body: Vec>, + /// the Date header, rfc 2822 + pub date: String, } pub struct Server { @@ -131,7 +133,19 @@ pub fn par2_file_desc(name: &str, size: u64) -> Vec { } pub fn post(number: u64, subject: &str, bytes: u64, body: Vec>) -> Post { - Post { number, subject: subject.into(), message_id: format!(""), bytes, body } + Post { + number, + subject: subject.into(), + message_id: format!(""), + bytes, + body, + date: "Fri, 02 Oct 2026 10:11:12 +0000".into(), + } +} + +/// A post with its own date (rfc 2822), for date based tests. +pub fn post_at(number: u64, subject: &str, date: &str) -> Post { + Post { date: date.into(), ..post(number, subject, 10, vec![]) } } pub fn handle(stream: TcpStream, state: Arc) { @@ -218,8 +232,8 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { let mut listing = Vec::new(); for p in hits { let row = format!( - "{}\t{}\tposter \tFri, 02 Oct 2026 10:11:12 +0000\t{}\t\t{}\t10\r\n", - p.number, p.subject, p.message_id, p.bytes + "{}\t{}\tposter \t{}\t{}\t\t{}\t10\r\n", + p.number, p.subject, p.date, p.message_id, p.bytes ); listing.extend_from_slice(row.as_bytes()); } diff --git a/tests/date_search.rs b/tests/date_search.rs new file mode 100644 index 00000000..68c36494 --- /dev/null +++ b/tests/date_search.rs @@ -0,0 +1,37 @@ +//! Finding the article posted at a given time by binary search over one +//! article XOVERs, with gaps in the numbering and slightly out of order dates. + +mod common; + +use atlas::nntp::BlockingPool; +use common::{GROUP, Server, mock, post_at, spawn_server}; + +/// posts 1..=1000, one per hour from 2026-01-01 00:00 UTC, with every 10th +/// number missing and number 500 dated an hour too early +fn hourly() -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (1..=1000u64) + .filter(|n| n % 10 != 0) + .map(|n| { + let hours = if n == 500 { n as i64 - 2 } else { n as i64 - 1 }; + let when = start + chrono::Duration::hours(hours); + post_at(n, &format!(r#""p{n}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() +} + +#[test] +fn finds_the_first_article_at_or_after_a_time() { + let port = spawn_server(Server::new(hourly())); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + let at = |rfc3339: &str| { + let t = chrono::DateTime::parse_from_rfc3339(rfc3339).unwrap().timestamp(); + pool.block_on(pool.pool.article_at(0, GROUP, 1, 1000, t)).unwrap() + }; + + assert_eq!(at("2025-12-01T00:00:00+00:00"), 1, "before everything: the first article"); + assert_eq!(at("2026-01-01T04:00:00+00:00"), 5, "exactly on an article"); + assert_eq!(at("2026-01-01T08:30:00+00:00"), 11, "number 10 is missing, 11 is next"); + assert_eq!(at("2026-03-01T00:00:00+00:00"), 1001, "after everything: high + 1"); +} From a43a2c0141ef026f1298dfd4f3788da944b55979 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:53:01 -0500 Subject: [PATCH 007/159] Day chunks of backfill in the main database Co-Authored-By: Claude Haiku 4.5 --- src/chunks.rs | 145 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/store.rs | 4 +- 3 files changed, 149 insertions(+), 1 deletion(-) create mode 100644 src/chunks.rs diff --git a/src/chunks.rs b/src/chunks.rs new file mode 100644 index 00000000..3af8262a --- /dev/null +++ b/src/chunks.rs @@ -0,0 +1,145 @@ +//! Day chunks of a group's backfill that any server carrying the group can +//! take (see docs/superpowers/specs/2026-10-05-faster-backfill-smaller-storage-design.md). +//! Lives in the main database. + +use rusqlite::{Connection, OptionalExtension, Result, params}; + +/// a claim older than this is taken over (its worker died or was stopped) +pub const CLAIM_TIMEOUT: i64 = 30 * 60; + +const PENDING: i64 = 0; +const CLAIMED: i64 = 1; +const DONE: i64 = 2; + +pub fn create(conn: &Connection) -> Result<()> { + conn.execute_batch( + "create table if not exists backfill_chunks ( + grp TEXT NOT NULL, + day INTEGER NOT NULL, + state INTEGER NOT NULL, + server TEXT, + claimed_at INTEGER, + primary key (grp, day) + ) without rowid;", + ) +} + +/// days since 1970-01-01 UTC +pub fn unix_day(t: i64) -> i64 { + t.div_euclid(86_400) +} + +/// Pending chunks for `newest_day` down to `oldest_day`, keeping any that exist. +pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> Result { + let mut insert = conn.prepare_cached("insert or ignore into backfill_chunks (grp, day, state) values (?, ?, ?)")?; + let mut added = 0; + for day in (oldest_day..=newest_day).rev() { + added += insert.execute(params![group, day, PENDING])?; + } + Ok(added) +} + +pub fn is_split(conn: &Connection, group: &str) -> Result { + conn.prepare_cached("select 1 from backfill_chunks where grp = ? limit 1")?.exists([group]) +} + +/// The newest chunk of `groups` that is pending or whose claim went stale, +/// claimed for `host`. The indexer's main connection is the only writer, so select then update is safe. +pub fn claim(conn: &Connection, groups: &[String], host: &str, now: i64) -> Result> { + if groups.is_empty() { + return Ok(None); + } + let marks = vec!["?"; groups.len()].join(","); + let sql = format!( + "select grp, day from backfill_chunks + where grp in ({marks}) and (state = {PENDING} or (state = {CLAIMED} and claimed_at < ?)) + order by day desc limit 1" + ); + let mut values: Vec = groups.iter().map(|g| g.clone().into()).collect(); + values.push((now - CLAIM_TIMEOUT).into()); + let found: Option<(String, i64)> = + conn.prepare(&sql)?.query_row(rusqlite::params_from_iter(values), |r| Ok((r.get(0)?, r.get(1)?))).optional()?; + if let Some((group, day)) = &found { + conn.execute( + "update backfill_chunks set state = ?, server = ?, claimed_at = ? where grp = ? and day = ?", + params![CLAIMED, host, now, group, day], + )?; + } + Ok(found) +} + +pub fn finish(conn: &Connection, group: &str, day: i64) -> Result<()> { + conn.execute("update backfill_chunks set state = ? where grp = ? and day = ?", params![DONE, group, day])?; + Ok(()) +} + +pub fn release(conn: &Connection, group: &str, day: i64) -> Result<()> { + conn.execute( + "update backfill_chunks set state = ?, server = null, claimed_at = null where grp = ? and day = ?", + params![PENDING, group, day], + )?; + Ok(()) +} + +/// (done, total) chunks of a group +pub fn progress(conn: &Connection, group: &str) -> Result<(i64, i64)> { + conn.query_row("select coalesce(sum(state = 2), 0), count(*) from backfill_chunks where grp = ?", [group], |r| { + Ok((r.get(0)?, r.get(1)?)) + }) +} + +/// groups with chunks still to do +pub fn split_groups(conn: &Connection) -> Result> { + conn.prepare("select distinct grp from backfill_chunks where state != 2 order by grp")? + .query_map([], |r| r.get(0))? + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn conn() -> Connection { + let c = Connection::open_in_memory().unwrap(); + create(&c).unwrap(); + c + } + + #[test] + fn days_are_claimed_newest_first_and_once() { + let c = conn(); + assert_eq!(add(&c, "g", 20_000, 19_998).unwrap(), 3); + assert_eq!(add(&c, "g", 20_000, 19_998).unwrap(), 0, "adding again adds nothing"); + assert!(is_split(&c, "g").unwrap()); + let groups = vec!["g".to_string()]; + + assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), Some(("g".into(), 20_000))); + assert_eq!(claim(&c, &groups, "b", 1000).unwrap(), Some(("g".into(), 19_999))); + finish(&c, "g", 20_000).unwrap(); + release(&c, "g", 19_999).unwrap(); + assert_eq!(claim(&c, &groups, "b", 1000).unwrap(), Some(("g".into(), 19_999)), "released goes back"); + assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), Some(("g".into(), 19_998))); + assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), None); + assert_eq!(progress(&c, "g").unwrap(), (1, 3)); + } + + #[test] + fn stale_claims_are_taken_over() { + let c = conn(); + add(&c, "g", 5, 5).unwrap(); + let groups = vec!["g".to_string()]; + assert!(claim(&c, &groups, "a", 1000).unwrap().is_some()); + assert_eq!(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT - 1).unwrap(), None); + assert_eq!(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT + 1).unwrap(), Some(("g".into(), 5))); + } + + #[test] + fn only_listed_groups_and_unsplit_groups() { + let c = conn(); + add(&c, "g", 5, 5).unwrap(); + assert_eq!(claim(&c, &["other".to_string()], "a", 0).unwrap(), None); + assert!(!is_split(&c, "other").unwrap()); + assert_eq!(split_groups(&c).unwrap(), vec!["g".to_string()]); + assert_eq!(unix_day(86_400 * 3 + 5), 3); + } +} diff --git a/src/lib.rs b/src/lib.rs index 71f14364..024c889e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod api; pub mod app; pub mod atomic; pub mod bg_indexer; +pub mod chunks; pub mod compact; pub mod config; pub mod convert; diff --git a/src/store.rs b/src/store.rs index f20592fc..be441cce 100644 --- a/src/store.rs +++ b/src/store.rs @@ -92,7 +92,9 @@ pub fn create_main(conn: &Connection) -> Result<()> { conn.execute_batch( "create table if not exists meta (key TEXT PRIMARY KEY, value INTEGER); insert or ignore into meta (key, value) values ('next_seq', 1);", - ) + )?; + crate::chunks::create(conn)?; + Ok(()) } /// A shard's tables, if missing. From 2f2e187b04bf37f2f4446136e770ee489ec0ff9d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:55:52 -0500 Subject: [PATCH 008/159] Fix: make claim atomic, wrap add in transaction, add doc comments - Replace select-then-update in claim with atomic UPDATE...RETURNING - Wrap insert loop in add with unchecked_transaction - Add doc comments to create, is_split, finish, release - Add concurrent-connection test verifying atomicity Co-Authored-By: Claude Haiku 4.5 --- src/chunks.rs | 65 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 50 insertions(+), 15 deletions(-) diff --git a/src/chunks.rs b/src/chunks.rs index 3af8262a..4be94602 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -11,6 +11,7 @@ const PENDING: i64 = 0; const CLAIMED: i64 = 1; const DONE: i64 = 2; +/// Initialize the backfill_chunks table if it doesn't exist. pub fn create(conn: &Connection) -> Result<()> { conn.execute_batch( "create table if not exists backfill_chunks ( @@ -31,48 +32,52 @@ pub fn unix_day(t: i64) -> i64 { /// Pending chunks for `newest_day` down to `oldest_day`, keeping any that exist. pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> Result { - let mut insert = conn.prepare_cached("insert or ignore into backfill_chunks (grp, day, state) values (?, ?, ?)")?; + let tx = conn.unchecked_transaction()?; let mut added = 0; - for day in (oldest_day..=newest_day).rev() { - added += insert.execute(params![group, day, PENDING])?; + { + let mut insert = + tx.prepare_cached("insert or ignore into backfill_chunks (grp, day, state) values (?, ?, ?)")?; + for day in (oldest_day..=newest_day).rev() { + added += insert.execute(params![group, day, PENDING])?; + } } + tx.commit()?; Ok(added) } +/// Check if a group has any chunks in backfill. pub fn is_split(conn: &Connection, group: &str) -> Result { conn.prepare_cached("select 1 from backfill_chunks where grp = ? limit 1")?.exists([group]) } -/// The newest chunk of `groups` that is pending or whose claim went stale, -/// claimed for `host`. The indexer's main connection is the only writer, so select then update is safe. +/// Atomically claim the newest chunk of `groups` that is pending or whose claim went stale. pub fn claim(conn: &Connection, groups: &[String], host: &str, now: i64) -> Result> { if groups.is_empty() { return Ok(None); } let marks = vec!["?"; groups.len()].join(","); let sql = format!( - "select grp, day from backfill_chunks - where grp in ({marks}) and (state = {PENDING} or (state = {CLAIMED} and claimed_at < ?)) - order by day desc limit 1" + "update backfill_chunks set state = ?, server = ?, claimed_at = ? + where (grp, day) = (select grp, day from backfill_chunks + where grp in ({marks}) and (state = {PENDING} or (state = {CLAIMED} and claimed_at < ?)) + order by day desc limit 1) + returning grp, day" ); - let mut values: Vec = groups.iter().map(|g| g.clone().into()).collect(); + let mut values: Vec = vec![CLAIMED.into(), host.to_string().into(), now.into()]; + values.extend(groups.iter().map(|g| g.clone().into())); values.push((now - CLAIM_TIMEOUT).into()); let found: Option<(String, i64)> = conn.prepare(&sql)?.query_row(rusqlite::params_from_iter(values), |r| Ok((r.get(0)?, r.get(1)?))).optional()?; - if let Some((group, day)) = &found { - conn.execute( - "update backfill_chunks set state = ?, server = ?, claimed_at = ? where grp = ? and day = ?", - params![CLAIMED, host, now, group, day], - )?; - } Ok(found) } +/// Mark a chunk as done. pub fn finish(conn: &Connection, group: &str, day: i64) -> Result<()> { conn.execute("update backfill_chunks set state = ? where grp = ? and day = ?", params![DONE, group, day])?; Ok(()) } +/// Return a claimed chunk to pending state. pub fn release(conn: &Connection, group: &str, day: i64) -> Result<()> { conn.execute( "update backfill_chunks set state = ?, server = null, claimed_at = null where grp = ? and day = ?", @@ -142,4 +147,34 @@ mod tests { assert_eq!(split_groups(&c).unwrap(), vec!["g".to_string()]); assert_eq!(unix_day(86_400 * 3 + 5), 3); } + + #[test] + fn claim_is_atomic_with_concurrent_connections() { + let dir = tempfile::tempdir().unwrap(); + let db_path = dir.path().join("test.db"); + + // create db and add chunks + let c1 = Connection::open(&db_path).unwrap(); + create(&c1).unwrap(); + add(&c1, "g", 20, 19).unwrap(); + c1.close().ok(); + + // open two connections and claim + let c_a = Connection::open(&db_path).unwrap(); + let c_b = Connection::open(&db_path).unwrap(); + + let groups = vec!["g".to_string()]; + let a_claim = claim(&c_a, &groups, "a", 1000).unwrap(); + let b_claim = claim(&c_b, &groups, "b", 1000).unwrap(); + + // they should get different days (newest first, then next) + assert!(a_claim.is_some() && b_claim.is_some()); + assert_ne!(a_claim.as_ref().map(|(_, d)| d), b_claim.as_ref().map(|(_, d)| d)); + assert_eq!(a_claim.as_ref().map(|(_, d)| d), Some(&20)); + assert_eq!(b_claim.as_ref().map(|(_, d)| d), Some(&19)); + + // third claim should get None + let c_c = Connection::open(&db_path).unwrap(); + assert_eq!(claim(&c_c, &groups, "c", 1000).unwrap(), None); + } } From 4b19f73d60e82c96b253f3c74b6110a6e8f02c54 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:58:39 -0500 Subject: [PATCH 009/159] Index one day chunk of a group on one server Co-Authored-By: Claude Sonnet 5.5 --- src/indexer.rs | 73 ++++++++++++++++++++++++++++++++++++++++++++ tests/date_search.rs | 33 ++++++++++++++++++++ 2 files changed, 106 insertions(+) diff --git a/src/indexer.rs b/src/indexer.rs index 6edc6535..01fd7d2d 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -298,6 +298,79 @@ where } } +/// a day chunk also takes this much on each side: post dates are only +/// roughly in article number order, duplicates are dropped when saved +pub const CHUNK_OVERLAP: i64 = 3600; + +/// Index one day (`day`, unix days) of `group` on `server`, for a group whose +/// backfill is split into day chunks (see chunks.rs). The chunk is marked done +/// when the whole day is in, released again if stopped part way or failing. +pub async fn run_chunk

( + ctx: &PassContext, + settings: &PassSettings, + db: &Db, + group: &str, + server: usize, + day: i64, + progress: &mut P, +) -> Result +where + P: FnMut(&Progress) + ?Sized, +{ + let release = || { + let g = group.to_string(); + on_db(db, move |conn| Ok(crate::chunks::release(conn, &g, day)?)) + }; + + let found = match ctx.pool.select_group_on(server, group).await { + Ok((s, info)) if s == server => info, + Ok(_) | Err(_) => { + release().await?; + return Err(anyhow!("{group} isnt on {}", ctx.pool.host(server))); + } + }; + let (_count, first, last, _name) = found; + + let from = day * 86_400 - CHUNK_OVERLAP; + let to = (day + 1) * 86_400 + CHUNK_OVERLAP; + let start = match ctx.pool.article_at(server, group, first, last, from).await { + Ok(n) => n, + Err(e) => { + release().await?; + return Err(e.into()); + } + }; + let end = match ctx.pool.article_at(server, group, start.max(first), last, to).await { + Ok(n) => n.saturating_sub(1), + Err(e) => { + release().await?; + return Err(e.into()); + } + }; + if start > end { + let g = group.to_string(); + on_db(db, move |conn| Ok(crate::chunks::finish(conn, &g, day)?)).await?; + return Ok(Progress::default()); + } + + let pass = Pass { ctx, settings, db, group, server, key: cursor_key(&ctx.pool, server, group) }; + match pass.process_range(start as i64, end as i64, "CHUNK", progress).await { + Ok((saved, true)) => { + let g = group.to_string(); + on_db(db, move |conn| Ok(crate::chunks::finish(conn, &g, day)?)).await?; + Ok(saved) + } + Ok((saved, false)) => { + release().await?; + Ok(saved) + } + Err(e) => { + release().await?; + Err(e) + } + } +} + struct Pass<'a> { ctx: &'a PassContext, settings: &'a PassSettings, diff --git a/tests/date_search.rs b/tests/date_search.rs index 68c36494..9ca54d79 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -35,3 +35,36 @@ fn finds_the_first_article_at_or_after_a_time() { assert_eq!(at("2026-01-01T08:30:00+00:00"), 11, "number 10 is missing, 11 is next"); assert_eq!(at("2026-03-01T00:00:00+00:00"), 1001, "after everything: high + 1"); } + +/// One day of a group indexed on one server: exactly that day's posts, the +/// chunk marked done. +#[test] +fn a_day_chunk_indexes_that_day() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let port = spawn_server(Server::new(hourly())); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + let day = + atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-02T00:00:00+00:00").unwrap().timestamp()); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let saved = + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})).unwrap(); + + // hours 24..47 are articles 25..48, plus an hour of overlap each side + // (24 and 49); 30 and 40 don't exist. 24..=49 minus 2 = 24 articles + assert_eq!(saved.articles, 24); + let conn = atlas::db::open_at(&main).unwrap(); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); +} From 4b73578261ee992dcbd376a66c7894bc4ed8d240 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:04:45 -0500 Subject: [PATCH 010/159] Split big groups' backfill into day chunks across servers Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 35 ++++++++++++++ src/config.rs | 17 +++++++ src/indexer.rs | 104 ++++++++++++++++++++++++++++++++++++++-- src/nntp.rs | 5 ++ tests/split_backfill.rs | 85 ++++++++++++++++++++++++++++++++ 5 files changed, 243 insertions(+), 3 deletions(-) create mode 100644 tests/split_backfill.rs diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index c4be1901..1dcf8039 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -219,6 +219,7 @@ fn settings_of(config: &Config) -> PassSettings { mode: config.index_mode.clone(), batch_size: config.batch_size() as i64, request_size: config.request_size(), + split_min_backlog: config.split_min_backlog(), } } @@ -253,6 +254,9 @@ struct Scheduler { next: Mutex>, /// groups a worker is on right now busy: Mutex>, + /// (group, server) pairs where the server said it doesnt carry the group, + /// soo its idle workers dont take that group's chunks + skip: Mutex>, /// groups resting after going idle or after an error wait_until: Mutex>, /// consecutive errors per group @@ -391,12 +395,42 @@ impl Scheduler { } } +/// A day chunk of any split group for an idle worker on `server`: the newest +/// one pending, among the groups this server hasnt said it lacks. +async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option<(String, i64)> { + let host = sched.ctx.pool.host(server); + let skip: Vec = + sched.skip.lock().unwrap().iter().filter(|(_, s)| *s == server).map(|(g, _)| g.clone()).collect(); + crate::indexer::claim_chunk(db, host, skip).await.ok().flatten() +} + /// One worker on `server`: index whichever of its groups is due next, again and again. /// All workers share one db connection, soo their writes queue up in order /// instead of racing for sqlite's write lock (and timing out on a busy db). async fn worker(sched: Arc, server: usize, db: Db) { while !sched.stopping() { let Some(group) = sched.take_group(server) else { + // nothing of its own: help with a split group's day chunks. not + // marked busy, a group's chunks run on several servers at once + if let Some((group, day)) = take_chunk(&sched, server, &db).await { + let settings = sched.settings.read().unwrap().clone(); + let stats = sched.stats.clone(); + let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); + let chunk = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &group, server, day, &mut progress); + match unless_stopped(&sched.ctx.stop, chunk).await { + None => break, + Some(Err(e)) if e.to_string().contains("isnt on") => { + sched.skip.lock().unwrap().insert((group, server)); + } + Some(Err(e)) => { + ui::error(&format!("Indexing error ({group}, day chunk): {e}")); + // the chunk went back, dont grab it again right away + nap(Duration::from_secs(1), || sched.stopping()).await; + } + Some(Ok(_)) => {} + } + continue; + } nap(Duration::from_secs(1), || sched.stopping()).await; continue; }; @@ -493,6 +527,7 @@ async fn run_servers( workers, next: Mutex::new(HashMap::new()), busy: Mutex::new(HashSet::new()), + skip: Mutex::new(HashSet::new()), wait_until: Mutex::new(HashMap::new()), errors: Mutex::new(HashMap::new()), failed: Mutex::new(HashMap::new()), diff --git a/src/config.rs b/src/config.rs index d6c2a9cd..c32d6cbb 100644 --- a/src/config.rs +++ b/src/config.rs @@ -25,6 +25,9 @@ pub const MAX_PARALLEL_GROUPS: usize = 256; /// measured on old articles, 10k per request got 3-6x the headers/s of 1k on /// one connection, and 50k was no better on most servers and erratic pub const DEFAULT_REQUEST_SIZE: u64 = 10_000; +/// article numbers of backfill left on a group's home server before its +/// backfill is split into day chunks over every server that carries it +pub const SPLIT_MIN_BACKLOG: i64 = 10_000_000; /// One usenet provider. Lower `priority` is tried first. #[derive(Clone, Debug, PartialEq, Eq)] @@ -127,6 +130,8 @@ pub struct Config { pub api_key: Option, pub batch_size: Option, pub request_size: Option, + /// None = SPLIT_MIN_BACKLOG + pub split_min_backlog: Option, /// groups indexed at the same time, None = worked out from the connections pub parallel_groups: Option, } @@ -143,6 +148,7 @@ impl Default for Config { api_key: None, batch_size: None, request_size: None, + split_min_backlog: None, parallel_groups: None, } } @@ -194,6 +200,12 @@ impl Config { self.request_size.unwrap_or(DEFAULT_REQUEST_SIZE).max(1) } + /// article numbers of backfill left before a group's backfill is split + /// over every server that carries it + pub fn split_min_backlog(&self) -> i64 { + self.split_min_backlog.unwrap_or(SPLIT_MIN_BACKLOG).max(1) + } + /// the highest priority server pub fn primary(&self) -> Option<&UsenetServer> { self.servers.first() @@ -256,6 +268,7 @@ impl Config { api_key: v.get("api_key").and_then(Value::as_str).filter(|k| !k.is_empty()).map(String::from), batch_size: v.get("batch_size").and_then(as_int).and_then(|n| u64::try_from(n).ok()).filter(|n| *n > 0), request_size: v.get("request_size").and_then(as_int).and_then(|n| u64::try_from(n).ok()).filter(|n| *n > 0), + split_min_backlog: v.get("split_min_backlog").and_then(as_int).filter(|n| *n > 0), parallel_groups: v .get("parallel_groups") .and_then(as_int) @@ -438,6 +451,10 @@ pub fn save_config(cfg: &Config) -> io::Result<()> { out.insert("api_key".into(), json!(key)); } + if let Some(n) = cfg.split_min_backlog { + out.insert("split_min_backlog".into(), json!(n)); + } + write_json(&Value::Object(out), private) } diff --git a/src/indexer.rs b/src/indexer.rs index 01fd7d2d..5d273823 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -89,6 +89,8 @@ pub struct PassSettings { pub batch_size: i64, /// article numbers per XOVER request pub request_size: u64, + /// backfill left on a group's home server before it is split into day chunks + pub split_min_backlog: i64, } impl Default for PassSettings { @@ -97,6 +99,7 @@ impl Default for PassSettings { mode: "dynamic".into(), batch_size: DEFAULT_BATCH_SIZE as i64, request_size: DEFAULT_REQUEST_SIZE, + split_min_backlog: crate::config::SPLIT_MIN_BACKLOG, } } } @@ -279,8 +282,36 @@ where let k = key.clone(); on_db(db, move |conn| Ok(db::save_group_bounds(conn, &k, first, last)?)).await?; - let pass = Pass { ctx, settings, db, group, server, key }; let phase = ctx.states.with(group, |st| st.phase); + let backfilling = settings.mode == "backfill" || (settings.mode != "live" && phase == Phase::Backfill); + if backfilling + && maybe_split(ctx, settings, db, group, server, first as u64, state.backfill_cursor.max(0) as u64).await? + { + // a split group's backfill is day chunks, this server takes the next one + let host = ctx.pool.host(server); + let g = group.to_string(); + let claimed = on_db(db, move |conn| { + Ok(crate::chunks::claim(conn, std::slice::from_ref(&g), &host, chrono::Utc::now().timestamp())?) + }) + .await?; + let r = match claimed { + Some((_, day)) => run_chunk(ctx, settings, db, group, server, day, progress).await, + None => { + // nothing pending: in backfill mode the group rests like a finished backfill + let idle = settings.mode == "backfill"; + ctx.states.with(group, |st| { + st.backfilling = false; + st.idle |= idle; + }); + Ok(Progress::default()) + } + }; + // dynamic mode takes turns, the next pass is live + ctx.states.with(group, |st| st.phase = Phase::Live); + return r; + } + + let pass = Pass { ctx, settings, db, group, server, key }; match settings.mode.as_str() { "live" => pass.live(state, last, progress).await, @@ -298,6 +329,69 @@ where } } +/// Split `group`'s backfill into day chunks when its home server still has +/// more than `split_min_backlog` article numbers to go and another indexing +/// server carries it too. Chunks run from the day at the home cursor back to +/// the oldest day any carrying server has. True when the group is split. +async fn maybe_split( + ctx: &PassContext, + settings: &PassSettings, + db: &Db, + group: &str, + home: usize, + first: u64, + cursor: u64, +) -> Result { + let g = group.to_string(); + if on_db(db, move |conn| Ok(crate::chunks::is_split(conn, &g)?)).await? { + return Ok(true); + } + if (cursor.saturating_sub(first) as i64) < settings.split_min_backlog { + return Ok(false); + } + + // the newest day still to do: the post date at the home cursor + let newest_day = match ctx.pool.posted_date(home, group, cursor).await? { + Some(t) => crate::chunks::unix_day(t), + None => return Ok(false), + }; + + // the oldest day any other carrying server has + let mut oldest_day = newest_day; + let mut carriers = 1; + for other in ctx.pool.indexing_servers().into_iter().filter(|&s| s != home) { + let Ok((s, (_, low, _, _))) = ctx.pool.select_group_on(other, group).await else { continue }; + if s != other { + continue; + } + if let Some(t) = ctx.pool.posted_date(other, group, low).await? { + carriers += 1; + oldest_day = oldest_day.min(crate::chunks::unix_day(t)); + } + } + if let Some(t) = ctx.pool.posted_date(home, group, first).await? { + oldest_day = oldest_day.min(crate::chunks::unix_day(t)); + } + if carriers < 2 { + return Ok(false); + } + + let g = group.to_string(); + let added = on_db(db, move |conn| Ok(crate::chunks::add(conn, &g, newest_day, oldest_day)?)).await?; + println!("[SPLIT] {group}: backfill split into {added} day chunks over {carriers} servers"); + Ok(true) +} + +/// Claim the newest chunk of any split group for `host`, except `skip`. +pub async fn claim_chunk(db: &Db, host: String, skip: Vec) -> Result> { + on_db(db, move |conn| { + let groups: Vec = + crate::chunks::split_groups(conn)?.into_iter().filter(|g| !skip.contains(g)).collect(); + Ok(crate::chunks::claim(conn, &groups, &host, chrono::Utc::now().timestamp())?) + }) + .await +} + /// a day chunk also takes this much on each side: post dates are only /// roughly in article number order, duplicates are dropped when saved pub const CHUNK_OVERLAP: i64 = 3600; @@ -706,8 +800,12 @@ impl Indexer { stop: self.stop.clone(), verbose: self.verbose, }; - let settings = - PassSettings { mode: self.mode.clone(), batch_size: self.batch_size, request_size: self.request_size }; + let settings = PassSettings { + mode: self.mode.clone(), + batch_size: self.batch_size, + request_size: self.request_size, + ..PassSettings::default() + }; let db = self.db.clone(); let saved = self.client.block_on(async { diff --git a/src/nntp.rs b/src/nntp.rs index 7e48a60b..2d0628a4 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1169,6 +1169,11 @@ impl Pool { } } + /// When the first article at or after `number` on server `i` was posted (unix seconds). + pub async fn posted_date(&self, i: usize, group: &str, number: u64) -> Result> { + Ok(self.posted_at(i, group, number, 100).await?.map(|(_, t)| t)) + } + /// The first article number in `low..=high` on server `i` posted at or after /// `when` (unix seconds), `high + 1` when there is none. A binary search over /// small article requests (about 35 for a billion numbers, plus one to settle). Post dates are diff --git a/tests/split_backfill.rs b/tests/split_backfill.rs new file mode 100644 index 00000000..6d43c077 --- /dev/null +++ b/tests/split_backfill.rs @@ -0,0 +1,85 @@ +//! A big group's backfill split across two servers that number the same +//! posts differently: both servers index day chunks, every post is saved +//! exactly once, and every chunk ends done. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days, numbered from `offset` +fn posts(offset: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (0..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn a_split_group_is_shared_by_both_servers() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + let a = Server::new(posts(1)); + let b = Server::new(posts(500_001)); + let (pa, pb) = (spawn_server(a.clone()), spawn_server(b.clone())); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pa, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": pb, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 500 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(120); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let split = atlas::chunks::is_split(&conn, GROUP).unwrap_or(false); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + if split && total > 0 && done == total && articles >= 1200 { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}, split {split}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once, overlaps deduplicated"); + assert!(a.xovers.load(Ordering::SeqCst) > 0 && b.xovers.load(Ordering::SeqCst) > 0, "both servers worked"); +} From 59ce5665775acc048dcb5f73c36da29c5f3baac3 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:15:23 -0500 Subject: [PATCH 011/159] Probe split servers without moving groups, back off chunk errors Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 76 +++++++++++++++++++------- src/indexer.rs | 96 ++++++++++++++++++++++---------- src/nntp.rs | 6 ++ tests/split_backfill.rs | 14 ++++- tests/split_homes.rs | 118 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 259 insertions(+), 51 deletions(-) create mode 100644 tests/split_homes.rs diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 1dcf8039..48496b33 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -13,7 +13,7 @@ use serde_json::json; use crate::atomic::write_atomic; use crate::config::{Config, UsenetServer, load_config}; use crate::db; -use crate::indexer::{Db, PassContext, PassSettings, Progress, RunStates, run_pass, shared_db}; +use crate::indexer::{Db, NotCarried, PassContext, PassSettings, Progress, RunStates, run_pass, shared_db}; use crate::nntp::{Pool, unless_stopped}; use crate::paths; use crate::sab; @@ -254,9 +254,11 @@ struct Scheduler { next: Mutex>, /// groups a worker is on right now busy: Mutex>, - /// (group, server) pairs where the server said it doesnt carry the group, - /// soo its idle workers dont take that group's chunks - skip: Mutex>, + /// (group, server) pairs whose day chunks the server leaves alone: for + /// good (None) when it doesnt carry the group, until then after chunk errors + skip: Mutex>>, + /// consecutive day chunk errors per (group, server) + chunk_errors: Mutex>, /// groups resting after going idle or after an error wait_until: Mutex>, /// consecutive errors per group @@ -359,6 +361,33 @@ impl Scheduler { self.passes.fetch_add(1, Ordering::Relaxed); } + /// After a day chunk of `group` on `server`. Errors count like a pass error + /// and rest the pair; a server that doesnt carry the group skips its chunks for good. + fn finish_chunk(&self, group: String, server: usize, result: anyhow::Result) { + let key = (group, server); + match result { + Ok(_) => { + self.chunk_errors.lock().unwrap().remove(&key); + } + Err(_) if self.ctx.stop.load(Ordering::Relaxed) => {} + Err(e) if e.downcast_ref::().is_some() => { + println!("{e}, leaving its day chunks to the other servers"); + self.skip.lock().unwrap().insert(key, None); + } + Err(e) => { + self.stats.lock().unwrap().error_count += 1; + let count = { + let mut errors = self.chunk_errors.lock().unwrap(); + let c = errors.entry(key.clone()).or_insert(0); + *c += 1; + *c + }; + ui::error(&format!("Indexing error ({}, day chunk on {}): {e}", key.0, self.ctx.pool.host(server))); + self.skip.lock().unwrap().insert(key, Some(Instant::now() + backoff(count))); + } + } + } + /// groups not parked fn active_groups(&self) -> Vec { let failed = self.failed.lock().unwrap(); @@ -398,10 +427,26 @@ impl Scheduler { /// A day chunk of any split group for an idle worker on `server`: the newest /// one pending, among the groups this server hasnt said it lacks. async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option<(String, i64)> { + // a server resting after a failure takes no chunks either + if !sched.ctx.pool.indexing_tier().contains(&server) { + return None; + } + let host = sched.ctx.pool.host(server); - let skip: Vec = - sched.skip.lock().unwrap().iter().filter(|(_, s)| *s == server).map(|(g, _)| g.clone()).collect(); - crate::indexer::claim_chunk(db, host, skip).await.ok().flatten() + let skip: Vec = { + let now = Instant::now(); + let mut skip = sched.skip.lock().unwrap(); + skip.retain(|_, until| until.is_none_or(|t| t > now)); + skip.keys().filter(|(_, s)| *s == server).map(|(g, _)| g.clone()).collect() + }; + + match crate::indexer::claim_chunk(db, host, skip).await { + Ok(chunk) => chunk, + Err(e) => { + ui::error(&format!("couldnt claim a day chunk: {e}")); + None + } + } } /// One worker on `server`: index whichever of its groups is due next, again and again. @@ -417,18 +462,8 @@ async fn worker(sched: Arc, server: usize, db: Db) { let stats = sched.stats.clone(); let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); let chunk = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &group, server, day, &mut progress); - match unless_stopped(&sched.ctx.stop, chunk).await { - None => break, - Some(Err(e)) if e.to_string().contains("isnt on") => { - sched.skip.lock().unwrap().insert((group, server)); - } - Some(Err(e)) => { - ui::error(&format!("Indexing error ({group}, day chunk): {e}")); - // the chunk went back, dont grab it again right away - nap(Duration::from_secs(1), || sched.stopping()).await; - } - Some(Ok(_)) => {} - } + let Some(result) = unless_stopped(&sched.ctx.stop, chunk).await else { break }; + sched.finish_chunk(group, server, result); continue; } nap(Duration::from_secs(1), || sched.stopping()).await; @@ -527,7 +562,8 @@ async fn run_servers( workers, next: Mutex::new(HashMap::new()), busy: Mutex::new(HashSet::new()), - skip: Mutex::new(HashSet::new()), + skip: Mutex::new(HashMap::new()), + chunk_errors: Mutex::new(HashMap::new()), wait_until: Mutex::new(HashMap::new()), errors: Mutex::new(HashMap::new()), failed: Mutex::new(HashMap::new()), diff --git a/src/indexer.rs b/src/indexer.rs index 5d273823..ad880dac 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -1,6 +1,7 @@ use std::collections::HashMap; use std::sync::atomic::AtomicBool; use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; use anyhow::{Result, anyhow}; use rusqlite::Connection; @@ -43,11 +44,13 @@ pub struct GroupRunState { pub phase: Phase, pub idle: bool, pub backfilling: bool, + /// a big group found unsplittable isnt probed again until then + pub no_split_until: Option, } impl Default for GroupRunState { fn default() -> Self { - GroupRunState { phase: Phase::Backfill, idle: false, backfilling: false } + GroupRunState { phase: Phase::Backfill, idle: false, backfilling: false, no_split_until: None } } } @@ -329,6 +332,9 @@ where } } +/// how long a big group that couldnt be split waits before it is probed again +const SPLIT_RECHECK: Duration = Duration::from_secs(3600); + /// Split `group`'s backfill into day chunks when its home server still has /// more than `split_min_backlog` article numbers to go and another indexing /// server carries it too. Chunks run from the day at the home cursor back to @@ -349,39 +355,69 @@ async fn maybe_split( if (cursor.saturating_sub(first) as i64) < settings.split_min_backlog { return Ok(false); } + if ctx.states.with(group, |st| st.no_split_until.is_some_and(|t| Instant::now() < t)) { + return Ok(false); + } - // the newest day still to do: the post date at the home cursor - let newest_day = match ctx.pool.posted_date(home, group, cursor).await? { - Some(t) => crate::chunks::unix_day(t), - None => return Ok(false), + let Some((newest_day, oldest_day, carriers)) = split_days(ctx, group, home, first, cursor).await? else { + ctx.states.with(group, |st| st.no_split_until = Some(Instant::now() + SPLIT_RECHECK)); + return Ok(false); }; - // the oldest day any other carrying server has - let mut oldest_day = newest_day; + let g = group.to_string(); + let added = on_db(db, move |conn| Ok(crate::chunks::add(conn, &g, newest_day, oldest_day)?)).await?; + println!("[SPLIT] {group}: backfill split into {added} day chunks over {carriers} servers"); + Ok(true) +} + +/// The days a split of `group` covers, (newest, oldest), and how many servers +/// carry it. None when it cant split: home's dates at either end are unknown +/// or no other indexing server carries the group. +async fn split_days( + ctx: &PassContext, + group: &str, + home: usize, + first: u64, + cursor: u64, +) -> Result> { + use crate::chunks::unix_day; + + // the newest day still to do is the post date at the home cursor, the + // oldest at least home's first article + let Some(newest) = ctx.pool.posted_date(home, group, cursor).await? else { return Ok(None) }; + let Some(oldest) = ctx.pool.posted_date(home, group, first).await? else { return Ok(None) }; + let newest_day = unix_day(newest); + let mut oldest_day = unix_day(oldest).min(newest_day); + + // other servers are best effort: one that fails is left out. one that + // carries the group counts, its oldest date only if it has one let mut carriers = 1; for other in ctx.pool.indexing_servers().into_iter().filter(|&s| s != home) { - let Ok((s, (_, low, _, _))) = ctx.pool.select_group_on(other, group).await else { continue }; - if s != other { - continue; - } - if let Some(t) = ctx.pool.posted_date(other, group, low).await? { - carriers += 1; - oldest_day = oldest_day.min(crate::chunks::unix_day(t)); + let Ok((_, low, _, _)) = ctx.pool.group_on(other, group).await else { continue }; + carriers += 1; + if let Ok(Some(t)) = ctx.pool.posted_date(other, group, low).await { + oldest_day = oldest_day.min(unix_day(t)); } } - if let Some(t) = ctx.pool.posted_date(home, group, first).await? { - oldest_day = oldest_day.min(crate::chunks::unix_day(t)); - } - if carriers < 2 { - return Ok(false); - } - let g = group.to_string(); - let added = on_db(db, move |conn| Ok(crate::chunks::add(conn, &g, newest_day, oldest_day)?)).await?; - println!("[SPLIT] {group}: backfill split into {added} day chunks over {carriers} servers"); - Ok(true) + Ok((carriers >= 2).then_some((newest_day, oldest_day, carriers))) +} + +/// A day chunk's server doesnt carry its group (GROUP answered 411). +#[derive(Debug)] +pub struct NotCarried { + pub group: String, + pub host: String, +} + +impl std::fmt::Display for NotCarried { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} isnt on {}", self.group, self.host) + } } +impl std::error::Error for NotCarried {} + /// Claim the newest chunk of any split group for `host`, except `skip`. pub async fn claim_chunk(db: &Db, host: String, skip: Vec) -> Result> { on_db(db, move |conn| { @@ -416,11 +452,15 @@ where on_db(db, move |conn| Ok(crate::chunks::release(conn, &g, day)?)) }; - let found = match ctx.pool.select_group_on(server, group).await { - Ok((s, info)) if s == server => info, - Ok(_) | Err(_) => { + // GROUP on this server alone: falling over would move where the group lives + let found = match ctx.pool.group_on(server, group).await { + Ok(info) => info, + Err(e) => { release().await?; - return Err(anyhow!("{group} isnt on {}", ctx.pool.host(server))); + if e.code() == Some(411) { + return Err(NotCarried { group: group.to_string(), host: ctx.pool.host(server) }.into()); + } + return Err(e.into()); } }; let (_count, first, last, _name) = found; diff --git a/src/nntp.rs b/src/nntp.rs index 2d0628a4..f2ca2367 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1116,6 +1116,12 @@ impl Pool { lease.check(r) } + /// GROUP on server `i` alone, for probing a server: no falling over to + /// another server, soo where the group lives stays as it is. + pub async fn group_on(&self, i: usize, group: &str) -> Result<(u64, u64, u64, String)> { + self.select_on(i, group).await + } + /// GROUP on the active server, falling over to the next server that carries it /// (which then becomes the active one). pub async fn select_group(&self, group: &str) -> Result<(u64, u64, u64, String)> { diff --git a/tests/split_backfill.rs b/tests/split_backfill.rs index 6d43c077..b8371fc9 100644 --- a/tests/split_backfill.rs +++ b/tests/split_backfill.rs @@ -39,8 +39,14 @@ fn a_split_group_is_shared_by_both_servers() { std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); } - let a = Server::new(posts(1)); - let b = Server::new(posts(500_001)); + // a little delay per request soo a chunk takes long enough for the other + // server's idle worker to wake up and take some + let slow = |mut s: Arc| { + Arc::get_mut(&mut s).unwrap().xover_delay = Duration::from_millis(10); + s + }; + let a = slow(Server::new(posts(1))); + let b = slow(Server::new(posts(500_001))); let (pa, pb) = (spawn_server(a.clone()), spawn_server(b.clone())); let config = serde_json::json!({ "usenet_servers": [ @@ -81,5 +87,7 @@ fn a_split_group_is_shared_by_both_servers() { let conn = atlas::db::open_with_shards(&main).unwrap(); assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once, overlaps deduplicated"); - assert!(a.xovers.load(Ordering::SeqCst) > 0 && b.xovers.load(Ordering::SeqCst) > 0, "both servers worked"); + let servers: i64 = + conn.query_row("select count(distinct server) from backfill_chunks where state = 2", [], |r| r.get(0)).unwrap(); + assert_eq!(servers, 2, "both servers indexed day chunks"); } diff --git a/tests/split_homes.rs b/tests/split_homes.rs new file mode 100644 index 00000000..c2af3649 --- /dev/null +++ b/tests/split_homes.rs @@ -0,0 +1,118 @@ +//! A split group with a third indexing server that doesnt carry it: probing +//! that server for the split and its idle worker trying day chunks must not +//! move the group off its home (one set of cursors), and every chunk is done +//! by the two servers that carry it. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{Server, post_at, spawn_server}; + +/// the mock always carries common::GROUP, this one only with `any_group`. +/// its home is localhost, and GROUP on 127.1 falling over would pick +/// 127.0.0.1 (see Pool::pick_server_in and Pool::ranked), soo a probe that +/// falls over moves the group and leaves a second set of cursors +const SPLIT_GROUP: &str = "alt.binaries.split"; + +/// 40 posts a day for 30 days, numbered from `offset` +fn posts(offset: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (0..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn a_server_without_the_group_doesnt_move_it() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + let carrier = |offset| { + let mut s = Server::new(posts(offset)); + let m = Arc::get_mut(&mut s).unwrap(); + m.any_group = true; + m.xover_delay = Duration::from_millis(10); + s + }; + let (a, b) = (carrier(1), carrier(500_001)); + // answers 411 for SPLIT_GROUP + let c = Server::new(posts(900_001)); + let (pa, pb, pc) = (spawn_server(a), spawn_server(b), spawn_server(c)); + // three host names for 127.0.0.1, soo cursors and chunk claims tell the servers apart + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pa, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": pb, "ssl": false, "connections": 4, "priority": 1}, + {"host": "127.1", "username": "bob", "password": "secret", "port": pc, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [SPLIT_GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 500 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(120); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, SPLIT_GROUP).unwrap_or((0, 0)); + if total > 0 && done == total && articles >= 1200 { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); + + let cursors: Vec = conn + .prepare("select name from groups where name like ? order by name") + .unwrap() + .query_map([format!("{SPLIT_GROUP}%")], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(cursors.len(), 1, "the group stayed on one home server: {cursors:?}"); + + let chunk_servers: Vec = conn + .prepare("select distinct server from backfill_chunks where state = 2 order by server") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap(); + assert_eq!(chunk_servers, vec!["127.0.0.1".to_string(), "localhost".to_string()], "only the carriers did chunks"); +} From c60947e814ab20a6ccc9acb680657c3de5e8ba71 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:18:39 -0500 Subject: [PATCH 012/159] Backfill page shows day chunk progress of split groups Co-Authored-By: Claude Haiku 4.5 --- src/stats_dashboard.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/stats_dashboard.rs b/src/stats_dashboard.rs index af243517..8417a32d 100644 --- a/src/stats_dashboard.rs +++ b/src/stats_dashboard.rs @@ -83,6 +83,8 @@ struct Quick { releases_approx: i64, db_bytes: u64, wal_bytes: u64, + /// (group, done, total) for split groups' day chunks + chunks: Vec<(String, i64, i64)>, } fn load_quick() -> Quick { @@ -101,6 +103,11 @@ fn load_quick() -> Quick { q.progress = db::group_progress(&conn).unwrap_or_default(); // running totals the shards keep, instant (q.releases_approx, q.articles_approx) = crate::store::totals(&conn).unwrap_or_default(); + q.chunks = crate::chunks::split_groups(&conn) + .unwrap_or_default() + .into_iter() + .filter_map(|g| crate::chunks::progress(&conn, &g).ok().map(|(d, t)| (g, d, t))) + .collect(); q } @@ -778,6 +785,10 @@ fn draw_backfill(f: &mut Frame, app: &App, area: Rect) { note("counts are article numbers, gaps on the server included"), ]; let mut progress = progress; + if !quick.chunks.is_empty() { + let (done, total) = quick.chunks.iter().fold((0, 0), |(d, t), c| (d + c.1, t + c.2)); + progress.push(kv("split groups", format!("{}, day chunks {done} of {total} done", quick.chunks.len()))); + } if b.unmeasured > 0 { progress.push(note(&format!("{} groups get their range on their next pass", count(b.unmeasured as i64)))); } @@ -1378,7 +1389,10 @@ mod tests { "limit": 10, "connections": 10, "headers": 900, "wire_bytes": 100, "text_bytes": 400}] }), status: serde_json::json!({"running": false}), - quick: Arc::new(Mutex::new(Quick::default())), + quick: Arc::new(Mutex::new(Quick { + chunks: vec![("alt.binaries.x".into(), 3, 10)], + ..Quick::default() + })), content: Arc::new(Mutex::new(ContentState { data: Some(Content { releases: 10, @@ -1407,6 +1421,7 @@ mod tests { assert!(text.contains(name), "page {page}"); match page { 0 => assert!(text.contains("headers/s")), + 1 => assert!(text.contains("day chunks 3 of 10 done")), 2 => assert!( text.contains(".mkv") && text.contains("NZBs available 9 (90.0%)") From 700a2afa36a5cd370abf19a647a1158c6d05af7e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:22:29 -0500 Subject: [PATCH 013/159] Fix: use aggregate query for split group chunk stats instead of N+1 Replace split_groups() + per-group progress() calls with one SELECT that aggregates all backfill_chunks data in a single scan. Store stats as tuple (groups, splitting, done, total, done_last_hour) to avoid per-group allocations. Draw shows: "split groups: N (M in progress), day chunks D of T done, L in the last hour". Add test verifying aggregate query on in-memory db. Co-Authored-By: Claude Haiku 4.5 --- src/stats_dashboard.rs | 69 +++++++++++++++++++++++++++++++++--------- 1 file changed, 55 insertions(+), 14 deletions(-) diff --git a/src/stats_dashboard.rs b/src/stats_dashboard.rs index 8417a32d..87929b05 100644 --- a/src/stats_dashboard.rs +++ b/src/stats_dashboard.rs @@ -83,8 +83,19 @@ struct Quick { releases_approx: i64, db_bytes: u64, wal_bytes: u64, - /// (group, done, total) for split groups' day chunks - chunks: Vec<(String, i64, i64)>, + /// split group stats: (groups, splitting, done, total, done_last_hour) + chunks: (i64, i64, i64, i64, i64), +} + +fn load_chunks_stats(conn: &rusqlite::Connection) -> (i64, i64, i64, i64, i64) { + let now = + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); + let hour_ago = now - 3600; + let sql = "select count(*), coalesce(sum(pending > 0), 0), coalesce(sum(done), 0), coalesce(sum(total), 0), \ + coalesce(sum(recent), 0) + from (select grp, sum(state != 2) as pending, sum(state = 2) as done, count(*) as total, \ + sum(state = 2 and claimed_at > ?) as recent from backfill_chunks group by grp)"; + conn.query_row(sql, [hour_ago], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))).unwrap_or_default() } fn load_quick() -> Quick { @@ -103,11 +114,7 @@ fn load_quick() -> Quick { q.progress = db::group_progress(&conn).unwrap_or_default(); // running totals the shards keep, instant (q.releases_approx, q.articles_approx) = crate::store::totals(&conn).unwrap_or_default(); - q.chunks = crate::chunks::split_groups(&conn) - .unwrap_or_default() - .into_iter() - .filter_map(|g| crate::chunks::progress(&conn, &g).ok().map(|(d, t)| (g, d, t))) - .collect(); + q.chunks = load_chunks_stats(&conn); q } @@ -785,9 +792,19 @@ fn draw_backfill(f: &mut Frame, app: &App, area: Rect) { note("counts are article numbers, gaps on the server included"), ]; let mut progress = progress; - if !quick.chunks.is_empty() { - let (done, total) = quick.chunks.iter().fold((0, 0), |(d, t), c| (d + c.1, t + c.2)); - progress.push(kv("split groups", format!("{}, day chunks {done} of {total} done", quick.chunks.len()))); + let (groups, splitting, done, total, done_last_hour) = quick.chunks; + if groups > 0 { + progress.push(kv( + "split groups", + format!( + "{} ({} in progress), day chunks {} of {} done, {} in the last hour", + groups, + splitting, + count(done), + count(total), + count(done_last_hour) + ), + )); } if b.unmeasured > 0 { progress.push(note(&format!("{} groups get their range on their next pass", count(b.unmeasured as i64)))); @@ -1389,10 +1406,7 @@ mod tests { "limit": 10, "connections": 10, "headers": 900, "wire_bytes": 100, "text_bytes": 400}] }), status: serde_json::json!({"running": false}), - quick: Arc::new(Mutex::new(Quick { - chunks: vec![("alt.binaries.x".into(), 3, 10)], - ..Quick::default() - })), + quick: Arc::new(Mutex::new(Quick { chunks: (1, 0, 3, 10, 0), ..Quick::default() })), content: Arc::new(Mutex::new(ContentState { data: Some(Content { releases: 10, @@ -1432,4 +1446,31 @@ mod tests { } } } + + #[test] + fn chunks_stats_aggregation() { + use rusqlite::Connection; + let conn = Connection::open_in_memory().unwrap(); + crate::chunks::create(&conn).unwrap(); + let now = + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); + + // g1: finish 3 chunks (all done) + crate::chunks::add(&conn, "g1", 100, 98).unwrap(); + conn.execute("update backfill_chunks set state = 2 where grp = 'g1'", []).unwrap(); + // g2: finish 1 recently (with recent claimed_at), claim 1 recently (2 chunks total, 1 done, 1 in progress) + crate::chunks::add(&conn, "g2", 200, 199).unwrap(); + conn.execute("update backfill_chunks set state = 2, claimed_at = ? where grp = 'g2' and day = 200", [now]) + .unwrap(); + conn.execute("update backfill_chunks set state = 1, claimed_at = ? where grp = 'g2' and day = 199", [now]) + .unwrap(); + + // 2 groups, 1 in progress (g2 has pending), 4 done total, 5 total, 1 done in last hour + let (groups, splitting, done, total, done_last_hour) = load_chunks_stats(&conn); + assert_eq!(groups, 2); + assert_eq!(splitting, 1); // 1 group with pending > 0 (g2) + assert_eq!(done, 4); // g1 has 3 done, g2 has 1 done + assert_eq!(total, 5); // 3 chunks for g1, 2 chunks for g2 + assert_eq!(done_last_hour, 1); // 1 chunk in g2 finished recently (claimed_at is recent) + } } From e668f5b57625d8df8db21ab1326c494e58890304 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:24:40 -0500 Subject: [PATCH 014/159] Pack message-id locals by alphabet Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 180 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 173 insertions(+), 7 deletions(-) diff --git a/src/store.rs b/src/store.rs index be441cce..f915e587 100644 --- a/src/store.rs +++ b/src/store.rs @@ -210,6 +210,64 @@ const TEXT: u8 = 0; const HEX_LOWER: u8 = 1; const HEX_UPPER: u8 = 2; +const DIGITS: u8 = 3; +const BASE36_LOWER: u8 = 4; +const BASE36_UPPER: u8 = 5; +const BASE62: u8 = 6; +const BASE64_URL: u8 = 7; + +/// the alphabet of each packed tag, by digit value +fn alphabet(tag: u8) -> &'static [u8] { + match tag { + DIGITS => b"0123456789", + BASE36_LOWER => b"0123456789abcdefghijklmnopqrstuvwxyz", + BASE36_UPPER => b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", + BASE62 => b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", + BASE64_URL => b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_", + _ => b"", + } +} + +/// big-endian base-256 bytes of a base-`n` number given as digit values +fn to_bytes(digits: &[u8], n: u32) -> Vec { + let mut out: Vec = Vec::new(); // little endian while building + for &d in digits { + let mut carry = u32::from(d); + for b in out.iter_mut() { + let v = u32::from(*b) * n + carry; + *b = (v & 0xff) as u8; + carry = v >> 8; + } + while carry > 0 { + out.push((carry & 0xff) as u8); + carry >>= 8; + } + } + out.reverse(); + out +} + +/// `len` base-`n` digit values of a big-endian base-256 number +fn from_bytes(bytes: &[u8], n: u32, len: usize) -> Vec { + let mut num: Vec = bytes.to_vec(); + let mut digits = Vec::with_capacity(len); + for _ in 0..len { + let mut rem = 0u32; + for b in num.iter_mut() { + let v = (rem << 8) | u32::from(*b); + *b = (v / n) as u8; + rem = v % n; + } + digits.push(rem as u8); + } + digits.reverse(); + digits +} + +/// Packs a message-id's local part by its shape: hex at half the size +/// (tags 1, 2), other single-alphabet ids as a base-N number (tags 3-7, +/// then `[len]`), anything else as text (tag 0). Deterministic, and +/// `unpack_local` gives back exactly the same string. pub(crate) fn pack_local(local: &str) -> Vec { let bytes = local.as_bytes(); let even = !bytes.is_empty() && bytes.len().is_multiple_of(2); @@ -220,23 +278,49 @@ pub(crate) fn pack_local(local: &str) -> Vec { let mut out = Vec::with_capacity(1 + bytes.len() / 2); out.push(if lower { HEX_LOWER } else { HEX_UPPER }); out.extend(bytes.chunks(2).map(|p| (nibble(p[0]) << 4) | nibble(p[1]))); - out - } else { - let mut out = Vec::with_capacity(1 + bytes.len()); - out.push(TEXT); - out.extend_from_slice(bytes); - out + return out; } + if (1..=255).contains(&bytes.len()) { + for tag in [DIGITS, BASE36_LOWER, BASE36_UPPER, BASE62, BASE64_URL] { + let abc = alphabet(tag); + let values: Option> = + bytes.iter().map(|b| abc.iter().position(|a| a == b).map(|p| p as u8)).collect(); + if let Some(values) = values { + let mut out = vec![tag, bytes.len() as u8]; + out.extend(to_bytes(&values, abc.len() as u32)); + return out; + } + } + } + let mut out = Vec::with_capacity(1 + bytes.len()); + out.push(TEXT); + out.extend_from_slice(bytes); + out } -fn unpack_local(blob: &[u8]) -> String { +/// A local part back from any of the packings (tags 0-7). +pub(crate) fn unpack_local(blob: &[u8]) -> String { match blob.first() { Some(&HEX_LOWER) => blob[1..].iter().map(|b| format!("{b:02x}")).collect(), Some(&HEX_UPPER) => blob[1..].iter().map(|b| format!("{b:02X}")).collect(), + Some(&tag) if (DIGITS..=BASE64_URL).contains(&tag) && blob.len() >= 2 => { + let abc = alphabet(tag); + from_bytes(&blob[2..], abc.len() as u32, blob[1] as usize) + .iter() + .map(|&d| abc[d as usize] as char) + .collect() + } _ => String::from_utf8_lossy(blob.get(1..).unwrap_or_default()).into_owned(), } } +/// a local packed the current way, whatever way it was packed before +// not called yet: compact uses it to rewrite old rows +#[allow(dead_code)] +pub(crate) fn repack(local: &[u8]) -> Vec { + pack_local(&unpack_local(local)) +} + /// `` -> (local, "@domain>"); anything else stays whole pub(crate) fn split_message_id(id: &str) -> Option<(&str, &str)> { let inner = id.strip_prefix('<')?; @@ -431,6 +515,17 @@ pub(crate) fn add_segment(conn: &Connection, domains: &mut Domains, file_id: i64 return Ok(false); } } + // a row from before locals were packed by alphabet has the same local stored as text + if (DIGITS..=BASE64_URL).contains(&local[0]) { + let mut legacy = vec![TEXT]; + legacy.extend_from_slice(unpack_local(&local).as_bytes()); + let stored_legacy = conn + .prepare_cached("select 1 from segments where file_id = ? and local = ? and domain = ?")? + .exists(params![file_id, legacy, domain])?; + if stored_legacy { + return Ok(false); + } + } let added = conn .prepare_cached("insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)")? .execute(params![file_id, local, domain, a.part, a.bytes])?; @@ -700,6 +795,51 @@ mod tests { assert_eq!(pack_local("1064b678f3f54e28a5afd48a3a986076").len(), 17, "hex is stored at half the size"); } + #[test] + fn locals_pack_by_shape_and_come_back_exactly() { + let cases = [ + ("1064b678f3f54e28a5afd48a3a986076", 1u8), // ngPost hex + ("ABCDEF0123", 2), + ("0001234", 3), // digits (odd length, so not hex), leading zeros kept + ("0abc9xyz", 4), + ("0ABC9XYZ", 5), + ("hotfTpetaZRIbOYuTuQ31", 6), // JBinUp + ("DR59tDkIGMDKQS1YflogRq2MTqVgoHslO", 6), + ("ZjPsQyLgOjNtQvXbHeKaXyCm1730295651235", 6), // Nyuu: letters + ms timestamp + ("a-b_c-9", 7), + ("abc", 4), // odd length hex-looking goes base36 + ("nnd$009a5634$43be2fd7", 0), // anything else stays text + ("", 0), + ]; + for (local, tag) in cases { + let packed = pack_local(local); + assert_eq!(packed[0], tag, "{local}"); + assert_eq!(unpack_local(&packed), local, "{local}"); + assert_eq!(pack_local(local), packed, "deterministic: {local}"); + } + let long = "z".repeat(300); // not "a": that would be hex + assert_eq!(pack_local(&long)[0], 0, "longer than 255 stays text"); + assert_eq!(pack_local("ZjPsQyLgOjNtQvXbHeKaXyCm1730295651235").len(), 30, "base62 is smaller than text (38)"); + } + + #[test] + fn old_packings_still_decode_and_repack_to_the_current_one() { + // text and hex from before tags 3-7 keep their meaning + assert_eq!(unpack_local(&[TEXT, b'h', b'i']), "hi"); + assert_eq!(unpack_local(&[HEX_LOWER, 0xab, 0x01]), "ab01"); + assert_eq!(unpack_local(&[HEX_UPPER, 0xab, 0x01]), "AB01"); + let old_text = [&[TEXT][..], b"hotfTpetaZRIbOYuTuQ31"].concat(); + let current = pack_local("hotfTpetaZRIbOYuTuQ31"); + assert_eq!(repack(&old_text), current); + assert_eq!(repack(¤t), current, "repacking is stable"); + assert_eq!(repack(&[HEX_LOWER, 0xab]), vec![HEX_LOWER, 0xab]); + // the longest ids still round-trip + let max = "z".repeat(255); + assert_eq!(unpack_local(&pack_local(&max)), max); + let max64 = format!("{}-", "Z".repeat(254)); + assert_eq!(unpack_local(&pack_local(&max64)), max64); + } + #[test] fn only_shared_domains_get_rows_and_nothing_is_saved_twice() { let dir = tempfile::tempdir().unwrap(); @@ -733,6 +873,32 @@ mod tests { assert!(!add_segment(&conn, &mut fresh, file.id, &article).unwrap(), "same article again: not saved twice"); let segments: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); assert_eq!(segments, 1); + + // the same for a row saved as text before locals were packed by alphabet + let legacy = Article { + message_id: "".to_string(), + part: Some(1), + ..Default::default() + }; + let (_, domain) = { + let mut shared = Domains::default(); + let mut last = (Vec::new(), 0); + for n in 0..SHARED_AFTER { + last = shared.encode(&conn, &format!("<{n:032x}@JBinUp.local>")).unwrap(); + } + last + }; + assert!(domain > 0); + let mut stored = vec![0u8]; + stored.extend_from_slice(b"hotfTpetaZRIbOYuTuQ31"); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, 1, 0)", + params![file.id, stored, domain], + ) + .unwrap(); + assert!(!add_segment(&conn, &mut Domains::default(), file.id, &legacy).unwrap(), "legacy text row found"); + let segments: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(segments, 2); } #[test] From 1fd874f443247f711fb75d74321d4e2fb95a6dcc Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:28:07 -0500 Subject: [PATCH 015/159] Compressed per-file segment blob codec Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 43 ++++++++++++- Cargo.toml | 1 + src/blob.rs | 171 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + 4 files changed, 215 insertions(+), 1 deletion(-) create mode 100644 src/blob.rs diff --git a/Cargo.lock b/Cargo.lock index 357654da..4e076219 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "adler2" @@ -234,6 +234,7 @@ dependencies = [ "ureq", "webbrowser", "webpki-roots", + "zstd", ] [[package]] @@ -382,6 +383,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" dependencies = [ "find-msvc-tools", + "jobserver", + "libc", "shlex", ] @@ -1370,6 +1373,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + [[package]] name = "js-sys" version = "0.3.106" @@ -3882,6 +3895,34 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zstd" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882" +dependencies = [ + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.1.0+zstd.1.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +dependencies = [ + "cc", + "pkg-config", +] + [[package]] name = "zvariant" version = "4.2.0" diff --git a/Cargo.toml b/Cargo.toml index fc7760a0..8c75a32d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ unicode-width = "0.2" ureq = { version = "3", default-features = false, features = ["json", "rustls"] } webbrowser = "1" webpki-roots = "1" +zstd = "0.13" [target.'cfg(unix)'.dependencies] signal-hook = "0.4" diff --git a/src/blob.rs b/src/blob.rs new file mode 100644 index 00000000..457d3675 --- /dev/null +++ b/src/blob.rs @@ -0,0 +1,171 @@ +//! A sealed file's articles in one compressed value (files.blob), see the +//! storage spec. Format v1, zstd compressed: +//! u8 version, varint count, then per segment: varint part+1 (0 = none), +//! zigzag varint bytes minus the previous segment's, varint domain, varint +//! local length, local bytes. + +use std::io::{Error, ErrorKind, Result}; + +const VERSION: u8 = 1; +const LEVEL: i32 = 6; + +/// One article of a sealed file. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Seg { + pub part: Option, + pub bytes: i64, + pub domain: i64, + pub local: Vec, +} + +fn put_varint(out: &mut Vec, mut v: u64) { + while v >= 0x80 { + out.push((v as u8) | 0x80); + v >>= 7; + } + out.push(v as u8); +} + +fn cut_short() -> Error { + Error::new(ErrorKind::UnexpectedEof, "blob cut short") +} + +fn get_varint(buf: &[u8], pos: &mut usize) -> Result { + let mut v = 0u64; + for shift in (0..64).step_by(7) { + let b = *buf.get(*pos).ok_or_else(cut_short)?; + *pos += 1; + v |= u64::from(b & 0x7f) << shift; + if b & 0x80 == 0 { + return Ok(v); + } + } + Err(Error::new(ErrorKind::InvalidData, "varint too long")) +} + +fn zigzag(v: i64) -> u64 { + ((v << 1) ^ (v >> 63)) as u64 +} + +fn unzigzag(v: u64) -> i64 { + ((v >> 1) as i64) ^ -((v & 1) as i64) +} + +/// Packs segments into a blob. Order is not kept, a copy is sorted by part +/// (whole file articles last) so neighbours compress well. +pub fn encode(segs: &[Seg]) -> Vec { + let mut sorted: Vec<&Seg> = segs.iter().collect(); + sorted.sort_by(|a, b| (a.part.is_some(), a.part, &a.local).cmp(&(b.part.is_some(), b.part, &b.local))); + let mut raw = vec![VERSION]; + put_varint(&mut raw, sorted.len() as u64); + let mut prev_bytes = 0i64; + for s in sorted { + put_varint(&mut raw, s.part.map_or(0, |p| p as u64 + 1)); + put_varint(&mut raw, zigzag(s.bytes.wrapping_sub(prev_bytes))); + prev_bytes = s.bytes; + put_varint(&mut raw, s.domain as u64); + put_varint(&mut raw, s.local.len() as u64); + raw.extend_from_slice(&s.local); + } + zstd::bulk::compress(&raw, LEVEL).expect("zstd compress of an in memory buffer") +} + +/// Unpacks a blob made by `encode`. Truncated or corrupt input is an error. +pub fn decode(blob: &[u8]) -> Result> { + let raw = zstd::stream::decode_all(blob)?; + if raw.first() != Some(&VERSION) { + return Err(Error::new(ErrorKind::InvalidData, "unknown blob version")); + } + let mut pos = 1; + let count = get_varint(&raw, &mut pos)? as usize; + // every segment takes at least 4 bytes, so a bigger count is corrupt + let mut segs = Vec::with_capacity(count.min(raw.len() / 4)); + let mut prev_bytes = 0i64; + for _ in 0..count { + let part = match get_varint(&raw, &mut pos)? { + 0 => None, + p => Some((p - 1) as i64), + }; + let bytes = prev_bytes.wrapping_add(unzigzag(get_varint(&raw, &mut pos)?)); + prev_bytes = bytes; + let domain = get_varint(&raw, &mut pos)? as i64; + let len = usize::try_from(get_varint(&raw, &mut pos)?).map_err(|_| cut_short())?; + let end = pos.checked_add(len).ok_or_else(cut_short)?; + let local = raw.get(pos..end).ok_or_else(cut_short)?.to_vec(); + pos = end; + segs.push(Seg { part, bytes, domain, local }); + } + Ok(segs) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn seg(part: Option, bytes: i64, domain: i64, local: &[u8]) -> Seg { + Seg { part, bytes, domain, local: local.to_vec() } + } + + #[test] + fn segments_come_back_exactly() { + let segs = vec![ + seg(Some(2), 750_000, 3, b"\x06\x05abc"), + seg(Some(1), 750_123, 3, b"\x01\xde\xad"), + seg(None, 0, 0, b"\x00"), + seg(Some(3), 12, 9, b""), + ]; + let mut back = decode(&encode(&segs)).unwrap(); + let mut want = segs.clone(); + back.sort_by(|a, b| (a.part, &a.local).cmp(&(b.part, &b.local))); + want.sort_by(|a, b| (a.part, &a.local).cmp(&(b.part, &b.local))); + assert_eq!(back, want); + assert!(decode(&encode(&[])).unwrap().is_empty()); + } + + #[test] + fn a_big_file_is_small() { + let segs: Vec = (1..=1000) + .map(|p| { + seg( + Some(p), + 768_000, + 1, + &[1, (p % 251) as u8, (p * 7 % 251) as u8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], + ) + }) + .collect(); + let size = encode(&segs).len(); + assert!(size < 1000 * 20, "{size} bytes for 1000 segments"); + } + + #[test] + fn garbage_is_an_error() { + assert!(decode(b"not zstd").is_err()); + } + + #[test] + fn truncated_or_corrupt_input_is_an_error() { + let segs: Vec = (1..=50).map(|p| seg(Some(p), 1000 + p, 2, b"\x01abcdef")).collect(); + let blob = encode(&segs); + for cut in 0..blob.len() { + assert!(decode(&blob[..cut]).is_err(), "cut at {cut}"); + } + // valid zstd around a payload that lies about its contents + for raw in [ + &[2u8, 0][..], // unknown version + &[1u8][..], // no count + &[1, 5][..], // count with no segments + &[1, 1, 1, 0, 0, 200][..], // local longer than the data + &[1, 1, 1, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01][..], // length near u64::MAX + &[1, 1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01][..], // varint too long + ] { + assert!(decode(&zstd::bulk::compress(raw, 1).unwrap()).is_err(), "{raw:?}"); + } + } + + #[test] + fn extreme_values_survive() { + let segs = vec![seg(Some(0), i64::MAX, i64::MAX, b"a"), seg(Some(1), 0, 0, b"b"), seg(Some(2), -5, 1, b"c")]; + assert_eq!(decode(&encode(&segs)).unwrap(), segs); + } +} diff --git a/src/lib.rs b/src/lib.rs index 024c889e..bfac527e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod api; pub mod app; pub mod atomic; pub mod bg_indexer; +pub mod blob; pub mod chunks; pub mod compact; pub mod config; From 358e267b476091c5ed23c2741b565f1cf066c758 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:29:04 -0500 Subject: [PATCH 016/159] Fix blob encode doc: whole file articles sort first Co-Authored-By: Claude Opus 5.5 --- src/blob.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/blob.rs b/src/blob.rs index 457d3675..f5331f23 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -52,7 +52,7 @@ fn unzigzag(v: u64) -> i64 { } /// Packs segments into a blob. Order is not kept, a copy is sorted by part -/// (whole file articles last) so neighbours compress well. +/// (whole file articles first) so neighbours compress well. pub fn encode(segs: &[Seg]) -> Vec { let mut sorted: Vec<&Seg> = segs.iter().collect(); sorted.sort_by(|a, b| (a.part.is_some(), a.part, &a.local).cmp(&(b.part.is_some(), b.part, &b.local))); From e4f9edd5460019d016139a0f03ca767e333d117c Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:33:54 -0500 Subject: [PATCH 017/159] Seal a file's articles into one blob; reads and late articles see it Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 468 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 443 insertions(+), 25 deletions(-) diff --git a/src/store.rs b/src/store.rs index f915e587..68936326 100644 --- a/src/store.rs +++ b/src/store.rs @@ -16,7 +16,8 @@ //! ordering by id is still newest first across shards, and an id says which //! shard holds it. -use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::time::Instant; @@ -144,7 +145,9 @@ pub fn create_shard(path: &Path) -> Result<()> { subject_mid TEXT, expected INTEGER, file_total INTEGER, - seen BLOB NOT NULL + seen BLOB NOT NULL, + blob BLOB, + touched_at INTEGER ); create unique index if not exists files_key on files(release_id, filename); @@ -162,7 +165,22 @@ pub fn create_shard(path: &Path) -> Result<()> { create table if not exists meta (key TEXT PRIMARY KEY, value INTEGER); insert or ignore into meta (key, value) values ('releases', 0), ('articles', 0); ", - ) + )?; + migrate_shard(&conn) +} + +/// Columns a shard made before sealing lacks: `files.blob` (a sealed file's +/// articles) and `files.touched_at` (when articles were last added). Adding +/// a nullable column doesnt rewrite the table. +pub fn migrate_shard(conn: &Connection) -> Result<()> { + let cols: Vec = + conn.prepare("pragma table_info(files)")?.query_map([], |r| r.get(1))?.collect::>()?; + for (col, kind) in [("blob", "BLOB"), ("touched_at", "INTEGER")] { + if !cols.iter().any(|c| c == col) { + conn.execute(&format!("alter table files add column {col} {kind}"), [])?; + } + } + Ok(()) } // ---------------------------------------------------------------- ids @@ -441,6 +459,8 @@ pub(crate) struct FileState { pub expected: Option, pub file_total: Option, pub seen: Vec, + /// its articles are in `files.blob` (plus any rows that came later) + pub sealed: bool, } impl FileState { @@ -471,7 +491,7 @@ impl FileState { pub(crate) fn file(conn: &Connection, release_id: i64, filename: &str) -> Result { let found = conn .prepare_cached( - "select id, subject, subject_part, subject_mid, expected, file_total, seen from files + "select id, subject, subject_part, subject_mid, expected, file_total, seen, blob is not null from files where release_id = ? and filename = ?", )? .query_row(params![release_id, filename], |r| { @@ -483,6 +503,7 @@ pub(crate) fn file(conn: &Connection, release_id: i64, filename: &str) -> Result expected: r.get(4)?, file_total: r.get(5)?, seen: r.get(6)?, + sealed: r.get(7)?, }) }) .optional()?; @@ -496,39 +517,47 @@ pub(crate) fn file(conn: &Connection, release_id: i64, filename: &str) -> Result pub(crate) fn put_file(conn: &Connection, f: &FileState) -> Result<()> { conn.prepare_cached( - "update files set subject = ?, subject_part = ?, subject_mid = ?, expected = ?, file_total = ?, seen = ? - where id = ?", + "update files set subject = ?, subject_part = ?, subject_mid = ?, expected = ?, file_total = ?, seen = ?, + touched_at = unixepoch() where id = ?", )? .execute(params![f.subject, f.subject_part, f.subject_mid, f.expected, f.file_total, f.seen, f.id])?; Ok(()) } -/// Add one article to a file; false when it was already there. -pub(crate) fn add_segment(conn: &Connection, domains: &mut Domains, file_id: i64, a: &Article) -> Result { +/// Add one article to a file; false when it was already there, as a row or +/// in the file's sealed blob. +pub(crate) fn add_segment( + conn: &Connection, + domains: &mut Domains, + f: &FileState, + a: &Article, + sealed: &mut SealedCache, +) -> Result { let (local, domain) = domains.encode(conn, &a.message_id)?; + let stored = |sealed: &mut SealedCache, local: &[u8], domain: i64| -> Result { + let row = conn + .prepare_cached("select 1 from segments where file_id = ? and local = ? and domain = ?")? + .exists(params![f.id, local, domain])?; + Ok(row || (f.sealed && sealed.contains(conn, f.id, local, domain)?)) + }; + if f.sealed && sealed.contains(conn, f.id, &local, domain)? { + return Ok(false); + } // an article saved before its domain got a row is stored whole: dont save it twice - if domain != 0 { - let stored_whole = conn - .prepare_cached("select 1 from segments where file_id = ? and local = ? and domain = 0")? - .exists(params![file_id, whole(&a.message_id)])?; - if stored_whole { - return Ok(false); - } + if domain != 0 && stored(sealed, &whole(&a.message_id), 0)? { + return Ok(false); } // a row from before locals were packed by alphabet has the same local stored as text if (DIGITS..=BASE64_URL).contains(&local[0]) { let mut legacy = vec![TEXT]; legacy.extend_from_slice(unpack_local(&local).as_bytes()); - let stored_legacy = conn - .prepare_cached("select 1 from segments where file_id = ? and local = ? and domain = ?")? - .exists(params![file_id, legacy, domain])?; - if stored_legacy { + if stored(sealed, &legacy, domain)? { return Ok(false); } } let added = conn .prepare_cached("insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)")? - .execute(params![file_id, local, domain, a.part, a.bytes])?; + .execute(params![f.id, local, domain, a.part, a.bytes])?; Ok(added > 0) } @@ -549,6 +578,117 @@ fn release_complete(conn: &Connection, release_id: i64, file_total: Option) Ok(files > 0 && file_total.is_none_or(|ft| files == ft)) } +// ---------------------------------------------------------------- sealing + +/// files untouched this long get sealed even when incomplete +pub const SEAL_AGE: i64 = 3 * 86_400; + +fn blob_error(e: std::io::Error) -> rusqlite::Error { + rusqlite::Error::ToSqlConversionFailure(Box::new(e)) +} + +/// a sealed file's blob, decoded; none when the file isnt sealed +fn sealed_segments(conn: &Connection, file_id: i64) -> Result>> { + conn.prepare_cached("select blob from files where id = ? and blob is not null")? + .query_row([file_id], |r| r.get::<_, Vec>(0)) + .optional()? + .map(|b| crate::blob::decode(&b).map_err(blob_error)) + .transpose() +} + +/// Seal a file: its rows (and any blob it already has) become one blob, the +/// rows go, all or nothing. Returns the segments in the blob, 0 when there +/// is none (no rows, or rows that cant be sealed). +// not called yet: the shard writer and compact seal with it +#[allow(dead_code)] +pub(crate) fn seal_file(conn: &Connection, file_id: i64) -> Result { + conn.execute_batch("savepoint seal")?; + let sealed = seal_rows(conn, file_id); + match sealed { + Ok(_) => conn.execute_batch("release seal")?, + Err(_) => conn.execute_batch("rollback to seal; release seal")?, + } + sealed +} + +fn seal_rows(conn: &Connection, file_id: i64) -> Result { + let mut segs = sealed_segments(conn, file_id)?.unwrap_or_default(); + let rows: Vec = conn + .prepare_cached("select part, bytes, domain, local from segments where file_id = ?")? + .query_map([file_id], |r| { + Ok(crate::blob::Seg { + part: r.get(0)?, + bytes: r.get::<_, Option>(1)?.unwrap_or(0), + domain: r.get(2)?, + local: r.get(3)?, + }) + })? + .collect::>()?; + if rows.is_empty() { + return Ok(segs.len()); + } + // the blob has no room for a negative part number: such a file stays rows + if rows.iter().any(|r| r.part.is_some_and(|p| p < 0)) { + return Ok(0); + } + segs.extend(rows); + conn.prepare_cached("update files set blob = ? where id = ?")? + .execute(params![crate::blob::encode(&segs), file_id])?; + conn.prepare_cached("delete from segments where file_id = ?")?.execute([file_id])?; + Ok(segs.len()) +} + +/// Files after `after_id` with rows to seal: complete, or untouched for +/// `SEAL_AGE` (never touched since the upgrade counts as old). Returns the +/// ids and the last id looked at. +// not called yet: the shard writer and compact seal with it +#[allow(dead_code)] +pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) -> Result<(Vec, i64)> { + let mut stmt = conn.prepare_cached( + "select f.id, f.expected, f.seen, f.touched_at from files f + where f.id > ? and exists (select 1 from segments s where s.file_id = f.id) + order by f.id limit ?", + )?; + let mut ids = Vec::new(); + let mut last = after_id; + let mut rows = stmt.query(params![after_id, limit as i64])?; + while let Some(r) = rows.next()? { + let id: i64 = r.get(0)?; + let expected: Option = r.get(1)?; + let seen: Vec = r.get(2)?; + let touched: Option = r.get(3)?; + last = id; + let complete = expected.is_some_and(|e| is_exactly(&seen, e)); + if complete || touched.is_none_or(|t| t < now - SEAL_AGE) { + ids.push(id); + } + } + Ok((ids, last)) +} + +/// Blobs of sealed files, decoded once each, for checking late articles. +#[derive(Default)] +pub(crate) struct SealedCache { + files: HashMap, i64)>>, +} + +impl SealedCache { + pub(crate) fn new() -> Self { + Self::default() + } + + /// the article (local, domain) is already in file `file_id`'s blob + pub(crate) fn contains(&mut self, conn: &Connection, file_id: i64, local: &[u8], domain: i64) -> Result { + let set = match self.files.entry(file_id) { + Entry::Occupied(e) => e.into_mut(), + Entry::Vacant(e) => e.insert( + sealed_segments(conn, file_id)?.unwrap_or_default().into_iter().map(|s| (s.local, s.domain)).collect(), + ), + }; + Ok(set.contains(&(local.to_vec(), domain))) + } +} + // ---------------------------------------------------------------- saving /// Saves releases into one shard: upsert the release, add its new articles, @@ -573,6 +713,8 @@ impl ShardWriter { ) -> Result<()> { let shard = self.shard; let domains = &mut self.domains; + // blobs of sealed files that get late articles, decoded once each + let mut sealed = SealedCache::new(); let tx = conn.transaction()?; let (mut new_releases, mut new_articles) = (0i64, 0i64); { @@ -632,7 +774,7 @@ impl ShardWriter { let mut f = file(&tx, release_id, name)?; let before = added.len(); for a in articles { - if add_segment(&tx, domains, f.id, a)? { + if add_segment(&tx, domains, &f, a, &mut sealed)? { f.add(a); added.push(a); } @@ -722,10 +864,58 @@ pub fn articles(conn: &Connection, release_id: i64) -> Result> { }) })?; let mut rows: Vec = rows.collect::>()?; + + // sealed files: their blobs, next to any rows that came after sealing + let mut sealed = conn.prepare(&format!( + "select f.blob, f.filename, f.expected, f.subject, r.poster, r.posted_date + from s{s}.files f join s{s}.releases r on r.id = f.release_id + where f.release_id = ? and f.blob is not null" + ))?; + let mut suffixes: HashMap> = HashMap::new(); + let mut blob_rows = sealed.query([release_id])?; + while let Some(r) = blob_rows.next()? { + let blob: Vec = r.get(0)?; + let filename: String = r.get(1)?; + for seg in crate::blob::decode(&blob).map_err(blob_error)? { + let suffix = match suffixes.entry(seg.domain) { + Entry::Occupied(e) => e.into_mut(), + Entry::Vacant(e) => e.insert( + conn.query_row(&format!("select suffix from s{s}.domains where id = ?"), [seg.domain], |r| { + r.get(0) + }) + .optional()?, + ), + }; + rows.push(ArticleRow { + message_id: decode(&seg.local, suffix.as_deref()), + filename: (!filename.is_empty()).then(|| filename.clone()), + part: seg.part, + total_parts: r.get(2)?, + bytes: Some(seg.bytes), + subject: r.get(3)?, + poster: r.get(4)?, + posted_date: r.get(5)?, + }); + } + } rows.sort_by(|a, b| (&a.filename, a.part, &a.message_id).cmp(&(&b.filename, b.part, &b.message_id))); Ok(rows) } +/// articles in shard `schema` (`s3`, or `main` for a shard opened on its +/// own): loose rows plus every sealed blob's segments +pub fn article_count(conn: &Connection, schema: &str) -> Result { + let loose: i64 = conn.query_row(&format!("select count(*) from {schema}.segments"), [], |r| r.get(0))?; + let mut sealed = 0i64; + let mut stmt = conn.prepare(&format!("select blob from {schema}.files where blob is not null"))?; + let mut rows = stmt.query([])?; + while let Some(r) = rows.next()? { + let b: Vec = r.get(0)?; + sealed += crate::blob::decode(&b).map_err(blob_error)?.len() as i64; + } + Ok(loose + sealed) +} + /// (releases, articles) over every shard, from the running totals. `conn` has /// the shards attached. pub fn totals(conn: &Connection) -> Result<(i64, i64)> { @@ -751,7 +941,7 @@ pub fn purge_incomplete(main: &Path) -> Result<()> { delete from releases where complete = 0; commit;", )?; - let articles: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0))?; + let articles = article_count(&conn, "main")?; conn.execute("update meta set value = max(value - ?, 0) where key = 'releases'", [removed])?; conn.execute("update meta set value = ? where key = 'articles'", [articles])?; let _ = conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(())); @@ -865,12 +1055,18 @@ mod tests { let file = file(&conn, 8, "a.rar").unwrap(); let article = Article { message_id: format!("<{:032x}@nyuu>", 7), part: Some(1), ..Default::default() }; let mut fresh = Domains::default(); - assert!(add_segment(&conn, &mut fresh, file.id, &article).unwrap(), "first time: stored whole"); + assert!( + add_segment(&conn, &mut fresh, &file, &article, &mut SealedCache::new()).unwrap(), + "first time: stored whole" + ); for n in 0..SHARED_AFTER { fresh.encode(&conn, &format!("<{n:032x}@nyuu>")).unwrap(); } assert!(conn.prepare("select 1 from domains where suffix = '@nyuu>'").unwrap().exists([]).unwrap()); - assert!(!add_segment(&conn, &mut fresh, file.id, &article).unwrap(), "same article again: not saved twice"); + assert!( + !add_segment(&conn, &mut fresh, &file, &article, &mut SealedCache::new()).unwrap(), + "same article again: not saved twice" + ); let segments: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); assert_eq!(segments, 1); @@ -896,7 +1092,10 @@ mod tests { params![file.id, stored, domain], ) .unwrap(); - assert!(!add_segment(&conn, &mut Domains::default(), file.id, &legacy).unwrap(), "legacy text row found"); + assert!( + !add_segment(&conn, &mut Domains::default(), &file, &legacy, &mut SealedCache::new()).unwrap(), + "legacy text row found" + ); let segments: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); assert_eq!(segments, 2); } @@ -929,4 +1128,223 @@ mod tests { insert_part(&mut huge, 5_000_000_000); assert!(huge.is_empty()); } + + /// a shard with one release: file a.rar (3 parts) and b.rar (2 parts) + fn sealed_fixture() -> (tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let art = |file: &str, part: i64, total: i64, id: &str| Article { + message_id: id.into(), + subject: format!("\"{file}\" yEnc ({part}/{total})"), + filename: Some(file.into()), + part: Some(part), + total_parts: Some(total), + bytes: 100 + part, + ..Default::default() + }; + let release = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![ + art("a.rar", 1, 3, ""), + art("a.rar", 2, 3, "<0abc12def34@ngPost>"), + art("a.rar", 3, 3, ""), + art("b.rar", 1, 2, ""), + ], + ..Default::default() + }; + save(&main, &[release]).unwrap(); + (dir, main) + } + + #[test] + fn sealing_keeps_every_nzb_and_late_articles_merge() { + let (_dir, main) = sealed_fixture(); + let shard = shard_path(&main, shard_of("alt.binaries.t")); + let read = || { + let conn = db::open_with_shards(&main).unwrap(); + let id: i64 = conn.query_row("select id from releases", [], |r| r.get(0)).unwrap(); + articles(&conn, id).unwrap() + }; + let before = read(); + + let conn = db::open_at(&shard).unwrap(); + let ids: Vec = conn + .prepare("select id from files") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + for id in &ids { + seal_file(&conn, *id).unwrap(); + } + let loose: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(loose, 0, "sealed files have no rows left"); + assert_eq!(read(), before, "same articles back from the blobs"); + assert_eq!( + article_count(&db::open_with_shards(&main).unwrap(), &format!("s{}", shard_of("alt.binaries.t"))).unwrap(), + 4 + ); + + // a late article for a sealed file is saved once, one already sealed isnt + let late = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![ + Article { + message_id: "".into(), + filename: Some("b.rar".into()), + part: Some(2), + total_parts: Some(2), + bytes: 102, + ..Default::default() + }, + Article { + message_id: "".into(), + filename: Some("a.rar".into()), + part: Some(1), + total_parts: Some(3), + bytes: 101, + ..Default::default() + }, + ], + ..Default::default() + }; + save(&main, &[late]).unwrap(); + let after = read(); + assert_eq!(after.len(), 5); + assert_eq!(after.iter().filter(|a| a.message_id == "").count(), 1); + + // resealing folds the late row in + let b: i64 = conn.query_row("select id from files where filename = 'b.rar'", [], |r| r.get(0)).unwrap(); + assert_eq!(seal_file(&conn, b).unwrap(), 2); + assert_eq!(read(), after); + } + + #[test] + fn sealed_nzb_is_byte_for_byte_the_same() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let art = |file: &str, part: Option, id: &str, bytes: i64| Article { + message_id: id.into(), + subject: format!("\"{file}\" yEnc"), + filename: Some(file.into()), + part, + total_parts: Some(2), + bytes, + ..Default::default() + }; + let release = Release { + name: "Nzb".into(), + group: "alt.binaries.t".into(), + poster: "me ".into(), + date: "2026-10-01 12:00:00".into(), + articles: vec![ + art("a.rar", Some(2), "<00ff00ff@ngPost>", 700_000), + art("a.rar", Some(1), "", 750_000), // stored whole + art("a.rar", None, "", 5), + art("a.rar", Some(1), "", 750_000), // a repost of part 1 + art("", Some(1), "<00aa@ngPost>", 9), // no filename + ], + ..Default::default() + }; + save(&main, &[release]).unwrap(); + let nzb = || { + let conn = db::open_with_shards(&main).unwrap(); + let id: i64 = conn.query_row("select id from releases", [], |r| r.get(0)).unwrap(); + let r = crate::search::get_release_with(&conn, id).unwrap().unwrap(); + crate::nzb::render_nzb(&r, &articles(&conn, id).unwrap()) + }; + let before = nzb(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let ids: Vec = conn + .prepare("select id from files") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + for id in ids { + assert!(seal_file(&conn, id).unwrap() > 0); + } + assert_eq!(nzb(), before); + } + + #[test] + fn a_legacy_text_local_in_a_blob_is_found() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("atlas.s0.db"); + create_shard(&path).unwrap(); + let conn = db::open_at(&path).unwrap(); + let mut domains = Domains::default(); + let mut domain = 0; + for n in 0..SHARED_AFTER { + domain = domains.encode(&conn, &format!("<{n:032x}@JBinUp.local>")).unwrap().1; + } + assert!(domain > 0); + let f = file(&conn, 8, "a.rar").unwrap(); + let mut stored = vec![TEXT]; + stored.extend_from_slice(b"hotfTpetaZRIbOYuTuQ31"); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, 1, 0)", + params![f.id, stored, domain], + ) + .unwrap(); + assert_eq!(seal_file(&conn, f.id).unwrap(), 1); + let f = file(&conn, 8, "a.rar").unwrap(); + assert!(f.sealed); + let article = + Article { message_id: "".into(), part: Some(1), ..Default::default() }; + assert!(!add_segment(&conn, &mut domains, &f, &article, &mut SealedCache::new()).unwrap()); + let other = Article { message_id: "".into(), part: Some(2), ..Default::default() }; + assert!(add_segment(&conn, &mut domains, &f, &other, &mut SealedCache::new()).unwrap(), "a new one is a row"); + let loose: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(loose, 1); + } + + #[test] + fn old_shards_get_the_seal_columns() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("atlas.s0.db"); + { + let conn = db::open_at(&path).unwrap(); + conn.execute_batch( + "create table files (id INTEGER PRIMARY KEY, release_id INTEGER NOT NULL, filename TEXT NOT NULL, + subject TEXT, subject_part INTEGER, subject_mid TEXT, expected INTEGER, file_total INTEGER, + seen BLOB NOT NULL); + insert into files (release_id, filename, seen) values (8, 'a.rar', x'02');", + ) + .unwrap(); + } + create_shard(&path).unwrap(); + create_shard(&path).unwrap(); // again: nothing to add + let conn = db::open_at(&path).unwrap(); + let f = file(&conn, 8, "a.rar").unwrap(); + assert!(!f.sealed); + assert_eq!(f.seen, vec![2]); + let touched: Option = conn.query_row("select touched_at from files", [], |r| r.get(0)).unwrap(); + assert_eq!(touched, None, "untouched since the upgrade"); + put_file(&conn, &f).unwrap(); + let touched: Option = conn.query_row("select touched_at from files", [], |r| r.get(0)).unwrap(); + assert!(touched.is_some()); + } + + #[test] + fn complete_or_stale_files_are_sealable() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + // the clock put_file stamped touched_at with + let now: i64 = conn.query_row("select unixepoch()", [], |r| r.get(0)).unwrap(); + // a.rar is complete (1..=3), b.rar has 1 of 2 and was just touched + let (ids, _) = sealable(&conn, 0, 100, now).unwrap(); + let name = |id: i64| -> String { + conn.query_row("select filename from files where id = ?", [id], |r| r.get(0)).unwrap() + }; + assert_eq!(ids.iter().map(|&i| name(i)).collect::>(), vec!["a.rar".to_string()]); + conn.execute("update files set touched_at = ? where filename = 'b.rar'", [now - SEAL_AGE - 1]).unwrap(); + assert_eq!(sealable(&conn, 0, 100, now).unwrap().0.len(), 2, "b.rar went stale"); + } } From a9d365d139f6ef8739b0ec4e03dcab0cdaddfa62 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:39:00 -0500 Subject: [PATCH 018/159] Seal fixes: one snapshot for NZB reads, sealable walks by scanned files Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 118 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 104 insertions(+), 14 deletions(-) diff --git a/src/store.rs b/src/store.rs index 68936326..d0c01485 100644 --- a/src/store.rs +++ b/src/store.rs @@ -146,8 +146,8 @@ pub fn create_shard(path: &Path) -> Result<()> { expected INTEGER, file_total INTEGER, seen BLOB NOT NULL, - blob BLOB, - touched_at INTEGER + touched_at INTEGER, + blob BLOB ); create unique index if not exists files_key on files(release_id, filename); @@ -169,13 +169,14 @@ pub fn create_shard(path: &Path) -> Result<()> { migrate_shard(&conn) } -/// Columns a shard made before sealing lacks: `files.blob` (a sealed file's -/// articles) and `files.touched_at` (when articles were last added). Adding -/// a nullable column doesnt rewrite the table. +/// Columns a shard made before sealing lacks: `files.touched_at` (when +/// articles were last added) and `files.blob` (a sealed file's articles), in +/// the same order `create_shard` has them. Adding a nullable column doesnt +/// rewrite the table. pub fn migrate_shard(conn: &Connection) -> Result<()> { let cols: Vec = conn.prepare("pragma table_info(files)")?.query_map([], |r| r.get(1))?.collect::>()?; - for (col, kind) in [("blob", "BLOB"), ("touched_at", "INTEGER")] { + for (col, kind) in [("touched_at", "INTEGER"), ("blob", "BLOB")] { if !cols.iter().any(|c| c == col) { conn.execute(&format!("alter table files add column {col} {kind}"), [])?; } @@ -638,27 +639,36 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { Ok(segs.len()) } -/// Files after `after_id` with rows to seal: complete, or untouched for -/// `SEAL_AGE` (never touched since the upgrade counts as old). Returns the -/// ids and the last id looked at. +/// The next `limit` files after `after_id`, and which of them to seal: ones +/// with rows that are complete and not sealed yet, or untouched for +/// `SEAL_AGE` (never touched since the upgrade counts as old; a sealed file +/// with late rows waits for this too). Files with a negative part number +/// never seal. Returns the ids and the last id looked at, for walking the +/// table `limit` files at a time: `last == after_id` means the end. // not called yet: the shard writer and compact seal with it #[allow(dead_code)] pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) -> Result<(Vec, i64)> { let mut stmt = conn.prepare_cached( - "select f.id, f.expected, f.seen, f.touched_at from files f - where f.id > ? and exists (select 1 from segments s where s.file_id = f.id) - order by f.id limit ?", + "select f.id, f.expected, f.seen, f.touched_at, f.blob is not null, + exists (select 1 from segments s where s.file_id = f.id), + exists (select 1 from segments s where s.file_id = f.id and s.part < 0) + from files f where f.id > ? order by f.id limit ?", )?; let mut ids = Vec::new(); let mut last = after_id; let mut rows = stmt.query(params![after_id, limit as i64])?; while let Some(r) = rows.next()? { let id: i64 = r.get(0)?; + last = id; + let (has_rows, negative): (bool, bool) = (r.get(5)?, r.get(6)?); + if !has_rows || negative { + continue; + } let expected: Option = r.get(1)?; let seen: Vec = r.get(2)?; let touched: Option = r.get(3)?; - last = id; - let complete = expected.is_some_and(|e| is_exactly(&seen, e)); + let sealed: bool = r.get(4)?; + let complete = !sealed && expected.is_some_and(|e| is_exactly(&seen, e)); if complete || touched.is_none_or(|t| t < now - SEAL_AGE) { ids.push(id); } @@ -844,6 +854,10 @@ pub fn save(main: &Path, releases: &[Release]) -> Result<()> { /// for building its NZB. `conn` has the shards attached. pub fn articles(conn: &Connection, release_id: i64) -> Result> { let s = shard_of_id(release_id); + // rows and blobs from one snapshot: a file sealed between two separate + // reads would show its articles twice (or not at all). a caller already + // in a transaction has one + let _snapshot = if conn.is_autocommit() { Some(conn.unchecked_transaction()?) } else { None }; let mut stmt = conn.prepare(&format!( "select s.local, d.suffix, f.filename, s.part, f.expected, s.bytes, f.subject, r.poster, r.posted_date from s{s}.files f join s{s}.segments s on s.file_id = f.id join s{s}.releases r on r.id = f.release_id @@ -1332,6 +1346,82 @@ mod tests { assert!(touched.is_some()); } + #[test] + fn sealable_walks_the_table_a_step_at_a_time() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let now: i64 = conn.query_row("select unixepoch()", [], |r| r.get(0)).unwrap(); + let ids: Vec = conn + .prepare("select id from files order by id") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + for id in &ids { + seal_file(&conn, *id).unwrap(); + } + + // all sealed: nothing to do, but every call moves on by `limit` files + assert_eq!(sealable(&conn, 0, 1, now).unwrap(), (vec![], ids[0])); + assert_eq!(sealable(&conn, ids[0], 1, now).unwrap(), (vec![], ids[1])); + assert_eq!(sealable(&conn, ids[1], 1, now).unwrap(), (vec![], ids[1]), "the end: last == after_id"); + + // a late row makes sealed b.rar complete, it still waits until it's stale + let late = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![Article { + message_id: "".into(), + filename: Some("b.rar".into()), + part: Some(2), + total_parts: Some(2), + bytes: 102, + ..Default::default() + }], + ..Default::default() + }; + save(&main, &[late]).unwrap(); + assert!(sealable(&conn, 0, 100, now).unwrap().0.is_empty()); + conn.execute("update files set touched_at = ? where filename = 'b.rar'", [now - SEAL_AGE - 1]).unwrap(); + assert_eq!(sealable(&conn, 0, 100, now).unwrap().0, vec![ids[1]]); + + // a negative part number cant go in a blob: never listed + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, x'00', 0, -1, 0)", + [ids[1]], + ) + .unwrap(); + assert!(sealable(&conn, 0, 100, now).unwrap().0.is_empty()); + assert_eq!(seal_file(&conn, ids[1]).unwrap(), 0); + } + + #[test] + fn articles_reads_inside_a_callers_transaction() { + let (_dir, main) = sealed_fixture(); + let reader = db::open_with_shards(&main).unwrap(); + let id: i64 = reader.query_row("select id from releases", [], |r| r.get(0)).unwrap(); + let before = articles(&reader, id).unwrap(); + reader.execute_batch("begin").unwrap(); + assert_eq!(articles(&reader, id).unwrap(), before); + // sealed by another connection meanwhile: the reader's snapshot doesnt change + let shard = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let files: Vec = shard + .prepare("select id from files") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + for f in files { + seal_file(&shard, f).unwrap(); + } + assert_eq!(articles(&reader, id).unwrap(), before); + reader.execute_batch("commit").unwrap(); + assert_eq!(articles(&reader, id).unwrap(), before, "and the same from the blobs"); + assert!(reader.is_autocommit(), "no transaction left open"); + } + #[test] fn complete_or_stale_files_are_sealable() { let (_dir, main) = sealed_fixture(); From 6459f6a1330f985929e8572353ea72116e3e022e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:42:00 -0500 Subject: [PATCH 019/159] Shard writers seal due files between transactions Co-Authored-By: Claude Sonnet 5.5 --- src/indexer.rs | 3 +++ src/profile.rs | 4 ++++ src/store.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index ad880dac..8f8d9146 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -167,6 +167,9 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s Ok(conn) => { let saved = store.save(conn, ids, batch.iter().map(|job| job.releases.as_slice())); let t = std::time::Instant::now(); + let _ = store.seal_some(conn, chrono::Utc::now().timestamp()); + Load::add_since(&LOAD.writer_seal_ns, t); + let t = std::time::Instant::now(); let _ = db::finish_checkpoint(conn); Load::add_since(&LOAD.writer_checkpoint_ns, t); saved.map_err(|e| e.to_string()) diff --git a/src/profile.rs b/src/profile.rs index f7e07827..95d5cd52 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -74,6 +74,8 @@ pub struct Load { pub writer_queued: AtomicU64, /// part of writer_busy spent finishing checkpoints between transactions pub writer_checkpoint_ns: AtomicU64, + /// part of writer_busy spent sealing files between transactions + pub writer_seal_ns: AtomicU64, /// time header requests spent on the wire, and how many there were pub xover_ns: AtomicU64, pub xovers: AtomicU64, @@ -89,6 +91,7 @@ pub static LOAD: Load = Load { writer_slices: AtomicU64::new(0), writer_queued: AtomicU64::new(0), writer_checkpoint_ns: AtomicU64::new(0), + writer_seal_ns: AtomicU64::new(0), xover_ns: AtomicU64::new(0), xovers: AtomicU64::new(0), lease_wait_ns: AtomicU64::new(0), @@ -114,6 +117,7 @@ impl Load { "writer_slices": get(&self.writer_slices), "writer_queued": get(&self.writer_queued), "writer_checkpoint_ns": get(&self.writer_checkpoint_ns), + "writer_seal_ns": get(&self.writer_seal_ns), "xover_ns": get(&self.xover_ns), "xovers": get(&self.xovers), "lease_wait_ns": get(&self.lease_wait_ns), diff --git a/src/store.rs b/src/store.rs index d0c01485..0d66a917 100644 --- a/src/store.rs +++ b/src/store.rs @@ -600,8 +600,6 @@ fn sealed_segments(conn: &Connection, file_id: i64) -> Result Result { conn.execute_batch("savepoint seal")?; let sealed = seal_rows(conn, file_id); @@ -645,8 +643,6 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { /// with late rows waits for this too). Files with a negative part number /// never seal. Returns the ids and the last id looked at, for walking the /// table `limit` files at a time: `last == after_id` means the end. -// not called yet: the shard writer and compact seal with it -#[allow(dead_code)] pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) -> Result<(Vec, i64)> { let mut stmt = conn.prepare_cached( "select f.id, f.expected, f.seen, f.touched_at, f.blob is not null, @@ -706,11 +702,42 @@ impl SealedCache { pub struct ShardWriter { pub shard: usize, domains: Domains, + /// where the last seal tick stopped in the files table + seal_after: i64, } +/// files sealed per writer tick at most +pub const SEAL_PER_TICK: usize = 2_000; + impl ShardWriter { pub fn new(shard: usize) -> ShardWriter { - ShardWriter { shard, domains: Domains::default() } + ShardWriter { shard, domains: Domains::default(), seal_after: 0 } + } + + /// Seal up to SEAL_PER_TICK files that are due, walking the files table by + /// id from where the last tick stopped. At the end of the table it goes + /// back to the start. Not for use inside a save transaction. + pub fn seal_some(&mut self, conn: &mut Connection, now: i64) -> Result { + let tx = conn.transaction()?; + let scan = SEAL_PER_TICK * 4; + let (mut ids, mut last) = sealable(&tx, self.seal_after, scan, now)?; + // nothing left after the cursor: start over from the first file + if last == self.seal_after && self.seal_after != 0 { + (ids, last) = sealable(&tx, 0, scan, now)?; + } + // past the cap, the next tick picks up after the last one sealed + let next = if ids.len() > SEAL_PER_TICK { + ids.truncate(SEAL_PER_TICK); + ids[SEAL_PER_TICK - 1] + } else { + last + }; + for id in &ids { + seal_file(&tx, *id)?; + } + tx.commit()?; + self.seal_after = next; + Ok(ids.len()) } /// Releases of this shard's groups, in one transaction. The same release @@ -1437,4 +1464,18 @@ mod tests { conn.execute("update files set touched_at = ? where filename = 'b.rar'", [now - SEAL_AGE - 1]).unwrap(); assert_eq!(sealable(&conn, 0, 100, now).unwrap().0.len(), 2, "b.rar went stale"); } + + #[test] + fn a_writer_seals_what_is_due_a_tick_at_a_time() { + let (_dir, main) = sealed_fixture(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + let mut writer = ShardWriter::new(shard); + let now = 2_000_000_000; + conn.execute("update files set touched_at = ?", [now]).unwrap(); + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1, "only the complete file"); + conn.execute("update files set touched_at = ?", [now - SEAL_AGE - 1]).unwrap(); + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1, "the stale one, after wrapping around"); + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 0); + } } From 3505b7e8d73e1aceb6d2b5d2c6e8ba86e1e25b33 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:44:41 -0500 Subject: [PATCH 020/159] Seal ticks: skip files that fail, time budget, ack before sealing Co-Authored-By: Claude Sonnet 5.5 --- src/indexer.rs | 29 ++++++++++++++------- src/profile.rs | 4 +++ src/store.rs | 68 +++++++++++++++++++++++++++++++++++++++----------- 3 files changed, 78 insertions(+), 23 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 8f8d9146..af3dfca4 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -165,14 +165,7 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s let t = std::time::Instant::now(); let result = match &mut opened { Ok(conn) => { - let saved = store.save(conn, ids, batch.iter().map(|job| job.releases.as_slice())); - let t = std::time::Instant::now(); - let _ = store.seal_some(conn, chrono::Utc::now().timestamp()); - Load::add_since(&LOAD.writer_seal_ns, t); - let t = std::time::Instant::now(); - let _ = db::finish_checkpoint(conn); - Load::add_since(&LOAD.writer_checkpoint_ns, t); - saved.map_err(|e| e.to_string()) + store.save(conn, ids, batch.iter().map(|job| job.releases.as_slice())).map_err(|e| e.to_string()) } Err(e) => Err(format!("couldnt open {}: {e}", path.display())), }; @@ -180,10 +173,28 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s LOAD.writer_batches.fetch_add(1, Relaxed); LOAD.writer_slices.fetch_add(batch.len() as u64, Relaxed); - // the whole batch rolled back on an error, every slice in it failed + // the whole batch rolled back on an error, every slice in it failed. + // the save is committed by now: the slices dont wait for the housekeeping + let saved = result.is_ok(); for job in batch { let _ = job.done.send(result.clone()); } + + // housekeeping between transactions + if let Ok(conn) = &mut opened { + let t = std::time::Instant::now(); + if saved { + let sealing = std::time::Instant::now(); + if store.seal_some(conn, chrono::Utc::now().timestamp()).is_err() { + LOAD.writer_seal_errors.fetch_add(1, Relaxed); + } + Load::add_since(&LOAD.writer_seal_ns, sealing); + } + let checkpointing = std::time::Instant::now(); + let _ = db::finish_checkpoint(conn); + Load::add_since(&LOAD.writer_checkpoint_ns, checkpointing); + Load::add_since(&LOAD.writer_busy_ns, t); + } } } diff --git a/src/profile.rs b/src/profile.rs index 95d5cd52..18cd979b 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -76,6 +76,8 @@ pub struct Load { pub writer_checkpoint_ns: AtomicU64, /// part of writer_busy spent sealing files between transactions pub writer_seal_ns: AtomicU64, + /// files (or whole seal ticks) that failed to seal + pub writer_seal_errors: AtomicU64, /// time header requests spent on the wire, and how many there were pub xover_ns: AtomicU64, pub xovers: AtomicU64, @@ -92,6 +94,7 @@ pub static LOAD: Load = Load { writer_queued: AtomicU64::new(0), writer_checkpoint_ns: AtomicU64::new(0), writer_seal_ns: AtomicU64::new(0), + writer_seal_errors: AtomicU64::new(0), xover_ns: AtomicU64::new(0), xovers: AtomicU64::new(0), lease_wait_ns: AtomicU64::new(0), @@ -118,6 +121,7 @@ impl Load { "writer_queued": get(&self.writer_queued), "writer_checkpoint_ns": get(&self.writer_checkpoint_ns), "writer_seal_ns": get(&self.writer_seal_ns), + "writer_seal_errors": get(&self.writer_seal_errors), "xover_ns": get(&self.xover_ns), "xovers": get(&self.xovers), "lease_wait_ns": get(&self.lease_wait_ns), diff --git a/src/store.rs b/src/store.rs index 0d66a917..a309899f 100644 --- a/src/store.rs +++ b/src/store.rs @@ -22,7 +22,7 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::time::Instant; -use rusqlite::{Connection, OptionalExtension, Result, params}; +use rusqlite::{Connection, OptionalExtension, Result, TransactionBehavior, params}; use crate::db; use crate::parser::{Article, Release}; @@ -709,16 +709,22 @@ pub struct ShardWriter { /// files sealed per writer tick at most pub const SEAL_PER_TICK: usize = 2_000; +/// a seal tick stops after this long, so the writer gets back to saving +pub const SEAL_BUDGET: std::time::Duration = std::time::Duration::from_millis(100); + impl ShardWriter { pub fn new(shard: usize) -> ShardWriter { ShardWriter { shard, domains: Domains::default(), seal_after: 0 } } - /// Seal up to SEAL_PER_TICK files that are due, walking the files table by - /// id from where the last tick stopped. At the end of the table it goes - /// back to the start. Not for use inside a save transaction. + /// Seal up to SEAL_PER_TICK files that are due, for at most SEAL_BUDGET, + /// walking the files table by id from where the last tick stopped. At the + /// end of the table it goes back to the start. A file that fails to seal + /// is counted and skipped. Not for use inside a save transaction. + /// Returns the files sealed. pub fn seal_some(&mut self, conn: &mut Connection, now: i64) -> Result { - let tx = conn.transaction()?; + let started = Instant::now(); + let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; let scan = SEAL_PER_TICK * 4; let (mut ids, mut last) = sealable(&tx, self.seal_after, scan, now)?; // nothing left after the cursor: start over from the first file @@ -726,18 +732,27 @@ impl ShardWriter { (ids, last) = sealable(&tx, 0, scan, now)?; } // past the cap, the next tick picks up after the last one sealed - let next = if ids.len() > SEAL_PER_TICK { + if ids.len() > SEAL_PER_TICK { ids.truncate(SEAL_PER_TICK); - ids[SEAL_PER_TICK - 1] - } else { - last - }; - for id in &ids { - seal_file(&tx, *id)?; + last = ids[SEAL_PER_TICK - 1]; + } + let mut sealed = 0; + for (i, id) in ids.iter().enumerate() { + // out of time: the next tick picks up after the last one done + if i > 0 && started.elapsed() >= SEAL_BUDGET { + last = ids[i - 1]; + break; + } + match seal_file(&tx, *id) { + Ok(segs) => sealed += usize::from(segs > 0), + Err(_) => { + profile::LOAD.writer_seal_errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } } tx.commit()?; - self.seal_after = next; - Ok(ids.len()) + self.seal_after = last; + Ok(sealed) } /// Releases of this shard's groups, in one transaction. The same release @@ -1478,4 +1493,29 @@ mod tests { assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1, "the stale one, after wrapping around"); assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 0); } + + #[test] + fn a_file_that_wont_seal_does_not_stop_the_tick() { + let (_dir, main) = sealed_fixture(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + let mut writer = ShardWriter::new(shard); + let now = 2_000_000_000; + conn.execute("update files set touched_at = ?", [now - SEAL_AGE - 1]).unwrap(); + // a.rar has rows and a blob nobody can decode + conn.execute("update files set blob = x'ff00ff' where filename = 'a.rar'", []).unwrap(); + let rows = |c: &Connection, name: &str| -> i64 { + c.query_row( + "select count(*) from segments where file_id = (select id from files where filename = ?)", + [name], + |r| r.get(0), + ) + .unwrap() + }; + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1, "b.rar sealed, a.rar skipped"); + assert_eq!(rows(&conn, "a.rar"), 3, "a.rar keeps its rows"); + assert_eq!(rows(&conn, "b.rar"), 0); + let b: i64 = conn.query_row("select id from files where filename = 'b.rar'", [], |r| r.get(0)).unwrap(); + assert_eq!(writer.seal_after, b, "the cursor went past the bad file"); + } } From f5053082b93a3765f736c5ad96e6696d346a56cf Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:53:09 -0500 Subject: [PATCH 021/159] Compact re-encodes locals and seals due files Blobs are rewritten too: domain uses are counted inside blobs, segments of dropped domains become whole ids and kept ones are repacked. Files are copied in id order next to their rows and due ones sealed on the way, so the copy has no free pages. A corrupt blob stops the shard. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 403 ++++++++++++++++++++++++++++++++++++++++++------- src/store.rs | 15 +- 2 files changed, 358 insertions(+), 60 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index e1e8e314..cb820f5f 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -4,6 +4,9 @@ //! - message-ids whose domain fewer than `SHARED_AFTER` articles share are //! stored whole, and those domains dropped: some posting tools make up a //! new domain per article, which left tens of millions of single use rows +//! - the other message-ids packed the current way (locals saved before the +//! packing by shape are re-encoded), in blobs too +//! - every file that is due sealed into a blob as it's copied //! - the copy has no free space in it (the conversion left the space its //! staging table used) //! @@ -15,8 +18,10 @@ use std::path::{Path, PathBuf}; use std::time::Instant; use anyhow::{Context, Result, anyhow, bail}; -use rusqlite::{Connection, params}; +use rusqlite::types::Value; +use rusqlite::{Connection, OptionalExtension, params, params_from_iter}; +use crate::blob::{self, Seg}; use crate::db; use crate::store::{self, SHARDS, SHARED_AFTER}; @@ -96,6 +101,8 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> { let conn = db::open_at(&path)?; conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(()))?; + // a shard from before sealing gets its (empty) seal columns + store::migrate_shard(&conn)?; } let before = size(&path); @@ -113,26 +120,34 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> )?; conn.execute("attach database ? as old", [path.to_string_lossy()])?; - // how many articles use each domain + // how many articles use each domain, as rows and inside sealed blobs say("counting domains"); let max_domain: i64 = conn.query_row("select coalesce(max(id), 0) from old.domains", [], |r| r.get(0))?; let mut uses = vec![0u32; max_domain as usize + 1]; { + let mut used = |d: i64| { + if let Some(n) = uses.get_mut(d as usize) { + *n = n.saturating_add(1); + } + }; let mut stmt = conn.prepare("select domain from old.segments")?; let mut rows = stmt.query([])?; while let Some(r) = rows.next()? { - let d: i64 = r.get(0)?; - if let Some(n) = uses.get_mut(d as usize) { - *n = n.saturating_add(1); + used(r.get(0)?); + } + let mut stmt = conn.prepare("select id, blob from old.files where blob is not null")?; + let mut rows = stmt.query([])?; + while let Some(r) = rows.next()? { + for seg in unseal(shard, r.get(0)?, &r.get::<_, Vec>(1)?)? { + used(seg.domain); } } } let shared = |d: i64| d != 0 && uses.get(d as usize).is_some_and(|n| *n >= SHARED_AFTER); - say("copying releases and files"); + say("copying releases"); conn.execute_batch( "insert into releases select * from old.releases order by id; - insert into files select * from old.files order by id; insert or replace into meta select * from old.meta;", )?; @@ -157,34 +172,82 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> tx.commit()?; } - // the articles, in key order: those of dropped domains stored whole - say(&format!("copying articles ({kept} shared domains, dropping {dropped})")); - let mut copied = 0i64; + // the files and their articles, in id order: those of dropped domains + // stored whole, the rest packed the current way, and files that are due + // sealed into one blob on the way (sealing afterwards would leave the + // copy full of the deleted rows' free pages) + say(&format!("copying files and articles ({kept} shared domains, dropping {dropped}), sealing those due")); + let now = chrono::Utc::now().timestamp(); + let (mut copied, mut sealed) = (0i64, 0i64); { - let read = Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; - let mut stmt = read.prepare( + let open = || Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY); + let (files_read, rows_read) = (open()?, open()?); + let mut suffix_of = files_read.prepare("select suffix from domains where id = ?")?; + let mut files_stmt = files_read.prepare(&format!("select {FILE_COLUMNS} from files order by id"))?; + let mut files = files_stmt.query([])?; + let mut rows_stmt = rows_read.prepare( "select s.file_id, s.local, s.domain, s.part, s.bytes, d.suffix - from segments s left join domains d on d.id = s.domain", + from segments s left join domains d on d.id = s.domain order by s.file_id", )?; - let mut rows = stmt.query([])?; + let mut rows = rows_stmt.query([])?; + let mut pending = next_row(&mut rows, &shared)?; + let mut tx = conn.transaction()?; let mut in_tx = 0; loop { - let Some(r) = rows.next()? else { break }; - let (file_id, local, domain): (i64, Vec, i64) = (r.get(0)?, r.get(1)?, r.get(2)?); - let (part, bytes): (Option, Option) = (r.get(3)?, r.get(4)?); - let (local, domain) = if domain == 0 || shared(domain) { - (local, domain) - } else { - let suffix: Option = r.get(5)?; - (store::whole(&store::decode(&local, suffix.as_deref())), 0) - }; - tx.prepare_cached( - "insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", - )? - .execute(params![file_id, local, domain, part, bytes])?; - copied += 1; - in_tx += 1; + let file = files.next()?; + let id: Option = file.map(|f| f.get(0)).transpose()?; + // rows whose file isnt there (purged, or past the last file) stay rows + while let Some(row) = pending.take_if(|r| id.is_none_or(|id| r.file_id < id)) { + insert_row(&tx, &row)?; + (copied, in_tx) = (copied + 1, in_tx + 1); + pending = next_row(&mut rows, &shared)?; + } + let (Some(f), Some(id)) = (file, id) else { break }; + let mut file_rows = Vec::new(); + while let Some(row) = pending.take_if(|r| r.file_id == id) { + file_rows.push(row); + pending = next_row(&mut rows, &shared)?; + } + + // its blob, with every message-id stored the way its rows are + let old_blob: Option> = f.get(10)?; + let mut segs = Vec::new(); + for seg in old_blob.as_deref().map(|b| unseal(shard, id, b)).transpose()?.unwrap_or_default() { + let suffix: Option = if seg.domain != 0 && !shared(seg.domain) { + suffix_of.query_row([seg.domain], |r| r.get(0)).optional()? + } else { + None + }; + let (local, domain) = rewrite(seg.local, seg.domain, shared(seg.domain), suffix.as_deref()); + segs.push(Seg { local, domain, ..seg }); + } + + // rows a blob cant hold exactly (a negative part, no size) stay rows + let fits = file_rows.iter().all(|r| r.part.is_none_or(|p| p >= 0) && r.bytes.is_some()); + let seen: Vec = f.get(8)?; + let seal = + !file_rows.is_empty() && fits && store::due(f.get(6)?, &seen, f.get(9)?, old_blob.is_some(), now); + if seal { + segs.extend(file_rows.drain(..).map(|r| Seg { + part: r.part, + bytes: r.bytes.unwrap_or(0), + domain: r.domain, + local: r.local, + })); + sealed += 1; + } + let blob = (old_blob.is_some() || seal).then(|| blob::encode(&segs)); + + let mut values: Vec = (0..10).map(|i| f.get(i)).collect::>()?; + values.push(blob.map_or(Value::Null, Value::Blob)); + tx.prepare_cached(&format!("insert into files ({FILE_COLUMNS}) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))? + .execute(params_from_iter(values))?; + for row in &file_rows { + insert_row(&tx, row)?; + } + copied += (segs.len() + file_rows.len()) as i64; + in_tx += 1 + segs.len() + file_rows.len(); if in_tx >= BATCH { tx.commit()?; tx = conn.transaction()?; @@ -193,6 +256,7 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> } tx.commit()?; } + say(&format!("sealed {sealed} files")); say("building indexes and the search index"); conn.execute_batch( @@ -223,8 +287,56 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> Ok(Shrunk { before, after, domains_kept: kept, domains_dropped: dropped }) } -/// The copy holds the same releases, files and articles as the original, and -/// a sample of releases build the same NZBs from both. +/// the files table's columns, blob last +const FILE_COLUMNS: &str = + "id, release_id, filename, subject, subject_part, subject_mid, expected, file_total, seen, touched_at, blob"; + +/// A sealed file's articles. A blob that wont decode stops the shard: copying +/// on without it would lose the file's articles. +fn unseal(shard: usize, file_id: i64, blob: &[u8]) -> Result> { + blob::decode(blob) + .with_context(|| format!("shard {shard}: file {file_id} has a corrupt blob; the original was kept")) +} + +/// A message-id as the copy stores it, (local, domain): kept whole, packed +/// the current way under a shared domain, or made whole when its domain is +/// dropped. +fn rewrite(local: Vec, domain: i64, shared: bool, suffix: Option<&str>) -> (Vec, i64) { + if domain == 0 { + (local, 0) + } else if shared { + (store::repack(&local), domain) + } else { + (store::whole(&store::decode(&local, suffix)), 0) + } +} + +/// one article row of the copy +struct Row { + file_id: i64, + local: Vec, + domain: i64, + part: Option, + bytes: Option, +} + +/// the next row of `select file_id, local, domain, part, bytes, suffix`, rewritten +fn next_row(rows: &mut rusqlite::Rows, shared: &dyn Fn(i64) -> bool) -> Result> { + let Some(r) = rows.next()? else { return Ok(None) }; + let (domain, suffix): (i64, Option) = (r.get(2)?, r.get(5)?); + let (local, domain) = rewrite(r.get(1)?, domain, shared(domain), suffix.as_deref()); + Ok(Some(Row { file_id: r.get(0)?, local, domain, part: r.get(3)?, bytes: r.get(4)? })) +} + +fn insert_row(conn: &Connection, r: &Row) -> Result<()> { + conn.prepare_cached("insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)")? + .execute(params![r.file_id, r.local, r.domain, r.part, r.bytes])?; + Ok(()) +} + +/// The copy holds the same releases, files and articles (rows and inside +/// blobs) as the original, and a sample of releases build the same NZBs from +/// both. fn check(original: &Path, copy: &Path, shard: usize, copied: i64) -> Result<()> { let attach = |path: &Path| -> Result { let conn = Connection::open_in_memory()?; @@ -235,13 +347,18 @@ fn check(original: &Path, copy: &Path, shard: usize, copied: i64) -> Result<()> let count = |conn: &Connection, table: &str| -> Result { Ok(conn.query_row(&format!("select count(*) from s{shard}.{table}"), [], |r| r.get(0))?) }; - for table in ["releases", "files", "segments"] { + for table in ["releases", "files"] { let (a, b) = (count(&old, table)?, count(&new, table)?); if a != b { bail!("shard {shard}: {table} has {b} rows in the copy, {a} in the original; the original was kept"); } } - if copied != count(&new, "segments")? { + let schema = format!("s{shard}"); + let (a, b) = (store::article_count(&old, &schema)?, store::article_count(&new, &schema)?); + if a != b { + bail!("shard {shard}: {b} articles in the copy, {a} in the original; the original was kept"); + } + if copied != b { bail!("shard {shard}: some articles came out as duplicates; the original was kept"); } @@ -284,13 +401,65 @@ mod tests { ids.into_iter().map(|id| (id, store::articles(&conn, id).unwrap())).collect() } - #[test] - fn compacting_drops_single_use_domains_and_keeps_every_nzb() { - let dir = tempfile::tempdir().unwrap(); - let main = dir.path().join("atlas.db"); - db::create_db_at(&main).unwrap(); + /// articles over every shard, loose rows and blobs + fn article_total(main: &Path) -> i64 { + store::shard_paths(main).iter().map(|p| store::article_count(&db::open_at(p).unwrap(), "main").unwrap()).sum() + } + + /// segment rows over every shard (articles not sealed into a blob) + fn loose(main: &Path) -> i64 { + store::shard_paths(main) + .iter() + .map(|p| { + db::open_at(p).unwrap().query_row("select count(*) from segments", [], |r| r.get::<_, i64>(0)).unwrap() + }) + .sum() + } + + fn domains(main: &Path) -> i64 { + let conn = db::open_with_shards(main).unwrap(); + let sql = format!( + "select sum(c) from ({})", + store::each_shard(|i| format!("select count(*) as c from s{i}.domains")) + ); + conn.query_row(&sql, [], |r| r.get(0)).unwrap() + } + + /// every blob's segments, checked against the domains of their shard + fn blob_segs_with_known_domains(main: &Path) -> Vec { + let mut all = Vec::new(); + for path in store::shard_paths(main) { + let conn = db::open_at(&path).unwrap(); + let ids: std::collections::HashSet = conn + .prepare("select id from domains") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + let blobs: Vec> = conn + .prepare("select blob from files where blob is not null") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + for b in blobs { + for seg in crate::blob::decode(&b).unwrap() { + assert!(seg.domain == 0 || ids.contains(&seg.domain), "{seg:?} points at a missing domain"); + all.push(seg); + } + } + } + all + } - // releases over several groups: a shared domain, and made up ones per article + /// what the conversion left, from before locals were packed by shape: 40 + /// releases over several groups, 6 articles each, three with the shared + /// ngPost domain (their locals stored as text) and three with a made up + /// domain each, every domain in the table + fn legacy_fixture(main: &Path) { + db::create_db_at(main).unwrap(); let releases: Vec = (0..40) .map(|r| Release { name: format!("Rel.{r}"), @@ -298,7 +467,7 @@ mod tests { articles: (1..=6) .map(|p| Article { message_id: if p % 2 == 0 { - format!("<{:032x}@ngPost>", r * 10 + p) + format!("") } else { format!("") }, @@ -313,10 +482,9 @@ mod tests { ..Default::default() }) .collect(); - store::save(&main, &releases).unwrap(); + store::save(main, &releases).unwrap(); - // what the conversion left: every domain in the table, made up ones too - for path in store::shard_paths(&main) { + for path in store::shard_paths(main) { let conn = db::open_at(&path).unwrap(); let whole: Vec<(i64, Vec)> = conn .prepare("select file_id, local from segments where domain = 0") @@ -330,29 +498,57 @@ mod tests { let (part, suffix) = store::split_message_id(&id).unwrap(); conn.execute("insert or ignore into domains (suffix) values (?)", [suffix]).unwrap(); let d: i64 = conn.query_row("select id from domains where suffix = ?", [suffix], |r| r.get(0)).unwrap(); + // the old packing: anything but hex as text + let mut text = vec![0u8]; + text.extend_from_slice(part.as_bytes()); conn.execute( "update segments set local = ?, domain = ? where file_id = ? and local = ? and domain = 0", - params![store::pack_local(part), d, file_id, local], + params![text, d, file_id, local], + ) + .unwrap(); + } + let packed: Vec<(i64, Vec, i64)> = conn + .prepare("select file_id, local, domain from segments where local >= x'01'") + .unwrap() + .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + for (file_id, local, domain) in packed { + let mut text = vec![0u8]; + text.extend_from_slice(store::unpack_local(&local).as_bytes()); + conn.execute( + "update segments set local = ? where file_id = ? and local = ? and domain = ?", + params![text, file_id, local, domain], ) .unwrap(); } } - let domains = |main: &Path| -> i64 { - let conn = db::open_with_shards(main).unwrap(); - let sql = format!( - "select sum(c) from ({})", - store::each_shard(|i| format!("select count(*) as c from s{i}.domains")) - ); - conn.query_row(&sql, [], |r| r.get(0)).unwrap() - }; - assert_eq!(domains(&main), 120 + 5, "every made up domain has a row, ngPost one per shard used"); + assert_eq!(domains(main), 120 + 5, "every made up domain has a row, ngPost one per shard used"); + } + + #[test] + fn compacting_drops_single_use_domains_repacks_seals_and_keeps_every_nzb() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); let before = all_articles(&main); + let count = article_total(&main); + assert_eq!(count, 240); let shrunk = run(&main, &|_| {}).unwrap(); assert_eq!(shrunk.domains_dropped, 120); assert_eq!(domains(&main), shrunk.domains_kept); assert!(shrunk.domains_kept <= 5); assert_eq!(all_articles(&main), before, "every NZB reads back the same"); + assert_eq!(article_total(&main), count); + assert_eq!(loose(&main), 0, "every file was due (complete), so all are sealed"); + let segs = blob_segs_with_known_domains(&main); + assert_eq!(segs.len() as i64, count); + for seg in segs.iter().filter(|s| s.domain != 0) { + assert_eq!(seg.local, store::repack(&seg.local), "packed the current way"); + assert_ne!(seg.local[0], 0, "not text"); + } for path in store::shard_paths(&main) { assert!(!with_suffix(&path, "precompact").exists(), "originals removed once all are done"); let mode: String = db::open_at(&path).unwrap().query_row("pragma journal_mode", [], |r| r.get(0)).unwrap(); @@ -376,4 +572,105 @@ mod tests { store::save(&main, &[more]).unwrap(); assert_eq!(all_articles(&main), before, "an article already there isnt saved twice"); } + + /// the file of release `name` in its group's shard: (shard path, file id) + fn file_of(main: &Path, name: &str, group: &str) -> (PathBuf, i64) { + let path = store::shard_path(main, store::shard_of(group)); + let id = db::open_at(&path) + .unwrap() + .query_row( + "select f.id from files f join releases r on r.id = f.release_id where r.name = ? and r.group_name = ?", + [name, group], + |r| r.get(0), + ) + .unwrap(); + (path, id) + } + + #[test] + fn compacting_sealed_shards_again_keeps_every_nzb() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}).unwrap(); + assert_eq!(loose(&main), 0); + + // late articles for a sealed file, under a domain only one of them + // ends up using (the first two are stored whole), the file untouched + // long enough to seal again + let late = Release { + name: "Rel.1".into(), + group: "alt.binaries.g1".into(), + articles: (7..=9) + .map(|p| Article { + message_id: format!(""), + filename: Some("f.rar".into()), + part: Some(p), + total_parts: Some(6), + bytes: 20, + ..Default::default() + }) + .collect(), + ..Default::default() + }; + store::save(&main, &[late]).unwrap(); + let (path, late_file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + { + let conn = db::open_at(&path).unwrap(); + let late_domain: i64 = conn + .query_row( + "select count(*) from segments s join domains d on d.id = s.domain where d.suffix = '@Late>'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(late_domain, 1, "one row under the new domain, two whole"); + conn.execute("update files set touched_at = 0 where id = ?", [late_file]).unwrap(); + } + + // a domain only a sealed blob uses, once + let (path, lonely_file) = file_of(&main, "Rel.2", "alt.binaries.g2"); + { + let conn = db::open_at(&path).unwrap(); + conn.execute("insert into domains (suffix) values ('@Lonely>')", []).unwrap(); + let lonely = conn.last_insert_rowid(); + let blob: Vec = + conn.query_row("select blob from files where id = ?", [lonely_file], |r| r.get(0)).unwrap(); + let mut segs = crate::blob::decode(&blob).unwrap(); + segs.push(Seg { part: Some(7), bytes: 30, domain: lonely, local: store::pack_local("solo7") }); + conn.execute("update files set blob = ? where id = ?", params![crate::blob::encode(&segs), lonely_file]) + .unwrap(); + } + + let before = all_articles(&main); + let ids: Vec<&str> = before.iter().flat_map(|(_, rows)| rows.iter().map(|r| r.message_id.as_str())).collect(); + for id in ["", "", "", ""] { + assert!(ids.contains(&id), "{id} reads back before compacting"); + } + let count = article_total(&main); + assert_eq!(count, 240 + 4); + + let shrunk = run(&main, &|_| {}).unwrap(); + assert_eq!(shrunk.domains_dropped, 2, "@Late> and @Lonely>"); + assert_eq!(all_articles(&main), before, "every NZB reads back the same"); + assert_eq!(article_total(&main), count); + assert_eq!(loose(&main), 0, "the late rows are sealed in with the blob"); + assert_eq!(blob_segs_with_known_domains(&main).len() as i64, count); + } + + #[test] + fn a_corrupt_blob_stops_compacting_and_keeps_the_original() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}).unwrap(); + let (path, file) = file_of(&main, "Rel.3", "alt.binaries.g3"); + db::open_at(&path).unwrap().execute("update files set blob = x'00' where id = ?", [file]).unwrap(); + + let err = run(&main, &|_| {}).unwrap_err(); + assert!(format!("{err:#}").contains("corrupt"), "{err:#}"); + let blob: Vec = + db::open_at(&path).unwrap().query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + assert_eq!(blob, vec![0], "the original is still in place"); + } } diff --git a/src/store.rs b/src/store.rs index a309899f..0007c58f 100644 --- a/src/store.rs +++ b/src/store.rs @@ -334,8 +334,6 @@ pub(crate) fn unpack_local(blob: &[u8]) -> String { } /// a local packed the current way, whatever way it was packed before -// not called yet: compact uses it to rewrite old rows -#[allow(dead_code)] pub(crate) fn repack(local: &[u8]) -> Vec { pack_local(&unpack_local(local)) } @@ -660,18 +658,21 @@ pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) if !has_rows || negative { continue; } - let expected: Option = r.get(1)?; let seen: Vec = r.get(2)?; - let touched: Option = r.get(3)?; - let sealed: bool = r.get(4)?; - let complete = !sealed && expected.is_some_and(|e| is_exactly(&seen, e)); - if complete || touched.is_none_or(|t| t < now - SEAL_AGE) { + if due(r.get(1)?, &seen, r.get(3)?, r.get(4)?, now) { ids.push(id); } } Ok((ids, last)) } +/// A file with rows is due to seal when it's complete and not sealed yet, or +/// untouched for `SEAL_AGE` (never touched since the upgrade counts as old). +pub(crate) fn due(expected: Option, seen: &[u8], touched: Option, sealed: bool, now: i64) -> bool { + let complete = !sealed && expected.is_some_and(|e| is_exactly(seen, e)); + complete || touched.is_none_or(|t| t < now - SEAL_AGE) +} + /// Blobs of sealed files, decoded once each, for checking late articles. #[derive(Default)] pub(crate) struct SealedCache { From 6fe0dac5735ddf08a02f55b08c64392ffe258220 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:02:14 -0500 Subject: [PATCH 022/159] auto_run_compact: compact every 24 hours from the indexer Compaction now tries every shard: a failed one keeps its original and the rest are swapped and their backups removed, then run reports each failure. Co-Authored-By: Claude Sonnet 5.5 --- src/bg_indexer.rs | 78 +++++++++++++++++++++++++++++++++++-- src/compact.rs | 90 ++++++++++++++++++++++++++++++++++++++----- src/config.rs | 8 ++++ src/store.rs | 11 ++++++ tests/auto_compact.rs | 67 ++++++++++++++++++++++++++++++++ 5 files changed, 240 insertions(+), 14 deletions(-) create mode 100644 tests/auto_compact.rs diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 48496b33..df7dad7a 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -27,6 +27,9 @@ const IDLE_RECHECK: Duration = Duration::from_secs(10); /// how often config.json is re-read while indexing const CONFIG_RELOAD: Duration = Duration::from_secs(5); +/// how often auto_run_compact compacts the database +pub const COMPACT_EVERY: Duration = Duration::from_secs(24 * 3600); + /// servers with a host and password, in priority order fn usable_servers(config: &crate::config::Config) -> Vec { config.servers.iter().filter(|s| !s.host.is_empty() && !s.password.is_empty()).cloned().collect() @@ -214,6 +217,15 @@ async fn nap(d: Duration, done: impl Fn() -> bool) { } } +/// how often auto_run_compact compacts (ATLAS_COMPACT_EVERY_SECS for tests) +fn compact_every() -> Duration { + std::env::var("ATLAS_COMPACT_EVERY_SECS") + .ok() + .and_then(|v| v.parse().ok()) + .map(Duration::from_secs) + .unwrap_or(COMPACT_EVERY) +} + fn settings_of(config: &Config) -> PassSettings { PassSettings { mode: config.index_mode.clone(), @@ -268,6 +280,8 @@ struct Scheduler { stats: Arc>, /// wind down (servers changed or stopping): finish current passes, start no new ones wind_down: AtomicBool, + /// the compaction interval passed (set together with `wind_down`) + compact_due: AtomicBool, passes: AtomicUsize, } @@ -521,6 +535,26 @@ async fn watch_config(sched: Arc, servers: Vec) { } } +/// With auto_run_compact: once the interval has passed since the last +/// compaction (or since the indexer started, when there was none), wind down so +/// `supervise` can compact. +async fn compact_timer(sched: Arc) { + let every = compact_every(); + let last = db::open_at(&paths::database()).ok().and_then(|conn| crate::store::get_meta(&conn, "last_compact").ok()); + let last = last.flatten().unwrap_or_else(|| now() as i64); + let due = UNIX_EPOCH + Duration::from_secs(last.max(0) as u64) + every; + // the last compaction is in the past, soo a fresh start still waits out the rest + while !sched.stopping() { + if SystemTime::now() >= due { + println!("compacting the database, indexing resumes after"); + sched.compact_due.store(true, Ordering::Relaxed); + sched.wind_down.store(true, Ordering::Relaxed); + return; + } + nap(Duration::from_secs(1), || sched.stopping()).await; + } +} + /// status.json / stats.json once a second for the menu and dashboard /// (plus a timing breakdown every 30s with ATLAS_PROFILE) async fn report(sched: Arc) { @@ -535,14 +569,15 @@ async fn report(sched: Arc) { } } -/// Index with this set of servers until stopping or the config needs a rebuild. +/// Index with this set of servers until stopping, the config needs a rebuild +/// or a compaction is due (true). async fn run_servers( config: &Config, pool: Arc, states: RunStates, stats: Arc>, stop: Arc, -) { +) -> bool { let servers = usable_servers(config); let groups = config.tracked_groups(); let plan = plan_workers(config); @@ -569,6 +604,7 @@ async fn run_servers( failed: Mutex::new(HashMap::new()), stats, wind_down: AtomicBool::new(false), + compact_due: AtomicBool::new(false), passes: AtomicUsize::new(0), }); @@ -576,7 +612,7 @@ async fn run_servers( Ok(conn) => shared_db(conn), Err(e) => { ui::error(&format!("couldnt open database: {e}")); - return; + return false; } }; @@ -592,6 +628,9 @@ async fn run_servers( } tasks.spawn(watch_config(sched.clone(), servers)); tasks.spawn(report(sched.clone())); + if config.auto_run_compact { + tasks.spawn(compact_timer(sched.clone())); + } // the workers and the config watcher all stop on `stopping()` while tasks.join_next().await.is_some() { @@ -602,6 +641,33 @@ async fn run_servers( checkpoint_stop.store(true, Ordering::Relaxed); let _ = tokio::task::spawn_blocking(move || checkpointer.join()).await; + sched.compact_due.load(Ordering::Relaxed) +} + +/// Compact every shard in this process (the indexer is wound down, so nothing +/// else writes), then note the time. Noted on failure too, soo a failing +/// compaction is tried again in 24 hours, not every minute. +async fn compact(config: &Config, stats: &Arc>) { + write_status(true, "compacting the database", &config.index_mode, false, "running", false, 0); + let main = paths::database(); + let started = Instant::now(); + let path = main.clone(); + let report = |msg: &str| println!("{msg}"); + let result = tokio::task::spawn_blocking(move || crate::compact::run(&path, &report)).await; + match result { + Ok(Ok(_)) => println!("compacted in {}", crate::dashboard::human_time(started.elapsed().as_secs() as i64)), + Ok(Err(e)) => { + ui::error(&format!("auto compaction failed, the originals were kept: {e:#}")); + stats.lock().unwrap().error_count += 1; + } + Err(e) => { + ui::error(&format!("auto compaction stopped: {e}")); + stats.lock().unwrap().error_count += 1; + } + } + if let Ok(conn) = db::open_at(&main) { + let _ = crate::store::set_meta(&conn, "last_compact", chrono::Utc::now().timestamp()); + } } async fn supervise(stop: Arc, stats: Arc>) { @@ -631,8 +697,12 @@ async fn supervise(stop: Arc, stats: Arc>) { continue; } - run_servers(&config, pool.clone(), states.clone(), stats.clone(), stop.clone()).await; + let compact_due = run_servers(&config, pool.clone(), states.clone(), stats.clone(), stop.clone()).await; pool.close().await; + + if compact_due && !stopping() { + compact(&config, &stats).await; + } } } diff --git a/src/compact.rs b/src/compact.rs index cb820f5f..515ef24f 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -12,7 +12,9 @@ //! //! Each shard's copy is checked (row counts, and a sample of NZBs against the //! original) before it replaces the original. The originals stay next to it -//! as `atlas.sN.precompact.db` until every shard is done, then they go. +//! as `atlas.sN.precompact.db` until every shard has had its turn, then they +//! go. A shard that fails keeps its original in place and the others carry +//! on; `run` then returns an error naming each failed shard. use std::path::{Path, PathBuf}; use std::time::Instant; @@ -63,23 +65,41 @@ pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync)) -> Result { } let started = Instant::now(); let mut total = Shrunk::default(); + let mut failed: Vec<(usize, String)> = Vec::new(); + // every shard gets its turn: one that fails keeps its original and doesnt + // stop the others for chunk in (0..SHARDS).collect::>().chunks(PARALLEL) { let results: Vec> = std::thread::scope(|s| { let jobs: Vec<_> = chunk.iter().map(|&shard| s.spawn(move || compact_shard(main, shard, progress))).collect(); jobs.into_iter().map(|j| j.join().unwrap_or_else(|_| Err(anyhow!("compacting a shard panicked")))).collect() }); - for r in results { - let r = r?; - total.before += r.before; - total.after += r.after; - total.domains_kept += r.domains_kept; - total.domains_dropped += r.domains_dropped; + for (&shard, r) in chunk.iter().zip(results) { + match r { + Ok(r) => { + total.before += r.before; + total.after += r.after; + total.domains_kept += r.domains_kept; + total.domains_dropped += r.domains_dropped; + } + Err(e) => failed.push((shard, format!("shard {shard}: {e:#}"))), + } + } + } + // the originals of the shards that were swapped can go. a failed shard + // keeps its original in place, and loses its half made copy (unless the + // shard isnt in place: the copy or the aside original may be all there is) + for shard in 0..SHARDS { + let path = store::shard_path(main, shard); + if !failed.iter().any(|(f, _)| *f == shard) { + remove_db(&with_suffix(&path, "precompact")); + } else if path.exists() { + remove_db(&with_suffix(&path, "compact")); } } - // every shard is done and checked: the originals can go - for shard in store::shard_paths(main) { - remove_db(&with_suffix(&shard, "precompact")); + if !failed.is_empty() { + let each: Vec = failed.into_iter().map(|(_, e)| e).collect(); + bail!("{} of {SHARDS} shards were not compacted, their originals were kept: {}", each.len(), each.join("; ")); } progress(&format!( "compacted {:.1}GB into {:.1}GB in {}: kept {} shared domains, dropped {} single use ones", @@ -673,4 +693,54 @@ mod tests { db::open_at(&path).unwrap().query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); assert_eq!(blob, vec![0], "the original is still in place"); } + + /// NZB rows of every release outside shard `skip`, by id + fn articles_outside(main: &Path, skip: usize) -> Vec<(i64, Vec)> { + let conn = db::open_with_shards(main).unwrap(); + let sql = (0..SHARDS) + .filter(|i| *i != skip) + .map(|i| format!("select id from s{i}.releases")) + .collect::>() + .join(" union all "); + let mut ids: Vec = + conn.prepare(&sql).unwrap().query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect(); + ids.sort(); + ids.into_iter().map(|id| (id, store::articles(&conn, id).unwrap())).collect() + } + + #[test] + fn a_failed_shard_doesnt_stop_the_others() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let (path, file) = file_of(&main, "Rel.3", "alt.binaries.g3"); + let bad = store::shard_of("alt.binaries.g3"); + let before = articles_outside(&main, bad); + assert!(!before.is_empty()); + db::open_at(&path).unwrap().execute("update files set blob = x'00' where id = ?", [file]).unwrap(); + + let err = run(&main, &|_| {}).unwrap_err(); + let msg = format!("{err:#}"); + assert!(msg.contains(&format!("shard {bad}:")) && msg.contains("corrupt"), "{msg}"); + + // the others were compacted (sealed) and their backups removed + let loose_in = |p: &Path| -> i64 { + db::open_at(p).unwrap().query_row("select count(*) from segments", [], |r| r.get(0)).unwrap() + }; + for (i, shard) in store::shard_paths(&main).iter().enumerate() { + assert!(!with_suffix(shard, "precompact").exists(), "no backup left over for shard {i}"); + assert!(!with_suffix(shard, "compact").exists(), "no half made copy left over for shard {i}"); + if i == bad { + assert!(loose_in(shard) > 0, "the failed shard still has its loose rows"); + } else { + assert_eq!(loose_in(shard), 0, "shard {i} was compacted and sealed"); + } + } + assert_eq!(articles_outside(&main, bad), before, "the others read back the same"); + + // the failed one is untouched + let blob: Vec = + db::open_at(&path).unwrap().query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + assert_eq!(blob, vec![0]); + } } diff --git a/src/config.rs b/src/config.rs index c32d6cbb..62b73dc1 100644 --- a/src/config.rs +++ b/src/config.rs @@ -134,6 +134,8 @@ pub struct Config { pub split_min_backlog: Option, /// groups indexed at the same time, None = worked out from the connections pub parallel_groups: Option, + /// compact the database every 24 hours from the indexer + pub auto_run_compact: bool, } impl Default for Config { @@ -150,6 +152,7 @@ impl Default for Config { request_size: None, split_min_backlog: None, parallel_groups: None, + auto_run_compact: false, } } } @@ -274,6 +277,7 @@ impl Config { .and_then(as_int) .and_then(|n| usize::try_from(n).ok()) .filter(|n| *n > 0), + auto_run_compact: v.get("auto_run_compact").and_then(Value::as_bool).unwrap_or(false), }; cfg.sort_servers(); @@ -455,6 +459,10 @@ pub fn save_config(cfg: &Config) -> io::Result<()> { out.insert("split_min_backlog".into(), json!(n)); } + if cfg.auto_run_compact { + out.insert("auto_run_compact".into(), json!(true)); + } + write_json(&Value::Object(out), private) } diff --git a/src/store.rs b/src/store.rs index 0007c58f..4d4d2fc2 100644 --- a/src/store.rs +++ b/src/store.rs @@ -223,6 +223,17 @@ pub fn set_next_seq(main: &Connection, seq: i64) -> Result<()> { Ok(()) } +/// A number kept in the main database's `meta` table, if it's there. +pub fn get_meta(conn: &Connection, key: &str) -> Result> { + conn.query_row("select value from main.meta where key = ?", [key], |r| r.get(0)).optional() +} + +/// Keep a number in the main database's `meta` table. +pub fn set_meta(conn: &Connection, key: &str, value: i64) -> Result<()> { + conn.execute("insert or replace into main.meta (key, value) values (?, ?)", params![key, value])?; + Ok(()) +} + // ---------------------------------------------------------------- message-ids const TEXT: u8 = 0; diff --git a/tests/auto_compact.rs b/tests/auto_compact.rs new file mode 100644 index 00000000..aa3a8687 --- /dev/null +++ b/tests/auto_compact.rs @@ -0,0 +1,67 @@ +//! With auto_run_compact on, the indexer stops for a compaction once the +//! interval has passed, records it, and goes back to indexing. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post, spawn_server}; + +#[test] +fn compacts_on_schedule_and_keeps_indexing() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + std::env::set_var("ATLAS_COMPACT_EVERY_SECS", "2"); + } + let posts: Vec = (1..=200) + .map(|n| post(n, &format!(r#""r{}.part{}.rar" yEnc (1/1)"#, n / 20, n % 20 + 1), 10, vec![])) + .collect(); + let port = spawn_server(Server::new(posts)); + let config = serde_json::json!({ + "usenet_servers": [{"host": "127.0.0.1", "username": "bob", "password": "secret", "port": port, "ssl": false, "connections": 2, "priority": 1}], + "groups": [GROUP], "index_mode": "backfill", "request_size": 50, "auto_run_compact": true + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + assert!(cfg.auto_run_compact); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(60); + let compacted = loop { + let conn = atlas::db::open_at(&main).unwrap(); + if let Some(t) = atlas::store::get_meta(&conn, "last_compact").unwrap() { + break t; + } + assert!(Instant::now() < deadline, "never compacted"); + std::thread::sleep(Duration::from_millis(200)); + }; + assert!(compacted > 0); + + // indexing goes on after it: everything gets indexed + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + if atlas::store::totals(&conn).unwrap().1 >= 200 { + break; + } + assert!(Instant::now() < deadline, "indexing didnt resume"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); +} From 19972c7617e0d25471a0f56358adc81a5eaf3d60 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:09:46 -0500 Subject: [PATCH 023/159] Auto compaction honors stop, joins writers first, keeps the start time compact::run takes a stop flag (checked per file, per phase, before the swap, and inside long SQL statements) and leaves the originals alone when stopped. The indexer's db writers are joined before compacting, a missing shard after compaction stops the indexer, and the 24 hour clock counts from the first start. Co-Authored-By: Claude Sonnet 5.5 --- Cargo.toml | 2 +- src/bg_indexer.rs | 43 +++++++++---- src/compact.rs | 138 +++++++++++++++++++++++++++++++++++++----- src/indexer.rs | 26 ++++++-- src/main.rs | 4 +- src/store.rs | 9 ++- tests/auto_compact.rs | 22 ++++++- 7 files changed, 208 insertions(+), 36 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8c75a32d..d624ed3c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,7 @@ getrandom = "0.3" indexmap = "2" ratatui = "0.30" regex = "1" -rusqlite = { version = "0.40", features = ["bundled"] } +rusqlite = { version = "0.40", features = ["bundled", "hooks"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] } rustyline = "18" serde = { version = "1", features = ["derive"] } diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index df7dad7a..f954d112 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -541,9 +541,9 @@ async fn watch_config(sched: Arc, servers: Vec) { async fn compact_timer(sched: Arc) { let every = compact_every(); let last = db::open_at(&paths::database()).ok().and_then(|conn| crate::store::get_meta(&conn, "last_compact").ok()); - let last = last.flatten().unwrap_or_else(|| now() as i64); + // no stored time: count from when the indexer started (rebuilds dont reset it) + let last = last.flatten().unwrap_or_else(|| sched.stats.lock().unwrap().start_time as i64); let due = UNIX_EPOCH + Duration::from_secs(last.max(0) as u64) + every; - // the last compaction is in the past, soo a fresh start still waits out the rest while !sched.stopping() { if SystemTime::now() >= due { println!("compacting the database, indexing resumes after"); @@ -641,21 +641,27 @@ async fn run_servers( checkpoint_stop.store(true, Ordering::Relaxed); let _ = tokio::task::spawn_blocking(move || checkpointer.join()).await; + // the last clone of the db waits for the writers (one may be sealing) + let _ = tokio::task::spawn_blocking(move || drop(db)).await; sched.compact_due.load(Ordering::Relaxed) } -/// Compact every shard in this process (the indexer is wound down, so nothing -/// else writes), then note the time. Noted on failure too, soo a failing -/// compaction is tried again in 24 hours, not every minute. -async fn compact(config: &Config, stats: &Arc>) { +/// Compact every shard in this process (the indexer is wound down and its +/// writers are gone, soo nothing else writes), then note the time. Noted on +/// failure too, soo a failing compaction is tried again in 24 hours, not every +/// minute. Not noted when it was stopped: that wasnt a failure, and it runs +/// again on the next start. False when a shard is missing afterwards. +async fn compact(config: &Config, stats: &Arc>, stop: &Arc) -> bool { write_status(true, "compacting the database", &config.index_mode, false, "running", false, 0); let main = paths::database(); let started = Instant::now(); - let path = main.clone(); + let (path, flag) = (main.clone(), stop.clone()); let report = |msg: &str| println!("{msg}"); - let result = tokio::task::spawn_blocking(move || crate::compact::run(&path, &report)).await; + let result = tokio::task::spawn_blocking(move || crate::compact::run(&path, &report, &flag)).await; + let stopped = stop.load(Ordering::Relaxed); match result { Ok(Ok(_)) => println!("compacted in {}", crate::dashboard::human_time(started.elapsed().as_secs() as i64)), + Ok(Err(e)) if stopped => println!("compaction stopped, the shards left are as they were: {e:#}"), Ok(Err(e)) => { ui::error(&format!("auto compaction failed, the originals were kept: {e:#}")); stats.lock().unwrap().error_count += 1; @@ -665,9 +671,24 @@ async fn compact(config: &Config, stats: &Arc>) { stats.lock().unwrap().error_count += 1; } } - if let Ok(conn) = db::open_at(&main) { + + // a swap that was cut half way leaves its shard missing, and a writer + // would make an empty one there + let missing: Vec = + crate::store::shard_paths(&main).iter().filter(|p| !p.exists()).map(|p| p.display().to_string()).collect(); + if !missing.is_empty() { + ui::error(&format!( + "shards missing after compacting, stopping the indexer. restore from the .precompact.db / .compact.db files next to them: {}", + missing.join(", ") + )); + stats.lock().unwrap().error_count += 1; + return false; + } + + if !stopped && let Ok(conn) = db::open_at(&main) { let _ = crate::store::set_meta(&conn, "last_compact", chrono::Utc::now().timestamp()); } + true } async fn supervise(stop: Arc, stats: Arc>) { @@ -700,8 +721,8 @@ async fn supervise(stop: Arc, stats: Arc>) { let compact_due = run_servers(&config, pool.clone(), states.clone(), stats.clone(), stop.clone()).await; pool.close().await; - if compact_due && !stopping() { - compact(&config, &stats).await; + if compact_due && !stopping() && !compact(&config, &stats, &stop).await { + break; } } } diff --git a/src/compact.rs b/src/compact.rs index 515ef24f..d4ec8ee0 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -17,6 +17,8 @@ //! on; `run` then returns an error naming each failed shard. use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Instant; use anyhow::{Context, Result, anyhow, bail}; @@ -58,8 +60,30 @@ pub struct Shrunk { pub domains_dropped: i64, } -/// Compact every shard of `main`. Returns the total before and after. -pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync)) -> Result { +/// the rows of a copying loop between looks at the stop flag +const STOP_EVERY: usize = 65_536; + +/// Stop with an error once `stop` is set. Compacting only ever leaves the +/// original shard alone until the swap, soo stopping anywhere before it loses +/// nothing: the half made copy goes and the shard stays as it was. +fn halt(stop: &AtomicBool, shard: usize) -> Result<()> { + if stop.load(Ordering::Relaxed) { + bail!("shard {shard}: stopped, the original was kept"); + } + Ok(()) +} + +/// Have SQLite give up long statements (a bulk insert, an index build) once +/// `stop` is set: they fail with an interrupt, like any other error. +fn interruptible(conn: &Connection, stop: &Arc) -> Result<()> { + let stop = stop.clone(); + conn.progress_handler(1000, Some(move || stop.load(Ordering::Relaxed)))?; + Ok(()) +} + +/// Compact every shard of `main`. Returns the total before and after. Once +/// `stop` is set, shards not done are left as they were (and an error says so). +pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync), stop: &Arc) -> Result { if !store::exists(main) { bail!("{} has no shards (convert it first)", main.display()); } @@ -69,9 +93,13 @@ pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync)) -> Result { // every shard gets its turn: one that fails keeps its original and doesnt // stop the others for chunk in (0..SHARDS).collect::>().chunks(PARALLEL) { + if stop.load(Ordering::Relaxed) { + failed.extend(chunk.iter().map(|&shard| (shard, format!("shard {shard}: stopped")))); + continue; + } let results: Vec> = std::thread::scope(|s| { let jobs: Vec<_> = - chunk.iter().map(|&shard| s.spawn(move || compact_shard(main, shard, progress))).collect(); + chunk.iter().map(|&shard| s.spawn(move || compact_shard(main, shard, progress, stop))).collect(); jobs.into_iter().map(|j| j.join().unwrap_or_else(|_| Err(anyhow!("compacting a shard panicked")))).collect() }); for (&shard, r) in chunk.iter().zip(results) { @@ -97,6 +125,9 @@ pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync)) -> Result { remove_db(&with_suffix(&path, "compact")); } } + if stop.load(Ordering::Relaxed) { + bail!("stopped, {} of {SHARDS} shards were left as they were", failed.len()); + } if !failed.is_empty() { let each: Vec = failed.into_iter().map(|(_, e)| e).collect(); bail!("{} of {SHARDS} shards were not compacted, their originals were kept: {}", each.len(), each.join("; ")); @@ -112,10 +143,16 @@ pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync)) -> Result { Ok(total) } -fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> Result { +fn compact_shard( + main: &Path, + shard: usize, + progress: &(dyn Fn(&str) + Sync), + stop: &Arc, +) -> Result { let path = store::shard_path(main, shard); let copy = with_suffix(&path, "compact"); let say = |msg: &str| progress(&format!("compacting shard {shard}: {msg}")); + halt(stop, shard)?; // fold the WAL in soo the original is whole on its own { @@ -130,6 +167,7 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> remove_db(©); store::create_shard(©)?; let mut conn = db::open_at(©)?; + interruptible(&conn, stop)?; conn.query_row("pragma journal_mode = off", [], |_| Ok(()))?; conn.execute_batch( "pragma synchronous = off; @@ -152,12 +190,18 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> }; let mut stmt = conn.prepare("select domain from old.segments")?; let mut rows = stmt.query([])?; + let mut n = 0usize; while let Some(r) = rows.next()? { used(r.get(0)?); + n += 1; + if n.is_multiple_of(STOP_EVERY) { + halt(stop, shard)?; + } } let mut stmt = conn.prepare("select id, blob from old.files where blob is not null")?; let mut rows = stmt.query([])?; while let Some(r) = rows.next()? { + halt(stop, shard)?; for seg in unseal(shard, r.get(0)?, &r.get::<_, Vec>(1)?)? { used(seg.domain); } @@ -165,6 +209,7 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> } let shared = |d: i64| d != 0 && uses.get(d as usize).is_some_and(|n| *n >= SHARED_AFTER); + halt(stop, shard)?; say("copying releases"); conn.execute_batch( "insert into releases select * from old.releases order by id; @@ -196,6 +241,7 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> // stored whole, the rest packed the current way, and files that are due // sealed into one blob on the way (sealing afterwards would leave the // copy full of the deleted rows' free pages) + halt(stop, shard)?; say(&format!("copying files and articles ({kept} shared domains, dropping {dropped}), sealing those due")); let now = chrono::Utc::now().timestamp(); let (mut copied, mut sealed) = (0i64, 0i64); @@ -215,12 +261,16 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> let mut tx = conn.transaction()?; let mut in_tx = 0; loop { + halt(stop, shard)?; let file = files.next()?; let id: Option = file.map(|f| f.get(0)).transpose()?; // rows whose file isnt there (purged, or past the last file) stay rows while let Some(row) = pending.take_if(|r| id.is_none_or(|id| r.file_id < id)) { insert_row(&tx, &row)?; (copied, in_tx) = (copied + 1, in_tx + 1); + if (copied as usize).is_multiple_of(STOP_EVERY) { + halt(stop, shard)?; + } pending = next_row(&mut rows, &shared)?; } let (Some(f), Some(id)) = (file, id) else { break }; @@ -278,19 +328,26 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> } say(&format!("sealed {sealed} files")); + halt(stop, shard)?; say("building indexes and the search index"); conn.execute_batch( "detach database old; insert into releases_fts(releases_fts) values('rebuild');", )?; drop(conn); - store::create_shard(©)?; + { + let conn = db::open_at(©)?; + interruptible(&conn, stop)?; + store::build_shard(&conn)?; + } // the check: same rows, same NZBs + halt(stop, shard)?; say("checking"); - check(&path, ©, shard, copied)?; + check(&path, ©, shard, copied, stop)?; - // swap + // swap: the last point to stop at + halt(stop, shard)?; let conn = db::open_at(©)?; conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(()))?; @@ -357,9 +414,10 @@ fn insert_row(conn: &Connection, r: &Row) -> Result<()> { /// The copy holds the same releases, files and articles (rows and inside /// blobs) as the original, and a sample of releases build the same NZBs from /// both. -fn check(original: &Path, copy: &Path, shard: usize, copied: i64) -> Result<()> { +fn check(original: &Path, copy: &Path, shard: usize, copied: i64, stop: &Arc) -> Result<()> { let attach = |path: &Path| -> Result { let conn = Connection::open_in_memory()?; + interruptible(&conn, stop)?; conn.execute("attach database ? as ?", params![path.to_string_lossy(), format!("s{shard}")])?; Ok(conn) }; @@ -387,6 +445,7 @@ fn check(original: &Path, copy: &Path, shard: usize, copied: i64) -> Result<()> let (Some(low), Some(high)) = (low, high) else { return Ok(()) }; let step = ((high - low) / CHECK_SAMPLE).max(1); for n in 0..CHECK_SAMPLE { + halt(stop, shard)?; let found: Option = old .query_row( &format!("select id from s{shard}.releases where id >= ? order by id limit 1"), @@ -408,6 +467,10 @@ mod tests { use super::*; use crate::parser::{Article, Release}; + fn no_stop() -> Arc { + Arc::new(AtomicBool::new(false)) + } + /// every release's NZB rows, by id fn all_articles(main: &Path) -> Vec<(i64, Vec)> { let conn = db::open_with_shards(main).unwrap(); @@ -556,7 +619,7 @@ mod tests { let count = article_total(&main); assert_eq!(count, 240); - let shrunk = run(&main, &|_| {}).unwrap(); + let shrunk = run(&main, &|_| {}, &no_stop()).unwrap(); assert_eq!(shrunk.domains_dropped, 120); assert_eq!(domains(&main), shrunk.domains_kept); assert!(shrunk.domains_kept <= 5); @@ -612,7 +675,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let main = dir.path().join("atlas.db"); legacy_fixture(&main); - run(&main, &|_| {}).unwrap(); + run(&main, &|_| {}, &no_stop()).unwrap(); assert_eq!(loose(&main), 0); // late articles for a sealed file, under a domain only one of them @@ -670,7 +733,7 @@ mod tests { let count = article_total(&main); assert_eq!(count, 240 + 4); - let shrunk = run(&main, &|_| {}).unwrap(); + let shrunk = run(&main, &|_| {}, &no_stop()).unwrap(); assert_eq!(shrunk.domains_dropped, 2, "@Late> and @Lonely>"); assert_eq!(all_articles(&main), before, "every NZB reads back the same"); assert_eq!(article_total(&main), count); @@ -683,11 +746,11 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let main = dir.path().join("atlas.db"); legacy_fixture(&main); - run(&main, &|_| {}).unwrap(); + run(&main, &|_| {}, &no_stop()).unwrap(); let (path, file) = file_of(&main, "Rel.3", "alt.binaries.g3"); db::open_at(&path).unwrap().execute("update files set blob = x'00' where id = ?", [file]).unwrap(); - let err = run(&main, &|_| {}).unwrap_err(); + let err = run(&main, &|_| {}, &no_stop()).unwrap_err(); assert!(format!("{err:#}").contains("corrupt"), "{err:#}"); let blob: Vec = db::open_at(&path).unwrap().query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); @@ -719,7 +782,7 @@ mod tests { assert!(!before.is_empty()); db::open_at(&path).unwrap().execute("update files set blob = x'00' where id = ?", [file]).unwrap(); - let err = run(&main, &|_| {}).unwrap_err(); + let err = run(&main, &|_| {}, &no_stop()).unwrap_err(); let msg = format!("{err:#}"); assert!(msg.contains(&format!("shard {bad}:")) && msg.contains("corrupt"), "{msg}"); @@ -743,4 +806,51 @@ mod tests { db::open_at(&path).unwrap().query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); assert_eq!(blob, vec![0]); } + + /// no shard is half done: the files are all there, the NZBs read back the + /// same, and nothing from the copying is left lying around + fn assert_untouched_or_whole(main: &Path, before: &[(i64, Vec)]) { + for shard in store::shard_paths(main) { + assert!(shard.exists(), "{} is still there", shard.display()); + assert!(!with_suffix(&shard, "precompact").exists(), "no backup left over"); + assert!(!with_suffix(&shard, "compact").exists(), "no half made copy left over"); + } + assert_eq!(all_articles(main), before, "every NZB reads back the same"); + } + + #[test] + fn a_stop_before_the_start_leaves_every_shard_as_it_was() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + let (rows, count) = (loose(&main), article_total(&main)); + + let stop = Arc::new(AtomicBool::new(true)); + let err = run(&main, &|_| {}, &stop).unwrap_err(); + assert!(format!("{err:#}").contains("stopped"), "{err:#}"); + assert_untouched_or_whole(&main, &before); + assert_eq!((loose(&main), article_total(&main)), (rows, count), "nothing was sealed or dropped"); + } + + #[test] + fn a_stop_while_copying_drops_the_copies_and_keeps_the_originals() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + + // the flag goes up as the first shard reports the copy of its files + let stop = Arc::new(AtomicBool::new(false)); + let flag = stop.clone(); + let progress = move |msg: &str| { + if msg.contains("copying files and articles") { + flag.store(true, Ordering::Relaxed); + } + }; + let err = run(&main, &progress, &stop).unwrap_err(); + assert!(format!("{err:#}").contains("stopped"), "{err:#}"); + assert!(stop.load(Ordering::Relaxed)); + assert_untouched_or_whole(&main, &before); + } } diff --git a/src/indexer.rs b/src/indexer.rs index af3dfca4..882b2b26 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -119,6 +119,20 @@ const MAX_BATCH: usize = 8; pub struct Db { conn: Arc>, saves: Vec>, + /// last field: dropping the final clone closes the queues above, then waits + /// for the writer threads to finish what they were doing + _writers: Arc, +} + +/// The writer threads, joined when dropped. +struct Writers(Vec>); + +impl Drop for Writers { + fn drop(&mut self) { + for writer in self.0.drain(..) { + let _ = writer.join(); + } + } } struct SaveJob { @@ -127,22 +141,22 @@ struct SaveJob { } /// `conn` is the main database. The writer threads end once every clone of -/// the `Db` is gone. +/// the `Db` is gone, and the last clone to go waits for them. pub fn shared_db(conn: Connection) -> Db { let main = conn.path().map(std::path::PathBuf::from).unwrap_or_else(crate::paths::database); let ids = Arc::new(crate::store::Ids::new(&main)); - let saves = (0..crate::store::SHARDS) + let (saves, writers): (Vec<_>, Vec<_>) = (0..crate::store::SHARDS) .map(|shard| { let (saves, jobs) = std::sync::mpsc::channel(); let (path, ids) = (crate::store::shard_path(&main, shard), ids.clone()); - std::thread::Builder::new() + let handle = std::thread::Builder::new() .name(format!("atlas-db-writer-{shard}")) .spawn(move || writer(shard, &path, &ids, jobs)) .expect("couldnt start a db writer"); - saves + (saves, handle) }) - .collect(); - Db { conn: Arc::new(Mutex::new(conn)), saves } + .unzip(); + Db { conn: Arc::new(Mutex::new(conn)), saves, _writers: Arc::new(Writers(writers)) } } fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: std::sync::mpsc::Receiver) { diff --git a/src/main.rs b/src/main.rs index 9c9697a7..a4086cbc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -60,7 +60,9 @@ fn run_compact() -> i32 { println!("stop indexing first"); return 1; } - match compact::run(&paths::database(), &|msg| println!("{msg}")) { + // nothing sets it: only the indexer stops a compaction early + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + match compact::run(&paths::database(), &|msg| println!("{msg}"), &stop) { Ok(_) => 0, Err(e) => { println!("couldnt compact: {e:#}"); diff --git a/src/store.rs b/src/store.rs index 4d4d2fc2..ee6148bb 100644 --- a/src/store.rs +++ b/src/store.rs @@ -100,7 +100,12 @@ pub fn create_main(conn: &Connection) -> Result<()> { /// A shard's tables, if missing. pub fn create_shard(path: &Path) -> Result<()> { - let conn = db::open_at(path)?; + build_shard(&db::open_at(path)?) +} + +/// `create_shard` on a connection the caller opened (and may have set up to +/// be interrupted). +pub fn build_shard(conn: &Connection) -> Result<()> { conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; conn.execute_batch( " @@ -166,7 +171,7 @@ pub fn create_shard(path: &Path) -> Result<()> { insert or ignore into meta (key, value) values ('releases', 0), ('articles', 0); ", )?; - migrate_shard(&conn) + migrate_shard(conn) } /// Columns a shard made before sealing lacks: `files.touched_at` (when diff --git a/tests/auto_compact.rs b/tests/auto_compact.rs index aa3a8687..a6cdeb50 100644 --- a/tests/auto_compact.rs +++ b/tests/auto_compact.rs @@ -1,10 +1,15 @@ //! With auto_run_compact on, the indexer stops for a compaction once the //! interval has passed, records it, and goes back to indexing. //! +//! Unix only: it tells the rewrite by the shard files' inodes. +//! //! One test, and the environment is set before any thread starts. +#![cfg(unix)] + mod common; +use std::os::unix::fs::MetadataExt; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; @@ -32,6 +37,12 @@ fn compacts_on_schedule_and_keeps_indexing() { std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); atlas::db::create_db().unwrap(); + let main = home.path().join("atlas.db"); + let shards = atlas::store::shard_paths(&main); + assert!(shards.iter().all(|p| p.exists()), "create_db made the shards"); + let inodes = || shards.iter().map(|p| std::fs::metadata(p).unwrap().ino()).collect::>(); + let before = inodes(); + let stop = Arc::new(AtomicBool::new(false)); let cfg = atlas::config::load_config().unwrap(); assert!(cfg.auto_run_compact); @@ -40,7 +51,6 @@ fn compacts_on_schedule_and_keeps_indexing() { std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) }; - let main = home.path().join("atlas.db"); let deadline = Instant::now() + Duration::from_secs(60); let compacted = loop { let conn = atlas::db::open_at(&main).unwrap(); @@ -51,6 +61,16 @@ fn compacts_on_schedule_and_keeps_indexing() { std::thread::sleep(Duration::from_millis(200)); }; assert!(compacted > 0); + // last_compact is noted on failure too: the compaction really ran when + // every shard is a new file (compacting writes a copy and swaps it in), + // and none of the copying is left lying around + assert!(inodes().iter().zip(&before).all(|(now, was)| now != was), "every shard was rewritten"); + for shard in &shards { + for suffix in ["compact", "precompact"] { + let stem = shard.file_stem().unwrap().to_string_lossy().into_owned(); + assert!(!shard.with_file_name(format!("{stem}.{suffix}.db")).exists()); + } + } // indexing goes on after it: everything gets indexed let deadline = Instant::now() + Duration::from_secs(60); From 1a8b277b156e91d4f61db81262f7ce451d0ede06 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:14:43 -0500 Subject: [PATCH 024/159] Document split backfill, sealed files, packed message-ids, auto_run_compact Co-Authored-By: Claude Haiku 4.5 --- README.md | 16 +++++++++++++++- config.example.json | 1 + 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e8b3ff2f..6368afc9 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,8 @@ On first run, Atlas asks for one server (host, username, password, and port) and | `api_host` | `127.0.0.1` | Address the Newznab API listens on. Use `0.0.0.0` to reach it from other machines. | | `api_port` | `9090` | Newznab API port. | | `api_key` | generated | Newznab API key. Atlas creates it on first start and stores it here. | +| `split_min_backlog` | `10000000` | Article numbers of backfill left before a group's backfill is split into day chunks that every server carrying the group can take. | +| `auto_run_compact` | `false` | Compact the database every 24 hours; indexing pauses while it runs. | Atlas keeps any other keys you add to the file when it saves it. @@ -235,11 +237,17 @@ Start the indexer from the main menu with option 1. The indexer runs as a backgr | `backfill` | Indexes backward from the newest article only. | | `live` | Indexes forward from the newest article only and ignores older posts. | +### Splitting big groups + +When a group's backfill exceeds `split_min_backlog` article numbers and the group is carried by two or more indexing servers, Atlas splits its backfill into day-sized chunks. Chunks are stored in the main database as tasks that any server carrying the group can claim. Idle workers on any server take the newest chunk, while live indexing stays on the group's home server. The stats dashboard shows split group progress on the backfill page. + ### How the database is stored Atlas splits releases and their articles over 8 database files next to `atlas.db`, named `atlas.s0.db` to `atlas.s7.db`, by group. Each file has its own writer thread, so the 8 save in parallel, and slices that arrive while a writer is busy are saved together in one transaction. `atlas.db` keeps the per-group cursors. -Articles are stored compactly, at about a quarter of the space of the old layout: each file of a release is stored once with the subject its NZB uses, and each article is a short row with its message ID, part number, and size. Message IDs share their domain and store hex IDs as bytes. NZBs come out exactly as before. +Articles are stored compactly, at about a quarter of the space of the old layout: each file of a release is stored once with the subject its NZB uses, and each article is a short row with its message ID, part number, and size. Message ID locals are packed by alphabet using specialized encodings (hex at half the size for hexadecimal locals, base-N encoding for other alphabets), and domains are shared. NZBs come out exactly as before. + +Files that are complete, or untouched for three days, are sealed into one compressed zstd blob. Sealed files reduce storage further and improve query performance on old articles. Shard writers seal files online, processing up to 2,000 files per 100 milliseconds. The `--compact` command seals every file due in its pass and re-encodes message-IDs across the whole database. A release ID tells Atlas which file holds the release, and IDs keep counting up across all 8 files in the order releases are added, so the newest releases still come first. @@ -256,6 +264,12 @@ The menu shows the progress meanwhile, and searches don't work until the convers Release IDs change in the conversion, so NZB links that Prowlarr or your apps saved before it no longer work. Search again to get the new ones. +### Compacting a database + +The `--compact` command rewrites every shard into a fresh database file while the indexer is stopped. It re-encodes message-IDs using the current packing scheme and seals every file due to be sealed. The copy has no free space in it, which reduces the total database size. Expect the database to shrink substantially after compacting for the first time (rough estimate from the spec: 138 GB to 60 GB). Each shard's copy is verified before replacing the original; if any shard fails, its original is kept and the operation is retried in 24 hours. + +With `auto_run_compact` enabled, Atlas compacts the database automatically every 24 hours: indexing pauses while the operation runs, and resumes when done. Stop or quit commands are honored mid-compaction. If a shard fails, it is retried in 24 hours. + A group that has caught up rests for 10 seconds before Atlas checks it again. Atlas parks a group that fails 3 times in a row for 5 minutes. Stopping the indexer takes about a second. Atlas drops any requests still in flight and closes their connections instead of reusing them. A pass that didn't finish leaves its cursor where it was, so Atlas indexes that range again on the next start. diff --git a/config.example.json b/config.example.json index 8ec95fbc..1e2d8e56 100644 --- a/config.example.json +++ b/config.example.json @@ -42,6 +42,7 @@ "alt.binaries.boneless" ], "index_mode": "backfill", + "auto_run_compact": false, "api_port": 9090, "api_host": "0.0.0.0" } From ad0f1712200c977aadf63f4fb4580a14c326e10d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:15:19 -0500 Subject: [PATCH 025/159] README: tighten split backfill, sealing and compaction wording Co-Authored-By: Claude Opus 5.5 --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6368afc9..30462870 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ Start the indexer from the main menu with option 1. The indexer runs as a backgr ### Splitting big groups -When a group's backfill exceeds `split_min_backlog` article numbers and the group is carried by two or more indexing servers, Atlas splits its backfill into day-sized chunks. Chunks are stored in the main database as tasks that any server carrying the group can claim. Idle workers on any server take the newest chunk, while live indexing stays on the group's home server. The stats dashboard shows split group progress on the backfill page. +When two or more indexing servers carry a group and its backfill has more than `split_min_backlog` article numbers left, Atlas splits the rest of its history into UTC day chunks. A worker with nothing of its own to do claims the newest pending chunk on any server that carries the group, so idle connections help with big groups. Live indexing stays on the group's home server. The Backfill page of the stats dashboard shows split groups and their day chunks. ### How the database is stored @@ -247,7 +247,7 @@ Atlas splits releases and their articles over 8 database files next to `atlas.db Articles are stored compactly, at about a quarter of the space of the old layout: each file of a release is stored once with the subject its NZB uses, and each article is a short row with its message ID, part number, and size. Message ID locals are packed by alphabet using specialized encodings (hex at half the size for hexadecimal locals, base-N encoding for other alphabets), and domains are shared. NZBs come out exactly as before. -Files that are complete, or untouched for three days, are sealed into one compressed zstd blob. Sealed files reduce storage further and improve query performance on old articles. Shard writers seal files online, processing up to 2,000 files per 100 milliseconds. The `--compact` command seals every file due in its pass and re-encodes message-IDs across the whole database. +Atlas seals each file that is complete, or untouched for three days, into one zstd-compressed blob, which takes far less space than its article rows. Each shard writer seals files between saves, up to 2,000 files or 100 milliseconds at a time. Articles that arrive after a file is sealed are stored as rows and merged into its NZB. The `--compact` command seals every file that's due and re-encodes message IDs across the whole database. A release ID tells Atlas which file holds the release, and IDs keep counting up across all 8 files in the order releases are added, so the newest releases still come first. @@ -266,9 +266,9 @@ Release IDs change in the conversion, so NZB links that Prowlarr or your apps sa ### Compacting a database -The `--compact` command rewrites every shard into a fresh database file while the indexer is stopped. It re-encodes message-IDs using the current packing scheme and seals every file due to be sealed. The copy has no free space in it, which reduces the total database size. Expect the database to shrink substantially after compacting for the first time (rough estimate from the spec: 138 GB to 60 GB). Each shard's copy is verified before replacing the original; if any shard fails, its original is kept and the operation is retried in 24 hours. +The `--compact` command rewrites every shard into a fresh database file while the indexer is stopped. It re-encodes message IDs with the current packing and seals every file that's due. The copy has no free space in it. Expect the first compaction to shrink the database a lot, roughly from 138 GB to 60 GB on a full database. Atlas checks each shard's copy before it replaces the original. If a shard fails, Atlas keeps its original and reports the error; the other shards are still compacted. -With `auto_run_compact` enabled, Atlas compacts the database automatically every 24 hours: indexing pauses while the operation runs, and resumes when done. Stop or quit commands are honored mid-compaction. If a shard fails, it is retried in 24 hours. +With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. A group that has caught up rests for 10 seconds before Atlas checks it again. Atlas parks a group that fails 3 times in a row for 5 minutes. From 6e0f770ed68ca6c3e8f7181191de28e505d02617 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:35:33 -0500 Subject: [PATCH 026/159] Date search skips missing numbers forward instead of guessing left A probe that landed on 100+ missing numbers sent the binary search left, pulling chunk starts far back and cutting chunk ends short, soo a day's articles past the gap were never fetched. Probes now scan forward in doubling windows (spreading out past 6,400 numbers) and only go left when nothing exists after the probe. Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 60 +++++++++++++++++------ tests/date_search.rs | 111 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 156 insertions(+), 15 deletions(-) diff --git a/src/nntp.rs b/src/nntp.rs index f2ca2367..604fb4a9 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1180,33 +1180,63 @@ impl Pool { Ok(self.posted_at(i, group, number, 100).await?.map(|(_, t)| t)) } + /// The first article in `from..end` on server `i` with its post time, and + /// whether every number between `from` and it was looked at. Missing + /// numbers are skipped forward in windows that double from 100 numbers up + /// to `SCAN_MAX`; past that the windows stay that size and spread out (each + /// starts twice as far from `from` as the last ended), soo a hole of + /// millions costs a few dozen small requests, at the price of maybe missing + /// an article between two windows. + async fn first_in(&self, i: usize, group: &str, from: u64, end: u64) -> Result> { + const LOOK: u64 = 100; + const SCAN_MAX: u64 = LOOK << 6; + let (mut at, mut size, mut whole) = (from, LOOK, true); + while at < end { + let look = size.min(end - at); + if let Some((n, t)) = self.posted_at(i, group, at, look).await? { + return Ok(Some((n, t, whole))); + } + let covered = at + look; + if size < SCAN_MAX { + at = covered; + size *= 2; + continue; + } + // the last window always ends at `end` + let next = (covered + (covered - from)).min(end.saturating_sub(SCAN_MAX)).max(covered); + whole &= next == covered; + at = next; + } + Ok(None) + } + /// The first article number in `low..=high` on server `i` posted at or after /// `when` (unix seconds), `high + 1` when there is none. A binary search over - /// small article requests (about 35 for a billion numbers, plus one to settle). Post dates are - /// only roughly in order, so the answer is approximate near the edges: - /// callers overlap their ranges. + /// small article requests (about 35 for a billion numbers, plus one to + /// settle); a probe that lands on missing numbers skips forward to the next + /// article. Post dates are only roughly in order, soo the answer is + /// approximate near the edges: callers overlap their ranges. pub async fn article_at(&self, i: usize, group: &str, low: u64, high: u64, when: i64) -> Result { - const LOOK: u64 = 100; let (mut lo, mut hi) = (low, high + 1); while lo < hi { let mid = lo + (hi - lo) / 2; - match self.posted_at(i, group, mid, LOOK).await? { - Some((n, t)) if t < when => lo = n + 1, - Some(_) => hi = mid, - // a gap: nothing to compare, keep searching to the left of it + match self.first_in(i, group, mid, hi).await? { + Some((n, t, _)) if t < when => lo = n + 1, + // every number from mid up to n is missing + Some((_, _, true)) => hi = mid, + // some numbers between mid and n werent looked at, n is an upper bound + Some((n, _, false)) => hi = n, + // nothing from mid on None => hi = mid, } } if lo > high { - return Ok(lo); + return Ok(high + 1); } // lo may be a number missing from the group: settle on the article that exists - let look = LOOK.min(high + 1 - lo); - Ok(match self.posted_at(i, group, lo, look).await? { - Some((n, _)) => n, - // nothing up to the end of the range - None if look == high + 1 - lo => high + 1, - None => lo, + Ok(match self.first_in(i, group, lo, high + 1).await? { + Some((n, _, _)) => n, + None => high + 1, }) } diff --git a/tests/date_search.rs b/tests/date_search.rs index 9ca54d79..882493de 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -68,3 +68,114 @@ fn a_day_chunk_indexes_that_day() { let conn = atlas::db::open_at(&main).unwrap(); assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); } + +/// posts `low..=high`, number n posted n - 1 hours after 2026-01-01 00:00 UTC, +/// minus the numbers in `gap` +fn with_gap(low: u64, high: u64, gap: std::ops::RangeInclusive) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (low..=high) + .filter(|n| !gap.contains(n)) + .map(|n| { + let when = start + chrono::Duration::hours(n as i64 - 1); + post_at(n, &format!(r#""p{n}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() +} + +/// unix seconds of the hour number `n` is posted at in `with_gap` +fn hour_of(n: u64) -> i64 { + chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap().timestamp() + (n as i64 - 1) * 3600 +} + +fn search(posts: Vec, low: u64, high: u64, when: i64) -> u64 { + let port = spawn_server(Server::new(posts)); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + pool.block_on(pool.pool.article_at(0, GROUP, low, high, when)).unwrap() +} + +#[test] +fn a_long_gap_at_the_midpoint_is_skipped_forward() { + // 1..=2000 with 900..=1199 missing: the first probe (1000) lands in the gap + let posts = || with_gap(1, 2000, 900..=1199); + assert_eq!(search(posts(), 1, 2000, hour_of(1500)), 1500, "after the gap"); + assert_eq!(search(posts(), 1, 2000, hour_of(1200)), 1200, "the first article after the gap"); + assert_eq!(search(posts(), 1, 2000, hour_of(1000)), 1200, "inside the gap: the next article"); + assert_eq!(search(posts(), 1, 2000, hour_of(800)), 800, "before the gap"); +} + +#[test] +fn a_long_gap_at_the_start_settles_on_the_first_article() { + // 1..=300 missing, the group's low says 1 + let posts = || with_gap(1, 1300, 1..=300); + assert_eq!(search(posts(), 1, 1300, hour_of(1) - 86_400), 301, "before everything: the first article"); + assert_eq!(search(posts(), 1, 1300, hour_of(700)), 700); +} + +#[test] +fn a_long_gap_at_the_end_is_high_plus_one() { + // the group's high says 2000, nothing after 1699 exists + let posts = || with_gap(1, 1699, 0..=0); + assert_eq!(search(posts(), 1, 2000, hour_of(1800)), 2001, "after everything: high + 1"); + assert_eq!(search(posts(), 1, 2000, hour_of(1650)), 1650); +} + +#[test] +fn a_hole_of_millions_is_crossed_in_few_requests() { + let server = Server::new(with_gap(1, 3_000_050, 51..=3_000_000)); + let port = spawn_server(server.clone()); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + let at = |n: u64| pool.block_on(pool.pool.article_at(0, GROUP, 1, 3_000_050, hour_of(n))).unwrap(); + + assert_eq!(at(40), 40); + assert_eq!(at(60), 3_000_001, "inside the hole: the first article after it"); + assert_eq!(at(3_000_020), 3_000_020); + let xovers = server.xovers.load(std::sync::atomic::Ordering::SeqCst); + assert!(xovers < 400, "{xovers} requests for three searches"); +} + +/// A day chunk whose day has 150 numbers missing in the middle still fetches +/// every article of that day. +#[test] +fn a_day_chunk_skips_a_gap_inside_the_day() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + + // one post every 2 minutes from 2026-01-01: day 1 is 1..=720, day 2 is + // 721..=1440, and 1050..=1199 are missing right where the search for the + // day's end first probes + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts: Vec = (1..=1440u64) + .filter(|n| !(1050..=1199).contains(n)) + .map(|n| { + let when = start + chrono::Duration::minutes((n as i64 - 1) * 2); + post_at(n, &format!(r#""p{n}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect(); + let port = spawn_server(Server::new(posts)); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + let day = + atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-02T00:00:00+00:00").unwrap().timestamp()); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let saved = + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})).unwrap(); + + // day 2 is 720 numbers minus the 150 missing, plus the hour before it + // (691..=720, 30 posts); nothing comes after 1440 + assert_eq!(saved.articles, 720 - 150 + 30); + let conn = atlas::db::open_at(&main).unwrap(); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); +} From 6f112d4387c06719e609b5c0ce5975c497176ca8 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:39:50 -0500 Subject: [PATCH 027/159] Writers seal what their saves completed, walk for stale files once a minute Every save tick used to scan 8,000 files rows and, on first start, seal every pre-upgrade file online. Now a writer seals the files its own saves completed (up to 50,000 remembered), walks the files table at most every SEAL_WALK_EVERY seconds, skips the tick while more saves are queued, and leaves files never touched since the upgrade to --compact. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/indexer.rs | 23 ++++- src/store.rs | 234 +++++++++++++++++++++++++++++++++++++++++-------- 3 files changed, 217 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 30462870..ce98428a 100644 --- a/README.md +++ b/README.md @@ -247,7 +247,7 @@ Atlas splits releases and their articles over 8 database files next to `atlas.db Articles are stored compactly, at about a quarter of the space of the old layout: each file of a release is stored once with the subject its NZB uses, and each article is a short row with its message ID, part number, and size. Message ID locals are packed by alphabet using specialized encodings (hex at half the size for hexadecimal locals, base-N encoding for other alphabets), and domains are shared. NZBs come out exactly as before. -Atlas seals each file that is complete, or untouched for three days, into one zstd-compressed blob, which takes far less space than its article rows. Each shard writer seals files between saves, up to 2,000 files or 100 milliseconds at a time. Articles that arrive after a file is sealed are stored as rows and merged into its NZB. The `--compact` command seals every file that's due and re-encodes message IDs across the whole database. +Atlas seals each file that is complete, or untouched for three days, into one zstd-compressed blob, which takes far less space than its article rows. Each shard writer seals the files its own saves completed between saves, up to 2,000 files or 100 milliseconds at a time, and looks through its shard for files untouched for three days once a minute. Writers leave files from before the upgrade alone; the first `--compact` seals those. Articles that arrive after a file is sealed are stored as rows and merged into its NZB. The `--compact` command seals every file that's due and re-encodes message IDs across the whole database. A release ID tells Atlas which file holds the release, and IDs keep counting up across all 8 files in the order releases are added, so the newest releases still come first. diff --git a/src/indexer.rs b/src/indexer.rs index 882b2b26..57284bc3 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -165,8 +165,17 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s let mut opened = db::open_at(path).and_then(|conn| db::tune_for_writing(&conn).map(|_| conn)); let mut store = crate::store::ShardWriter::new(shard); - - while let Ok(first) = jobs.recv() { + // a job taken off the queue to see if more were waiting + let mut next: Option = None; + + loop { + let first = match next.take() { + Some(job) => job, + None => match jobs.recv() { + Ok(job) => job, + Err(_) => break, + }, + }; let mut batch = vec![first]; while batch.len() < MAX_BATCH { match jobs.try_recv() { @@ -197,7 +206,15 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s // housekeeping between transactions if let Ok(conn) = &mut opened { let t = std::time::Instant::now(); - if saved { + // more slices waiting: saving them comes first + let waiting = match jobs.try_recv() { + Ok(job) => { + next = Some(job); + true + } + Err(_) => false, + }; + if saved && !waiting { let sealing = std::time::Instant::now(); if store.seal_some(conn, chrono::Utc::now().timestamp()).is_err() { LOAD.writer_seal_errors.fetch_add(1, Relaxed); diff --git a/src/store.rs b/src/store.rs index ee6148bb..1336b414 100644 --- a/src/store.rs +++ b/src/store.rs @@ -17,7 +17,7 @@ //! shard holds it. use std::collections::hash_map::Entry; -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::time::Instant; @@ -651,12 +651,13 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { Ok(segs.len()) } -/// The next `limit` files after `after_id`, and which of them to seal: ones -/// with rows that are complete and not sealed yet, or untouched for -/// `SEAL_AGE` (never touched since the upgrade counts as old; a sealed file -/// with late rows waits for this too). Files with a negative part number -/// never seal. Returns the ids and the last id looked at, for walking the -/// table `limit` files at a time: `last == after_id` means the end. +/// The next `limit` files after `after_id`, and which of them a writer +/// seals: ones with rows that are complete and not sealed yet, or untouched +/// for `SEAL_AGE` (a sealed file with late rows waits for this). Files never +/// touched since the upgrade are left to compaction, and files with a +/// negative part number never seal. Returns the ids and the last id looked +/// at, for walking the table `limit` files at a time: `last == after_id` +/// means the end. pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) -> Result<(Vec, i64)> { let mut stmt = conn.prepare_cached( "select f.id, f.expected, f.seen, f.touched_at, f.blob is not null, @@ -675,13 +676,32 @@ pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) continue; } let seen: Vec = r.get(2)?; - if due(r.get(1)?, &seen, r.get(3)?, r.get(4)?, now) { + let touched: Option = r.get(3)?; + if touched.is_some() && due(r.get(1)?, &seen, touched, r.get(4)?, now) { ids.push(id); } } Ok((ids, last)) } +/// A file a save just completed is still complete, not sealed and has rows +/// that can go in a blob. +fn still_due(conn: &Connection, file_id: i64, now: i64) -> Result { + conn.prepare_cached( + "select f.expected, f.seen, f.touched_at, f.blob is not null, + exists (select 1 from segments s where s.file_id = f.id), + exists (select 1 from segments s where s.file_id = f.id and s.part < 0) + from files f where f.id = ?", + )? + .query_row([file_id], |r| { + let (has_rows, negative): (bool, bool) = (r.get(4)?, r.get(5)?); + let seen: Vec = r.get(1)?; + Ok(has_rows && !negative && due(r.get(0)?, &seen, r.get(2)?, r.get(3)?, now)) + }) + .optional() + .map(|due| due.unwrap_or(false)) +} + /// A file with rows is due to seal when it's complete and not sealed yet, or /// untouched for `SEAL_AGE` (never touched since the upgrade counts as old). pub(crate) fn due(expected: Option, seen: &[u8], touched: Option, sealed: bool, now: i64) -> bool { @@ -719,8 +739,13 @@ impl SealedCache { pub struct ShardWriter { pub shard: usize, domains: Domains, - /// where the last seal tick stopped in the files table + /// files this writer's saves completed, oldest first, waiting to be sealed + completed: VecDeque, + completed_ids: HashSet, + /// where the last walk stopped in the files table seal_after: i64, + /// when the last walk ran (unix seconds) + walked_at: Option, } /// files sealed per writer tick at most @@ -729,46 +754,96 @@ pub const SEAL_PER_TICK: usize = 2_000; /// a seal tick stops after this long, so the writer gets back to saving pub const SEAL_BUDGET: std::time::Duration = std::time::Duration::from_millis(100); +/// a writer walks the files table for stale files at most this often (seconds) +pub const SEAL_WALK_EVERY: i64 = 60; + +/// completed files a writer keeps for sealing at most, the oldest go first +const COMPLETED_CAP: usize = 50_000; + impl ShardWriter { pub fn new(shard: usize) -> ShardWriter { - ShardWriter { shard, domains: Domains::default(), seal_after: 0 } + ShardWriter { + shard, + domains: Domains::default(), + completed: VecDeque::new(), + completed_ids: HashSet::new(), + seal_after: 0, + walked_at: None, + } + } + + fn remember_completed(&mut self, file_id: i64) { + if !self.completed_ids.insert(file_id) { + return; + } + if self.completed.len() >= COMPLETED_CAP + && let Some(oldest) = self.completed.pop_front() + { + self.completed_ids.remove(&oldest); + } + self.completed.push_back(file_id); } - /// Seal up to SEAL_PER_TICK files that are due, for at most SEAL_BUDGET, - /// walking the files table by id from where the last tick stopped. At the - /// end of the table it goes back to the start. A file that fails to seal - /// is counted and skipped. Not for use inside a save transaction. - /// Returns the files sealed. + /// Seal up to SEAL_PER_TICK files, for at most SEAL_BUDGET: first the + /// files this writer's saves completed, then, at most every + /// SEAL_WALK_EVERY seconds, the due files of a step through the files + /// table by id from where the last walk stopped (back to the start at the + /// end of the table). A file that fails to seal is counted and skipped. + /// Not for use inside a save transaction. Returns the files sealed. pub fn seal_some(&mut self, conn: &mut Connection, now: i64) -> Result { let started = Instant::now(); + let out_of_time = |done: usize| done > 0 && started.elapsed() >= SEAL_BUDGET; let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?; - let scan = SEAL_PER_TICK * 4; - let (mut ids, mut last) = sealable(&tx, self.seal_after, scan, now)?; - // nothing left after the cursor: start over from the first file - if last == self.seal_after && self.seal_after != 0 { - (ids, last) = sealable(&tx, 0, scan, now)?; - } - // past the cap, the next tick picks up after the last one sealed - if ids.len() > SEAL_PER_TICK { - ids.truncate(SEAL_PER_TICK); - last = ids[SEAL_PER_TICK - 1]; + let seal = |id: i64| match seal_file(&tx, id) { + Ok(segs) => Ok(usize::from(segs > 0)), + Err(e) => { + profile::LOAD.writer_seal_errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Err(e) + } + }; + let (mut sealed, mut done) = (0, 0); + + // what the last saves completed: oldest first, what doesnt fit waits for the next tick + while done < SEAL_PER_TICK && !out_of_time(done) { + let Some(id) = self.completed.pop_front() else { break }; + self.completed_ids.remove(&id); + done += 1; + if still_due(&tx, id, now)? { + sealed += seal(id).unwrap_or(0); + } } - let mut sealed = 0; - for (i, id) in ids.iter().enumerate() { - // out of time: the next tick picks up after the last one done - if i > 0 && started.elapsed() >= SEAL_BUDGET { - last = ids[i - 1]; - break; + + let walk = self.walked_at.is_none_or(|t| now - t >= SEAL_WALK_EVERY); + if walk && done < SEAL_PER_TICK && !out_of_time(done) { + self.walked_at = Some(now); + let scan = SEAL_PER_TICK * 4; + let (mut ids, mut last) = sealable(&tx, self.seal_after, scan, now)?; + // nothing left after the cursor: start over from the first file + if last == self.seal_after && self.seal_after != 0 { + (ids, last) = sealable(&tx, 0, scan, now)?; + } + // past the cap, the next walk picks up after the last one sealed + let room = SEAL_PER_TICK - done; + if ids.len() > room { + ids.truncate(room); + last = ids[room - 1]; } - match seal_file(&tx, *id) { - Ok(segs) => sealed += usize::from(segs > 0), - Err(_) => { - profile::LOAD.writer_seal_errors.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + for (i, id) in ids.iter().enumerate() { + // out of time: the next walk picks up after the last one done + if out_of_time(done) { + if i > 0 { + last = ids[i - 1]; + } else { + last = self.seal_after; + } + break; } + done += 1; + sealed += seal(*id).unwrap_or(0); } + self.seal_after = last; } tx.commit()?; - self.seal_after = last; Ok(sealed) } @@ -784,6 +859,8 @@ impl ShardWriter { let domains = &mut self.domains; // blobs of sealed files that get late articles, decoded once each let mut sealed = SealedCache::new(); + // files this save completed, for sealing once it's committed + let mut completed = Vec::new(); let tx = conn.transaction()?; let (mut new_releases, mut new_articles) = (0i64, 0i64); { @@ -850,6 +927,9 @@ impl ShardWriter { } if added.len() > before { put_file(&tx, &f)?; + if !f.sealed && f.expected.is_some_and(|e| is_exactly(&f.seen, e)) { + completed.push(f.id); + } } } profile::ARTICLES.add_since(t); @@ -879,6 +959,11 @@ impl ShardWriter { let t = Instant::now(); let r = tx.commit(); profile::COMMIT.add_since(t); + if r.is_ok() { + for id in completed { + self.remember_completed(id); + } + } r } } @@ -1507,8 +1592,81 @@ mod tests { conn.execute("update files set touched_at = ?", [now]).unwrap(); assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1, "only the complete file"); conn.execute("update files set touched_at = ?", [now - SEAL_AGE - 1]).unwrap(); - assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1, "the stale one, after wrapping around"); - assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 0); + assert_eq!(writer.seal_some(&mut conn, now + 1).unwrap(), 0, "no walk until SEAL_WALK_EVERY is up"); + let later = now + SEAL_WALK_EVERY; + assert_eq!(writer.seal_some(&mut conn, later).unwrap(), 1, "the stale one, after wrapping around"); + assert_eq!(writer.seal_some(&mut conn, later + SEAL_WALK_EVERY).unwrap(), 0); + } + + /// the fixture's release, saved by `writer` + fn save_with(writer: &mut ShardWriter, main: &Path, release: Release) { + let mut conn = db::open_at(&shard_path(main, writer.shard)).unwrap(); + writer.save(&mut conn, &Ids::new(main), [std::slice::from_ref(&release)]).unwrap(); + } + + #[test] + fn between_walks_a_writer_seals_the_files_its_saves_completed() { + let (_dir, main) = sealed_fixture(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + let mut writer = ShardWriter::new(shard); + let now: i64 = conn.query_row("select unixepoch()", [], |r| r.get(0)).unwrap(); + // the walk seals a.rar (complete), b.rar has 1 of 2 + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 1); + + // another writer completes b.rar: not this writer's, and no walk yet + let b2 = |id: &str| Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![Article { + message_id: id.into(), + filename: Some("b.rar".into()), + part: Some(2), + total_parts: Some(2), + bytes: 102, + ..Default::default() + }], + ..Default::default() + }; + save(&main, &[b2("")]).unwrap(); + assert_eq!(writer.seal_some(&mut conn, now + 1).unwrap(), 0, "not from this writer's saves"); + + // a file this writer's save completes seals on the next tick + let mut other = ShardWriter::new(shard); + let c = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![Article { + message_id: "".into(), + filename: Some("c.rar".into()), + part: Some(1), + total_parts: Some(1), + bytes: 5, + ..Default::default() + }], + ..Default::default() + }; + save_with(&mut other, &main, c); + assert_eq!(other.seal_some(&mut conn, now + 1).unwrap(), 2, "c.rar from its save, b.rar from its first walk"); + save_with(&mut writer, &main, b2("")); + let rows: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(rows, 1, "b.rar got a row, it's sealed and complete: waits to be stale"); + assert_eq!(writer.seal_some(&mut conn, now + 2).unwrap(), 0); + } + + #[test] + fn writers_leave_files_untouched_since_the_upgrade_to_compaction() { + let (_dir, main) = sealed_fixture(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + conn.execute("update files set touched_at = null", []).unwrap(); + let now: i64 = conn.query_row("select unixepoch()", [], |r| r.get(0)).unwrap(); + let mut writer = ShardWriter::new(shard); + assert_eq!(writer.seal_some(&mut conn, now).unwrap(), 0, "complete or not, a legacy file waits"); + assert_eq!(writer.seal_some(&mut conn, now + SEAL_WALK_EVERY).unwrap(), 0); + // compaction still takes them + assert!(due(Some(3), &[0b1110], None, false, now)); + assert!(due(Some(2), &[0b0010], None, false, now)); } #[test] From 3d7f317d5f4c6c1efae089a8de246cf4355d32d2 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:41:09 -0500 Subject: [PATCH 028/159] Stopping skips sealing and drops slices nobody waits for Writers are joined on shutdown, soo every queued save plus a seal tick per batch ran before the indexer could exit. A writer now skips sealing once its queue is closed, and drops queued slices whose pass is gone (their cursor didnt move, the headers get fetched again). Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 50 insertions(+), 6 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 57284bc3..6215863b 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -184,6 +184,12 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s } } LOAD.writer_queued.fetch_sub(batch.len() as u64, Relaxed); + // nobody waits for a slice whose pass was dropped (stopping): its + // cursor didnt move and its headers get fetched again, soo skip it + batch.retain(|job| !job.done.is_closed()); + if batch.is_empty() { + continue; + } let t = std::time::Instant::now(); let result = match &mut opened { @@ -206,15 +212,17 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s // housekeeping between transactions if let Ok(conn) = &mut opened { let t = std::time::Instant::now(); - // more slices waiting: saving them comes first - let waiting = match jobs.try_recv() { + // more slices waiting: saving them comes first. a closed queue + // means the indexer is stopping, it waits for this thread + let seal = match jobs.try_recv() { Ok(job) => { next = Some(job); - true + false } - Err(_) => false, + Err(std::sync::mpsc::TryRecvError::Empty) => saved, + Err(std::sync::mpsc::TryRecvError::Disconnected) => false, }; - if saved && !waiting { + if seal { let sealing = std::time::Instant::now(); if store.seal_some(conn, chrono::Utc::now().timestamp()).is_err() { LOAD.writer_seal_errors.fetch_add(1, Relaxed); @@ -231,7 +239,9 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s impl Db { /// Save one slice's releases. Returns once they are committed. Dropping - /// the future early leaves the slice queued: it still gets saved. + /// the future before the writer gets to the slice drops the slice too + /// (its pass didnt finish, soo the cursor didnt move past it); once the + /// writer has it, it gets saved. async fn save(&self, releases: Vec) -> Result<()> { // a slice is one group, soo one shard let Some(shard) = releases.first().map(|r| crate::store::shard_of(&r.group)) else { return Ok(()) }; @@ -919,4 +929,38 @@ mod tests { assert!(make_slices(6, 5, 100, false).is_empty()); assert_eq!(make_slices(u64::MAX - 1, u64::MAX, 10, false), vec![(u64::MAX - 1, u64::MAX)]); } + + #[test] + fn a_slice_nobody_waits_for_isnt_saved() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let shared = shared_db(db::open_at(&main).unwrap()); + let release = |name: &str| Release { + name: name.into(), + group: "alt.binaries.t".into(), + articles: vec![crate::parser::Article { message_id: format!("<{name}@x>"), ..Default::default() }], + ..Default::default() + }; + + // a pass that was dropped while stopping: nobody waits for its slice + let (done, gone) = tokio::sync::oneshot::channel(); + drop(gone); + crate::profile::LOAD.writer_queued.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let shard = crate::store::shard_of("alt.binaries.t"); + shared.saves[shard].send(SaveJob { releases: vec![release("dropped")], done }).unwrap(); + let rt = tokio::runtime::Builder::new_current_thread().build().unwrap(); + rt.block_on(shared.save(vec![release("kept")])).unwrap(); + drop(shared); + + let conn = db::open_with_shards(&main).unwrap(); + let names: Vec = conn + .prepare("select name from releases") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .map(|r| r.unwrap()) + .collect(); + assert_eq!(names, vec!["kept".to_string()]); + } } From 6a5a776aff6a798efa14de788bb38a89eab9f780 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:43:46 -0500 Subject: [PATCH 029/159] Idle workers only take chunks of tracked groups in a backfilling mode A group taken out of config.json, or indexed live only, kept its pending day chunks and idle workers still claimed and fetched them. Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 36 +++++++++++++++++--- src/indexer.rs | 14 +++++--- tests/chunk_claims.rs | 78 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 119 insertions(+), 9 deletions(-) create mode 100644 tests/chunk_claims.rs diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index f954d112..c19443c9 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -438,8 +438,17 @@ impl Scheduler { } } -/// A day chunk of any split group for an idle worker on `server`: the newest -/// one pending, among the groups this server hasnt said it lacks. +/// The groups whose day chunks a worker may take: ones still in config.json, +/// except `skip`, and none when the mode never backfills. +fn chunk_groups(mode: &str, groups: &[String], skip: &HashSet) -> HashSet { + if mode == "live" { + return HashSet::new(); + } + groups.iter().filter(|g| !skip.contains(*g)).cloned().collect() +} + +/// A day chunk of a split group for an idle worker on `server`: the newest +/// one pending, among the tracked groups this server hasnt said it lacks. async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option<(String, i64)> { // a server resting after a failure takes no chunks either if !sched.ctx.pool.indexing_tier().contains(&server) { @@ -447,14 +456,19 @@ async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option<(String } let host = sched.ctx.pool.host(server); - let skip: Vec = { + let skip: HashSet = { let now = Instant::now(); let mut skip = sched.skip.lock().unwrap(); skip.retain(|_, until| until.is_none_or(|t| t > now)); skip.keys().filter(|(_, s)| *s == server).map(|(g, _)| g.clone()).collect() }; + let mode = sched.settings.read().unwrap().mode.clone(); + let groups = chunk_groups(&mode, &sched.groups.read().unwrap(), &skip); + if groups.is_empty() { + return None; + } - match crate::indexer::claim_chunk(db, host, skip).await { + match crate::indexer::claim_chunk(db, host, groups).await { Ok(chunk) => chunk, Err(e) => { ui::error(&format!("couldnt claim a day chunk: {e}")); @@ -816,3 +830,17 @@ pub fn run_until(config: Config, stop: Arc) -> i32 { stats.lock().unwrap().write("", "", false, false); 0 } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn chunks_only_for_tracked_groups_in_a_backfilling_mode() { + let groups = vec!["a".to_string(), "b".to_string()]; + let skip = HashSet::from(["b".to_string()]); + assert_eq!(chunk_groups("backfill", &groups, &skip), HashSet::from(["a".to_string()])); + assert_eq!(chunk_groups("dynamic", &groups, &HashSet::new()).len(), 2); + assert!(chunk_groups("live", &groups, &HashSet::new()).is_empty(), "live never backfills"); + } +} diff --git a/src/indexer.rs b/src/indexer.rs index 6215863b..1a7f7395 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -473,12 +473,16 @@ impl std::fmt::Display for NotCarried { impl std::error::Error for NotCarried {} -/// Claim the newest chunk of any split group for `host`, except `skip`. -pub async fn claim_chunk(db: &Db, host: String, skip: Vec) -> Result> { +/// Claim the newest chunk for `host` of the split groups among `groups`. +pub async fn claim_chunk( + db: &Db, + host: String, + groups: std::collections::HashSet, +) -> Result> { on_db(db, move |conn| { - let groups: Vec = - crate::chunks::split_groups(conn)?.into_iter().filter(|g| !skip.contains(g)).collect(); - Ok(crate::chunks::claim(conn, &groups, &host, chrono::Utc::now().timestamp())?) + let split: Vec = + crate::chunks::split_groups(conn)?.into_iter().filter(|g| groups.contains(g)).collect(); + Ok(crate::chunks::claim(conn, &split, &host, chrono::Utc::now().timestamp())?) }) .await } diff --git a/tests/chunk_claims.rs b/tests/chunk_claims.rs new file mode 100644 index 00000000..35ab15df --- /dev/null +++ b/tests/chunk_claims.rs @@ -0,0 +1,78 @@ +//! Idle workers only take day chunks of groups the indexer still tracks: +//! chunks left behind by a group removed from config.json stay pending. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// a group split before it was taken out of config.json +const GONE: &str = "alt.binaries.gone"; + +#[test] +fn chunks_of_a_group_no_longer_in_the_config_are_left_alone() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + // serves any alt.binaries group, GONE included + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = (1..=50u64) + .map(|n| { + let when = start + chrono::Duration::hours(n as i64); + post_at(n, &format!(r#""p{n}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect(); + let mut server = Server::new(posts); + Arc::get_mut(&mut server).unwrap().any_group = true; + let port = spawn_server(server.clone()); + + // three workers for one group: two of them idle, looking for day chunks + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": port, "ssl": false, "connections": 8, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "parallel_groups": 3, + "batch_size": 100, + "request_size": 50 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + let main = home.path().join("atlas.db"); + let day = atlas::chunks::unix_day(start.timestamp()); + atlas::chunks::add(&atlas::db::open_at(&main).unwrap(), GONE, day + 1, day).unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + // GROUP gets indexed, idle workers keep looking for chunks meanwhile + let deadline = Instant::now() + Duration::from_secs(60); + while atlas::store::totals(&atlas::db::open_with_shards(&main).unwrap()).unwrap().1 < 50 { + assert!(Instant::now() < deadline, "GROUP never got indexed"); + std::thread::sleep(Duration::from_millis(100)); + } + std::thread::sleep(Duration::from_secs(3)); + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + + let conn = atlas::db::open_at(&main).unwrap(); + let touched: i64 = + conn.query_row("select count(*) from backfill_chunks where state != 0", [], |r| r.get(0)).unwrap(); + assert_eq!(touched, 0, "no chunk of {GONE} was claimed"); + assert!(!server.groups_seen.lock().unwrap().contains(GONE)); +} From e45868f1ec15648df08b0cab6da66a662ec96de6 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:48:12 -0500 Subject: [PATCH 030/159] Menu writes wait while the database is being compacted AI search saves and the broken release purge wrote into the original shard after the compaction took its copy, and were lost at the swap. Compaction now holds an atlas.compacting lock file (pid and start time, removed on every exit, ignored once that process is gone) and those writes refuse while it's there. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + README.md | 2 +- src/ai.rs | 5 +++ src/compact.rs | 89 +++++++++++++++++++++++++++++++++++++++++++ src/db.rs | 15 +++++--- src/procs.rs | 7 ++++ tests/auto_compact.rs | 1 + 7 files changed, 114 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index d8750886..b9a9ccdc 100644 --- a/.gitignore +++ b/.gitignore @@ -49,6 +49,7 @@ atlas.db-* # the shards, and files the conversion and compaction leave while they run atlas.*.db atlas.*.db-* +atlas.compacting status.json stats.json *.json.tmp diff --git a/README.md b/README.md index ce98428a..99f73840 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,7 @@ Release IDs change in the conversion, so NZB links that Prowlarr or your apps sa The `--compact` command rewrites every shard into a fresh database file while the indexer is stopped. It re-encodes message IDs with the current packing and seals every file that's due. The copy has no free space in it. Expect the first compaction to shrink the database a lot, roughly from 138 GB to 60 GB on a full database. Atlas checks each shard's copy before it replaces the original. If a shard fails, Atlas keeps its original and reports the error; the other shards are still compacted. -With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. +With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, an `atlas.compacting` file sits next to `atlas.db`, and the menu's AI search saves and broken release purge refuse to run until it's done. A group that has caught up rests for 10 seconds before Atlas checks it again. Atlas parks a group that fails 3 times in a row for 5 minutes. diff --git a/src/ai.rs b/src/ai.rs index f09b9de1..5a4bc49f 100644 --- a/src/ai.rs +++ b/src/ai.rs @@ -128,6 +128,11 @@ pub fn fetch_group_candidates(config: &Config, limit: usize) -> Vec { /// Pull the newest headers from each group, keep keyword matches, save em. pub fn fetch_and_store(config: &Config, groups: &[String], keywords: &[String], max_per_group: i64) -> usize { + // nothing could be saved: dont fetch either + if let Err(e) = crate::compact::refuse_while_compacting(&crate::paths::database()) { + println!("{e}"); + return 0; + } let client = client_for(config); let mut saved = 0; diff --git a/src/compact.rs b/src/compact.rs index d4ec8ee0..b4fc67ca 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -51,6 +51,56 @@ fn size(path: &Path) -> u64 { std::fs::metadata(path).map(|m| m.len()).unwrap_or(0) } +/// `atlas.compacting` next to `main`: there while a compaction runs, holding +/// the pid and start time of the process running it. +pub fn lock_path(main: &Path) -> PathBuf { + main.with_extension("compacting") +} + +/// A compaction of `main` is running. A lock left by a process that is gone +/// (or whose pid now belongs to another process) doesnt count. +pub fn in_progress(main: &Path) -> bool { + let Ok(text) = std::fs::read_to_string(lock_path(main)) else { return false }; + let mut fields = text.split_whitespace().map(|f| f.parse::().ok()); + let (Some(Some(pid)), Some(Some(started))) = (fields.next(), fields.next()) else { return false }; + let Ok(pid) = u32::try_from(pid) else { return false }; + // 0: the process couldnt see its own start time, the pid alone counts + crate::procs::started_at(pid).is_some_and(|t| started == 0 || t == started) +} + +/// Writes from outside the indexer (AI search saves, purging) wait while +/// `main` is being compacted: they would land in the original after its copy +/// was taken and be lost when the copy replaces it. +pub fn refuse_while_compacting(main: &Path) -> Result<()> { + if in_progress(main) { + bail!("the database is being compacted; try again later"); + } + Ok(()) +} + +/// The lock file of a running compaction, removed when dropped (done, +/// failed or stopped). +struct Lock(PathBuf); + +impl Lock { + fn take(main: &Path) -> Result { + if in_progress(main) { + bail!("another compaction of {} is running", main.display()); + } + let pid = std::process::id(); + let started = crate::procs::started_at(pid).unwrap_or(0); + let path = lock_path(main); + std::fs::write(&path, format!("{pid} {started}")).with_context(|| format!("writing {}", path.display()))?; + Ok(Lock(path)) + } +} + +impl Drop for Lock { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + /// What compacting one shard did. #[derive(Debug, Default, Clone, Copy)] pub struct Shrunk { @@ -87,6 +137,7 @@ pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync), stop: &Arc if !store::exists(main) { bail!("{} has no shards (convert it first)", main.display()); } + let _lock = Lock::take(main)?; let started = Instant::now(); let mut total = Shrunk::default(); let mut failed: Vec<(usize, String)> = Vec::new(); @@ -471,6 +522,44 @@ mod tests { Arc::new(AtomicBool::new(false)) } + #[test] + fn writes_from_outside_are_refused_while_compacting() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + assert!(refuse_while_compacting(&main).is_ok()); + + // seen from the progress messages, while the run is going + let refused = std::sync::Mutex::new(Vec::new()); + let progress = |_: &str| refused.lock().unwrap().push(refuse_while_compacting(&main).is_err()); + run(&main, &progress, &no_stop()).unwrap(); + let refused = refused.into_inner().unwrap(); + assert!(!refused.is_empty() && refused.iter().all(|r| *r), "refused all through the run: {refused:?}"); + assert!(refuse_while_compacting(&main).is_ok(), "and not after it"); + assert!(!lock_path(&main).exists()); + + // stopped or failing: the lock goes too + let stop = Arc::new(AtomicBool::new(true)); + assert!(run(&main, &|_| {}, &stop).is_err()); + assert!(!lock_path(&main).exists()); + } + + #[test] + fn a_lock_left_by_a_dead_process_doesnt_count() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + let pid = std::process::id(); + let started = crate::procs::started_at(pid).unwrap(); + std::fs::write(lock_path(&main), format!("{pid} {started}")).unwrap(); + let err = refuse_while_compacting(&main).unwrap_err().to_string(); + assert_eq!(err, "the database is being compacted; try again later"); + // the same pid but a different start: the pid was reused + std::fs::write(lock_path(&main), format!("{pid} {}", started + 1)).unwrap(); + assert!(refuse_while_compacting(&main).is_ok()); + std::fs::write(lock_path(&main), "junk").unwrap(); + assert!(refuse_while_compacting(&main).is_ok()); + } + /// every release's NZB rows, by id fn all_articles(main: &Path) -> Vec<(i64, Vec)> { let conn = db::open_with_shards(main).unwrap(); diff --git a/src/db.rs b/src/db.rs index db528ed0..fbf39c6a 100644 --- a/src/db.rs +++ b/src/db.rs @@ -264,17 +264,22 @@ fn rebuild_articles_unique(conn: &Connection) -> Result<()> { }) } -/// Save releases from outside the indexer (AI search), each into its group's shard. -pub fn save_releases_bulk(releases: &[Release]) -> Result<()> { +/// Save releases from outside the indexer (AI search), each into its group's +/// shard. Refused while the database is being compacted. +pub fn save_releases_bulk(releases: &[Release]) -> anyhow::Result<()> { if releases.is_empty() { return Ok(()); } - store::save(&paths::database(), releases) + let main = paths::database(); + crate::compact::refuse_while_compacting(&main)?; + Ok(store::save(&main, releases)?) } -/// delete incomplete releases, returns bytes freed on disk -pub fn purge_broken() -> Result { +/// delete incomplete releases, returns bytes freed on disk. Refused while the +/// database is being compacted. +pub fn purge_broken() -> anyhow::Result { let main = paths::database(); + crate::compact::refuse_while_compacting(&main)?; let size = || store::shard_paths(&main).iter().map(|p| fs::metadata(p).map(|m| m.len() as i64).unwrap_or(0)).sum::(); let before = size(); diff --git a/src/procs.rs b/src/procs.rs index 60f1d7dd..0faee864 100644 --- a/src/procs.rs +++ b/src/procs.rs @@ -62,6 +62,13 @@ pub fn is_indexer_pid(pid: i64) -> bool { .unwrap_or(false) } +/// When process `pid` started (seconds since the epoch), None when it isnt running. +pub fn started_at(pid: u32) -> Option { + reap(); + with_process(pid, |p| (!matches!(p.status(), ProcessStatus::Zombie | ProcessStatus::Dead)).then(|| p.start_time())) + .flatten() +} + fn read_pid() -> Option { let text = fs::read_to_string(paths::pid_file()).ok()?; match text.trim().parse() { diff --git a/tests/auto_compact.rs b/tests/auto_compact.rs index a6cdeb50..b189da81 100644 --- a/tests/auto_compact.rs +++ b/tests/auto_compact.rs @@ -65,6 +65,7 @@ fn compacts_on_schedule_and_keeps_indexing() { // every shard is a new file (compacting writes a copy and swaps it in), // and none of the copying is left lying around assert!(inodes().iter().zip(&before).all(|(now, was)| now != was), "every shard was rewritten"); + assert!(!home.path().join("atlas.compacting").exists(), "the compaction lock is gone"); for shard in &shards { for suffix in ["compact", "precompact"] { let stem = shard.file_stem().unwrap().to_string_lossy().into_owned(); From 1dbb145a6e39e5b23d8109746d30cb5854b78e4e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:49:28 -0500 Subject: [PATCH 031/159] Keep split days between 2000-01-01 and today A forged Date header at either end of a group could make thousands of empty day chunks. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/indexer.rs b/src/indexer.rs index 1a7f7395..2df6a1ef 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -455,9 +455,20 @@ async fn split_days( } } + let (newest_day, oldest_day) = clamp_days(newest_day, oldest_day, unix_day(chrono::Utc::now().timestamp())); Ok((carriers >= 2).then_some((newest_day, oldest_day, carriers))) } +/// 2000-01-01: binary retention doesnt reach further back than this +const SPLIT_OLDEST_DAY: i64 = 10_957; + +/// A split's (newest, oldest) days kept between 2000-01-01 and `today`, soo a +/// forged Date header cant make thousands of empty chunks. +fn clamp_days(newest_day: i64, oldest_day: i64, today: i64) -> (i64, i64) { + let newest = newest_day.clamp(SPLIT_OLDEST_DAY, today); + (newest, oldest_day.clamp(SPLIT_OLDEST_DAY, newest)) +} + /// A day chunk's server doesnt carry its group (GROUP answered 411). #[derive(Debug)] pub struct NotCarried { @@ -934,6 +945,15 @@ mod tests { assert_eq!(make_slices(u64::MAX - 1, u64::MAX, 10, false), vec![(u64::MAX - 1, u64::MAX)]); } + #[test] + fn split_days_stay_between_2000_and_today() { + let today = 20_400; + assert_eq!(clamp_days(20_000, 19_000, today), (20_000, 19_000), "sane dates stay"); + assert_eq!(clamp_days(30_000, 19_000, today), (today, 19_000), "a date in the future"); + assert_eq!(clamp_days(20_000, 0, today), (20_000, SPLIT_OLDEST_DAY), "a date from 1970"); + assert_eq!(clamp_days(-5, -10, today), (SPLIT_OLDEST_DAY, SPLIT_OLDEST_DAY)); + } + #[test] fn a_slice_nobody_waits_for_isnt_saved() { let dir = tempfile::tempdir().unwrap(); From e939e46c2b4625e7bddae8de24e64fbe1da9cb95 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:51:29 -0500 Subject: [PATCH 032/159] Compaction checks every rewritten message-id against the original A repacked local or a message-id made whole has to decode to the same message-id the original stored, in rows and in blobs; otherwise the shard fails and keeps its original. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 69 +++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 57 insertions(+), 12 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index b4fc67ca..da0c54b7 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -307,7 +307,7 @@ fn compact_shard( from segments s left join domains d on d.id = s.domain order by s.file_id", )?; let mut rows = rows_stmt.query([])?; - let mut pending = next_row(&mut rows, &shared)?; + let mut pending = next_row(shard, &mut rows, &shared)?; let mut tx = conn.transaction()?; let mut in_tx = 0; @@ -322,13 +322,13 @@ fn compact_shard( if (copied as usize).is_multiple_of(STOP_EVERY) { halt(stop, shard)?; } - pending = next_row(&mut rows, &shared)?; + pending = next_row(shard, &mut rows, &shared)?; } let (Some(f), Some(id)) = (file, id) else { break }; let mut file_rows = Vec::new(); while let Some(row) = pending.take_if(|r| r.file_id == id) { file_rows.push(row); - pending = next_row(&mut rows, &shared)?; + pending = next_row(shard, &mut rows, &shared)?; } // its blob, with every message-id stored the way its rows are @@ -340,7 +340,7 @@ fn compact_shard( } else { None }; - let (local, domain) = rewrite(seg.local, seg.domain, shared(seg.domain), suffix.as_deref()); + let (local, domain) = rewrite(shard, id, seg.local, seg.domain, shared(seg.domain), suffix.as_deref())?; segs.push(Seg { local, domain, ..seg }); } @@ -428,15 +428,43 @@ fn unseal(shard: usize, file_id: i64, blob: &[u8]) -> Result> { /// A message-id as the copy stores it, (local, domain): kept whole, packed /// the current way under a shared domain, or made whole when its domain is -/// dropped. -fn rewrite(local: Vec, domain: i64, shared: bool, suffix: Option<&str>) -> (Vec, i64) { - if domain == 0 { - (local, 0) +/// dropped. `suffix` is the domain's, needed for a dropped one. A rewrite +/// that doesnt give back the same message-id stops the shard. +fn rewrite( + shard: usize, + file_id: i64, + local: Vec, + domain: i64, + shared: bool, + suffix: Option<&str>, +) -> Result<(Vec, i64)> { + let (new_local, new_domain) = if domain == 0 { + return Ok((local, 0)); } else if shared { (store::repack(&local), domain) } else { (store::whole(&store::decode(&local, suffix)), 0) + }; + if new_local != local { + let new_suffix = if new_domain == 0 { None } else { suffix }; + check_same_id(shard, file_id, (&local, suffix), (&new_local, new_suffix))?; } + Ok((new_local, new_domain)) +} + +/// The message-id a rewritten (local, suffix) stands for is the original's: +/// a packing bug would quietly change NZBs otherwise. +fn check_same_id( + shard: usize, + file_id: i64, + (old_local, old_suffix): (&[u8], Option<&str>), + (new_local, new_suffix): (&[u8], Option<&str>), +) -> Result<()> { + let (was, now) = (store::decode(old_local, old_suffix), store::decode(new_local, new_suffix)); + if was != now { + bail!("shard {shard}: file {file_id}: message-id {was} came out as {now}; the original was kept"); + } + Ok(()) } /// one article row of the copy @@ -449,11 +477,11 @@ struct Row { } /// the next row of `select file_id, local, domain, part, bytes, suffix`, rewritten -fn next_row(rows: &mut rusqlite::Rows, shared: &dyn Fn(i64) -> bool) -> Result> { +fn next_row(shard: usize, rows: &mut rusqlite::Rows, shared: &dyn Fn(i64) -> bool) -> Result> { let Some(r) = rows.next()? else { return Ok(None) }; - let (domain, suffix): (i64, Option) = (r.get(2)?, r.get(5)?); - let (local, domain) = rewrite(r.get(1)?, domain, shared(domain), suffix.as_deref()); - Ok(Some(Row { file_id: r.get(0)?, local, domain, part: r.get(3)?, bytes: r.get(4)? })) + let (file_id, domain, suffix): (i64, i64, Option) = (r.get(0)?, r.get(2)?, r.get(5)?); + let (local, domain) = rewrite(shard, file_id, r.get(1)?, domain, shared(domain), suffix.as_deref())?; + Ok(Some(Row { file_id, local, domain, part: r.get(3)?, bytes: r.get(4)? })) } fn insert_row(conn: &Connection, r: &Row) -> Result<()> { @@ -522,6 +550,23 @@ mod tests { Arc::new(AtomicBool::new(false)) } + #[test] + fn a_rewrite_that_changes_a_message_id_stops_the_shard() { + let local = store::pack_local("Nyu1Q2z"); + // packed again the same way, kept whole: the same message-id + assert_eq!(rewrite(3, 9, local.clone(), 5, true, Some("@ngPost>")).unwrap(), (local.clone(), 5)); + let (whole, domain) = rewrite(3, 9, local.clone(), 5, false, Some("@ngPost>")).unwrap(); + assert_eq!((store::decode(&whole, None), domain), ("".to_string(), 0)); + // a rewrite that came out different + let err = check_same_id(3, 9, (&local, Some("@ngPost>")), (&store::pack_local("Nyu1Q2y"), Some("@ngPost>"))) + .unwrap_err() + .to_string(); + assert!( + err.contains("shard 3") && err.contains("") && err.contains("original was kept"), + "{err}" + ); + } + #[test] fn writes_from_outside_are_refused_while_compacting() { let dir = tempfile::tempdir().unwrap(); From 156c59ade9669ab79aad4fac5d78fea79ba6ad0a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:53:06 -0500 Subject: [PATCH 033/159] A failing day chunk returns its own error, not a failed release Giving the chunk back after a failure is now only logged when it fails, soo the error that stopped the chunk is the one reported. Non-411 GROUP errors already came back as they are (group_on doesnt fall over). Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 35 ++++++++++++++++------------------- tests/date_search.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 19 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 2df6a1ef..148efd95 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -521,17 +521,23 @@ where let g = group.to_string(); on_db(db, move |conn| Ok(crate::chunks::release(conn, &g, day)?)) }; + // give the chunk back after `e`, and return `e`: failing to give it back + // is only logged (the claim goes stale and gets taken over) + let failed = async |e: anyhow::Error| { + if let Err(r) = release().await { + println!("[CHUNK] {group} day {day}: couldnt give the chunk back: {r:#}"); + } + Err(e) + }; - // GROUP on this server alone: falling over would move where the group lives + // GROUP on this server alone: falling over would move where the group + // lives, and only a 411 means the server doesnt carry it let found = match ctx.pool.group_on(server, group).await { Ok(info) => info, - Err(e) => { - release().await?; - if e.code() == Some(411) { - return Err(NotCarried { group: group.to_string(), host: ctx.pool.host(server) }.into()); - } - return Err(e.into()); + Err(e) if e.code() == Some(411) => { + return failed(NotCarried { group: group.to_string(), host: ctx.pool.host(server) }.into()).await; } + Err(e) => return failed(e.into()).await, }; let (_count, first, last, _name) = found; @@ -539,17 +545,11 @@ where let to = (day + 1) * 86_400 + CHUNK_OVERLAP; let start = match ctx.pool.article_at(server, group, first, last, from).await { Ok(n) => n, - Err(e) => { - release().await?; - return Err(e.into()); - } + Err(e) => return failed(e.into()).await, }; let end = match ctx.pool.article_at(server, group, start.max(first), last, to).await { Ok(n) => n.saturating_sub(1), - Err(e) => { - release().await?; - return Err(e.into()); - } + Err(e) => return failed(e.into()).await, }; if start > end { let g = group.to_string(); @@ -568,10 +568,7 @@ where release().await?; Ok(saved) } - Err(e) => { - release().await?; - Err(e) - } + Err(e) => failed(e).await, } } diff --git a/tests/date_search.rs b/tests/date_search.rs index 882493de..9bd80770 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -179,3 +179,39 @@ fn a_day_chunk_skips_a_gap_inside_the_day() { let conn = atlas::db::open_at(&main).unwrap(); assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); } + +/// A chunk that fails and then cant be given back still reports why it +/// failed, not the failure to give it back. +#[test] +fn a_failing_chunk_reports_its_own_error() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let port = spawn_server(Server::new(hourly())); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + // giving the chunk back fails: there is no chunk table + let main_conn = atlas::db::open_at(&main).unwrap(); + main_conn.execute_batch("drop table backfill_chunks").unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + // the mock doesnt carry this group: GROUP answers 411 + let err = pool + .block_on(atlas::indexer::run_chunk( + &ctx, + &Default::default(), + &db, + "alt.binaries.other", + 0, + 20_455, + &mut |_| {}, + )) + .unwrap_err(); + assert!(err.downcast_ref::().is_some(), "{err:#}"); +} From e4d5b548678125ecb2222d6ac27702d47ae205a8 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 15:56:46 -0500 Subject: [PATCH 034/159] Self-review: clamp survives a pre-2000 clock, writers never seal legacy files Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 4 +++- src/store.rs | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 148efd95..f0a4abb4 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -465,7 +465,8 @@ const SPLIT_OLDEST_DAY: i64 = 10_957; /// A split's (newest, oldest) days kept between 2000-01-01 and `today`, soo a /// forged Date header cant make thousands of empty chunks. fn clamp_days(newest_day: i64, oldest_day: i64, today: i64) -> (i64, i64) { - let newest = newest_day.clamp(SPLIT_OLDEST_DAY, today); + // a clock set before 2000 mustnt panic the clamp + let newest = newest_day.clamp(SPLIT_OLDEST_DAY, today.max(SPLIT_OLDEST_DAY)); (newest, oldest_day.clamp(SPLIT_OLDEST_DAY, newest)) } @@ -949,6 +950,7 @@ mod tests { assert_eq!(clamp_days(30_000, 19_000, today), (today, 19_000), "a date in the future"); assert_eq!(clamp_days(20_000, 0, today), (20_000, SPLIT_OLDEST_DAY), "a date from 1970"); assert_eq!(clamp_days(-5, -10, today), (SPLIT_OLDEST_DAY, SPLIT_OLDEST_DAY)); + assert_eq!(clamp_days(20_000, 19_000, 0), (SPLIT_OLDEST_DAY, SPLIT_OLDEST_DAY), "a clock from 1970"); } #[test] diff --git a/src/store.rs b/src/store.rs index 1336b414..3dbf4be1 100644 --- a/src/store.rs +++ b/src/store.rs @@ -695,8 +695,8 @@ fn still_due(conn: &Connection, file_id: i64, now: i64) -> Result { )? .query_row([file_id], |r| { let (has_rows, negative): (bool, bool) = (r.get(4)?, r.get(5)?); - let seen: Vec = r.get(1)?; - Ok(has_rows && !negative && due(r.get(0)?, &seen, r.get(2)?, r.get(3)?, now)) + let (seen, touched): (Vec, Option) = (r.get(1)?, r.get(2)?); + Ok(has_rows && !negative && touched.is_some() && due(r.get(0)?, &seen, touched, r.get(3)?, now)) }) .optional() .map(|due| due.unwrap_or(false)) From c727bc807c1b482dd2db1f1d40b4fb2ab77bb14d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 16:13:39 -0500 Subject: [PATCH 035/159] Date search finds the first article after a hole, not one past it Spread out windows that hit after a hole of millions returned the first article of the hit window, up to tens of thousands past the hole's end, soo a day right after a hole was saved empty and marked done. A hit after spread windows is now bisected down to the hole's end, and a probe that lands in a hole also finds the last article before it, soo the search crosses the hole once (about 40-70 requests for a 3M hole). Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 166 ++++++++++++++++++++++++++++++------------- tests/date_search.rs | 82 ++++++++++++++++++--- 2 files changed, 189 insertions(+), 59 deletions(-) diff --git a/src/nntp.rs b/src/nntp.rs index 604fb4a9..03149193 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -758,6 +758,13 @@ pub struct ServerStat { pub text_bytes: u64, } +/// an article number and when it was posted (unix seconds) +type Dated = (u64, i64); + +/// numbers per date search request at first, and at most +const DATE_LOOK: u64 = 100; +const DATE_SCAN_MAX: u64 = DATE_LOOK << 6; + /// Several providers tried in priority order, each with up to `connections` /// requests in flight. /// @@ -1161,83 +1168,140 @@ impl Pool { Err(first_err) } - /// The first article at or after `number` within the next `look` numbers on - /// server `i`, with its post time: (number, unix seconds). None when there is - /// none (a gap in the numbering). - async fn posted_at(&self, i: usize, group: &str, number: u64, look: u64) -> Result> { - match self.xover_on(i, group, number, number + look - 1).await { + /// The first and the last article in `start..start + look` on server `i`, + /// with their post times: (number, unix seconds). None when there is none + /// (a gap in the numbering). + async fn window(&self, i: usize, group: &str, start: u64, look: u64) -> Result> { + match self.xover_on(i, group, start, start + look - 1).await { Ok(rows) => Ok(rows .iter() .filter_map(|r| crate::dates::posted_timestamp(&r.date).map(|t| (r.number, t))) - .min_by_key(|(n, _)| *n)), + .fold(None, |ends, a| match ends { + None => Some((a, a)), + Some((first, last)) => { + Some((if a.0 < first.0 { a } else { first }, if a.0 > last.0 { a } else { last })) + } + })), Err(e) if e.code() == Some(423) => Ok(None), Err(e) => Err(e), } } + /// The first article at or after `number` within the next `look` numbers on + /// server `i`, with its post time. None when there is none. + async fn posted_at(&self, i: usize, group: &str, number: u64, look: u64) -> Result> { + Ok(self.window(i, group, number, look).await?.map(|(first, _)| first)) + } + /// When the first article at or after `number` on server `i` was posted (unix seconds). pub async fn posted_date(&self, i: usize, group: &str, number: u64) -> Result> { - Ok(self.posted_at(i, group, number, 100).await?.map(|(_, t)| t)) - } - - /// The first article in `from..end` on server `i` with its post time, and - /// whether every number between `from` and it was looked at. Missing - /// numbers are skipped forward in windows that double from 100 numbers up - /// to `SCAN_MAX`; past that the windows stay that size and spread out (each - /// starts twice as far from `from` as the last ended), soo a hole of - /// millions costs a few dozen small requests, at the price of maybe missing - /// an article between two windows. - async fn first_in(&self, i: usize, group: &str, from: u64, end: u64) -> Result> { - const LOOK: u64 = 100; - const SCAN_MAX: u64 = LOOK << 6; - let (mut at, mut size, mut whole) = (from, LOOK, true); + Ok(self.posted_at(i, group, number, DATE_LOOK).await?.map(|(_, t)| t)) + } + + /// The first article in `from..end` on server `i`, with its post time. + /// Missing numbers are skipped in windows that double from `DATE_LOOK` up + /// to `DATE_SCAN_MAX` numbers; past that the windows spread out (each + /// starts twice as far from `from` as the last ended, the last ends at + /// `end`), soo a hole of millions takes a few dozen small requests. A hit + /// after spread out windows is narrowed down by bisecting the numbers in + /// between, taking the hole as one run of missing numbers followed by + /// articles. + async fn first_in(&self, i: usize, group: &str, from: u64, end: u64) -> Result> { + // numbers before `gap` are all missing + let (mut at, mut size, mut gap) = (from, DATE_LOOK, from); while at < end { let look = size.min(end - at); - if let Some((n, t)) = self.posted_at(i, group, at, look).await? { - return Ok(Some((n, t, whole))); + if let Some(hit) = self.posted_at(i, group, at, look).await? { + // the first article is between the last empty window and this one + let (mut lo, mut hi, mut best) = (gap, at, hit); + while lo < hi { + let mid = lo + (hi - lo) / 2; + let look = DATE_LOOK.min(hi - mid); + match self.posted_at(i, group, mid, look).await? { + Some(found) => (best, hi) = (found, found.0), + None => lo = mid + look, + } + } + return Ok(Some(best)); } - let covered = at + look; - if size < SCAN_MAX { - at = covered; + gap = at + look; + if size < DATE_SCAN_MAX { + at = gap; size *= 2; - continue; + } else { + at = (gap + (gap - from)).min(end.saturating_sub(DATE_SCAN_MAX)).max(gap); + } + } + Ok(None) + } + + /// The last article in `from..end` on server `i`, with its post time: like + /// `first_in`, going backwards from `end`, the hole taken as articles + /// followed by one run of missing numbers. + async fn last_in(&self, i: usize, group: &str, from: u64, end: u64) -> Result> { + // numbers from `gap` on are all missing + let (mut to, mut size, mut gap) = (end, DATE_LOOK, end); + while to > from { + let look = size.min(to - from); + if let Some((_, hit)) = self.window(i, group, to - look, look).await? { + // the last article is between this window and the last empty one + let (mut lo, mut hi, mut best) = (to, gap, hit); + while lo < hi { + let mid = lo + (hi - lo) / 2; + let look = DATE_LOOK.min(hi - mid); + match self.window(i, group, mid, look).await? { + Some((_, found)) => (best, lo) = (found, found.0 + 1), + None => hi = mid, + } + } + return Ok(Some(best)); + } + gap = to - look; + if size < DATE_SCAN_MAX { + to = gap; + size *= 2; + } else { + to = end.saturating_sub(2 * (end - gap)).max(from.saturating_add(DATE_SCAN_MAX)).min(gap); } - // the last window always ends at `end` - let next = (covered + (covered - from)).min(end.saturating_sub(SCAN_MAX)).max(covered); - whole &= next == covered; - at = next; } Ok(None) } /// The first article number in `low..=high` on server `i` posted at or after /// `when` (unix seconds), `high + 1` when there is none. A binary search over - /// small article requests (about 35 for a billion numbers, plus one to - /// settle); a probe that lands on missing numbers skips forward to the next - /// article. Post dates are only roughly in order, soo the answer is - /// approximate near the edges: callers overlap their ranges. + /// small article requests (about 35 for a billion numbers); a probe that + /// lands in a hole in the numbering finds the articles on both sides of it, + /// soo the hole is crossed once. Post dates are only roughly in order, soo + /// the answer is approximate near the edges: callers overlap their ranges. pub async fn article_at(&self, i: usize, group: &str, low: u64, high: u64, when: i64) -> Result { - let (mut lo, mut hi) = (low, high + 1); + // every article before lo is older than `when`, none from hi on is; + // first is the first article from hi on (high + 1 when there is none) + let (mut lo, mut hi, mut first) = (low, high + 1, high + 1); while lo < hi { let mid = lo + (hi - lo) / 2; - match self.first_in(i, group, mid, hi).await? { - Some((n, t, _)) if t < when => lo = n + 1, - // every number from mid up to n is missing - Some((_, _, true)) => hi = mid, - // some numbers between mid and n werent looked at, n is an upper bound - Some((n, _, false)) => hi = n, - // nothing from mid on - None => hi = mid, + let found = self.first_in(i, group, mid, hi).await?; + if let Some((n, t)) = found + && t < when + { + lo = n + 1; + continue; + } + // nothing from mid up to the article found (or up to hi) + let gap_end = found.map_or(hi, |(n, _)| n); + if let Some((n, _)) = found { + first = n; + } + hi = mid; + // mid is in a hole: the article before it decides which side + // the answer is on, instead of halving through the hole + if gap_end - mid > DATE_LOOK { + match self.last_in(i, group, lo, mid).await? { + Some((m, t)) if t >= when => (hi, first) = (m, m), + _ => lo = mid, + } } } - if lo > high { - return Ok(high + 1); - } - // lo may be a number missing from the group: settle on the article that exists - Ok(match self.first_in(i, group, lo, high + 1).await? { - Some((n, _, _)) => n, - None => high + 1, - }) + Ok(first) } async fn xover_on(&self, i: usize, group: &str, start: u64, end: u64) -> Result> { diff --git a/tests/date_search.rs b/tests/date_search.rs index 9bd80770..cedddd0b 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -120,19 +120,85 @@ fn a_long_gap_at_the_end_is_high_plus_one() { assert_eq!(search(posts(), 1, 2000, hour_of(1650)), 1650); } +/// one post a minute: 1..=50 from 2026-01-01 00:00 UTC, nothing from 51 to +/// 3,000,000, then 3,000,001..=3,100,000 from 2026-01-03 00:00 +fn holed() -> Vec { + let at = |rfc3339: &str| chrono::DateTime::parse_from_rfc3339(rfc3339).unwrap(); + let (before, after) = (at("2026-01-01T00:00:00+00:00"), at("2026-01-03T00:00:00+00:00")); + let post = |n: u64, when: chrono::DateTime| { + post_at(n, &format!(r#""p{n}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }; + let early = (1..=50u64).map(|n| post(n, before + chrono::Duration::minutes(n as i64 - 1))); + let late = (3_000_001..=3_100_000u64).map(|n| post(n, after + chrono::Duration::minutes((n - 3_000_001) as i64))); + early.chain(late).collect() +} + +/// unix seconds article `n` of `holed` is posted at +fn minute_of(n: u64) -> i64 { + let at = |rfc3339: &str| chrono::DateTime::parse_from_rfc3339(rfc3339).unwrap().timestamp(); + if n <= 50 { + at("2026-01-01T00:00:00+00:00") + (n as i64 - 1) * 60 + } else { + at("2026-01-03T00:00:00+00:00") + (n - 3_000_001) as i64 * 60 + } +} + #[test] -fn a_hole_of_millions_is_crossed_in_few_requests() { - let server = Server::new(with_gap(1, 3_000_050, 51..=3_000_000)); +fn a_hole_of_millions_is_crossed_to_its_first_article_in_few_requests() { + let server = Server::new(holed()); let port = spawn_server(server.clone()); let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); pool.connect().unwrap(); - let at = |n: u64| pool.block_on(pool.pool.article_at(0, GROUP, 1, 3_000_050, hour_of(n))).unwrap(); + let xovers = || server.xovers.load(std::sync::atomic::Ordering::SeqCst); + let at = |low: u64, when: i64| { + let before = xovers(); + let n = pool.block_on(pool.pool.article_at(0, GROUP, low, 3_100_000, when)).unwrap(); + let used = xovers() - before; + assert!(used <= 150, "{used} requests to find {n}"); + n + }; + let in_the_hole = minute_of(50) + 86_400; + + assert_eq!(at(1, minute_of(40)), 40); + assert_eq!(at(1, in_the_hole), 3_000_001, "inside the hole: the first article after it"); + assert_eq!(at(1, minute_of(3_000_001)), 3_000_001, "the first article after the hole"); + assert_eq!(at(1, minute_of(3_000_002)), 3_000_002); + assert_eq!(at(1, minute_of(3_050_000)), 3_050_000); + assert_eq!(at(1, minute_of(3_100_000) + 60), 3_100_001, "after everything: high + 1"); + + // a low watermark that still says 1,500,000 though nothing is there + assert_eq!(at(1_500_000, minute_of(40)), 3_000_001, "everything from low on is newer"); + assert_eq!(at(1_500_000, in_the_hole), 3_000_001); + assert_eq!(at(1_500_000, minute_of(3_000_001)), 3_000_001); +} + +/// The first day after a hole of millions is indexed whole. +#[test] +fn a_day_chunk_right_after_a_hole_of_millions_gets_every_article() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let port = spawn_server(Server::new(holed())); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); - assert_eq!(at(40), 40); - assert_eq!(at(60), 3_000_001, "inside the hole: the first article after it"); - assert_eq!(at(3_000_020), 3_000_020); - let xovers = server.xovers.load(std::sync::atomic::Ordering::SeqCst); - assert!(xovers < 400, "{xovers} requests for three searches"); + let day = atlas::chunks::unix_day(minute_of(3_000_001)); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let saved = + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})).unwrap(); + + // the day's 1,440 posts and the hour after it; the hour before is the hole + assert_eq!(saved.articles, 1_440 + 60); + let conn = atlas::db::open_at(&main).unwrap(); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); } /// A day chunk whose day has 150 numbers missing in the middle still fetches From 26c5a97e359be7d0208571573447b33dc38cb4b4 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 16:19:12 -0500 Subject: [PATCH 036/159] Days a server doesnt keep go back for a server that has them Chunks reach back to the oldest day any carrier keeps, but any carrier could claim them: one with shorter retention found nothing (or only the part of the day it keeps) and marked the chunk done. run_chunk now gives back a day the server doesnt keep from its start (TooOld, not counted as an error), remembers the server's oldest day per group for an hour, and claims skip older days for that server. The split's oldest day is still done by a server whose oldest article is on it. Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 7 ++- src/chunks.rs | 50 +++++++++++++----- src/indexer.rs | 111 +++++++++++++++++++++++++++++++++++---- src/nntp.rs | 6 +++ tests/date_search.rs | 50 ++++++++++++++++++ tests/split_retention.rs | 101 +++++++++++++++++++++++++++++++++++ 6 files changed, 300 insertions(+), 25 deletions(-) create mode 100644 tests/split_retention.rs diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index c19443c9..7cfcdd0d 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -13,7 +13,7 @@ use serde_json::json; use crate::atomic::write_atomic; use crate::config::{Config, UsenetServer, load_config}; use crate::db; -use crate::indexer::{Db, NotCarried, PassContext, PassSettings, Progress, RunStates, run_pass, shared_db}; +use crate::indexer::{Db, NotCarried, PassContext, PassSettings, Progress, RunStates, TooOld, run_pass, shared_db}; use crate::nntp::{Pool, unless_stopped}; use crate::paths; use crate::sab; @@ -384,6 +384,8 @@ impl Scheduler { self.chunk_errors.lock().unwrap().remove(&key); } Err(_) if self.ctx.stop.load(Ordering::Relaxed) => {} + // the day went back for another server, and this one wont take one that old again soon + Err(e) if e.downcast_ref::().is_some() => {} Err(e) if e.downcast_ref::().is_some() => { println!("{e}, leaving its day chunks to the other servers"); self.skip.lock().unwrap().insert(key, None); @@ -468,7 +470,8 @@ async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option<(String return None; } - match crate::indexer::claim_chunk(db, host, groups).await { + let oldest = sched.ctx.states.kept_days(server); + match crate::indexer::claim_chunk(db, host, groups, oldest).await { Ok(chunk) => chunk, Err(e) => { ui::error(&format!("couldnt claim a day chunk: {e}")); diff --git a/src/chunks.rs b/src/chunks.rs index 4be94602..383040fa 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -50,21 +50,29 @@ pub fn is_split(conn: &Connection, group: &str) -> Result { conn.prepare_cached("select 1 from backfill_chunks where grp = ? limit 1")?.exists([group]) } -/// Atomically claim the newest chunk of `groups` that is pending or whose claim went stale. -pub fn claim(conn: &Connection, groups: &[String], host: &str, now: i64) -> Result> { +/// Atomically claim the newest chunk that is pending or whose claim went +/// stale, of `groups`: (group, oldest day the server keeps), `i64::MIN` when +/// any day will do. +pub fn claim(conn: &Connection, groups: &[(String, i64)], host: &str, now: i64) -> Result> { if groups.is_empty() { return Ok(None); } - let marks = vec!["?"; groups.len()].join(","); + let rows = vec!["(?, ?)"; groups.len()].join(", "); let sql = format!( - "update backfill_chunks set state = ?, server = ?, claimed_at = ? - where (grp, day) = (select grp, day from backfill_chunks - where grp in ({marks}) and (state = {PENDING} or (state = {CLAIMED} and claimed_at < ?)) - order by day desc limit 1) + "with wanted (g, oldest) as (values {rows}) + update backfill_chunks set state = ?, server = ?, claimed_at = ? + where (grp, day) = (select c.grp, c.day from backfill_chunks c join wanted w on w.g = c.grp + where c.day >= w.oldest + and (c.state = {PENDING} or (c.state = {CLAIMED} and c.claimed_at < ?)) + order by c.day desc limit 1) returning grp, day" ); - let mut values: Vec = vec![CLAIMED.into(), host.to_string().into(), now.into()]; - values.extend(groups.iter().map(|g| g.clone().into())); + let mut values: Vec = Vec::new(); + for (g, oldest) in groups { + values.push(g.clone().into()); + values.push((*oldest).into()); + } + values.extend([CLAIMED.into(), host.to_string().into(), now.into()]); values.push((now - CLAIM_TIMEOUT).into()); let found: Option<(String, i64)> = conn.prepare(&sql)?.query_row(rusqlite::params_from_iter(values), |r| Ok((r.get(0)?, r.get(1)?))).optional()?; @@ -93,6 +101,11 @@ pub fn progress(conn: &Connection, group: &str) -> Result<(i64, i64)> { }) } +/// the oldest day of a group's chunks +pub fn oldest_day(conn: &Connection, group: &str) -> Result> { + conn.query_row("select min(day) from backfill_chunks where grp = ?", [group], |r| r.get(0)) +} + /// groups with chunks still to do pub fn split_groups(conn: &Connection) -> Result> { conn.prepare("select distinct grp from backfill_chunks where state != 2 order by grp")? @@ -116,7 +129,7 @@ mod tests { assert_eq!(add(&c, "g", 20_000, 19_998).unwrap(), 3); assert_eq!(add(&c, "g", 20_000, 19_998).unwrap(), 0, "adding again adds nothing"); assert!(is_split(&c, "g").unwrap()); - let groups = vec!["g".to_string()]; + let groups = vec![("g".to_string(), i64::MIN)]; assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), Some(("g".into(), 20_000))); assert_eq!(claim(&c, &groups, "b", 1000).unwrap(), Some(("g".into(), 19_999))); @@ -132,7 +145,7 @@ mod tests { fn stale_claims_are_taken_over() { let c = conn(); add(&c, "g", 5, 5).unwrap(); - let groups = vec!["g".to_string()]; + let groups = vec![("g".to_string(), i64::MIN)]; assert!(claim(&c, &groups, "a", 1000).unwrap().is_some()); assert_eq!(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT - 1).unwrap(), None); assert_eq!(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT + 1).unwrap(), Some(("g".into(), 5))); @@ -142,12 +155,23 @@ mod tests { fn only_listed_groups_and_unsplit_groups() { let c = conn(); add(&c, "g", 5, 5).unwrap(); - assert_eq!(claim(&c, &["other".to_string()], "a", 0).unwrap(), None); + assert_eq!(claim(&c, &[("other".to_string(), i64::MIN)], "a", 0).unwrap(), None); assert!(!is_split(&c, "other").unwrap()); assert_eq!(split_groups(&c).unwrap(), vec!["g".to_string()]); assert_eq!(unix_day(86_400 * 3 + 5), 3); } + #[test] + fn days_older_than_a_servers_oldest_are_left_to_others() { + let c = conn(); + add(&c, "g", 12, 10).unwrap(); + let from_11 = [("g".to_string(), 11)]; + assert_eq!(claim(&c, &from_11, "short", 0).unwrap(), Some(("g".into(), 12))); + assert_eq!(claim(&c, &from_11, "short", 0).unwrap(), Some(("g".into(), 11))); + assert_eq!(claim(&c, &from_11, "short", 0).unwrap(), None, "day 10 is older than it keeps"); + assert_eq!(claim(&c, &[("g".to_string(), i64::MIN)], "long", 0).unwrap(), Some(("g".into(), 10))); + } + #[test] fn claim_is_atomic_with_concurrent_connections() { let dir = tempfile::tempdir().unwrap(); @@ -163,7 +187,7 @@ mod tests { let c_a = Connection::open(&db_path).unwrap(); let c_b = Connection::open(&db_path).unwrap(); - let groups = vec!["g".to_string()]; + let groups = vec![("g".to_string(), i64::MIN)]; let a_claim = claim(&c_a, &groups, "a", 1000).unwrap(); let b_claim = claim(&c_b, &groups, "b", 1000).unwrap(); diff --git a/src/indexer.rs b/src/indexer.rs index f0a4abb4..f0821825 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -46,11 +46,20 @@ pub struct GroupRunState { pub backfilling: bool, /// a big group found unsplittable isnt probed again until then pub no_split_until: Option, + /// per server, the oldest day it keeps of the group (as found by a day + /// chunk too old for it), until it's looked at again + pub keeps_from: HashMap, } impl Default for GroupRunState { fn default() -> Self { - GroupRunState { phase: Phase::Backfill, idle: false, backfilling: false, no_split_until: None } + GroupRunState { + phase: Phase::Backfill, + idle: false, + backfilling: false, + no_split_until: None, + keeps_from: HashMap::new(), + } } } @@ -76,6 +85,26 @@ impl RunStates { groups.iter().all(|g| states.get(g).is_some_and(|s| s.idle)) } + /// The oldest day `server` keeps of `group`, `i64::MIN` when not known. + pub fn keeps_from(&self, group: &str, server: usize) -> i64 { + let now = Instant::now(); + let states = self.0.lock().unwrap(); + let found = states.get(group).and_then(|s| s.keeps_from.get(&server)); + found.filter(|(_, until)| *until > now).map_or(i64::MIN, |(day, _)| *day) + } + + /// The groups whose oldest day on `server` is known, with that day. + pub fn kept_days(&self, server: usize) -> HashMap { + let now = Instant::now(); + let states = self.0.lock().unwrap(); + states + .iter() + .filter_map(|(g, s)| { + s.keeps_from.get(&server).filter(|(_, until)| *until > now).map(|(d, _)| (g.clone(), *d)) + }) + .collect() + } + /// switching modes starts every group over in the backfill phase pub fn reset(&self) { for st in self.0.lock().unwrap().values_mut() { @@ -347,13 +376,16 @@ where { // a split group's backfill is day chunks, this server takes the next one let host = ctx.pool.host(server); - let g = group.to_string(); - let claimed = on_db(db, move |conn| { - Ok(crate::chunks::claim(conn, std::slice::from_ref(&g), &host, chrono::Utc::now().timestamp())?) - }) - .await?; + let wanted = [(group.to_string(), ctx.states.keeps_from(group, server))]; + let claimed = + on_db(db, move |conn| Ok(crate::chunks::claim(conn, &wanted, &host, chrono::Utc::now().timestamp())?)) + .await?; let r = match claimed { - Some((_, day)) => run_chunk(ctx, settings, db, group, server, day, progress).await, + // a day this server doesnt keep is left to the others, it isnt an error + Some((_, day)) => match run_chunk(ctx, settings, db, group, server, day, progress).await { + Err(e) if e.downcast_ref::().is_some() => Ok(Progress::default()), + r => r, + }, None => { // nothing pending: in backfill mode the group rests like a finished backfill let idle = settings.mode == "backfill"; @@ -485,15 +517,45 @@ impl std::fmt::Display for NotCarried { impl std::error::Error for NotCarried {} -/// Claim the newest chunk for `host` of the split groups among `groups`. +/// A day chunk older than anything its server keeps of the group: the chunk +/// goes back for a server that has the day. +#[derive(Debug)] +pub struct TooOld { + pub group: String, + pub host: String, + /// the oldest day the server keeps (unix days), `i64::MAX` when it has nothing + pub oldest_day: i64, +} + +impl std::fmt::Display for TooOld { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{} on {} doesnt go back that far", self.group, self.host) + } +} + +impl std::error::Error for TooOld {} + +/// how long a server's oldest day of a group is trusted before a chunk older +/// than it is tried there again +const KEEPS_RECHECK: Duration = Duration::from_secs(3600); + +/// Claim the newest chunk for `host` of the split groups among `groups`, +/// none older than the server's oldest day in `oldest` (by group). pub async fn claim_chunk( db: &Db, host: String, groups: std::collections::HashSet, + oldest: HashMap, ) -> Result> { on_db(db, move |conn| { - let split: Vec = - crate::chunks::split_groups(conn)?.into_iter().filter(|g| groups.contains(g)).collect(); + let split: Vec<(String, i64)> = crate::chunks::split_groups(conn)? + .into_iter() + .filter(|g| groups.contains(g)) + .map(|g| { + let day = oldest.get(&g).copied().unwrap_or(i64::MIN); + (g, day) + }) + .collect(); Ok(crate::chunks::claim(conn, &split, &host, chrono::Utc::now().timestamp())?) }) .await @@ -544,6 +606,35 @@ where let from = day * 86_400 - CHUNK_OVERLAP; let to = (day + 1) * 86_400 + CHUNK_OVERLAP; + + // a day this server doesnt keep from its start would come out empty or + // cut short, though another server may have all of it: give it back, and + // the server takes no day that old for a while. the split's oldest day is + // the exception: no server goes back further, the one whose oldest + // article is on it does what there is + let oldest = match ctx.pool.first_post(server, group, first, last).await { + Ok(oldest) => oldest, + Err(e) => return failed(e.into()).await, + }; + let keeps_day = match oldest { + Some(t) if t <= day * 86_400 => true, + Some(t) if crate::chunks::unix_day(t) == day => { + let g = group.to_string(); + match on_db(db, move |conn| Ok(crate::chunks::oldest_day(conn, &g)?)).await { + Ok(split_oldest) => split_oldest == Some(day), + Err(e) => return failed(e).await, + } + } + _ => false, + }; + if !keeps_day { + // the first day it keeps whole + let oldest_day = oldest.map_or(i64::MAX, |t| crate::chunks::unix_day(t - 1) + 1); + ctx.states.with(group, |st| st.keeps_from.insert(server, (oldest_day, Instant::now() + KEEPS_RECHECK))); + let host = ctx.pool.host(server); + println!("[CHUNK] {group} day {day} is older than {host} keeps, leaving it to the other servers"); + return failed(TooOld { group: group.to_string(), host, oldest_day }.into()).await; + } let start = match ctx.pool.article_at(server, group, first, last, from).await { Ok(n) => n, Err(e) => return failed(e.into()).await, diff --git a/src/nntp.rs b/src/nntp.rs index 03149193..cb5584d6 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1267,6 +1267,12 @@ impl Pool { Ok(None) } + /// When the first article in `low..=high` on server `i` was posted (unix + /// seconds): how far back the server keeps the group. None when it has none. + pub async fn first_post(&self, i: usize, group: &str, low: u64, high: u64) -> Result> { + Ok(self.first_in(i, group, low, high + 1).await?.map(|(_, t)| t)) + } + /// The first article number in `low..=high` on server `i` posted at or after /// `when` (unix seconds), `high + 1` when there is none. A binary search over /// small article requests (about 35 for a billion numbers); a probe that diff --git a/tests/date_search.rs b/tests/date_search.rs index cedddd0b..183e17f3 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -281,3 +281,53 @@ fn a_failing_chunk_reports_its_own_error() { .unwrap_err(); assert!(err.downcast_ref::().is_some(), "{err:#}"); } + +/// A day before anything the server keeps goes back unfinished (another +/// server may have it); an empty day the server does keep is finished. +#[test] +fn a_day_older_than_the_server_keeps_is_given_back() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour of 2026-01-01 and of 2026-01-03, none on 2026-01-02 + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = (0..72u64) + .filter(|h| !(24..48).contains(h)) + .map(|h| { + post_at( + h + 1, + &format!(r#""p{h}.bin" yEnc (1/1)"#), + &(start + chrono::Duration::hours(h as i64)).to_rfc2822(), + ) + }) + .collect(); + let port = spawn_server(Server::new(posts)); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + let first_day = atlas::chunks::unix_day(start.timestamp()); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, first_day + 2, first_day - 1).unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let run = + |day: i64| pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})); + + let err = run(first_day - 1).unwrap_err(); + let too_old = err.downcast_ref::().expect("a TooOld"); + assert_eq!(too_old.oldest_day, first_day); + assert_eq!(ctx.states.keeps_from(GROUP, 0), first_day, "remembered for the next claims"); + let empty = run(first_day + 1).unwrap(); + assert_eq!(empty.articles, 2, "only the overlap hours"); + let conn = atlas::db::open_at(&main).unwrap(); + let state = |day: i64| -> i64 { + conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() + }; + assert_eq!(state(first_day - 1), 0, "given back, still pending"); + assert_eq!(state(first_day + 1), 2, "an empty day it keeps is done"); +} diff --git a/tests/split_retention.rs b/tests/split_retention.rs new file mode 100644 index 00000000..e31556ae --- /dev/null +++ b/tests/split_retention.rs @@ -0,0 +1,101 @@ +//! A split group on two servers, one of which only keeps the last 10 of its +//! 30 days: the days older than that are all done by the other server, with +//! every article, and the short server doesnt keep grabbing them. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset`, +/// only those from day `from_day` on +fn posts(offset: u64, from_day: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (from_day * 40..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn days_older_than_a_servers_retention_go_to_the_server_that_has_them() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + let slow = |mut s: Arc| { + Arc::get_mut(&mut s).unwrap().xover_delay = Duration::from_millis(10); + s + }; + // "127.0.0.1" keeps all 30 days, "localhost" the last 10 + let long = slow(Server::new(posts(1, 0))); + let short = slow(Server::new(posts(500_001, 20))); + let (pl, ps) = (spawn_server(long.clone()), spawn_server(short.clone())); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pl, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": ps, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(120); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + if total > 0 && done == total { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); + let first_short_day = + atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-21T00:00:00+00:00").unwrap().timestamp()); + let old_by_short: i64 = conn + .query_row( + "select count(*) from backfill_chunks where server = 'localhost' and day < ?", + [first_short_day], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(old_by_short, 0, "the short server finished no day it doesnt keep"); + let short_xovers = short.xovers.load(Ordering::SeqCst); + assert!(short_xovers < 1500, "the short server kept trying old days: {short_xovers} requests"); +} From 3cc24d6056b48b26ab79c035e18e96239a585a38 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 16:21:38 -0500 Subject: [PATCH 037/159] README: days past a server's retention go to another server Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 99f73840..2d92a62d 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ Start the indexer from the main menu with option 1. The indexer runs as a backgr ### Splitting big groups -When two or more indexing servers carry a group and its backfill has more than `split_min_backlog` article numbers left, Atlas splits the rest of its history into UTC day chunks. A worker with nothing of its own to do claims the newest pending chunk on any server that carries the group, so idle connections help with big groups. Live indexing stays on the group's home server. The Backfill page of the stats dashboard shows split groups and their day chunks. +When two or more indexing servers carry a group and its backfill has more than `split_min_backlog` article numbers left, Atlas splits the rest of its history into UTC day chunks. A worker with nothing of its own to do claims the newest pending chunk on any server that carries the group, so idle connections help with big groups. A server that doesn't keep a day from its start, because its retention is shorter, gives the chunk back for a server that does. Live indexing stays on the group's home server. The Backfill page of the stats dashboard shows split groups and their day chunks. ### How the database is stored From 39fc0c5190af53ede6cdf440410833fddf5564f6 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:03:52 -0500 Subject: [PATCH 038/159] Date search reads the span a bisect skipped Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 12 ++++ tests/common/mod.rs | 11 ++-- tests/date_search.rs | 128 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 147 insertions(+), 4 deletions(-) diff --git a/src/nntp.rs b/src/nntp.rs index cb5584d6..0ff3a1b0 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1222,6 +1222,12 @@ impl Pool { None => lo = mid + look, } } + // the bisect skipped what it took for empty: read it once + if best.0 > gap + && let Some(f) = self.posted_at(i, group, gap, best.0 - gap).await? + { + best = f; + } return Ok(Some(best)); } gap = at + look; @@ -1254,6 +1260,12 @@ impl Pool { None => hi = mid, } } + // the bisect skipped what it took for empty: read it once + if gap > best.0 + 1 + && let Some((_, l)) = self.window(i, group, best.0 + 1, gap - best.0 - 1).await? + { + best = l; + } return Ok(Some(best)); } gap = to - look; diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 2afeb1e3..aab91a22 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -176,7 +176,7 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { let cmd = line.trim_end().to_string(); line.clear(); let (verb, arg) = cmd.split_once(' ').unwrap_or((&cmd, "")); - let posts = state.posts.lock().unwrap().clone(); + let posts_lock = || state.posts.lock().unwrap(); match verb.to_uppercase().as_str() { "AUTHINFO" if arg.starts_with("USER") => send(&mut out, b"381 more"), @@ -192,6 +192,7 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { "GROUP" if state.no_group => send(&mut out, b"501 GROUP command error"), "GROUP" if arg == GROUP || (state.any_group && arg.starts_with("alt.binaries.")) => { selected = Some(arg.to_string()); + let posts = posts_lock(); let first = posts.iter().map(|p| p.number).min().unwrap_or(0); let last = posts.iter().map(|p| p.number).max().unwrap_or(0); send(&mut out, format!("211 {} {first} {last} {arg}", posts.len()).as_bytes()); @@ -199,7 +200,7 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { "GROUP" => send(&mut out, b"411 no such group"), "LIST" => { send(&mut out, b"215 list follows"); - let last = posts.iter().map(|p| p.number).max().unwrap_or(0); + let last = posts_lock().iter().map(|p| p.number).max().unwrap_or(0); send(&mut out, format!("{GROUP} {last} 1 y").as_bytes()); send(&mut out, b"alt.binaries.empty 5 5 y"); send(&mut out, b"comp.lang.rust 900 1 y"); @@ -224,7 +225,9 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { state.xovers_in_flight.fetch_sub(1, Ordering::SeqCst); let (a, b) = arg.split_once('-').unwrap(); let (a, b): (u64, u64) = (a.parse().unwrap(), b.parse().unwrap()); - let hits: Vec<&Post> = posts.iter().filter(|p| (a..=b).contains(&p.number)).collect(); + let posts = posts_lock(); + let lo = posts.partition_point(|p| p.number < a); + let hits: Vec<&Post> = posts[lo..].iter().take_while(|p| p.number <= b).collect(); if hits.is_empty() { send(&mut out, b"423 no articles in that range"); continue; @@ -255,7 +258,7 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { let _ = out.write_all(&listing); } } - "BODY" => match posts.iter().find(|p| p.message_id == arg).filter(|_| state.bodies) { + "BODY" => match posts_lock().iter().find(|p| p.message_id == arg).filter(|_| state.bodies) { Some(p) => { send(&mut out, format!("222 0 {arg}").as_bytes()); for l in &p.body { diff --git a/tests/date_search.rs b/tests/date_search.rs index 183e17f3..c5a1cf9b 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -331,3 +331,131 @@ fn a_day_older_than_the_server_keeps_is_given_back() { assert_eq!(state(first_day - 1), 0, "given back, still pending"); assert_eq!(state(first_day + 1), 2, "an empty day it keeps is done"); } + +/// (number, unix seconds) of a post +type Slot = (u64, i64); + +fn jan_1() -> i64 { + chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap().timestamp() +} + +fn slot_posts(list: &[Slot]) -> Vec { + list.iter() + .map(|&(n, t)| { + let when = chrono::DateTime::from_timestamp(t, 0).unwrap(); + post_at(n, &format!(r#""p{n}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() +} + +/// numbers `gap` apart, somewhere in 100..=500 (a fixed pseudo random walk) +fn sparse_step(state: &mut u64) -> u64 { + *state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + 100 + (*state >> 33) % 401 +} + +/// `count` posts a minute apart from `(n, t)` on, `step` numbers apart +fn run(list: &mut Vec, (mut n, mut t): Slot, count: usize, mut step: impl FnMut() -> u64) -> Slot { + for _ in 0..count { + list.push((n, t)); + n += step(); + t += 60; + } + (n, t) +} + +/// 1..=50 from Jan 1, a hole to 3,000,000, 3,000 posts with 100 to 500 +/// numbers between them from Jan 3, then 100,000 posts side by side +fn hole_then_sparse_then_dense() -> Vec { + let mut list = Vec::new(); + let end = run(&mut list, (1, jan_1()), 50, || 1); + assert_eq!(end.0, 51); + let (mut seed, start) = (7, (3_000_001, jan_1() + 2 * 86_400)); + let next = run(&mut list, start, 3_000, || sparse_step(&mut seed)); + run(&mut list, next, 100_000, || 1); + list +} + +/// 20,000 posts side by side from Jan 1, 3,000 with 100 to 500 numbers +/// between them, a hole of 3,000,000, then 100,000 posts side by side +fn dense_then_sparse_then_hole() -> Vec { + let mut list = Vec::new(); + let next = run(&mut list, (1, jan_1()), 20_000, || 1); + let mut seed = 11; + let (n, t) = run(&mut list, next, 3_000, || sparse_step(&mut seed)); + run(&mut list, (n + 3_000_000, t), 100_000, || 1); + list +} + +/// Every time in `whens` finds exactly the first post at or after it. +fn finds_the_first_post_for_each(list: &[Slot], lows: &[u64], whens: &[i64]) { + let server = Server::new(slot_posts(list)); + let port = spawn_server(server.clone()); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + let high = list.last().unwrap().0; + for &low in lows { + for &when in whens { + let before = server.xovers.load(std::sync::atomic::Ordering::SeqCst); + let got = pool.block_on(pool.pool.article_at(0, GROUP, low, high, when)).unwrap(); + let used = server.xovers.load(std::sync::atomic::Ordering::SeqCst) - before; + let want = list.iter().find(|&&(n, t)| n >= low && t >= when).map_or(high + 1, |&(n, _)| n); + assert_eq!(got, want, "low {low}, time {when}"); + assert!(used <= 150, "{used} requests to find {got}"); + } + } +} + +/// Indexing each of `days` saves every post of the day and the hour around it. +fn chunks_save_every_post_of(list: &[Slot], days: &[i64]) { + for &day in days { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let port = spawn_server(Server::new(slot_posts(list))); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day, atlas::chunks::unix_day(list[0].1).min(day)).unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let saved = pool + .block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})) + .unwrap(); + let (from, to) = (day * 86_400 - 3600, (day + 1) * 86_400 + 3600); + let want = list.iter().filter(|&&(_, t)| t >= from && t < to).count() as i64; + assert_eq!(saved.articles, want, "day {day}"); + } +} + +fn days_from(list: &[Slot], first: usize, count: usize) -> Vec { + let mut days: Vec = list[first..].iter().map(|&(_, t)| atlas::chunks::unix_day(t)).collect(); + days.dedup(); + days.truncate(count); + days +} + +/// A hole, then articles hundreds of numbers apart, then a crowd: one empty +/// window must not make the bisect skip the sparse articles after the hole. +#[test] +fn a_sparse_region_after_a_hole_is_not_skipped() { + let list = hole_then_sparse_then_dense(); + let whens: Vec = list.iter().skip(50).take(3_200).step_by(7).map(|&(_, t)| t).collect(); + finds_the_first_post_for_each(&list, &[1, 1_500_000], &whens); + chunks_save_every_post_of(&list, &days_from(&list, 50, 5)); +} + +/// A crowd, articles hundreds of numbers apart, then a hole: the last article +/// before the hole is the sparse one, not one a window further back. +#[test] +fn a_sparse_region_before_a_hole_is_not_skipped() { + let list = dense_then_sparse_then_hole(); + let whens: Vec = list.iter().skip(19_000).take(4_500).step_by(7).map(|&(_, t)| t).collect(); + finds_the_first_post_for_each(&list, &[1], &whens); + chunks_save_every_post_of(&list, &days_from(&list, 19_000, 5)); +} From 86fea56f7c17763b9502c46cecb226c0d967f068 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:29:45 -0500 Subject: [PATCH 039/159] A server that goes down only moves its own groups Groups were spread over the servers up right now by hash modulo their connections, soo one server resting after a failed connect re-dealt groups between the healthy ones too, each starting a new set of cursors. A group now keeps the server it gets with every indexing server up, unless that server is the one down. This is what failed split_homes on Windows CI: the non-carrier "127.1" couldnt be reached there, rested as down, and the split group moved from localhost to 127.0.0.1. The mock now also listens on ::1 (localhost is ::1 first on Windows and macOS), the non-carrier is "[::1]", and the test checks it was asked. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/nntp.rs | 38 ++++++++++++++++++++++++++++++++++++++ tests/common/mod.rs | 42 ++++++++++++++++++++++++++++++++++-------- tests/split_homes.rs | 18 ++++++++++++------ 4 files changed, 85 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 2d92a62d..583237ad 100644 --- a/README.md +++ b/README.md @@ -160,7 +160,7 @@ The old single-server layout, with `host`, `username`, `password`, and `port` at ### How Atlas uses the servers -- **Indexing uses every server at once, whatever its priority.** Atlas spreads groups over the indexing servers in proportion to their `connections`, and each server runs its own groups, so all connections stay busy. Each group stays on one server, because article numbers, and therefore the indexing cursors, differ between providers. +- **Indexing uses every server at once, whatever its priority.** Atlas spreads groups over the indexing servers in proportion to their `connections`, and each server runs its own groups, so all connections stay busy. Each group stays on one server, because article numbers, and therefore the indexing cursors, differ between providers. A server that stops answering hands only its own groups to the others for a while. - **A group that a server doesn't carry:** Atlas looks it up on the other servers. - **par2 and nfo articles:** Atlas asks the servers in priority order until one has them. - **A server that can't connect:** Atlas skips it for a minute and moves its groups to the other servers. When a group moves, its cursor on the new server starts from the top. Atlas re-scans those articles but de-duplicates them, so it doesn't store anything twice. diff --git a/src/nntp.rs b/src/nntp.rs index 0ff3a1b0..22b95af8 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -887,6 +887,17 @@ impl Pool { return home; } + // a server that is down only moves its own groups: the others keep the + // server they get with every indexing server up + let first = self.spread_over(&self.indexing_servers(), group); + if tier.contains(&first) { + return first; + } + self.spread_over(tier, group) + } + + /// `group`'s server among `tier`, by its hash weighted by connections. + fn spread_over(&self, tier: &[usize], group: &str) -> usize { let total: u64 = tier.iter().map(|&i| self.connections(i) as u64).sum(); if total == 0 { return tier.first().copied().unwrap_or(0); @@ -1974,6 +1985,33 @@ mod tests { assert_eq!(pool.pick_server("alt.binaries.moved"), 1); } + #[test] + fn a_server_going_down_only_moves_its_own_groups() { + let server = |host: &str| { + let mut s = UsenetServer::new(host, "u", "p", 563); + s.connections = Some(4); + s + }; + let pool = Pool::new(&[server("a"), server("b"), server("c")]); + let groups: Vec = (0..300).map(|i| format!("alt.binaries.group{i}")).collect(); + let before: Vec = groups.iter().map(|g| pool.pick_server(g)).collect(); + + *pool.servers[2].down_until.lock().unwrap() = Some(Instant::now() + DOWN_FOR); + assert_eq!(pool.indexing_tier(), vec![0, 1]); + for (g, &was) in groups.iter().zip(&before) { + let now = pool.pick_server(g); + if was == 2 { + assert_ne!(now, 2, "{g}: its server is down, it goes to another"); + } else { + assert_eq!(now, was, "{g}: its server is up, it stays there"); + } + } + + // back up: every group is where it was + *pool.servers[2].down_until.lock().unwrap() = None; + assert_eq!(groups.iter().map(|g| pool.pick_server(g)).collect::>(), before); + } + #[test] fn compressed_group_list() { let mut listing = Vec::new(); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index aab91a22..d9036ad8 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -282,18 +282,44 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { } } +/// The mock listens on 127.0.0.1 and, where the machine has IPv6, on ::1 at +/// the same port: "localhost" is ::1 first on Windows and macOS, and a +/// refused ::1 costs Windows about 2s per connection before it tries 127.0.0.1. pub fn spawn_server(state: Arc) -> u16 { - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); - let port = listener.local_addr().unwrap().port(); - thread::spawn(move || { - for stream in listener.incoming().flatten() { - let state = state.clone(); - thread::spawn(move || handle(stream, state)); - } - }); + let (v4, v6) = loopback_listeners(); + let port = v4.local_addr().unwrap().port(); + for listener in std::iter::once(v4).chain(v6) { + let state = state.clone(); + thread::spawn(move || { + for stream in listener.incoming().flatten() { + let state = state.clone(); + thread::spawn(move || handle(stream, state)); + } + }); + } port } +/// a port free on 127.0.0.1, and on ::1 too unless the machine has no IPv6 +fn loopback_listeners() -> (TcpListener, Option) { + for _ in 0..20 { + let v4 = TcpListener::bind("127.0.0.1:0").unwrap(); + if !has_ipv6_loopback() { + return (v4, None); + } + // the port can be taken on ::1 by something else: try another + if let Ok(v6) = TcpListener::bind(("::1", v4.local_addr().unwrap().port())) { + return (v4, Some(v6)); + } + } + panic!("no port free on both 127.0.0.1 and ::1"); +} + +/// ::1 can be listened on (some containers have no IPv6) +pub fn has_ipv6_loopback() -> bool { + TcpListener::bind("[::1]:0").is_ok() +} + pub fn index_until_idle(indexer: &mut Indexer) { for _ in 0..20 { indexer.index_group(GROUP).unwrap(); diff --git a/tests/split_homes.rs b/tests/split_homes.rs index c2af3649..6f775c10 100644 --- a/tests/split_homes.rs +++ b/tests/split_homes.rs @@ -14,9 +14,11 @@ use std::time::{Duration, Instant}; use common::{Server, post_at, spawn_server}; /// the mock always carries common::GROUP, this one only with `any_group`. -/// its home is localhost, and GROUP on 127.1 falling over would pick -/// 127.0.0.1 (see Pool::pick_server_in and Pool::ranked), soo a probe that -/// falls over moves the group and leaves a second set of cursors +/// its home is localhost, and GROUP on the third server falling over would +/// pick 127.0.0.1 (see Pool::pick_server_in and Pool::ranked), soo a probe +/// that falls over moves the group and leaves a second set of cursors. The +/// third server resting as down mustnt move it either (with all three up it +/// hashes to localhost, over the other two alone to 127.0.0.1) const SPLIT_GROUP: &str = "alt.binaries.split"; /// 40 posts a day for 30 days, numbered from `offset` @@ -56,13 +58,16 @@ fn a_server_without_the_group_doesnt_move_it() { let (a, b) = (carrier(1), carrier(500_001)); // answers 411 for SPLIT_GROUP let c = Server::new(posts(900_001)); - let (pa, pb, pc) = (spawn_server(a), spawn_server(b), spawn_server(c)); - // three host names for 127.0.0.1, soo cursors and chunk claims tell the servers apart + let (pa, pb, pc) = (spawn_server(a), spawn_server(b), spawn_server(c.clone())); + // three host names for the loopback, soo cursors and chunk claims tell the + // servers apart. the third has to reach its mock (and answer 411) on every + // os, and 127.1 isnt a name every resolver takes (Windows CI couldnt reach it) + let third = if common::has_ipv6_loopback() { "[::1]" } else { "127.1" }; let config = serde_json::json!({ "usenet_servers": [ {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pa, "ssl": false, "connections": 4, "priority": 1}, {"host": "localhost", "username": "bob", "password": "secret", "port": pb, "ssl": false, "connections": 4, "priority": 1}, - {"host": "127.1", "username": "bob", "password": "secret", "port": pc, "ssl": false, "connections": 4, "priority": 1} + {"host": third, "username": "bob", "password": "secret", "port": pc, "ssl": false, "connections": 4, "priority": 1} ], "groups": [SPLIT_GROUP], "index_mode": "backfill", @@ -114,5 +119,6 @@ fn a_server_without_the_group_doesnt_move_it() { .unwrap() .collect::>() .unwrap(); + assert!(c.accepted.load(Ordering::SeqCst) > 0, "the third server was asked"); assert_eq!(chunk_servers, vec!["127.0.0.1".to_string(), "localhost".to_string()], "only the carriers did chunks"); } From b070409f233f85957f71a7c6073ca9c96c2b546a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:39:07 -0500 Subject: [PATCH 040/159] Only a chunk's current claim finishes or gives it back A day chunk running past CLAIM_TIMEOUT is taken over by another worker, and the first worker's finish or release then overwrote the new owner: a late release could turn a finished chunk back into a pending one. claim now returns a Claim (group, day, server, claimed_at) and finish / release only touch the chunk while that claim still holds it. run_chunk takes the claim, and logs when its chunk was taken over. Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 11 ++--- src/chunks.rs | 101 ++++++++++++++++++++++++++++++++----------- src/indexer.rs | 33 ++++++++------ tests/date_search.rs | 43 +++++++++++++----- 4 files changed, 134 insertions(+), 54 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 7cfcdd0d..2eca9d65 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -451,7 +451,7 @@ fn chunk_groups(mode: &str, groups: &[String], skip: &HashSet) -> HashSe /// A day chunk of a split group for an idle worker on `server`: the newest /// one pending, among the tracked groups this server hasnt said it lacks. -async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option<(String, i64)> { +async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option { // a server resting after a failure takes no chunks either if !sched.ctx.pool.indexing_tier().contains(&server) { return None; @@ -488,13 +488,14 @@ async fn worker(sched: Arc, server: usize, db: Db) { let Some(group) = sched.take_group(server) else { // nothing of its own: help with a split group's day chunks. not // marked busy, a group's chunks run on several servers at once - if let Some((group, day)) = take_chunk(&sched, server, &db).await { + if let Some(chunk) = take_chunk(&sched, server, &db).await { let settings = sched.settings.read().unwrap().clone(); let stats = sched.stats.clone(); + let group = chunk.group.clone(); let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); - let chunk = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &group, server, day, &mut progress); - let Some(result) = unless_stopped(&sched.ctx.stop, chunk).await else { break }; - sched.finish_chunk(group, server, result); + let run = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &chunk, server, &mut progress); + let Some(result) = unless_stopped(&sched.ctx.stop, run).await else { break }; + sched.finish_chunk(chunk.group, server, result); continue; } nap(Duration::from_secs(1), || sched.stopping()).await; diff --git a/src/chunks.rs b/src/chunks.rs index 383040fa..71193740 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -50,10 +50,21 @@ pub fn is_split(conn: &Connection, group: &str) -> Result { conn.prepare_cached("select 1 from backfill_chunks where grp = ? limit 1")?.exists([group]) } +/// A claimed chunk. Its server and claim time tell this claim from a later +/// one of the same chunk: a chunk that ran past CLAIM_TIMEOUT and was taken +/// over is the new owner's, finishing or giving back the old claim does nothing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Claim { + pub group: String, + pub day: i64, + pub server: String, + pub claimed_at: i64, +} + /// Atomically claim the newest chunk that is pending or whose claim went /// stale, of `groups`: (group, oldest day the server keeps), `i64::MIN` when /// any day will do. -pub fn claim(conn: &Connection, groups: &[(String, i64)], host: &str, now: i64) -> Result> { +pub fn claim(conn: &Connection, groups: &[(String, i64)], host: &str, now: i64) -> Result> { if groups.is_empty() { return Ok(None); } @@ -76,22 +87,31 @@ pub fn claim(conn: &Connection, groups: &[(String, i64)], host: &str, now: i64) values.push((now - CLAIM_TIMEOUT).into()); let found: Option<(String, i64)> = conn.prepare(&sql)?.query_row(rusqlite::params_from_iter(values), |r| Ok((r.get(0)?, r.get(1)?))).optional()?; - Ok(found) + Ok(found.map(|(group, day)| Claim { group, day, server: host.to_string(), claimed_at: now })) } -/// Mark a chunk as done. -pub fn finish(conn: &Connection, group: &str, day: i64) -> Result<()> { - conn.execute("update backfill_chunks set state = ? where grp = ? and day = ?", params![DONE, group, day])?; - Ok(()) +/// Mark a claimed chunk as done. False when the claim was taken over. +pub fn finish(conn: &Connection, claim: &Claim) -> Result { + let n = conn.execute( + &format!( + "update backfill_chunks set state = ? + where grp = ? and day = ? and state = {CLAIMED} and server = ? and claimed_at = ?" + ), + params![DONE, claim.group, claim.day, claim.server, claim.claimed_at], + )?; + Ok(n > 0) } -/// Return a claimed chunk to pending state. -pub fn release(conn: &Connection, group: &str, day: i64) -> Result<()> { - conn.execute( - "update backfill_chunks set state = ?, server = null, claimed_at = null where grp = ? and day = ?", - params![PENDING, group, day], +/// Return a claimed chunk to pending state. False when the claim was taken over. +pub fn release(conn: &Connection, claim: &Claim) -> Result { + let n = conn.execute( + &format!( + "update backfill_chunks set state = ?, server = null, claimed_at = null + where grp = ? and day = ? and state = {CLAIMED} and server = ? and claimed_at = ?" + ), + params![PENDING, claim.group, claim.day, claim.server, claim.claimed_at], )?; - Ok(()) + Ok(n > 0) } /// (done, total) chunks of a group @@ -123,6 +143,11 @@ mod tests { c } + /// the day of a claim + fn day(claimed: Result>) -> Option { + claimed.unwrap().map(|c| c.day) + } + #[test] fn days_are_claimed_newest_first_and_once() { let c = conn(); @@ -131,12 +156,14 @@ mod tests { assert!(is_split(&c, "g").unwrap()); let groups = vec![("g".to_string(), i64::MIN)]; - assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), Some(("g".into(), 20_000))); - assert_eq!(claim(&c, &groups, "b", 1000).unwrap(), Some(("g".into(), 19_999))); - finish(&c, "g", 20_000).unwrap(); - release(&c, "g", 19_999).unwrap(); - assert_eq!(claim(&c, &groups, "b", 1000).unwrap(), Some(("g".into(), 19_999)), "released goes back"); - assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), Some(("g".into(), 19_998))); + let a = claim(&c, &groups, "a", 1000).unwrap().unwrap(); + assert_eq!(a, Claim { group: "g".into(), day: 20_000, server: "a".into(), claimed_at: 1000 }); + let b = claim(&c, &groups, "b", 1000).unwrap().unwrap(); + assert_eq!(b.day, 19_999); + assert!(finish(&c, &a).unwrap()); + assert!(release(&c, &b).unwrap()); + assert_eq!(day(claim(&c, &groups, "b", 1000)), Some(19_999), "released goes back"); + assert_eq!(day(claim(&c, &groups, "a", 1000)), Some(19_998)); assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), None); assert_eq!(progress(&c, "g").unwrap(), (1, 3)); } @@ -148,7 +175,29 @@ mod tests { let groups = vec![("g".to_string(), i64::MIN)]; assert!(claim(&c, &groups, "a", 1000).unwrap().is_some()); assert_eq!(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT - 1).unwrap(), None); - assert_eq!(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT + 1).unwrap(), Some(("g".into(), 5))); + assert_eq!(day(claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT + 1)), Some(5)); + } + + #[test] + fn a_claim_taken_over_cant_be_finished_or_given_back() { + let c = conn(); + add(&c, "g", 5, 5).unwrap(); + let groups = vec![("g".to_string(), i64::MIN)]; + // a's chunk runs past CLAIM_TIMEOUT, b takes it over and finishes it + let a = claim(&c, &groups, "a", 1000).unwrap().unwrap(); + let b = claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT + 1).unwrap().unwrap(); + assert!(finish(&c, &b).unwrap()); + + // a's late release and finish change nothing: done, and b's + assert!(!release(&c, &a).unwrap()); + assert!(!finish(&c, &a).unwrap()); + let row = |c: &Connection| { + c.query_row("select state, server from backfill_chunks where grp = 'g' and day = 5", [], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, Option>(1)?)) + }) + .unwrap() + }; + assert_eq!(row(&c), (DONE, Some("b".to_string()))); } #[test] @@ -166,10 +215,10 @@ mod tests { let c = conn(); add(&c, "g", 12, 10).unwrap(); let from_11 = [("g".to_string(), 11)]; - assert_eq!(claim(&c, &from_11, "short", 0).unwrap(), Some(("g".into(), 12))); - assert_eq!(claim(&c, &from_11, "short", 0).unwrap(), Some(("g".into(), 11))); - assert_eq!(claim(&c, &from_11, "short", 0).unwrap(), None, "day 10 is older than it keeps"); - assert_eq!(claim(&c, &[("g".to_string(), i64::MIN)], "long", 0).unwrap(), Some(("g".into(), 10))); + assert_eq!(day(claim(&c, &from_11, "short", 0)), Some(12)); + assert_eq!(day(claim(&c, &from_11, "short", 0)), Some(11)); + assert_eq!(day(claim(&c, &from_11, "short", 0)), None, "day 10 is older than it keeps"); + assert_eq!(day(claim(&c, &[("g".to_string(), i64::MIN)], "long", 0)), Some(10)); } #[test] @@ -193,9 +242,9 @@ mod tests { // they should get different days (newest first, then next) assert!(a_claim.is_some() && b_claim.is_some()); - assert_ne!(a_claim.as_ref().map(|(_, d)| d), b_claim.as_ref().map(|(_, d)| d)); - assert_eq!(a_claim.as_ref().map(|(_, d)| d), Some(&20)); - assert_eq!(b_claim.as_ref().map(|(_, d)| d), Some(&19)); + assert_ne!(a_claim.as_ref().map(|c| c.day), b_claim.as_ref().map(|c| c.day)); + assert_eq!(a_claim.as_ref().map(|c| c.day), Some(20)); + assert_eq!(b_claim.as_ref().map(|c| c.day), Some(19)); // third claim should get None let c_c = Connection::open(&db_path).unwrap(); diff --git a/src/indexer.rs b/src/indexer.rs index f0821825..53d54b73 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -382,7 +382,7 @@ where .await?; let r = match claimed { // a day this server doesnt keep is left to the others, it isnt an error - Some((_, day)) => match run_chunk(ctx, settings, db, group, server, day, progress).await { + Some(chunk) => match run_chunk(ctx, settings, db, &chunk, server, progress).await { Err(e) if e.downcast_ref::().is_some() => Ok(Progress::default()), r => r, }, @@ -546,7 +546,7 @@ pub async fn claim_chunk( host: String, groups: std::collections::HashSet, oldest: HashMap, -) -> Result> { +) -> Result> { on_db(db, move |conn| { let split: Vec<(String, i64)> = crate::chunks::split_groups(conn)? .into_iter() @@ -565,24 +565,33 @@ pub async fn claim_chunk( /// roughly in article number order, duplicates are dropped when saved pub const CHUNK_OVERLAP: i64 = 3600; -/// Index one day (`day`, unix days) of `group` on `server`, for a group whose -/// backfill is split into day chunks (see chunks.rs). The chunk is marked done -/// when the whole day is in, released again if stopped part way or failing. +/// Index the day chunk `chunk` claimed (its day in unix days) on `server`, +/// for a group whose backfill is split into day chunks (see chunks.rs). The +/// chunk is marked done when the whole day is in, released again if stopped +/// part way or failing. Either is skipped once another worker took the chunk +/// over (this one ran past CLAIM_TIMEOUT): the chunk is that worker's. pub async fn run_chunk

( ctx: &PassContext, settings: &PassSettings, db: &Db, - group: &str, + chunk: &crate::chunks::Claim, server: usize, - day: i64, progress: &mut P, ) -> Result where P: FnMut(&Progress) + ?Sized, { + let (group, day) = (chunk.group.as_str(), chunk.day); let release = || { - let g = group.to_string(); - on_db(db, move |conn| Ok(crate::chunks::release(conn, &g, day)?)) + let c = chunk.clone(); + on_db(db, move |conn| Ok(crate::chunks::release(conn, &c)?)) + }; + let finish = async || { + let c = chunk.clone(); + if !on_db(db, move |conn| Ok(crate::chunks::finish(conn, &c)?)).await? { + println!("[CHUNK] {group} day {day}: taken over by another worker, leaving it to that one"); + } + anyhow::Ok(()) }; // give the chunk back after `e`, and return `e`: failing to give it back // is only logged (the claim goes stale and gets taken over) @@ -644,16 +653,14 @@ where Err(e) => return failed(e.into()).await, }; if start > end { - let g = group.to_string(); - on_db(db, move |conn| Ok(crate::chunks::finish(conn, &g, day)?)).await?; + finish().await?; return Ok(Progress::default()); } let pass = Pass { ctx, settings, db, group, server, key: cursor_key(&ctx.pool, server, group) }; match pass.process_range(start as i64, end as i64, "CHUNK", progress).await { Ok((saved, true)) => { - let g = group.to_string(); - on_db(db, move |conn| Ok(crate::chunks::finish(conn, &g, day)?)).await?; + finish().await?; Ok(saved) } Ok((saved, false)) => { diff --git a/tests/date_search.rs b/tests/date_search.rs index c5a1cf9b..d2554f8f 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -6,6 +6,20 @@ mod common; use atlas::nntp::BlockingPool; use common::{GROUP, Server, mock, post_at, spawn_server}; +/// `day` of `group` claimed by the mock's server, the way a worker claims it +/// (only the claim's owner finishes or gives back a chunk) +fn claimed(main: &std::path::Path, group: &str, day: i64) -> atlas::chunks::Claim { + let chunk = atlas::chunks::Claim { group: group.into(), day, server: "127.0.0.1".into(), claimed_at: 1 }; + atlas::db::open_at(main) + .unwrap() + .execute( + "update backfill_chunks set state = 1, server = ?, claimed_at = ? where grp = ? and day = ?", + rusqlite::params![chunk.server, chunk.claimed_at, group, day], + ) + .unwrap(); + chunk +} + /// posts 1..=1000, one per hour from 2026-01-01 00:00 UTC, with every 10th /// number missing and number 500 dated an hour too early fn hourly() -> Vec { @@ -59,8 +73,9 @@ fn a_day_chunk_indexes_that_day() { verbose: false, }; let db = atlas::indexer::shared_db(main_conn); + let chunk = claimed(&main, GROUP, day); let saved = - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})).unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); // hours 24..47 are articles 25..48, plus an hour of overlap each side // (24 and 49); 30 and 40 don't exist. 24..=49 minus 2 = 24 articles @@ -192,8 +207,9 @@ fn a_day_chunk_right_after_a_hole_of_millions_gets_every_article() { verbose: false, }; let db = atlas::indexer::shared_db(main_conn); + let chunk = claimed(&main, GROUP, day); let saved = - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})).unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); // the day's 1,440 posts and the hour after it; the hour before is the hole assert_eq!(saved.articles, 1_440 + 60); @@ -236,8 +252,9 @@ fn a_day_chunk_skips_a_gap_inside_the_day() { verbose: false, }; let db = atlas::indexer::shared_db(main_conn); + let chunk = claimed(&main, GROUP, day); let saved = - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})).unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); // day 2 is 720 numbers minus the 150 missing, plus the hour before it // (691..=720, 30 posts); nothing comes after 1440 @@ -273,9 +290,13 @@ fn a_failing_chunk_reports_its_own_error() { &ctx, &Default::default(), &db, - "alt.binaries.other", + &atlas::chunks::Claim { + group: "alt.binaries.other".into(), + day: 20_455, + server: "127.0.0.1".into(), + claimed_at: 1, + }, 0, - 20_455, &mut |_| {}, )) .unwrap_err(); @@ -315,8 +336,10 @@ fn a_day_older_than_the_server_keeps_is_given_back() { verbose: false, }; let db = atlas::indexer::shared_db(main_conn); - let run = - |day: i64| pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})); + let run = |day: i64| { + let chunk = claimed(&main, GROUP, day); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})) + }; let err = run(first_day - 1).unwrap_err(); let too_old = err.downcast_ref::().expect("a TooOld"); @@ -424,9 +447,9 @@ fn chunks_save_every_post_of(list: &[Slot], days: &[i64]) { verbose: false, }; let db = atlas::indexer::shared_db(main_conn); - let saved = pool - .block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, GROUP, 0, day, &mut |_| {})) - .unwrap(); + let chunk = claimed(&main, GROUP, day); + let saved = + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); let (from, to) = (day * 86_400 - 3600, (day + 1) * 86_400 + 3600); let want = list.iter().filter(|&&(_, t)| t >= from && t < to).count() as i64; assert_eq!(saved.articles, want, "day {day}"); From 321e8ed96b7eda0507576b91ac2d0ac3f1948481 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:41:18 -0500 Subject: [PATCH 041/159] Chunks done in the last hour count by when they finished The dashboard counted done chunks by claimed_at, which finish never moved: a chunk that took over an hour wasnt counted, one claimed in the last hour and done long ago was. backfill_chunks gets a done_at column that finish sets, and the dashboard counts by it. A table made before it (the running indexer's) gets the column added on the next open. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 56 +++++++++++++++++++++++++++++++++--------- src/indexer.rs | 3 ++- src/stats_dashboard.rs | 23 ++++++++++------- 3 files changed, 60 insertions(+), 22 deletions(-) diff --git a/src/chunks.rs b/src/chunks.rs index 71193740..f4c0079c 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -11,7 +11,8 @@ const PENDING: i64 = 0; const CLAIMED: i64 = 1; const DONE: i64 = 2; -/// Initialize the backfill_chunks table if it doesn't exist. +/// Initialize the backfill_chunks table if it doesn't exist, and give one +/// made before chunks kept their finish time its done_at column. pub fn create(conn: &Connection) -> Result<()> { conn.execute_batch( "create table if not exists backfill_chunks ( @@ -20,9 +21,22 @@ pub fn create(conn: &Connection) -> Result<()> { state INTEGER NOT NULL, server TEXT, claimed_at INTEGER, + done_at INTEGER, primary key (grp, day) ) without rowid;", - ) + )?; + if has_done_at(conn)? { + return Ok(()); + } + match conn.execute_batch("alter table backfill_chunks add column done_at INTEGER") { + // the indexer and the menu can both add it at once + Err(_) if has_done_at(conn)? => Ok(()), + r => r, + } +} + +fn has_done_at(conn: &Connection) -> Result { + conn.prepare("select 1 from pragma_table_info('backfill_chunks') where name = 'done_at'")?.exists([]) } /// days since 1970-01-01 UTC @@ -90,14 +104,14 @@ pub fn claim(conn: &Connection, groups: &[(String, i64)], host: &str, now: i64) Ok(found.map(|(group, day)| Claim { group, day, server: host.to_string(), claimed_at: now })) } -/// Mark a claimed chunk as done. False when the claim was taken over. -pub fn finish(conn: &Connection, claim: &Claim) -> Result { +/// Mark a claimed chunk as done at `now`. False when the claim was taken over. +pub fn finish(conn: &Connection, claim: &Claim, now: i64) -> Result { let n = conn.execute( &format!( - "update backfill_chunks set state = ? + "update backfill_chunks set state = ?, done_at = ? where grp = ? and day = ? and state = {CLAIMED} and server = ? and claimed_at = ?" ), - params![DONE, claim.group, claim.day, claim.server, claim.claimed_at], + params![DONE, now, claim.group, claim.day, claim.server, claim.claimed_at], )?; Ok(n > 0) } @@ -160,7 +174,7 @@ mod tests { assert_eq!(a, Claim { group: "g".into(), day: 20_000, server: "a".into(), claimed_at: 1000 }); let b = claim(&c, &groups, "b", 1000).unwrap().unwrap(); assert_eq!(b.day, 19_999); - assert!(finish(&c, &a).unwrap()); + assert!(finish(&c, &a, 1100).unwrap()); assert!(release(&c, &b).unwrap()); assert_eq!(day(claim(&c, &groups, "b", 1000)), Some(19_999), "released goes back"); assert_eq!(day(claim(&c, &groups, "a", 1000)), Some(19_998)); @@ -186,18 +200,36 @@ mod tests { // a's chunk runs past CLAIM_TIMEOUT, b takes it over and finishes it let a = claim(&c, &groups, "a", 1000).unwrap().unwrap(); let b = claim(&c, &groups, "b", 1000 + CLAIM_TIMEOUT + 1).unwrap().unwrap(); - assert!(finish(&c, &b).unwrap()); + let done_at = 1000 + CLAIM_TIMEOUT + 60; + assert!(finish(&c, &b, done_at).unwrap()); // a's late release and finish change nothing: done, and b's assert!(!release(&c, &a).unwrap()); - assert!(!finish(&c, &a).unwrap()); + assert!(!finish(&c, &a, done_at + 60).unwrap()); let row = |c: &Connection| { - c.query_row("select state, server from backfill_chunks where grp = 'g' and day = 5", [], |r| { - Ok((r.get::<_, i64>(0)?, r.get::<_, Option>(1)?)) + c.query_row("select state, server, done_at from backfill_chunks where grp = 'g' and day = 5", [], |r| { + Ok((r.get::<_, i64>(0)?, r.get::<_, Option>(1)?, r.get::<_, Option>(2)?)) }) .unwrap() }; - assert_eq!(row(&c), (DONE, Some("b".to_string()))); + assert_eq!(row(&c), (DONE, Some("b".to_string()), Some(done_at))); + } + + #[test] + fn a_table_from_before_done_at_gets_the_column() { + let c = Connection::open_in_memory().unwrap(); + c.execute_batch( + "create table backfill_chunks (grp TEXT NOT NULL, day INTEGER NOT NULL, state INTEGER NOT NULL, + server TEXT, claimed_at INTEGER, primary key (grp, day)) without rowid; + insert into backfill_chunks values ('g', 5, 1, 'a', 1000);", + ) + .unwrap(); + create(&c).unwrap(); + create(&c).unwrap(); + let a = Claim { group: "g".into(), day: 5, server: "a".into(), claimed_at: 1000 }; + assert!(finish(&c, &a, 1100).unwrap(), "the chunk claimed before is still there"); + let done_at: Option = c.query_row("select done_at from backfill_chunks", [], |r| r.get(0)).unwrap(); + assert_eq!(done_at, Some(1100)); } #[test] diff --git a/src/indexer.rs b/src/indexer.rs index 53d54b73..521b40c8 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -588,7 +588,8 @@ where }; let finish = async || { let c = chunk.clone(); - if !on_db(db, move |conn| Ok(crate::chunks::finish(conn, &c)?)).await? { + let now = chrono::Utc::now().timestamp(); + if !on_db(db, move |conn| Ok(crate::chunks::finish(conn, &c, now)?)).await? { println!("[CHUNK] {group} day {day}: taken over by another worker, leaving it to that one"); } anyhow::Ok(()) diff --git a/src/stats_dashboard.rs b/src/stats_dashboard.rs index 87929b05..ad1c4a21 100644 --- a/src/stats_dashboard.rs +++ b/src/stats_dashboard.rs @@ -94,7 +94,7 @@ fn load_chunks_stats(conn: &rusqlite::Connection) -> (i64, i64, i64, i64, i64) { let sql = "select count(*), coalesce(sum(pending > 0), 0), coalesce(sum(done), 0), coalesce(sum(total), 0), \ coalesce(sum(recent), 0) from (select grp, sum(state != 2) as pending, sum(state = 2) as done, count(*) as total, \ - sum(state = 2 and claimed_at > ?) as recent from backfill_chunks group by grp)"; + sum(state = 2 and done_at > ?) as recent from backfill_chunks group by grp)"; conn.query_row(sql, [hour_ago], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))).unwrap_or_default() } @@ -1455,15 +1455,20 @@ mod tests { let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); - // g1: finish 3 chunks (all done) + let claim = |group: &str, at: i64| { + crate::chunks::claim(&conn, &[(group.to_string(), i64::MIN)], "s", at).unwrap().unwrap() + }; + + // g1: 3 chunks, all finished two hours ago crate::chunks::add(&conn, "g1", 100, 98).unwrap(); - conn.execute("update backfill_chunks set state = 2 where grp = 'g1'", []).unwrap(); - // g2: finish 1 recently (with recent claimed_at), claim 1 recently (2 chunks total, 1 done, 1 in progress) + for _ in 0..3 { + assert!(crate::chunks::finish(&conn, &claim("g1", now - 7300), now - 7200).unwrap()); + } + // g2: 1 chunk claimed two hours ago and finished just now, 1 claimed just now + // (2 chunks total, 1 done, 1 in progress) crate::chunks::add(&conn, "g2", 200, 199).unwrap(); - conn.execute("update backfill_chunks set state = 2, claimed_at = ? where grp = 'g2' and day = 200", [now]) - .unwrap(); - conn.execute("update backfill_chunks set state = 1, claimed_at = ? where grp = 'g2' and day = 199", [now]) - .unwrap(); + assert!(crate::chunks::finish(&conn, &claim("g2", now - 7200), now).unwrap()); + claim("g2", now); // 2 groups, 1 in progress (g2 has pending), 4 done total, 5 total, 1 done in last hour let (groups, splitting, done, total, done_last_hour) = load_chunks_stats(&conn); @@ -1471,6 +1476,6 @@ mod tests { assert_eq!(splitting, 1); // 1 group with pending > 0 (g2) assert_eq!(done, 4); // g1 has 3 done, g2 has 1 done assert_eq!(total, 5); // 3 chunks for g1, 2 chunks for g2 - assert_eq!(done_last_hour, 1); // 1 chunk in g2 finished recently (claimed_at is recent) + assert_eq!(done_last_hour, 1, "finished in the last hour, though claimed before it"); } } From c28a05220e73517b032275f19da47a6ac380c577 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:43:48 -0500 Subject: [PATCH 042/159] Compaction and menu writes share a real lock The atlas.compacting marker was check-then-write: a menu save or purge could pass its check just before a compaction wrote the marker and then commit during the copy (lost at the swap), and two --compact runs could both see no marker. Compaction now holds an exclusive OS file lock on atlas.compacting for its whole run (try_lock, refused with Busy when taken), and AI search saves and the broken release purge hold it shared for theirs (refused while a compaction runs). The OS drops a lock with its process, soo the pid / start time staleness check goes, and the file stays behind unlocked. Auto compaction that finds the lock taken logs it, doesnt record last_compact, and tries again 10 minutes later. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/ai.rs | 5 +- src/bg_indexer.rs | 48 +++++++++++--- src/compact.rs | 145 ++++++++++++++++++++++++++++-------------- src/db.rs | 9 +-- src/procs.rs | 7 -- tests/auto_compact.rs | 2 +- 7 files changed, 148 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 583237ad..5b20ec07 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,7 @@ Release IDs change in the conversion, so NZB links that Prowlarr or your apps sa The `--compact` command rewrites every shard into a fresh database file while the indexer is stopped. It re-encodes message IDs with the current packing and seals every file that's due. The copy has no free space in it. Expect the first compaction to shrink the database a lot, roughly from 138 GB to 60 GB on a full database. Atlas checks each shard's copy before it replaces the original. If a shard fails, Atlas keeps its original and reports the error; the other shards are still compacted. -With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, an `atlas.compacting` file sits next to `atlas.db`, and the menu's AI search saves and broken release purge refuse to run until it's done. +With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, it holds a lock on the `atlas.compacting` file next to `atlas.db`, and the menu's AI search saves and broken release purge refuse to run until it's done. A compaction doesn't start while one of those is saving, or while another compaction runs; auto compaction then tries again 10 minutes later. The lock goes away with the process that holds it, so a crash leaves nothing to clean up (the file itself stays). A group that has caught up rests for 10 seconds before Atlas checks it again. Atlas parks a group that fails 3 times in a row for 5 minutes. diff --git a/src/ai.rs b/src/ai.rs index 5a4bc49f..d32550a6 100644 --- a/src/ai.rs +++ b/src/ai.rs @@ -128,8 +128,9 @@ pub fn fetch_group_candidates(config: &Config, limit: usize) -> Vec { /// Pull the newest headers from each group, keep keyword matches, save em. pub fn fetch_and_store(config: &Config, groups: &[String], keywords: &[String], max_per_group: i64) -> usize { - // nothing could be saved: dont fetch either - if let Err(e) = crate::compact::refuse_while_compacting(&crate::paths::database()) { + // nothing could be saved: dont fetch either. the save holds off a + // compaction itself, this only looks + if let Err(e) = crate::compact::hold_off_compaction(&crate::paths::database()) { println!("{e}"); return 0; } diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 2eca9d65..c63be7fd 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -29,6 +29,9 @@ const CONFIG_RELOAD: Duration = Duration::from_secs(5); /// how often auto_run_compact compacts the database pub const COMPACT_EVERY: Duration = Duration::from_secs(24 * 3600); +/// a compaction that couldnt take the lock (a `--compact` or a menu write +/// holds it) is tried again after this long +const COMPACT_RETRY: Duration = Duration::from_secs(10 * 60); /// servers with a host and password, in priority order fn usable_servers(config: &crate::config::Config) -> Vec { @@ -282,6 +285,8 @@ struct Scheduler { wind_down: AtomicBool, /// the compaction interval passed (set together with `wind_down`) compact_due: AtomicBool, + /// no compaction before this (one couldnt take the lock) + compact_after: Option, passes: AtomicUsize, } @@ -561,7 +566,8 @@ async fn compact_timer(sched: Arc) { let last = db::open_at(&paths::database()).ok().and_then(|conn| crate::store::get_meta(&conn, "last_compact").ok()); // no stored time: count from when the indexer started (rebuilds dont reset it) let last = last.flatten().unwrap_or_else(|| sched.stats.lock().unwrap().start_time as i64); - let due = UNIX_EPOCH + Duration::from_secs(last.max(0) as u64) + every; + let due = + (UNIX_EPOCH + Duration::from_secs(last.max(0) as u64) + every).max(sched.compact_after.unwrap_or(UNIX_EPOCH)); while !sched.stopping() { if SystemTime::now() >= due { println!("compacting the database, indexing resumes after"); @@ -588,13 +594,14 @@ async fn report(sched: Arc) { } /// Index with this set of servers until stopping, the config needs a rebuild -/// or a compaction is due (true). +/// or a compaction is due (true), not before `compact_after`. async fn run_servers( config: &Config, pool: Arc, states: RunStates, stats: Arc>, stop: Arc, + compact_after: Option, ) -> bool { let servers = usable_servers(config); let groups = config.tracked_groups(); @@ -623,6 +630,7 @@ async fn run_servers( stats, wind_down: AtomicBool::new(false), compact_due: AtomicBool::new(false), + compact_after, passes: AtomicUsize::new(0), }); @@ -664,12 +672,23 @@ async fn run_servers( sched.compact_due.load(Ordering::Relaxed) } +/// How an auto compaction went, for what the indexer does next. +enum Compacted { + /// done, failed or stopped: indexing goes on + Ran, + /// another compaction or a menu write held the lock, nothing was touched + Busy, + /// a shard is missing afterwards: the indexer stops + ShardMissing, +} + /// Compact every shard in this process (the indexer is wound down and its /// writers are gone, soo nothing else writes), then note the time. Noted on /// failure too, soo a failing compaction is tried again in 24 hours, not every /// minute. Not noted when it was stopped: that wasnt a failure, and it runs -/// again on the next start. False when a shard is missing afterwards. -async fn compact(config: &Config, stats: &Arc>, stop: &Arc) -> bool { +/// again on the next start. Nor when it couldnt take the lock: it's tried +/// again after COMPACT_RETRY. +async fn compact(config: &Config, stats: &Arc>, stop: &Arc) -> Compacted { write_status(true, "compacting the database", &config.index_mode, false, "running", false, 0); let main = paths::database(); let started = Instant::now(); @@ -679,6 +698,10 @@ async fn compact(config: &Config, stats: &Arc>, stop: &Arc println!("compacted in {}", crate::dashboard::human_time(started.elapsed().as_secs() as i64)), + Ok(Err(e)) if e.downcast_ref::().is_some() => { + ui::warn(&format!("couldnt compact the database: {e}. trying again in {}m", COMPACT_RETRY.as_secs() / 60)); + return Compacted::Busy; + } Ok(Err(e)) if stopped => println!("compaction stopped, the shards left are as they were: {e:#}"), Ok(Err(e)) => { ui::error(&format!("auto compaction failed, the originals were kept: {e:#}")); @@ -700,18 +723,20 @@ async fn compact(config: &Config, stats: &Arc>, stop: &Arc, stats: Arc>) { let states = RunStates::default(); let stopping = || stop.load(Ordering::Relaxed); + // a compaction that couldnt take the lock waits till then + let mut compact_after = None; while !stopping() { let Some(config) = load_config() else { @@ -736,11 +761,16 @@ async fn supervise(stop: Arc, stats: Arc>) { continue; } - let compact_due = run_servers(&config, pool.clone(), states.clone(), stats.clone(), stop.clone()).await; + let compact_due = + run_servers(&config, pool.clone(), states.clone(), stats.clone(), stop.clone(), compact_after).await; pool.close().await; - if compact_due && !stopping() && !compact(&config, &stats, &stop).await { - break; + if compact_due && !stopping() { + match compact(&config, &stats, &stop).await { + Compacted::Ran => compact_after = None, + Compacted::Busy => compact_after = Some(SystemTime::now() + COMPACT_RETRY), + Compacted::ShardMissing => break, + } } } } diff --git a/src/compact.rs b/src/compact.rs index da0c54b7..dadc855a 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -51,53 +51,80 @@ fn size(path: &Path) -> u64 { std::fs::metadata(path).map(|m| m.len()).unwrap_or(0) } -/// `atlas.compacting` next to `main`: there while a compaction runs, holding -/// the pid and start time of the process running it. +/// `atlas.compacting` next to `main`: a compaction holds it locked +/// exclusively for its whole run, and a write from outside the indexer holds +/// it shared for its own. The OS lets go of a lock when its process ends, soo +/// a crash leaves nothing to clean up. The file itself stays (removing a file +/// someone may be locking races them). pub fn lock_path(main: &Path) -> PathBuf { main.with_extension("compacting") } -/// A compaction of `main` is running. A lock left by a process that is gone -/// (or whose pid now belongs to another process) doesnt count. -pub fn in_progress(main: &Path) -> bool { - let Ok(text) = std::fs::read_to_string(lock_path(main)) else { return false }; - let mut fields = text.split_whitespace().map(|f| f.parse::().ok()); - let (Some(Some(pid)), Some(Some(started))) = (fields.next(), fields.next()) else { return false }; - let Ok(pid) = u32::try_from(pid) else { return false }; - // 0: the process couldnt see its own start time, the pid alone counts - crate::procs::started_at(pid).is_some_and(|t| started == 0 || t == started) +fn open_lock(main: &Path) -> Result { + let path = lock_path(main); + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(&path) + .with_context(|| format!("opening {}", path.display())) } -/// Writes from outside the indexer (AI search saves, purging) wait while -/// `main` is being compacted: they would land in the original after its copy -/// was taken and be lost when the copy replaces it. -pub fn refuse_while_compacting(main: &Path) -> Result<()> { - if in_progress(main) { - bail!("the database is being compacted; try again later"); +/// A compaction couldnt start: another one, or a write from outside the +/// indexer, holds the lock. +#[derive(Debug)] +pub struct Busy; + +impl std::fmt::Display for Busy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "another compaction or a database write holds the lock") } - Ok(()) } -/// The lock file of a running compaction, removed when dropped (done, -/// failed or stopped). -struct Lock(PathBuf); +impl std::error::Error for Busy {} + +/// Writes from outside the indexer (AI search saves, purging) hold this for +/// their whole run: they would land in the original after a compaction took +/// its copy, and be lost when the copy replaces it. Refused while a +/// compaction runs; a compaction cant start while one is held. +#[must_use = "the write is only safe while the guard is held"] +pub struct WriteGuard(std::fs::File); + +/// Hold off compaction for a write from outside the indexer, see `WriteGuard`. +pub fn hold_off_compaction(main: &Path) -> Result { + let file = open_lock(main)?; + match file.try_lock_shared() { + Ok(()) => Ok(WriteGuard(file)), + Err(std::fs::TryLockError::WouldBlock) => bail!("the database is being compacted; try again later"), + Err(std::fs::TryLockError::Error(e)) => Err(e).context("locking the database for a write"), + } +} + +impl Drop for WriteGuard { + fn drop(&mut self) { + // closing the file lets go too, but Windows may take a while to + let _ = self.0.unlock(); + } +} + +/// The lock of a running compaction, let go when dropped (done, failed or stopped). +struct Lock(std::fs::File); impl Lock { fn take(main: &Path) -> Result { - if in_progress(main) { - bail!("another compaction of {} is running", main.display()); + let file = open_lock(main)?; + match file.try_lock() { + Ok(()) => Ok(Lock(file)), + Err(std::fs::TryLockError::WouldBlock) => Err(Busy.into()), + Err(std::fs::TryLockError::Error(e)) => Err(e).context("locking the database for compacting"), } - let pid = std::process::id(); - let started = crate::procs::started_at(pid).unwrap_or(0); - let path = lock_path(main); - std::fs::write(&path, format!("{pid} {started}")).with_context(|| format!("writing {}", path.display()))?; - Ok(Lock(path)) } } impl Drop for Lock { fn drop(&mut self) { - let _ = std::fs::remove_file(&self.0); + let _ = self.0.unlock(); } } @@ -567,42 +594,68 @@ mod tests { ); } + fn busy(r: Result) -> bool { + r.is_err_and(|e| e.downcast_ref::().is_some()) + } + #[test] fn writes_from_outside_are_refused_while_compacting() { let dir = tempfile::tempdir().unwrap(); let main = dir.path().join("atlas.db"); db::create_db_at(&main).unwrap(); - assert!(refuse_while_compacting(&main).is_ok()); + drop(hold_off_compaction(&main).unwrap()); // seen from the progress messages, while the run is going let refused = std::sync::Mutex::new(Vec::new()); - let progress = |_: &str| refused.lock().unwrap().push(refuse_while_compacting(&main).is_err()); + let progress = |_: &str| refused.lock().unwrap().push(hold_off_compaction(&main).err().map(|e| e.to_string())); run(&main, &progress, &no_stop()).unwrap(); let refused = refused.into_inner().unwrap(); - assert!(!refused.is_empty() && refused.iter().all(|r| *r), "refused all through the run: {refused:?}"); - assert!(refuse_while_compacting(&main).is_ok(), "and not after it"); - assert!(!lock_path(&main).exists()); + assert!( + !refused.is_empty() + && refused.iter().all(|r| r.as_deref() == Some("the database is being compacted; try again later")), + "refused all through the run: {refused:?}" + ); + assert!(hold_off_compaction(&main).is_ok(), "and not after it"); // stopped or failing: the lock goes too let stop = Arc::new(AtomicBool::new(true)); assert!(run(&main, &|_| {}, &stop).is_err()); - assert!(!lock_path(&main).exists()); + assert!(hold_off_compaction(&main).is_ok()); } #[test] - fn a_lock_left_by_a_dead_process_doesnt_count() { + fn a_second_compaction_at_once_is_refused() { let dir = tempfile::tempdir().unwrap(); let main = dir.path().join("atlas.db"); - let pid = std::process::id(); - let started = crate::procs::started_at(pid).unwrap(); - std::fs::write(lock_path(&main), format!("{pid} {started}")).unwrap(); - let err = refuse_while_compacting(&main).unwrap_err().to_string(); - assert_eq!(err, "the database is being compacted; try again later"); - // the same pid but a different start: the pid was reused - std::fs::write(lock_path(&main), format!("{pid} {}", started + 1)).unwrap(); - assert!(refuse_while_compacting(&main).is_ok()); - std::fs::write(lock_path(&main), "junk").unwrap(); - assert!(refuse_while_compacting(&main).is_ok()); + db::create_db_at(&main).unwrap(); + + let second = std::sync::Mutex::new(Vec::new()); + let progress = |_: &str| { + let mut second = second.lock().unwrap(); + if second.is_empty() { + second.push(run(&main, &|_| {}, &no_stop())); + } + }; + run(&main, &progress, &no_stop()).unwrap(); + let second = second.into_inner().unwrap().pop().expect("the second ran during the first"); + assert!(busy(second), "the second was refused, the first finished"); + } + + #[test] + fn a_write_from_outside_holds_off_compaction() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + + let write = hold_off_compaction(&main).unwrap(); + // writes dont hold each other off + let other = hold_off_compaction(&main).unwrap(); + assert!(busy(run(&main, &|_| {}, &no_stop()))); + assert!(!store::shard_paths(&main).iter().any(|p| with_suffix(p, "compact").exists()), "nothing was started"); + drop((write, other)); + run(&main, &|_| {}, &no_stop()).unwrap(); + assert!(lock_path(&main).exists(), "the lock file stays, unlocked"); + assert!(hold_off_compaction(&main).is_ok()); } /// every release's NZB rows, by id diff --git a/src/db.rs b/src/db.rs index fbf39c6a..f6c6b595 100644 --- a/src/db.rs +++ b/src/db.rs @@ -265,21 +265,22 @@ fn rebuild_articles_unique(conn: &Connection) -> Result<()> { } /// Save releases from outside the indexer (AI search), each into its group's -/// shard. Refused while the database is being compacted. +/// shard. Refused while the database is being compacted, and holds off a +/// compaction until saved. pub fn save_releases_bulk(releases: &[Release]) -> anyhow::Result<()> { if releases.is_empty() { return Ok(()); } let main = paths::database(); - crate::compact::refuse_while_compacting(&main)?; + let _writing = crate::compact::hold_off_compaction(&main)?; Ok(store::save(&main, releases)?) } /// delete incomplete releases, returns bytes freed on disk. Refused while the -/// database is being compacted. +/// database is being compacted, and holds off a compaction until done. pub fn purge_broken() -> anyhow::Result { let main = paths::database(); - crate::compact::refuse_while_compacting(&main)?; + let _writing = crate::compact::hold_off_compaction(&main)?; let size = || store::shard_paths(&main).iter().map(|p| fs::metadata(p).map(|m| m.len() as i64).unwrap_or(0)).sum::(); let before = size(); diff --git a/src/procs.rs b/src/procs.rs index 0faee864..60f1d7dd 100644 --- a/src/procs.rs +++ b/src/procs.rs @@ -62,13 +62,6 @@ pub fn is_indexer_pid(pid: i64) -> bool { .unwrap_or(false) } -/// When process `pid` started (seconds since the epoch), None when it isnt running. -pub fn started_at(pid: u32) -> Option { - reap(); - with_process(pid, |p| (!matches!(p.status(), ProcessStatus::Zombie | ProcessStatus::Dead)).then(|| p.start_time())) - .flatten() -} - fn read_pid() -> Option { let text = fs::read_to_string(paths::pid_file()).ok()?; match text.trim().parse() { diff --git a/tests/auto_compact.rs b/tests/auto_compact.rs index b189da81..2f3e6743 100644 --- a/tests/auto_compact.rs +++ b/tests/auto_compact.rs @@ -65,7 +65,7 @@ fn compacts_on_schedule_and_keeps_indexing() { // every shard is a new file (compacting writes a copy and swaps it in), // and none of the copying is left lying around assert!(inodes().iter().zip(&before).all(|(now, was)| now != was), "every shard was rewritten"); - assert!(!home.path().join("atlas.compacting").exists(), "the compaction lock is gone"); + assert!(atlas::compact::hold_off_compaction(&main).is_ok(), "the compaction lock was let go"); for shard in &shards { for suffix in ["compact", "precompact"] { let stem = shard.file_stem().unwrap().to_string_lossy().into_owned(); From b480b26fc7c157edad7f8255da82407852750c79 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 17:58:46 -0500 Subject: [PATCH 043/159] A save that rolls back takes its new domains with it A shard writer kept the id of a domain row it inserted even when the save then failed and the row rolled back, so a later save could write segments pointing at a domain that doesn't exist and their NZBs lost the suffix. New domain ids are now staged per transaction and only become known once the save commits. Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 1 + src/store.rs | 99 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 96 insertions(+), 4 deletions(-) diff --git a/src/convert.rs b/src/convert.rs index c0ece811..1ff119f7 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -324,6 +324,7 @@ fn move_articles( } } tx.commit()?; + domains.committed(); } // into place in key order: an append, sorted on disk diff --git a/src/store.rs b/src/store.rs index 3dbf4be1..33b795b8 100644 --- a/src/store.rs +++ b/src/store.rs @@ -374,6 +374,9 @@ pub struct Domains { ids: HashMap, /// domains not in the table yet: how often they came up, bounded seen: HashMap, + /// rows this writer inserted in its open transaction: they move to `ids` + /// once it commits, and are gone if it rolls back + staged: HashMap, } /// domains a writer keeps in memory at most, known and not yet known @@ -393,7 +396,7 @@ impl Domains { /// (local blob, domain id) for a message-id; domain 0 = stored whole pub(crate) fn encode(&mut self, conn: &Connection, id: &str) -> Result<(Vec, i64)> { let Some((local, suffix)) = split_message_id(id) else { return Ok((whole(id), 0)) }; - if let Some(d) = self.ids.get(suffix) { + if let Some(d) = self.ids.get(suffix).or_else(|| self.staged.get(suffix)) { return Ok((pack_local(local), *d)); } let found: Option = conn @@ -413,14 +416,32 @@ impl Domains { } self.seen.remove(suffix); conn.prepare_cached("insert into domains (suffix) values (?)")?.execute([suffix])?; - conn.last_insert_rowid() + let domain = conn.last_insert_rowid(); + self.staged.insert(suffix.to_string(), domain); + return Ok((pack_local(local), domain)); } }; + self.remember(suffix.to_string(), domain); + Ok((pack_local(local), domain)) + } + + fn remember(&mut self, suffix: String, domain: i64) { if self.ids.len() >= DOMAIN_CACHE { self.ids.clear(); } - self.ids.insert(suffix.to_string(), domain); - Ok((pack_local(local), domain)) + self.ids.insert(suffix, domain); + } + + /// The transaction `encode` was used in committed: its new rows are known. + pub(crate) fn committed(&mut self) { + for (suffix, domain) in std::mem::take(&mut self.staged) { + self.remember(suffix, domain); + } + } + + /// The transaction `encode` was used in rolled back: its new rows are gone. + pub(crate) fn rolled_back(&mut self) { + self.staged.clear(); } } @@ -854,6 +875,22 @@ impl ShardWriter { conn: &mut Connection, ids: &Ids, batches: impl IntoIterator, + ) -> Result<()> { + let r = self.save_in_transaction(conn, ids, batches); + // domains inserted by a save that rolled back have no row: a later + // save must not use their ids + match r { + Ok(()) => self.domains.committed(), + Err(_) => self.domains.rolled_back(), + } + r + } + + fn save_in_transaction<'a>( + &mut self, + conn: &mut Connection, + ids: &Ids, + batches: impl IntoIterator, ) -> Result<()> { let shard = self.shard; let domains = &mut self.domains; @@ -1654,6 +1691,60 @@ mod tests { assert_eq!(writer.seal_some(&mut conn, now + 2).unwrap(), 0); } + #[test] + fn a_failed_save_leaves_no_domain_behind_in_the_writer() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + let mut writer = ShardWriter::new(shard); + // enough articles on one new domain for it to get a row + let release = |name: &str, first: u32| Release { + name: name.into(), + group: "alt.binaries.t".into(), + articles: (first..first + SHARED_AFTER + 1) + .map(|n| Article { + message_id: format!("<{n:032x}@fresh>"), + filename: Some("a.rar".into()), + part: Some(n as i64 + 1), + bytes: 10, + ..Default::default() + }) + .collect(), + ..Default::default() + }; + + // the save fails at its last write, after the domain's row went in + conn.execute_batch( + "create temp trigger no_totals before update on meta begin select raise(abort, 'forced'); end", + ) + .unwrap(); + assert!(writer.save(&mut conn, &Ids::new(&main), [std::slice::from_ref(&release("One", 0))]).is_err()); + conn.execute_batch("drop trigger no_totals").unwrap(); + let rows: i64 = conn.query_row("select count(*) from domains", [], |r| r.get(0)).unwrap(); + assert_eq!(rows, 0, "rolled back with the save"); + + let two = release("Two", 100); + writer.save(&mut conn, &Ids::new(&main), [std::slice::from_ref(&two)]).unwrap(); + let orphans: i64 = conn + .query_row( + "select count(*) from segments s where s.domain != 0 + and not exists (select 1 from domains d where d.id = s.domain)", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(orphans, 0, "every segment's domain has a row"); + let shards = db::open_with_shards(&main).unwrap(); + let id: i64 = shards.query_row("select id from releases where name = 'Two'", [], |r| r.get(0)).unwrap(); + let mut got: Vec = articles(&shards, id).unwrap().into_iter().map(|a| a.message_id).collect(); + let mut want: Vec = two.articles.iter().map(|a| a.message_id.clone()).collect(); + got.sort(); + want.sort(); + assert_eq!(got, want, "the NZB's message-ids are whole"); + } + #[test] fn writers_leave_files_untouched_since_the_upgrade_to_compaction() { let (_dir, main) = sealed_fixture(); From e15cf77e964b9c2dae18a2e6c981ddceeae44bdc Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:05:19 -0500 Subject: [PATCH 044/159] The indexer holds off compaction while it indexes A manual --compact that was already running when the indexer started got its copy taken while the indexer kept committing to the original, and the swap lost those writes. The indexer now holds the compaction lock shared while it indexes (across config rebuilds), lets go only for its own auto compaction and takes it back after. It refuses to start, with exit code 1, while a compaction holds the lock. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/bg_indexer.rs | 34 ++++++++++++++++-- src/compact.rs | 24 ++++++------- tests/auto_compact.rs | 11 ++++++ tests/compact_lock.rs | 83 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 139 insertions(+), 15 deletions(-) create mode 100644 tests/compact_lock.rs diff --git a/README.md b/README.md index 5b20ec07..83a068e0 100644 --- a/README.md +++ b/README.md @@ -268,7 +268,7 @@ Release IDs change in the conversion, so NZB links that Prowlarr or your apps sa The `--compact` command rewrites every shard into a fresh database file while the indexer is stopped. It re-encodes message IDs with the current packing and seals every file that's due. The copy has no free space in it. Expect the first compaction to shrink the database a lot, roughly from 138 GB to 60 GB on a full database. Atlas checks each shard's copy before it replaces the original. If a shard fails, Atlas keeps its original and reports the error; the other shards are still compacted. -With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, it holds a lock on the `atlas.compacting` file next to `atlas.db`, and the menu's AI search saves and broken release purge refuse to run until it's done. A compaction doesn't start while one of those is saving, or while another compaction runs; auto compaction then tries again 10 minutes later. The lock goes away with the process that holds it, so a crash leaves nothing to clean up (the file itself stays). +With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, it holds a lock on the `atlas.compacting` file next to `atlas.db`, and the indexer, the menu's AI search saves and the broken release purge refuse to run until it's done. A compaction doesn't start while the indexer runs (outside its own auto compaction), while one of those is saving, or while another compaction runs; auto compaction then tries again 10 minutes later. The lock goes away with the process that holds it, so a crash leaves nothing to clean up (the file itself stays). A group that has caught up rests for 10 seconds before Atlas checks it again. Atlas parks a group that fails 3 times in a row for 5 minutes. diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index c63be7fd..e0fa1705 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -732,11 +732,19 @@ async fn compact(config: &Config, stats: &Arc>, stop: &Arc, stats: Arc>) { +/// Index until stopping. Returns the exit code: not 0 when a compaction held +/// the database at the start. +async fn supervise(stop: Arc, stats: Arc>) -> i32 { let states = RunStates::default(); let stopping = || stop.load(Ordering::Relaxed); + let main = paths::database(); // a compaction that couldnt take the lock waits till then let mut compact_after = None; + // indexing writes the shards: no compaction from elsewhere while it runs + // (its copy would miss what's written meanwhile). let go only for this + // indexer's own compaction, taken again after it + let mut writing = None; + let mut started = false; while !stopping() { let Some(config) = load_config() else { @@ -750,6 +758,23 @@ async fn supervise(stop: Arc, stats: Arc>) { break; } + if writing.is_none() { + match crate::compact::hold_off_compaction(&main) { + Ok(guard) => writing = Some(guard), + Err(e) if !started => { + ui::error(&format!("not indexing: {e:#}")); + write_status(false, "", &config.index_mode, false, "stopped", true, 1); + return 1; + } + Err(e) => { + ui::warn(&format!("cant index yet: {e:#}")); + nap(Duration::from_secs(30), stopping).await; + continue; + } + } + } + started = true; + let pool = Arc::new(Pool::new(&servers)); // at least one server has to answer before spinning everything up @@ -766,6 +791,7 @@ async fn supervise(stop: Arc, stats: Arc>) { pool.close().await; if compact_due && !stopping() { + writing = None; match compact(&config, &stats, &stop).await { Compacted::Ran => compact_after = None, Compacted::Busy => compact_after = Some(SystemTime::now() + COMPACT_RETRY), @@ -773,6 +799,7 @@ async fn supervise(stop: Arc, stats: Arc>) { } } } + 0 } pub fn run() -> i32 { @@ -858,7 +885,10 @@ pub fn run_until(config: Config, stop: Arc) -> i32 { let stats = Arc::new(Mutex::new(Stats::new())); write_status(true, &groups_label(&config.tracked_groups(), 0), &config.index_mode, false, "running", false, 0); - runtime.block_on(supervise(stop, stats.clone())); + let code = runtime.block_on(supervise(stop, stats.clone())); + if code != 0 { + return code; + } write_status(false, "", &config.index_mode, false, "stopped", false, 0); stats.lock().unwrap().write("", "", false, false); diff --git a/src/compact.rs b/src/compact.rs index dadc855a..6a465846 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -52,10 +52,10 @@ fn size(path: &Path) -> u64 { } /// `atlas.compacting` next to `main`: a compaction holds it locked -/// exclusively for its whole run, and a write from outside the indexer holds -/// it shared for its own. The OS lets go of a lock when its process ends, soo -/// a crash leaves nothing to clean up. The file itself stays (removing a file -/// someone may be locking races them). +/// exclusively for its whole run, the indexer holds it shared while it +/// indexes, and a write from outside the indexer for its own. The OS lets go +/// of a lock when its process ends, soo a crash leaves nothing to clean up. +/// The file itself stays (removing a file someone may be locking races them). pub fn lock_path(main: &Path) -> PathBuf { main.with_extension("compacting") } @@ -71,27 +71,27 @@ fn open_lock(main: &Path) -> Result { .with_context(|| format!("opening {}", path.display())) } -/// A compaction couldnt start: another one, or a write from outside the -/// indexer, holds the lock. +/// A compaction couldnt start: another one, the indexer or a write from +/// outside it holds the lock. #[derive(Debug)] pub struct Busy; impl std::fmt::Display for Busy { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "another compaction or a database write holds the lock") + write!(f, "the indexer, another compaction or a database write holds the lock") } } impl std::error::Error for Busy {} -/// Writes from outside the indexer (AI search saves, purging) hold this for -/// their whole run: they would land in the original after a compaction took -/// its copy, and be lost when the copy replaces it. Refused while a -/// compaction runs; a compaction cant start while one is held. +/// The indexer while it indexes, and writes from outside it (AI search saves, +/// purging) for their whole run, hold this: they would land in the original +/// after a compaction took its copy, and be lost when the copy replaces it. +/// Refused while a compaction runs; a compaction cant start while one is held. #[must_use = "the write is only safe while the guard is held"] pub struct WriteGuard(std::fs::File); -/// Hold off compaction for a write from outside the indexer, see `WriteGuard`. +/// Hold off compaction while writing the shards, see `WriteGuard`. pub fn hold_off_compaction(main: &Path) -> Result { let file = open_lock(main)?; match file.try_lock_shared() { diff --git a/tests/auto_compact.rs b/tests/auto_compact.rs index 2f3e6743..5a5384ba 100644 --- a/tests/auto_compact.rs +++ b/tests/auto_compact.rs @@ -83,6 +83,17 @@ fn compacts_on_schedule_and_keeps_indexing() { assert!(Instant::now() < deadline, "indexing didnt resume"); std::thread::sleep(Duration::from_millis(200)); } + // and holds the lock again (shared: not a compaction of its own, which + // holds it exclusively) + let indexer_holds_it = || { + let lock = std::fs::File::open(atlas::compact::lock_path(&main)).unwrap(); + lock.try_lock().is_err() && lock.try_lock_shared().is_ok() + }; + let deadline = Instant::now() + Duration::from_secs(5); + while !indexer_holds_it() { + assert!(Instant::now() < deadline, "the indexer didnt take the lock back after compacting"); + std::thread::sleep(Duration::from_millis(20)); + } stop.store(true, Ordering::Relaxed); assert_eq!(runner.join().unwrap(), 0); } diff --git a/tests/compact_lock.rs b/tests/compact_lock.rs new file mode 100644 index 00000000..ce4bc75f --- /dev/null +++ b/tests/compact_lock.rs @@ -0,0 +1,83 @@ +//! The indexer and a compaction never write the shards at once: the indexer +//! doesnt start while a compaction holds the lock, and a compaction cant +//! start while the indexer runs (its writes would land in an original after +//! the copy was read, and be lost in the swap). +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post, spawn_server}; + +#[test] +fn the_indexer_and_a_compaction_lock_each_other_out() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + let posts: Vec = (1..=200) + .map(|n| post(n, &format!(r#""r{}.part{}.rar" yEnc (1/1)"#, n / 20, n % 20 + 1), 10, vec![])) + .collect(); + let port = spawn_server(Server::new(posts)); + let config = serde_json::json!({ + "usenet_servers": [{"host": "127.0.0.1", "username": "bob", "password": "secret", "port": port, "ssl": false, "connections": 2, "priority": 1}], + "groups": [GROUP], "index_mode": "backfill", "request_size": 50 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + let main = home.path().join("atlas.db"); + let articles = || atlas::store::totals(&atlas::db::open_with_shards(&main).unwrap()).unwrap().1; + let cfg = atlas::config::load_config().unwrap(); + let index = |stop: &Arc| { + let (cfg, stop) = (cfg.clone(), stop.clone()); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + // a compaction holds the lock: the indexer refuses to start and writes nothing + let compacting = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .open(atlas::compact::lock_path(&main)) + .unwrap(); + compacting.try_lock().unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let runner = index(&stop); + let deadline = Instant::now() + Duration::from_secs(10); + while !runner.is_finished() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + let refused = runner.is_finished(); + stop.store(true, Ordering::Relaxed); + let code = runner.join().unwrap(); + assert!(refused, "the indexer started while a compaction held the lock"); + assert_ne!(code, 0, "refusing is an error"); + assert_eq!(articles(), 0, "nothing was written"); + compacting.unlock().unwrap(); + drop(compacting); + + // the indexer runs: a compaction is refused, and touches nothing + let stop = Arc::new(AtomicBool::new(false)); + let runner = index(&stop); + let deadline = Instant::now() + Duration::from_secs(60); + while articles() == 0 { + assert!(Instant::now() < deadline, "never indexed"); + std::thread::sleep(Duration::from_millis(50)); + } + let never = Arc::new(AtomicBool::new(false)); + let err = atlas::compact::run(&main, &|_| {}, &never).unwrap_err(); + assert!(err.downcast_ref::().is_some(), "refused while indexing: {err:#}"); + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + + // and once it stopped, a compaction runs + atlas::compact::run(&main, &|_| {}, &never).unwrap(); +} From 8c062a963651b48ab37b0a9aed337887182019ef Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:12:32 -0500 Subject: [PATCH 045/159] Only the server going back furthest does a split's oldest day Any server whose retention started on the split's oldest day could finish it, soo one keeping it from 18:00 could mark it done while another kept it from 01:00. The first time a server gets there, every indexing server is asked for its first article; the one going back furthest is noted per group (backfill_deepest) and is the only one to do that day. The others give it back as too old. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/chunks.rs | 18 +++++++++++-- src/indexer.rs | 50 +++++++++++++++++++++++++++++++++--- tests/date_search.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 124 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 83a068e0..c4ee8cc2 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,7 @@ Start the indexer from the main menu with option 1. The indexer runs as a backgr ### Splitting big groups -When two or more indexing servers carry a group and its backfill has more than `split_min_backlog` article numbers left, Atlas splits the rest of its history into UTC day chunks. A worker with nothing of its own to do claims the newest pending chunk on any server that carries the group, so idle connections help with big groups. A server that doesn't keep a day from its start, because its retention is shorter, gives the chunk back for a server that does. Live indexing stays on the group's home server. The Backfill page of the stats dashboard shows split groups and their day chunks. +When two or more indexing servers carry a group and its backfill has more than `split_min_backlog` article numbers left, Atlas splits the rest of its history into UTC day chunks. A worker with nothing of its own to do claims the newest pending chunk on any server that carries the group, so idle connections help with big groups. A server that doesn't keep a day from its start, because its retention is shorter, gives the chunk back for a server that does. No server keeps the oldest day of the split from its start; the server that goes back furthest on it indexes what there is. Live indexing stays on the group's home server. The Backfill page of the stats dashboard shows split groups and their day chunks. ### How the database is stored diff --git a/src/chunks.rs b/src/chunks.rs index f4c0079c..cdf03bfc 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -12,7 +12,8 @@ const CLAIMED: i64 = 1; const DONE: i64 = 2; /// Initialize the backfill_chunks table if it doesn't exist, and give one -/// made before chunks kept their finish time its done_at column. +/// made before chunks kept their finish time its done_at column. Also the +/// server that goes back furthest, by split group (see `deepest`). pub fn create(conn: &Connection) -> Result<()> { conn.execute_batch( "create table if not exists backfill_chunks ( @@ -23,7 +24,8 @@ pub fn create(conn: &Connection) -> Result<()> { claimed_at INTEGER, done_at INTEGER, primary key (grp, day) - ) without rowid;", + ) without rowid; + create table if not exists backfill_deepest (grp TEXT PRIMARY KEY, server TEXT NOT NULL) without rowid;", )?; if has_done_at(conn)? { return Ok(()); @@ -140,6 +142,18 @@ pub fn oldest_day(conn: &Connection, group: &str) -> Result> { conn.query_row("select min(day) from backfill_chunks where grp = ?", [group], |r| r.get(0)) } +/// The server whose first article of a split group is the oldest: the one +/// to index the split's oldest day, which no server keeps whole. +pub fn deepest(conn: &Connection, group: &str) -> Result> { + conn.query_row("select server from backfill_deepest where grp = ?", [group], |r| r.get(0)).optional() +} + +/// Note `server` as the one going back furthest on `group`. +pub fn set_deepest(conn: &Connection, group: &str, server: &str) -> Result<()> { + conn.execute("insert or replace into backfill_deepest (grp, server) values (?, ?)", [group, server])?; + Ok(()) +} + /// groups with chunks still to do pub fn split_groups(conn: &Connection) -> Result> { conn.prepare("select distinct grp from backfill_chunks where state != 2 order by grp")? diff --git a/src/indexer.rs b/src/indexer.rs index 521b40c8..343efaa4 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -620,8 +620,8 @@ where // a day this server doesnt keep from its start would come out empty or // cut short, though another server may have all of it: give it back, and // the server takes no day that old for a while. the split's oldest day is - // the exception: no server goes back further, the one whose oldest - // article is on it does what there is + // the exception: no server keeps it whole, the one that goes back + // furthest on it does what there is let oldest = match ctx.pool.first_post(server, group, first, last).await { Ok(oldest) => oldest, Err(e) => return failed(e.into()).await, @@ -630,9 +630,17 @@ where Some(t) if t <= day * 86_400 => true, Some(t) if crate::chunks::unix_day(t) == day => { let g = group.to_string(); - match on_db(db, move |conn| Ok(crate::chunks::oldest_day(conn, &g)?)).await { - Ok(split_oldest) => split_oldest == Some(day), + let split_oldest = match on_db(db, move |conn| Ok(crate::chunks::oldest_day(conn, &g)?)).await { + Ok(d) => d, Err(e) => return failed(e).await, + }; + if split_oldest != Some(day) { + false + } else { + match goes_back_furthest(ctx, db, group, server, t).await { + Ok(furthest) => furthest, + Err(e) => return failed(e).await, + } } } _ => false, @@ -672,6 +680,40 @@ where } } +/// Whether `server`, whose first article of split `group` was posted at +/// `oldest`, goes back furthest of the indexing servers: the one to index the +/// split's oldest day. Found by asking each server for its first article the +/// first time, then kept, soo it doesnt move as retention rolls on (asked +/// again once that server is no longer an indexing one). A server that +/// cant be asked fails it: the chunk goes back and is tried again later. +async fn goes_back_furthest(ctx: &PassContext, db: &Db, group: &str, server: usize, oldest: i64) -> Result { + let host = ctx.pool.host(server); + let servers = ctx.pool.indexing_servers(); + let g = group.to_string(); + let known = on_db(db, move |conn| Ok(crate::chunks::deepest(conn, &g)?)).await?; + if let Some(deepest) = known.filter(|h| servers.iter().any(|&i| ctx.pool.host(i) == *h)) { + return Ok(deepest == host); + } + + let mut deepest = (oldest, host.clone()); + for other in servers.into_iter().filter(|&i| i != server) { + let (_, low, high, _) = match ctx.pool.group_on(other, group).await { + Ok(info) => info, + Err(e) if e.code() == Some(411) => continue, + Err(e) => return Err(e.into()), + }; + if let Some(t) = ctx.pool.first_post(other, group, low, high).await? + && t < deepest.0 + { + deepest = (t, ctx.pool.host(other)); + } + } + let (g, d) = (group.to_string(), deepest.1.clone()); + on_db(db, move |conn| Ok(crate::chunks::set_deepest(conn, &g, &d)?)).await?; + println!("[CHUNK] {group}: {} goes back furthest, it does the oldest day", deepest.1); + Ok(deepest.1 == host) +} + struct Pass<'a> { ctx: &'a PassContext, settings: &'a PassSettings, diff --git a/tests/date_search.rs b/tests/date_search.rs index d2554f8f..169c0e88 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -355,6 +355,67 @@ fn a_day_older_than_the_server_keeps_is_given_back() { assert_eq!(state(first_day + 1), 2, "an empty day it keeps is done"); } +/// The split's oldest day, which no server keeps from its start: only the +/// server that goes back furthest on it indexes it, from its first article. +/// One whose retention starts later that day gives it back. +#[test] +fn only_the_server_going_back_furthest_does_the_oldest_day() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour for 3 days from 2026-01-01, from `from_hour` on + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = |from_hour: u64, offset: u64| -> Vec { + (from_hour..72) + .map(|h| { + let when = start + chrono::Duration::hours(h as i64); + post_at(offset + h, &format!(r#""p{h}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() + }; + // "127.0.0.1" keeps the first day from 01:00, "localhost" from 18:00 + let deep = spawn_server(Server::new(posts(1, 1))); + let shallow = spawn_server(Server::new(posts(18, 1001))); + let mut later = mock(shallow, "secret", 2, 1); + later.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(deep, "secret", 2, 1), later]); + pool.connect().unwrap(); + + let day = atlas::chunks::unix_day(start.timestamp()); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day + 2, day).unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let conn = atlas::db::open_at(&main).unwrap(); + let run = |server: usize| { + let chunk = atlas::chunks::Claim { group: GROUP.into(), day, server: pool.pool.host(server), claimed_at: 1 }; + conn.execute( + "update backfill_chunks set state = 1, server = ?, claimed_at = 1 where grp = ? and day = ?", + rusqlite::params![chunk.server, GROUP, day], + ) + .unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, server, &mut |_| {})) + }; + let state = + || -> i64 { conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() }; + + // the 18:00 server gets to it first, and again: it isnt the one + for _ in 0..2 { + let err = run(1).expect_err("the server going back less far did the oldest day"); + assert!(err.downcast_ref::().is_some(), "{err:#}"); + assert_eq!(state(), 0, "given back, still pending"); + } + // the 01:00 one does it: 01:00 to midnight, plus the hour after + let saved = run(0).unwrap(); + assert_eq!(saved.articles, 24); + assert_eq!(state(), 2); +} + /// (number, unix seconds) of a post type Slot = (u64, i64); From 6b4b47d0cbc34301f8f0396328c230ce3c4c92ab Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:16:34 -0500 Subject: [PATCH 046/159] A chunk dropped by stopping is given back right away Stopping drops a pass stuck on the network, and a day chunk dropped that way skipped its release paths: it stayed claimed until CLAIM_TIMEOUT and a quick restart found it taken. run_chunk now gives its claim back when it's dropped part way (only while that claim still owns the chunk), which covers the idle workers' chunks and a split group's own pass alike. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 48 +++++++++++++++++++++++++++++++++++++++++-- tests/date_search.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 343efaa4..462b7093 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -568,8 +568,9 @@ pub const CHUNK_OVERLAP: i64 = 3600; /// Index the day chunk `chunk` claimed (its day in unix days) on `server`, /// for a group whose backfill is split into day chunks (see chunks.rs). The /// chunk is marked done when the whole day is in, released again if stopped -/// part way or failing. Either is skipped once another worker took the chunk -/// over (this one ran past CLAIM_TIMEOUT): the chunk is that worker's. +/// part way or failing, or dropped part way (stopping drops a pass stuck on +/// the network). Either is skipped once another worker took the chunk over +/// (this one ran past CLAIM_TIMEOUT): the chunk is that worker's. pub async fn run_chunk

( ctx: &PassContext, settings: &PassSettings, @@ -578,6 +579,49 @@ pub async fn run_chunk

( server: usize, progress: &mut P, ) -> Result +where + P: FnMut(&Progress) + ?Sized, +{ + let mut unfinished = GiveBackOnDrop { db, chunk, armed: true }; + let r = index_chunk(ctx, settings, db, chunk, server, progress).await; + unfinished.armed = false; + r +} + +/// Gives a claimed chunk back when its run is dropped part way, instead of +/// it staying claimed until CLAIM_TIMEOUT (a quick restart would find it +/// taken). Every way the run ends on its own finishes or gives it back already. +struct GiveBackOnDrop<'a> { + db: &'a Db, + chunk: &'a crate::chunks::Claim, + armed: bool, +} + +impl Drop for GiveBackOnDrop<'_> { + fn drop(&mut self) { + if !self.armed { + return; + } + // best effort and quick: one update, only while this claim still owns it + let r = match self.db.conn.lock() { + Ok(conn) => crate::chunks::release(&conn, self.chunk).map(|_| ()).map_err(anyhow::Error::from), + Err(_) => Err(anyhow!("the database connection is poisoned")), + }; + if let Err(e) = r { + let (group, day) = (&self.chunk.group, self.chunk.day); + println!("[CHUNK] {group} day {day}: couldnt give the chunk back when stopped: {e:#}"); + } + } +} + +async fn index_chunk

( + ctx: &PassContext, + settings: &PassSettings, + db: &Db, + chunk: &crate::chunks::Claim, + server: usize, + progress: &mut P, +) -> Result where P: FnMut(&Progress) + ?Sized, { diff --git a/tests/date_search.rs b/tests/date_search.rs index 169c0e88..07008b1a 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -355,6 +355,55 @@ fn a_day_older_than_the_server_keeps_is_given_back() { assert_eq!(state(first_day + 1), 2, "an empty day it keeps is done"); } +/// Stopping drops a chunk part way (here on a request stuck on the network): +/// the chunk goes back to pending right away, not after CLAIM_TIMEOUT, soo a +/// quick restart doesnt find it taken. +#[test] +fn a_chunk_dropped_by_stopping_is_given_back() { + use std::sync::atomic::{AtomicBool, Ordering}; + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let mut server = Server::new(hourly()); + let s = std::sync::Arc::get_mut(&mut server).unwrap(); + s.stall = std::time::Duration::from_secs(10); + s.stalls_left.store(1, Ordering::SeqCst); + let port = spawn_server(server.clone()); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + let day = + atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-02T00:00:00+00:00").unwrap().timestamp()); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: stop.clone(), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let chunk = claimed(&main, GROUP, day); + let stuck = server.clone(); + let stopper = std::thread::spawn(move || { + while stuck.stalled.load(Ordering::SeqCst) == 0 { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + stop.store(true, Ordering::SeqCst); + }); + let (settings, mut progress) = (Default::default(), |_: &atlas::indexer::Progress| {}); + let run = atlas::indexer::run_chunk(&ctx, &settings, &db, &chunk, 0, &mut progress); + assert!(pool.block_on(atlas::nntp::unless_stopped(&ctx.stop, run)).is_none(), "dropped by stopping"); + stopper.join().unwrap(); + + let state: i64 = atlas::db::open_at(&main) + .unwrap() + .query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)) + .unwrap(); + assert_eq!(state, 0, "given back"); +} + /// The split's oldest day, which no server keeps from its start: only the /// server that goes back furthest on it indexes it, from its first article. /// One whose retention starts later that day gives it back. From 1baafc7bb38ee89dbd83553463ab13bf86728a98 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:20:05 -0500 Subject: [PATCH 047/159] auto_run_compact applies on config reload The compaction timer was only started when auto_run_compact was on at the start of a run, and the config watcher ignored the flag, soo turning it on or off in config.json did nothing until a restart. The timer now always runs and looks at the flag every second; the watcher keeps it up to date. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/bg_indexer.rs | 27 +++++++----- tests/auto_compact_reload.rs | 81 ++++++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 11 deletions(-) create mode 100644 tests/auto_compact_reload.rs diff --git a/README.md b/README.md index c4ee8cc2..5873fe4d 100644 --- a/README.md +++ b/README.md @@ -175,7 +175,7 @@ Atlas also handles these provider quirks on its own: The background indexer reads `config.json` again every 5 seconds: -- New groups, `index_mode`, `batch_size`, and `request_size` apply immediately. +- New groups, `index_mode`, `batch_size`, `request_size`, and `auto_run_compact` apply immediately. - Changes to servers, logins, `connections`, or `parallel_groups` rebuild the connection pool. A login you fix in the file, or in **Settings > Usenet servers**, takes effect within a few seconds. - `api_host` and `api_port` apply when the API restarts. Restart Atlas, or use **Settings > Change API port**. diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index e0fa1705..2b33f2ad 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -287,6 +287,8 @@ struct Scheduler { compact_due: AtomicBool, /// no compaction before this (one couldnt take the lock) compact_after: Option, + /// auto_run_compact as config.json has it now + auto_compact: AtomicBool, passes: AtomicUsize, } @@ -520,9 +522,9 @@ async fn worker(sched: Arc, server: usize, db: Db) { } } -/// Re-read config.json while indexing: new groups / mode / batch settings -/// apply right away. Returns when servers or the parallelism changed (the -/// caller rebuilds) or when stopping. +/// Re-read config.json while indexing: new groups / mode / batch settings / +/// auto compaction apply right away. Returns when servers or the parallelism +/// changed (the caller rebuilds) or when stopping. async fn watch_config(sched: Arc, servers: Vec) { loop { nap(CONFIG_RELOAD, || sched.stopping()).await; @@ -538,6 +540,11 @@ async fn watch_config(sched: Arc, servers: Vec) { return; } + let auto = config.auto_run_compact; + if sched.auto_compact.swap(auto, Ordering::Relaxed) != auto { + println!("auto compaction turned {}", if auto { "on" } else { "off" }); + } + let settings = settings_of(&config); { let mut current = sched.settings.write().unwrap(); @@ -558,9 +565,10 @@ async fn watch_config(sched: Arc, servers: Vec) { } } -/// With auto_run_compact: once the interval has passed since the last -/// compaction (or since the indexer started, when there was none), wind down so -/// `supervise` can compact. +/// While auto_run_compact is on (looked at every second, config.json can +/// change it): once the interval has passed since the last compaction (or +/// since the indexer started, when there was none), wind down so `supervise` +/// can compact. async fn compact_timer(sched: Arc) { let every = compact_every(); let last = db::open_at(&paths::database()).ok().and_then(|conn| crate::store::get_meta(&conn, "last_compact").ok()); @@ -569,7 +577,7 @@ async fn compact_timer(sched: Arc) { let due = (UNIX_EPOCH + Duration::from_secs(last.max(0) as u64) + every).max(sched.compact_after.unwrap_or(UNIX_EPOCH)); while !sched.stopping() { - if SystemTime::now() >= due { + if sched.auto_compact.load(Ordering::Relaxed) && SystemTime::now() >= due { println!("compacting the database, indexing resumes after"); sched.compact_due.store(true, Ordering::Relaxed); sched.wind_down.store(true, Ordering::Relaxed); @@ -631,6 +639,7 @@ async fn run_servers( wind_down: AtomicBool::new(false), compact_due: AtomicBool::new(false), compact_after, + auto_compact: AtomicBool::new(config.auto_run_compact), passes: AtomicUsize::new(0), }); @@ -654,9 +663,7 @@ async fn run_servers( } tasks.spawn(watch_config(sched.clone(), servers)); tasks.spawn(report(sched.clone())); - if config.auto_run_compact { - tasks.spawn(compact_timer(sched.clone())); - } + tasks.spawn(compact_timer(sched.clone())); // the workers and the config watcher all stop on `stopping()` while tasks.join_next().await.is_some() { diff --git a/tests/auto_compact_reload.rs b/tests/auto_compact_reload.rs new file mode 100644 index 00000000..06e0f4bc --- /dev/null +++ b/tests/auto_compact_reload.rs @@ -0,0 +1,81 @@ +//! auto_run_compact applies while indexing, like the other settings: turned +//! on in config.json the indexer starts compacting on schedule, turned off it +//! stops. +//! +//! Unix only: it tells a compaction by the shard files' inodes. +//! +//! One test, and the environment is set before any thread starts. + +#![cfg(unix)] + +mod common; + +use std::os::unix::fs::MetadataExt; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post, spawn_server}; + +/// longer than the indexer takes to re-read config.json (every 5s) +const RELOAD: Duration = Duration::from_secs(7); + +#[test] +fn turning_auto_compaction_on_and_off_applies_while_indexing() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + std::env::set_var("ATLAS_COMPACT_EVERY_SECS", "1"); + } + let posts: Vec = (1..=100) + .map(|n| post(n, &format!(r#""r{}.part{}.rar" yEnc (1/1)"#, n / 20, n % 20 + 1), 10, vec![])) + .collect(); + let port = spawn_server(Server::new(posts)); + let config = |auto: bool| { + let config = serde_json::json!({ + "usenet_servers": [{"host": "127.0.0.1", "username": "bob", "password": "secret", "port": port, "ssl": false, "connections": 2, "priority": 1}], + "groups": [GROUP], "index_mode": "backfill", "request_size": 50, "auto_run_compact": auto + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + }; + config(false); + atlas::db::create_db().unwrap(); + let main = home.path().join("atlas.db"); + let shards = atlas::store::shard_paths(&main); + let inodes = || shards.iter().map(|p| std::fs::metadata(p).unwrap().ino()).collect::>(); + let compacted = || atlas::store::get_meta(&atlas::db::open_at(&main).unwrap(), "last_compact").unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + // off: the interval passes and nothing is compacted + let before = inodes(); + std::thread::sleep(Duration::from_secs(3)); + assert_eq!(compacted(), None, "compacted with auto_run_compact off"); + assert_eq!(inodes(), before); + + // turned on: it compacts + config(true); + let deadline = Instant::now() + RELOAD + Duration::from_secs(10); + while compacted().is_none() { + assert!(Instant::now() < deadline, "turned on, but never compacted"); + std::thread::sleep(Duration::from_millis(100)); + } + + // turned off again: once that's read, it stops + config(false); + std::thread::sleep(RELOAD); + let settled = inodes(); + std::thread::sleep(Duration::from_secs(3)); + assert_eq!(inodes(), settled, "turned off, but still compacting"); + + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); +} From c60c9e305627047d4e35543eaf1dba3a75a4985e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:44:43 -0500 Subject: [PATCH 048/159] A cap on headers fetched and not saved yet, over every pass Fetching ran far ahead of saving: every pass kept up to its connections' slices in flight plus twice that buffered, and with 83 passes on split day chunks the live run held ~112M headers (~60GB) it hadnt saved yet. The pool now has one budget, max_unsaved_headers (default 500,000, about 0.3GB of headers), shared by every pass. A slice takes its article numbers from it before its XOVER goes out, gives back what didnt come once the reply is in, and the rest once it's saved (or skipped). The room is taken before a connection, soo a pass waiting for room never holds a connection the passes saving need for their name lookups, and a stream's slices take it in order, one waiting at a time. A pass also buffers at most 4 slices. The Bottleneck page shows the unsaved headers against the cap; a change to the cap in config.json rebuilds the pool. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +- config.example.json | 1 + src/bg_indexer.rs | 16 ++++-- src/config.rs | 28 ++++++++++ src/indexer.rs | 3 + src/nntp.rs | 122 ++++++++++++++++++++++++++++++++++++++-- src/stats_dashboard.rs | 15 ++++- tests/unsaved_cap.rs | 123 +++++++++++++++++++++++++++++++++++++++++ 8 files changed, 300 insertions(+), 13 deletions(-) create mode 100644 tests/unsaved_cap.rs diff --git a/README.md b/README.md index 5873fe4d..9eacab69 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,7 @@ On first run, Atlas asks for one server (host, username, password, and port) and | `api_key` | generated | Newznab API key. Atlas creates it on first start and stores it here. | | `split_min_backlog` | `10000000` | Article numbers of backfill left before a group's backfill is split into day chunks that every server carrying the group can take. | | `auto_run_compact` | `false` | Compact the database every 24 hours; indexing pauses while it runs. | +| `max_unsaved_headers` | `500000` | Headers the indexer fetches ahead of saving them, over all groups at once. This bounds its memory: 500,000 headers take about 0.3 GB. A header request waits for room before it goes out, and its room comes back once its slice is saved. Raise it if the Bottleneck page shows it full while the database writers and connections have time to spare. | Atlas keeps any other keys you add to the file when it saves it. @@ -176,7 +177,7 @@ Atlas also handles these provider quirks on its own: The background indexer reads `config.json` again every 5 seconds: - New groups, `index_mode`, `batch_size`, `request_size`, and `auto_run_compact` apply immediately. -- Changes to servers, logins, `connections`, or `parallel_groups` rebuild the connection pool. A login you fix in the file, or in **Settings > Usenet servers**, takes effect within a few seconds. +- Changes to servers, logins, `connections`, `parallel_groups`, or `max_unsaved_headers` rebuild the connection pool. A login you fix in the file, or in **Settings > Usenet servers**, takes effect within a few seconds. - `api_host` and `api_port` apply when the API restarts. Restart Atlas, or use **Settings > Change API port**. ### Measure connection limits @@ -356,7 +357,7 @@ Names what limits indexing right now, and shows how busy each resource has been | Database writer | Share of the time the writer thread spends saving slices, how many slices wait for it, and how many slices go into each transaction. | | Usenet connections | Connections in use against what the providers allow, and requests waiting for a free connection. | | CPU | Cores the indexer uses, and how many of them parse headers. | -| Memory | System memory in use. | +| Memory | System memory in use, and headers fetched but not saved yet against `max_unsaved_headers`. | | Provider latency | How long a header request takes, and how many requests are in flight. | | Network | Data received from the servers per second. | | Disk | Data the indexer reads from and writes to disk per second. | diff --git a/config.example.json b/config.example.json index 1e2d8e56..56eabf90 100644 --- a/config.example.json +++ b/config.example.json @@ -43,6 +43,7 @@ ], "index_mode": "backfill", "auto_run_compact": false, + "max_unsaved_headers": 500000, "api_port": 9090, "api_host": "0.0.0.0" } diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 2b33f2ad..b944324e 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -442,7 +442,10 @@ impl Scheduler { stats.extra.insert("groups_configured".into(), json!(groups.len())); stats.extra.insert("workers".into(), json!(self.workers)); stats.extra.insert("pid".into(), json!(std::process::id())); - stats.extra.insert("load".into(), crate::profile::LOAD.snapshot()); + let mut load = crate::profile::LOAD.snapshot(); + load["unsaved_headers"] = json!(self.ctx.pool.unsaved_headers()); + load["max_unsaved_headers"] = json!(self.ctx.pool.max_unsaved()); + stats.extra.insert("load".into(), load); stats.write("", &mode, true, idle); } } @@ -523,8 +526,8 @@ async fn worker(sched: Arc, server: usize, db: Db) { } /// Re-read config.json while indexing: new groups / mode / batch settings / -/// auto compaction apply right away. Returns when servers or the parallelism -/// changed (the caller rebuilds) or when stopping. +/// auto compaction apply right away. Returns when servers, the parallelism or +/// the unsaved headers cap changed (the caller rebuilds) or when stopping. async fn watch_config(sched: Arc, servers: Vec) { loop { nap(CONFIG_RELOAD, || sched.stopping()).await; @@ -534,7 +537,10 @@ async fn watch_config(sched: Arc, servers: Vec) { let Some(config) = load_config() else { continue }; - if usable_servers(&config) != servers || plan_workers(&config) != sched.plan { + if usable_servers(&config) != servers + || plan_workers(&config) != sched.plan + || config.max_unsaved_headers() != sched.ctx.pool.max_unsaved() + { println!("config changed, restarting the indexer"); sched.wind_down.store(true, Ordering::Relaxed); return; @@ -782,7 +788,7 @@ async fn supervise(stop: Arc, stats: Arc>) -> i32 { } started = true; - let pool = Arc::new(Pool::new(&servers)); + let pool = Arc::new(Pool::new(&servers).with_max_unsaved(config.max_unsaved_headers())); // at least one server has to answer before spinning everything up if let Err(e) = pool.connect().await { diff --git a/src/config.rs b/src/config.rs index 62b73dc1..2c234d8f 100644 --- a/src/config.rs +++ b/src/config.rs @@ -25,6 +25,9 @@ pub const MAX_PARALLEL_GROUPS: usize = 256; /// measured on old articles, 10k per request got 3-6x the headers/s of 1k on /// one connection, and 50k was no better on most servers and erratic pub const DEFAULT_REQUEST_SIZE: u64 = 10_000; +/// headers fetched and not saved yet, over every group at once, when +/// config.json doesnt say (about 0.3GB of headers) +pub const DEFAULT_MAX_UNSAVED_HEADERS: u64 = 500_000; /// article numbers of backfill left on a group's home server before its /// backfill is split into day chunks over every server that carries it pub const SPLIT_MIN_BACKLOG: i64 = 10_000_000; @@ -136,6 +139,8 @@ pub struct Config { pub parallel_groups: Option, /// compact the database every 24 hours from the indexer pub auto_run_compact: bool, + /// None = DEFAULT_MAX_UNSAVED_HEADERS + pub max_unsaved_headers: Option, } impl Default for Config { @@ -153,6 +158,7 @@ impl Default for Config { split_min_backlog: None, parallel_groups: None, auto_run_compact: false, + max_unsaved_headers: None, } } } @@ -203,6 +209,12 @@ impl Config { self.request_size.unwrap_or(DEFAULT_REQUEST_SIZE).max(1) } + /// headers the indexer fetches ahead of saving them, over every group at once + pub fn max_unsaved_headers(&self) -> usize { + let n = self.max_unsaved_headers.unwrap_or(DEFAULT_MAX_UNSAVED_HEADERS).max(1); + usize::try_from(n).unwrap_or(usize::MAX) + } + /// article numbers of backfill left before a group's backfill is split /// over every server that carries it pub fn split_min_backlog(&self) -> i64 { @@ -278,6 +290,11 @@ impl Config { .and_then(|n| usize::try_from(n).ok()) .filter(|n| *n > 0), auto_run_compact: v.get("auto_run_compact").and_then(Value::as_bool).unwrap_or(false), + max_unsaved_headers: v + .get("max_unsaved_headers") + .and_then(as_int) + .and_then(|n| u64::try_from(n).ok()) + .filter(|n| *n > 0), }; cfg.sort_servers(); @@ -579,6 +596,17 @@ mod tests { assert_eq!(cfg.api_port(), 8000); assert_eq!(cfg.api_host, "127.0.0.1"); assert_eq!(cfg.index_mode, "dynamic"); + assert_eq!(cfg.max_unsaved_headers(), DEFAULT_MAX_UNSAVED_HEADERS as usize); + } + + #[test] + fn max_unsaved_headers_from_the_file() { + let cfg = |v: Value| Config::from_value(&v).max_unsaved_headers(); + assert_eq!(cfg(json!({"max_unsaved_headers": 2_000_000})), 2_000_000); + assert_eq!(cfg(json!({"max_unsaved_headers": "40000"})), 40_000); + // nonsense falls back to the default + assert_eq!(cfg(json!({"max_unsaved_headers": 0})), DEFAULT_MAX_UNSAVED_HEADERS as usize); + assert_eq!(cfg(json!({"max_unsaved_headers": -5})), DEFAULT_MAX_UNSAVED_HEADERS as usize); } #[test] diff --git a/src/indexer.rs b/src/indexer.rs index 462b7093..6b468f9c 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -865,6 +865,9 @@ impl Pass<'_> { let (mut low, mut high): (Option, Option) = (None, None); while let Some(slice) = rx.recv().await { + // the slice's room in the unsaved budget goes back once it's saved + // (or skipped), at the end of this loop + let _unsaved = slice.unsaved; let headers: Vec = match slice.result { Ok(h) => h, // 423 = no articles in that slice diff --git a/src/nntp.rs b/src/nntp.rs index 22b95af8..3a284651 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -160,6 +160,10 @@ const DOWN_FOR: Duration = Duration::from_secs(60); const GROUP_REFUSALS: usize = 3; /// how often a request in flight looks at the stop flag const STOP_POLL: Duration = Duration::from_millis(50); +/// fetched slices a pass lets wait for it to save them, besides the ones its +/// connections hold (the unsaved budget bounds them all, this keeps one pass +/// from taking a big share of it) +const SLICES_BUFFERED: usize = 4; /// `fut`'s output, or None as soon as `stop` is set: stopping doesnt wait on /// a provider that went quiet mid reply. Dropping a request part way is safe, @@ -781,6 +785,58 @@ pub struct Pool { timeout: Duration, /// groups their first choice server doesnt carry: the server that does homes: Mutex>, + unsaved: Arc, +} + +/// Headers fetched (or on their way) and not saved yet, over every pass on a +/// pool: what bounds the indexer's memory. A slice takes its article numbers +/// from it before its XOVER goes out, gives back what didnt come (gaps, an +/// empty or failed slice) once the reply is in, and the rest once it's saved. +struct UnsavedBudget { + permits: Arc, + cap: usize, + /// held right now, and the most ever held at once + now: AtomicUsize, + peak: AtomicUsize, +} + +impl UnsavedBudget { + fn new(cap: usize) -> Arc { + let cap = cap.clamp(1, Semaphore::MAX_PERMITS.min(u32::MAX as usize)); + Arc::new(UnsavedBudget { + permits: Arc::new(Semaphore::new(cap)), + cap, + now: AtomicUsize::new(0), + peak: AtomicUsize::new(0), + }) + } +} + +/// A slice's room in the unsaved budget, given back when dropped. +pub struct Unsaved { + permit: OwnedSemaphorePermit, + budget: Arc, +} + +impl Unsaved { + /// give back all but `headers` + fn keep(&mut self, headers: usize) { + let extra = self.permit.num_permits().saturating_sub(headers); + if extra > 0 + && let Some(back) = self.permit.split(extra) + { + self.budget.now.fetch_sub(extra, Ordering::Relaxed); + drop(back); + } + } +} + +impl Drop for Unsaved { + fn drop(&mut self) { + // counted down before the permit goes back (right after this), soo + // `now` never shows more than the cap + self.budget.now.fetch_sub(self.permit.num_permits(), Ordering::Relaxed); + } } impl Pool { @@ -811,6 +867,7 @@ impl Pool { failed_over_at: Mutex::new(None), timeout: DEFAULT_TIMEOUT, homes: Mutex::new(HashMap::new()), + unsaved: UnsavedBudget::new(crate::config::DEFAULT_MAX_UNSAVED_HEADERS as usize), } } @@ -819,6 +876,39 @@ impl Pool { self } + /// At most `headers` fetched and not saved yet, over every pass at once. + pub fn with_max_unsaved(mut self, headers: usize) -> Self { + self.unsaved = UnsavedBudget::new(headers); + self + } + + /// the cap on headers fetched and not saved yet + pub fn max_unsaved(&self) -> usize { + self.unsaved.cap + } + + /// headers fetched (or being fetched) and not saved yet, right now + pub fn unsaved_headers(&self) -> usize { + self.unsaved.now.load(Ordering::Relaxed) + } + + /// the most headers that were ever unsaved at once + pub fn unsaved_peak(&self) -> usize { + self.unsaved.peak.load(Ordering::Relaxed) + } + + /// Room for a slice of `numbers` article numbers in the unsaved budget, + /// waiting until there is. A slice bigger than the whole budget waits for + /// all of it. + async fn reserve_unsaved(&self, numbers: u64) -> Unsaved { + let budget = self.unsaved.clone(); + let n = usize::try_from(numbers).unwrap_or(usize::MAX).clamp(1, budget.cap); + let permit = budget.permits.clone().acquire_many_owned(n as u32).await.expect("semaphore closed"); + let now = budget.now.fetch_add(n, Ordering::Relaxed) + n; + budget.peak.fetch_max(now, Ordering::Relaxed); + Unsaved { permit, budget } + } + pub fn len(&self) -> usize { self.servers.len() } @@ -1408,6 +1498,14 @@ impl Pool { /// soon as it is free. No new slices are started once `stop` is set or a /// slice fails with anything but 423 (empty) / 5xx (not available), and /// once `stop` is set the slices still in flight are dropped unsent. + /// + /// Every slice holds its room in the pool's unsaved budget (`Unsaved`) + /// until the receiver drops it, soo a receiver keeps it until the slice is + /// saved. The room is taken before a connection, and the slices of one + /// stream take it in order, one waiting at a time. Nothing that holds room + /// waits for more: a slice holding some is fetching (and needs only a + /// connection, which no one waiting for room holds), waiting in the + /// channel for its receiver, or being saved, soo room always comes free. pub fn stream_headers( self: &Arc, group: &str, @@ -1419,8 +1517,8 @@ impl Pool { // several groups can stream from one server at once, the server's // semaphore keeps the total at its `connections` let workers = self.connections(i).max(1).min(slices.len().max(1)); - let (tx, rx) = tokio::sync::mpsc::channel(workers * 2); - let queue = Arc::new(Mutex::new(std::collections::VecDeque::from(slices))); + let (tx, rx) = tokio::sync::mpsc::channel(SLICES_BUFFERED); + let queue = Arc::new(tokio::sync::Mutex::new(std::collections::VecDeque::from(slices))); let halt = Arc::new(AtomicBool::new(false)); for _ in 0..workers { @@ -1433,10 +1531,22 @@ impl Pool { return; } - let Some((start, end)) = queue.lock().unwrap().pop_front() else { return }; + // the next slice and its room, the queue held meanwhile + let ((start, end), mut unsaved) = { + let mut queue = queue.lock().await; + let Some((start, end)) = queue.pop_front() else { return }; + let room = pool.reserve_unsaved(end.saturating_sub(start).saturating_add(1)); + let Some(unsaved) = unless_stopped(&stop, room).await else { return }; + ((start, end), unsaved) + }; + if halt.load(Ordering::Relaxed) { + return; + } + let Some(result) = unless_stopped(&stop, pool.xover_on(i, &group, start, end)).await else { return; }; + unsaved.keep(result.as_ref().map_or(0, Vec::len)); if let Err(e) = &result && e.code() != Some(423) @@ -1445,7 +1555,7 @@ impl Pool { halt.store(true, Ordering::Relaxed); } - if tx.send(HeaderSlice { start, end, result }).await.is_err() { + if tx.send(HeaderSlice { start, end, result, unsaved }).await.is_err() { return; } } @@ -1542,6 +1652,8 @@ pub struct HeaderSlice { pub start: u64, pub end: u64, pub result: Result>, + /// the slice's room in the unsaved budget: keep it until the slice is saved + pub unsaved: Unsaved, } /// For each job, fetch its message-ids in order until `extract` gives a @@ -1585,7 +1697,7 @@ impl BlockingPool { } pub fn from_config(cfg: &crate::config::Config) -> Self { - Self::new(&cfg.servers) + Self::from_pool(Pool::new(&cfg.servers).with_max_unsaved(cfg.max_unsaved_headers())) } pub fn from_pool(pool: Pool) -> Self { diff --git a/src/stats_dashboard.rs b/src/stats_dashboard.rs index ad1c4a21..bc9bc7c9 100644 --- a/src/stats_dashboard.rs +++ b/src/stats_dashboard.rs @@ -342,6 +342,9 @@ struct LoadRates { writer_busy: f64, /// slices waiting for the writer now queued: u64, + /// headers fetched and not saved yet now, and the cap on them + unsaved: u64, + max_unsaved: u64, /// slices saved per transaction per_batch: f64, /// share of the time the writer spent finishing checkpoints (part of writer_busy) @@ -379,6 +382,8 @@ fn load_rates(old: &Reading, new: &Reading) -> Option { Some(LoadRates { writer_busy: (ns("writer_busy_ns") / dt / writers).min(1.0), queued: new.load["writer_queued"].as_u64().unwrap_or(0), + unsaved: new.load["unsaved_headers"].as_u64().unwrap_or(0), + max_unsaved: new.load["max_unsaved_headers"].as_u64().unwrap_or(0), per_batch: if batches > 0.0 { delta("writer_slices") / batches } else { 0.0 }, writer_checkpoint: (ns("writer_checkpoint_ns") / dt / writers).min(1.0), latency: if xovers > 0.0 { ns("xover_ns") / xovers } else { 0.0 }, @@ -1064,7 +1069,13 @@ fn draw_bottleneck(f: &mut Frame, app: &App, area: Rect) { ( "memory", Some(mem_share), - format!("{} of {} used", human_bytes(app.mem_used as f64), human_bytes(app.mem_total as f64)), + format!( + "{} of {} used, {} of {} headers fetched and not saved yet", + human_bytes(app.mem_used as f64), + human_bytes(app.mem_total as f64), + r.unsaved, + r.max_unsaved + ), ), ( "provider latency", @@ -1327,6 +1338,7 @@ mod tests { load: serde_json::json!({ "at": at, "writer_busy_ns": (busy_s * 1e9) as u64, "writer_slices": slices, "writer_batches": batches, "writer_queued": 7, "xover_ns": (xover_s * 1e9) as u64, "xovers": xovers, + "unsaved_headers": 120_000, "max_unsaved_headers": 500_000, "lease_wait_ns": (wait_s * 1e9) as u64, "parse_ns": 0 }), disk: Some((at, disk, 0)), @@ -1341,6 +1353,7 @@ mod tests { .unwrap(); assert!((r.writer_busy - 0.95).abs() < 1e-9); assert_eq!((r.queued, r.per_batch), (7, 8.0)); + assert_eq!((r.unsaved, r.max_unsaved), (120_000, 500_000)); assert!((r.latency - 2.0).abs() < 1e-9 && (r.in_flight - 40.0).abs() < 1e-9); assert!((r.disk_read - 1e6).abs() < 1e-3); diff --git a/tests/unsaved_cap.rs b/tests/unsaved_cap.rs new file mode 100644 index 00000000..21cbbed0 --- /dev/null +++ b/tests/unsaved_cap.rs @@ -0,0 +1,123 @@ +//! The cap on headers fetched but not saved yet, over every pass at once: +//! many passes on few connections with a budget of two slices all finish, +//! every article is saved exactly once, the budget is never overrun and +//! nothing of it is left held afterwards. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; + +use atlas::indexer::{PassContext, PassSettings, RunStates, run_pass, shared_db}; +use atlas::nntp::Pool; +use common::{Server, mock, par2_file_desc, post, spawn_server, yenc_body}; + +const POSTS: u64 = 400; +const REQUEST: u64 = 20; +const GROUPS: usize = 16; + +/// `POSTS` articles in releases of one slice each, every release with a par2, +/// soo saving a slice needs BODY lookups on the connections the XOVERs use +fn busy_server() -> Arc { + let posts = (1..=POSTS) + .map(|n| { + let (rel, part) = ((n - 1) / REQUEST, (n - 1) % REQUEST); + if part == 0 { + let par2 = par2_file_desc(&format!("Real.Name.{rel}.mkv"), 9); + post(n, &format!(r#""rel{rel}.par2" yEnc (1/1)"#), 10, yenc_body("rel.par2", &par2)) + } else { + post(n, &format!(r#""rel{rel}.part{part}.rar" yEnc (1/1)"#), 10, vec![]) + } + }) + .collect(); + let mut s = Server::new(posts); + let s_mut = Arc::get_mut(&mut s).unwrap(); + s_mut.any_group = true; + s_mut.xover_delay = Duration::from_millis(5); + s +} + +/// Every group indexed to the end at once, on two servers of two +/// connections each, with room for `cap` unsaved headers. +fn index_everything(cap: usize) { + let servers = [busy_server(), busy_server()]; + let ports: Vec = servers.iter().map(|s| spawn_server(s.clone())).collect(); + let pool = + Arc::new(Pool::new(&[mock(ports[0], "secret", 2, 1), mock(ports[1], "secret", 2, 2)]).with_max_unsaved(cap)); + + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let db = shared_db(atlas::db::open_at(&main).unwrap()); + + let ctx = Arc::new(PassContext { + pool: pool.clone(), + states: RunStates::default(), + stop: Arc::new(AtomicBool::new(false)), + verbose: false, + }); + let settings = Arc::new(PassSettings { + mode: "backfill".into(), + batch_size: 100, + request_size: REQUEST, + split_min_backlog: i64::MAX, + }); + + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).enable_all().build().unwrap(); + let saved: Vec = rt.block_on(async { + pool.connect().await.unwrap(); + let mut passes = tokio::task::JoinSet::new(); + for g in 0..GROUPS { + let (ctx, settings, db) = (ctx.clone(), settings.clone(), db.clone()); + passes.spawn(async move { + let group = format!("alt.binaries.cap{g}"); + let mut saved = 0; + for _ in 0..50 { + let p = run_pass(&ctx, &settings, &db, &group, g % 2, &mut |_| {}).await.unwrap(); + saved += p.articles; + if ctx.states.is_idle(&group) { + return saved; + } + } + panic!("{group} never went idle"); + }); + } + let all = async { + let mut saved = Vec::new(); + while let Some(r) = passes.join_next().await { + saved.push(r.unwrap()); + } + saved + }; + tokio::time::timeout(Duration::from_secs(60), all).await.expect("the passes are stuck") + }); + + assert_eq!(saved, vec![POSTS as i64; GROUPS], "every article saved once, per group"); + let xovers: usize = servers.iter().map(|s| s.xovers.load(Ordering::SeqCst)).sum(); + assert_eq!(xovers, GROUPS * (POSTS / REQUEST) as usize, "every slice fetched once"); + + let peak = pool.unsaved_peak(); + assert!(peak <= cap, "{peak} headers unsaved at once, the cap is {cap}"); + assert!(peak >= cap.min(REQUEST as usize), "the cap was never reached ({peak}), the test proves nothing"); + assert_eq!(pool.unsaved_headers(), 0, "budget left held after every pass ended"); + + // the names came from the bodies: saving did its lookups + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (releases, named): (i64, i64) = conn + .query_row("select count(*), count(display_name) from releases", [], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap(); + assert_eq!((releases, named), ((GROUPS as u64 * POSTS / REQUEST) as i64, releases)); +} + +/// Two slices' worth for 16 passes of up to two connections each. +#[test] +fn many_passes_share_a_budget_of_two_slices() { + index_everything(2 * REQUEST as usize); +} + +/// A budget smaller than one slice: a slice waits for all of it. +#[test] +fn a_budget_smaller_than_a_slice_still_gets_through() { + index_everything(7); +} From 5edbd1c664940967ea112370cfddcd1fe6ebb102 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:49:39 -0500 Subject: [PATCH 049/159] Name lookups go to the least busy server Every par2/nfo BODY went to the active server first, and in the background indexer that is simply the first one, soo with seven servers indexing all name lookups queued on one small server (15 connections, busy with header requests) and held up saving. A lookup now starts on the indexing server with the fewest requests in use or waiting per connection (equally busy ones in priority order), then tries the other indexing servers from least to most busy, then the rest in priority order. With one server nothing changes. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- src/nntp.rs | 43 +++++++++++++++++++++++++++++++---- tests/common/mod.rs | 7 ++++++ tests/multi_server.rs | 53 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9eacab69..ec981147 100644 --- a/README.md +++ b/README.md @@ -153,7 +153,7 @@ Atlas keeps any other keys you add to the file when it saves it. | `port` | `563` | `563` is SSL and `119` is plain text. | | `ssl` | from the port | Forces SSL on or off. | | `connections` | `10` | Requests Atlas keeps in flight on this server at once. Set it to what your plan allows. See [Measure connection limits](#measure-connection-limits). | -| `priority` | `99` | Atlas asks servers with lower values first when it looks up par2 and nfo articles. Servers with equal priority keep their order in the file. | +| `priority` | `99` | Order of the servers for failover and for par2 and nfo lookups among equally busy servers. Lower values come first. Servers with equal priority keep their order in the file. | | `index` | `true` | Whether the server takes part in indexing. `false` keeps it for article lookups only, for example a block account whose data you don't want to spend on headers. | | `compress` | `true` | Requests gzip-compressed header listings. Servers without compression get plain requests, and Atlas turns compression off for a server that sends unreadable data. | @@ -163,7 +163,7 @@ The old single-server layout, with `host`, `username`, `password`, and `port` at - **Indexing uses every server at once, whatever its priority.** Atlas spreads groups over the indexing servers in proportion to their `connections`, and each server runs its own groups, so all connections stay busy. Each group stays on one server, because article numbers, and therefore the indexing cursors, differ between providers. A server that stops answering hands only its own groups to the others for a while. - **A group that a server doesn't carry:** Atlas looks it up on the other servers. -- **par2 and nfo articles:** Atlas asks the servers in priority order until one has them. +- **par2 and nfo articles:** Atlas asks the least busy indexing server first, so lookups don't all queue on one server. If it doesn't have the article, Atlas asks the other indexing servers from least to most busy, and then the remaining servers, such as those with `index: false`, in priority order. - **A server that can't connect:** Atlas skips it for a minute and moves its groups to the other servers. When a group moves, its cursor on the new server starts from the top. Atlas re-scans those articles but de-duplicates them, so it doesn't store anything twice. Atlas also handles these provider quirks on its own: diff --git a/src/nntp.rs b/src/nntp.rs index 3a284651..b142ee41 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -677,12 +677,31 @@ struct Server { /// connections atlas currently allows itself (starts at `connections`, /// shrinks when the provider refuses more) limit: AtomicUsize, + /// requests waiting for a free connection right now + waiting: AtomicUsize, /// for the stats dashboard headers: AtomicU64, wire: AtomicU64, text: AtomicU64, } +/// Counts a request waiting for a connection while it lives (a request +/// dropped while it waits is counted out too). +struct Waiting<'a>(&'a AtomicUsize); + +impl<'a> Waiting<'a> { + fn on(count: &'a AtomicUsize) -> Self { + count.fetch_add(1, Ordering::Relaxed); + Waiting(count) + } +} + +impl Drop for Waiting<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::Relaxed); + } +} + impl Server { fn compress(&self) -> bool { self.cfg.compress.unwrap_or(true) && !self.no_compress.load(Ordering::Relaxed) @@ -856,6 +875,7 @@ impl Pool { warned_auth: AtomicBool::new(false), warned_limit: AtomicBool::new(false), limit: AtomicUsize::new(cfg.connections().max(1) as usize), + waiting: AtomicUsize::new(0), headers: AtomicU64::new(0), wire: AtomicU64::new(0), text: AtomicU64::new(0), @@ -1061,7 +1081,10 @@ impl Pool { loop { let waited = Instant::now(); - let permit = server.permits.clone().acquire_owned().await.expect("semaphore closed"); + let permit = { + let _waiting = Waiting::on(&server.waiting); + server.permits.clone().acquire_owned().await.expect("semaphore closed") + }; crate::profile::Load::add_since(&crate::profile::LOAD.lease_wait_ns, waited); let idle = { @@ -1612,10 +1635,22 @@ impl Pool { } } - /// BODY from the active server, then every other server in priority order. + /// How busy server `i` is: requests on it and waiting for it, per connection. + fn busy(&self, i: usize) -> f64 { + let s = &self.servers[i]; + let limit = s.limit.load(Ordering::Relaxed).max(1); + let in_use = limit.saturating_sub(s.permits.available_permits()); + (in_use + s.waiting.load(Ordering::Relaxed)) as f64 / limit as f64 + } + + /// BODY from the least busy indexing server first, soo name lookups dont + /// all queue on one server (equally busy ones in priority order), then + /// from the others in priority order until one has it. pub async fn fetch_body(&self, message_id: &str) -> Result> { - let active = self.active_index(); - let order = std::iter::once(active).chain((0..self.servers.len()).filter(|&i| i != active)); + let mut order = self.indexing_tier(); + order.sort_by(|&a, &b| self.busy(a).total_cmp(&self.busy(b))); + let rest: Vec = (0..self.servers.len()).filter(|i| !order.contains(i)).collect(); + order.extend(rest); let mut last_err = Self::no_servers(); for i in order { diff --git a/tests/common/mod.rs b/tests/common/mod.rs index d9036ad8..74dbd626 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -57,6 +57,9 @@ pub struct Server { pub stalled: AtomicUsize, /// connections ever accepted pub accepted: AtomicUsize, + /// BODYs answered with the article, and how long each takes + pub bodies_sent: AtomicUsize, + pub body_delay: Duration, } impl Server { @@ -83,6 +86,8 @@ impl Server { stalls_left: AtomicUsize::new(0), stalled: AtomicUsize::new(0), accepted: AtomicUsize::new(0), + bodies_sent: AtomicUsize::new(0), + body_delay: Duration::ZERO, }) } } @@ -260,6 +265,8 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { } "BODY" => match posts_lock().iter().find(|p| p.message_id == arg).filter(|_| state.bodies) { Some(p) => { + thread::sleep(state.body_delay); + state.bodies_sent.fetch_add(1, Ordering::SeqCst); send(&mut out, format!("222 0 {arg}").as_bytes()); for l in &p.body { // dot stuffing diff --git a/tests/multi_server.rs b/tests/multi_server.rs index 74d3b283..c04bca7b 100644 --- a/tests/multi_server.rs +++ b/tests/multi_server.rs @@ -104,3 +104,56 @@ fn broken_compression_falls_back_to_plain() { let (_, articles) = atlas::store::totals(&conn).unwrap(); assert_eq!(articles, 40); } + +/// Name lookups spread over the servers instead of all queueing on the +/// first one: two servers with the same articles share the BODYs. +#[test] +fn name_lookups_spread_over_servers() { + let posts: Vec = (1..=40) + .map(|n| { + post(n, &format!(r#""thing{n}.nfo" yEnc (1/1)"#), 10, vec![format!("Release Name: Thing {n}").into_bytes()]) + }) + .collect(); + let servers: Vec> = (0..2) + .map(|_| { + let mut s = Server::new(posts.clone()); + Arc::get_mut(&mut s).unwrap().body_delay = Duration::from_millis(20); + s + }) + .collect(); + let (p1, p2) = (spawn_server(servers[0].clone()), spawn_server(servers[1].clone())); + + let pool = BlockingPool::new(&[mock(p1, "secret", 2, 1), mock(p2, "secret", 2, 2)]); + pool.connect().unwrap(); + + let extract: atlas::nntp::Extract = atlas::nfo::display_name; + let jobs = posts.iter().map(|p| vec![(p.message_id.clone(), extract)]).collect(); + let names = pool.first_names(jobs); + assert!(names.iter().all(Option::is_some), "{names:?}"); + + let sent: Vec = servers.iter().map(|s| s.bodies_sent.load(Ordering::SeqCst)).collect(); + assert_eq!(sent.iter().sum::(), 40); + assert!(sent.iter().all(|&n| n >= 10), "the lookups should be shared, got {sent:?}"); +} + +/// A server missing the article (430) hands the lookup to the next one. +#[test] +fn name_lookups_fall_back_on_a_missing_article() { + let posts: Vec = (1..=10) + .map(|n| { + post(n, &format!(r#""thing{n}.nfo" yEnc (1/1)"#), 10, vec![format!("Release Name: Thing {n}").into_bytes()]) + }) + .collect(); + let mut missing = Server::new(posts.clone()); + Arc::get_mut(&mut missing).unwrap().bodies = false; + let has = Server::new(posts.clone()); + let (p1, p2) = (spawn_server(missing.clone()), spawn_server(has.clone())); + + let pool = BlockingPool::new(&[mock(p1, "secret", 2, 1), mock(p2, "secret", 2, 2)]); + pool.connect().unwrap(); + + let extract: atlas::nntp::Extract = atlas::nfo::display_name; + let jobs = posts.iter().map(|p| vec![(p.message_id.clone(), extract)]).collect(); + assert!(pool.first_names(jobs).iter().all(Option::is_some)); + assert_eq!(has.bodies_sent.load(Ordering::SeqCst), 10); +} From 664abfbd68fe73d39af91096fc18278a91e7b2e6 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 18:54:09 -0500 Subject: [PATCH 050/159] 420 No Articles Selected is an empty range, like 423 Some providers answer an XOVER range with no articles in it with 420 instead of 423. That failed the slice, stopped the rest of the pass and threw away a whole 500k pass (6 times in the live run). Header slices, fetch_headers and the date probes now take 420 as empty, the same as 423. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 4 ++-- src/nntp.rs | 16 +++++++++++----- tests/common/mod.rs | 7 +++++++ tests/server_quirks.rs | 33 +++++++++++++++++++++++++++++++-- 4 files changed, 51 insertions(+), 9 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 6b468f9c..41c4116d 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -870,8 +870,8 @@ impl Pass<'_> { let _unsaved = slice.unsaved; let headers: Vec = match slice.result { Ok(h) => h, - // 423 = no articles in that slice - Err(e) if e.code() == Some(423) => { + // 423 (or 420) = no articles in that slice + Err(e) if e.is_empty_range() => { done += 1; continue; } diff --git a/src/nntp.rs b/src/nntp.rs index b142ee41..3e8a2448 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -43,6 +43,12 @@ impl NntpError { } } + /// an XOVER range with no articles in it: 423, or 420 ("No Articles + /// Selected") from some providers + pub fn is_empty_range(&self) -> bool { + matches!(self.code(), Some(420 | 423)) + } + /// 4xx pub fn is_temporary(&self) -> bool { self.code().is_some_and(|c| (400..500).contains(&c)) @@ -1306,7 +1312,7 @@ impl Pool { Some((if a.0 < first.0 { a } else { first }, if a.0 > last.0 { a } else { last })) } })), - Err(e) if e.code() == Some(423) => Ok(None), + Err(e) if e.is_empty_range() => Ok(None), Err(e) => Err(e), } } @@ -1519,7 +1525,7 @@ impl Pool { /// up to `connections` requests in flight, sending each slice to the /// receiver the moment it arrives. A connection picks up the next slice as /// soon as it is free. No new slices are started once `stop` is set or a - /// slice fails with anything but 423 (empty) / 5xx (not available), and + /// slice fails with anything but 423/420 (empty) / 5xx (not available), and /// once `stop` is set the slices still in flight are dropped unsent. /// /// Every slice holds its room in the pool's unsaved budget (`Unsaved`) @@ -1572,7 +1578,7 @@ impl Pool { unsaved.keep(result.as_ref().map_or(0, Vec::len)); if let Err(e) = &result - && e.code() != Some(423) + && !e.is_empty_range() && !e.is_permanent() { halt.store(true, Ordering::Relaxed); @@ -1590,7 +1596,7 @@ impl Pool { /// XOVER `start..=end` of `group` on the active server, split into slices /// fetched in parallel over its connections. Slices with no articles - /// (423) come back empty; any other failure fails the whole range. + /// (423/420) come back empty; any other failure fails the whole range. pub async fn fetch_headers(self: &Arc, group: &str, start: u64, end: u64) -> Result> { if end < start { return Ok(Vec::new()); @@ -1622,7 +1628,7 @@ impl Pool { let (idx, result) = joined.map_err(|e| NntpError::Protocol(format!("xover task failed: {e}")))?; match result { Ok(rows) => parts[idx] = rows, - Err(e) if e.code() == Some(423) => {} + Err(e) if e.is_empty_range() => {} Err(e) => { failure.get_or_insert(e); } diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 74dbd626..57222dc1 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -60,6 +60,8 @@ pub struct Server { /// BODYs answered with the article, and how long each takes pub bodies_sent: AtomicUsize, pub body_delay: Duration, + /// answer an empty XOVER range with 420 (some providers) instead of 423 + pub empty_is_420: bool, } impl Server { @@ -88,6 +90,7 @@ impl Server { accepted: AtomicUsize::new(0), bodies_sent: AtomicUsize::new(0), body_delay: Duration::ZERO, + empty_is_420: false, }) } } @@ -233,6 +236,10 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { let posts = posts_lock(); let lo = posts.partition_point(|p| p.number < a); let hits: Vec<&Post> = posts[lo..].iter().take_while(|p| p.number <= b).collect(); + if hits.is_empty() && state.empty_is_420 { + send(&mut out, b"420 No Articles Selected"); + continue; + } if hits.is_empty() { send(&mut out, b"423 no articles in that range"); continue; diff --git a/tests/server_quirks.rs b/tests/server_quirks.rs index 88f66b2b..9fe501aa 100644 --- a/tests/server_quirks.rs +++ b/tests/server_quirks.rs @@ -1,5 +1,6 @@ //! Provider behaviour seen in the wild: fewer connections allowed than -//! configured, and article only servers that reject GROUP. +//! configured, article only servers that reject GROUP, and empty ranges +//! answered with 420. mod common; @@ -7,8 +8,9 @@ use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; +use atlas::indexer::Indexer; use atlas::nntp::BlockingPool; -use common::{GROUP, Server, mock, post, spawn_server}; +use common::{GROUP, Server, index_until_idle, mock, post, spawn_server}; fn posts(n: u64) -> Vec { (1..=n).map(|i| post(i, &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 20, i % 20 + 1), 10, vec![])).collect() @@ -86,3 +88,30 @@ fn one_rejected_group_doesnt_take_a_server_out() { assert!(pool.block_on(pool.pool.select_group_on(0, GROUP)).is_ok()); assert_eq!(pool.pool.indexing_servers(), vec![0]); } + +/// A provider answering an empty range with `420 No Articles Selected` +/// instead of 423: the range is empty, the pass goes on and finishes. +#[test] +fn an_empty_range_answered_420_is_just_empty() { + // articles 1-100 and 301-400, nothing in between + let posts = posts(400).into_iter().filter(|p| !(101..=300).contains(&p.number)).collect(); + let mut state = Server::new(posts); + Arc::get_mut(&mut state).unwrap().empty_is_420 = true; + let port = spawn_server(state.clone()); + + let dir = tempfile::tempdir().unwrap(); + let db_path = dir.path().join("atlas.db"); + atlas::db::create_db_at(&db_path).unwrap(); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + let mut indexer = Indexer::new(pool, "backfill", atlas::db::open_at(&db_path).unwrap()); + indexer.request_size = 50; + index_until_idle(&mut indexer); + + let conn = atlas::db::open_with_shards(&db_path).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + assert_eq!(articles, 200); + let cursor: i64 = + conn.query_row("select backfill_cursor from groups where name = ?", [GROUP], |r| r.get(0)).unwrap(); + assert_eq!(cursor, 0, "the backfill went all the way down"); +} From b4444caa1d9ac26c96d5ad6a1a9af765a3f697c6 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:09:04 -0500 Subject: [PATCH 051/159] A test that saving keeps nothing per header The live run's footprint grew with headers processed, which could have been something on the parse/save path keeping a little of every header. This test indexes six groups' worth of headers through one shard writer with an allocator that counts live bytes, and fails when the heap grows past 4MB after the first rounds (a leak of 60 bytes a header fails it). It passes: nothing there is kept per header, the growth was headers fetched ahead of saving. Co-Authored-By: Claude Opus 5.5 --- tests/save_memory.rs | 108 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 tests/save_memory.rs diff --git a/tests/save_memory.rs b/tests/save_memory.rs new file mode 100644 index 00000000..1aca40dd --- /dev/null +++ b/tests/save_memory.rs @@ -0,0 +1,108 @@ +//! Nothing on the fetch, parse and save path keeps anything per header: the +//! heap after indexing more and more headers stays where it was. Counts the +//! live bytes of every allocation in this test binary. + +mod common; + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; + +use atlas::indexer::{PassContext, PassSettings, RunStates, run_pass, shared_db}; +use atlas::nntp::Pool; +use common::{Post, Server, mock, spawn_server}; + +struct Counting; +static LIVE: AtomicIsize = AtomicIsize::new(0); + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + LIVE.fetch_add(l.size() as isize, Ordering::Relaxed); + unsafe { System.alloc(l) } + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + LIVE.fetch_sub(l.size() as isize, Ordering::Relaxed); + unsafe { System.dealloc(p, l) } + } + unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 { + LIVE.fetch_add(n as isize - l.size() as isize, Ordering::Relaxed); + unsafe { System.realloc(p, l, n) } + } +} + +#[global_allocator] +static COUNTING: Counting = Counting; + +const POSTS: u64 = 40_000; +const ROUNDS: usize = 6; + +/// releases of 50 parts with obfuscated names, message-ids on 40 domains +fn posts() -> Vec { + (1..=POSTS) + .map(|n| { + let (rel, part) = (n / 50, n % 50 + 1); + Post { + number: n, + subject: format!(r#"[{rel}/999] - "{:016x}.part{part:02}.rar" yEnc ({part}/50)"#, rel * 7919), + message_id: format!("<{:024x}@d{}.example>", n.wrapping_mul(0x9e37_79b9_7f4a_7c15), n % 40), + bytes: 700_000, + body: vec![], + date: "Fri, 02 Oct 2026 10:11:12 +0000".into(), + } + }) + .collect() +} + +#[test] +fn the_heap_doesnt_grow_with_headers_saved() { + let mut s = Server::new(posts()); + Arc::get_mut(&mut s).unwrap().any_group = true; + let port = spawn_server(s); + let pool = Arc::new(Pool::new(&[mock(port, "secret", 8, 1)])); + + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let db = shared_db(atlas::db::open_at(&main).unwrap()); + let ctx = PassContext { + pool: pool.clone(), + states: RunStates::default(), + stop: Arc::new(AtomicBool::new(false)), + verbose: false, + }; + let settings = + PassSettings { mode: "backfill".into(), batch_size: 20_000, request_size: 2_000, split_min_backlog: i64::MAX }; + let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).enable_all().build().unwrap(); + rt.block_on(pool.connect()).unwrap(); + + // a group per round, all on one shard: one writer saves them all + let groups: Vec = (0..) + .map(|g| format!("alt.binaries.heap{g}")) + .filter(|g| atlas::store::shard_of(g) == 0) + .take(ROUNDS) + .collect(); + let mut live = Vec::new(); + for group in &groups { + rt.block_on(async { + for _ in 0..20 { + run_pass(&ctx, &settings, &db, group, 0, &mut |_| {}).await.unwrap(); + if ctx.states.is_idle(group) { + return; + } + } + panic!("{group} never went idle"); + }); + live.push(LIVE.load(Ordering::Relaxed)); + } + + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + assert_eq!(articles, ROUNDS as i64 * POSTS as i64); + + // after the first rounds warm up (caches, connections, statements), more + // headers saved leave the heap as it was: 400 bytes kept per header would + // be 64MB over these rounds + let grew = live[ROUNDS - 1] - live[1]; + let headers = (ROUNDS - 2) as isize * POSTS as isize; + assert!(grew < 4 << 20, "the heap grew {} bytes over {headers} headers: {live:?}", grew); +} From 7fc321b16a98e89c40bafd46afb41c9f2cce5830 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:28:03 -0500 Subject: [PATCH 052/159] A compaction cut short mid swap gets its original back A crash between moving a shard aside and moving its compacted copy in left nothing at the shard's path, and the next start made an empty shard there. Now every entry point takes the compaction lock before setting up the database, the setup puts back an original left as .precompact.db (and drops the copy), and a shard missing while the others are there is refused instead of made empty. Writers open shards without creating them, a compaction puts back a shard whose copy failed to move in, and it refuses to replace a backup left by an earlier one. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/app.rs | 14 +++- src/bg_indexer.rs | 38 +++++++--- src/compact.rs | 178 +++++++++++++++++++++++++++++++++++++++++++--- src/db.rs | 75 +++++++++++++++++-- src/indexer.rs | 2 +- src/main.rs | 8 +++ src/store.rs | 4 +- 8 files changed, 288 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index ec981147..9da09d05 100644 --- a/README.md +++ b/README.md @@ -269,7 +269,7 @@ Release IDs change in the conversion, so NZB links that Prowlarr or your apps sa The `--compact` command rewrites every shard into a fresh database file while the indexer is stopped. It re-encodes message IDs with the current packing and seals every file that's due. The copy has no free space in it. Expect the first compaction to shrink the database a lot, roughly from 138 GB to 60 GB on a full database. Atlas checks each shard's copy before it replaces the original. If a shard fails, Atlas keeps its original and reports the error; the other shards are still compacted. -With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, it holds a lock on the `atlas.compacting` file next to `atlas.db`, and the indexer, the menu's AI search saves and the broken release purge refuse to run until it's done. A compaction doesn't start while the indexer runs (outside its own auto compaction), while one of those is saving, or while another compaction runs; auto compaction then tries again 10 minutes later. The lock goes away with the process that holds it, so a crash leaves nothing to clean up (the file itself stays). +With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, it holds a lock on the `atlas.compacting` file next to `atlas.db`, and the indexer, the menu's AI search saves and the broken release purge refuse to run until it's done. A compaction doesn't start while the indexer runs (outside its own auto compaction), while one of those is saving, or while another compaction runs; auto compaction then tries again 10 minutes later. The lock goes away with the process that holds it, so a crash leaves nothing to clean up (the file itself stays). A crash in the middle of swapping a shard can leave its original moved aside as `atlas.sN.precompact.db` with nothing in its place. The next start of atlas, the indexer or a compaction puts it back (and removes the half swapped copy), taking the lock first. A shard that is missing with no backup next to it, while the other shards are there, stops atlas from starting instead of being made again empty; put it back first. A group that has caught up rests for 10 seconds before Atlas checks it again. Atlas parks a group that fails 3 times in a row for 5 minutes. diff --git a/src/app.rs b/src/app.rs index 26c4e39a..c100e765 100644 --- a/src/app.rs +++ b/src/app.rs @@ -707,9 +707,17 @@ fn status_line(config: &Config, indexing: bool) -> Line { } pub fn main_menu() -> i32 { - if let Err(e) = create_db() { - ui::error(&format!("couldnt open database {}: {e}", paths::database().display())); - return 1; + // compaction is held off only while setting up: the menu itself doesnt + // write (its saves hold it off for themselves) + match create_db() { + Ok(Some(_setup)) => {} + Ok(None) => ui::warn( + "the database is being compacted; indexing, AI search saves and purging are refused till it's done", + ), + Err(e) => { + ui::error(&format!("couldnt open database {}: {e:#}", paths::database().display())); + return 1; + } } let mut config = match load_config() { diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index b944324e..99d774c5 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -11,6 +11,7 @@ use serde::Serialize; use serde_json::json; use crate::atomic::write_atomic; +use crate::compact::WriteGuard; use crate::config::{Config, UsenetServer, load_config}; use crate::db; use crate::indexer::{Db, NotCarried, PassContext, PassSettings, Progress, RunStates, TooOld, run_pass, shared_db}; @@ -746,8 +747,9 @@ async fn compact(config: &Config, stats: &Arc>, stop: &Arc, stats: Arc>) -> i32 { +/// the database at the start. `writing` is the hold on compaction taken +/// before setting up the database, if there was one. +async fn supervise(stop: Arc, stats: Arc>, writing: Option) -> i32 { let states = RunStates::default(); let stopping = || stop.load(Ordering::Relaxed); let main = paths::database(); @@ -756,7 +758,7 @@ async fn supervise(stop: Arc, stats: Arc>) -> i32 { // indexing writes the shards: no compaction from elsewhere while it runs // (its copy would miss what's written meanwhile). let go only for this // indexer's own compaction, taken again after it - let mut writing = None; + let mut writing = writing; let mut started = false; while !stopping() { @@ -831,10 +833,20 @@ pub fn run() -> i32 { return 1; } - if let Err(e) = db::create_db() { - ui::error(&format!("couldnt open database: {e}")); - return 1; - } + // compaction held off from before setting up: a shard it's swapping + // would look missing. kept for indexing + let writing = match db::create_db() { + Ok(Some(held)) => held, + Ok(None) => { + ui::error("not indexing: the database is being compacted; try again later"); + write_status(false, "", &config.index_mode, false, "stopped", true, 1); + return 1; + } + Err(e) => { + ui::error(&format!("couldnt open database: {e:#}")); + return 1; + } + }; // one time move of an older database into the shards, here and not in the // menu because it takes a while on a big one. the menu shows the progress @@ -852,8 +864,8 @@ pub fn run() -> i32 { return 1; } } - if let Err(e) = db::create_db() { - ui::error(&format!("couldnt open the converted database: {e}")); + if let Err(e) = db::create_db_at(&main) { + ui::error(&format!("couldnt open the converted database: {e:#}")); return 1; } } @@ -866,12 +878,16 @@ pub fn run() -> i32 { let _ = signal_hook::flag::register(signal_hook::consts::SIGINT, stop.clone()); } - run_until(config, stop) + index(config, stop, Some(writing)) } /// The indexing loop from `run`, stopping once `stop` is set (tests set it /// directly, `run` wires it to SIGTERM / SIGINT). pub fn run_until(config: Config, stop: Arc) -> i32 { + index(config, stop, None) +} + +fn index(config: Config, stop: Arc, writing: Option) -> i32 { // start sabnzbd soo its ready when you wanna download. on its own thread // soo indexing doesnt sit around for up to 90s waiting on it if sab::available() && !sab::is_running() { @@ -898,7 +914,7 @@ pub fn run_until(config: Config, stop: Arc) -> i32 { let stats = Arc::new(Mutex::new(Stats::new())); write_status(true, &groups_label(&config.tracked_groups(), 0), &config.index_mode, false, "running", false, 0); - let code = runtime.block_on(supervise(stop, stats.clone())); + let code = runtime.block_on(supervise(stop, stats.clone(), writing)); if code != 0 { return code; } diff --git a/src/compact.rs b/src/compact.rs index 6a465846..bd6b1485 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -14,7 +14,9 @@ //! original) before it replaces the original. The originals stay next to it //! as `atlas.sN.precompact.db` until every shard has had its turn, then they //! go. A shard that fails keeps its original in place and the others carry -//! on; `run` then returns an error naming each failed shard. +//! on; `run` then returns an error naming each failed shard. A swap cut short +//! between moving the original aside and the copy in (a crash) is undone by +//! the next start or compaction, see `recover_cut_swaps`. use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -36,7 +38,8 @@ const CHECK_SAMPLE: i64 = 300; /// rows per transaction const BATCH: usize = 500_000; -fn with_suffix(path: &Path, suffix: &str) -> PathBuf { +/// `atlas.s3.db` -> `atlas.s3.{suffix}.db` +pub(crate) fn with_suffix(path: &Path, suffix: &str) -> PathBuf { let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); path.with_file_name(format!("{stem}.{suffix}.db")) } @@ -93,10 +96,15 @@ pub struct WriteGuard(std::fs::File); /// Hold off compaction while writing the shards, see `WriteGuard`. pub fn hold_off_compaction(main: &Path) -> Result { + try_hold_off_compaction(main)?.ok_or_else(|| anyhow!("the database is being compacted; try again later")) +} + +/// `hold_off_compaction`, None while a compaction runs. +pub fn try_hold_off_compaction(main: &Path) -> Result> { let file = open_lock(main)?; match file.try_lock_shared() { - Ok(()) => Ok(WriteGuard(file)), - Err(std::fs::TryLockError::WouldBlock) => bail!("the database is being compacted; try again later"), + Ok(()) => Ok(Some(WriteGuard(file))), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), Err(std::fs::TryLockError::Error(e)) => Err(e).context("locking the database for a write"), } } @@ -128,6 +136,39 @@ impl Drop for Lock { } } +/// Put back the original of every shard whose swap was cut short (a crash, +/// or its copy failing to move in): the original moved aside as +/// `.precompact.db` and nothing in its place. Nothing writes a shard while +/// it's compacted, soo the original is whole: it goes back, and the copy +/// goes. A backup next to a shard that is in place is kept (the copy may have +/// gone in, or a shard made empty in its place by an older atlas; which one +/// is whole isnt known). Returns a line for each, to show. +/// +/// Only with the lock held (either kind): a running compaction has a shard +/// moved aside on purpose for a moment. +pub fn recover_cut_swaps(main: &Path) -> Result> { + let mut said = Vec::new(); + for path in store::shard_paths(main) { + let original = with_suffix(&path, "precompact"); + if !original.try_exists()? { + continue; + } + if path.try_exists()? { + said.push(format!( + "{} is left from a compaction that was cut short, and kept: once {} reads back fine, remove it", + original.display(), + path.display() + )); + continue; + } + std::fs::rename(&original, &path) + .with_context(|| format!("putting {} back as {}", original.display(), path.display()))?; + remove_db(&with_suffix(&path, "compact")); + said.push(format!("{} was moved aside by a compaction that was cut short; it's back in place", path.display())); + } + Ok(said) +} + /// What compacting one shard did. #[derive(Debug, Default, Clone, Copy)] pub struct Shrunk { @@ -161,10 +202,13 @@ fn interruptible(conn: &Connection, stop: &Arc) -> Result<()> { /// Compact every shard of `main`. Returns the total before and after. Once /// `stop` is set, shards not done are left as they were (and an error says so). pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync), stop: &Arc) -> Result { + let _lock = Lock::take(main)?; + for line in recover_cut_swaps(main)? { + progress(&line); + } if !store::exists(main) { bail!("{} has no shards (convert it first)", main.display()); } - let _lock = Lock::take(main)?; let started = Instant::now(); let mut total = Shrunk::default(); let mut failed: Vec<(usize, String)> = Vec::new(); @@ -193,8 +237,8 @@ pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync), stop: &Arc } } // the originals of the shards that were swapped can go. a failed shard - // keeps its original in place, and loses its half made copy (unless the - // shard isnt in place: the copy or the aside original may be all there is) + // keeps its original in place, and loses its half made copy; one whose + // copy didnt move in gets its original back for shard in 0..SHARDS { let path = store::shard_path(main, shard); if !failed.iter().any(|(f, _)| *f == shard) { @@ -203,6 +247,11 @@ pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync), stop: &Arc remove_db(&with_suffix(&path, "compact")); } } + if failed.iter().any(|(shard, _)| !store::shard_path(main, *shard).exists()) { + for line in recover_cut_swaps(main)? { + progress(&line); + } + } if stop.load(Ordering::Relaxed) { bail!("stopped, {} of {SHARDS} shards were left as they were", failed.len()); } @@ -231,6 +280,12 @@ fn compact_shard( let copy = with_suffix(&path, "compact"); let say = |msg: &str| progress(&format!("compacting shard {shard}: {msg}")); halt(stop, shard)?; + // a backup left by a compaction cut short isnt known to be redundant, and + // the swap would need its name + let backup = with_suffix(&path, "precompact"); + if backup.try_exists()? { + bail!("{} is left from an earlier compaction; the original was kept", backup.display()); + } // fold the WAL in soo the original is whole on its own { @@ -431,7 +486,6 @@ fn compact_shard( conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(()))?; drop(conn); let original = with_suffix(&path, "precompact"); - remove_db(&original); std::fs::rename(&path, &original).context("moving the original shard aside")?; for suffix in ["-wal", "-shm"] { let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); @@ -1040,4 +1094,112 @@ mod tests { assert!(stop.load(Ordering::Relaxed)); assert_untouched_or_whole(&main, &before); } + + /// what a swap cut short after its first rename leaves: the shard of + /// `group` moved aside as `.precompact.db`, its checked copy still next + /// to it as `.compact.db`, nothing at the shard's own path + fn cut_swap(main: &Path, group: &str) -> PathBuf { + let path = store::shard_path(main, store::shard_of(group)); + let copy = with_suffix(&path, "compact"); + std::fs::copy(&path, ©).unwrap(); + std::fs::rename(&path, with_suffix(&path, "precompact")).unwrap(); + for suffix in ["-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); + } + assert!(!path.exists() && copy.exists()); + path + } + + #[test] + fn a_swap_cut_short_gets_its_original_back_on_the_next_start() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + let path = cut_swap(&main, "alt.binaries.g3"); + + db::create_db_at(&main).unwrap(); + assert!(path.exists(), "the original is back in place"); + assert!(!with_suffix(&path, "precompact").exists(), "moved back, not copied"); + assert!(!with_suffix(&path, "compact").exists(), "the copy went"); + assert_eq!(all_articles(&main), before, "every NZB reads back the same"); + } + + #[test] + fn a_missing_shard_with_others_there_is_refused_not_made_empty() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let group = "alt.binaries.g3"; + let path = store::shard_path(&main, store::shard_of(group)); + + // no backup at all + remove_db(&path); + let err = format!("{:#}", db::create_db_at(&main).unwrap_err()); + assert!(err.contains(&path.display().to_string()) && err.contains("missing"), "{err}"); + assert!(!path.exists(), "no empty shard in its place"); + + // only a compacted copy, which may not have been checked: kept, still refused + let copy = with_suffix(&path, "compact"); + std::fs::copy(store::shard_path(&main, (store::shard_of(group) + 1) % SHARDS), ©).unwrap(); + let err = format!("{:#}", db::create_db_at(&main).unwrap_err()); + assert!(err.contains(©.display().to_string()), "{err}"); + assert!(!path.exists() && copy.exists(), "the copy is left for whoever puts it back"); + + // writers dont make it either + let release = Release { name: "Late".into(), group: group.into(), ..Default::default() }; + assert!(store::save(&main, &[release]).is_err()); + assert!(!path.exists(), "a save made no empty shard"); + } + + #[test] + fn a_shard_is_left_alone_while_a_compaction_holds_the_lock() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + let path = cut_swap(&main, "alt.binaries.g3"); + + // mid swap of a running compaction: nothing set up, nothing put back + let compacting = Lock::take(&main).unwrap(); + assert!(db::create_db_holding(&main).unwrap().is_none()); + assert!(!path.exists() && with_suffix(&path, "precompact").exists(), "the swap is left to the compaction"); + drop(compacting); + + let held = db::create_db_holding(&main).unwrap().expect("set up once the compaction is gone"); + assert!(busy(run(&main, &|_| {}, &no_stop())), "and compaction held off while held"); + drop(held); + assert_eq!(all_articles(&main), before); + } + + #[test] + fn a_compaction_puts_back_what_a_cut_swap_left_before_starting() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + cut_swap(&main, "alt.binaries.g3"); + + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_untouched_or_whole(&main, &before); + } + + #[test] + fn a_backup_left_next_to_a_shard_in_place_is_kept() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + // cut after the copy went in: both there, and which is whole isnt known + let path = store::shard_path(&main, store::shard_of("alt.binaries.g3")); + let backup = with_suffix(&path, "precompact"); + std::fs::copy(&path, &backup).unwrap(); + + db::create_db_at(&main).unwrap(); + assert!(backup.exists(), "kept on start"); + let err = format!("{:#}", run(&main, &|_| {}, &no_stop()).unwrap_err()); + assert!(err.contains(&backup.display().to_string()), "{err}"); + assert!(backup.exists(), "kept by a compaction too"); + assert_eq!(all_articles(&main), before); + } } diff --git a/src/db.rs b/src/db.rs index f6c6b595..f3bc5278 100644 --- a/src/db.rs +++ b/src/db.rs @@ -10,6 +10,7 @@ use std::time::Duration; use rusqlite::{Connection, OptionalExtension, params}; +use crate::compact::WriteGuard; use crate::parser::Release; use crate::paths; use crate::store; @@ -29,7 +30,19 @@ pub fn open_with_shards(path: &Path) -> Result { } pub fn open_at(path: &Path) -> Result { - let conn = Connection::open(path)?; + set_up(Connection::open(path)?) +} + +/// A shard to write, which has to be there already: `open_at` would make a +/// missing one (empty) on the spot, and a shard a compaction was cut short +/// swapping would then look in place with nothing in it. +pub fn open_shard(path: &Path) -> Result { + use rusqlite::OpenFlags; + let flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX; + set_up(Connection::open_with_flags(path, flags)?) +} + +fn set_up(conn: Connection) -> Result { conn.busy_timeout(Duration::from_secs(30))?; // bundled sqlite turns these on by default, python's didnt. purge deletes // releases before their articles and old dbs can hold orphans. @@ -107,18 +120,31 @@ fn wal_path(db: &Path) -> std::path::PathBuf { std::path::PathBuf::from(p) } -pub fn create_db() -> Result<()> { +/// `create_db_holding` for the database in its usual place. +pub fn create_db() -> anyhow::Result> { let path = paths::database(); if let Some(parent) = path.parent() { let _ = fs::create_dir_all(parent); } - create_db_at(&path) + create_db_holding(&path) +} + +/// `create_db_at` with compaction held off first: a compaction moves each +/// shard aside for a moment, and setting up then would take it for missing. +/// Returns the hold, for the caller to keep while it writes or drop. None +/// while a compaction runs, and nothing was set up (a compaction only runs +/// on a database that is). +pub fn create_db_holding(path: &Path) -> anyhow::Result> { + let Some(held) = crate::compact::try_hold_off_compaction(path)? else { return Ok(None) }; + create_db_at(path)?; + Ok(Some(held)) } /// The main database and its shards, or brings an older one up to date. A /// database from before the shards is left as it is (apart from missing -/// columns) for convert.rs; until then there are no shards. -pub fn create_db_at(path: &Path) -> Result<()> { +/// columns) for convert.rs; until then there are no shards. Run with +/// compaction held off, see `create_db_holding`. +pub fn create_db_at(path: &Path) -> anyhow::Result<()> { let conn = open_at(path)?; // wal soo the indexer can write while search reads @@ -142,11 +168,46 @@ pub fn create_db_at(path: &Path) -> Result<()> { } if has_old_layout(&conn)? { - return migrate_old(&conn); + return Ok(migrate_old(&conn)?); } store::create_main(&conn)?; - for shard in store::shard_paths(path) { + create_shards(path) +} + +/// Every shard of `main`, made if new, once the ones a compaction was cut +/// short swapping are back. One missing while others are there is refused +/// rather than made empty: searches would miss what it held, and new +/// releases would go into the empty one. +fn create_shards(main: &Path) -> anyhow::Result<()> { + for line in crate::compact::recover_cut_swaps(main)? { + crate::ui::warn(&line); + } + let shards = store::shard_paths(main); + let mut missing = Vec::new(); + for path in &shards { + if !path.try_exists()? { + missing.push(path); + } + } + if !missing.is_empty() && missing.len() < shards.len() { + let each: Vec = missing + .iter() + .map(|p| { + let copy = crate::compact::with_suffix(p, "compact"); + if copy.exists() { + format!("{} (a compacted copy of it, maybe not checked, is {})", p.display(), copy.display()) + } else { + p.display().to_string() + } + }) + .collect(); + anyhow::bail!( + "shards missing while the others are there: {}. not making empty ones in their place; put them back first", + each.join(", ") + ); + } + for shard in shards { store::create_shard(&shard)?; } Ok(()) diff --git a/src/indexer.rs b/src/indexer.rs index 41c4116d..07bbd5f4 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -192,7 +192,7 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s use crate::profile::{LOAD, Load}; use std::sync::atomic::Ordering::Relaxed; - let mut opened = db::open_at(path).and_then(|conn| db::tune_for_writing(&conn).map(|_| conn)); + let mut opened = db::open_shard(path).and_then(|conn| db::tune_for_writing(&conn).map(|_| conn)); let mut store = crate::store::ShardWriter::new(shard); // a job taken off the queue to see if more were waiting let mut next: Option = None; diff --git a/src/main.rs b/src/main.rs index a4086cbc..aa5d8454 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,6 +45,14 @@ fn run_convert() -> i32 { println!("stop indexing first"); return 1; } + // the shards it makes arent compacted till they're filled + let _converting = match compact::hold_off_compaction(&main) { + Ok(held) => held, + Err(e) => { + println!("couldnt convert: {e:#}"); + return 1; + } + }; match convert::run(&main, &|msg| println!("{msg}")) { Ok(_) => 0, Err(e) => { diff --git a/src/store.rs b/src/store.rs index 33b795b8..b4e059aa 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1023,7 +1023,7 @@ pub fn save(main: &Path, releases: &[Release]) -> Result<()> { by_shard[shard_of(&r.group)].push(r.clone()); } for (shard, list) in by_shard.iter().enumerate().filter(|(_, l)| !l.is_empty()) { - let mut conn = db::open_at(&shard_path(main, shard))?; + let mut conn = db::open_shard(&shard_path(main, shard))?; ShardWriter::new(shard).save(&mut conn, &ids, [list.as_slice()])?; } Ok(()) @@ -1126,7 +1126,7 @@ pub fn totals(conn: &Connection) -> Result<(i64, i64)> { /// Delete incomplete releases (and their files and articles) from every shard. pub fn purge_incomplete(main: &Path) -> Result<()> { for path in shard_paths(main) { - let conn = db::open_at(&path)?; + let conn = db::open_shard(&path)?; let removed: i64 = conn.query_row("select count(*) from releases where complete = 0", [], |r| r.get(0))?; conn.execute_batch( "begin; From d64a8b784e9ce5eddb93afe2d1f7b0741f86e28e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:31:52 -0500 Subject: [PATCH 053/159] A split finds each carrier's oldest article across gaps The oldest day of a split came from the post date of each server's low mark, looking only 100 numbers on. A provider whose low mark lags its retention by more than that counted for nothing, and its older days got no chunks. Each carrier's oldest day, home's too, now comes from first_post over its low..high range, which crosses gaps. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 29 +++++++++++++++++-------- tests/common/mod.rs | 6 +++++- tests/date_search.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 10 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 07bbd5f4..c7c28150 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -372,7 +372,16 @@ where let phase = ctx.states.with(group, |st| st.phase); let backfilling = settings.mode == "backfill" || (settings.mode != "live" && phase == Phase::Backfill); if backfilling - && maybe_split(ctx, settings, db, group, server, first as u64, state.backfill_cursor.max(0) as u64).await? + && maybe_split( + ctx, + settings, + db, + group, + server, + (first as u64, last as u64), + state.backfill_cursor.max(0) as u64, + ) + .await? { // a split group's backfill is day chunks, this server takes the next one let host = ctx.pool.host(server); @@ -432,7 +441,7 @@ async fn maybe_split( db: &Db, group: &str, home: usize, - first: u64, + (first, last): (u64, u64), cursor: u64, ) -> Result { let g = group.to_string(); @@ -446,7 +455,7 @@ async fn maybe_split( return Ok(false); } - let Some((newest_day, oldest_day, carriers)) = split_days(ctx, group, home, first, cursor).await? else { + let Some((newest_day, oldest_day, carriers)) = split_days(ctx, group, home, (first, last), cursor).await? else { ctx.states.with(group, |st| st.no_split_until = Some(Instant::now() + SPLIT_RECHECK)); return Ok(false); }; @@ -459,20 +468,22 @@ async fn maybe_split( /// The days a split of `group` covers, (newest, oldest), and how many servers /// carry it. None when it cant split: home's dates at either end are unknown -/// or no other indexing server carries the group. +/// or no other indexing server carries the group. `first` and `last` are +/// home's low and high marks. async fn split_days( ctx: &PassContext, group: &str, home: usize, - first: u64, + (first, last): (u64, u64), cursor: u64, ) -> Result> { use crate::chunks::unix_day; // the newest day still to do is the post date at the home cursor, the - // oldest at least home's first article + // oldest at least home's first article. first articles are searched for + // from the low marks, which can lag far behind what a server still keeps let Some(newest) = ctx.pool.posted_date(home, group, cursor).await? else { return Ok(None) }; - let Some(oldest) = ctx.pool.posted_date(home, group, first).await? else { return Ok(None) }; + let Some(oldest) = ctx.pool.first_post(home, group, first, last).await? else { return Ok(None) }; let newest_day = unix_day(newest); let mut oldest_day = unix_day(oldest).min(newest_day); @@ -480,9 +491,9 @@ async fn split_days( // carries the group counts, its oldest date only if it has one let mut carriers = 1; for other in ctx.pool.indexing_servers().into_iter().filter(|&s| s != home) { - let Ok((_, low, _, _)) = ctx.pool.group_on(other, group).await else { continue }; + let Ok((_, low, high, _)) = ctx.pool.group_on(other, group).await else { continue }; carriers += 1; - if let Ok(Some(t)) = ctx.pool.posted_date(other, group, low).await { + if let Ok(Some(t)) = ctx.pool.first_post(other, group, low, high).await { oldest_day = oldest_day.min(unix_day(t)); } } diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 57222dc1..fe3ac1ac 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -62,6 +62,9 @@ pub struct Server { pub body_delay: Duration, /// answer an empty XOVER range with 420 (some providers) instead of 423 pub empty_is_420: bool, + /// GROUP reports this as the low water mark instead of the first post's + /// number, like a provider whose low mark lags behind its retention + pub reported_low: Option, } impl Server { @@ -91,6 +94,7 @@ impl Server { bodies_sent: AtomicUsize::new(0), body_delay: Duration::ZERO, empty_is_420: false, + reported_low: None, }) } } @@ -201,7 +205,7 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { "GROUP" if arg == GROUP || (state.any_group && arg.starts_with("alt.binaries.")) => { selected = Some(arg.to_string()); let posts = posts_lock(); - let first = posts.iter().map(|p| p.number).min().unwrap_or(0); + let first = state.reported_low.unwrap_or_else(|| posts.iter().map(|p| p.number).min().unwrap_or(0)); let last = posts.iter().map(|p| p.number).max().unwrap_or(0); send(&mut out, format!("211 {} {first} {last} {arg}", posts.len()).as_bytes()); } diff --git a/tests/date_search.rs b/tests/date_search.rs index 07008b1a..7537a2ab 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -465,6 +465,57 @@ fn only_the_server_going_back_furthest_does_the_oldest_day() { assert_eq!(state(), 2); } +/// A split reaches back to the oldest day of every carrier, also one whose +/// GROUP low mark sits 5,000 numbers before its first article (retention +/// has moved on, the mark hasnt): its older days get chunks. +#[test] +fn a_split_reaches_a_carrier_whose_low_mark_lags() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour for 10 days from 2026-01-01, from `from_hour` on + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = |from_hour: u64, offset: u64| -> Vec { + (from_hour..240) + .map(|h| { + let when = start + chrono::Duration::hours(h as i64); + post_at(offset + h, &format!(r#""p{h}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() + }; + // home keeps the last 5 days, "localhost" all 10 with a low mark 5,000 behind + let short = spawn_server(Server::new(posts(120, 1))); + let mut deep = Server::new(posts(0, 10_001)); + std::sync::Arc::get_mut(&mut deep).unwrap().reported_low = Some(5_001); + let mut lagging = mock(spawn_server(deep), "secret", 2, 2); + lagging.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(short, "secret", 2, 1), lagging]); + pool.connect().unwrap(); + + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(atlas::db::open_at(&main).unwrap()); + let settings = atlas::indexer::PassSettings { + mode: "backfill".into(), + batch_size: 10, + request_size: 10, + split_min_backlog: 10, + }; + pool.block_on(atlas::indexer::run_pass(&ctx, &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); + + let conn = atlas::db::open_at(&main).unwrap(); + let day = atlas::chunks::unix_day(start.timestamp()); + assert_eq!( + atlas::chunks::oldest_day(&conn, GROUP).unwrap(), + Some(day), + "chunks back to the deep server's first day" + ); +} + /// (number, unix seconds) of a post type Slot = (u64, i64); From 7291a6e1925cb16440cb4c50435986a71c183a33 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:35:29 -0500 Subject: [PATCH 054/159] The deepest server is forgotten once it drops the group The server noted as going back furthest on a split group stayed noted while it was an indexing server, even after it answered 411 for that group, so the partial oldest day stayed pending. A 411 on a chunk now removes the note when it names that server, and the next server to reach the oldest day asks every carrier again. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 7 +++++ src/indexer.rs | 8 +++++- tests/common/mod.rs | 4 +++ tests/date_search.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 84 insertions(+), 1 deletion(-) diff --git a/src/chunks.rs b/src/chunks.rs index cdf03bfc..b69b2c89 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -154,6 +154,13 @@ pub fn set_deepest(conn: &Connection, group: &str, server: &str) -> Result<()> { Ok(()) } +/// Forget `server` as the one going back furthest on `group`, when it no +/// longer carries it: the next to reach the oldest day asks again. +pub fn forget_deepest(conn: &Connection, group: &str, server: &str) -> Result<()> { + conn.execute("delete from backfill_deepest where grp = ? and server = ?", [group, server])?; + Ok(()) +} + /// groups with chunks still to do pub fn split_groups(conn: &Connection) -> Result> { conn.prepare("select distinct grp from backfill_chunks where state != 2 order by grp")? diff --git a/src/indexer.rs b/src/indexer.rs index c7c28150..a57615be 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -663,6 +663,11 @@ where let found = match ctx.pool.group_on(server, group).await { Ok(info) => info, Err(e) if e.code() == Some(411) => { + // if it was noted as going back furthest, the oldest day goes to the next one + let (g, host) = (group.to_string(), ctx.pool.host(server)); + if let Err(e) = on_db(db, move |conn| Ok(crate::chunks::forget_deepest(conn, &g, &host)?)).await { + println!("[CHUNK] {group}: couldnt forget the server going back furthest: {e:#}"); + } return failed(NotCarried { group: group.to_string(), host: ctx.pool.host(server) }.into()).await; } Err(e) => return failed(e.into()).await, @@ -739,7 +744,8 @@ where /// `oldest`, goes back furthest of the indexing servers: the one to index the /// split's oldest day. Found by asking each server for its first article the /// first time, then kept, soo it doesnt move as retention rolls on (asked -/// again once that server is no longer an indexing one). A server that +/// again once that server is no longer an indexing one, or no longer +/// carries the group: `index_chunk` forgets it on a 411). A server that /// cant be asked fails it: the chunk goes back and is tried again later. async fn goes_back_furthest(ctx: &PassContext, db: &Db, group: &str, server: usize, oldest: i64) -> Result { let host = ctx.pool.host(server); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index fe3ac1ac..580c97af 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -65,6 +65,8 @@ pub struct Server { /// GROUP reports this as the low water mark instead of the first post's /// number, like a provider whose low mark lags behind its retention pub reported_low: Option, + /// once set, GROUP answers 411, like a provider that dropped the group + pub dropped: std::sync::atomic::AtomicBool, } impl Server { @@ -95,6 +97,7 @@ impl Server { body_delay: Duration::ZERO, empty_is_420: false, reported_low: None, + dropped: Default::default(), }) } } @@ -202,6 +205,7 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { send(&mut out, if ok { b"281 ok".as_slice() } else { b"481 nope" }) } "GROUP" if state.no_group => send(&mut out, b"501 GROUP command error"), + "GROUP" if state.dropped.load(Ordering::SeqCst) => send(&mut out, b"411 no such group"), "GROUP" if arg == GROUP || (state.any_group && arg.starts_with("alt.binaries.")) => { selected = Some(arg.to_string()); let posts = posts_lock(); diff --git a/tests/date_search.rs b/tests/date_search.rs index 7537a2ab..18f14a0d 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -465,6 +465,72 @@ fn only_the_server_going_back_furthest_does_the_oldest_day() { assert_eq!(state(), 2); } +/// The server noted as going back furthest drops the group (GROUP answers +/// 411): the note goes, and the next deepest carrier does the oldest day +/// instead of it staying pending. +#[test] +fn the_oldest_day_moves_on_when_the_deepest_server_drops_the_group() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour for 3 days from 2026-01-01, from `from_hour` on + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = |from_hour: u64, offset: u64| -> Vec { + (from_hour..72) + .map(|h| { + let when = start + chrono::Duration::hours(h as i64); + post_at(offset + h, &format!(r#""p{h}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() + }; + // "127.0.0.1" keeps the first day from 01:00, "localhost" from 18:00 + let deep_server = Server::new(posts(1, 1)); + let deep = spawn_server(deep_server.clone()); + let shallow = spawn_server(Server::new(posts(18, 1001))); + let mut later = mock(shallow, "secret", 2, 1); + later.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(deep, "secret", 2, 1), later]); + pool.connect().unwrap(); + + let day = atlas::chunks::unix_day(start.timestamp()); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day + 2, day).unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let conn = atlas::db::open_at(&main).unwrap(); + let run = |server: usize| { + let chunk = atlas::chunks::Claim { group: GROUP.into(), day, server: pool.pool.host(server), claimed_at: 1 }; + conn.execute( + "update backfill_chunks set state = 1, server = ?, claimed_at = 1 where grp = ? and day = ?", + rusqlite::params![chunk.server, GROUP, day], + ) + .unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, server, &mut |_| {})) + }; + let state = + || -> i64 { conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() }; + + // the 01:00 server is noted as the deepest + assert!(run(1).unwrap_err().downcast_ref::().is_some()); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("127.0.0.1")); + + // then drops the group, and finds out on its next chunk + deep_server.dropped.store(true, std::sync::atomic::Ordering::SeqCst); + assert!(run(0).unwrap_err().downcast_ref::().is_some()); + assert_eq!(state(), 0); + + // the 18:00 one goes back furthest now: 18:00 to midnight, plus the hour after + let saved = run(1).expect("the next deepest carrier does the oldest day"); + assert_eq!(saved.articles, 7); + assert_eq!(state(), 2); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("localhost")); +} + /// A split reaches back to the oldest day of every carrier, also one whose /// GROUP low mark sits 5,000 numbers before its first article (retention /// has moved on, the mark hasnt): its older days get chunks. From 974226d01df04167af082359d1a6f0bae1415176 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:45:38 -0500 Subject: [PATCH 055/159] The date search reads the numbers its spread out windows stepped over Past DATE_SCAN_MAX the probe windows spread out, and an empty window moved the "all missing up to here" mark past the numbers stepped over before it. A small cluster there was never read, so a later article was taken as the first (and going backwards, an earlier one as the last). The windows now keep the stepped over runs. On a hit, each run between two empty windows is read in one request (quick in a hole), and the run next to the hit is bisected and its remainder read, as before. This applies to first_in and last_in, so first_post and article_at too. Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 135 +++++++++++++++++++++++++++---------------- tests/date_search.rs | 54 +++++++++++++++++ 2 files changed, 139 insertions(+), 50 deletions(-) diff --git a/src/nntp.rs b/src/nntp.rs index 3e8a2448..7de6d79f 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1332,83 +1332,118 @@ impl Pool { /// Missing numbers are skipped in windows that double from `DATE_LOOK` up /// to `DATE_SCAN_MAX` numbers; past that the windows spread out (each /// starts twice as far from `from` as the last ended, the last ends at - /// `end`), soo a hole of millions takes a few dozen small requests. A hit - /// after spread out windows is narrowed down by bisecting the numbers in - /// between, taking the hole as one run of missing numbers followed by - /// articles. + /// `end`), soo a hole of millions takes a few dozen small requests. The + /// numbers stepped over are read before a hit is taken as the first, see + /// `first_before`. async fn first_in(&self, i: usize, group: &str, from: u64, end: u64) -> Result> { - // numbers before `gap` are all missing - let (mut at, mut size, mut gap) = (from, DATE_LOOK, from); + // the numbers between windows that weren't read, lowest first + let mut skipped = Vec::new(); + // every number from `from` up to here was read or stepped over + let (mut at, mut size, mut read_to) = (from, DATE_LOOK, from); while at < end { + if at > read_to { + skipped.push((read_to, at)); + } let look = size.min(end - at); if let Some(hit) = self.posted_at(i, group, at, look).await? { - // the first article is between the last empty window and this one - let (mut lo, mut hi, mut best) = (gap, at, hit); - while lo < hi { - let mid = lo + (hi - lo) / 2; - let look = DATE_LOOK.min(hi - mid); - match self.posted_at(i, group, mid, look).await? { - Some(found) => (best, hi) = (found, found.0), - None => lo = mid + look, - } - } - // the bisect skipped what it took for empty: read it once - if best.0 > gap - && let Some(f) = self.posted_at(i, group, gap, best.0 - gap).await? - { - best = f; - } - return Ok(Some(best)); + return self.first_before(i, group, &skipped, hit).await.map(Some); } - gap = at + look; + read_to = at + look; if size < DATE_SCAN_MAX { - at = gap; + at = read_to; size *= 2; } else { - at = (gap + (gap - from)).min(end.saturating_sub(DATE_SCAN_MAX)).max(gap); + at = (read_to + (read_to - from)).min(end.saturating_sub(DATE_SCAN_MAX)).max(read_to); } } Ok(None) } + /// The first article on server `i`, given the first one a window found + /// (`hit`) and the numbers stepped over before it (`skipped`, lowest + /// first): an article stepped over comes first. Those between two empty + /// windows are read in one request each (quick when there's nothing, as + /// in a hole). The run up to the hit is narrowed down by bisecting, + /// taking it as one run of missing numbers followed by articles, and what + /// the bisect took for missing is read once. + async fn first_before(&self, i: usize, group: &str, skipped: &[(u64, u64)], hit: Dated) -> Result { + let Some((&(start, end), between)) = skipped.split_last() else { return Ok(hit) }; + for &(from, to) in between { + if let Some(found) = self.posted_at(i, group, from, to - from).await? { + return Ok(found); + } + } + let (mut lo, mut hi, mut best) = (start, end, hit); + while lo < hi { + let mid = lo + (hi - lo) / 2; + let look = DATE_LOOK.min(hi - mid); + match self.posted_at(i, group, mid, look).await? { + Some(found) => (best, hi) = (found, found.0), + None => lo = mid + look, + } + } + if best.0 > start + && let Some(f) = self.posted_at(i, group, start, best.0 - start).await? + { + best = f; + } + Ok(best) + } + /// The last article in `from..end` on server `i`, with its post time: like - /// `first_in`, going backwards from `end`, the hole taken as articles - /// followed by one run of missing numbers. + /// `first_in`, going backwards from `end`. async fn last_in(&self, i: usize, group: &str, from: u64, end: u64) -> Result> { - // numbers from `gap` on are all missing - let (mut to, mut size, mut gap) = (end, DATE_LOOK, end); + // the numbers between windows that weren't read, highest first + let mut skipped = Vec::new(); + // every number from here up to `end` was read or stepped over + let (mut to, mut size, mut read_from) = (end, DATE_LOOK, end); while to > from { + if to < read_from { + skipped.push((to, read_from)); + } let look = size.min(to - from); if let Some((_, hit)) = self.window(i, group, to - look, look).await? { - // the last article is between this window and the last empty one - let (mut lo, mut hi, mut best) = (to, gap, hit); - while lo < hi { - let mid = lo + (hi - lo) / 2; - let look = DATE_LOOK.min(hi - mid); - match self.window(i, group, mid, look).await? { - Some((_, found)) => (best, lo) = (found, found.0 + 1), - None => hi = mid, - } - } - // the bisect skipped what it took for empty: read it once - if gap > best.0 + 1 - && let Some((_, l)) = self.window(i, group, best.0 + 1, gap - best.0 - 1).await? - { - best = l; - } - return Ok(Some(best)); + return self.last_after(i, group, &skipped, hit).await.map(Some); } - gap = to - look; + read_from = to - look; if size < DATE_SCAN_MAX { - to = gap; + to = read_from; size *= 2; } else { - to = end.saturating_sub(2 * (end - gap)).max(from.saturating_add(DATE_SCAN_MAX)).min(gap); + to = end.saturating_sub(2 * (end - read_from)).max(from.saturating_add(DATE_SCAN_MAX)).min(read_from); } } Ok(None) } + /// `first_before` going backwards: the last article, given the last one + /// a window found and the numbers stepped over after it (highest first). + /// The run from the hit up is taken as articles followed by one run of + /// missing numbers. + async fn last_after(&self, i: usize, group: &str, skipped: &[(u64, u64)], hit: Dated) -> Result { + let Some((&(start, end), between)) = skipped.split_last() else { return Ok(hit) }; + for &(from, to) in between { + if let Some((_, found)) = self.window(i, group, from, to - from).await? { + return Ok(found); + } + } + let (mut lo, mut hi, mut best) = (start, end, hit); + while lo < hi { + let mid = lo + (hi - lo) / 2; + let look = DATE_LOOK.min(hi - mid); + match self.window(i, group, mid, look).await? { + Some((_, found)) => (best, lo) = (found, found.0 + 1), + None => hi = mid, + } + } + if end > best.0 + 1 + && let Some((_, l)) = self.window(i, group, best.0 + 1, end - best.0 - 1).await? + { + best = l; + } + Ok(best) + } + /// When the first article in `low..=high` on server `i` was posted (unix /// seconds): how far back the server keeps the group. None when it has none. pub async fn first_post(&self, i: usize, group: &str, low: u64, high: u64) -> Result> { diff --git a/tests/date_search.rs b/tests/date_search.rs index 18f14a0d..d2f94eb8 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -187,6 +187,60 @@ fn a_hole_of_millions_is_crossed_to_its_first_article_in_few_requests() { assert_eq!(at(1_500_000, minute_of(3_000_001)), 3_000_001); } +/// one post a minute from `when` on, numbered `numbers` +fn minutely(numbers: std::ops::RangeInclusive, when: &str) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339(when).unwrap(); + let first = *numbers.start(); + numbers + .map(|n| { + let at = start + chrono::Duration::minutes((n - first) as i64); + post_at(n, &format!(r#""p{n}.bin" yEnc (1/1)"#), &at.to_rfc2822()) + }) + .collect() +} + +fn unix(rfc3339: &str) -> i64 { + chrono::DateTime::parse_from_rfc3339(rfc3339).unwrap().timestamp() +} + +/// A few articles in the numbers the spread out windows step over, before +/// the articles they land on: going forward, they are still the first. +#[test] +fn a_small_cluster_between_spread_out_windows_is_found_going_forward() { + // nothing below 40,000, five posts there, nothing again till 100,000 + let mut posts = minutely(40_000..=40_004, "2026-01-01T00:00:00+00:00"); + posts.extend(minutely(100_000..=103_000, "2026-01-03T00:00:00+00:00")); + let port = spawn_server(Server::new(posts)); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + let first = pool.block_on(pool.pool.first_post(0, GROUP, 1, 103_000)).unwrap(); + assert_eq!(first, Some(unix("2026-01-01T00:00:00+00:00")), "the cluster's first post"); + let at = |when: &str| pool.block_on(pool.pool.article_at(0, GROUP, 1, 103_000, unix(when))).unwrap(); + assert_eq!(at("2025-12-31T00:00:00+00:00"), 40_000); + assert_eq!(at("2026-01-01T00:02:00+00:00"), 40_002); + assert_eq!(at("2026-01-02T00:00:00+00:00"), 100_000); +} + +/// The same going backwards: a few articles in the numbers the spread out +/// windows step over, after the articles they land on, are still the last +/// before the hole. +#[test] +fn a_small_cluster_between_spread_out_windows_is_found_going_backward() { + // 1..=600 (ten hours), five posts at 25,000, nothing again till 90,000 + let mut posts = minutely(1..=600, "2026-01-01T00:00:00+00:00"); + posts.extend(minutely(25_000..=25_004, "2026-01-02T00:00:00+00:00")); + posts.extend(minutely(90_000..=93_000, "2026-01-03T00:00:00+00:00")); + let port = spawn_server(Server::new(posts)); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + let at = |when: &str| pool.block_on(pool.pool.article_at(0, GROUP, 1, 93_000, unix(when))).unwrap(); + assert_eq!(at("2026-01-02T00:00:00+00:00"), 25_000); + assert_eq!(at("2026-01-01T12:00:00+00:00"), 25_000, "between the first run and the cluster"); + assert_eq!(at("2026-01-02T12:00:00+00:00"), 90_000); +} + /// The first day after a hole of millions is indexed whole. #[test] fn a_day_chunk_right_after_a_hole_of_millions_gets_every_article() { From 3a991e901f37c10d03056cb93286f70fe6a2209b Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:49:20 -0500 Subject: [PATCH 056/159] Header requests are cut down to the unsaved budget With max_unsaved_headers below request_size, a slice reserved the whole budget but its XOVER still fetched request_size headers, so more were held than the cap. Slices are now no bigger than the cap. The budget also counts headers a slice holds past its room, so its numbers (and the cap test) show what is really held: the cap test failed on a cap of 7 with 20 held. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/indexer.rs | 6 ++++-- src/nntp.rs | 14 +++++++++++--- tests/unsaved_cap.rs | 11 +++++++---- 4 files changed, 23 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 9da09d05..0ed8baca 100644 --- a/README.md +++ b/README.md @@ -140,7 +140,7 @@ On first run, Atlas asks for one server (host, username, password, and port) and | `api_key` | generated | Newznab API key. Atlas creates it on first start and stores it here. | | `split_min_backlog` | `10000000` | Article numbers of backfill left before a group's backfill is split into day chunks that every server carrying the group can take. | | `auto_run_compact` | `false` | Compact the database every 24 hours; indexing pauses while it runs. | -| `max_unsaved_headers` | `500000` | Headers the indexer fetches ahead of saving them, over all groups at once. This bounds its memory: 500,000 headers take about 0.3 GB. A header request waits for room before it goes out, and its room comes back once its slice is saved. Raise it if the Bottleneck page shows it full while the database writers and connections have time to spare. | +| `max_unsaved_headers` | `500000` | Headers the indexer fetches ahead of saving them, over all groups at once. This bounds its memory: 500,000 headers take about 0.3 GB. A header request waits for room before it goes out, and its room comes back once its slice is saved. Raise it if the Bottleneck page shows it full while the database writers and connections have time to spare. Set below `request_size`, header requests are cut down to it, which makes them small and slow. | Atlas keeps any other keys you add to the file when it saves it. diff --git a/src/indexer.rs b/src/indexer.rs index a57615be..3b1754af 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -870,8 +870,10 @@ impl Pass<'_> { P: FnMut(&Progress) + ?Sized, { let (pool, group) = (&self.ctx.pool, self.group); - let slices = - make_slices(start.max(0) as u64, end.max(0) as u64, self.settings.request_size, kind == "BACKFILL"); + // no slice bigger than the whole unsaved budget: it would hold more + // headers than the cap allows + let size = self.settings.request_size.min(pool.max_unsaved() as u64); + let slices = make_slices(start.max(0) as u64, end.max(0) as u64, size, kind == "BACKFILL"); let total = slices.len(); let mut rx = pool.stream_headers(group, self.server, slices, self.ctx.stop.clone()); diff --git a/src/nntp.rs b/src/nntp.rs index 7de6d79f..e921c169 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -841,6 +841,9 @@ impl UnsavedBudget { pub struct Unsaved { permit: OwnedSemaphorePermit, budget: Arc, + /// headers held past the room (a slice bigger than the whole budget), + /// counted soo `now` and `peak` show what is really held + over: usize, } impl Unsaved { @@ -853,14 +856,19 @@ impl Unsaved { self.budget.now.fetch_sub(extra, Ordering::Relaxed); drop(back); } + self.over = headers.saturating_sub(self.permit.num_permits()); + if self.over > 0 { + let now = self.budget.now.fetch_add(self.over, Ordering::Relaxed) + self.over; + self.budget.peak.fetch_max(now, Ordering::Relaxed); + } } } impl Drop for Unsaved { fn drop(&mut self) { // counted down before the permit goes back (right after this), soo - // `now` never shows more than the cap - self.budget.now.fetch_sub(self.permit.num_permits(), Ordering::Relaxed); + // `now` never shows more than is held + self.budget.now.fetch_sub(self.permit.num_permits() + self.over, Ordering::Relaxed); } } @@ -932,7 +940,7 @@ impl Pool { let permit = budget.permits.clone().acquire_many_owned(n as u32).await.expect("semaphore closed"); let now = budget.now.fetch_add(n, Ordering::Relaxed) + n; budget.peak.fetch_max(now, Ordering::Relaxed); - Unsaved { permit, budget } + Unsaved { permit, budget, over: 0 } } pub fn len(&self) -> usize { diff --git a/tests/unsaved_cap.rs b/tests/unsaved_cap.rs index 21cbbed0..33c68a9f 100644 --- a/tests/unsaved_cap.rs +++ b/tests/unsaved_cap.rs @@ -16,6 +16,7 @@ use common::{Server, mock, par2_file_desc, post, spawn_server, yenc_body}; const POSTS: u64 = 400; const REQUEST: u64 = 20; const GROUPS: usize = 16; +const BATCH: u64 = 100; /// `POSTS` articles in releases of one slice each, every release with a par2, /// soo saving a slice needs BODY lookups on the connections the XOVERs use @@ -59,7 +60,7 @@ fn index_everything(cap: usize) { }); let settings = Arc::new(PassSettings { mode: "backfill".into(), - batch_size: 100, + batch_size: BATCH as i64, request_size: REQUEST, split_min_backlog: i64::MAX, }); @@ -94,12 +95,14 @@ fn index_everything(cap: usize) { }); assert_eq!(saved, vec![POSTS as i64; GROUPS], "every article saved once, per group"); + // slices no bigger than the budget, in passes of BATCH + let slice = REQUEST.min(cap as u64); let xovers: usize = servers.iter().map(|s| s.xovers.load(Ordering::SeqCst)).sum(); - assert_eq!(xovers, GROUPS * (POSTS / REQUEST) as usize, "every slice fetched once"); + assert_eq!(xovers, GROUPS * (POSTS / BATCH * BATCH.div_ceil(slice)) as usize, "every slice fetched once"); let peak = pool.unsaved_peak(); assert!(peak <= cap, "{peak} headers unsaved at once, the cap is {cap}"); - assert!(peak >= cap.min(REQUEST as usize), "the cap was never reached ({peak}), the test proves nothing"); + assert!(peak >= slice as usize, "the cap was never reached ({peak}), the test proves nothing"); assert_eq!(pool.unsaved_headers(), 0, "budget left held after every pass ended"); // the names came from the bodies: saving did its lookups @@ -116,7 +119,7 @@ fn many_passes_share_a_budget_of_two_slices() { index_everything(2 * REQUEST as usize); } -/// A budget smaller than one slice: a slice waits for all of it. +/// A budget smaller than one slice: the slices are cut down to it. #[test] fn a_budget_smaller_than_a_slice_still_gets_through() { index_everything(7); From 94eb9dd59f6bcca7e5ac05e6f85f8162f814df85 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:53:29 -0500 Subject: [PATCH 057/159] An idle writer still seals what comes due Sealing ran only right after a save, and a writer with nothing to save waited in recv() forever, so once indexing caught up, files that went stale were never sealed. The writer now waits at most SEAL_WALK_EVERY for a save, and when none comes it seals what is due and checkpoints. It still skips that while saves are queued, and stops when the queue closes. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 102 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 84 insertions(+), 18 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 3b1754af..2cecf52b 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -172,6 +172,12 @@ struct SaveJob { /// `conn` is the main database. The writer threads end once every clone of /// the `Db` is gone, and the last clone to go waits for them. pub fn shared_db(conn: Connection) -> Db { + shared_db_idling(conn, Duration::from_secs(crate::store::SEAL_WALK_EVERY as u64)) +} + +/// `shared_db` whose writers, with nothing to save for `every`, look for +/// files due to be sealed. +fn shared_db_idling(conn: Connection, every: Duration) -> Db { let main = conn.path().map(std::path::PathBuf::from).unwrap_or_else(crate::paths::database); let ids = Arc::new(crate::store::Ids::new(&main)); let (saves, writers): (Vec<_>, Vec<_>) = (0..crate::store::SHARDS) @@ -180,7 +186,7 @@ pub fn shared_db(conn: Connection) -> Db { let (path, ids) = (crate::store::shard_path(&main, shard), ids.clone()); let handle = std::thread::Builder::new() .name(format!("atlas-db-writer-{shard}")) - .spawn(move || writer(shard, &path, &ids, jobs)) + .spawn(move || writer(shard, &path, &ids, jobs, every)) .expect("couldnt start a db writer"); (saves, handle) }) @@ -188,9 +194,18 @@ pub fn shared_db(conn: Connection) -> Db { Db { conn: Arc::new(Mutex::new(conn)), saves, _writers: Arc::new(Writers(writers)) } } -fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: std::sync::mpsc::Receiver) { +/// A shard's writer: saves what comes in, and between saves (or after +/// `idle` with nothing to save) seals what is due and checkpoints. +fn writer( + shard: usize, + path: &std::path::Path, + ids: &crate::store::Ids, + jobs: std::sync::mpsc::Receiver, + idle: Duration, +) { use crate::profile::{LOAD, Load}; use std::sync::atomic::Ordering::Relaxed; + use std::sync::mpsc::{RecvTimeoutError, TryRecvError}; let mut opened = db::open_shard(path).and_then(|conn| db::tune_for_writing(&conn).map(|_| conn)); let mut store = crate::store::ShardWriter::new(shard); @@ -200,9 +215,16 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s loop { let first = match next.take() { Some(job) => job, - None => match jobs.recv() { + None => match jobs.recv_timeout(idle) { Ok(job) => job, - Err(_) => break, + // nothing to save: files still come due as they go stale + Err(RecvTimeoutError::Timeout) => { + if let Ok(conn) = &mut opened { + housekeeping(conn, &mut store, true); + } + continue; + } + Err(RecvTimeoutError::Disconnected) => break, }, }; let mut batch = vec![first]; @@ -240,7 +262,6 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s // housekeeping between transactions if let Ok(conn) = &mut opened { - let t = std::time::Instant::now(); // more slices waiting: saving them comes first. a closed queue // means the indexer is stopping, it waits for this thread let seal = match jobs.try_recv() { @@ -248,22 +269,32 @@ fn writer(shard: usize, path: &std::path::Path, ids: &crate::store::Ids, jobs: s next = Some(job); false } - Err(std::sync::mpsc::TryRecvError::Empty) => saved, - Err(std::sync::mpsc::TryRecvError::Disconnected) => false, + Err(TryRecvError::Empty) => saved, + Err(TryRecvError::Disconnected) => false, }; - if seal { - let sealing = std::time::Instant::now(); - if store.seal_some(conn, chrono::Utc::now().timestamp()).is_err() { - LOAD.writer_seal_errors.fetch_add(1, Relaxed); - } - Load::add_since(&LOAD.writer_seal_ns, sealing); - } - let checkpointing = std::time::Instant::now(); - let _ = db::finish_checkpoint(conn); - Load::add_since(&LOAD.writer_checkpoint_ns, checkpointing); - Load::add_since(&LOAD.writer_busy_ns, t); + housekeeping(conn, &mut store, seal); + } + } +} + +/// A writer's work between saves: seal some of what is due (when `seal`), +/// and copy the WAL into the shard. +fn housekeeping(conn: &mut Connection, store: &mut crate::store::ShardWriter, seal: bool) { + use crate::profile::{LOAD, Load}; + use std::sync::atomic::Ordering::Relaxed; + + let t = std::time::Instant::now(); + if seal { + let sealing = std::time::Instant::now(); + if store.seal_some(conn, chrono::Utc::now().timestamp()).is_err() { + LOAD.writer_seal_errors.fetch_add(1, Relaxed); } + Load::add_since(&LOAD.writer_seal_ns, sealing); } + let checkpointing = std::time::Instant::now(); + let _ = db::finish_checkpoint(conn); + Load::add_since(&LOAD.writer_checkpoint_ns, checkpointing); + Load::add_since(&LOAD.writer_busy_ns, t); } impl Db { @@ -1193,4 +1224,39 @@ mod tests { .collect(); assert_eq!(names, vec!["kept".to_string()]); } + + #[test] + fn an_idle_writer_still_seals_what_is_due() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + // one part of two, untouched for long: due though never completed + let part = crate::parser::Article { + message_id: "".into(), + subject: "\"a.rar\" yEnc (1/2)".into(), + filename: Some("a.rar".into()), + part: Some(1), + total_parts: Some(2), + bytes: 10, + ..Default::default() + }; + let release = + Release { name: "Rel".into(), group: "alt.binaries.t".into(), articles: vec![part], ..Default::default() }; + crate::store::save(&main, &[release]).unwrap(); + let shard = db::open_at(&crate::store::shard_path(&main, crate::store::shard_of("alt.binaries.t"))).unwrap(); + shard.execute("update files set touched_at = 0", []).unwrap(); + let sealed = || -> i64 { + shard.query_row("select count(*) from files where blob is not null", [], |r| r.get(0)).unwrap() + }; + assert_eq!(sealed(), 0); + + // no save ever comes + let shared = shared_db_idling(db::open_at(&main).unwrap(), Duration::from_millis(50)); + let deadline = Instant::now() + Duration::from_secs(10); + while sealed() == 0 && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(20)); + } + assert_eq!(sealed(), 1, "the idle writer sealed the stale file"); + drop(shared); + } } From c383c4d9cc524ab559417c341278e0cc8ffcf37e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 19:58:40 -0500 Subject: [PATCH 058/159] A split group reaches back when a server goes back further Once a group had chunk rows, maybe_split returned at once, so a server added later with deeper retention never got chunks for the older days, and normal backfill never got to them either. A split group's carriers are now probed again on the first pass after a start and every SPLIT_RECHECK. Days older than the split's oldest get pending chunks. The old oldest day, done only from where the deepest server then started, is pending again, and the noted deepest server is forgotten. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/chunks.rs | 31 +++++++++++++++++++ src/indexer.rs | 36 +++++++++++++++++++++ tests/date_search.rs | 74 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 142 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0ed8baca..83115f04 100644 --- a/README.md +++ b/README.md @@ -240,7 +240,7 @@ Start the indexer from the main menu with option 1. The indexer runs as a backgr ### Splitting big groups -When two or more indexing servers carry a group and its backfill has more than `split_min_backlog` article numbers left, Atlas splits the rest of its history into UTC day chunks. A worker with nothing of its own to do claims the newest pending chunk on any server that carries the group, so idle connections help with big groups. A server that doesn't keep a day from its start, because its retention is shorter, gives the chunk back for a server that does. No server keeps the oldest day of the split from its start; the server that goes back furthest on it indexes what there is. Live indexing stays on the group's home server. The Backfill page of the stats dashboard shows split groups and their day chunks. +When two or more indexing servers carry a group and its backfill has more than `split_min_backlog` article numbers left, Atlas splits the rest of its history into UTC day chunks. A worker with nothing of its own to do claims the newest pending chunk on any server that carries the group, so idle connections help with big groups. A server that doesn't keep a day from its start, because its retention is shorter, gives the chunk back for a server that does. No server keeps the oldest day of the split from its start; the server that goes back furthest on it indexes what there is. Every hour, and when the indexer starts, Atlas checks whether a server now goes back further, for example one you added. If one does, the older days get chunks too, and the old oldest day is done again in full. Live indexing stays on the group's home server. The Backfill page of the stats dashboard shows split groups and their day chunks. ### How the database is stored diff --git a/src/chunks.rs b/src/chunks.rs index b69b2c89..4633efbc 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -61,6 +61,37 @@ pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> Ok(added) } +/// Chunks for the days of split `group` from before its oldest one back to +/// `oldest_day`, when a server goes back further than any did at the split. +/// The old oldest day was done (if it was) only from where the server going +/// back furthest then started: it is to do again, and that server is +/// forgotten (see `deepest`). Returns the days added. +pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64) -> Result { + let tx = conn.unchecked_transaction()?; + let Some(old) = self::oldest_day(&tx, group)? else { return Ok(0) }; + if oldest_day >= old { + return Ok(0); + } + let mut added = 0; + { + let mut insert = + tx.prepare_cached("insert or ignore into backfill_chunks (grp, day, state) values (?, ?, ?)")?; + for day in (oldest_day..old).rev() { + added += insert.execute(params![group, day, PENDING])?; + } + } + tx.execute( + &format!( + "update backfill_chunks set state = {PENDING}, server = null, claimed_at = null, done_at = null + where grp = ? and day = ? and state = {DONE}" + ), + params![group, old], + )?; + tx.execute("delete from backfill_deepest where grp = ?", [group])?; + tx.commit()?; + Ok(added) +} + /// Check if a group has any chunks in backfill. pub fn is_split(conn: &Connection, group: &str) -> Result { conn.prepare_cached("select 1 from backfill_chunks where grp = ? limit 1")?.exists([group]) diff --git a/src/indexer.rs b/src/indexer.rs index 2cecf52b..74c7932d 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -46,6 +46,8 @@ pub struct GroupRunState { pub backfilling: bool, /// a big group found unsplittable isnt probed again until then pub no_split_until: Option, + /// a split group's servers are looked at for older days again then + pub reach_back_after: Option, /// per server, the oldest day it keeps of the group (as found by a day /// chunk too old for it), until it's looked at again pub keeps_from: HashMap, @@ -58,6 +60,7 @@ impl Default for GroupRunState { idle: false, backfilling: false, no_split_until: None, + reach_back_after: None, keeps_from: HashMap::new(), } } @@ -477,6 +480,19 @@ async fn maybe_split( ) -> Result { let g = group.to_string(); if on_db(db, move |conn| Ok(crate::chunks::is_split(conn, &g)?)).await? { + // a server that goes back further (one added, or keeping more now) + // is looked for every SPLIT_RECHECK: normal backfill never gets to + // the days older than the split's + let due = ctx.states.with(group, |st| { + let due = st.reach_back_after.is_none_or(|t| Instant::now() >= t); + if due { + st.reach_back_after = Some(Instant::now() + SPLIT_RECHECK); + } + due + }); + if due && let Err(e) = reach_back(ctx, db, group, home, (first, last), cursor).await { + println!("[SPLIT] {group}: couldnt look for servers going back further: {e:#}"); + } return Ok(true); } if (cursor.saturating_sub(first) as i64) < settings.split_min_backlog { @@ -494,9 +510,29 @@ async fn maybe_split( let g = group.to_string(); let added = on_db(db, move |conn| Ok(crate::chunks::add(conn, &g, newest_day, oldest_day)?)).await?; println!("[SPLIT] {group}: backfill split into {added} day chunks over {carriers} servers"); + ctx.states.with(group, |st| st.reach_back_after = Some(Instant::now() + SPLIT_RECHECK)); Ok(true) } +/// Days older than split `group`'s oldest that a carrier keeps now: chunks +/// for them, see `chunks::reach_back`. +async fn reach_back( + ctx: &PassContext, + db: &Db, + group: &str, + home: usize, + bounds: (u64, u64), + cursor: u64, +) -> Result<()> { + let Some((_, oldest_day, _)) = split_days(ctx, group, home, bounds, cursor).await? else { return Ok(()) }; + let g = group.to_string(); + let added = on_db(db, move |conn| Ok(crate::chunks::reach_back(conn, &g, oldest_day)?)).await?; + if added > 0 { + println!("[SPLIT] {group}: a server goes back further, {added} older day chunks"); + } + Ok(()) +} + /// The days a split of `group` covers, (newest, oldest), and how many servers /// carry it. None when it cant split: home's dates at either end are unknown /// or no other indexing server carries the group. `first` and `last` are diff --git a/tests/date_search.rs b/tests/date_search.rs index d2f94eb8..1ef10449 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -585,6 +585,80 @@ fn the_oldest_day_moves_on_when_the_deepest_server_drops_the_group() { assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("localhost")); } +/// A split made while the servers kept 5 days, then a server that keeps 10 +/// joins: the older days get chunks, the old oldest day (done only from +/// where the deepest server then started) is pending again, and the new +/// deepest server does the new oldest day. +#[test] +fn a_split_reaches_back_when_a_deeper_server_joins() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour for 10 days from 2026-01-01, from `from_hour` on + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = |from_hour: u64, offset: u64| -> Vec { + (from_hour..240) + .map(|h| { + let when = start + chrono::Duration::hours(h as i64); + post_at(offset + h, &format!(r#""p{h}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() + }; + let short = spawn_server(Server::new(posts(121, 1))); + let mut deep = mock(spawn_server(Server::new(posts(0, 10_001))), "secret", 2, 2); + deep.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(short, "secret", 2, 1), deep]); + pool.connect().unwrap(); + + // the split from before: days 5 to 9, the oldest done by the home server + let day0 = atlas::chunks::unix_day(start.timestamp()); + let conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&conn, GROUP, day0 + 9, day0 + 5).unwrap(); + conn.execute("update backfill_chunks set state = 2, server = '127.0.0.1', done_at = 1 where day = ?", [day0 + 5]) + .unwrap(); + atlas::chunks::set_deepest(&conn, GROUP, "127.0.0.1").unwrap(); + + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(atlas::db::open_at(&main).unwrap()); + let settings = atlas::indexer::PassSettings { + mode: "backfill".into(), + batch_size: 10, + request_size: 10, + split_min_backlog: 10, + }; + pool.block_on(atlas::indexer::run_pass(&ctx, &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); + + assert_eq!( + atlas::chunks::oldest_day(&conn, GROUP).unwrap(), + Some(day0), + "chunks back to the new server's first day" + ); + let state = |day: i64| -> i64 { + conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() + }; + assert_eq!(state(day0 + 5), 0, "the old oldest day is to do again"); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap(), None, "the deepest server is asked again"); + + // and the new days get indexed: the new oldest by the server that has it + for day in [day0 + 4, day0] { + let chunk = atlas::chunks::Claim { group: GROUP.into(), day, server: "localhost".into(), claimed_at: 1 }; + conn.execute( + "update backfill_chunks set state = 1, server = 'localhost', claimed_at = 1 where grp = ? and day = ?", + rusqlite::params![GROUP, day], + ) + .unwrap(); + let saved = + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 1, &mut |_| {})).unwrap(); + assert!(saved.articles >= 24, "day {day}: {} articles", saved.articles); + assert_eq!(state(day), 2); + } +} + /// A split reaches back to the oldest day of every carrier, also one whose /// GROUP low mark sits 5,000 numbers before its first article (retention /// has moved on, the mark hasnt): its older days get chunks. From 68c53dd38f3c07084292d87311f2ece4b9aaf9a6 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:08:39 -0500 Subject: [PATCH 059/159] A broken config.json is reported as broken, not missing Invalid JSON in config.json (a trailing comma, say) read the same as no file, so atlas said "not found" and offered first run setup, which would have written over it. config::file_problem tells a file that is there but unreadable or not valid JSON from a missing one, and says where: the path and serde_json's message with line and column, never the text, which holds passwords. The menu and --selftest stop on it, and --bg-indexer and the indexer's config check report it. Co-Authored-By: Claude Opus 5.5 --- src/app.rs | 9 +++++++++ src/bg_indexer.rs | 8 ++++++-- src/config.rs | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/app.rs b/src/app.rs index c100e765..b0b2fbbe 100644 --- a/src/app.rs +++ b/src/app.rs @@ -720,6 +720,11 @@ pub fn main_menu() -> i32 { } } + // a config.json that's there but broken isnt missing: setup would write over it + if let Some(problem) = crate::config::file_problem() { + ui::error(&format!("{problem}. fix it and start atlas again")); + return 1; + } let mut config = match load_config() { Some(c) if !c.servers.is_empty() => c, other => { @@ -832,6 +837,10 @@ pub fn main_menu() -> i32 { } pub fn selftest() -> i32 { + if let Some(problem) = crate::config::file_problem() { + println!("selftest: {problem}"); + return 1; + } let Some(cfg) = load_config() else { println!("selftest: no config found (run Settings or set ATLAS_NNTP_* env)"); return 1; diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 99d774c5..6a3a82e0 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -763,7 +763,8 @@ async fn supervise(stop: Arc, stats: Arc>, writing: Opt while !stopping() { let Some(config) = load_config() else { - ui::error("error with config, stopped"); + let why = crate::config::file_problem().unwrap_or_else(|| "config.json not found".into()); + ui::error(&format!("error with config, stopped: {why}")); break; }; @@ -819,7 +820,10 @@ async fn supervise(stop: Arc, stats: Arc>, writing: Opt pub fn run() -> i32 { let Some(config) = load_config().filter(|c| !c.servers.is_empty()) else { - println!("no valid config"); + match crate::config::file_problem() { + Some(problem) => println!("{problem}"), + None => println!("no valid config"), + } return 1; }; diff --git a/src/config.rs b/src/config.rs index 2c234d8f..d4545a9b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -341,6 +341,24 @@ fn env_creds_active() -> bool { ["ATLAS_NNTP_HOST", "ATLAS_NNTP_USER", "ATLAS_NNTP_PASS"].iter().all(|k| env_nonempty(k).is_some()) } +/// Why config.json cant be used though it's there, see `file_problem_at`. +pub fn file_problem() -> Option { + file_problem_at(&config_file()) +} + +/// Why the config file at `path` cant be used though it's there: it cant be +/// read, or isnt valid JSON (where, as serde_json says, never the text: it +/// holds passwords). None when it's fine, or isnt there at all. +pub fn file_problem_at(path: &std::path::Path) -> Option { + match fs::read_to_string(path) { + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + Err(e) => Some(format!("couldnt read {}: {e}", path.display())), + Ok(text) => { + serde_json::from_str::(&text).err().map(|e| format!("{} isnt valid JSON: {e}", path.display())) + } + } +} + fn read_file() -> Option { let text = fs::read_to_string(config_file()).ok()?; serde_json::from_str(&text).ok() @@ -599,6 +617,24 @@ mod tests { assert_eq!(cfg.max_unsaved_headers(), DEFAULT_MAX_UNSAVED_HEADERS as usize); } + #[test] + fn an_invalid_config_says_where_without_its_text() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.json"); + assert_eq!(file_problem_at(&path), None, "missing isnt a problem: setup offers to make one"); + + // a trailing comma after the last server + std::fs::write(&path, "{\n \"usenet_servers\": [{\"host\": \"news.x\", \"password\": \"hunter2\"},]\n}\n") + .unwrap(); + let problem = file_problem_at(&path).expect("a trailing comma is a problem"); + assert!(problem.contains(&path.display().to_string()), "{problem}"); + assert!(problem.contains("trailing comma at line 2 column"), "{problem}"); + assert!(!problem.contains("hunter2") && !problem.contains("news.x"), "no file contents: {problem}"); + + std::fs::write(&path, "{\"groups\": []}").unwrap(); + assert_eq!(file_problem_at(&path), None); + } + #[test] fn max_unsaved_headers_from_the_file() { let cfg = |v: Value| Config::from_value(&v).max_unsaved_headers(); From 882fc8f80a9e087adcd7643b72fd084a27e75045 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:26:10 -0500 Subject: [PATCH 060/159] The wipe removes every shard along with the main database Settings > Wipe db and cache removed only atlas.db, soo the next setup reused every atlas.sN.db: all releases survived while the new main database reset the cursors and the id counter against the old shards. The wipe now removes the shards, their -wal/-shm sidecars and any .compact/.precompact leftovers under the exclusive compaction lock, and is refused while the indexer or a compaction holds it. Co-Authored-By: Claude Opus 5.5 --- src/app.rs | 23 ++++++++------ src/compact.rs | 4 +-- src/db.rs | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 12 deletions(-) diff --git a/src/app.rs b/src/app.rs index b0b2fbbe..3f57310f 100644 --- a/src/app.rs +++ b/src/app.rs @@ -535,16 +535,19 @@ fn do_settings() { return; } - let dir = paths::app_dir(); - for f in [ - dir.join("atlas.db"), - dir.join("atlas.db-wal"), - dir.join("atlas.db-shm"), - paths::pid_file(), - paths::indexer_log(), - paths::status_file(), - paths::stats_file(), - ] { + // every shard goes with it, under the exclusive lock: leaving them + // would give the new main database cursors and ids over old shards + if let Err(e) = crate::db::wipe(&paths::database()) { + if e.downcast_ref::().is_some() { + ui::warn("the database is in use (indexing, a compaction or a save); nothing was wiped"); + } else { + ui::error(&format!("couldnt wipe the database: {e:#}")); + } + ui::pause(); + return; + } + + for f in [paths::pid_file(), paths::indexer_log(), paths::status_file(), paths::stats_file()] { let _ = fs::remove_file(f); } diff --git a/src/compact.rs b/src/compact.rs index bd6b1485..15d17c7a 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -117,10 +117,10 @@ impl Drop for WriteGuard { } /// The lock of a running compaction, let go when dropped (done, failed or stopped). -struct Lock(std::fs::File); +pub(crate) struct Lock(std::fs::File); impl Lock { - fn take(main: &Path) -> Result { + pub(crate) fn take(main: &Path) -> Result { let file = open_lock(main)?; match file.try_lock() { Ok(()) => Ok(Lock(file)), diff --git a/src/db.rs b/src/db.rs index f3bc5278..7748b59d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -8,6 +8,7 @@ use std::fs; use std::path::Path; use std::time::Duration; +use anyhow::Context; use rusqlite::{Connection, OptionalExtension, params}; use crate::compact::WriteGuard; @@ -140,6 +141,32 @@ pub fn create_db_holding(path: &Path) -> anyhow::Result> { Ok(Some(held)) } +/// Settings > wipe: the main database and every shard, with their sidecars +/// and what a compaction leaves (`.compact.db`, `.precompact.db`). Under the +/// exclusive compaction lock, soo refused (`Busy`) while the indexer, a write +/// from outside it or a compaction has the database. Leaves nothing to set +/// up again from: the next `create_db` makes a new one. +pub fn wipe(main: &Path) -> anyhow::Result<()> { + let _exclusive = crate::compact::Lock::take(main)?; + let mut dbs = vec![main.to_path_buf()]; + for shard in store::shard_paths(main) { + dbs.push(crate::compact::with_suffix(&shard, "compact")); + dbs.push(crate::compact::with_suffix(&shard, "precompact")); + dbs.push(shard); + } + for db in dbs { + for suffix in ["", "-wal", "-shm", "-journal"] { + let file = format!("{}{suffix}", db.display()); + match fs::remove_file(&file) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e).with_context(|| format!("removing {file}")), + } + } + } + Ok(()) +} + /// The main database and its shards, or brings an older one up to date. A /// database from before the shards is left as it is (apart from missing /// columns) for convert.rs; until then there are no shards. Run with @@ -471,6 +498,7 @@ pub fn update_backfill_cursor(conn: &Connection, group: &str, article: i64) -> R #[cfg(test)] mod tests { use super::*; + use std::path::PathBuf; #[test] fn group_dates_only_ever_widen() { let dir = tempfile::tempdir().unwrap(); @@ -610,4 +638,60 @@ mod tests { assert!(has_old_layout(&open_at(&old).unwrap()).unwrap()); assert!(!store::shard_path(&old, 0).exists(), "no shards until it is converted"); } + + /// releases in every shard, and the id counter + fn held(main: &Path) -> (i64, Option) { + let releases = store::shard_paths(main) + .iter() + .map(|p| { + open_at(p).unwrap().query_row("select count(*) from releases", [], |r| r.get::<_, i64>(0)).unwrap() + }) + .sum(); + (releases, store::get_meta(&open_at(main).unwrap(), "next_seq").unwrap()) + } + + #[test] + fn a_wipe_clears_every_shard_and_restarts_the_ids() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + create_db_at(&main).unwrap(); + let releases: Vec = ["alt.binaries.a", "alt.binaries.b", "alt.binaries.c"] + .iter() + .map(|g| Release { name: format!("Old {g}"), group: g.to_string(), ..Default::default() }) + .collect(); + store::save(&main, &releases).unwrap(); + init_group_state(&open_at(&main).unwrap(), "alt.binaries.a@news.x", 500).unwrap(); + let (before, next) = held(&main); + assert_eq!(before, 3); + assert!(next.unwrap() > 1); + + // what a compaction leaves behind, and the sidecars of a shard + let shard = store::shard_path(&main, 2); + let leftovers = [ + crate::compact::with_suffix(&shard, "compact"), + crate::compact::with_suffix(&shard, "precompact"), + PathBuf::from(format!("{}-wal", shard.display())), + PathBuf::from(format!("{}-shm", shard.display())), + ]; + for f in &leftovers { + std::fs::write(f, b"old").unwrap(); + } + + // the indexer, or a compaction, using the database: nothing is wiped + let writing = crate::compact::hold_off_compaction(&main).unwrap(); + let err = wipe(&main).unwrap_err(); + assert!(err.downcast_ref::().is_some(), "{err:#}"); + assert_eq!(held(&main).0, 3, "refused, all still there"); + drop(writing); + + wipe(&main).unwrap(); + for f in leftovers.iter().chain(&store::shard_paths(&main)) { + assert!(!f.exists(), "{} is gone", f.display()); + } + assert!(!main.exists()); + + create_db_at(&main).unwrap(); + assert_eq!(held(&main), (0, Some(1)), "no releases, ids from the start"); + assert!(group_progress(&open_at(&main).unwrap()).unwrap().is_empty(), "no cursors"); + } } From 8bcd03dd097fc82b16da8e385210f3db7910b4ce Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:26:10 -0500 Subject: [PATCH 061/159] A config.json whose root isnt an object is reported, not set up over null, a list or a string is valid JSON, soo it passed the broken file check, loaded as an empty config, and first-run setup then saved over the file. It is now reported as a problem (path and what it holds, never its contents) and setup isnt offered; the env credentials path ignores such a file too. Co-Authored-By: Claude Opus 5.5 --- src/config.rs | 44 +++++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/src/config.rs b/src/config.rs index d4545a9b..8e4f0341 100644 --- a/src/config.rs +++ b/src/config.rs @@ -348,20 +348,34 @@ pub fn file_problem() -> Option { /// Why the config file at `path` cant be used though it's there: it cant be /// read, or isnt valid JSON (where, as serde_json says, never the text: it -/// holds passwords). None when it's fine, or isnt there at all. +/// holds passwords), or is JSON that isnt an object (`null`, a list...: it +/// would load as an empty config, and setup would save over it). None when +/// it's fine, or isnt there at all. pub fn file_problem_at(path: &std::path::Path) -> Option { - match fs::read_to_string(path) { - Err(e) if e.kind() == io::ErrorKind::NotFound => None, - Err(e) => Some(format!("couldnt read {}: {e}", path.display())), - Ok(text) => { - serde_json::from_str::(&text).err().map(|e| format!("{} isnt valid JSON: {e}", path.display())) + let text = match fs::read_to_string(path) { + Err(e) if e.kind() == io::ErrorKind::NotFound => return None, + Err(e) => return Some(format!("couldnt read {}: {e}", path.display())), + Ok(text) => text, + }; + match serde_json::from_str::(&text) { + Err(e) => Some(format!("{} isnt valid JSON: {e}", path.display())), + Ok(Value::Object(_)) => None, + Ok(other) => { + let kind = match other { + Value::Null => "null", + Value::Bool(_) => "a boolean", + Value::Number(_) => "a number", + Value::String(_) => "a string", + _ => "an array", + }; + Some(format!("{} holds {kind}, not an object", path.display())) } } } fn read_file() -> Option { let text = fs::read_to_string(config_file()).ok()?; - serde_json::from_str(&text).ok() + serde_json::from_str(&text).ok().filter(Value::is_object) } /// Load config. Servers come from `usenet_servers` (or the old top level @@ -635,6 +649,22 @@ mod tests { assert_eq!(file_problem_at(&path), None); } + #[test] + fn valid_json_that_isnt_an_object_is_a_problem_too() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.json"); + // setup would save over any of these, as if there were no config + for (text, kind) in [("null", "null"), ("[]", "an array"), ("\"hunter2\"", "a string"), ("42", "a number")] { + std::fs::write(&path, text).unwrap(); + let problem = file_problem_at(&path).unwrap_or_else(|| panic!("{text} isnt a config")); + assert!(problem.contains(&path.display().to_string()), "{problem}"); + assert!(problem.contains(&format!("{kind}, not an object")), "{problem}"); + assert!(!problem.contains("hunter2"), "no file contents: {problem}"); + } + std::fs::write(&path, "{}").unwrap(); + assert_eq!(file_problem_at(&path), None, "an empty object is still a config"); + } + #[test] fn max_unsaved_headers_from_the_file() { let cfg = |v: Value| Config::from_value(&v).max_unsaved_headers(); From 44a89270c17dde8df3f69f80579c52ab6826b803 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:31:14 -0500 Subject: [PATCH 062/159] A test that the date search holds a bounded number of headers A crowd of 140,001 articles sits in numbers the spread out windows step over; first_post and article_at across it must find the right article while holding under 8MB at once (the crowd parsed is about 100MB). The mock streams uncompressed XOVER replies row by row, soo a huge listing isnt built in the test process and a client that hangs up stops it. Fails until the date search stops reading stepped over spans whole. Co-Authored-By: Claude Opus 5.5 --- tests/common/mod.rs | 35 ++++++++----- tests/date_search_memory.rs | 102 ++++++++++++++++++++++++++++++++++++ 2 files changed, 124 insertions(+), 13 deletions(-) create mode 100644 tests/date_search_memory.rs diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 580c97af..2909ace5 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -243,24 +243,21 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { let (a, b): (u64, u64) = (a.parse().unwrap(), b.parse().unwrap()); let posts = posts_lock(); let lo = posts.partition_point(|p| p.number < a); - let hits: Vec<&Post> = posts[lo..].iter().take_while(|p| p.number <= b).collect(); - if hits.is_empty() && state.empty_is_420 { + let hits = || posts[lo..].iter().take_while(|p| p.number <= b); + let row = |p: &Post| { + format!( + "{}\t{}\tposter \t{}\t{}\t\t{}\t10\r\n", + p.number, p.subject, p.date, p.message_id, p.bytes + ) + }; + if hits().next().is_none() && state.empty_is_420 { send(&mut out, b"420 No Articles Selected"); continue; } - if hits.is_empty() { + if hits().next().is_none() { send(&mut out, b"423 no articles in that range"); continue; } - let mut listing = Vec::new(); - for p in hits { - let row = format!( - "{}\t{}\tposter \t{}\t{}\t\t{}\t10\r\n", - p.number, p.subject, p.date, p.message_id, p.bytes - ); - listing.extend_from_slice(row.as_bytes()); - } - listing.extend_from_slice(b".\r\n"); if compressed && state.compress_broken { send(&mut out, b"224 overview follows [COMPRESS=GZIP]"); @@ -268,14 +265,26 @@ pub fn serve(stream: TcpStream, state: &Server, over_limit: bool) { // and hang up, like a confused server would return; } else if compressed { + let mut listing = Vec::new(); + for p in hits() { + listing.extend_from_slice(row(p).as_bytes()); + } + listing.extend_from_slice(b".\r\n"); let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::fast()); z.write_all(&listing).unwrap(); send(&mut out, b"224 overview follows [COMPRESS=GZIP]"); let _ = out.write_all(&z.finish().unwrap()); state.compressed_sent.fetch_add(1, Ordering::SeqCst); } else { + // row by row, soo a huge listing isnt built in memory first + // (a client that hangs up part way just stops it) send(&mut out, b"224 overview follows"); - let _ = out.write_all(&listing); + let mut w = std::io::BufWriter::new(&mut out); + let sent = + hits().try_for_each(|p| w.write_all(row(p).as_bytes())).and_then(|_| w.write_all(b".\r\n")); + if sent.and_then(|_| w.flush()).is_err() { + return; + } } } "BODY" => match posts_lock().iter().find(|p| p.message_id == arg).filter(|_| state.bodies) { diff --git a/tests/date_search_memory.rs b/tests/date_search_memory.rs new file mode 100644 index 00000000..f3486b3f --- /dev/null +++ b/tests/date_search_memory.rs @@ -0,0 +1,102 @@ +//! The date search holds a bounded number of headers whatever the span it +//! reads: a crowd of articles in numbers the spread out windows stepped over +//! isnt read into memory whole. Counts the live bytes of every allocation in +//! this test binary (the mock server's included, it streams its replies). + +mod common; + +use std::alloc::{GlobalAlloc, Layout, System}; +use std::sync::atomic::{AtomicIsize, Ordering}; + +use atlas::nntp::BlockingPool; +use common::{GROUP, Server, mock, post_at, spawn_server}; + +struct Counting; +static LIVE: AtomicIsize = AtomicIsize::new(0); +static PEAK: AtomicIsize = AtomicIsize::new(0); + +fn grew(n: isize) { + let now = LIVE.fetch_add(n, Ordering::Relaxed) + n; + PEAK.fetch_max(now, Ordering::Relaxed); +} + +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, l: Layout) -> *mut u8 { + grew(l.size() as isize); + unsafe { System.alloc(l) } + } + unsafe fn dealloc(&self, p: *mut u8, l: Layout) { + LIVE.fetch_sub(l.size() as isize, Ordering::Relaxed); + unsafe { System.dealloc(p, l) } + } + unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 { + grew(n as isize - l.size() as isize); + unsafe { System.realloc(p, l, n) } + } +} + +#[global_allocator] +static COUNTING: Counting = Counting; + +fn jan(day: i64) -> i64 { + chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap().timestamp() + (day - 1) * 86_400 +} + +/// 1..=50 a minute apart on Jan 1; a crowd of 140,001 posts a second apart +/// from Jan 2 at 150,000..=290,000; nothing till 598,000..=600,000 on Jan 10. +/// Searching from 100 on, the spread out windows step over the whole crowd +/// (they land on 140,100.. and 292,900.., both empty) before they hit the +/// last run. +fn crowd_between_windows() -> Vec<(u64, i64)> { + let early = (1..=50u64).map(|n| (n, jan(1) + (n as i64 - 1) * 60)); + let crowd = (150_000..=290_000u64).map(|n| (n, jan(2) + (n - 150_000) as i64)); + let late = (598_000..=600_000u64).map(|n| (n, jan(10) + (n - 598_000) as i64 * 60)); + early.chain(crowd).chain(late).collect() +} + +#[test] +fn the_date_search_holds_a_bounded_number_of_headers() { + let list = crowd_between_windows(); + let posts = list + .iter() + .map(|&(n, t)| { + // subjects as long as real ones, soo holding the crowd would show + let subject = format!(r#"[01/99] - "{n:0>96}.part01.rar" yEnc (1/1)"#); + post_at(n, &subject, &chrono::DateTime::from_timestamp(t, 0).unwrap().to_rfc2822()) + }) + .collect(); + let server = Server::new(posts); + let port = spawn_server(server.clone()); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + // a search finds `want`, holding little on top of what was live before + // it (the crowd's headers alone are about 100MB once parsed), in a + // reasonable number of requests + let check = |what: &str, want: Option, search: &dyn Fn() -> Option| { + let xovers = server.xovers.load(Ordering::SeqCst); + let before = LIVE.load(Ordering::Relaxed); + PEAK.store(before, Ordering::Relaxed); + let found = search(); + let held = PEAK.load(Ordering::Relaxed) - before; + let used = server.xovers.load(Ordering::SeqCst) - xovers; + eprintln!("{what}: found {found:?}, held {held} bytes, {used} requests"); + assert_eq!(found, want, "{what}"); + assert!(held < 8 << 20, "{what}: held {held} bytes at once"); + assert!(used <= 150, "{what}: {used} requests"); + }; + let first = |low: u64, when: i64| list.iter().find(|&&(n, t)| n >= low && t >= when).map_or(600_001, |&(n, _)| n); + let posted = |n: u64| list.iter().find(|&&(m, _)| m == n).unwrap().1; + + // how far back the server keeps the group, from a low mark of 100 + check("first post from 100", Some(jan(2)), &|| { + pool.block_on(pool.pool.first_post(0, GROUP, 100, 600_000)).unwrap() + }); + // the article at a time: inside the crowd, between the crowd and the last + // run (the backward search crosses the crowd), before everything + for (low, when) in [(1, posted(200_000)), (1, jan(5)), (100, jan(1)), (1, posted(290_000) + 1)] { + check(&format!("article at {when} from {low}"), Some(first(low, when) as i64), &|| { + Some(pool.block_on(pool.pool.article_at(0, GROUP, low, 600_000, when)).unwrap() as i64) + }); + } +} From eef60abe22c57908b324d2a2934e0fb4a90d49da Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:31:21 -0500 Subject: [PATCH 063/159] The date search reads at most 6,400 rows of any listing Reading the numbers spread out windows stepped over (first_before, last_after) asked for spans of up to millions of numbers in one XOVER and parsed the whole listing into memory, outside the unsaved cap: one search over a crowd held its every header. On a live indexer with split groups this grew the heap ~3GB/min until saving stalled (sampled in article_at -> first_in -> posted_at -> window -> parse_overview). Every date search request now goes through Pool::ends: the listing is read row by row (plain and compressed alike, see Conn::each_line) keeping only its first and last dated article, and no more than DATE_ROWS rows. Listings are sorted, soo the first rows answer a forward search; a backward one halves what it couldnt read whole, the upper half first. A listing cut short leaves its connection busy, soo it is thrown away. Windows of up to DATE_SCAN_MAX numbers are never cut. A compressed reply is also handed out as it inflates instead of being kept whole. Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 329 +++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 273 insertions(+), 56 deletions(-) diff --git a/src/nntp.rs b/src/nntp.rs index e921c169..5ce5a389 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -206,6 +206,45 @@ where } } +/// What a date search keeps of an XOVER listing: its first and its last +/// article with a post date, as (number, post time). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Ends { + pub first: Option, + pub last: Option, + /// rows read, and the highest number among them + pub rows: usize, + pub read_to: Option, + /// every row was read (not cut short at the row limit) + pub whole: bool, +} + +impl Ends { + /// nothing in the range + fn empty() -> Ends { + Ends { whole: true, ..Ends::default() } + } + + /// fold in one overview row + fn add(&mut self, row: &[u8]) { + self.rows += 1; + let mut fields = row.split(|b| *b == b'\t'); + let Some(number) = fields.next().and_then(|f| std::str::from_utf8(f).ok()?.trim().parse::().ok()) else { + return; + }; + self.read_to = self.read_to.max(Some(number)); + let Some(t) = fields.nth(2).and_then(|d| crate::dates::posted_timestamp(&String::from_utf8_lossy(d))) else { + return; + }; + if self.first.is_none_or(|f| number < f.0) { + self.first = Some((number, t)); + } + if self.last.is_none_or(|l| number > l.0) { + self.last = Some((number, t)); + } + } +} + /// One logged in connection to one server. pub struct Conn { io: BufReader>, @@ -290,49 +329,54 @@ impl Conn { } /// Body of a `[COMPRESS=GZIP]` multi-line response: a zlib (or gzip) - /// stream holding the usual dot terminated, dot stuffed lines. - async fn read_compressed_multiline(&mut self) -> Result>> { + /// stream holding the usual dot terminated, dot stuffed lines, handed to + /// `line` one at a time (see `each_line`). + async fn each_compressed_line(&mut self, mut line: impl FnMut(Vec) -> bool) -> Result { let mut inflater = Inflater::default(); - let mut lines = Vec::new(); + // inflated text not handed out yet: lines go as soon as they are + // whole, soo it holds about one read's worth let mut text = Vec::new(); - let mut scanned = 0; let mut terminated = false; loop { if !terminated { + let mut scanned = 0; while let Some(nl) = text[scanned..].iter().position(|b| *b == b'\n') { - let mut line = text[scanned..scanned + nl].to_vec(); + let mut l = text[scanned..scanned + nl].to_vec(); scanned += nl + 1; - if line.last() == Some(&b'\r') { - line.pop(); + if l.last() == Some(&b'\r') { + l.pop(); } - if line == b"." { + if l == b"." { terminated = true; break; } - if line.starts_with(b"..") { - line.remove(0); + if l.starts_with(b"..") { + l.remove(0); } - self.text += line.len() as u64 + 2; - lines.push(line); + self.text += l.len() as u64 + 2; + if !line(l) { + return Ok(false); + } } + text.drain(..scanned); } // done once the terminator showed up and the compressed stream is fully read, // soo no stray trailer bytes are left for the next command to trip over if terminated && inflater.finished() { - return Ok(lines); + return Ok(true); } let chunk = if terminated { // all lines are in, only the end of the compressed stream is missing. // a server that never closes the stream properly sends nothing more match self.read_chunk(STREAM_END_WAIT).await { - Err(NntpError::Io(e)) if e.kind() == io::ErrorKind::TimedOut => return Ok(lines), + Err(NntpError::Io(e)) if e.kind() == io::ErrorKind::TimedOut => return Ok(true), r => r?, } } else { @@ -391,22 +435,23 @@ impl Conn { Ok((code, message.to_string())) } - /// Lines of a multi-line response with dot-stuffing removed. - async fn read_multiline(&mut self) -> Result>> { - let mut lines = Vec::new(); - + /// A plain multi-line response, handed to `line` one at a time with + /// dot-stuffing removed (see `each_line`). + async fn each_plain_line(&mut self, mut line: impl FnMut(Vec) -> bool) -> Result { loop { - let mut line = self.read_raw_line().await?; + let mut l = self.read_raw_line().await?; - if line == b"." { - return Ok(lines); + if l == b"." { + return Ok(true); } - if line.starts_with(b"..") { - line.remove(0); + if l.starts_with(b"..") { + l.remove(0); } - lines.push(line); + if !line(l) { + return Ok(false); + } } } @@ -473,13 +518,53 @@ impl Conn { /// mark any listing they compressed (XOVER, LIST, ...) with `[COMPRESS=GZIP]` /// on the status line. async fn read_response_body(&mut self, status_message: &str) -> Result>> { + let mut lines = Vec::new(); + self.each_line(status_message, |l| { + lines.push(l); + true + }) + .await?; + Ok(lines) + } + + /// The lines of a multi-line response handed to `line` one at a time + /// until it returns false. True when the response was read to its end; + /// false when `line` stopped it: the rest is left unread, soo the + /// connection cant take another request. + async fn each_line(&mut self, status_message: &str, line: impl FnMut(Vec) -> bool) -> Result { if status_message.to_ascii_uppercase().contains("COMPRESS=GZIP") { - self.read_compressed_multiline().await + self.each_compressed_line(line).await } else { - self.read_multiline().await + self.each_plain_line(line).await } } + /// XOVER `start..=end` read for its first and last article with a post + /// date, `rows` rows at most: a listing longer than that is left unread + /// past them (`Ends::whole` is false) and the connection cant take + /// another request. Listings come sorted by number (RFC 3977), soo + /// `first` is the range's first even then. + pub async fn xover_ends(&mut self, start: u64, end: u64, rows: usize) -> Result { + let (code, message) = self.command("XOVER", Some(&format!("{start}-{end}"))).await?; + + if code != 224 { + return Err(NntpError::Reply { code, message }); + } + + let mut ends = Ends::default(); + let whole = self + .each_line(&message, |line| { + if ends.rows == rows { + return false; + } + ends.add(&line); + true + }) + .await?; + ends.whole = whole; + Ok(ends) + } + async fn list_active(&mut self, pattern: Option<&str>) -> Result>> { let args = match pattern { Some(p) => format!("ACTIVE {p}"), @@ -793,6 +878,10 @@ type Dated = (u64, i64); /// numbers per date search request at first, and at most const DATE_LOOK: u64 = 100; const DATE_SCAN_MAX: u64 = DATE_LOOK << 6; +/// rows a date search reads of one listing at most: whatever span it asks +/// for (stepped over numbers can hide a crowd), it holds no more. A window +/// of `DATE_SCAN_MAX` numbers is always read whole +const DATE_ROWS: usize = DATE_SCAN_MAX as usize; /// Several providers tried in priority order, each with up to `connections` /// requests in flight. @@ -1306,29 +1395,103 @@ impl Pool { Err(first_err) } - /// The first and the last article in `start..start + look` on server `i`, - /// with their post times: (number, unix seconds). None when there is none - /// (a gap in the numbering). - async fn window(&self, i: usize, group: &str, start: u64, look: u64) -> Result> { - match self.xover_on(i, group, start, start + look - 1).await { - Ok(rows) => Ok(rows - .iter() - .filter_map(|r| crate::dates::posted_timestamp(&r.date).map(|t| (r.number, t))) - .fold(None, |ends, a| match ends { - None => Some((a, a)), - Some((first, last)) => { - Some((if a.0 < first.0 { a } else { first }, if a.0 > last.0 { a } else { last })) - } - })), - Err(e) if e.is_empty_range() => Ok(None), - Err(e) => Err(e), + /// The first and the last dated article of `start..=end` on server `i`, + /// from an XOVER read `DATE_ROWS` rows at most (see `Conn::xover_ends`): + /// a date search never holds a listing, however many numbers it asks + /// for. A listing cut short costs its connection, which still has the + /// rest of it on the wire. + async fn ends(&self, i: usize, group: &str, start: u64, end: u64) -> Result { + let r = match self.ends_once(i, group, start, end).await { + Err(NntpError::Decompress(e)) => { + self.no_compression(i, &e); + self.ends_once(i, group, start, end).await + } + r => r, + }; + match r { + Err(e) if e.is_empty_range() => Ok(Ends::empty()), + r => r, + } + } + + async fn ends_once(&self, i: usize, group: &str, start: u64, end: u64) -> Result { + let mut lease = self.lease_for(i, Some(group), false).await?; + + if lease.group() != Some(group) { + let r = lease.begin().select_group(group).await; + lease.check(r)?; + } + + let sent = Instant::now(); + let r = lease.begin().xover_ends(start, end, DATE_ROWS).await; + crate::profile::Load::add_since(&crate::profile::LOAD.xover_ns, sent); + crate::profile::LOAD.xovers.fetch_add(1, Ordering::Relaxed); + match r { + Ok(ends) => { + lease.server.headers.fetch_add(ends.rows as u64, Ordering::Relaxed); + // the rest of a listing cut short is still coming: the lease + // stays busy, soo the connection is thrown away + if ends.whole { lease.check(Ok(ends)) } else { Ok(ends) } + } + r => lease.check(r), } } /// The first article at or after `number` within the next `look` numbers on - /// server `i`, with its post time. None when there is none. + /// server `i`, with its post time. None when there is none. One request: + /// listings are sorted, the first rows say. async fn posted_at(&self, i: usize, group: &str, number: u64, look: u64) -> Result> { - Ok(self.window(i, group, number, look).await?.map(|(first, _)| first)) + let end = number.saturating_add(look - 1); + let mut from = number; + loop { + let ends = self.ends(i, group, from, end).await?; + match (ends.first, ends.read_to) { + (Some(first), _) => return Ok(Some(first)), + // a cut short listing whose rows had no date: on past them + (None, Some(n)) if !ends.whole && n < end => from = n + 1, + _ => return Ok(None), + } + } + } + + /// The last article in `start..start + look` on server `i`, with its post + /// time. None when there is none. A listing too long to read whole is + /// halved, the upper half first, until the halves are: what was read of + /// it answers when nothing above it is found. + async fn last_at(&self, i: usize, group: &str, start: u64, look: u64) -> Result> { + enum Todo { + /// numbers still to read + Span(u64, u64), + /// the last article below the spans above it in the stack + Found(Dated), + } + let mut todo = vec![Todo::Span(start, start.saturating_add(look))]; + while let Some(next) = todo.pop() { + let (a, b) = match next { + Todo::Found(d) => return Ok(Some(d)), + Todo::Span(a, b) => (a, b), + }; + let ends = self.ends(i, group, a, b - 1).await?; + if ends.whole { + if ends.last.is_some() { + return Ok(ends.last); + } + continue; + } + // everything up to `read_to` was read: the rest of the span, in halves + if let Some(last) = ends.last { + todo.push(Todo::Found(last)); + } + let from = ends.read_to.map_or(a, |n| n + 1); + if from < b { + let mid = from + (b - from) / 2; + if from < mid { + todo.push(Todo::Span(from, mid)); + } + todo.push(Todo::Span(mid, b)); + } + } + Ok(None) } /// When the first article at or after `number` on server `i` was posted (unix seconds). @@ -1410,7 +1573,7 @@ impl Pool { skipped.push((to, read_from)); } let look = size.min(to - from); - if let Some((_, hit)) = self.window(i, group, to - look, look).await? { + if let Some(hit) = self.last_at(i, group, to - look, look).await? { return self.last_after(i, group, &skipped, hit).await.map(Some); } read_from = to - look; @@ -1431,7 +1594,7 @@ impl Pool { async fn last_after(&self, i: usize, group: &str, skipped: &[(u64, u64)], hit: Dated) -> Result { let Some((&(start, end), between)) = skipped.split_last() else { return Ok(hit) }; for &(from, to) in between { - if let Some((_, found)) = self.window(i, group, from, to - from).await? { + if let Some(found) = self.last_at(i, group, from, to - from).await? { return Ok(found); } } @@ -1439,13 +1602,13 @@ impl Pool { while lo < hi { let mid = lo + (hi - lo) / 2; let look = DATE_LOOK.min(hi - mid); - match self.window(i, group, mid, look).await? { - Some((_, found)) => (best, lo) = (found, found.0 + 1), + match self.last_at(i, group, mid, look).await? { + Some(found) => (best, lo) = (found, found.0 + 1), None => hi = mid, } } if end > best.0 + 1 - && let Some((_, l)) = self.window(i, group, best.0 + 1, end - best.0 - 1).await? + && let Some(l) = self.last_at(i, group, best.0 + 1, end - best.0 - 1).await? { best = l; } @@ -1495,15 +1658,20 @@ impl Pool { Ok(first) } + /// Compressed listings from server `i` couldnt be read: it gets plain ones from now on. + fn no_compression(&self, i: usize, e: &str) { + let server = &self.servers[i]; + if !server.no_compress.swap(true, Ordering::Relaxed) { + println!("{}: couldnt read compressed headers ({e}), turning compression off", server.cfg.host); + } + server.idle.lock().unwrap().retain(|c| !c.compressed); + } + async fn xover_on(&self, i: usize, group: &str, start: u64, end: u64) -> Result> { match self.xover_once(i, group, start, end).await { Err(NntpError::Decompress(e)) => { // turn compression off for this server and redo the slice uncompressed - let server = &self.servers[i]; - if !server.no_compress.swap(true, Ordering::Relaxed) { - println!("{}: couldnt read compressed headers ({e}), turning compression off", server.cfg.host); - } - server.idle.lock().unwrap().retain(|c| !c.compressed); + self.no_compression(i, &e); self.xover_once(i, group, start, end).await } r => r, @@ -2068,7 +2236,7 @@ mod tests { server.write_all(b"205 next\r\n").await.unwrap(); tokio::time::sleep(Duration::from_secs(10)).await; }); - let lines = conn.read_compressed_multiline().await.unwrap(); + let lines = conn.read_response_body("[COMPRESS=GZIP]").await.unwrap(); assert_eq!(conn.read_status().await.unwrap().0, 205, "read past the end of the response"); lines }) @@ -2114,13 +2282,62 @@ mod tests { } } + /// A date search reads a listing's first rows and no more: plain or + /// compressed, a listing longer than its rows is left unread. + #[test] + fn a_long_listing_is_read_only_as_far_as_the_row_limit() { + let dated = |n: usize| { + let mut text = Vec::new(); + for i in 1..=n { + let row = format!("{i}\ts{i}\tme\tFri, 02 Oct 2026 10:{:02}:00 +0000\t<{i}@x>\t\t100\t1\r\n", i % 60); + text.extend_from_slice(row.as_bytes()); + } + text.extend_from_slice(b".\r\n"); + text + }; + let read = |status: &'static str, wire: Vec, rows: usize| { + run(async move { + let (client, mut server) = tokio::io::duplex(1 << 16); + let mut conn = Conn::over(Box::new(client), Duration::from_secs(5)); + tokio::spawn(async move { + let mut cmd = [0u8; 64]; + let _ = tokio::io::AsyncReadExt::read(&mut server, &mut cmd).await; + let _ = server.write_all(status.as_bytes()).await; + let _ = server.write_all(&wire).await; + }); + conn.xover_ends(1, 50_000, rows).await.unwrap() + }) + }; + let posted = |n: u64| { + ( + n, + chrono::DateTime::parse_from_rfc2822(&format!("Fri, 02 Oct 2026 10:{:02}:00 +0000", n % 60)) + .unwrap() + .timestamp(), + ) + }; + + for (name, status, wire) in [ + ("plain", "224 overview follows\r\n", dated(50_000)), + ("compressed", "224 overview follows [COMPRESS=GZIP]\r\n", zlib(&dated(50_000))), + ] { + let cut = read(status, wire.clone(), 100); + assert_eq!((cut.whole, cut.rows, cut.read_to), (false, 100, Some(100)), "{name}"); + assert_eq!((cut.first, cut.last), (Some(posted(1)), Some(posted(100))), "{name}"); + + let whole = read(status, wire, 50_000); + assert_eq!((whole.whole, whole.rows), (true, 50_000), "{name}"); + assert_eq!((whole.first, whole.last), (Some(posted(1)), Some(posted(50_000))), "{name}"); + } + } + #[test] fn garbage_is_a_decompress_error() { run(async { let (client, mut server) = tokio::io::duplex(1 << 16); let mut conn = Conn::over(Box::new(client), Duration::from_secs(2)); server.write_all(&[0x78, 0x9c, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01]).await.unwrap(); - let err = conn.read_compressed_multiline().await.unwrap_err(); + let err = conn.read_response_body("[COMPRESS=GZIP]").await.unwrap_err(); assert!(matches!(err, NntpError::Decompress(_)), "{err}"); }); } From 1ef382afc212014b9bc1d66b4d020057e95c4add Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:32:24 -0500 Subject: [PATCH 064/159] A test for articles found only between spread out windows A server whose articles are all in numbers the spread out windows step over, none where a window lands, going forward (first_post) and backward (article_at crossing a hole down to them). Fails until the search reads what it stepped over before calling a range empty. Co-Authored-By: Claude Opus 5.5 --- tests/date_search.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/date_search.rs b/tests/date_search.rs index 1ef10449..756caece 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -222,6 +222,29 @@ fn a_small_cluster_between_spread_out_windows_is_found_going_forward() { assert_eq!(at("2026-01-02T00:00:00+00:00"), 100_000); } +/// Articles only in numbers the spread out windows step over, none where +/// any window lands: the search finds them instead of taking the range for +/// empty (a server whose history is all there would look like it has none). +#[test] +fn articles_only_between_spread_out_windows_are_found() { + // five posts at 20,000, then nothing till a run at 190,000 + let mut posts = minutely(20_000..=20_004, "2026-01-02T00:00:00+00:00"); + posts.extend(minutely(190_000..=190_100, "2026-01-03T00:00:00+00:00")); + let port = spawn_server(Server::new(posts)); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + // going forward: every window in 1..=100,000 is empty + let first = pool.block_on(pool.pool.first_post(0, GROUP, 1, 100_000)).unwrap(); + assert_eq!(first, Some(unix("2026-01-02T00:00:00+00:00")), "the cluster's first post"); + // going backward from the middle (a hole up to the run): the cluster is + // the last article before it, every window short of it is empty + let at = |when: &str| pool.block_on(pool.pool.article_at(0, GROUP, 1, 190_100, unix(when))).unwrap(); + assert_eq!(at("2026-01-01T00:00:00+00:00"), 20_000); + assert_eq!(at("2026-01-02T00:03:00+00:00"), 20_003); + assert_eq!(at("2026-01-02T12:00:00+00:00"), 190_000); +} + /// The same going backwards: a few articles in the numbers the spread out /// windows step over, after the articles they land on, are still the last /// before the hole. From 9fb93be442a9896dbd9ed1745ebf1a722243df8e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:36:45 -0500 Subject: [PATCH 065/159] A range is empty only once what its windows stepped over is read too first_in and last_in read the numbers their spread out windows stepped over only after a window found an article. When every window was empty they said the range had none, though articles could all be in what was stepped over: first_post could then take a server for having nothing and leave its history out. Now each stepped over span is read (one bounded request each, nearest first) before giving up. Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/nntp.rs b/src/nntp.rs index 5ce5a389..237206b0 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1504,8 +1504,8 @@ impl Pool { /// to `DATE_SCAN_MAX` numbers; past that the windows spread out (each /// starts twice as far from `from` as the last ended, the last ends at /// `end`), soo a hole of millions takes a few dozen small requests. The - /// numbers stepped over are read before a hit is taken as the first, see - /// `first_before`. + /// numbers stepped over are read before a hit is taken as the first (see + /// `first_before`), and before the range is taken for empty. async fn first_in(&self, i: usize, group: &str, from: u64, end: u64) -> Result> { // the numbers between windows that weren't read, lowest first let mut skipped = Vec::new(); @@ -1527,6 +1527,12 @@ impl Pool { at = (read_to + (read_to - from)).min(end.saturating_sub(DATE_SCAN_MAX)).max(read_to); } } + // no window found one: the first article, if any, was stepped over + for &(from, to) in &skipped { + if let Some(found) = self.posted_at(i, group, from, to - from).await? { + return Ok(Some(found)); + } + } Ok(None) } @@ -1584,6 +1590,12 @@ impl Pool { to = end.saturating_sub(2 * (end - read_from)).max(from.saturating_add(DATE_SCAN_MAX)).min(read_from); } } + // no window found one: the last article, if any, was stepped over + for &(from, to) in &skipped { + if let Some(found) = self.last_at(i, group, from, to - from).await? { + return Ok(Some(found)); + } + } Ok(None) } From 7d9200a2040cb0fd8a57d1faba5edc59cc426bef Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:39:22 -0500 Subject: [PATCH 066/159] A test for a split whose oldest day a server comes to keep more of The oldest day was done from 18:00 (where every carrier started); a carrier then keeps it from 01:00. The day is no older, soo nothing reopened it and 01:00 to 18:00 was never indexed. Fails until retention is compared by time, not by day. Co-Authored-By: Claude Opus 5.5 --- tests/date_search.rs | 74 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/tests/date_search.rs b/tests/date_search.rs index 756caece..14b81604 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -733,6 +733,80 @@ fn a_split_reaches_a_carrier_whose_low_mark_lags() { ); } +/// A carrier that comes to keep more of the split's oldest day (from 01:00 +/// where the day was done from 18:00): the day isnt older, but it is to do +/// again, by that carrier, soo 01:00 to 18:00 gets indexed. +#[test] +fn a_split_redoes_its_oldest_day_when_a_server_goes_back_further_in_it() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour from 2026-01-01 00:00, the hours in `hours` + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = |hours: std::ops::Range, offset: u64| -> Vec { + hours + .map(|h| { + let when = start + chrono::Duration::hours(h as i64); + post_at(offset + h, &format!(r#""p{h}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() + }; + // both keep the group from Jan 1 18:00 at first + let deep = Server::new(posts(18..240, 10_001)); + let short = spawn_server(Server::new(posts(18..240, 1))); + let mut later = mock(spawn_server(deep.clone()), "secret", 2, 2); + later.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(short, "secret", 2, 1), later]); + pool.connect().unwrap(); + + let ctx = || atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(atlas::db::open_at(&main).unwrap()); + let settings = atlas::indexer::PassSettings { + mode: "backfill".into(), + batch_size: 10, + request_size: 10, + split_min_backlog: 10, + }; + let conn = atlas::db::open_at(&main).unwrap(); + let day0 = atlas::chunks::unix_day(start.timestamp()); + let state = |day: i64| -> i64 { + conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() + }; + let run_day = |day: i64, server: usize| { + let host = if server == 0 { "127.0.0.1" } else { "localhost" }; + let chunk = atlas::chunks::Claim { group: GROUP.into(), day, server: host.into(), claimed_at: 1 }; + conn.execute( + "update backfill_chunks set state = 1, server = ?, claimed_at = 1 where grp = ? and day = ?", + rusqlite::params![host, GROUP, day], + ) + .unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx(), &Default::default(), &db, &chunk, server, &mut |_| {})).unwrap() + }; + + // the split, and its oldest day done from 18:00 by the home server + pool.block_on(atlas::indexer::run_pass(&ctx(), &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); + assert_eq!(atlas::chunks::oldest_day(&conn, GROUP).unwrap(), Some(day0)); + assert_eq!(run_day(day0, 0).articles, 7, "18:00 to midnight and the hour after"); + assert_eq!(state(day0), 2); + + // "localhost" keeps the day from 01:00 now + let mut older = posts(1..18, 10_001); + older.extend(deep.posts.lock().unwrap().drain(..)); + *deep.posts.lock().unwrap() = older; + + pool.block_on(atlas::indexer::run_pass(&ctx(), &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); + assert_eq!(atlas::chunks::oldest_day(&conn, GROUP).unwrap(), Some(day0), "no older day"); + assert_eq!(state(day0), 0, "the oldest day is to do again"); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap(), None, "the deepest server is asked again"); + assert_eq!(run_day(day0, 1).articles, 24, "01:00 to midnight and the hour after"); + assert_eq!(state(day0), 2); +} + /// (number, unix seconds) of a post type Slot = (u64, i64); From e0aab0c848cab862d0c18d855e10092e39d9a46d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:40:45 -0500 Subject: [PATCH 067/159] A shard next to its precompact backup refuses writes till one is removed When both exist and their roles cant be established (a cut short compaction, or an older atlas that made an empty shard beside the backup), startup only warned and indexing wrote into the shard. Now the indexer, AI search saves, purging and convert refuse, with a message naming both files and how to keep either; the menu and reads still start. A database with no backups is unaffected. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- src/bg_indexer.rs | 9 ++++- src/compact.rs | 91 +++++++++++++++++++++++++++++++++++++++---- src/db.rs | 2 +- tests/compact_lock.rs | 18 +++++++++ 5 files changed, 112 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 83115f04..050fb3f4 100644 --- a/README.md +++ b/README.md @@ -269,7 +269,7 @@ Release IDs change in the conversion, so NZB links that Prowlarr or your apps sa The `--compact` command rewrites every shard into a fresh database file while the indexer is stopped. It re-encodes message IDs with the current packing and seals every file that's due. The copy has no free space in it. Expect the first compaction to shrink the database a lot, roughly from 138 GB to 60 GB on a full database. Atlas checks each shard's copy before it replaces the original. If a shard fails, Atlas keeps its original and reports the error; the other shards are still compacted. -With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, it holds a lock on the `atlas.compacting` file next to `atlas.db`, and the indexer, the menu's AI search saves and the broken release purge refuse to run until it's done. A compaction doesn't start while the indexer runs (outside its own auto compaction), while one of those is saving, or while another compaction runs; auto compaction then tries again 10 minutes later. The lock goes away with the process that holds it, so a crash leaves nothing to clean up (the file itself stays). A crash in the middle of swapping a shard can leave its original moved aside as `atlas.sN.precompact.db` with nothing in its place. The next start of atlas, the indexer or a compaction puts it back (and removes the half swapped copy), taking the lock first. A shard that is missing with no backup next to it, while the other shards are there, stops atlas from starting instead of being made again empty; put it back first. +With `auto_run_compact` set to `true`, the indexer compacts the database every 24 hours. Indexing pauses while it runs and resumes afterward. Stopping the indexer during a compaction stops it within seconds and keeps the originals of unfinished shards. A failed shard is tried again 24 hours later. While a compaction runs, it holds a lock on the `atlas.compacting` file next to `atlas.db`, and the indexer, the menu's AI search saves and the broken release purge refuse to run until it's done. A compaction doesn't start while the indexer runs (outside its own auto compaction), while one of those is saving, or while another compaction runs; auto compaction then tries again 10 minutes later. The lock goes away with the process that holds it, so a crash leaves nothing to clean up (the file itself stays). A crash in the middle of swapping a shard can leave its original moved aside as `atlas.sN.precompact.db` with nothing in its place. The next start of atlas, the indexer or a compaction puts it back (and removes the half swapped copy), taking the lock first. A shard that is missing with no backup next to it, while the other shards are there, stops atlas from starting instead of being made again empty; put it back first. A shard with an `atlas.sN.precompact.db` next to it, when it isn't known which of the two is whole (the crash may have come after the copy went in, or an older atlas made an empty shard beside the backup), is not touched: the menu still opens, but the indexer, AI search saves and purging refuse to write, and the message names both files and how to go on (keep the shard and delete the backup, or the other way round). A group that has caught up rests for 10 seconds before Atlas checks it again. Atlas parks a group that fails 3 times in a row for 5 minutes. @@ -294,7 +294,7 @@ AI search lets you describe what you want in plain language, for example `find m - **Usenet servers:** list, add, edit, and remove servers, including host, login, port, SSL, connections, and priority. - **Change indexer mode:** switch between dynamic, live, and backfill. - **Purge broken releases:** delete incomplete releases to free up space. -- **Wipe DB and cache:** clear the database, logs, status, and stats. Stop the indexer first. +- **Wipe DB and cache:** clear the database (`atlas.db` and every `atlas.sN.db` shard, with leftovers of a compaction), logs, status, and stats. Stop the indexer first; it is refused while the indexer, a compaction or a save has the database. - **Change API port:** move the Newznab API and restart it with the current `api_host`. ## Stats dashboard diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 6a3a82e0..54496020 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -840,7 +840,14 @@ pub fn run() -> i32 { // compaction held off from before setting up: a shard it's swapping // would look missing. kept for indexing let writing = match db::create_db() { - Ok(Some(held)) => held, + Ok(Some(held)) => match crate::compact::refuse_unresolved_backups(&paths::database()) { + Ok(()) => held, + Err(e) => { + ui::error(&format!("not indexing: {e:#}")); + write_status(false, "", &config.index_mode, false, "stopped", true, 1); + return 1; + } + }, Ok(None) => { ui::error("not indexing: the database is being compacted; try again later"); write_status(false, "", &config.index_mode, false, "stopped", true, 1); diff --git a/src/compact.rs b/src/compact.rs index 15d17c7a..de2cb3f2 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -94,9 +94,17 @@ impl std::error::Error for Busy {} #[must_use = "the write is only safe while the guard is held"] pub struct WriteGuard(std::fs::File); -/// Hold off compaction while writing the shards, see `WriteGuard`. +/// Hold off compaction while writing the shards, see `WriteGuard`. Also +/// refused while a shard and its `.precompact.db` are both there and which +/// one is whole isnt known (`unresolved_backups`): a write would go into +/// whichever is wrong. Whoever holds this is about to write; setting up the +/// database and reading go through `try_hold_off_compaction` and aren't held +/// back. pub fn hold_off_compaction(main: &Path) -> Result { - try_hold_off_compaction(main)?.ok_or_else(|| anyhow!("the database is being compacted; try again later")) + let held = + try_hold_off_compaction(main)?.ok_or_else(|| anyhow!("the database is being compacted; try again later"))?; + refuse_unresolved_backups(main)?; + Ok(held) } /// `hold_off_compaction`, None while a compaction runs. @@ -136,13 +144,52 @@ impl Drop for Lock { } } +/// Shards with a `.precompact.db` next to them, as (shard, backup). With the +/// lock held a backup next to a shard is not a compaction at work: it was +/// cut short, or an older atlas made an empty shard beside it. +pub fn unresolved_backups(main: &Path) -> Result> { + let mut found = Vec::new(); + for path in store::shard_paths(main) { + let backup = with_suffix(&path, "precompact"); + if backup.try_exists()? && path.try_exists()? { + found.push((path, backup)); + } + } + Ok(found) +} + +/// What to tell the user about one `unresolved_backups` pair: both files, and +/// how to go on with either. +fn unresolved_message(shard: &Path, backup: &Path) -> String { + let bytes = |p: &Path| crate::ui::fmt_size(Some(size(p) as i64)); + format!( + "{shard} ({}) and {backup} ({}) both exist, and which one is whole isnt known: a compaction was cut short, \ + or an older atlas made an empty shard next to the backup. Not writing the shards till this is resolved. \ + Stop atlas, then either keep {shard} and delete {backup}, or keep {backup}: delete {shard} (and its -wal and \ + -shm files) and rename {backup} to {shard}. The bigger one usually has the releases", + bytes(shard), + bytes(backup), + shard = shard.display(), + backup = backup.display(), + ) +} + +/// Err for the first of `unresolved_backups`, see `unresolved_message`. +pub fn refuse_unresolved_backups(main: &Path) -> Result<()> { + match unresolved_backups(main)?.first() { + Some((shard, backup)) => bail!("{}", unresolved_message(shard, backup)), + None => Ok(()), + } +} + /// Put back the original of every shard whose swap was cut short (a crash, /// or its copy failing to move in): the original moved aside as /// `.precompact.db` and nothing in its place. Nothing writes a shard while /// it's compacted, soo the original is whole: it goes back, and the copy /// goes. A backup next to a shard that is in place is kept (the copy may have /// gone in, or a shard made empty in its place by an older atlas; which one -/// is whole isnt known). Returns a line for each, to show. +/// is whole isnt known) and said so: the indexer and saves refuse till the +/// user removes one (`hold_off_compaction`). Returns a line for each, to show. /// /// Only with the lock held (either kind): a running compaction has a shard /// moved aside on purpose for a moment. @@ -154,11 +201,7 @@ pub fn recover_cut_swaps(main: &Path) -> Result> { continue; } if path.try_exists()? { - said.push(format!( - "{} is left from a compaction that was cut short, and kept: once {} reads back fine, remove it", - original.display(), - path.display() - )); + said.push(unresolved_message(&path, &original)); continue; } std::fs::rename(&original, &path) @@ -1202,4 +1245,36 @@ mod tests { assert!(backup.exists(), "kept by a compaction too"); assert_eq!(all_articles(&main), before); } + + #[test] + fn a_shard_and_its_backup_together_refuse_writes_but_not_the_menu() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + + // a normal database, no backups: untouched + drop(hold_off_compaction(&main).unwrap()); + drop(db::create_db_holding(&main).unwrap().unwrap()); + + // an older atlas made an empty shard next to the backup: which to keep isnt known + let path = store::shard_path(&main, store::shard_of("alt.binaries.g3")); + let backup = with_suffix(&path, "precompact"); + std::fs::copy(&path, &backup).unwrap(); + + // writes are refused, with both files named and how to go on + let err = format!("{:#}", hold_off_compaction(&main).err().expect("refused")); + assert!(err.contains(&path.display().to_string()) && err.contains(&backup.display().to_string()), "{err}"); + assert!(err.contains("keep") && err.contains("delete"), "says how to resolve it: {err}"); + // the lock isnt kept by a refused hold: a compaction gets its own refusal, not Busy + assert!(!busy(run(&main, &|_| {}, &no_stop()))); + + // the menu still starts and reads + drop(db::create_db_holding(&main).unwrap().expect("set up")); + assert_eq!(all_articles(&main), before); + + // resolved: the shard is kept, the backup removed + std::fs::remove_file(&backup).unwrap(); + drop(hold_off_compaction(&main).unwrap()); + } } diff --git a/src/db.rs b/src/db.rs index 7748b59d..450b3917 100644 --- a/src/db.rs +++ b/src/db.rs @@ -678,7 +678,7 @@ mod tests { } // the indexer, or a compaction, using the database: nothing is wiped - let writing = crate::compact::hold_off_compaction(&main).unwrap(); + let writing = crate::compact::try_hold_off_compaction(&main).unwrap().unwrap(); let err = wipe(&main).unwrap_err(); assert!(err.downcast_ref::().is_some(), "{err:#}"); assert_eq!(held(&main).0, 3, "refused, all still there"); diff --git a/tests/compact_lock.rs b/tests/compact_lock.rs index ce4bc75f..f4720786 100644 --- a/tests/compact_lock.rs +++ b/tests/compact_lock.rs @@ -64,6 +64,24 @@ fn the_indexer_and_a_compaction_lock_each_other_out() { compacting.unlock().unwrap(); drop(compacting); + // a backup next to a shard that is in place, roles unknown (an older atlas + // made an empty shard beside it): the indexer refuses, and writes nothing + let backup = home.path().join("atlas.s0.precompact.db"); + std::fs::copy(atlas::store::shard_path(&main, 0), &backup).unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let runner = index(&stop); + let deadline = Instant::now() + Duration::from_secs(10); + while !runner.is_finished() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(50)); + } + let refused = runner.is_finished(); + stop.store(true, Ordering::Relaxed); + let code = runner.join().unwrap(); + assert!(refused, "the indexer started with a backup next to a shard"); + assert_ne!(code, 0, "refusing is an error"); + assert_eq!(articles(), 0, "nothing was written"); + std::fs::remove_file(&backup).unwrap(); + // the indexer runs: a compaction is refused, and touches nothing let stop = Arc::new(AtomicBool::new(false)); let runner = index(&stop); From 3b54f0303cccd232910d6b7fc50d4482c9c724f4 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 20:46:27 -0500 Subject: [PATCH 068/159] A split's oldest day is redone when a server keeps more of that day reach_back compared retention by UTC day alone: a carrier starting at 01:00 on the oldest day, done from 18:00 by the server then going back furthest, was no older a day, soo 01:00 to 18:00 was never indexed and that server stayed the deepest. The deepest server now keeps the time its first article was posted (backfill_deepest.oldest_at, added to old tables), split_days reports the exact oldest time over the carriers, and an earlier time within the oldest day reopens it and forgets the deepest server, like an older day does. A deepest noted before the time was kept is left as it was. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 93 ++++++++++++++++++++++++++++++++++---------- src/indexer.rs | 47 +++++++++++++++------- tests/date_search.rs | 2 +- 3 files changed, 106 insertions(+), 36 deletions(-) diff --git a/src/chunks.rs b/src/chunks.rs index 4633efbc..431c6dd5 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -25,22 +25,30 @@ pub fn create(conn: &Connection) -> Result<()> { done_at INTEGER, primary key (grp, day) ) without rowid; - create table if not exists backfill_deepest (grp TEXT PRIMARY KEY, server TEXT NOT NULL) without rowid;", + create table if not exists backfill_deepest ( + grp TEXT PRIMARY KEY, + server TEXT NOT NULL, + oldest_at INTEGER + ) without rowid;", )?; - if has_done_at(conn)? { + add_column(conn, "backfill_chunks", "done_at")?; + add_column(conn, "backfill_deepest", "oldest_at") +} + +/// Give `table` the INTEGER column `column` if a table made before it lacks it. +fn add_column(conn: &Connection, table: &str, column: &str) -> Result<()> { + let has = + || conn.prepare(&format!("select 1 from pragma_table_info('{table}') where name = '{column}'"))?.exists([]); + if has()? { return Ok(()); } - match conn.execute_batch("alter table backfill_chunks add column done_at INTEGER") { + match conn.execute_batch(&format!("alter table {table} add column {column} INTEGER")) { // the indexer and the menu can both add it at once - Err(_) if has_done_at(conn)? => Ok(()), + Err(_) if has()? => Ok(()), r => r, } } -fn has_done_at(conn: &Connection) -> Result { - conn.prepare("select 1 from pragma_table_info('backfill_chunks') where name = 'done_at'")?.exists([]) -} - /// days since 1970-01-01 UTC pub fn unix_day(t: i64) -> i64 { t.div_euclid(86_400) @@ -61,17 +69,28 @@ pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> Ok(added) } -/// Chunks for the days of split `group` from before its oldest one back to -/// `oldest_day`, when a server goes back further than any did at the split. -/// The old oldest day was done (if it was) only from where the server going -/// back furthest then started: it is to do again, and that server is -/// forgotten (see `deepest`). Returns the days added. -pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64) -> Result { +/// When a server goes back further than any did on split `group`, to +/// `oldest_at` (unix seconds) in `oldest_day`: chunks for the days from +/// before the split's oldest one back to `oldest_day`. The old oldest day +/// was done (if it was) only from where the server going back furthest then +/// started: it is to do again, and that server is forgotten (see `deepest`). +/// Also when `oldest_day` is the oldest day but `oldest_at` is before where +/// that server started in it. Returns the chunks added or to do again. +pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i64) -> Result { let tx = conn.unchecked_transaction()?; let Some(old) = self::oldest_day(&tx, group)? else { return Ok(0) }; - if oldest_day >= old { + if oldest_day > old { return Ok(0); } + if oldest_day == old { + let since: Option = tx + .query_row("select oldest_at from backfill_deepest where grp = ?", [group], |r| r.get(0)) + .optional()? + .flatten(); + if since.is_none_or(|since| oldest_at >= since) { + return Ok(0); + } + } let mut added = 0; { let mut insert = @@ -80,7 +99,7 @@ pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64) -> Result Result Result> { conn.query_row("select server from backfill_deepest where grp = ?", [group], |r| r.get(0)).optional() } -/// Note `server` as the one going back furthest on `group`. -pub fn set_deepest(conn: &Connection, group: &str, server: &str) -> Result<()> { - conn.execute("insert or replace into backfill_deepest (grp, server) values (?, ?)", [group, server])?; +/// Note `server` as the one going back furthest on `group`, from `oldest_at` +/// (when its first article was posted, unix seconds). +pub fn set_deepest(conn: &Connection, group: &str, server: &str, oldest_at: i64) -> Result<()> { + conn.execute( + "insert or replace into backfill_deepest (grp, server, oldest_at) values (?, ?, ?)", + params![group, server, oldest_at], + )?; Ok(()) } @@ -234,6 +257,36 @@ mod tests { assert_eq!(progress(&c, "g").unwrap(), (1, 3)); } + #[test] + fn the_oldest_day_is_redone_when_retention_reaches_further_into_it() { + let c = conn(); + let done = |c: &Connection| { + c.execute("update backfill_chunks set state = 2, server = 'a', done_at = 1 where day = 10", []).unwrap() + }; + let state = |c: &Connection| -> i64 { + c.query_row("select state from backfill_chunks where day = 10", [], |r| r.get(0)).unwrap() + }; + add(&c, "g", 12, 10).unwrap(); + done(&c); + // "a" went back furthest, to 18:00 on day 10 + set_deepest(&c, "g", "a", 10 * 86_400 + 18 * 3600).unwrap(); + + assert_eq!(reach_back(&c, "g", 10, 10 * 86_400 + 18 * 3600).unwrap(), 0, "no further"); + assert_eq!(reach_back(&c, "g", 10, 10 * 86_400 + 20 * 3600).unwrap(), 0, "less far"); + assert_eq!((state(&c), deepest(&c, "g").unwrap().as_deref()), (2, Some("a"))); + + assert_eq!(reach_back(&c, "g", 10, 10 * 86_400 + 3600).unwrap(), 1, "01:00 the same day"); + assert_eq!((state(&c), deepest(&c, "g").unwrap()), (0, None), "to do again, deepest asked again"); + + // a deepest noted before its time was: nothing to compare, left alone + done(&c); + c.execute("insert into backfill_deepest (grp, server) values ('g', 'a')", []).unwrap(); + assert_eq!(reach_back(&c, "g", 10, 10 * 86_400).unwrap(), 0); + assert_eq!(state(&c), 2); + // a day before it still reaches back + assert_eq!(reach_back(&c, "g", 9, 9 * 86_400).unwrap(), 2, "day 9 added, day 10 to do again"); + } + #[test] fn stale_claims_are_taken_over() { let c = conn(); diff --git a/src/indexer.rs b/src/indexer.rs index 74c7932d..14e705eb 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -502,7 +502,9 @@ async fn maybe_split( return Ok(false); } - let Some((newest_day, oldest_day, carriers)) = split_days(ctx, group, home, (first, last), cursor).await? else { + let Some(Split { newest_day, oldest_day, carriers, .. }) = + split_days(ctx, group, home, (first, last), cursor).await? + else { ctx.states.with(group, |st| st.no_split_until = Some(Instant::now() + SPLIT_RECHECK)); return Ok(false); }; @@ -524,26 +526,38 @@ async fn reach_back( bounds: (u64, u64), cursor: u64, ) -> Result<()> { - let Some((_, oldest_day, _)) = split_days(ctx, group, home, bounds, cursor).await? else { return Ok(()) }; + let Some(Split { oldest_day, oldest_at, .. }) = split_days(ctx, group, home, bounds, cursor).await? else { + return Ok(()); + }; let g = group.to_string(); - let added = on_db(db, move |conn| Ok(crate::chunks::reach_back(conn, &g, oldest_day)?)).await?; - if added > 0 { - println!("[SPLIT] {group}: a server goes back further, {added} older day chunks"); + let todo = on_db(db, move |conn| Ok(crate::chunks::reach_back(conn, &g, oldest_day, oldest_at)?)).await?; + if todo > 0 { + println!("[SPLIT] {group}: a server goes back further, {todo} day chunks to do"); } Ok(()) } -/// The days a split of `group` covers, (newest, oldest), and how many servers -/// carry it. None when it cant split: home's dates at either end are unknown -/// or no other indexing server carries the group. `first` and `last` are -/// home's low and high marks. +/// What a split of a group covers. +struct Split { + newest_day: i64, + oldest_day: i64, + /// when the oldest article any carrier keeps was posted (unix seconds) + oldest_at: i64, + /// servers carrying the group + carriers: usize, +} + +/// The days a split of `group` covers and how many servers carry it. None +/// when it cant split: home's dates at either end are unknown or no other +/// indexing server carries the group. `first` and `last` are home's low and +/// high marks. async fn split_days( ctx: &PassContext, group: &str, home: usize, (first, last): (u64, u64), cursor: u64, -) -> Result> { +) -> Result> { use crate::chunks::unix_day; // the newest day still to do is the post date at the home cursor, the @@ -552,7 +566,7 @@ async fn split_days( let Some(newest) = ctx.pool.posted_date(home, group, cursor).await? else { return Ok(None) }; let Some(oldest) = ctx.pool.first_post(home, group, first, last).await? else { return Ok(None) }; let newest_day = unix_day(newest); - let mut oldest_day = unix_day(oldest).min(newest_day); + let mut oldest_at = oldest; // other servers are best effort: one that fails is left out. one that // carries the group counts, its oldest date only if it has one @@ -561,12 +575,15 @@ async fn split_days( let Ok((_, low, high, _)) = ctx.pool.group_on(other, group).await else { continue }; carriers += 1; if let Ok(Some(t)) = ctx.pool.first_post(other, group, low, high).await { - oldest_day = oldest_day.min(unix_day(t)); + oldest_at = oldest_at.min(t); } } + let oldest_day = unix_day(oldest_at).min(newest_day); let (newest_day, oldest_day) = clamp_days(newest_day, oldest_day, unix_day(chrono::Utc::now().timestamp())); - Ok((carriers >= 2).then_some((newest_day, oldest_day, carriers))) + // a time clamped out of its day starts the day it was clamped to + let oldest_at = oldest_at.clamp(oldest_day * 86_400, (oldest_day + 1) * 86_400 - 1); + Ok((carriers >= 2).then_some(Split { newest_day, oldest_day, oldest_at, carriers })) } /// 2000-01-01: binary retention doesnt reach further back than this @@ -836,8 +853,8 @@ async fn goes_back_furthest(ctx: &PassContext, db: &Db, group: &str, server: usi deepest = (t, ctx.pool.host(other)); } } - let (g, d) = (group.to_string(), deepest.1.clone()); - on_db(db, move |conn| Ok(crate::chunks::set_deepest(conn, &g, &d)?)).await?; + let (g, (since, d)) = (group.to_string(), deepest.clone()); + on_db(db, move |conn| Ok(crate::chunks::set_deepest(conn, &g, &d, since)?)).await?; println!("[CHUNK] {group}: {} goes back furthest, it does the oldest day", deepest.1); Ok(deepest.1 == host) } diff --git a/tests/date_search.rs b/tests/date_search.rs index 14b81604..84a66dbf 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -639,7 +639,7 @@ fn a_split_reaches_back_when_a_deeper_server_joins() { atlas::chunks::add(&conn, GROUP, day0 + 9, day0 + 5).unwrap(); conn.execute("update backfill_chunks set state = 2, server = '127.0.0.1', done_at = 1 where day = ?", [day0 + 5]) .unwrap(); - atlas::chunks::set_deepest(&conn, GROUP, "127.0.0.1").unwrap(); + atlas::chunks::set_deepest(&conn, GROUP, "127.0.0.1", start.timestamp() + 121 * 3600).unwrap(); let ctx = atlas::indexer::PassContext { pool: pool.pool.clone(), From 55770fdeaec10e94e1e89c34739c073f9417157f Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:08:30 -0500 Subject: [PATCH 069/159] Files with more than 50,000 segment rows never seal into a blob A poster can put any number of rows under one file, and sealing (and compaction's copy) built the whole file in memory. Past SEAL_MAX_SEGMENTS the file stays rows: the walk skips it, seal_file refuses before reading rows, a blob won't take late rows past the cap, and compaction streams such a file's rows instead of merging them. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 71 ++++++++++++++++++++++++++++++-- src/store.rs | 108 ++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 165 insertions(+), 14 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index de2cb3f2..45cf67c7 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -450,8 +450,12 @@ fn compact_shard( pending = next_row(shard, &mut rows, &shared)?; } let (Some(f), Some(id)) = (file, id) else { break }; + // at most one past the most a blob takes; the rest of a bigger file + // is streamed below, never held let mut file_rows = Vec::new(); - while let Some(row) = pending.take_if(|r| r.file_id == id) { + while file_rows.len() as i64 <= store::SEAL_MAX_SEGMENTS + && let Some(row) = pending.take_if(|r| r.file_id == id) + { file_rows.push(row); pending = next_row(shard, &mut rows, &shared)?; } @@ -472,8 +476,12 @@ fn compact_shard( // rows a blob cant hold exactly (a negative part, no size) stay rows let fits = file_rows.iter().all(|r| r.part.is_none_or(|p| p >= 0) && r.bytes.is_some()); let seen: Vec = f.get(8)?; - let seal = - !file_rows.is_empty() && fits && store::due(f.get(6)?, &seen, f.get(9)?, old_blob.is_some(), now); + // and files with more segments than a blob takes stay rows + let small = (segs.len() + file_rows.len()) as i64 <= store::SEAL_MAX_SEGMENTS; + let seal = !file_rows.is_empty() + && fits + && small + && store::due(f.get(6)?, &seen, f.get(9)?, old_blob.is_some(), now); if seal { segs.extend(file_rows.drain(..).map(|r| Seg { part: r.part, @@ -494,6 +502,20 @@ fn compact_shard( } copied += (segs.len() + file_rows.len()) as i64; in_tx += 1 + segs.len() + file_rows.len(); + // the rest of a file too big to buffer, a row at a time + while let Some(row) = pending.take_if(|r| r.file_id == id) { + insert_row(&tx, &row)?; + (copied, in_tx) = (copied + 1, in_tx + 1); + if (copied as usize).is_multiple_of(STOP_EVERY) { + halt(stop, shard)?; + } + if in_tx >= BATCH { + tx.commit()?; + tx = conn.transaction()?; + in_tx = 0; + } + pending = next_row(shard, &mut rows, &shared)?; + } if in_tx >= BATCH { tx.commit()?; tx = conn.transaction()?; @@ -1025,6 +1047,49 @@ mod tests { assert_eq!(blob_segs_with_known_domains(&main).len() as i64, count); } + #[test] + fn a_file_over_the_cap_is_copied_as_rows_and_its_nzb_is_the_same() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + // a complete file (so due) whose rows a poster padded past what a blob takes + let (path, big) = file_of(&main, "Rel.1", "alt.binaries.g1"); + let conn = db::open_at(&path).unwrap(); + let before_rows: i64 = + conn.query_row("select count(*) from segments where file_id = ?", [big], |r| r.get(0)).unwrap(); + let extra = store::SEAL_MAX_SEGMENTS + 1 - before_rows; + conn.execute( + "with recursive n(i) as (select 1 union all select i + 1 from n where i < ?2) + insert into segments (file_id, local, domain, part, bytes) + select ?1, cast('big' || i as blob), 0, 100 + i, 1 from n", + params![big, extra], + ) + .unwrap(); + drop(conn); + let before = all_articles(&main); + let count = article_total(&main); + + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(all_articles(&main), before, "every NZB reads back the same"); + assert_eq!(article_total(&main), count); + assert_eq!(loose(&main), store::SEAL_MAX_SEGMENTS + 1, "only the big file stays rows"); + let conn = db::open_at(&path).unwrap(); + let (rows, blob): (i64, Option>) = conn + .query_row( + "select (select count(*) from segments where file_id = f.id), f.blob from files f where id = ?", + [big], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .unwrap(); + assert_eq!((rows, blob), (store::SEAL_MAX_SEGMENTS + 1, None)); + + // and without the extra row it seals again + conn.execute("delete from segments where file_id = ? and local = cast('big1' as blob)", [big]).unwrap(); + drop(conn); + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(loose(&main), 0, "at the cap a file seals"); + } + #[test] fn a_corrupt_blob_stops_compacting_and_keeps_the_original() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/store.rs b/src/store.rs index b4e059aa..e88343ab 100644 --- a/src/store.rs +++ b/src/store.rs @@ -619,6 +619,20 @@ fn release_complete(conn: &Connection, release_id: i64, file_total: Option) /// files untouched this long get sealed even when incomplete pub const SEAL_AGE: i64 = 3 * 86_400; +/// A file with more segments than this never seals: a blob is built in +/// memory, and a poster can put any number of rows under one file. Real files +/// have a few thousand parts at most. +pub const SEAL_MAX_SEGMENTS: i64 = 50_000; + +/// sql: file `f` has more than SEAL_MAX_SEGMENTS rows, counting no further +/// than one past +fn too_many_rows() -> String { + format!( + "(select count(*) from (select 1 from segments s where s.file_id = f.id limit {}) ) > {SEAL_MAX_SEGMENTS}", + SEAL_MAX_SEGMENTS + 1 + ) +} + fn blob_error(e: std::io::Error) -> rusqlite::Error { rusqlite::Error::ToSqlConversionFailure(Box::new(e)) } @@ -647,6 +661,14 @@ pub(crate) fn seal_file(conn: &Connection, file_id: i64) -> Result { fn seal_rows(conn: &Connection, file_id: i64) -> Result { let mut segs = sealed_segments(conn, file_id)?.unwrap_or_default(); + // too much for one blob in memory: stays rows, and a blob stays as it is + // (counted before any row is read) + let counted: i64 = conn + .prepare_cached("select count(*) from (select 1 from segments where file_id = ? limit ?)")? + .query_row(params![file_id, SEAL_MAX_SEGMENTS + 1], |r| r.get(0))?; + if counted > 0 && counted + segs.len() as i64 > SEAL_MAX_SEGMENTS { + return Ok(0); + } let rows: Vec = conn .prepare_cached("select part, bytes, domain, local from segments where file_id = ?")? .query_map([file_id], |r| { @@ -676,24 +698,26 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { /// seals: ones with rows that are complete and not sealed yet, or untouched /// for `SEAL_AGE` (a sealed file with late rows waits for this). Files never /// touched since the upgrade are left to compaction, and files with a -/// negative part number never seal. Returns the ids and the last id looked +/// negative part number, or more than `SEAL_MAX_SEGMENTS` rows, never seal. +/// Returns the ids and the last id looked /// at, for walking the table `limit` files at a time: `last == after_id` /// means the end. pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) -> Result<(Vec, i64)> { - let mut stmt = conn.prepare_cached( + let mut stmt = conn.prepare_cached(&format!( "select f.id, f.expected, f.seen, f.touched_at, f.blob is not null, exists (select 1 from segments s where s.file_id = f.id), - exists (select 1 from segments s where s.file_id = f.id and s.part < 0) + exists (select 1 from segments s where s.file_id = f.id and s.part < 0) or {} from files f where f.id > ? order by f.id limit ?", - )?; + too_many_rows() + ))?; let mut ids = Vec::new(); let mut last = after_id; let mut rows = stmt.query(params![after_id, limit as i64])?; while let Some(r) = rows.next()? { let id: i64 = r.get(0)?; last = id; - let (has_rows, negative): (bool, bool) = (r.get(5)?, r.get(6)?); - if !has_rows || negative { + let (has_rows, never): (bool, bool) = (r.get(5)?, r.get(6)?); + if !has_rows || never { continue; } let seen: Vec = r.get(2)?; @@ -708,16 +732,17 @@ pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) /// A file a save just completed is still complete, not sealed and has rows /// that can go in a blob. fn still_due(conn: &Connection, file_id: i64, now: i64) -> Result { - conn.prepare_cached( + conn.prepare_cached(&format!( "select f.expected, f.seen, f.touched_at, f.blob is not null, exists (select 1 from segments s where s.file_id = f.id), - exists (select 1 from segments s where s.file_id = f.id and s.part < 0) + exists (select 1 from segments s where s.file_id = f.id and s.part < 0) or {} from files f where f.id = ?", - )? + too_many_rows() + ))? .query_row([file_id], |r| { - let (has_rows, negative): (bool, bool) = (r.get(4)?, r.get(5)?); + let (has_rows, never): (bool, bool) = (r.get(4)?, r.get(5)?); let (seen, touched): (Vec, Option) = (r.get(1)?, r.get(2)?); - Ok(has_rows && !negative && touched.is_some() && due(r.get(0)?, &seen, touched, r.get(3)?, now)) + Ok(has_rows && !never && touched.is_some() && due(r.get(0)?, &seen, touched, r.get(3)?, now)) }) .optional() .map(|due| due.unwrap_or(false)) @@ -1577,6 +1602,67 @@ mod tests { assert_eq!(seal_file(&conn, ids[1]).unwrap(), 0); } + /// `n` more rows under a file, as a poster could add them + fn add_rows(conn: &Connection, file_id: i64, n: i64) { + conn.execute( + "with recursive n(i) as (select 1 union all select i + 1 from n where i < ?2) + insert into segments (file_id, local, domain, part, bytes) + select ?1, cast('big' || i as blob), 0, 100 + i, 1 from n", + params![file_id, n], + ) + .unwrap(); + } + + #[test] + fn a_file_with_more_than_the_cap_of_rows_never_seals() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let now: i64 = conn.query_row("select unixepoch()", [], |r| r.get(0)).unwrap(); + let id = |name: &str| -> i64 { + conn.query_row("select id from files where filename = ?", [name], |r| r.get(0)).unwrap() + }; + let rows = |id: i64| -> i64 { + conn.query_row("select count(*) from segments where file_id = ?", [id], |r| r.get(0)).unwrap() + }; + let (a, b) = (id("a.rar"), id("b.rar")); + // b.rar is stale (a.rar is complete): both are due, a.rar with the cap + 1 rows is not + conn.execute("update files set touched_at = ?", [now - SEAL_AGE - 1]).unwrap(); + assert_eq!(sealable(&conn, 0, 100, now).unwrap().0, vec![a, b]); + add_rows(&conn, a, SEAL_MAX_SEGMENTS + 1 - rows(a)); + assert_eq!(rows(a), SEAL_MAX_SEGMENTS + 1); + assert_eq!(sealable(&conn, 0, 100, now).unwrap().0, vec![b], "the big one is skipped"); + assert!(!still_due(&conn, a, now).unwrap()); + assert!(still_due(&conn, b, now).unwrap()); + + assert_eq!(seal_file(&conn, a).unwrap(), 0); + assert_eq!(rows(a), SEAL_MAX_SEGMENTS + 1, "still rows"); + let blob: Option> = conn.query_row("select blob from files where id = ?", [a], |r| r.get(0)).unwrap(); + assert_eq!(blob, None); + + // exactly the cap seals + conn.execute("delete from segments where file_id = ? and local = cast('big1' as blob)", [a]).unwrap(); + assert_eq!(rows(a), SEAL_MAX_SEGMENTS); + assert_eq!(sealable(&conn, 0, 100, now).unwrap().0, vec![a, b]); + assert_eq!(seal_file(&conn, a).unwrap() as i64, SEAL_MAX_SEGMENTS); + } + + #[test] + fn late_rows_that_would_take_a_blob_past_the_cap_stay_rows() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let now: i64 = conn.query_row("select unixepoch()", [], |r| r.get(0)).unwrap(); + let b: i64 = conn.query_row("select id from files where filename = 'b.rar'", [], |r| r.get(0)).unwrap(); + assert_eq!(seal_file(&conn, b).unwrap(), 1); + add_rows(&conn, b, SEAL_MAX_SEGMENTS); + conn.execute("update files set touched_at = ?", [now - SEAL_AGE - 1]).unwrap(); + + assert_eq!(seal_file(&conn, b).unwrap(), 0); + let rows: i64 = conn.query_row("select count(*) from segments where file_id = ?", [b], |r| r.get(0)).unwrap(); + assert_eq!(rows, SEAL_MAX_SEGMENTS, "the late rows were left"); + let blob: Vec = conn.query_row("select blob from files where id = ?", [b], |r| r.get(0)).unwrap(); + assert_eq!(crate::blob::decode(&blob).unwrap().len(), 1, "and the blob is as it was"); + } + #[test] fn articles_reads_inside_a_callers_transaction() { let (_dir, main) = sealed_fixture(); From c1f8cd0dda600dfab20302536019531342015ae4 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:09:07 -0500 Subject: [PATCH 070/159] A claimed oldest day is reset when a server reaches further into it reach_back only redid a done oldest day. A deeper carrier appearing while the former deepest one was still on that chunk left it claimed, and the worker's later finish marked the partial day done with the deepest row already forgotten. The claim is cleared now too, so that finish is a no-op. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/chunks.rs b/src/chunks.rs index 431c6dd5..cf91a08f 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -74,6 +74,7 @@ pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> /// before the split's oldest one back to `oldest_day`. The old oldest day /// was done (if it was) only from where the server going back furthest then /// started: it is to do again, and that server is forgotten (see `deepest`). +/// A claim on it is cleared too, so its worker's finish does nothing. /// Also when `oldest_day` is the oldest day but `oldest_at` is before where /// that server started in it. Returns the chunks added or to do again. pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i64) -> Result { @@ -102,7 +103,7 @@ pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i6 let redo = tx.execute( &format!( "update backfill_chunks set state = {PENDING}, server = null, claimed_at = null, done_at = null - where grp = ? and day = ? and state = {DONE}" + where grp = ? and day = ? and state in ({DONE}, {CLAIMED})" ), params![group, old], )?; @@ -287,6 +288,37 @@ mod tests { assert_eq!(reach_back(&c, "g", 9, 9 * 86_400).unwrap(), 2, "day 9 added, day 10 to do again"); } + #[test] + fn a_claimed_oldest_day_is_reset_when_retention_reaches_further_into_it() { + let c = conn(); + add(&c, "g", 12, 10).unwrap(); + let groups = vec![("g".to_string(), i64::MIN)]; + // a takes day 12, then day 11, then day 10 (the split's oldest), as the deepest + for _ in 0..2 { + claim(&c, &groups, "a", 1000).unwrap().unwrap(); + } + let a = claim(&c, &groups, "a", 1000).unwrap().unwrap(); + assert_eq!(a.day, 10); + set_deepest(&c, "g", "a", 10 * 86_400 + 18 * 3600).unwrap(); + + // b goes back further into day 10 while a is still on it + assert_eq!(reach_back(&c, "g", 10, 10 * 86_400 + 3600).unwrap(), 1); + assert_eq!(deepest(&c, "g").unwrap(), None); + let row: (i64, Option, Option) = c + .query_row("select state, server, claimed_at from backfill_chunks where day = 10", [], |r| { + Ok((r.get(0)?, r.get(1)?, r.get(2)?)) + }) + .unwrap(); + assert_eq!(row, (PENDING, None, None), "pending again, a's claim gone"); + + // a's late finish and release do nothing + assert!(!finish(&c, &a, 2000).unwrap()); + assert!(!release(&c, &a).unwrap()); + assert_eq!(progress(&c, "g").unwrap(), (0, 3)); + // and the next to claim it is not a stale claim's + assert_eq!(day(claim(&c, &groups, "b", 1001)), Some(10)); + } + #[test] fn stale_claims_are_taken_over() { let c = conn(); From 2ac9286792b4356d916ec34cd9b602b70abad2ad Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:09:43 -0500 Subject: [PATCH 071/159] The Backfill page follows a split group's chunks, not its frozen cursor A split group's normal backfill cursor stops moving, so the gauge, the remaining count, the finished groups and the ETA stayed put for it. Chunk progress is now loaded per group and stands in for the cursor's as that share of the group's article numbers. Co-Authored-By: Claude Opus 5.5 --- src/stats_dashboard.rs | 58 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/src/stats_dashboard.rs b/src/stats_dashboard.rs index bc9bc7c9..4de718a2 100644 --- a/src/stats_dashboard.rs +++ b/src/stats_dashboard.rs @@ -85,6 +85,18 @@ struct Quick { wal_bytes: u64, /// split group stats: (groups, splitting, done, total, done_last_hour) chunks: (i64, i64, i64, i64, i64), + /// split group -> (chunks done, chunks): their cursors stand still, the chunks move + group_chunks: BTreeMap, +} + +fn load_group_chunks(conn: &rusqlite::Connection) -> BTreeMap { + let Ok(mut stmt) = + conn.prepare("select grp, coalesce(sum(state = 2), 0), count(*) from backfill_chunks group by grp") + else { + return BTreeMap::new(); + }; + let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, (r.get::<_, i64>(1)?, r.get::<_, i64>(2)?)))); + rows.map(|rows| rows.flatten().collect()).unwrap_or_default() } fn load_chunks_stats(conn: &rusqlite::Connection) -> (i64, i64, i64, i64, i64) { @@ -115,6 +127,7 @@ fn load_quick() -> Quick { // running totals the shards keep, instant (q.releases_approx, q.articles_approx) = crate::store::totals(&conn).unwrap_or_default(); q.chunks = load_chunks_stats(&conn); + q.group_chunks = load_group_chunks(&conn); q } @@ -725,6 +738,14 @@ fn backfill_at(quick: &Quick, now: i64) -> Backfill { } b.unmeasured = seen.iter().filter(|g| !best.contains_key(*g)).count(); + // a split group's cursors stand still: its day chunks say how far it is, + // as that share of its article numbers + for (group, (total, covered, _)) in best.iter_mut() { + if let Some(&(done, chunks)) = quick.group_chunks.get(group).filter(|c| c.1 > 0) { + *covered = (*total as i128 * done.clamp(0, chunks) as i128 / chunks as i128) as i64; + } + } + let mut rows: Vec<(String, i64, f64)> = Vec::new(); let (mut rate_dated, mut total_dated, mut reached) = (0.0, 0i64, Vec::new()); for (group, (total, covered, row)) in best { @@ -1298,6 +1319,43 @@ mod tests { assert_eq!(b.reached, Some(base + 10 * day)); } + #[test] + fn split_groups_progress_follows_their_chunks_not_their_cursors() { + let row = |key: &str| db::GroupProgress { + key: key.into(), + live_cursor: 1000, + backfill_cursor: 1000, // the cursor stands still on a split group + first: Some(1), + last: Some(1000), + ..Default::default() + }; + let mut quick = Quick { + progress: vec![row("alt.binaries.s"), row("alt.binaries.t"), row("alt.binaries.u")], + ..Quick::default() + }; + let b = backfill_at(&quick, 1_780_000_000); + assert_eq!((b.total, b.covered, b.remaining, b.done), (3000, 0, 3000, 0), "no chunks: the cursors"); + + // s: 1 of 4 days done, t: all 6, u is not split + quick.group_chunks = BTreeMap::from([("alt.binaries.s".into(), (1, 4)), ("alt.binaries.t".into(), (6, 6))]); + let b = backfill_at(&quick, 1_780_000_000); + assert_eq!((b.total, b.covered, b.remaining, b.done), (3000, 1250, 1750, 1)); + assert_eq!(b.behind[0], ("alt.binaries.u".into(), 1000, 0.0)); + assert!(b.behind.contains(&("alt.binaries.s".into(), 750, 25.0))); + } + + #[test] + fn group_chunks_are_loaded_per_group() { + let conn = rusqlite::Connection::open_in_memory().unwrap(); + assert!(load_group_chunks(&conn).is_empty(), "no table: nothing"); + crate::chunks::create(&conn).unwrap(); + crate::chunks::add(&conn, "g1", 100, 98).unwrap(); + crate::chunks::add(&conn, "g2", 200, 199).unwrap(); + let claim = crate::chunks::claim(&conn, &[("g2".to_string(), i64::MIN)], "s", 1000).unwrap().unwrap(); + assert!(crate::chunks::finish(&conn, &claim, 1100).unwrap()); + assert_eq!(load_group_chunks(&conn), BTreeMap::from([("g1".into(), (0, 3)), ("g2".into(), (1, 2))])); + } + #[test] fn implausible_dates_give_no_rate() { let (day, now) = (86_400, 1_780_000_000); From 919a0be7309a9bb74e19dd699204866ac1140104 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:15:32 -0500 Subject: [PATCH 072/159] What a server keeps of a group is remembered by its host, not its pool index A config reload rebuilds the pool while RunStates lives on, so a cached oldest day under index 0 could end up restricting whichever server then sits at index 0. keeps_from and kept_days are keyed by host. Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 2 +- src/indexer.rs | 41 ++++++++++++++++++++++++++++------------- tests/date_search.rs | 2 +- 3 files changed, 30 insertions(+), 15 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 54496020..1299f504 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -481,7 +481,7 @@ async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option chunk, Err(e) => { diff --git a/src/indexer.rs b/src/indexer.rs index 14e705eb..a0e9f714 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -48,9 +48,10 @@ pub struct GroupRunState { pub no_split_until: Option, /// a split group's servers are looked at for older days again then pub reach_back_after: Option, - /// per server, the oldest day it keeps of the group (as found by a day - /// chunk too old for it), until it's looked at again - pub keeps_from: HashMap, + /// per server host (not its place in the pool, which a config reload can + /// give to another), the oldest day it keeps of the group (as found by a + /// day chunk too old for it), until it's looked at again + pub keeps_from: HashMap, } impl Default for GroupRunState { @@ -88,23 +89,26 @@ impl RunStates { groups.iter().all(|g| states.get(g).is_some_and(|s| s.idle)) } - /// The oldest day `server` keeps of `group`, `i64::MIN` when not known. - pub fn keeps_from(&self, group: &str, server: usize) -> i64 { + /// The oldest day the server `host` keeps of `group`, `i64::MIN` when not known. + pub fn keeps_from(&self, group: &str, host: &str) -> i64 { let now = Instant::now(); let states = self.0.lock().unwrap(); - let found = states.get(group).and_then(|s| s.keeps_from.get(&server)); + let found = states.get(group).and_then(|s| s.keeps_from.get(host)); found.filter(|(_, until)| *until > now).map_or(i64::MIN, |(day, _)| *day) } - /// The groups whose oldest day on `server` is known, with that day. - pub fn kept_days(&self, server: usize) -> HashMap { + /// Note `day` as the oldest the server `host` keeps of `group`, until it's looked at again. + fn keep_from(&self, group: &str, host: &str, day: i64) { + self.with(group, |st| st.keeps_from.insert(host.to_string(), (day, Instant::now() + KEEPS_RECHECK))); + } + + /// The groups whose oldest day on the server `host` is known, with that day. + pub fn kept_days(&self, host: &str) -> HashMap { let now = Instant::now(); let states = self.0.lock().unwrap(); states .iter() - .filter_map(|(g, s)| { - s.keeps_from.get(&server).filter(|(_, until)| *until > now).map(|(d, _)| (g.clone(), *d)) - }) + .filter_map(|(g, s)| s.keeps_from.get(host).filter(|(_, until)| *until > now).map(|(d, _)| (g.clone(), *d))) .collect() } @@ -419,7 +423,7 @@ where { // a split group's backfill is day chunks, this server takes the next one let host = ctx.pool.host(server); - let wanted = [(group.to_string(), ctx.states.keeps_from(group, server))]; + let wanted = [(group.to_string(), ctx.states.keeps_from(group, &host))]; let claimed = on_db(db, move |conn| Ok(crate::chunks::claim(conn, &wanted, &host, chrono::Utc::now().timestamp())?)) .await?; @@ -792,8 +796,8 @@ where if !keeps_day { // the first day it keeps whole let oldest_day = oldest.map_or(i64::MAX, |t| crate::chunks::unix_day(t - 1) + 1); - ctx.states.with(group, |st| st.keeps_from.insert(server, (oldest_day, Instant::now() + KEEPS_RECHECK))); let host = ctx.pool.host(server); + ctx.states.keep_from(group, &host, oldest_day); println!("[CHUNK] {group} day {day} is older than {host} keeps, leaving it to the other servers"); return failed(TooOld { group: group.to_string(), host, oldest_day }.into()).await; } @@ -1225,6 +1229,17 @@ impl Indexer { mod tests { use super::*; + #[test] + fn what_a_server_keeps_is_remembered_by_its_host_not_its_place_in_the_pool() { + let states = RunStates::default(); + // index 0 was a.example when this was learned; a config reload put b.example there + states.keep_from("alt.binaries.g", "a.example", 20_000); + assert_eq!(states.keeps_from("alt.binaries.g", "a.example"), 20_000); + assert_eq!(states.kept_days("a.example"), HashMap::from([("alt.binaries.g".to_string(), 20_000)])); + assert_eq!(states.keeps_from("alt.binaries.g", "b.example"), i64::MIN, "b is not restricted"); + assert!(states.kept_days("b.example").is_empty()); + } + #[test] fn slices_cover_the_range() { assert_eq!(make_slices(1, 10, 4, false), vec![(1, 4), (5, 8), (9, 10)]); diff --git a/tests/date_search.rs b/tests/date_search.rs index 84a66dbf..1de1574d 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -421,7 +421,7 @@ fn a_day_older_than_the_server_keeps_is_given_back() { let err = run(first_day - 1).unwrap_err(); let too_old = err.downcast_ref::().expect("a TooOld"); assert_eq!(too_old.oldest_day, first_day); - assert_eq!(ctx.states.keeps_from(GROUP, 0), first_day, "remembered for the next claims"); + assert_eq!(ctx.states.keeps_from(GROUP, &pool.pool.host(0)), first_day, "remembered for the next claims"); let empty = run(first_day + 1).unwrap(); assert_eq!(empty.articles, 2, "only the overlap hours"); let conn = atlas::db::open_at(&main).unwrap(); From 9f305b64a9efdc67457016e30a49f1b7de3f026b Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:34:26 -0500 Subject: [PATCH 073/159] A split reaches back from its newest chunk, not its frozen cursor Reach-back looked up the post date at the home backfill cursor, which stays where the split was made. Once home's retention moved past it the lookup came back empty and every hourly reach-back stopped before probing the carriers, so a deeper provider's older days never got chunks. An existing split now takes its newest day from its newest chunk. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 5 ++++ src/indexer.rs | 48 +++++++++++++++++++-------------------- tests/date_search.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 24 deletions(-) diff --git a/src/chunks.rs b/src/chunks.rs index cf91a08f..823e0dc0 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -193,6 +193,11 @@ pub fn oldest_day(conn: &Connection, group: &str) -> Result> { conn.query_row("select min(day) from backfill_chunks where grp = ?", [group], |r| r.get(0)) } +/// the newest day of a group's chunks +pub fn newest_day(conn: &Connection, group: &str) -> Result> { + conn.query_row("select max(day) from backfill_chunks where grp = ?", [group], |r| r.get(0)) +} + /// The server whose first article of a split group is the oldest: the one /// to index the split's oldest day, which no server keeps whole. pub fn deepest(conn: &Connection, group: &str) -> Result> { diff --git a/src/indexer.rs b/src/indexer.rs index a0e9f714..6b130520 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -494,7 +494,7 @@ async fn maybe_split( } due }); - if due && let Err(e) = reach_back(ctx, db, group, home, (first, last), cursor).await { + if due && let Err(e) = reach_back(ctx, db, group, home, (first, last)).await { println!("[SPLIT] {group}: couldnt look for servers going back further: {e:#}"); } return Ok(true); @@ -506,9 +506,12 @@ async fn maybe_split( return Ok(false); } - let Some(Split { newest_day, oldest_day, carriers, .. }) = - split_days(ctx, group, home, (first, last), cursor).await? - else { + // the newest day still to do is the post date at the home cursor + let split = match ctx.pool.posted_date(home, group, cursor).await? { + Some(t) => split_days(ctx, group, home, (first, last), crate::chunks::unix_day(t)).await?, + None => None, + }; + let Some(Split { newest_day, oldest_day, carriers, .. }) = split else { ctx.states.with(group, |st| st.no_split_until = Some(Instant::now() + SPLIT_RECHECK)); return Ok(false); }; @@ -521,16 +524,15 @@ async fn maybe_split( } /// Days older than split `group`'s oldest that a carrier keeps now: chunks -/// for them, see `chunks::reach_back`. -async fn reach_back( - ctx: &PassContext, - db: &Db, - group: &str, - home: usize, - bounds: (u64, u64), - cursor: u64, -) -> Result<()> { - let Some(Split { oldest_day, oldest_at, .. }) = split_days(ctx, group, home, bounds, cursor).await? else { +/// for them, see `chunks::reach_back`. The split's newest day is its newest +/// chunk's, not the date at the home cursor: the cursor stays where the +/// split was made, and home's retention moves past it. +async fn reach_back(ctx: &PassContext, db: &Db, group: &str, home: usize, bounds: (u64, u64)) -> Result<()> { + let g = group.to_string(); + let Some(newest_day) = on_db(db, move |conn| Ok(crate::chunks::newest_day(conn, &g)?)).await? else { + return Ok(()); + }; + let Some(Split { oldest_day, oldest_at, .. }) = split_days(ctx, group, home, bounds, newest_day).await? else { return Ok(()); }; let g = group.to_string(); @@ -551,25 +553,23 @@ struct Split { carriers: usize, } -/// The days a split of `group` covers and how many servers carry it. None -/// when it cant split: home's dates at either end are unknown or no other -/// indexing server carries the group. `first` and `last` are home's low and -/// high marks. +/// The days a split of `group` from `newest_day` covers and how many +/// servers carry it. None when it cant split: home's first date is unknown +/// or no other indexing server carries the group. `first` and `last` are +/// home's low and high marks. async fn split_days( ctx: &PassContext, group: &str, home: usize, (first, last): (u64, u64), - cursor: u64, + newest_day: i64, ) -> Result> { use crate::chunks::unix_day; - // the newest day still to do is the post date at the home cursor, the - // oldest at least home's first article. first articles are searched for - // from the low marks, which can lag far behind what a server still keeps - let Some(newest) = ctx.pool.posted_date(home, group, cursor).await? else { return Ok(None) }; + // the oldest day is at least home's first article. first articles are + // searched for from the low marks, which can lag far behind what a + // server still keeps let Some(oldest) = ctx.pool.first_post(home, group, first, last).await? else { return Ok(None) }; - let newest_day = unix_day(newest); let mut oldest_at = oldest; // other servers are best effort: one that fails is left out. one that diff --git a/tests/date_search.rs b/tests/date_search.rs index 1de1574d..4cceaf66 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -682,6 +682,60 @@ fn a_split_reaches_back_when_a_deeper_server_joins() { } } +/// A split whose home cursor stayed where the split was made, and home's +/// retention has since moved past it (nothing is left at the cursor): a +/// deeper server joining still gets the older days chunks. +#[test] +fn a_split_reaches_back_when_home_no_longer_keeps_its_cursor() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour for 10 days from 2026-01-01, from `from_hour` on + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = |from_hour: u64, offset: u64| -> Vec { + (from_hour..240) + .map(|h| { + let when = start + chrono::Duration::hours(h as i64); + post_at(offset + h, &format!(r#""p{h}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() + }; + // home keeps 1122.. now, its backfill cursor stayed at 5 + let short = spawn_server(Server::new(posts(121, 1001))); + let mut deep = mock(spawn_server(Server::new(posts(0, 10_001))), "secret", 2, 2); + deep.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(short, "secret", 2, 1), deep]); + pool.connect().unwrap(); + + let day0 = atlas::chunks::unix_day(start.timestamp()); + let conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&conn, GROUP, day0 + 9, day0 + 5).unwrap(); + atlas::chunks::set_deepest(&conn, GROUP, "127.0.0.1", start.timestamp() + 121 * 3600).unwrap(); + let state = atlas::db::GroupState { live_cursor: 1240, backfill_cursor: 5 }; + atlas::db::save_group_state(&conn, &format!("{GROUP}@127.0.0.1"), state).unwrap(); + + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(atlas::db::open_at(&main).unwrap()); + let settings = atlas::indexer::PassSettings { + mode: "backfill".into(), + batch_size: 10, + request_size: 10, + split_min_backlog: 10, + }; + pool.block_on(atlas::indexer::run_pass(&ctx, &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); + + assert_eq!( + atlas::chunks::oldest_day(&conn, GROUP).unwrap(), + Some(day0), + "chunks back to the new server's first day" + ); +} + /// A split reaches back to the oldest day of every carrier, also one whose /// GROUP low mark sits 5,000 numbers before its first article (retention /// has moved on, the mark hasnt): its older days get chunks. From 2d3a23dcbce8165b6e58ee85e975af61d8f5f303 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:37:43 -0500 Subject: [PATCH 074/159] The deepest server is forgotten once it no longer keeps the oldest day A server noted as going back furthest whose retention moved past the split's oldest day gave the day back as too old, but the note stayed, so every other carrier was turned away from the day for good. A server that gives a day back as too old is now forgotten as the deepest, the same as one that drops the group. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 3 +- src/indexer.rs | 12 ++++++-- tests/date_search.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 3 deletions(-) diff --git a/src/chunks.rs b/src/chunks.rs index 823e0dc0..f0fbf263 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -215,7 +215,8 @@ pub fn set_deepest(conn: &Connection, group: &str, server: &str, oldest_at: i64) } /// Forget `server` as the one going back furthest on `group`, when it no -/// longer carries it: the next to reach the oldest day asks again. +/// longer carries it or no longer keeps the oldest day: the next to reach +/// the oldest day asks again. pub fn forget_deepest(conn: &Connection, group: &str, server: &str) -> Result<()> { conn.execute("delete from backfill_deepest where grp = ? and server = ?", [group, server])?; Ok(()) diff --git a/src/indexer.rs b/src/indexer.rs index 6b130520..d68665b8 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -799,6 +799,13 @@ where let host = ctx.pool.host(server); ctx.states.keep_from(group, &host, oldest_day); println!("[CHUNK] {group} day {day} is older than {host} keeps, leaving it to the other servers"); + // a server that doesnt keep this day keeps none of the split's oldest + // either: if it was noted as going back furthest, its retention moved + // on, and the oldest day goes to the next one + let (g, h) = (group.to_string(), host.clone()); + if let Err(e) = on_db(db, move |conn| Ok(crate::chunks::forget_deepest(conn, &g, &h)?)).await { + println!("[CHUNK] {group}: couldnt forget the server going back furthest: {e:#}"); + } return failed(TooOld { group: group.to_string(), host, oldest_day }.into()).await; } let start = match ctx.pool.article_at(server, group, first, last, from).await { @@ -832,8 +839,9 @@ where /// `oldest`, goes back furthest of the indexing servers: the one to index the /// split's oldest day. Found by asking each server for its first article the /// first time, then kept, soo it doesnt move as retention rolls on (asked -/// again once that server is no longer an indexing one, or no longer -/// carries the group: `index_chunk` forgets it on a 411). A server that +/// again once that server is no longer an indexing one, no longer carries +/// the group, or no longer keeps the day: `index_chunk` forgets it on a 411 +/// or a day older than it keeps). A server that /// cant be asked fails it: the chunk goes back and is tried again later. async fn goes_back_furthest(ctx: &PassContext, db: &Db, group: &str, server: usize, oldest: i64) -> Result { let host = ctx.pool.host(server); diff --git a/tests/date_search.rs b/tests/date_search.rs index 4cceaf66..447146af 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -608,6 +608,74 @@ fn the_oldest_day_moves_on_when_the_deepest_server_drops_the_group() { assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("localhost")); } +/// The server noted as going back furthest still carries the group, but its +/// retention moved past the oldest day: it gives the day back, the note goes, +/// and the next deepest carrier does the oldest day instead of being turned +/// away by the stale note for good. +#[test] +fn the_oldest_day_moves_on_when_the_deepest_server_no_longer_keeps_it() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour for 3 days from 2026-01-01, from `from_hour` on + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = |from_hour: u64, offset: u64| -> Vec { + (from_hour..72) + .map(|h| { + let when = start + chrono::Duration::hours(h as i64); + post_at(offset + h, &format!(r#""p{h}.bin" yEnc (1/1)"#), &when.to_rfc2822()) + }) + .collect() + }; + // "127.0.0.1" keeps the first day from 01:00, "localhost" from 18:00 + let deep_server = Server::new(posts(1, 1)); + let deep = spawn_server(deep_server.clone()); + let shallow = spawn_server(Server::new(posts(18, 1001))); + let mut later = mock(shallow, "secret", 2, 1); + later.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(deep, "secret", 2, 1), later]); + pool.connect().unwrap(); + + let day = atlas::chunks::unix_day(start.timestamp()); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day + 2, day).unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let conn = atlas::db::open_at(&main).unwrap(); + let run = |server: usize| { + let chunk = atlas::chunks::Claim { group: GROUP.into(), day, server: pool.pool.host(server), claimed_at: 1 }; + conn.execute( + "update backfill_chunks set state = 1, server = ?, claimed_at = 1 where grp = ? and day = ?", + rusqlite::params![chunk.server, GROUP, day], + ) + .unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, server, &mut |_| {})) + }; + let state = + || -> i64 { conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() }; + + // the 01:00 server is noted as the deepest + assert!(run(1).unwrap_err().downcast_ref::().is_some()); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("127.0.0.1")); + + // then keeps only from the next day on, and finds out on its next chunk + deep_server.posts.lock().unwrap().retain(|p| p.number > 25); + assert!(run(0).unwrap_err().downcast_ref::().is_some()); + assert_eq!(state(), 0); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap(), None, "the stale note is forgotten"); + + // the 18:00 one goes back furthest now: 18:00 to midnight, plus the hour after + let saved = run(1).expect("the next deepest carrier does the oldest day"); + assert_eq!(saved.articles, 7); + assert_eq!(state(), 2); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("localhost")); +} + /// A split made while the servers kept 5 days, then a server that keeps 10 /// joins: the older days get chunks, the old oldest day (done only from /// where the deepest server then started) is pending again, and the new From 40587cd38e42f39012d679b643cbeb1c4f72f53b Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:41:01 -0500 Subject: [PATCH 075/159] A conversion has the database to itself for its whole run --convert only held off compaction (the shared lock), so two conversions, or one racing the indexer starting up, could both write the shards and atlas.new.db. It now takes the exclusive database lock for its whole run and is refused while anything else holds it. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/convert.rs | 16 ++++++++++++++++ src/main.rs | 15 ++++++--------- tests/convert.rs | 31 +++++++++++++++++++++++++++++++ 4 files changed, 54 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 050fb3f4..eac450ef 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,7 @@ The first time the new indexer starts on a database from an older version, it co 3. It checks a sample of releases: their NZBs, sizes, part counts, and completeness must come out the same as from the old database. 4. Only then does it swap the files. The old database stays as `atlas.old.db`; delete it once you're happy. -The menu shows the progress meanwhile, and searches don't work until the conversion finishes. On a 488 GB database it takes about 1.5 hours. If anything fails, Atlas leaves the old database as it was and tries again on the next start. To convert in the foreground instead, stop indexing and run `atlas --convert`. +The menu shows the progress meanwhile, and searches don't work until the conversion finishes. On a 488 GB database it takes about 1.5 hours. If anything fails, Atlas leaves the old database as it was and tries again on the next start. To convert in the foreground instead, stop indexing and run `atlas --convert`. It refuses to start while the indexer, a compaction or another `--convert` is using the database. Release IDs change in the conversion, so NZB links that Prowlarr or your apps saved before it no longer work. Search again to get the new ones. diff --git a/src/convert.rs b/src/convert.rs index 1ff119f7..89800c03 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -67,6 +67,22 @@ fn open_for_conversion(path: &Path) -> rusqlite::Result { Ok(conn) } +/// `--convert`: `run` under the exclusive database lock for its whole run, +/// refused while the indexer, a write, a compaction or another conversion +/// holds it (two at once would write the same shards and `atlas.new.db`). +/// None when there was nothing to convert. +pub fn run_alone(main: &Path, progress: &dyn Fn(&str)) -> Result> { + let _alone = crate::compact::Lock::take(main).map_err(|e| match e.downcast_ref::() { + Some(_) => anyhow!("the database is in use (indexing, a compaction or another conversion); try again later"), + None => e, + })?; + if !needed(main) { + return Ok(None); + } + crate::compact::refuse_unresolved_backups(main)?; + run(main, progress).map(Some) +} + /// Convert, reporting progress through `progress`. Returns how many releases /// and articles moved. pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { diff --git a/src/main.rs b/src/main.rs index aa5d8454..11123051 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,16 +45,13 @@ fn run_convert() -> i32 { println!("stop indexing first"); return 1; } - // the shards it makes arent compacted till they're filled - let _converting = match compact::hold_off_compaction(&main) { - Ok(held) => held, - Err(e) => { - println!("couldnt convert: {e:#}"); - return 1; + // alone: not alongside the indexer, a compaction or another conversion + match convert::run_alone(&main, &|msg| println!("{msg}")) { + Ok(Some(_)) => 0, + Ok(None) => { + println!("{} is already converted (or doesnt exist)", main.display()); + 0 } - }; - match convert::run(&main, &|msg| println!("{msg}")) { - Ok(_) => 0, Err(e) => { println!("couldnt convert, nothing was changed: {e:#}"); 1 diff --git a/tests/convert.rs b/tests/convert.rs index 04ce80ac..af5a4c79 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -251,3 +251,34 @@ fn a_conversion_stopped_during_the_check_picks_up_there() { assert_eq!(&nzb::render_nzb(&now, &store::articles(&conn, id).unwrap()), nzb_before, "{name}"); } } + +/// `--convert` has the database to itself for its whole run: refused while +/// the indexer (or a save) holds it, and a second conversion is refused +/// while one runs, each without touching anything. +#[test] +fn a_conversion_runs_alone() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + db::create_db_at(&main).unwrap(); + let new_main = dir.path().join("atlas.new.db"); + + let writing = atlas::compact::try_hold_off_compaction(&main).unwrap().unwrap(); + let err = convert::run_alone(&main, &|_| {}).expect_err("converted while the indexer held the database"); + assert!(format!("{err:#}").contains("in use"), "{err:#}"); + assert!(convert::needed(&main) && !new_main.exists(), "nothing was done"); + drop(writing); + + let second = std::cell::RefCell::new(None); + let converted = convert::run_alone(&main, &|_| { + if second.borrow().is_none() { + *second.borrow_mut() = Some(convert::run_alone(&main, &|_| {}).map(|_| ())); + } + }) + .unwrap(); + assert_eq!(converted.map(|(releases, _)| releases), Some(40)); + let err = second.into_inner().unwrap().expect_err("a second conversion ran alongside"); + assert!(format!("{err:#}").contains("in use"), "{err:#}"); + assert!(!convert::needed(&main), "the first one finished"); + assert_eq!(convert::run_alone(&main, &|_| {}).unwrap(), None, "nothing left to convert"); +} From cbbe800045af337dfbcacc7968db7f9e9cfc6553 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:44:01 -0500 Subject: [PATCH 076/159] The wipe removes the main database only after every shard The wipe removed atlas.db first. A shard that then couldnt be removed (still open on Windows) was left with no main database, and the next start made a fresh one over it, handing out its ids again. Shards and their leftovers now go first; a failure is an error and atlas.db stays. Co-Authored-By: Claude Opus 5.5 --- src/db.rs | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/src/db.rs b/src/db.rs index 450b3917..8ee10f57 100644 --- a/src/db.rs +++ b/src/db.rs @@ -141,19 +141,23 @@ pub fn create_db_holding(path: &Path) -> anyhow::Result> { Ok(Some(held)) } -/// Settings > wipe: the main database and every shard, with their sidecars -/// and what a compaction leaves (`.compact.db`, `.precompact.db`). Under the -/// exclusive compaction lock, soo refused (`Busy`) while the indexer, a write -/// from outside it or a compaction has the database. Leaves nothing to set -/// up again from: the next `create_db` makes a new one. +/// Settings > wipe: every shard, with their sidecars and what a compaction +/// leaves (`.compact.db`, `.precompact.db`), then the main database. Under +/// the exclusive compaction lock, soo refused (`Busy`) while the indexer, a +/// write from outside it or a compaction has the database. Leaves nothing to +/// set up again from: the next `create_db` makes a new one. The main +/// database goes only once every shard has: a new main database next to old +/// shards would hand out their ids again. A shard that cant be removed is an +/// error, with the main database left in place. pub fn wipe(main: &Path) -> anyhow::Result<()> { let _exclusive = crate::compact::Lock::take(main)?; - let mut dbs = vec![main.to_path_buf()]; + let mut dbs = Vec::new(); for shard in store::shard_paths(main) { dbs.push(crate::compact::with_suffix(&shard, "compact")); dbs.push(crate::compact::with_suffix(&shard, "precompact")); dbs.push(shard); } + dbs.push(main.to_path_buf()); for db in dbs { for suffix in ["", "-wal", "-shm", "-journal"] { let file = format!("{}{suffix}", db.display()); @@ -694,4 +698,25 @@ mod tests { assert_eq!(held(&main), (0, Some(1)), "no releases, ids from the start"); assert!(group_progress(&open_at(&main).unwrap()).unwrap().is_empty(), "no cursors"); } + + #[test] + fn a_wipe_that_cant_remove_a_shard_keeps_the_main_database() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + create_db_at(&main).unwrap(); + init_group_state(&open_at(&main).unwrap(), "alt.binaries.a@news.x", 500).unwrap(); + + // a shard that cant be removed (on Windows one still open, here a folder) + let stuck = store::shard_paths(&main).pop().unwrap(); + std::fs::remove_file(&stuck).unwrap(); + std::fs::create_dir(&stuck).unwrap(); + let err = wipe(&main).expect_err("a shard was left"); + assert!(format!("{err:#}").contains(&stuck.display().to_string()), "{err:#}"); + assert!(main.exists(), "the main database stays while a shard is left"); + assert_eq!(group_progress(&open_at(&main).unwrap()).unwrap().len(), 1, "with its cursors"); + + std::fs::remove_dir(&stuck).unwrap(); + wipe(&main).unwrap(); + assert!(!main.exists()); + } } From 8e8c734ec2f49fd5917df2397492713701d107da Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:51:26 -0500 Subject: [PATCH 077/159] A split isnt made from post dates that make no sense A poster could give the article at the home backfill cursor a Date from before 2000. The split clamped it into one chunk for 2000-01-01 that no server keeps, and the group never went back to its normal backfill. The dates of the first and last article at the cursor are read now; one before 2000, in the future or before home's first article is left out, and with none left, or a carrier's first article before 2000, the group isnt split and its normal backfill goes on. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 106 ++++++++++++++++++++++++++++++------------- src/nntp.rs | 9 ++-- tests/date_search.rs | 46 +++++++++++++++++++ 3 files changed, 127 insertions(+), 34 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index d68665b8..29e3c227 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -506,10 +506,13 @@ async fn maybe_split( return Ok(false); } - // the newest day still to do is the post date at the home cursor - let split = match ctx.pool.posted_date(home, group, cursor).await? { - Some(t) => split_days(ctx, group, home, (first, last), crate::chunks::unix_day(t)).await?, - None => None, + // the newest day still to do is when the articles at the home cursor + // were posted + let at_cursor = ctx.pool.posted_dates(home, group, cursor).await?; + let split = if at_cursor.is_empty() { + None + } else { + split_days(ctx, group, home, (first, last), Newest::AtCursor(at_cursor)).await? }; let Some(Split { newest_day, oldest_day, carriers, .. }) = split else { ctx.states.with(group, |st| st.no_split_until = Some(Instant::now() + SPLIT_RECHECK)); @@ -532,7 +535,9 @@ async fn reach_back(ctx: &PassContext, db: &Db, group: &str, home: usize, bounds let Some(newest_day) = on_db(db, move |conn| Ok(crate::chunks::newest_day(conn, &g)?)).await? else { return Ok(()); }; - let Some(Split { oldest_day, oldest_at, .. }) = split_days(ctx, group, home, bounds, newest_day).await? else { + let Some(Split { oldest_day, oldest_at, .. }) = + split_days(ctx, group, home, bounds, Newest::Day(newest_day)).await? + else { return Ok(()); }; let g = group.to_string(); @@ -553,24 +558,30 @@ struct Split { carriers: usize, } -/// The days a split of `group` from `newest_day` covers and how many -/// servers carry it. None when it cant split: home's first date is unknown -/// or no other indexing server carries the group. `first` and `last` are -/// home's low and high marks. +/// Where a split of a group starts. +enum Newest { + /// when the articles at the home cursor were posted (unix seconds), for a new split + AtCursor(Vec), + /// the newest day of a split there is (unix days) + Day(i64), +} + +/// The days a split of `group` from `newest` covers and how many servers +/// carry it. None when it cant split: home's first date is unknown, no +/// other indexing server carries the group, or the dates make no sense (see +/// `split_bounds`). `first` and `last` are home's low and high marks. async fn split_days( ctx: &PassContext, group: &str, home: usize, (first, last): (u64, u64), - newest_day: i64, + newest: Newest, ) -> Result> { - use crate::chunks::unix_day; - // the oldest day is at least home's first article. first articles are // searched for from the low marks, which can lag far behind what a // server still keeps - let Some(oldest) = ctx.pool.first_post(home, group, first, last).await? else { return Ok(None) }; - let mut oldest_at = oldest; + let Some(home_oldest) = ctx.pool.first_post(home, group, first, last).await? else { return Ok(None) }; + let mut oldest_at = home_oldest; // other servers are best effort: one that fails is left out. one that // carries the group counts, its oldest date only if it has one @@ -582,23 +593,45 @@ async fn split_days( oldest_at = oldest_at.min(t); } } + if carriers < 2 { + return Ok(None); + } - let oldest_day = unix_day(oldest_at).min(newest_day); - let (newest_day, oldest_day) = clamp_days(newest_day, oldest_day, unix_day(chrono::Utc::now().timestamp())); - // a time clamped out of its day starts the day it was clamped to + let today = crate::chunks::unix_day(chrono::Utc::now().timestamp()); + let Some((newest_day, oldest_day)) = split_bounds(&newest, home_oldest, oldest_at, today) else { + println!("[SPLIT] {group}: post dates that make no sense (forged Date headers?), the split is left as it is"); + return Ok(None); + }; + // a time from before its day (the split doesnt go further back than its + // newest day) starts the day let oldest_at = oldest_at.clamp(oldest_day * 86_400, (oldest_day + 1) * 86_400 - 1); - Ok((carriers >= 2).then_some(Split { newest_day, oldest_day, oldest_at, carriers })) + Ok(Some(Split { newest_day, oldest_day, oldest_at, carriers })) } /// 2000-01-01: binary retention doesnt reach further back than this const SPLIT_OLDEST_DAY: i64 = 10_957; -/// A split's (newest, oldest) days kept between 2000-01-01 and `today`, soo a -/// forged Date header cant make thousands of empty chunks. -fn clamp_days(newest_day: i64, oldest_day: i64, today: i64) -> (i64, i64) { - // a clock set before 2000 mustnt panic the clamp - let newest = newest_day.clamp(SPLIT_OLDEST_DAY, today.max(SPLIT_OLDEST_DAY)); - (newest, oldest_day.clamp(SPLIT_OLDEST_DAY, newest)) +/// A split's (newest, oldest) days from `newest`, home's first article +/// (`home_oldest`) and the first of any carrier (`oldest_at`, unix seconds). +/// Date headers are the posters' to forge, and a split made from a forged +/// one would leave the group's history unindexed for good: a date at the +/// cursor before 2000-01-01, after `today`, or more than a day before home's +/// first article is left out (the latest left answers), and None when none +/// is left or the oldest is before 2000-01-01. Clamping such a date into +/// range would still make a bogus split. +fn split_bounds(newest: &Newest, home_oldest: i64, oldest_at: i64, today: i64) -> Option<(i64, i64)> { + use crate::chunks::unix_day; + let newest_day = match newest { + Newest::AtCursor(times) => times + .iter() + .filter(|&&t| t >= home_oldest - 86_400) + .map(|&t| unix_day(t)) + .filter(|day| (SPLIT_OLDEST_DAY..=today).contains(day)) + .max()?, + Newest::Day(day) => *day, + }; + let oldest_day = unix_day(oldest_at); + (oldest_day >= SPLIT_OLDEST_DAY).then_some((newest_day, oldest_day.min(newest_day))) } /// A day chunk's server doesnt carry its group (GROUP answered 411). @@ -1258,13 +1291,24 @@ mod tests { } #[test] - fn split_days_stay_between_2000_and_today() { - let today = 20_400; - assert_eq!(clamp_days(20_000, 19_000, today), (20_000, 19_000), "sane dates stay"); - assert_eq!(clamp_days(30_000, 19_000, today), (today, 19_000), "a date in the future"); - assert_eq!(clamp_days(20_000, 0, today), (20_000, SPLIT_OLDEST_DAY), "a date from 1970"); - assert_eq!(clamp_days(-5, -10, today), (SPLIT_OLDEST_DAY, SPLIT_OLDEST_DAY)); - assert_eq!(clamp_days(20_000, 19_000, 0), (SPLIT_OLDEST_DAY, SPLIT_OLDEST_DAY), "a clock from 1970"); + fn a_split_is_made_only_from_dates_that_make_sense() { + let (today, day) = (20_400, 86_400); + let home = 19_500 * day; + let at = |times: &[i64]| Newest::AtCursor(times.to_vec()); + assert_eq!(split_bounds(&at(&[20_000 * day]), home, 19_000 * day, today), Some((20_000, 19_000)), "sane"); + assert_eq!(split_bounds(&at(&[0]), home, 19_000 * day, today), None, "a date from 1970 at the cursor"); + assert_eq!(split_bounds(&at(&[30_000 * day]), home, 19_000 * day, today), None, "one in the future"); + assert_eq!(split_bounds(&at(&[19_000 * day]), home, 19_000 * day, today), None, "before home's first"); + assert_eq!(split_bounds(&at(&[home - 3600]), home, home, today), Some((19_499, 19_499)), "roughly in order"); + assert_eq!( + split_bounds(&at(&[0, 20_000 * day]), home, 19_000 * day, today), + Some((20_000, 19_000)), + "one forged date of two is left out" + ); + assert_eq!(split_bounds(&at(&[20_000 * day]), home, 5 * day, today), None, "a carrier's first from 1970"); + assert_eq!(split_bounds(&Newest::Day(20_000), home, 19_000 * day, today), Some((20_000, 19_000))); + assert_eq!(split_bounds(&Newest::Day(20_000), home, 5 * day, today), None); + assert_eq!(split_bounds(&at(&[20_000 * day]), home, 19_000 * day, 0), None, "a clock from 1970"); } #[test] diff --git a/src/nntp.rs b/src/nntp.rs index 237206b0..f3ee2bc5 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1494,9 +1494,12 @@ impl Pool { Ok(None) } - /// When the first article at or after `number` on server `i` was posted (unix seconds). - pub async fn posted_date(&self, i: usize, group: &str, number: u64) -> Result> { - Ok(self.posted_at(i, group, number, DATE_LOOK).await?.map(|(_, t)| t)) + /// When the first and the last article in the `DATE_LOOK` numbers from + /// `number` on server `i` were posted (unix seconds), in one request. + /// Empty when there is none. + pub async fn posted_dates(&self, i: usize, group: &str, number: u64) -> Result> { + let ends = self.ends(i, group, number, number.saturating_add(DATE_LOOK - 1)).await?; + Ok(ends.first.into_iter().chain(ends.last).map(|(_, t)| t).collect()) } /// The first article in `from..end` on server `i`, with its post time. diff --git a/tests/date_search.rs b/tests/date_search.rs index 447146af..40245a46 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -855,6 +855,52 @@ fn a_split_reaches_a_carrier_whose_low_mark_lags() { ); } +/// The article at the home cursor has a forged Date from 1990: no split is +/// made of it (it would be one chunk for 2000-01-01 that no server keeps, +/// and the group's history would never be indexed), the normal backfill goes on. +#[test] +fn a_forged_old_date_at_the_cursor_doesnt_split() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // posts every hour for 10 days from 2026-01-01, the newest dated 1990 + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let posts = |offset: u64| -> Vec { + (0..240u64) + .map(|h| { + let when = match h { + 239 => "Mon, 01 Jan 1990 00:00:00 +0000".to_string(), + _ => (start + chrono::Duration::hours(h as i64)).to_rfc2822(), + }; + post_at(offset + h, &format!(r#""p{h}.bin" yEnc (1/1)"#), &when) + }) + .collect() + }; + let mut other = mock(spawn_server(Server::new(posts(10_001))), "secret", 2, 2); + other.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(spawn_server(Server::new(posts(1))), "secret", 2, 1), other]); + pool.connect().unwrap(); + + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(atlas::db::open_at(&main).unwrap()); + let settings = atlas::indexer::PassSettings { + mode: "backfill".into(), + batch_size: 10, + request_size: 10, + split_min_backlog: 10, + }; + let saved = pool.block_on(atlas::indexer::run_pass(&ctx, &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); + + let conn = atlas::db::open_at(&main).unwrap(); + assert!(!atlas::chunks::is_split(&conn, GROUP).unwrap(), "split from a forged date"); + assert!(saved.articles > 0, "the normal backfill goes on"); +} + /// A carrier that comes to keep more of the split's oldest day (from 01:00 /// where the day was done from 18:00): the day isnt older, but it is to do /// again, by that carrier, soo 01:00 to 18:00 gets indexed. From 5449c48e1cd27afe1cbeb5cc89405e1d09654ab2 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 21:57:52 -0500 Subject: [PATCH 078/159] The indexer converts at start under the exclusive lock too The indexer's own one time conversion ran under its shared setup hold, so two indexers starting at once, or one starting during a --convert, could both convert. It now lets go of the setup hold, converts through convert::run_alone (exclusive, refused while anything else holds the database), then takes the shared hold again for indexing, setting up the converted database. Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 46 ++++++++++++++++++++++++++++++---------------- tests/convert.rs | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 16 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 1299f504..fa0cea4b 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -862,24 +862,18 @@ pub fn run() -> i32 { // one time move of an older database into the shards, here and not in the // menu because it takes a while on a big one. the menu shows the progress let main = paths::database(); - if crate::convert::needed(&main) { - let report = |msg: &str| { - println!("{msg}"); - write_status(true, msg, &config.index_mode, false, "running", false, 0); - }; - match crate::convert::run(&main, &report) { - Ok(_) => {} - Err(e) => { - ui::error(&format!("couldnt convert the database, nothing was changed: {e:#}")); - write_status(false, "", &config.index_mode, false, "stopped", true, 1); - return 1; - } - } - if let Err(e) = db::create_db_at(&main) { - ui::error(&format!("couldnt open the converted database: {e:#}")); + let report = |msg: &str| { + println!("{msg}"); + write_status(true, msg, &config.index_mode, false, "running", false, 0); + }; + let writing = match convert_at_start(&main, writing, &report) { + Ok(held) => held, + Err(e) => { + ui::error(&format!("not indexing: {e:#}")); + write_status(false, "", &config.index_mode, false, "stopped", true, 1); return 1; } - } + }; let stop = Arc::new(AtomicBool::new(false)); @@ -892,6 +886,26 @@ pub fn run() -> i32 { index(config, stop, Some(writing)) } +/// The one time move into the shards at start, if `main` needs it, with +/// `setup` the hold taken for setting up. Returns the hold to index under. +/// The conversion runs alone, under the exclusive lock (`convert::run_alone`): +/// another indexer starting, or a `--convert`, mustnt convert alongside it. +/// The setup hold is let go for it, and taken again after, setting up the +/// converted database: refused if a compaction got in between. +pub fn convert_at_start( + main: &std::path::Path, + setup: WriteGuard, + report: &dyn Fn(&str), +) -> anyhow::Result { + use anyhow::Context as _; + if !crate::convert::needed(main) { + return Ok(setup); + } + drop(setup); + crate::convert::run_alone(main, report).context("couldnt convert the database, nothing was changed")?; + db::create_db_holding(main)?.ok_or_else(|| anyhow::anyhow!("the database is being compacted; try again later")) +} + /// The indexing loop from `run`, stopping once `stop` is set (tests set it /// directly, `run` wires it to SIGTERM / SIGINT). pub fn run_until(config: Config, stop: Arc) -> i32 { diff --git a/tests/convert.rs b/tests/convert.rs index af5a4c79..0f97baa1 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -282,3 +282,39 @@ fn a_conversion_runs_alone() { assert!(!convert::needed(&main), "the first one finished"); assert_eq!(convert::run_alone(&main, &|_| {}).unwrap(), None, "nothing left to convert"); } + +/// The indexer converting at start has the database to itself for the +/// conversion too: refused while another indexer or a `--convert` holds it, +/// and once converted it holds off compaction for indexing. +#[test] +fn an_indexer_converting_at_start_runs_alone() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + let setup = || db::create_db_holding(&main).unwrap().unwrap(); + let new_main = dir.path().join("atlas.new.db"); + + // another indexer that set up at the same time + let other = atlas::compact::try_hold_off_compaction(&main).unwrap().unwrap(); + let err = atlas::bg_indexer::convert_at_start(&main, setup(), &|_| {}).err().expect("converted alongside another"); + assert!(format!("{err:#}").contains("in use"), "{err:#}"); + assert!(convert::needed(&main) && !new_main.exists(), "nothing was done"); + drop(other); + + // a `--convert` running + let converting = std::cell::RefCell::new(None); + let indexing = atlas::bg_indexer::convert_at_start(&main, setup(), &|_| { + if converting.borrow().is_none() { + *converting.borrow_mut() = Some(convert::run_alone(&main, &|_| {}).map(|_| ())); + } + }) + .expect("the indexer converted"); + let err = converting.into_inner().unwrap().expect_err("--convert ran alongside the indexer's conversion"); + assert!(format!("{err:#}").contains("in use"), "{err:#}"); + assert!(!convert::needed(&main)); + + // indexing holds off a compaction, and nothing more is converted + assert!(convert::run_alone(&main, &|_| {}).is_err(), "the indexing hold is held"); + drop(indexing); + assert_eq!(convert::run_alone(&main, &|_| {}).unwrap(), None); +} From 271bcb8b96d8edb977fbd707d7d3977b4d30837a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:10:59 -0500 Subject: [PATCH 079/159] A split is refused when its newest day is before its oldest A poster picks the Date of the article at the cursor. One just before home's first article gave a newest day before the oldest, which was clamped to a split of a single too old day: every carrier gave its chunk back and the group never backfilled normally again. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 29e3c227..56794b87 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -617,8 +617,9 @@ const SPLIT_OLDEST_DAY: i64 = 10_957; /// one would leave the group's history unindexed for good: a date at the /// cursor before 2000-01-01, after `today`, or more than a day before home's /// first article is left out (the latest left answers), and None when none -/// is left or the oldest is before 2000-01-01. Clamping such a date into -/// range would still make a bogus split. +/// is left, the oldest is before 2000-01-01 or the newest day is before the +/// oldest. Clamping such a date into range would still make a bogus split +/// (a too old chunk every carrier gives back). fn split_bounds(newest: &Newest, home_oldest: i64, oldest_at: i64, today: i64) -> Option<(i64, i64)> { use crate::chunks::unix_day; let newest_day = match newest { @@ -631,7 +632,7 @@ fn split_bounds(newest: &Newest, home_oldest: i64, oldest_at: i64, today: i64) - Newest::Day(day) => *day, }; let oldest_day = unix_day(oldest_at); - (oldest_day >= SPLIT_OLDEST_DAY).then_some((newest_day, oldest_day.min(newest_day))) + (oldest_day >= SPLIT_OLDEST_DAY && newest_day >= oldest_day).then_some((newest_day, oldest_day)) } /// A day chunk's server doesnt carry its group (GROUP answered 411). @@ -1299,7 +1300,14 @@ mod tests { assert_eq!(split_bounds(&at(&[0]), home, 19_000 * day, today), None, "a date from 1970 at the cursor"); assert_eq!(split_bounds(&at(&[30_000 * day]), home, 19_000 * day, today), None, "one in the future"); assert_eq!(split_bounds(&at(&[19_000 * day]), home, 19_000 * day, today), None, "before home's first"); - assert_eq!(split_bounds(&at(&[home - 3600]), home, home, today), Some((19_499, 19_499)), "roughly in order"); + assert_eq!(split_bounds(&at(&[home - 3600]), home, home, today), None, "newest day before the oldest"); + assert_eq!(split_bounds(&at(&[home - 3600]), home, home - 7200, today), Some((19_499, 19_499)), "same day"); + assert_eq!( + split_bounds(&at(&[19_499 * day]), home - day, 19_500 * day, today), + None, + "a day before the oldest" + ); + assert_eq!(split_bounds(&Newest::Day(19_000), home, 19_100 * day, today), None, "a split's newest day too"); assert_eq!( split_bounds(&at(&[0, 20_000 * day]), home, 19_000 * day, today), Some((20_000, 19_000)), From d3d10102a1d554ca577bd6bd15fd339ed1e08b13 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:13:49 -0500 Subject: [PATCH 080/159] A used main database with no shard is not a new install With every shard file gone, setup made them all empty. The main database's cursors and next_seq then went on from where the shards had left off, and indexing skipped the history they covered. Shards are made new only for a main database with no groups and no ids handed out. Co-Authored-By: Claude Opus 5.5 --- src/db.rs | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 5 deletions(-) diff --git a/src/db.rs b/src/db.rs index 8ee10f57..56b41d6b 100644 --- a/src/db.rs +++ b/src/db.rs @@ -202,15 +202,36 @@ pub fn create_db_at(path: &Path) -> anyhow::Result<()> { return Ok(migrate_old(&conn)?); } + // a main database that has been used (cursors, ids handed out) is not a + // new install, whatever shards are there + let used = has_progress(&conn)?; store::create_main(&conn)?; - create_shards(path) + create_shards(path, used) +} + +/// Whether the main database holds indexing progress: cursors or ids handed +/// out for releases. The shards hold what those stand for. +fn has_progress(conn: &Connection) -> Result { + if conn.prepare("select 1 from main.groups")?.exists([])? { + return Ok(true); + } + let has_meta = + conn.prepare("select 1 from main.sqlite_master where type = 'table' and name = 'meta'")?.exists([])?; + if !has_meta { + return Ok(false); + } + let next: Option = + conn.query_row("select value from main.meta where key = 'next_seq'", [], |r| r.get(0)).optional()?; + Ok(next.is_some_and(|n| n > 1)) } /// Every shard of `main`, made if new, once the ones a compaction was cut /// short swapping are back. One missing while others are there is refused /// rather than made empty: searches would miss what it held, and new -/// releases would go into the empty one. -fn create_shards(main: &Path) -> anyhow::Result<()> { +/// releases would go into the empty one. The same when all are missing from a +/// main database that `used` (has progress): its cursors would skip what the +/// shards held. Only a main database new to this setup gets all of them new. +fn create_shards(main: &Path, used: bool) -> anyhow::Result<()> { for line in crate::compact::recover_cut_swaps(main)? { crate::ui::warn(&line); } @@ -221,7 +242,7 @@ fn create_shards(main: &Path) -> anyhow::Result<()> { missing.push(path); } } - if !missing.is_empty() && missing.len() < shards.len() { + if !missing.is_empty() && (missing.len() < shards.len() || used) { let each: Vec = missing .iter() .map(|p| { @@ -234,7 +255,7 @@ fn create_shards(main: &Path) -> anyhow::Result<()> { }) .collect(); anyhow::bail!( - "shards missing while the others are there: {}. not making empty ones in their place; put them back first", + "shards missing from a database in use: {}. not making empty ones in their place; put them back first", each.join(", ") ); } @@ -719,4 +740,44 @@ mod tests { wipe(&main).unwrap(); assert!(!main.exists()); } + + #[test] + fn a_used_main_database_without_any_shard_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + create_db_at(&main).unwrap(); + init_group_state(&open_at(&main).unwrap(), "alt.binaries.a@news.x", 500).unwrap(); + let shards = store::shard_paths(&main); + for shard in &shards { + std::fs::remove_file(shard).unwrap(); + } + + // its cursors are past what the empty shards would hold + let err = create_db_at(&main).expect_err("not a new install"); + let err = format!("{err:#}"); + assert!(shards.iter().all(|s| err.contains(&s.display().to_string())), "{err}"); + assert!(shards.iter().all(|s| !s.exists()), "no empty shards made"); + + // the same when only the ids were handed out + std::fs::remove_file(&main).unwrap(); + create_db_at(&main).unwrap(); + store::set_next_seq(&open_at(&main).unwrap(), 50).unwrap(); + for shard in &shards { + std::fs::remove_file(shard).unwrap(); + } + create_db_at(&main).expect_err("ids were handed out"); + } + + #[test] + fn a_main_database_with_nothing_in_it_gets_its_shards() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + create_db_at(&main).unwrap(); + for shard in store::shard_paths(&main) { + std::fs::remove_file(shard).unwrap(); + } + // a setup cut short before the shards + create_db_at(&main).unwrap(); + assert!(store::shard_paths(&main).iter().all(|s| s.exists())); + } } From e145b6fa5c729706cba802035aac7de738b73d56 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:16:11 -0500 Subject: [PATCH 081/159] The dashboard's db size counts the shards too stats.json's db_size came from the main database alone, which is tiny once the releases are in shards. It is now the main database and every shard, the same sum the stats dashboard shows. Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 2 +- src/stats_dashboard.rs | 7 ++----- src/store.rs | 34 ++++++++++++++++++++++++++++++++++ 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index fa0cea4b..2fd2e01e 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -169,7 +169,7 @@ impl Stats { fn write(&self, group: &str, mode: &str, running: bool, idle: bool) { let (peak_a, peak_b, avg_a, avg_b) = self.speeds(); - let db_size = fs::metadata(paths::database()).map(|m| m.len()).unwrap_or(0); + let db_size = crate::store::database_bytes(&paths::database()); let groups: serde_json::Map = self .group_stats diff --git a/src/stats_dashboard.rs b/src/stats_dashboard.rs index 4de718a2..dbdab9f9 100644 --- a/src/stats_dashboard.rs +++ b/src/stats_dashboard.rs @@ -113,12 +113,9 @@ fn load_chunks_stats(conn: &rusqlite::Connection) -> (i64, i64, i64, i64, i64) { fn load_quick() -> Quick { // the main database and its shards let main = paths::database(); - let files: Vec = - std::iter::once(main.clone()).chain(crate::store::shard_paths(&main)).collect(); - let size = |p: &std::path::Path| fs::metadata(p).map(|m| m.len()).unwrap_or(0); let mut q = Quick { - db_bytes: files.iter().map(|p| size(p)).sum(), - wal_bytes: files.iter().map(|p| size(std::path::Path::new(&format!("{}-wal", p.display())))).sum(), + db_bytes: crate::store::database_bytes(&main), + wal_bytes: crate::store::wal_bytes(&main), ..Quick::default() }; diff --git a/src/store.rs b/src/store.rs index e88343ab..37ea309b 100644 --- a/src/store.rs +++ b/src/store.rs @@ -56,6 +56,24 @@ pub fn shard_paths(main: &Path) -> Vec { (0..SHARDS).map(|i| shard_path(main, i)).collect() } +/// the size of the main database and its shards, in bytes (not their -wal +/// files, see `wal_bytes`) +pub fn database_bytes(main: &Path) -> u64 { + files_bytes(main, "") +} + +/// the size of the -wal files of the main database and its shards, in bytes +pub fn wal_bytes(main: &Path) -> u64 { + files_bytes(main, "-wal") +} + +fn files_bytes(main: &Path, suffix: &str) -> u64 { + std::iter::once(main.to_path_buf()) + .chain(shard_paths(main)) + .map(|p| std::fs::metadata(format!("{}{suffix}", p.display())).map(|m| m.len()).unwrap_or(0)) + .sum() +} + /// every shard of `main` is there pub fn exists(main: &Path) -> bool { shard_paths(main).iter().all(|p| p.exists()) @@ -1174,6 +1192,22 @@ pub fn purge_incomplete(main: &Path) -> Result<()> { mod tests { use super::*; + #[test] + fn the_database_size_is_the_main_database_and_every_shard() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + assert_eq!(database_bytes(&main), 0, "nothing yet"); + std::fs::write(&main, [0; 10]).unwrap(); + for (i, shard) in shard_paths(&main).iter().enumerate() { + std::fs::write(shard, vec![0; 100 * (i + 1)]).unwrap(); + } + std::fs::write(format!("{}-wal", main.display()), [0; 7]).unwrap(); + std::fs::write(format!("{}-wal", shard_path(&main, 0).display()), [0; 3]).unwrap(); + let shards: usize = (1..=SHARDS).map(|i| 100 * i).sum(); + assert_eq!(database_bytes(&main), 10 + shards as u64); + assert_eq!(wal_bytes(&main), 10); + } + #[test] fn message_ids_come_back_exactly() { let ids = [ From 4a9f80cca7143b91cf043f1cf5769113a3fc374e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:19:31 -0500 Subject: [PATCH 082/159] The sealed cache holds a bounded number of decoded segments A save with one late article for each of many sealed files decoded every blob into a set kept until commit, up to 50000 segments each. The cache now starts over once it would hold more than 200000, and a blob that says it has more than SEAL_MAX_SEGMENTS, or unpacks to more than that many could take, is an error rather than decoded. Co-Authored-By: Claude Opus 5.5 --- src/blob.rs | 49 ++++++++++++++++++++++++++---- src/store.rs | 86 ++++++++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 117 insertions(+), 18 deletions(-) diff --git a/src/blob.rs b/src/blob.rs index f5331f23..50d77ad5 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -72,24 +72,47 @@ pub fn encode(segs: &[Seg]) -> Vec { /// Unpacks a blob made by `encode`. Truncated or corrupt input is an error. pub fn decode(blob: &[u8]) -> Result> { - let raw = zstd::stream::decode_all(blob)?; + parse(&zstd::stream::decode_all(blob)?, usize::MAX) +} + +/// the most a segment takes unpacked, for bounding what a blob may expand to +const MAX_SEG_RAW: usize = 1024; + +/// `decode` for a blob of at most `max` segments: one that says it has more, +/// or unpacks to more than `max` segments could take, is an error and is +/// never held in memory. +pub fn decode_capped(blob: &[u8], max: usize) -> Result> { + use std::io::Read; + let limit = (max as u64).saturating_mul(MAX_SEG_RAW as u64).saturating_add(16); + let mut raw = Vec::new(); + zstd::stream::read::Decoder::new(blob)?.take(limit).read_to_end(&mut raw)?; + if raw.len() as u64 >= limit { + return Err(Error::new(ErrorKind::InvalidData, "blob unpacks to more than its cap")); + } + parse(&raw, max) +} + +fn parse(raw: &[u8], max: usize) -> Result> { if raw.first() != Some(&VERSION) { return Err(Error::new(ErrorKind::InvalidData, "unknown blob version")); } let mut pos = 1; - let count = get_varint(&raw, &mut pos)? as usize; + let count = get_varint(raw, &mut pos)? as usize; + if count > max { + return Err(Error::new(ErrorKind::InvalidData, "blob has more segments than its cap")); + } // every segment takes at least 4 bytes, so a bigger count is corrupt let mut segs = Vec::with_capacity(count.min(raw.len() / 4)); let mut prev_bytes = 0i64; for _ in 0..count { - let part = match get_varint(&raw, &mut pos)? { + let part = match get_varint(raw, &mut pos)? { 0 => None, p => Some((p - 1) as i64), }; - let bytes = prev_bytes.wrapping_add(unzigzag(get_varint(&raw, &mut pos)?)); + let bytes = prev_bytes.wrapping_add(unzigzag(get_varint(raw, &mut pos)?)); prev_bytes = bytes; - let domain = get_varint(&raw, &mut pos)? as i64; - let len = usize::try_from(get_varint(&raw, &mut pos)?).map_err(|_| cut_short())?; + let domain = get_varint(raw, &mut pos)? as i64; + let len = usize::try_from(get_varint(raw, &mut pos)?).map_err(|_| cut_short())?; let end = pos.checked_add(len).ok_or_else(cut_short)?; let local = raw.get(pos..end).ok_or_else(cut_short)?.to_vec(); pos = end; @@ -106,6 +129,20 @@ mod tests { Seg { part, bytes, domain, local: local.to_vec() } } + #[test] + fn a_blob_past_its_cap_is_an_error() { + let segs: Vec = (0..10).map(|i| seg(Some(i), 5, 0, b"\x00")).collect(); + let blob = encode(&segs); + assert_eq!(decode_capped(&blob, 10).unwrap().len(), 10); + assert!(decode_capped(&blob, 9).is_err(), "more segments than the cap"); + // a count that fits the cap, with more unpacked than that many take + let mut raw = vec![VERSION]; + put_varint(&mut raw, 1); + raw.resize(10_000, 0); + assert!(decode_capped(&zstd::bulk::compress(&raw, 1).unwrap(), 1).is_err()); + assert!(decode_capped(b"garbage", 10).is_err()); + } + #[test] fn segments_come_back_exactly() { let segs = vec![ diff --git a/src/store.rs b/src/store.rs index 37ea309b..2db69caf 100644 --- a/src/store.rs +++ b/src/store.rs @@ -655,12 +655,14 @@ fn blob_error(e: std::io::Error) -> rusqlite::Error { rusqlite::Error::ToSqlConversionFailure(Box::new(e)) } -/// a sealed file's blob, decoded; none when the file isnt sealed +/// a sealed file's blob, decoded; none when the file isnt sealed. A blob +/// holds SEAL_MAX_SEGMENTS at most (sealing sees to that): one with more is +/// an error, not something to decode into memory. fn sealed_segments(conn: &Connection, file_id: i64) -> Result>> { conn.prepare_cached("select blob from files where id = ? and blob is not null")? .query_row([file_id], |r| r.get::<_, Vec>(0)) .optional()? - .map(|b| crate::blob::decode(&b).map_err(blob_error)) + .map(|b| crate::blob::decode_capped(&b, SEAL_MAX_SEGMENTS as usize).map_err(blob_error)) .transpose() } @@ -773,26 +775,42 @@ pub(crate) fn due(expected: Option, seen: &[u8], touched: Option, seal complete || touched.is_none_or(|t| t < now - SEAL_AGE) } -/// Blobs of sealed files, decoded once each, for checking late articles. -#[derive(Default)] +/// the segments a `SealedCache` keeps decoded at most: a save can touch a +/// sealed file per article, and each is up to SEAL_MAX_SEGMENTS +const SEALED_CACHE_MAX_SEGMENTS: usize = 200_000; + +/// Blobs of sealed files, decoded once each, for checking late articles. Holds +/// at most `SEALED_CACHE_MAX_SEGMENTS` decoded segments: past that it starts +/// over, the cache only saves decoding a blob again. pub(crate) struct SealedCache { files: HashMap, i64)>>, + /// segments in `files` + segments: usize, + max_segments: usize, } impl SealedCache { pub(crate) fn new() -> Self { - Self::default() + Self::with_max(SEALED_CACHE_MAX_SEGMENTS) + } + + fn with_max(max_segments: usize) -> Self { + SealedCache { files: HashMap::new(), segments: 0, max_segments } } /// the article (local, domain) is already in file `file_id`'s blob pub(crate) fn contains(&mut self, conn: &Connection, file_id: i64, local: &[u8], domain: i64) -> Result { - let set = match self.files.entry(file_id) { - Entry::Occupied(e) => e.into_mut(), - Entry::Vacant(e) => e.insert( - sealed_segments(conn, file_id)?.unwrap_or_default().into_iter().map(|s| (s.local, s.domain)).collect(), - ), - }; - Ok(set.contains(&(local.to_vec(), domain))) + if !self.files.contains_key(&file_id) { + let set: HashSet<(Vec, i64)> = + sealed_segments(conn, file_id)?.unwrap_or_default().into_iter().map(|s| (s.local, s.domain)).collect(); + if self.segments + set.len() > self.max_segments { + self.files.clear(); + self.segments = 0; + } + self.segments += set.len(); + self.files.insert(file_id, set); + } + Ok(self.files[&file_id].contains(&(local.to_vec(), domain))) } } @@ -1192,6 +1210,50 @@ pub fn purge_incomplete(main: &Path) -> Result<()> { mod tests { use super::*; + /// a table of sealed files for a `SealedCache`: file i holds `per` segments + fn sealed_files(files: i64, per: i64) -> Connection { + let conn = Connection::open_in_memory().unwrap(); + conn.execute_batch("create table files (id INTEGER PRIMARY KEY, blob BLOB)").unwrap(); + for id in 1..=files { + let segs: Vec = (0..per) + .map(|p| crate::blob::Seg { + part: Some(p), + bytes: 1, + domain: id, + local: format!("{id}-{p}").into_bytes(), + }) + .collect(); + conn.execute("insert into files (id, blob) values (?, ?)", params![id, crate::blob::encode(&segs)]) + .unwrap(); + } + conn + } + + #[test] + fn the_sealed_cache_stays_within_its_bound_and_still_finds_every_duplicate() { + let conn = sealed_files(40, 3); + let mut cache = SealedCache::with_max(10); + // one late article per sealed file, twice around + for _ in 0..2 { + for id in 1..=40 { + assert!(cache.contains(&conn, id, format!("{id}-1").as_bytes(), id).unwrap(), "file {id}"); + assert!(!cache.contains(&conn, id, b"new", id).unwrap()); + assert!(cache.segments <= 10, "{} segments kept", cache.segments); + assert_eq!(cache.segments, cache.files.values().map(|s| s.len()).sum::()); + } + } + } + + #[test] + fn a_sealed_blob_past_the_cap_is_an_error_not_a_decode() { + let conn = sealed_files(1, SEAL_MAX_SEGMENTS + 1); + let mut cache = SealedCache::new(); + assert!(cache.contains(&conn, 1, b"1-1", 1).is_err()); + assert!(cache.files.is_empty()); + let conn = sealed_files(1, SEAL_MAX_SEGMENTS); + assert!(cache.contains(&conn, 1, b"1-1", 1).unwrap(), "the cap itself is fine"); + } + #[test] fn the_database_size_is_the_main_database_and_every_shard() { let dir = tempfile::tempdir().unwrap(); From 657acec87730fd9f74e65bef58c2cf63160dba30 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:31:46 -0500 Subject: [PATCH 083/159] The small-budget cap test runs four passes, not sixteen With a budget smaller than one slice only one slice is unsaved at a time, soo all 960 slices went strictly one after another; on Windows runners that took over the 60 s limit. It was slow, not stuck: four passes still contend for both servers and four connections in a quarter of the slices. Co-Authored-By: Claude Opus 5.5 --- tests/unsaved_cap.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/tests/unsaved_cap.rs b/tests/unsaved_cap.rs index 33c68a9f..941f918c 100644 --- a/tests/unsaved_cap.rs +++ b/tests/unsaved_cap.rs @@ -15,7 +15,6 @@ use common::{Server, mock, par2_file_desc, post, spawn_server, yenc_body}; const POSTS: u64 = 400; const REQUEST: u64 = 20; -const GROUPS: usize = 16; const BATCH: u64 = 100; /// `POSTS` articles in releases of one slice each, every release with a par2, @@ -39,9 +38,9 @@ fn busy_server() -> Arc { s } -/// Every group indexed to the end at once, on two servers of two +/// `groups` groups indexed to the end at once, on two servers of two /// connections each, with room for `cap` unsaved headers. -fn index_everything(cap: usize) { +fn index_everything(cap: usize, groups: usize) { let servers = [busy_server(), busy_server()]; let ports: Vec = servers.iter().map(|s| spawn_server(s.clone())).collect(); let pool = @@ -69,7 +68,7 @@ fn index_everything(cap: usize) { let saved: Vec = rt.block_on(async { pool.connect().await.unwrap(); let mut passes = tokio::task::JoinSet::new(); - for g in 0..GROUPS { + for g in 0..groups { let (ctx, settings, db) = (ctx.clone(), settings.clone(), db.clone()); passes.spawn(async move { let group = format!("alt.binaries.cap{g}"); @@ -94,11 +93,11 @@ fn index_everything(cap: usize) { tokio::time::timeout(Duration::from_secs(60), all).await.expect("the passes are stuck") }); - assert_eq!(saved, vec![POSTS as i64; GROUPS], "every article saved once, per group"); + assert_eq!(saved, vec![POSTS as i64; groups], "every article saved once, per group"); // slices no bigger than the budget, in passes of BATCH let slice = REQUEST.min(cap as u64); let xovers: usize = servers.iter().map(|s| s.xovers.load(Ordering::SeqCst)).sum(); - assert_eq!(xovers, GROUPS * (POSTS / BATCH * BATCH.div_ceil(slice)) as usize, "every slice fetched once"); + assert_eq!(xovers, groups * (POSTS / BATCH * BATCH.div_ceil(slice)) as usize, "every slice fetched once"); let peak = pool.unsaved_peak(); assert!(peak <= cap, "{peak} headers unsaved at once, the cap is {cap}"); @@ -110,17 +109,20 @@ fn index_everything(cap: usize) { let (releases, named): (i64, i64) = conn .query_row("select count(*), count(display_name) from releases", [], |r| Ok((r.get(0)?, r.get(1)?))) .unwrap(); - assert_eq!((releases, named), ((GROUPS as u64 * POSTS / REQUEST) as i64, releases)); + assert_eq!((releases, named), ((groups as u64 * POSTS / REQUEST) as i64, releases)); } /// Two slices' worth for 16 passes of up to two connections each. #[test] fn many_passes_share_a_budget_of_two_slices() { - index_everything(2 * REQUEST as usize); + index_everything(2 * REQUEST as usize, 16); } -/// A budget smaller than one slice: the slices are cut down to it. +/// A budget smaller than one slice: the slices are cut down to it. Only one +/// slice fits at a time, soo every slice of every pass goes one after another +/// (fetch, then save): four passes, still more than the four connections and +/// both servers, keep it to a few hundred slices. #[test] fn a_budget_smaller_than_a_slice_still_gets_through() { - index_everything(7); + index_everything(7, 4); } From 9045d16b466739f97d081f7da21ec51b60e22c0c Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:37:47 -0500 Subject: [PATCH 084/159] Forged Dates dont make a day chunk miss the day's posts The date search passes over Dates before 2000 or past now as undated. An article found older than the time searched for only moves the search past the numbers below it when the window of articles from it is all older too: one forged early Date no longer drops the posts below a midpoint. And a day chunk reads 8 windows of 100 numbers on each side of the range the search found, widening it to the day's posts there, soo a run of forged Dates that makes the search find the day short or empty doesnt lose them. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 5 +++ src/nntp.rs | 95 ++++++++++++++++++++++++++++++++++++++++++-- tests/date_search.rs | 83 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 179 insertions(+), 4 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 56794b87..205a54ee 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -850,6 +850,11 @@ where Ok(n) => n.saturating_sub(1), Err(e) => return failed(e.into()).await, }; + // posts of the day the search missed, near what it found + let (start, end) = match ctx.pool.widen_to_day(server, group, (first, last), (start, end), (from, to)).await { + Ok(range) => range, + Err(e) => return failed(e.into()).await, + }; if start > end { finish().await?; return Ok(Progress::default()); diff --git a/src/nntp.rs b/src/nntp.rs index f3ee2bc5..18d59005 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -233,7 +233,7 @@ impl Ends { return; }; self.read_to = self.read_to.max(Some(number)); - let Some(t) = fields.nth(2).and_then(|d| crate::dates::posted_timestamp(&String::from_utf8_lossy(d))) else { + let Some(t) = fields.nth(2).and_then(|d| plausible_post_time(&String::from_utf8_lossy(d))) else { return; }; if self.first.is_none_or(|f| number < f.0) { @@ -875,6 +875,21 @@ pub struct ServerStat { /// an article number and when it was posted (unix seconds) type Dated = (u64, i64); +/// A Date header as unix seconds when it could be true: from 2000 on and not +/// later than a little past now. Posters set their own Dates, soo a date search +/// passes over the others as undated rather than be thrown off by them. +fn plausible_post_time(date: &str) -> Option { + /// 2000-01-01, and the slack for clocks running ahead + const EARLIEST: i64 = 946_684_800; + const AHEAD: i64 = 2 * 86_400; + let t = crate::dates::posted_timestamp(date)?; + (EARLIEST..=chrono::Utc::now().timestamp() + AHEAD).contains(&t).then_some(t) +} + +/// windows of `DATE_LOOK` numbers a day chunk reads on each side of the range +/// the date search found for it, for posts of that day the search missed +pub const DAY_CHECK_WINDOWS: u64 = 8; + /// numbers per date search request at first, and at most const DATE_LOOK: u64 = 100; const DATE_SCAN_MAX: u64 = DATE_LOOK << 6; @@ -1649,15 +1664,24 @@ impl Pool { while lo < hi { let mid = lo + (hi - lo) / 2; let found = self.first_in(i, group, mid, hi).await?; + // the first article found older: the window from it says whether + // all of it is (a single forged Date doesnt move lo past the + // articles below mid), else its first one that isnt answers + let mut newer = found.map(|(n, _)| n); if let Some((n, t)) = found && t < when { - lo = n + 1; - continue; + match self.first_dated_from(i, group, n, hi, when).await? { + None => { + lo = n + 1; + continue; + } + Some(m) => newer = Some(m), + } } // nothing from mid up to the article found (or up to hi) let gap_end = found.map_or(hi, |(n, _)| n); - if let Some((n, _)) = found { + if let Some(n) = newer { first = n; } hi = mid; @@ -1673,6 +1697,69 @@ impl Pool { Ok(first) } + /// The articles of `start..=end` on server `i`, empty when there are none. + async fn listing(&self, i: usize, group: &str, start: u64, end: u64) -> Result> { + match self.xover_on(i, group, start, end).await { + Err(e) if e.is_empty_range() => Ok(Vec::new()), + r => r, + } + } + + /// The first article in the `DATE_LOOK` numbers from `n` (below `hi`) on + /// server `i` posted at or after `when`, by its plausible Date. None when + /// every one of them was posted before. + async fn first_dated_from(&self, i: usize, group: &str, n: u64, hi: u64, when: i64) -> Result> { + let end = n.saturating_add(DATE_LOOK - 1).min(hi.saturating_sub(1)).max(n); + let rows = self.listing(i, group, n, end).await?; + Ok(rows.iter().find(|o| plausible_post_time(&o.date).is_some_and(|t| t >= when)).map(|o| o.number)) + } + + /// `start..=end` of `group` on server `i` (`low..=high` on the server) + /// widened to the articles posted in `from..to` among the + /// `DAY_CHECK_WINDOWS` windows of `DATE_LOOK` numbers before `start` and + /// after `end`. The date search takes post dates for ordered, which a run + /// of forged Dates can make it miss a day's posts by, even all of them: + /// this bounded look around the range finds those near it. + pub async fn widen_to_day( + &self, + i: usize, + group: &str, + (low, high): (u64, u64), + (start, end): (u64, u64), + (from, to): (i64, i64), + ) -> Result<(u64, u64)> { + let in_day = |rows: &[Overview]| -> Vec { + rows.iter() + .filter(|o| plausible_post_time(&o.date).is_some_and(|t| (from..to).contains(&t))) + .map(|o| o.number) + .collect() + }; + let (mut first, mut last) = (start, end); + let mut at = start; + for _ in 0..DAY_CHECK_WINDOWS { + if at <= low { + break; + } + let a = at.saturating_sub(DATE_LOOK).max(low); + if let Some(&n) = in_day(&self.listing(i, group, a, at - 1).await?).iter().min() { + first = first.min(n); + } + at = a; + } + let mut at = end.saturating_add(1).max(low); + for _ in 0..DAY_CHECK_WINDOWS { + if at > high { + break; + } + let b = at.saturating_add(DATE_LOOK - 1).min(high); + if let Some(&n) = in_day(&self.listing(i, group, at, b).await?).iter().max() { + last = last.max(n); + } + at = b + 1; + } + Ok((first, last)) + } + /// Compressed listings from server `i` couldnt be read: it gets plain ones from now on. fn no_compression(&self, i: usize, e: &str) { let server = &self.servers[i]; diff --git a/tests/date_search.rs b/tests/date_search.rs index 40245a46..b17fbfa0 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -1102,3 +1102,86 @@ fn a_sparse_region_before_a_hole_is_not_skipped() { finds_the_first_post_for_each(&list, &[1], &whens); chunks_save_every_post_of(&list, &days_from(&list, 19_000, 5)); } + +/// One article above the first midpoint dated far too early (a forged Date) +/// doesnt move the search past the articles below it. +#[test] +fn a_forged_early_date_at_a_midpoint_doesnt_skip_the_articles_below_it() { + // the search for hour 700 probes 501 (older), then 751: forged to the start + let posts: Vec = with_gap(1, 1000, 0..=0) + .into_iter() + .map(|mut p| { + if p.number == 751 { + p.date = "Thu, 01 Jan 2026 00:00:00 +0000".into(); + } + p + }) + .collect(); + assert_eq!(search(posts, 1, 1000, hour_of(700)), 700); +} + +/// posts 1..=240 one an hour from 2026-01-01, 100..=200 forged to `forged`; +/// day 2026-01-10 is 217..=240 +fn forged_run(forged: &str) -> Vec { + with_gap(1, 240, 0..=0) + .into_iter() + .map(|mut p| { + if (100..=200).contains(&p.number) { + p.date = forged.into(); + } + p + }) + .collect() +} + +/// The day chunk for 2026-01-10 over `posts`: the numbers of it that were saved +fn chunk_of_jan_10(posts: Vec) -> Vec { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let port = spawn_server(Server::new(posts)); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + + let day = atlas::chunks::unix_day(hour_of(217)); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + let chunk = claimed(&main, GROUP, day); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); + + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); + let shard = atlas::store::shard_of(GROUP); + let mut q = conn.prepare(&format!("select subject from s{shard}.files")).unwrap(); + // subjects are "pN.bin" yEnc (1/1) + let mut saved: Vec = q + .query_map([], |r| r.get::<_, String>(0)) + .unwrap() + .map(|s| s.unwrap().trim_start_matches("\"p").split('.').next().unwrap().parse().unwrap()) + .collect(); + saved.sort(); + saved +} + +/// A run of posts with Dates from the future (later than now) is passed over +/// by the search: the day's posts after it are all fetched. +#[test] +fn a_run_of_future_dates_doesnt_empty_the_day() { + let saved = chunk_of_jan_10(forged_run("Mon, 01 Jan 2035 00:00:00 +0000")); + assert!((216..=240).all(|n| saved.contains(&n)), "the day's posts are missing: {saved:?}"); +} + +/// A run of posts with Dates after the day but not in the future: the search +/// finds the day empty, the check around it still finds the day's posts. +#[test] +fn a_run_of_later_dates_doesnt_empty_the_day() { + let saved = chunk_of_jan_10(forged_run("Mon, 01 Jun 2026 00:00:00 +0000")); + assert!((216..=240).all(|n| saved.contains(&n)), "the day's posts are missing: {saved:?}"); +} From 1aa995d0bef4b04b328833d87a6940d43726c598 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:38:42 -0500 Subject: [PATCH 085/159] A compaction's backup keeps its WAL, and a checkpoint held back is refused The result of each wal_checkpoint(truncate) is read: one that a reader or writer held back (busy, or not every page folded in) fails the shard rather than being taken for done. The original's -wal and -shm are moved aside with it as the .precompact backup instead of deleted, and a cut swap puts them back with it. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 83 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 76 insertions(+), 7 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 45cf67c7..64d5a942 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -50,6 +50,31 @@ fn remove_db(path: &Path) { } } +/// Fold the WAL of `conn`'s database into it, all of it: a checkpoint held +/// back (a reader, a writer) leaves committed pages only in the WAL, soo it +/// is an error rather than taken for done. +fn checkpoint(conn: &Connection) -> Result<()> { + let (busy, log, done): (i64, i64, i64) = + conn.query_row("pragma wal_checkpoint(truncate)", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?; + if busy != 0 || log != done { + bail!("the WAL checkpoint didnt complete ({done} of {log} pages, busy {busy})"); + } + Ok(()) +} + +/// Rename the database `from` to `to`, its -wal and -shm with it (those +/// there are): the WAL can hold committed pages of it. +fn rename_db(from: &Path, to: &Path) -> std::io::Result<()> { + std::fs::rename(from, to)?; + for suffix in ["-wal", "-shm"] { + let (a, b) = (format!("{}{suffix}", from.display()), format!("{}{suffix}", to.display())); + if Path::new(&a).exists() { + std::fs::rename(a, b)?; + } + } + Ok(()) +} + fn size(path: &Path) -> u64 { std::fs::metadata(path).map(|m| m.len()).unwrap_or(0) } @@ -204,7 +229,7 @@ pub fn recover_cut_swaps(main: &Path) -> Result> { said.push(unresolved_message(&path, &original)); continue; } - std::fs::rename(&original, &path) + rename_db(&original, &path) .with_context(|| format!("putting {} back as {}", original.display(), path.display()))?; remove_db(&with_suffix(&path, "compact")); said.push(format!("{} was moved aside by a compaction that was cut short; it's back in place", path.display())); @@ -333,7 +358,7 @@ fn compact_shard( // fold the WAL in soo the original is whole on its own { let conn = db::open_at(&path)?; - conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(()))?; + checkpoint(&conn).context("folding the original's WAL in")?; // a shard from before sealing gets its (empty) seal columns store::migrate_shard(&conn)?; } @@ -548,13 +573,12 @@ fn compact_shard( halt(stop, shard)?; let conn = db::open_at(©)?; conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; - conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(()))?; + checkpoint(&conn).context("folding the copy's WAL in")?; drop(conn); + // the original's -wal and -shm go aside with it: whatever they hold + // comes back with it if the swap is cut short (`recover_cut_swaps`) let original = with_suffix(&path, "precompact"); - std::fs::rename(&path, &original).context("moving the original shard aside")?; - for suffix in ["-wal", "-shm"] { - let _ = std::fs::remove_file(format!("{}{suffix}", path.display())); - } + rename_db(&path, &original).context("moving the original shard aside")?; std::fs::rename(©, &path).context("putting the compacted shard in place")?; let after = size(&path); say(&format!("{:.1}GB -> {:.1}GB", before as f64 / 1e9, after as f64 / 1e9)); @@ -1342,4 +1366,49 @@ mod tests { std::fs::remove_file(&backup).unwrap(); drop(hold_off_compaction(&main).unwrap()); } + + /// A checkpoint held back by a reader (its snapshot keeps WAL frames from + /// being folded in) is an error, not taken for done. + #[test] + fn a_checkpoint_a_reader_holds_back_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("x.db"); + let writer = db::open_at(&path).unwrap(); + writer.execute_batch("pragma journal_mode = wal; pragma wal_autocheckpoint = 0; create table t (x)").unwrap(); + let reader = db::open_at(&path).unwrap(); + reader.execute_batch("begin; select count(*) from t").unwrap(); + writer.execute("insert into t values (1)", []).unwrap(); + + writer.busy_timeout(std::time::Duration::ZERO).unwrap(); + let err = checkpoint(&writer).unwrap_err(); + assert!(format!("{err:#}").contains("checkpoint"), "{err:#}"); + reader.execute_batch("commit").unwrap(); + checkpoint(&writer).unwrap(); + } + + /// A shard moved aside with pages still in its WAL (committed, not + /// folded in) gets them back with it when the swap was cut short. + #[test] + fn a_cut_swap_puts_the_originals_wal_back_with_it() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let path = store::shard_path(&main, store::shard_of("alt.binaries.g3")); + let backup = with_suffix(&path, "precompact"); + { + // the moved aside original: its file and its WAL, taken while a + // connection keeps a write in the WAL + let conn = db::open_at(&path).unwrap(); + conn.execute_batch("pragma wal_autocheckpoint = 0; create table late (x); insert into late values (7)") + .unwrap(); + std::fs::copy(&path, &backup).unwrap(); + std::fs::copy(format!("{}-wal", path.display()), format!("{}-wal", backup.display())).unwrap(); + } + remove_db(&path); + + recover_cut_swaps(&main).unwrap(); + let late: i64 = db::open_at(&path).unwrap().query_row("select x from late", [], |r| r.get(0)).unwrap(); + assert_eq!(late, 7, "the write in the WAL came back too"); + assert!(!Path::new(&format!("{}-wal", backup.display())).exists()); + } } From f748dcbb576d7096f7873d4e9ab50a0c95aff32c Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:42:55 -0500 Subject: [PATCH 086/159] The sealed cache lets its least recently used file go, and a save decodes a bounded amount Past its cap the cache dropped every decoded file, soo late articles cycling over a few big sealed files decoded a blob for each one. It now lets the least recently used files go, and one save decodes at most 20 of the biggest blobs' worth of segments (1M): past that a sealed file not held is taken not to have the article, which is saved as a row, and sealing the file again drops a row its blob already has. Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 136 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 115 insertions(+), 21 deletions(-) diff --git a/src/store.rs b/src/store.rs index 2db69caf..65b58874 100644 --- a/src/store.rs +++ b/src/store.rs @@ -707,6 +707,11 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { if rows.iter().any(|r| r.part.is_some_and(|p| p < 0)) { return Ok(0); } + // a row the blob already has (saved past a save's decode budget, see + // `SealedCache`) isnt added twice + let held: HashSet<(&[u8], i64)> = segs.iter().map(|s| (s.local.as_slice(), s.domain)).collect(); + let rows: Vec = + rows.into_iter().filter(|r| !held.contains(&(r.local.as_slice(), r.domain))).collect(); segs.extend(rows); conn.prepare_cached("update files set blob = ? where id = ?")? .execute(params![crate::blob::encode(&segs), file_id])?; @@ -779,38 +784,82 @@ pub(crate) fn due(expected: Option, seen: &[u8], touched: Option, seal /// sealed file per article, and each is up to SEAL_MAX_SEGMENTS const SEALED_CACHE_MAX_SEGMENTS: usize = 200_000; -/// Blobs of sealed files, decoded once each, for checking late articles. Holds -/// at most `SEALED_CACHE_MAX_SEGMENTS` decoded segments: past that it starts -/// over, the cache only saves decoding a blob again. +/// the segments one `SealedCache` (one save) decodes at most, over all its +/// blobs: 20 of the biggest. Late articles cycling over more sealed files +/// than the cache holds would decode a blob each otherwise +const SEALED_DECODE_BUDGET: usize = 20 * SEAL_MAX_SEGMENTS as usize; + +/// a sealed file's articles as (local, domain) +type SegmentSet = HashSet<(Vec, i64)>; + +/// Blobs of sealed files, decoded once each, for checking late articles. +/// Holds at most `SEALED_CACHE_MAX_SEGMENTS` decoded segments, letting the +/// least recently used files go past that, and decodes at most +/// `SEALED_DECODE_BUDGET` segments in all. Past the budget a sealed file not +/// held is taken not to have the article: it's saved as a row, and sealing +/// the file again drops a row its blob already has (till then a repost of +/// an article could show twice in the NZB). pub(crate) struct SealedCache { - files: HashMap, i64)>>, + /// each file's segments, and when it was last used + files: HashMap, + /// the files by when they were last used + by_use: std::collections::BTreeMap, + uses: u64, /// segments in `files` segments: usize, max_segments: usize, + /// segments decoded so far + decoded: usize, + max_decoded: usize, } impl SealedCache { pub(crate) fn new() -> Self { - Self::with_max(SEALED_CACHE_MAX_SEGMENTS) - } - - fn with_max(max_segments: usize) -> Self { - SealedCache { files: HashMap::new(), segments: 0, max_segments } + Self::with_limits(SEALED_CACHE_MAX_SEGMENTS, SEALED_DECODE_BUDGET) + } + + fn with_limits(max_segments: usize, max_decoded: usize) -> Self { + SealedCache { + files: HashMap::new(), + by_use: Default::default(), + uses: 0, + segments: 0, + max_segments, + decoded: 0, + max_decoded, + } } /// the article (local, domain) is already in file `file_id`'s blob pub(crate) fn contains(&mut self, conn: &Connection, file_id: i64, local: &[u8], domain: i64) -> Result { - if !self.files.contains_key(&file_id) { - let set: HashSet<(Vec, i64)> = - sealed_segments(conn, file_id)?.unwrap_or_default().into_iter().map(|s| (s.local, s.domain)).collect(); - if self.segments + set.len() > self.max_segments { - self.files.clear(); - self.segments = 0; - } - self.segments += set.len(); - self.files.insert(file_id, set); + self.uses += 1; + let key = (local.to_vec(), domain); + if let Some((used, set)) = self.files.get_mut(&file_id) { + self.by_use.remove(used); + *used = self.uses; + self.by_use.insert(self.uses, file_id); + return Ok(set.contains(&key)); + } + if self.decoded >= self.max_decoded { + return Ok(false); + } + let set: SegmentSet = + sealed_segments(conn, file_id)?.unwrap_or_default().into_iter().map(|s| (s.local, s.domain)).collect(); + self.decoded += set.len(); + let found = set.contains(&key); + if set.len() > self.max_segments { + return Ok(found); } - Ok(self.files[&file_id].contains(&(local.to_vec(), domain))) + while self.segments + set.len() > self.max_segments + && let Some((_, oldest)) = self.by_use.pop_first() + && let Some((_, gone)) = self.files.remove(&oldest) + { + self.segments -= gone.len(); + } + self.segments += set.len(); + self.by_use.insert(self.uses, file_id); + self.files.insert(file_id, (self.uses, set)); + Ok(found) } } @@ -1232,16 +1281,44 @@ mod tests { #[test] fn the_sealed_cache_stays_within_its_bound_and_still_finds_every_duplicate() { let conn = sealed_files(40, 3); - let mut cache = SealedCache::with_max(10); + let mut cache = SealedCache::with_limits(10, usize::MAX); // one late article per sealed file, twice around for _ in 0..2 { for id in 1..=40 { assert!(cache.contains(&conn, id, format!("{id}-1").as_bytes(), id).unwrap(), "file {id}"); assert!(!cache.contains(&conn, id, b"new", id).unwrap()); assert!(cache.segments <= 10, "{} segments kept", cache.segments); - assert_eq!(cache.segments, cache.files.values().map(|s| s.len()).sum::()); + assert_eq!(cache.segments, cache.files.values().map(|(_, s)| s.len()).sum::()); + } + } + } + + /// The least recently used file goes when the cache is full, not all of + /// them: a file checked over and over stays decoded. + #[test] + fn the_sealed_cache_lets_the_least_recently_used_file_go() { + let conn = sealed_files(5, 4); + let mut cache = SealedCache::with_limits(12, usize::MAX); + for id in [1, 2, 3, 1, 4, 1, 5, 1] { + assert!(cache.contains(&conn, id, format!("{id}-1").as_bytes(), id).unwrap(), "file {id}"); + } + assert_eq!(cache.decoded, 5 * 4, "file 1 was decoded once"); + assert!(cache.segments <= 12); + } + + /// Late articles cycling over more sealed files than the cache holds + /// decode no more than the budget in one save. + #[test] + fn cycling_sealed_files_decodes_no_more_than_the_budget() { + let conn = sealed_files(5, 4); + let mut cache = SealedCache::with_limits(16, 40); + for _ in 0..3 { + for id in 1..=5 { + cache.contains(&conn, id, b"late", id).unwrap(); } } + assert!(cache.decoded <= 40, "{} segments decoded", cache.decoded); + assert!(cache.segments <= 16); } #[test] @@ -1539,6 +1616,23 @@ mod tests { assert_eq!(read(), after); } + /// A row its blob already has (saved past a save's decode budget) is + /// dropped when the file is sealed again, not kept twice. + #[test] + fn resealing_drops_a_row_the_blob_already_has() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let a: i64 = conn.query_row("select id from files where filename = 'a.rar'", [], |r| r.get(0)).unwrap(); + assert_eq!(seal_file(&conn, a).unwrap(), 3); + let first = sealed_segments(&conn, a).unwrap().unwrap().remove(0); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", + params![a, first.local, first.domain, first.part, first.bytes], + ) + .unwrap(); + assert_eq!(seal_file(&conn, a).unwrap(), 3, "the copy isnt added"); + } + #[test] fn sealed_nzb_is_byte_for_byte_the_same() { let dir = tempfile::tempdir().unwrap(); From fe27860b43f8179053416d969e3e5c7b3dd7f6c7 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:05:49 -0500 Subject: [PATCH 087/159] A day chunk's range ends where the next day's starts, soo no post is in none A day chunk searched for its own start and end by date, and a run of more forged Dates than the look around the range reached could make the range empty or short: the day was marked done with its posts never fetched. Now a chunk starts where the date search puts its day an hour early and ends where the same search puts the next day's start (or an hour past the day, when further). Neighbouring chunks share that boundary, the oldest starts at the low mark and the newest ends at the backfill cursor (the high mark without one), soo every number in between is some chunk's: a forged Date only moves an article into a neighbouring chunk. The look around the range is gone. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 60 ++++++++++++++++---- src/nntp.rs | 50 ---------------- tests/date_search.rs | 132 ++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 172 insertions(+), 70 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 205a54ee..8a73cc11 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -796,9 +796,6 @@ where }; let (_count, first, last, _name) = found; - let from = day * 86_400 - CHUNK_OVERLAP; - let to = (day + 1) * 86_400 + CHUNK_OVERLAP; - // a day this server doesnt keep from its start would come out empty or // cut short, though another server may have all of it: give it back, and // the server takes no day that old for a while. the split's oldest day is @@ -842,16 +839,20 @@ where } return failed(TooOld { group: group.to_string(), host, oldest_day }.into()).await; } - let start = match ctx.pool.article_at(server, group, first, last, from).await { - Ok(n) => n, - Err(e) => return failed(e.into()).await, - }; - let end = match ctx.pool.article_at(server, group, start.max(first), last, to).await { - Ok(n) => n.saturating_sub(1), - Err(e) => return failed(e.into()).await, + // the split's days and, for its newest, how far down this server's + // backfill got before the split (its high mark when it has no cursor) + let (g, key) = (group.to_string(), cursor_key(&ctx.pool, server, group)); + let bounds = on_db(db, move |conn| { + let days = crate::chunks::oldest_day(conn, &g)?.zip(crate::chunks::newest_day(conn, &g)?); + Ok((days, db::get_group_state(conn, &key)?)) + }) + .await; + let (days, cursor) = match bounds { + Ok((Some(days), state)) => (days, state.map_or(last, |s| (s.backfill_cursor.max(0) as u64).min(last))), + Ok((None, _)) => return failed(anyhow!("{group} has no day chunks")).await, + Err(e) => return failed(e).await, }; - // posts of the day the search missed, near what it found - let (start, end) = match ctx.pool.widen_to_day(server, group, (first, last), (start, end), (from, to)).await { + let (start, end) = match chunk_range(&ctx.pool, server, group, (first, last), day, days, cursor).await { Ok(range) => range, Err(e) => return failed(e.into()).await, }; @@ -874,6 +875,41 @@ where } } +/// The article numbers day chunk `day` of a split over `days` (oldest, +/// newest) covers on `server`, whose low and high marks are `first` and +/// `last`: from where the day starts to where the next one does, each found +/// by the same date search an hour early (`CHUNK_OVERLAP`), and to an hour +/// past the day when that is further. The oldest day starts at `first`, the +/// newest ends at `cursor`. Neighbouring days share where one ends and the +/// next starts, soo every number from `first` to `cursor` is some chunk's +/// however forged Dates move the searches: a forged Date only moves an +/// article into another chunk. Empty (start past end) when the day's posts +/// are all in its neighbours. +pub async fn chunk_range( + pool: &Pool, + server: usize, + group: &str, + (first, last): (u64, u64), + day: i64, + (oldest_day, newest_day): (i64, i64), + cursor: u64, +) -> crate::nntp::Result<(u64, u64)> { + let starts = |day: i64| pool.article_at(server, group, first, last, day * 86_400 - CHUNK_OVERLAP); + if day <= oldest_day && day >= newest_day { + return Ok((first, cursor)); + } + let next = starts(day + 1).await?; + // a start past the next day's (forged Dates) is moved down to it + let start = if day <= oldest_day { first } else { starts(day).await?.min(next) }; + let end = if day >= newest_day { + cursor + } else { + let past = pool.article_at(server, group, first, last, (day + 1) * 86_400 + CHUNK_OVERLAP).await?; + next.max(past).saturating_sub(1) + }; + Ok((start, end)) +} + /// Whether `server`, whose first article of split `group` was posted at /// `oldest`, goes back furthest of the indexing servers: the one to index the /// split's oldest day. Found by asking each server for its first article the diff --git a/src/nntp.rs b/src/nntp.rs index 18d59005..5c43d890 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -886,10 +886,6 @@ fn plausible_post_time(date: &str) -> Option { (EARLIEST..=chrono::Utc::now().timestamp() + AHEAD).contains(&t).then_some(t) } -/// windows of `DATE_LOOK` numbers a day chunk reads on each side of the range -/// the date search found for it, for posts of that day the search missed -pub const DAY_CHECK_WINDOWS: u64 = 8; - /// numbers per date search request at first, and at most const DATE_LOOK: u64 = 100; const DATE_SCAN_MAX: u64 = DATE_LOOK << 6; @@ -1714,52 +1710,6 @@ impl Pool { Ok(rows.iter().find(|o| plausible_post_time(&o.date).is_some_and(|t| t >= when)).map(|o| o.number)) } - /// `start..=end` of `group` on server `i` (`low..=high` on the server) - /// widened to the articles posted in `from..to` among the - /// `DAY_CHECK_WINDOWS` windows of `DATE_LOOK` numbers before `start` and - /// after `end`. The date search takes post dates for ordered, which a run - /// of forged Dates can make it miss a day's posts by, even all of them: - /// this bounded look around the range finds those near it. - pub async fn widen_to_day( - &self, - i: usize, - group: &str, - (low, high): (u64, u64), - (start, end): (u64, u64), - (from, to): (i64, i64), - ) -> Result<(u64, u64)> { - let in_day = |rows: &[Overview]| -> Vec { - rows.iter() - .filter(|o| plausible_post_time(&o.date).is_some_and(|t| (from..to).contains(&t))) - .map(|o| o.number) - .collect() - }; - let (mut first, mut last) = (start, end); - let mut at = start; - for _ in 0..DAY_CHECK_WINDOWS { - if at <= low { - break; - } - let a = at.saturating_sub(DATE_LOOK).max(low); - if let Some(&n) = in_day(&self.listing(i, group, a, at - 1).await?).iter().min() { - first = first.min(n); - } - at = a; - } - let mut at = end.saturating_add(1).max(low); - for _ in 0..DAY_CHECK_WINDOWS { - if at > high { - break; - } - let b = at.saturating_add(DATE_LOOK - 1).min(high); - if let Some(&n) = in_day(&self.listing(i, group, at, b).await?).iter().max() { - last = last.max(n); - } - at = b + 1; - } - Ok((first, last)) - } - /// Compressed listings from server `i` couldnt be read: it gets plain ones from now on. fn no_compression(&self, i: usize, e: &str) { let server = &self.servers[i]; diff --git a/tests/date_search.rs b/tests/date_search.rs index b17fbfa0..36227ed1 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -64,7 +64,8 @@ fn a_day_chunk_indexes_that_day() { let day = atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-02T00:00:00+00:00").unwrap().timestamp()); let main_conn = atlas::db::open_at(&main).unwrap(); - atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + // a day between two others: the oldest and newest reach the marks + atlas::chunks::add(&main_conn, GROUP, day + 1, day - 1).unwrap(); let ctx = atlas::indexer::PassContext { pool: pool.pool.clone(), @@ -81,7 +82,7 @@ fn a_day_chunk_indexes_that_day() { // (24 and 49); 30 and 40 don't exist. 24..=49 minus 2 = 24 articles assert_eq!(saved.articles, 24); let conn = atlas::db::open_at(&main).unwrap(); - assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 3)); } /// posts `low..=high`, number n posted n - 1 hours after 2026-01-01 00:00 UTC, @@ -276,7 +277,8 @@ fn a_day_chunk_right_after_a_hole_of_millions_gets_every_article() { let day = atlas::chunks::unix_day(minute_of(3_000_001)); let main_conn = atlas::db::open_at(&main).unwrap(); - atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + // a day between two others: the oldest and newest reach the marks + atlas::chunks::add(&main_conn, GROUP, day + 1, day - 1).unwrap(); let ctx = atlas::indexer::PassContext { pool: pool.pool.clone(), states: Default::default(), @@ -291,7 +293,7 @@ fn a_day_chunk_right_after_a_hole_of_millions_gets_every_article() { // the day's 1,440 posts and the hour after it; the hour before is the hole assert_eq!(saved.articles, 1_440 + 60); let conn = atlas::db::open_at(&main).unwrap(); - assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 3)); } /// A day chunk whose day has 150 numbers missing in the middle still fetches @@ -320,7 +322,8 @@ fn a_day_chunk_skips_a_gap_inside_the_day() { let day = atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-02T00:00:00+00:00").unwrap().timestamp()); let main_conn = atlas::db::open_at(&main).unwrap(); - atlas::chunks::add(&main_conn, GROUP, day, day).unwrap(); + // a day between two others: the oldest and newest reach the marks + atlas::chunks::add(&main_conn, GROUP, day + 1, day - 1).unwrap(); let ctx = atlas::indexer::PassContext { pool: pool.pool.clone(), @@ -337,7 +340,7 @@ fn a_day_chunk_skips_a_gap_inside_the_day() { // (691..=720, 30 posts); nothing comes after 1440 assert_eq!(saved.articles, 720 - 150 + 30); let conn = atlas::db::open_at(&main).unwrap(); - assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 3)); } /// A chunk that fails and then cant be given back still reports why it @@ -1059,7 +1062,8 @@ fn chunks_save_every_post_of(list: &[Slot], days: &[i64]) { let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); pool.connect().unwrap(); let main_conn = atlas::db::open_at(&main).unwrap(); - atlas::chunks::add(&main_conn, GROUP, day, atlas::chunks::unix_day(list[0].1).min(day)).unwrap(); + // between two other days: the oldest and newest reach the marks + atlas::chunks::add(&main_conn, GROUP, day + 1, atlas::chunks::unix_day(list[0].1).min(day - 1)).unwrap(); let ctx = atlas::indexer::PassContext { pool: pool.pool.clone(), states: Default::default(), @@ -1179,9 +1183,121 @@ fn a_run_of_future_dates_doesnt_empty_the_day() { } /// A run of posts with Dates after the day but not in the future: the search -/// finds the day empty, the check around it still finds the day's posts. +/// finds the day empty, its posts are in the chunk next to it. #[test] fn a_run_of_later_dates_doesnt_empty_the_day() { let saved = chunk_of_jan_10(forged_run("Mon, 01 Jun 2026 00:00:00 +0000")); assert!((216..=240).all(|n| saved.contains(&n)), "the day's posts are missing: {saved:?}"); } + +/// posts 1..=23 hourly on 2026-01-01, 24..=2023 forged to 2026-06-01, then +/// 2024..=2047 hourly on 2026-01-02 and 2048..=2071 on 2026-01-03: the date +/// search for 2026-01-02 and 2026-01-03 both land on 24 +fn long_forged_run() -> Vec { + let mut list: Vec = (1..=23).map(|n| (n, jan_1() + n as i64 * 3600)).collect(); + list.extend((24..=2023).map(|n| (n, unix("2026-06-01T00:00:00+00:00")))); + list.extend((2024..=2071).map(|n| (n, jan_1() + 86_400 + (n as i64 - 2024) * 3600))); + list +} + +/// The numbers saved by indexing every day chunk of a split of `days` +/// (oldest first) over `list` on one server. +fn saved_by_every_chunk(list: &[Slot], days: std::ops::RangeInclusive) -> Vec { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let port = spawn_server(Server::new(slot_posts(list))); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + let main_conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&main_conn, GROUP, *days.end(), *days.start()).unwrap(); + let ctx = atlas::indexer::PassContext { + pool: pool.pool.clone(), + states: Default::default(), + stop: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), + verbose: false, + }; + let db = atlas::indexer::shared_db(main_conn); + for day in days.clone() { + let chunk = claimed(&main, GROUP, day); + pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); + } + let conn = atlas::db::open_with_shards(&main).unwrap(); + let total = days.end() - days.start() + 1; + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (total, total)); + let shard = atlas::store::shard_of(GROUP); + let mut q = conn.prepare(&format!("select subject from s{shard}.files")).unwrap(); + let mut saved: Vec = q + .query_map([], |r| r.get::<_, String>(0)) + .unwrap() + .map(|s| s.unwrap().trim_start_matches("\"p").split('.').next().unwrap().parse().unwrap()) + .collect(); + saved.sort(); + saved +} + +/// 2,000 forged later Dates in a row, more than any look around a day's +/// range reaches: every post of the split is still fetched by some chunk. +#[test] +fn a_long_run_of_later_dates_doesnt_lose_the_days_after_it() { + let list = long_forged_run(); + let day = atlas::chunks::unix_day(jan_1()); + let saved = saved_by_every_chunk(&list, day..=day + 2); + let missing: Vec = list.iter().map(|&(n, _)| n).filter(|n| !saved.contains(n)).collect(); + assert!(missing.is_empty(), "{} posts missing, from {:?}", missing.len(), missing.first()); +} + +/// Over posts with runs of forged Dates at random (earlier, later, and +/// future), the ranges of a split's day chunks leave no number from the +/// low mark to the high mark out. +#[test] +fn day_chunk_ranges_cover_every_number_whatever_the_forged_runs() { + let mut seed = 0x5eed_u64; + let mut next = |below: u64| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) % below + }; + for case in 0..60 { + // six days of posts 20 minutes apart, numbers 1 to 3 apart + let mut list: Vec = Vec::new(); + let (mut n, mut t) = (1 + next(50), jan_1()); + while t < jan_1() + 6 * 86_400 { + list.push((n, t)); + n += 1 + next(3); + t += 1200; + } + let (oldest_day, newest_day) = (atlas::chunks::unix_day(list[0].1), atlas::chunks::unix_day(t - 1)); + // up to four runs of forged Dates, up to 1,500 posts long + for _ in 0..=next(4) { + let (at, len) = (next(list.len() as u64) as usize, 1 + next(1500) as usize); + let forged = match next(3) { + 0 => unix("2025-03-01T00:00:00+00:00"), + 1 => jan_1() + next(6 * 86_400) as i64, + _ => unix("2035-01-01T00:00:00+00:00"), + }; + for slot in list.iter_mut().skip(at).take(len) { + slot.1 = forged; + } + } + + let port = spawn_server(Server::new(slot_posts(&list))); + let pool = BlockingPool::new(&[mock(port, "secret", 2, 1)]); + pool.connect().unwrap(); + let (low, high) = (list[0].0, list.last().unwrap().0); + let mut ranges: Vec<(u64, u64)> = (oldest_day..=newest_day) + .map(|day| { + let range = + atlas::indexer::chunk_range(&pool.pool, 0, GROUP, (low, high), day, (oldest_day, newest_day), high); + pool.block_on(range).unwrap() + }) + .filter(|(start, end)| start <= end) + .collect(); + ranges.sort(); + let mut covered = low - 1; + for (start, end) in ranges { + assert!(start <= covered + 1, "case {case}: {} to {} in no chunk", covered + 1, start - 1); + covered = covered.max(end); + } + assert_eq!(covered, high, "case {case}: the chunks stop short of the high mark"); + } +} From 7a8dfeec753f1bd0d456a977bb60338237466039 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:09:57 -0500 Subject: [PATCH 088/159] Shards without their main database are refused, not adopted With atlas.db gone and its shards still there, setting up made a new main database with nothing in it, took the shards as its own, and handed out their release ids again from the start, with every cursor and day chunk forgotten. A missing main database next to shards with anything in them is now refused, naming them: put it back, or delete the shards to start over. Co-Authored-By: Claude Opus 5.5 --- src/db.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/db.rs b/src/db.rs index 56b41d6b..510a832d 100644 --- a/src/db.rs +++ b/src/db.rs @@ -176,6 +176,9 @@ pub fn wipe(main: &Path) -> anyhow::Result<()> { /// columns) for convert.rs; until then there are no shards. Run with /// compaction held off, see `create_db_holding`. pub fn create_db_at(path: &Path) -> anyhow::Result<()> { + if !path.try_exists()? { + refuse_orphaned_shards(path)?; + } let conn = open_at(path)?; // wal soo the indexer can write while search reads @@ -209,6 +212,26 @@ pub fn create_db_at(path: &Path) -> anyhow::Result<()> { create_shards(path, used) } +/// Refuses shards with something in them when their main database `main` +/// isnt there: a new one would hand out their release ids again and start +/// the cursors and day chunks over. +fn refuse_orphaned_shards(main: &Path) -> anyhow::Result<()> { + let mut found = Vec::new(); + for shard in store::shard_paths(main) { + if fs::metadata(&shard).is_ok_and(|m| m.len() > 0) { + found.push(shard.display().to_string()); + } + } + if !found.is_empty() { + anyhow::bail!( + "{} is missing but its shards are there: {}. put the main database back from a backup, or delete these shard files to start over", + main.display(), + found.join(", ") + ); + } + Ok(()) +} + /// Whether the main database holds indexing progress: cursors or ids handed /// out for releases. The shards hold what those stand for. fn has_progress(conn: &Connection) -> Result { @@ -768,6 +791,25 @@ mod tests { create_db_at(&main).expect_err("ids were handed out"); } + #[test] + fn shards_without_their_main_database_are_refused() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + create_db_at(&main).unwrap(); + let release = + crate::parser::Release { name: "Kept".into(), group: "alt.binaries.a".into(), ..Default::default() }; + store::save(&main, &[release]).unwrap(); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", main.display())); + } + + // a new main database would hand the shards' ids out again + let err = format!("{:#}", create_db_at(&main).expect_err("the shards are in use")); + let shard = store::shard_path(&main, store::shard_of("alt.binaries.a")); + assert!(err.contains(&main.display().to_string()) && err.contains(&shard.display().to_string()), "{err}"); + assert!(!main.exists(), "no new main database made"); + } + #[test] fn a_main_database_with_nothing_in_it_gets_its_shards() { let dir = tempfile::tempdir().unwrap(); From 1288a5d41aed45063705317c97fa21a999f81d3d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:13:47 -0500 Subject: [PATCH 089/159] A row a full blob already has is dropped before the blob is counted A file whose blob held SEAL_MAX_SEGMENTS segments, with a row the blob already had (saved past a save's decode budget), never sealed: the cap was checked on the blob and the rows together before the copies were taken out, soo the copy stayed a row for good. Rows the blob already has are now deleted first, and only the rows left count against the cap. Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 55 insertions(+), 6 deletions(-) diff --git a/src/store.rs b/src/store.rs index 65b58874..6f5305a3 100644 --- a/src/store.rs +++ b/src/store.rs @@ -681,12 +681,12 @@ pub(crate) fn seal_file(conn: &Connection, file_id: i64) -> Result { fn seal_rows(conn: &Connection, file_id: i64) -> Result { let mut segs = sealed_segments(conn, file_id)?.unwrap_or_default(); - // too much for one blob in memory: stays rows, and a blob stays as it is - // (counted before any row is read) + // more rows than one blob takes: they stay rows, and a blob stays as it + // is (counted before any row is read) let counted: i64 = conn .prepare_cached("select count(*) from (select 1 from segments where file_id = ? limit ?)")? .query_row(params![file_id, SEAL_MAX_SEGMENTS + 1], |r| r.get(0))?; - if counted > 0 && counted + segs.len() as i64 > SEAL_MAX_SEGMENTS { + if counted > SEAL_MAX_SEGMENTS { return Ok(0); } let rows: Vec = conn @@ -708,10 +708,19 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { return Ok(0); } // a row the blob already has (saved past a save's decode budget, see - // `SealedCache`) isnt added twice + // `SealedCache`) isnt added twice: it goes, before the blob is counted, + // soo a full blob doesnt keep it a row let held: HashSet<(&[u8], i64)> = segs.iter().map(|s| (s.local.as_slice(), s.domain)).collect(); - let rows: Vec = - rows.into_iter().filter(|r| !held.contains(&(r.local.as_slice(), r.domain))).collect(); + let (copies, rows): (Vec, Vec) = + rows.into_iter().partition(|r| held.contains(&(r.local.as_slice(), r.domain))); + for copy in &copies { + conn.prepare_cached("delete from segments where file_id = ? and local = ? and domain = ?")? + .execute(params![file_id, copy.local, copy.domain])?; + } + // too much for one blob in memory: the rest stays rows, the blob as it is + if segs.len() + rows.len() > SEAL_MAX_SEGMENTS as usize { + return Ok(0); + } segs.extend(rows); conn.prepare_cached("update files set blob = ? where id = ?")? .execute(params![crate::blob::encode(&segs), file_id])?; @@ -1633,6 +1642,46 @@ mod tests { assert_eq!(seal_file(&conn, a).unwrap(), 3, "the copy isnt added"); } + /// A row a full blob already has is dropped, not left a row because + /// adding it would go past the cap. + #[test] + fn a_row_a_full_blob_already_has_is_dropped() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let a: i64 = conn.query_row("select id from files where filename = 'a.rar'", [], |r| r.get(0)).unwrap(); + seal_file(&conn, a).unwrap(); + let mut segs = sealed_segments(&conn, a).unwrap().unwrap(); + let first = segs[0].clone(); + let pad = (segs.len() as i64..SEAL_MAX_SEGMENTS).map(|p| crate::blob::Seg { + part: Some(100 + p), + bytes: 1, + domain: 0, + local: format!("pad{p}").into_bytes(), + }); + segs.extend(pad.collect::>()); + conn.execute("update files set blob = ? where id = ?", params![crate::blob::encode(&segs), a]).unwrap(); + let insert = |local: &[u8], domain: i64| { + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", + params![a, local, domain, first.part, first.bytes], + ) + .unwrap(); + }; + let rows = + || conn.query_row("select count(*) from segments where file_id = ?", [a], |r| r.get::<_, i64>(0)).unwrap(); + + insert(&first.local, first.domain); + assert_eq!(seal_file(&conn, a).unwrap(), SEAL_MAX_SEGMENTS as usize, "a full blob, the copy dropped"); + assert_eq!(rows(), 0); + + // with a new row too the blob is past the cap: the new one stays a row, the copy goes + insert(&first.local, first.domain); + insert(b"new", 0); + assert_eq!(seal_file(&conn, a).unwrap(), 0); + assert_eq!(rows(), 1); + assert_eq!(sealed_segments(&conn, a).unwrap().unwrap().len() as i64, SEAL_MAX_SEGMENTS); + } + #[test] fn sealed_nzb_is_byte_for_byte_the_same() { let dir = tempfile::tempdir().unwrap(); From 444e66b4805bf001c4cfefd930f862792fa75d27 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:32:42 -0500 Subject: [PATCH 090/159] A conversion's swap refuses a held back checkpoint, and atlas.old.db keeps its WAL Every wal_checkpoint(truncate) of the swap (new main, shards, the old database) now reads its result through compact's checkpoint: busy, or not every page folded in, fails the conversion with the old database left in place. The old database moves aside with its -wal and -shm instead of having them deleted. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 4 ++-- src/convert.rs | 26 +++++++++++++------------- tests/convert.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 15 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 64d5a942..ef42d06e 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -53,7 +53,7 @@ fn remove_db(path: &Path) { /// Fold the WAL of `conn`'s database into it, all of it: a checkpoint held /// back (a reader, a writer) leaves committed pages only in the WAL, soo it /// is an error rather than taken for done. -fn checkpoint(conn: &Connection) -> Result<()> { +pub(crate) fn checkpoint(conn: &Connection) -> Result<()> { let (busy, log, done): (i64, i64, i64) = conn.query_row("pragma wal_checkpoint(truncate)", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?; if busy != 0 || log != done { @@ -64,7 +64,7 @@ fn checkpoint(conn: &Connection) -> Result<()> { /// Rename the database `from` to `to`, its -wal and -shm with it (those /// there are): the WAL can hold committed pages of it. -fn rename_db(from: &Path, to: &Path) -> std::io::Result<()> { +pub(crate) fn rename_db(from: &Path, to: &Path) -> std::io::Result<()> { std::fs::rename(from, to)?; for suffix in ["-wal", "-shm"] { let (a, b) = (format!("{}{suffix}", from.display()), format!("{}{suffix}", to.display())); diff --git a/src/convert.rs b/src/convert.rs index 89800c03..527046d7 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -24,6 +24,7 @@ use std::time::Instant; use anyhow::{Context, Result, anyhow, bail}; use rusqlite::{Connection, OpenFlags, OptionalExtension, params}; +use crate::compact::{checkpoint, rename_db}; use crate::db; use crate::parser::Article; use crate::search::{ArticleRow, ReleaseRow}; @@ -119,33 +120,32 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { progress("converting the database: checking NZBs against the old database"); check(main, &old, max_id, &shard_of_old)?; - // 5. the swap + // 5. the swap. every checkpoint has to fold its whole WAL in: one held + // back (a reader, a writer) leaves committed pages only in the WAL { let conn = db::open_at(&new_main)?; store::set_next_seq(&conn, max_id + 1)?; - conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(()))?; + checkpoint(&conn).context("folding the new main database's WAL in")?; } for path in store::shard_paths(main) { let conn = db::open_at(&path)?; conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; - conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(()))?; + checkpoint(&conn).with_context(|| format!("folding {}'s WAL in", path.display()))?; } drop(old); let backup = sibling(main, "atlas.old.db"); remove_db(&backup); { - // fold the old wal in soo atlas.old.db is whole on its own + // fold the old wal in soo atlas.old.db is whole on its own. nothing + // else should have it open (the conversion runs alone), soo a short + // wait: whoever does keeps the old database in place let conn = db::open_at(main)?; - conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(()))?; - } - std::fs::rename(main, &backup).context("moving the old database aside")?; - for suffix in ["-wal", "-shm"] { - let _ = std::fs::remove_file(format!("{}{suffix}", main.display())); - } - std::fs::rename(&new_main, main).context("putting the new main database in place")?; - for suffix in ["-wal", "-shm"] { - let _ = std::fs::remove_file(format!("{}{suffix}", new_main.display())); + conn.busy_timeout(std::time::Duration::from_secs(5))?; + checkpoint(&conn).context("folding the old database's WAL in")?; } + // its -wal and -shm go aside with it, whatever they still hold + rename_db(main, &backup).context("moving the old database aside")?; + rename_db(&new_main, main).context("putting the new main database in place")?; progress(&format!( "converted {moved_releases} releases and {moved_articles} articles in {} ({orphans} articles without a release left out). \ diff --git a/tests/convert.rs b/tests/convert.rs index 0f97baa1..af4ed7c4 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -318,3 +318,36 @@ fn an_indexer_converting_at_start_runs_alone() { drop(indexing); assert_eq!(convert::run_alone(&main, &|_| {}).unwrap(), None); } + +/// The swap folds the old database's WAL in before moving it aside as +/// atlas.old.db; a checkpoint a reader holds back (committed pages left only +/// in the WAL) refuses the swap instead of leaving a backup missing them. +#[test] +fn a_swap_whose_checkpoint_is_held_back_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + db::create_db_at(&main).unwrap(); + + // a reader's snapshot keeps the write after it in the WAL + let writer = Connection::open(&main).unwrap(); + writer.execute_batch("pragma wal_autocheckpoint = 0").unwrap(); + let reader = Connection::open(&main).unwrap(); + reader.execute_batch("begin; select count(*) from releases").unwrap(); + writer.execute_batch("create table late (x); insert into late values (7)").unwrap(); + + let err = convert::run(&main, &|_| {}).unwrap_err(); + assert!(format!("{err:#}").contains("checkpoint"), "{err:#}"); + assert!(convert::needed(&main), "the old database is still in place"); + assert!(!dir.path().join("atlas.old.db").exists()); + + // once the reader is gone the swap goes through, and the backup has the late write + reader.execute_batch("commit").unwrap(); + drop((reader, writer)); + convert::run(&main, &|_| {}).unwrap(); + let late: i64 = Connection::open(dir.path().join("atlas.old.db")) + .unwrap() + .query_row("select x from late", [], |r| r.get(0)) + .unwrap(); + assert_eq!(late, 7); +} From 2858351eed76e1121ba63c6d6a044532031a82bb Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:36:48 -0500 Subject: [PATCH 091/159] Compaction drops a loose row its file's blob already has Before a sealed file's loose rows are counted against the cap and appended to its blob, the ones with a (local, domain) the blob already holds go, the way seal_rows drops them, instead of becoming a permanent second copy. The copy's check allows for the dropped copies: the article count is the original's less them, and a sampled release may differ only by them. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 70 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 7 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index ef42d06e..1d9f4d62 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -18,6 +18,7 @@ //! between moving the original aside and the copy in (a crash) is undone by //! the next start or compaction, see `recover_cut_swaps`. +use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -445,7 +446,8 @@ fn compact_shard( halt(stop, shard)?; say(&format!("copying files and articles ({kept} shared domains, dropping {dropped}), sealing those due")); let now = chrono::Utc::now().timestamp(); - let (mut copied, mut sealed) = (0i64, 0i64); + // rows dropped as copies of what their file's blob already has + let (mut copied, mut sealed, mut copies) = (0i64, 0i64, 0i64); { let open = || Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY); let (files_read, rows_read) = (open()?, open()?); @@ -498,6 +500,15 @@ fn compact_shard( segs.push(Seg { local, domain, ..seg }); } + // a row the blob already has (the same message-id) isnt copied: + // it goes before the blob is counted, the way `seal_rows` drops it + if !segs.is_empty() { + let held: HashSet<(&[u8], i64)> = segs.iter().map(|s| (s.local.as_slice(), s.domain)).collect(); + let had = file_rows.len(); + file_rows.retain(|r| !held.contains(&(r.local.as_slice(), r.domain))); + copies += (had - file_rows.len()) as i64; + } + // rows a blob cant hold exactly (a negative part, no size) stay rows let fits = file_rows.iter().all(|r| r.part.is_none_or(|p| p >= 0) && r.bytes.is_some()); let seen: Vec = f.get(8)?; @@ -567,7 +578,7 @@ fn compact_shard( // the check: same rows, same NZBs halt(stop, shard)?; say("checking"); - check(&path, ©, shard, copied, stop)?; + check(&path, ©, shard, copied, copies, stop)?; // swap: the last point to stop at halt(stop, shard)?; @@ -661,9 +672,10 @@ fn insert_row(conn: &Connection, r: &Row) -> Result<()> { } /// The copy holds the same releases, files and articles (rows and inside -/// blobs) as the original, and a sample of releases build the same NZBs from +/// blobs) as the original, less the `copies` rows that were copies of what +/// their blob already had, and a sample of releases build the same NZBs from /// both. -fn check(original: &Path, copy: &Path, shard: usize, copied: i64, stop: &Arc) -> Result<()> { +fn check(original: &Path, copy: &Path, shard: usize, copied: i64, copies: i64, stop: &Arc) -> Result<()> { let attach = |path: &Path| -> Result { let conn = Connection::open_in_memory()?; interruptible(&conn, stop)?; @@ -682,8 +694,10 @@ fn check(original: &Path, copy: &Path, shard: usize, copied: i64, stop: &Arc 0 && same_but_copies(&a, &b)) { bail!("shard {shard}: release {id} reads back differently from the copy; the original was kept"); } } Ok(()) } +/// `copy` is `original` with only rows dropped that were a second copy of a +/// message-id (the one kept is one of the original's). +fn same_but_copies(original: &[crate::search::ArticleRow], copy: &[crate::search::ArticleRow]) -> bool { + fn ids(rows: &[crate::search::ArticleRow]) -> HashSet<&str> { + rows.iter().map(|r| r.message_id.as_str()).collect() + } + let kept = ids(copy); + kept.len() == copy.len() && kept == ids(original) && copy.iter().all(|r| original.contains(r)) +} + #[cfg(test)] mod tests { use super::*; @@ -1071,6 +1095,38 @@ mod tests { assert_eq!(blob_segs_with_known_domains(&main).len() as i64, count); } + /// A loose row a sealed file's blob already has (same message-id) goes + /// when compaction seals the file, instead of becoming a second copy in + /// the blob for good. + #[test] + fn compacting_drops_a_loose_row_its_blob_already_has() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}, &no_stop()).unwrap(); + let before = all_articles(&main); + let count = article_total(&main); + + let (path, file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + { + let conn = db::open_at(&path).unwrap(); + let blob: Vec = conn.query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + let seg = crate::blob::decode(&blob).unwrap().remove(0); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", + params![file, seg.local, seg.domain, seg.part, seg.bytes], + ) + .unwrap(); + conn.execute("update files set touched_at = 0 where id = ?", [file]).unwrap(); + } + assert_eq!(article_total(&main), count + 1); + + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(article_total(&main), count, "the copy went, not into the blob"); + assert_eq!(loose(&main), 0); + assert_eq!(all_articles(&main), before, "every NZB reads back the same"); + } + #[test] fn a_file_over_the_cap_is_copied_as_rows_and_its_nzb_is_the_same() { let dir = tempfile::tempdir().unwrap(); From cfe1640d33926ce370b1efd1e3420795328cae2b Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:40:33 -0500 Subject: [PATCH 092/159] A max_unsaved_headers past the pool's limit doesnt restart the indexer every reload Config's max_unsaved_headers() now goes through the same clamp the pool applies (nntp::unsaved_cap), soo the config reload compares like with like instead of seeing a change every 5s for a value above the semaphore's max. Co-Authored-By: Claude Opus 5.5 --- src/config.rs | 17 ++++++++++++++--- src/nntp.rs | 9 ++++++++- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/src/config.rs b/src/config.rs index 8e4f0341..6c05da67 100644 --- a/src/config.rs +++ b/src/config.rs @@ -209,10 +209,11 @@ impl Config { self.request_size.unwrap_or(DEFAULT_REQUEST_SIZE).max(1) } - /// headers the indexer fetches ahead of saving them, over every group at once + /// headers the indexer fetches ahead of saving them, over every group at + /// once: what the pool takes of the setting (`nntp::unsaved_cap`) pub fn max_unsaved_headers(&self) -> usize { - let n = self.max_unsaved_headers.unwrap_or(DEFAULT_MAX_UNSAVED_HEADERS).max(1); - usize::try_from(n).unwrap_or(usize::MAX) + let n = self.max_unsaved_headers.unwrap_or(DEFAULT_MAX_UNSAVED_HEADERS); + crate::nntp::unsaved_cap(usize::try_from(n).unwrap_or(usize::MAX)) } /// article numbers of backfill left before a group's backfill is split @@ -675,6 +676,16 @@ mod tests { assert_eq!(cfg(json!({"max_unsaved_headers": -5})), DEFAULT_MAX_UNSAVED_HEADERS as usize); } + /// A cap past what the pool can hold reads as what the pool holds, soo + /// the config reload (which compares the two) doesnt see a change every + /// time it looks. + #[test] + fn a_max_unsaved_headers_past_the_pools_limit_reads_as_the_pools_cap() { + let cfg = Config::from_value(&json!({"max_unsaved_headers": 1u64 << 62})); + let pool = crate::nntp::Pool::new(&[]).with_max_unsaved(cfg.max_unsaved_headers()); + assert_eq!(cfg.max_unsaved_headers(), pool.max_unsaved()); + } + #[test] fn multiple_servers_sorted_by_priority() { let v = json!({ diff --git a/src/nntp.rs b/src/nntp.rs index 5c43d890..8044b056 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -925,9 +925,16 @@ struct UnsavedBudget { peak: AtomicUsize, } +/// The unsaved headers cap a pool takes for `headers`: at least one, at +/// most what its semaphore holds. Config reads through this too, soo what it +/// asks for compares equal to what the pool has. +pub fn unsaved_cap(headers: usize) -> usize { + headers.clamp(1, Semaphore::MAX_PERMITS.min(u32::MAX as usize)) +} + impl UnsavedBudget { fn new(cap: usize) -> Arc { - let cap = cap.clamp(1, Semaphore::MAX_PERMITS.min(u32::MAX as usize)); + let cap = unsaved_cap(cap); Arc::new(UnsavedBudget { permits: Arc::new(Semaphore::new(cap)), cap, From 8cfa93daeb17568f3b8ac594c68f43999f84cc7b Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:58:47 -0500 Subject: [PATCH 093/159] A server's retention is judged from its first windows, and old days are the deepest's A forged Date on a carrier's first article (later or earlier than the truth) made it look shallower or deeper than it is: the deepest server could lose its history to a shorter one, or a shallow one finish days it doesnt keep. Pool::retention reads the first 3 windows of 100 numbers and takes each window's earliest date not more than a day before its 4th, the earliest of those answering; windows more than a day out of order make it unsure. An unsure carrier declines the split for now and ranks after the sure ones for going back furthest. The second furthest server's retention is kept with the furthest (backfill_deepest.runner_up_at): a day older than it is done by the furthest one alone. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 35 ++++++++++- src/indexer.rs | 122 ++++++++++++++++++++++++++---------- src/nntp.rs | 90 ++++++++++++++++++++++++++ tests/date_search.rs | 14 ++++- tests/split_forged_early.rs | 98 +++++++++++++++++++++++++++++ tests/split_forged_late.rs | 87 +++++++++++++++++++++++++ 6 files changed, 409 insertions(+), 37 deletions(-) create mode 100644 tests/split_forged_early.rs create mode 100644 tests/split_forged_late.rs diff --git a/src/chunks.rs b/src/chunks.rs index f0fbf263..5f351e0c 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -28,11 +28,13 @@ pub fn create(conn: &Connection) -> Result<()> { create table if not exists backfill_deepest ( grp TEXT PRIMARY KEY, server TEXT NOT NULL, - oldest_at INTEGER + oldest_at INTEGER, + runner_up_at INTEGER ) without rowid;", )?; add_column(conn, "backfill_chunks", "done_at")?; - add_column(conn, "backfill_deepest", "oldest_at") + add_column(conn, "backfill_deepest", "oldest_at")?; + add_column(conn, "backfill_deepest", "runner_up_at") } /// Give `table` the INTEGER column `column` if a table made before it lacks it. @@ -214,6 +216,22 @@ pub fn set_deepest(conn: &Connection, group: &str, server: &str, oldest_at: i64) Ok(()) } +/// Note how far back the server going back second furthest on `group` +/// goes (unix seconds): days before it are the furthest one's alone. +pub fn set_runner_up(conn: &Connection, group: &str, runner_up_at: i64) -> Result<()> { + conn.execute("update backfill_deepest set runner_up_at = ? where grp = ?", params![runner_up_at, group])?; + Ok(()) +} + +/// How far back the server going back second furthest on `group` goes +/// (unix seconds), when noted with the furthest one. +pub fn runner_up(conn: &Connection, group: &str) -> Result> { + Ok(conn + .query_row("select runner_up_at from backfill_deepest where grp = ?", [group], |r| r.get(0)) + .optional()? + .flatten()) +} + /// Forget `server` as the one going back furthest on `group`, when it no /// longer carries it or no longer keeps the oldest day: the next to reach /// the oldest day asks again. @@ -239,6 +257,19 @@ mod tests { c } + /// the second furthest server's retention is kept with the furthest, + /// and goes with it + #[test] + fn the_runner_up_is_kept_with_the_deepest() { + let c = conn(); + set_deepest(&c, "g", "a", 100).unwrap(); + assert_eq!(runner_up(&c, "g").unwrap(), None); + set_runner_up(&c, "g", 200).unwrap(); + assert_eq!(runner_up(&c, "g").unwrap(), Some(200)); + forget_deepest(&c, "g", "a").unwrap(); + assert_eq!(runner_up(&c, "g").unwrap(), None); + } + /// the day of a claim fn day(claimed: Result>) -> Option { claimed.unwrap().map(|c| c.day) diff --git a/src/indexer.rs b/src/indexer.rs index 8a73cc11..108a8728 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -9,7 +9,7 @@ use rusqlite::Connection; use crate::config::{DEFAULT_BATCH_SIZE, DEFAULT_REQUEST_SIZE}; use crate::db; use crate::nfo; -use crate::nntp::{BlockingPool, Extract, Overview, Pool, first_names, headers_to_articles}; +use crate::nntp::{BlockingPool, Extract, Overview, Pool, Retention, first_names, headers_to_articles}; use crate::par2; use crate::parser::{Release, group_articles, is_complete}; @@ -577,10 +577,20 @@ async fn split_days( (first, last): (u64, u64), newest: Newest, ) -> Result> { - // the oldest day is at least home's first article. first articles are + // the oldest day is at least home's retention. first articles are // searched for from the low marks, which can lag far behind what a - // server still keeps - let Some(home_oldest) = ctx.pool.first_post(home, group, first, last).await? else { return Ok(None) }; + // server still keeps. a server whose first dates disagree (forged) could + // be deeper or shallower than it looks: no split until it can be told + let unsure = + || println!("[SPLIT] {group}: first post dates that disagree (forged Date headers?), not split for now"); + let home_oldest = match ctx.pool.retention(home, group, first, last).await? { + Retention::Since(t) => t, + Retention::Empty => return Ok(None), + Retention::Unsure(_) => { + unsure(); + return Ok(None); + } + }; let mut oldest_at = home_oldest; // other servers are best effort: one that fails is left out. one that @@ -589,8 +599,13 @@ async fn split_days( for other in ctx.pool.indexing_servers().into_iter().filter(|&s| s != home) { let Ok((_, low, high, _)) = ctx.pool.group_on(other, group).await else { continue }; carriers += 1; - if let Ok(Some(t)) = ctx.pool.first_post(other, group, low, high).await { - oldest_at = oldest_at.min(t); + match ctx.pool.retention(other, group, low, high).await { + Ok(Retention::Since(t)) => oldest_at = oldest_at.min(t), + Ok(Retention::Unsure(_)) => { + unsure(); + return Ok(None); + } + Ok(Retention::Empty) | Err(_) => {} } } if carriers < 2 { @@ -801,12 +816,27 @@ where // the server takes no day that old for a while. the split's oldest day is // the exception: no server keeps it whole, the one that goes back // furthest on it does what there is - let oldest = match ctx.pool.first_post(server, group, first, last).await { - Ok(oldest) => oldest, + // (whether its first dates agree: see `goes_back_furthest`) + let (oldest, sure) = match ctx.pool.retention(server, group, first, last).await { + Ok(Retention::Since(t)) => (Some(t), true), + Ok(Retention::Unsure(t)) => (Some(t), false), + Ok(Retention::Empty) => (None, true), Err(e) => return failed(e.into()).await, }; + // from when the server is taken to keep days whole + let mut keeps_from = oldest; let keeps_day = match oldest { - Some(t) if t <= day * 86_400 => true, + // a day older than the second furthest server goes back is the + // furthest one's alone: a server only looks deep enough by the dates + // its posters set + Some(t) if t <= day * 86_400 => match goes_back_furthest(ctx, db, group, server, (t, sure)).await { + Ok((true, _)) => true, + Ok((false, runner_up)) => { + keeps_from = keeps_from.max(runner_up); + runner_up.is_none_or(|r| r <= day * 86_400) + } + Err(e) => return failed(e).await, + }, Some(t) if crate::chunks::unix_day(t) == day => { let g = group.to_string(); let split_oldest = match on_db(db, move |conn| Ok(crate::chunks::oldest_day(conn, &g)?)).await { @@ -816,8 +846,8 @@ where if split_oldest != Some(day) { false } else { - match goes_back_furthest(ctx, db, group, server, t).await { - Ok(furthest) => furthest, + match goes_back_furthest(ctx, db, group, server, (t, sure)).await { + Ok((furthest, _)) => furthest, Err(e) => return failed(e).await, } } @@ -826,7 +856,7 @@ where }; if !keeps_day { // the first day it keeps whole - let oldest_day = oldest.map_or(i64::MAX, |t| crate::chunks::unix_day(t - 1) + 1); + let oldest_day = keeps_from.map_or(i64::MAX, |t| crate::chunks::unix_day(t - 1) + 1); let host = ctx.pool.host(server); ctx.states.keep_from(group, &host, oldest_day); println!("[CHUNK] {group} day {day} is older than {host} keeps, leaving it to the other servers"); @@ -910,40 +940,66 @@ pub async fn chunk_range( Ok((start, end)) } -/// Whether `server`, whose first article of split `group` was posted at -/// `oldest`, goes back furthest of the indexing servers: the one to index the -/// split's oldest day. Found by asking each server for its first article the -/// first time, then kept, soo it doesnt move as retention rolls on (asked -/// again once that server is no longer an indexing one, no longer carries -/// the group, or no longer keeps the day: `index_chunk` forgets it on a 411 -/// or a day older than it keeps). A server that -/// cant be asked fails it: the chunk goes back and is tried again later. -async fn goes_back_furthest(ctx: &PassContext, db: &Db, group: &str, server: usize, oldest: i64) -> Result { +/// Whether `server`, which keeps split `group` from `oldest` (see +/// `Pool::retention`; with whether its first dates agree), goes back furthest of the indexing servers: the one to +/// index the split's oldest day, and the days before the second furthest +/// goes back to (returned with it, when there is one). Found by asking each +/// server how far back it keeps the group the first time, then kept, soo it +/// doesnt move as retention rolls on (asked again once that server is no +/// longer an indexing one, no longer carries the group, or no longer keeps +/// the day: `index_chunk` forgets it on a 411 or a day older than it keeps). +/// A server whose first dates disagree goes back furthest only when every +/// one's do: a forged run could make it look deeper than it is. A server +/// that cant be asked fails it: the chunk goes back and is tried again later. +async fn goes_back_furthest( + ctx: &PassContext, + db: &Db, + group: &str, + server: usize, + oldest: (i64, bool), +) -> Result<(bool, Option)> { let host = ctx.pool.host(server); let servers = ctx.pool.indexing_servers(); let g = group.to_string(); - let known = on_db(db, move |conn| Ok(crate::chunks::deepest(conn, &g)?)).await?; - if let Some(deepest) = known.filter(|h| servers.iter().any(|&i| ctx.pool.host(i) == *h)) { - return Ok(deepest == host); + let known = + on_db(db, move |conn| Ok((crate::chunks::deepest(conn, &g)?, crate::chunks::runner_up(conn, &g)?))).await?; + if let (Some(deepest), runner_up) = known + && servers.iter().any(|&i| ctx.pool.host(i) == deepest) + { + return Ok((deepest == host, runner_up)); } - let mut deepest = (oldest, host.clone()); + // every carrier's (whether unsure, since, host) + let mut found = vec![(!oldest.1, oldest.0, host.clone())]; for other in servers.into_iter().filter(|&i| i != server) { let (_, low, high, _) = match ctx.pool.group_on(other, group).await { Ok(info) => info, Err(e) if e.code() == Some(411) => continue, Err(e) => return Err(e.into()), }; - if let Some(t) = ctx.pool.first_post(other, group, low, high).await? - && t < deepest.0 - { - deepest = (t, ctx.pool.host(other)); + match ctx.pool.retention(other, group, low, high).await? { + Retention::Since(t) => found.push((false, t, ctx.pool.host(other))), + Retention::Unsure(t) => found.push((true, t, ctx.pool.host(other))), + Retention::Empty => {} } } - let (g, (since, d)) = (group.to_string(), deepest.clone()); - on_db(db, move |conn| Ok(crate::chunks::set_deepest(conn, &g, &d, since)?)).await?; - println!("[CHUNK] {group}: {} goes back furthest, it does the oldest day", deepest.1); - Ok(deepest.1 == host) + // the deepest of those whose dates agree, a tie to `server` (asked + // first); the days before the next deepest (by the same order) are its + // alone + found.sort_by_key(|(unsure, t, h)| (*unsure, *t, *h != host)); + let (_, since, deepest) = found.remove(0); + let runner_up = found.first().map(|(_, t, _)| *t); + let (g, d) = (group.to_string(), deepest.clone()); + on_db(db, move |conn| { + crate::chunks::set_deepest(conn, &g, &d, since)?; + if let Some(r) = runner_up { + crate::chunks::set_runner_up(conn, &g, r)?; + } + Ok(()) + }) + .await?; + println!("[CHUNK] {group}: {deepest} goes back furthest, it does the oldest day"); + Ok((deepest == host, runner_up)) } struct Pass<'a> { diff --git a/src/nntp.rs b/src/nntp.rs index 8044b056..a6a16a35 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -886,6 +886,47 @@ fn plausible_post_time(date: &str) -> Option { (EARLIEST..=chrono::Utc::now().timestamp() + AHEAD).contains(&t).then_some(t) } +/// windows of `DATE_LOOK` numbers from a server's first article that judge +/// how far back it keeps a group (`Pool::retention`) +const RETENTION_WINDOWS: u64 = 3; +/// Dates of a window passed over as forged before its earliest counts +const RETENTION_OUTLIERS: usize = 3; + +/// How far back a server keeps a group. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Retention { + /// it has no articles of it + Empty, + /// from about this time (unix seconds) + Since(i64), + /// its first articles' dates disagree too much to tell (a forged run, or + /// dates far out of order): from about this time, if they can be trusted + Unsure(i64), +} + +/// When a window of articles (`dates` sorted) starts: its earliest date not +/// more than a day before the one `RETENTION_OUTLIERS` places in, soo that +/// many forged far older Dates dont move it, nor does one forged later. +fn window_start(dates: &[i64]) -> i64 { + let floor = dates[RETENTION_OUTLIERS.min(dates.len() - 1)] - 86_400; + dates.iter().copied().find(|&d| d >= floor).unwrap_or(floor + 86_400) +} + +/// A server's retention from the date each of its first windows counts by, +/// in number order, and the date of its first article (`first`, +/// when no window had a date to go by). +fn retention_of(windows: &[i64], first: i64) -> Retention { + let since = windows.iter().copied().min().unwrap_or(first); + let mut newest = i64::MIN; + for &q in windows { + if q < newest.saturating_sub(86_400) { + return Retention::Unsure(since); + } + newest = newest.max(q); + } + Retention::Since(since) +} + /// numbers per date search request at first, and at most const DATE_LOOK: u64 = 100; const DATE_SCAN_MAX: u64 = DATE_LOOK << 6; @@ -1654,6 +1695,34 @@ impl Pool { Ok(self.first_in(i, group, low, high + 1).await?.map(|(_, t)| t)) } + /// How far back server `i` keeps the group (unix seconds), judged from + /// the dates of its first `RETENTION_WINDOWS` windows of `DATE_LOOK` + /// numbers rather than from its first Date alone: posters set their own, + /// and one forged on the first article (later or earlier than the truth) + /// would make the server look shallower or deeper than it is. Each + /// window counts from its earliest date that isnt an outlier (see + /// `window_start`), the earliest of those answers. Unsure when the windows disagree (one + /// more than a day older than an earlier one): a forged run, or dates too + /// far out of order to judge by. `low` and `high` are the server's marks. + pub async fn retention(&self, i: usize, group: &str, low: u64, high: u64) -> Result { + let Some((first, t)) = self.first_in(i, group, low, high + 1).await? else { return Ok(Retention::Empty) }; + let mut earliest = Vec::new(); + for w in 0..RETENTION_WINDOWS { + let from = first + w * DATE_LOOK; + if from > high { + break; + } + let rows = self.listing(i, group, from, (from + DATE_LOOK - 1).min(high)).await?; + let mut dates: Vec = rows.iter().filter_map(|o| plausible_post_time(&o.date)).collect(); + if dates.is_empty() { + continue; + } + dates.sort_unstable(); + earliest.push(window_start(&dates)); + } + Ok(retention_of(&earliest, t)) + } + /// The first article number in `low..=high` on server `i` posted at or after /// `when` (unix seconds), `high + 1` when there is none. A binary search over /// small article requests (about 35 for a billion numbers); a probe that @@ -2193,6 +2262,27 @@ pub fn yenc_decode(lines: &[Vec]) -> Option> { #[cfg(test)] mod tests { + /// the dates the first windows count by judge a server's retention: the earliest + /// answers, and one more than a day older than an earlier one is unsure + #[test] + fn retention_from_the_first_windows() { + use super::{Retention, retention_of}; + assert_eq!(retention_of(&[], 50), Retention::Since(50), "no dates: the first article's"); + assert_eq!(retention_of(&[1_000, 2_000, 90_000], 7), Retention::Since(1_000)); + assert_eq!(retention_of(&[1_000, 500, 2_000], 7), Retention::Since(500), "within a day out of order"); + assert_eq!(retention_of(&[200_000, 300_000, 100_000], 7), Retention::Unsure(100_000)); + assert_eq!(retention_of(&[200_000, 100_000], 7), Retention::Unsure(100_000)); + } + + /// a window starts at its earliest date, unless a few are far before the rest + #[test] + fn a_window_starts_at_its_earliest_date_but_a_forged_one() { + use super::window_start; + assert_eq!(window_start(&[10, 3_600, 7_200, 10_800, 14_400]), 10); + assert_eq!(window_start(&[10, 900_000, 900_100, 900_200, 900_300]), 900_000, "one forged far back"); + assert_eq!(window_start(&[5]), 5); + } + use super::*; use tokio::io::AsyncWriteExt; diff --git a/tests/date_search.rs b/tests/date_search.rs index 36227ed1..ad7c73ea 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -736,7 +736,12 @@ fn a_split_reaches_back_when_a_deeper_server_joins() { conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() }; assert_eq!(state(day0 + 5), 0, "the old oldest day is to do again"); - assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap(), None, "the deepest server is asked again"); + // asked again (a chunk the pass ran asks who keeps the day): the new one + assert_eq!( + atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), + Some("localhost"), + "the deepest server is asked again" + ); // and the new days get indexed: the new oldest by the server that has it for day in [day0 + 4, day0] { @@ -973,7 +978,12 @@ fn a_split_redoes_its_oldest_day_when_a_server_goes_back_further_in_it() { pool.block_on(atlas::indexer::run_pass(&ctx(), &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); assert_eq!(atlas::chunks::oldest_day(&conn, GROUP).unwrap(), Some(day0), "no older day"); assert_eq!(state(day0), 0, "the oldest day is to do again"); - assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap(), None, "the deepest server is asked again"); + // asked again (a chunk the pass ran asks who keeps the day): the new one + assert_eq!( + atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), + Some("localhost"), + "the deepest server is asked again" + ); assert_eq!(run_day(day0, 1).articles, 24, "01:00 to midnight and the hour after"); assert_eq!(state(day0), 2); } diff --git a/tests/split_forged_early.rs b/tests/split_forged_early.rs new file mode 100644 index 00000000..b558938d --- /dev/null +++ b/tests/split_forged_early.rs @@ -0,0 +1,98 @@ +//! A split group on two servers, the one that keeps only the last 10 of 30 +//! days with a forged Date on its first article (days before anything the +//! other keeps): it doesnt pass for going back furthest, finishes no day it +//! doesnt keep, and every day of the other server is indexed. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset`, +/// only those from day `from_day` on +fn posts(offset: u64, from_day: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (from_day * 40..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn a_forged_early_date_on_a_shallow_servers_first_article_loses_no_days() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + // "127.0.0.1" keeps all 30 days; "localhost" the last 10, its first + // article dated five days before the first of them all + let long = Server::new(posts(1, 0)); + let mut short_posts = posts(500_001, 20); + short_posts[0].date = "Sat, 27 Dec 2025 00:00:00 +0000".into(); + let short = Server::new(short_posts); + let (pl, ps) = (spawn_server(long), spawn_server(short)); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pl, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": ps, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(120); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + if total > 0 && done == total { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); + let first_short_day = + atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-21T00:00:00+00:00").unwrap().timestamp()); + let old_by_short: i64 = conn + .query_row( + "select count(*) from backfill_chunks where server = 'localhost' and day < ?", + [first_short_day], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(old_by_short, 0, "the short server finished no day it doesnt keep"); +} diff --git a/tests/split_forged_late.rs b/tests/split_forged_late.rs new file mode 100644 index 00000000..3f664358 --- /dev/null +++ b/tests/split_forged_late.rs @@ -0,0 +1,87 @@ +//! A split group on two servers, the one that keeps all 30 days with a +//! forged Date on its first article (days later than the truth): it still +//! counts as going back furthest, and every one of its days is indexed. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset`, +/// only those from day `from_day` on +fn posts(offset: u64, from_day: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (from_day * 40..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn a_forged_late_date_on_the_deepest_servers_first_article_loses_no_days() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + // "127.0.0.1" keeps all 30 days, its first article dated day 25; + // "localhost" keeps the last 20 + let mut long_posts = posts(1, 0); + long_posts[0].date = "Mon, 26 Jan 2026 00:00:00 +0000".into(); + let long = Server::new(long_posts); + let short = Server::new(posts(500_001, 10)); + let (pl, ps) = (spawn_server(long), spawn_server(short)); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pl, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": ps, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(120); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + if total > 0 && done == total { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); +} From fc1f14def478ad07aed636d2b72365b2407c8679 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:10:20 -0500 Subject: [PATCH 094/159] A day chunk reaches 5,000 numbers past each end for neighbours done elsewhere Neighbouring day chunks done on different servers each search their own numbering, and around a hole a run of forged Dates can move the two searches differently, leaving articles in neither. chunk_range now also reaches CHUNK_SAFETY (5,000) article numbers past each end its date searches put it at, within first..cursor; what a neighbour has too is dropped as a duplicate when saved. A forged run moving a search by more than that can still leave a gap (noted at chunk_range). PassSettings carries the reach soo tests of exact day ranges can turn it off. Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 1 + src/indexer.rs | 30 +++++++++--- tests/date_search.rs | 110 +++++++++++++++++++++++++++++++++++-------- tests/save_memory.rs | 9 +++- tests/unsaved_cap.rs | 1 + 5 files changed, 122 insertions(+), 29 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 2fd2e01e..ae957f24 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -236,6 +236,7 @@ fn settings_of(config: &Config) -> PassSettings { batch_size: config.batch_size() as i64, request_size: config.request_size(), split_min_backlog: config.split_min_backlog(), + chunk_safety: crate::indexer::CHUNK_SAFETY, } } diff --git a/src/indexer.rs b/src/indexer.rs index 108a8728..6301646b 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -130,6 +130,8 @@ pub struct PassSettings { pub request_size: u64, /// backfill left on a group's home server before it is split into day chunks pub split_min_backlog: i64, + /// article numbers a day chunk reaches past its ends (`CHUNK_SAFETY`) + pub chunk_safety: u64, } impl Default for PassSettings { @@ -139,6 +141,7 @@ impl Default for PassSettings { batch_size: DEFAULT_BATCH_SIZE as i64, request_size: DEFAULT_REQUEST_SIZE, split_min_backlog: crate::config::SPLIT_MIN_BACKLOG, + chunk_safety: CHUNK_SAFETY, } } } @@ -713,6 +716,10 @@ pub async fn claim_chunk( /// roughly in article number order, duplicates are dropped when saved pub const CHUNK_OVERLAP: i64 = 3600; +/// article numbers a day chunk reaches past each end its date searches put +/// it at, for neighbouring days done on other servers (see `chunk_range`) +pub const CHUNK_SAFETY: u64 = 5_000; + /// Index the day chunk `chunk` claimed (its day in unix days) on `server`, /// for a group whose backfill is split into day chunks (see chunks.rs). The /// chunk is marked done when the whole day is in, released again if stopped @@ -882,10 +889,11 @@ where Ok((None, _)) => return failed(anyhow!("{group} has no day chunks")).await, Err(e) => return failed(e).await, }; - let (start, end) = match chunk_range(&ctx.pool, server, group, (first, last), day, days, cursor).await { - Ok(range) => range, - Err(e) => return failed(e.into()).await, - }; + let (start, end) = + match chunk_range(&ctx.pool, server, group, (first, last), day, days, (cursor, settings.chunk_safety)).await { + Ok(range) => range, + Err(e) => return failed(e.into()).await, + }; if start > end { finish().await?; return Ok(Progress::default()); @@ -915,6 +923,14 @@ where /// however forged Dates move the searches: a forged Date only moves an /// article into another chunk. Empty (start past end) when the day's posts /// are all in its neighbours. +/// +/// That holds on one server; neighbouring days done on different servers +/// search their own numbering, and around a hole a run of forged Dates can +/// move the two searches differently, leaving articles in neither. Each end +/// also reaches `safety` (`CHUNK_SAFETY`) numbers past where its search put it (the +/// articles a neighbour has too are dropped as duplicates when saved): a +/// shift up to that many articles is covered, a forged run moving a search +/// further can still leave a gap. pub async fn chunk_range( pool: &Pool, server: usize, @@ -922,7 +938,7 @@ pub async fn chunk_range( (first, last): (u64, u64), day: i64, (oldest_day, newest_day): (i64, i64), - cursor: u64, + (cursor, safety): (u64, u64), ) -> crate::nntp::Result<(u64, u64)> { let starts = |day: i64| pool.article_at(server, group, first, last, day * 86_400 - CHUNK_OVERLAP); if day <= oldest_day && day >= newest_day { @@ -930,12 +946,12 @@ pub async fn chunk_range( } let next = starts(day + 1).await?; // a start past the next day's (forged Dates) is moved down to it - let start = if day <= oldest_day { first } else { starts(day).await?.min(next) }; + let start = if day <= oldest_day { first } else { starts(day).await?.min(next).saturating_sub(safety).max(first) }; let end = if day >= newest_day { cursor } else { let past = pool.article_at(server, group, first, last, (day + 1) * 86_400 + CHUNK_OVERLAP).await?; - next.max(past).saturating_sub(1) + next.max(past).saturating_sub(1).saturating_add(safety).min(cursor) }; Ok((start, end)) } diff --git a/tests/date_search.rs b/tests/date_search.rs index ad7c73ea..aa3ae5d9 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -6,6 +6,12 @@ mod common; use atlas::nntp::BlockingPool; use common::{GROUP, Server, mock, post_at, spawn_server}; +/// Pass settings whose day chunks are exactly what their date searches +/// find, without the reach for neighbouring days on other servers +fn exact() -> atlas::indexer::PassSettings { + atlas::indexer::PassSettings { chunk_safety: 0, ..Default::default() } +} + /// `day` of `group` claimed by the mock's server, the way a worker claims it /// (only the claim's owner finishes or gives back a chunk) fn claimed(main: &std::path::Path, group: &str, day: i64) -> atlas::chunks::Claim { @@ -75,8 +81,7 @@ fn a_day_chunk_indexes_that_day() { }; let db = atlas::indexer::shared_db(main_conn); let chunk = claimed(&main, GROUP, day); - let saved = - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); + let saved = pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 0, &mut |_| {})).unwrap(); // hours 24..47 are articles 25..48, plus an hour of overlap each side // (24 and 49); 30 and 40 don't exist. 24..=49 minus 2 = 24 articles @@ -287,8 +292,7 @@ fn a_day_chunk_right_after_a_hole_of_millions_gets_every_article() { }; let db = atlas::indexer::shared_db(main_conn); let chunk = claimed(&main, GROUP, day); - let saved = - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); + let saved = pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 0, &mut |_| {})).unwrap(); // the day's 1,440 posts and the hour after it; the hour before is the hole assert_eq!(saved.articles, 1_440 + 60); @@ -333,8 +337,7 @@ fn a_day_chunk_skips_a_gap_inside_the_day() { }; let db = atlas::indexer::shared_db(main_conn); let chunk = claimed(&main, GROUP, day); - let saved = - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); + let saved = pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 0, &mut |_| {})).unwrap(); // day 2 is 720 numbers minus the 150 missing, plus the hour before it // (691..=720, 30 posts); nothing comes after 1440 @@ -368,7 +371,7 @@ fn a_failing_chunk_reports_its_own_error() { let err = pool .block_on(atlas::indexer::run_chunk( &ctx, - &Default::default(), + &exact(), &db, &atlas::chunks::Claim { group: "alt.binaries.other".into(), @@ -418,7 +421,7 @@ fn a_day_older_than_the_server_keeps_is_given_back() { let db = atlas::indexer::shared_db(main_conn); let run = |day: i64| { let chunk = claimed(&main, GROUP, day); - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})) + pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 0, &mut |_| {})) }; let err = run(first_day - 1).unwrap_err(); @@ -528,7 +531,7 @@ fn only_the_server_going_back_furthest_does_the_oldest_day() { rusqlite::params![chunk.server, GROUP, day], ) .unwrap(); - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, server, &mut |_| {})) + pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, server, &mut |_| {})) }; let state = || -> i64 { conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() }; @@ -590,7 +593,7 @@ fn the_oldest_day_moves_on_when_the_deepest_server_drops_the_group() { rusqlite::params![chunk.server, GROUP, day], ) .unwrap(); - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, server, &mut |_| {})) + pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, server, &mut |_| {})) }; let state = || -> i64 { conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() }; @@ -657,7 +660,7 @@ fn the_oldest_day_moves_on_when_the_deepest_server_no_longer_keeps_it() { rusqlite::params![chunk.server, GROUP, day], ) .unwrap(); - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, server, &mut |_| {})) + pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, server, &mut |_| {})) }; let state = || -> i64 { conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() }; @@ -724,6 +727,7 @@ fn a_split_reaches_back_when_a_deeper_server_joins() { batch_size: 10, request_size: 10, split_min_backlog: 10, + chunk_safety: 0, }; pool.block_on(atlas::indexer::run_pass(&ctx, &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); @@ -751,8 +755,7 @@ fn a_split_reaches_back_when_a_deeper_server_joins() { rusqlite::params![GROUP, day], ) .unwrap(); - let saved = - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 1, &mut |_| {})).unwrap(); + let saved = pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 1, &mut |_| {})).unwrap(); assert!(saved.articles >= 24, "day {day}: {} articles", saved.articles); assert_eq!(state(day), 2); } @@ -802,6 +805,7 @@ fn a_split_reaches_back_when_home_no_longer_keeps_its_cursor() { batch_size: 10, request_size: 10, split_min_backlog: 10, + chunk_safety: 0, }; pool.block_on(atlas::indexer::run_pass(&ctx, &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); @@ -851,6 +855,7 @@ fn a_split_reaches_a_carrier_whose_low_mark_lags() { batch_size: 10, request_size: 10, split_min_backlog: 10, + chunk_safety: 0, }; pool.block_on(atlas::indexer::run_pass(&ctx, &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); @@ -901,6 +906,7 @@ fn a_forged_old_date_at_the_cursor_doesnt_split() { batch_size: 10, request_size: 10, split_min_backlog: 10, + chunk_safety: 0, }; let saved = pool.block_on(atlas::indexer::run_pass(&ctx, &settings, &db, GROUP, 0, &mut |_| {})).unwrap(); @@ -947,6 +953,7 @@ fn a_split_redoes_its_oldest_day_when_a_server_goes_back_further_in_it() { batch_size: 10, request_size: 10, split_min_backlog: 10, + chunk_safety: 0, }; let conn = atlas::db::open_at(&main).unwrap(); let day0 = atlas::chunks::unix_day(start.timestamp()); @@ -961,7 +968,7 @@ fn a_split_redoes_its_oldest_day_when_a_server_goes_back_further_in_it() { rusqlite::params![host, GROUP, day], ) .unwrap(); - pool.block_on(atlas::indexer::run_chunk(&ctx(), &Default::default(), &db, &chunk, server, &mut |_| {})).unwrap() + pool.block_on(atlas::indexer::run_chunk(&ctx(), &exact(), &db, &chunk, server, &mut |_| {})).unwrap() }; // the split, and its oldest day done from 18:00 by the home server @@ -1082,8 +1089,7 @@ fn chunks_save_every_post_of(list: &[Slot], days: &[i64]) { }; let db = atlas::indexer::shared_db(main_conn); let chunk = claimed(&main, GROUP, day); - let saved = - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); + let saved = pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 0, &mut |_| {})).unwrap(); let (from, to) = (day * 86_400 - 3600, (day + 1) * 86_400 + 3600); let want = list.iter().filter(|&&(_, t)| t >= from && t < to).count() as i64; assert_eq!(saved.articles, want, "day {day}"); @@ -1168,7 +1174,7 @@ fn chunk_of_jan_10(posts: Vec) -> Vec { }; let db = atlas::indexer::shared_db(main_conn); let chunk = claimed(&main, GROUP, day); - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 0, &mut |_| {})).unwrap(); let conn = atlas::db::open_with_shards(&main).unwrap(); assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 1)); @@ -1230,7 +1236,7 @@ fn saved_by_every_chunk(list: &[Slot], days: std::ops::RangeInclusive) -> V let db = atlas::indexer::shared_db(main_conn); for day in days.clone() { let chunk = claimed(&main, GROUP, day); - pool.block_on(atlas::indexer::run_chunk(&ctx, &Default::default(), &db, &chunk, 0, &mut |_| {})).unwrap(); + pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 0, &mut |_| {})).unwrap(); } let conn = atlas::db::open_with_shards(&main).unwrap(); let total = days.end() - days.start() + 1; @@ -1296,8 +1302,15 @@ fn day_chunk_ranges_cover_every_number_whatever_the_forged_runs() { let (low, high) = (list[0].0, list.last().unwrap().0); let mut ranges: Vec<(u64, u64)> = (oldest_day..=newest_day) .map(|day| { - let range = - atlas::indexer::chunk_range(&pool.pool, 0, GROUP, (low, high), day, (oldest_day, newest_day), high); + let range = atlas::indexer::chunk_range( + &pool.pool, + 0, + GROUP, + (low, high), + day, + (oldest_day, newest_day), + (high, 0), + ); pool.block_on(range).unwrap() }) .filter(|(start, end)| start <= end) @@ -1311,3 +1324,60 @@ fn day_chunk_ranges_cover_every_number_whatever_the_forged_runs() { assert_eq!(covered, high, "case {case}: the chunks stop short of the high mark"); } } + +/// Adjacent day chunks done on two servers whose numbering differs (one has +/// a hole near the day boundary) with a run of forged Dates across the +/// boundary: every article between them is in one or the other. +#[test] +fn adjacent_days_on_two_servers_leave_no_article_between_them() { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + // a post a minute for three days; a run before the day 1 / day 2 + // boundary dated a day after the last + let boundary = 2 * 1440u64; + let forged = (boundary - 400)..(boundary - 250); + let date = |i: u64| { + let when = if forged.contains(&i) { + start + chrono::Duration::hours(3 * 24 + 12) + } else { + start + chrono::Duration::minutes(i as i64) + }; + when.to_rfc2822() + }; + // "127.0.0.1" numbers them from 1, "localhost" from 50_001 with a hole + // of a billion numbers before the run + let number_b = |i: u64| if i < boundary - 500 { 50_001 + i } else { 1_000_050_001 + i }; + let posts = |number: &dyn Fn(u64) -> u64| -> Vec { + (0..3 * 1440u64) + .map(|i| { + let mut p = post_at(number(i), &format!(r#""p{i}.bin" yEnc (1/1)"#), &date(i)); + p.message_id = format!(""); + p + }) + .collect() + }; + let (pa, pb) = (spawn_server(Server::new(posts(&|i| i + 1))), spawn_server(Server::new(posts(&number_b)))); + let mut b = mock(pb, "secret", 2, 2); + b.host = "localhost".into(); + let pool = BlockingPool::new(&[mock(pa, "secret", 2, 1), b]); + pool.connect().unwrap(); + + let day0 = atlas::chunks::unix_day(start.timestamp()); + let days = (day0, day0 + 2); + let (a_marks, b_marks) = ((1, 3 * 1440), (50_001, number_b(3 * 1440 - 1))); + let range = |server: usize, marks: (u64, u64), day: i64, safety: u64| { + pool.block_on(atlas::indexer::chunk_range(&pool.pool, server, GROUP, marks, day, days, (marks.1, safety))) + .unwrap() + }; + // day 1 on "localhost", day 2 on "127.0.0.1" + let lost = |safety: u64| -> Vec { + let (b_start, b_end) = range(1, b_marks, day0 + 1, safety); + let (a_start, a_end) = range(0, a_marks, day0 + 2, safety); + (1440 + 120..3 * 1440) + .filter(|&i| !(b_start..=b_end).contains(&number_b(i)) && !(a_start..=a_end).contains(&(i + 1))) + .collect() + }; + // the date searches alone leave a gap: the forged run moves them differently + assert!(!lost(0).is_empty()); + let lost = lost(atlas::indexer::CHUNK_SAFETY); + assert!(lost.is_empty(), "{} lost, from {:?}", lost.len(), lost.first()); +} diff --git a/tests/save_memory.rs b/tests/save_memory.rs index 1aca40dd..d58edf5e 100644 --- a/tests/save_memory.rs +++ b/tests/save_memory.rs @@ -70,8 +70,13 @@ fn the_heap_doesnt_grow_with_headers_saved() { stop: Arc::new(AtomicBool::new(false)), verbose: false, }; - let settings = - PassSettings { mode: "backfill".into(), batch_size: 20_000, request_size: 2_000, split_min_backlog: i64::MAX }; + let settings = PassSettings { + mode: "backfill".into(), + batch_size: 20_000, + request_size: 2_000, + split_min_backlog: i64::MAX, + ..Default::default() + }; let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).enable_all().build().unwrap(); rt.block_on(pool.connect()).unwrap(); diff --git a/tests/unsaved_cap.rs b/tests/unsaved_cap.rs index 941f918c..f04b62ee 100644 --- a/tests/unsaved_cap.rs +++ b/tests/unsaved_cap.rs @@ -62,6 +62,7 @@ fn index_everything(cap: usize, groups: usize) { batch_size: BATCH as i64, request_size: REQUEST, split_min_backlog: i64::MAX, + ..Default::default() }); let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(4).enable_all().build().unwrap(); From f9cae07d936a1cb9b03d08befa07d7486eb2252e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:30:46 -0500 Subject: [PATCH 095/159] A stopped conversion only resumes from a copy of the same old database The new main database keeps the old one's release and article counts and highest ids from when the copy started; a resume with any of them changed copies again. The check also compares the newest 200 releases. Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 74 +++++++++++++++++++++++++++++++++++++++++------- tests/convert.rs | 43 ++++++++++++++++++++++++++++ 2 files changed, 107 insertions(+), 10 deletions(-) diff --git a/src/convert.rs b/src/convert.rs index 527046d7..1d5742ec 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -35,6 +35,8 @@ use crate::store::{self, SHARDS}; const BATCH: usize = 25_000; /// releases whose NZBs are compared before the swap const CHECK_SAMPLE: i64 = 2_000; +/// and the newest releases on top +const CHECK_TAIL: i64 = 200; /// threads reading the old articles at once const READERS: usize = 8; @@ -96,7 +98,8 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { // a run that got through the copy and was stopped during the check // picks up there instead of copying everything again - let (max_id, shard_of_old, moved_releases, moved_articles, orphans) = if copy_finished(main) { + let source = Source::of(&old)?; + let (max_id, shard_of_old, moved_releases, moved_articles, orphans) = if copy_finished(main, &source) { progress("converting the database: the copy finished earlier, checking it"); let max_id: i64 = old.query_row("select coalesce(max(id), 0) from releases", [], |r| r.get(0))?; let mut shard_of_old = vec![u8::MAX; max_id as usize + 1]; @@ -113,7 +116,7 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { let (releases, articles) = store::totals(&conn)?; (max_id, shard_of_old, releases, articles, 0) } else { - copy(main, &old, started, progress)? + copy(main, &old, &source, started, progress)? }; // 4. the check @@ -464,8 +467,8 @@ fn move_articles( }) } -/// Compare `CHECK_SAMPLE` releases, spread over the whole database, between -/// the old database and the shards. +/// Compare `CHECK_SAMPLE` releases, spread over the whole database, and the +/// newest `CHECK_TAIL` between the old database and the shards. fn check(main: &Path, old: &Connection, max_id: i64, shard_of_old: &[u8]) -> Result<()> { let new = Connection::open_in_memory()?; store::attach(&new, main)?; @@ -494,10 +497,18 @@ fn check(main: &Path, old: &Connection, max_id: i64, shard_of_old: &[u8]) -> Res }) }; + // spread over the ids, and the newest ones: the last written are the + // likeliest to be missing from a copy + let tail: Vec = old + .prepare("select id from releases order by id desc limit ?")? + .query_map([CHECK_TAIL], |r| r.get(0))? + .collect::>()?; + let starts = (0..CHECK_SAMPLE).map(|i| i * step).chain(tail); + let (mut checked, mut bad) = (0, Vec::new()); let mut seen = std::collections::HashSet::new(); - for i in 0..CHECK_SAMPLE { - let Ok(was) = old_release.query_row([i * step], row) else { continue }; + for start in starts { + let Ok(was) = old_release.query_row([start], row) else { continue }; if !seen.insert(was.id) { continue; } @@ -560,6 +571,7 @@ fn check(main: &Path, old: &Connection, max_id: i64, shard_of_old: &[u8]) -> Res fn copy( main: &Path, old: &Connection, + source: &Source, started: Instant, progress: &dyn Fn(&str), ) -> Result<(i64, Vec, i64, i64, i64)> { @@ -582,6 +594,7 @@ fn copy( let list = cols.join(", "); conn.execute(&format!("insert into groups ({list}) select {list} from old.groups"), [])?; conn.execute("detach database old", [])?; + source.save(&conn)?; } // fresh shards (a failed run leaves its own behind). releases go in without @@ -632,10 +645,51 @@ fn copy( Ok((max_id, shard_of_old, moved_releases, moved_articles, orphans)) } -/// The shards are complete from an earlier run: every shard writer marks its -/// shard once its articles are sorted into place. -fn copy_finished(main: &Path) -> bool { - sibling(main, "atlas.new.db").exists() +/// What the old database held when a copy started: its release and article +/// counts and highest ids. A copy is only picked up again from the same old +/// database; one written to or put back from another backup since differs. +#[derive(Debug, PartialEq)] +struct Source([i64; 4]); + +const SOURCE_KEYS: [&str; 4] = ["source_releases", "source_max_release", "source_articles", "source_max_article"]; + +impl Source { + fn of(old: &Connection) -> Result { + let (releases, max_release) = + old.query_row("select count(*), coalesce(max(id), 0) from releases", [], |r| Ok((r.get(0)?, r.get(1)?)))?; + let (articles, max_article) = + old.query_row("select count(*), coalesce(max(id), 0) from articles", [], |r| Ok((r.get(0)?, r.get(1)?)))?; + Ok(Source([releases, max_release, articles, max_article])) + } + + /// into the new main database's meta, as the copy starts + fn save(&self, conn: &Connection) -> Result<()> { + for (key, value) in SOURCE_KEYS.iter().zip(self.0) { + conn.execute("insert or replace into meta (key, value) values (?, ?)", params![key, value])?; + } + Ok(()) + } + + fn saved(conn: &Connection) -> Result> { + let mut values = [0; 4]; + for (key, value) in SOURCE_KEYS.iter().zip(values.iter_mut()) { + let Some(v) = conn.query_row("select value from meta where key = ?", [key], |r| r.get(0)).optional()? + else { + return Ok(None); + }; + *value = v; + } + Ok(Some(Source(values))) + } +} + +/// The shards are complete from an earlier run, copied from the old database +/// as it is now (`source`): every shard writer marks its shard once its +/// articles are sorted into place. +fn copy_finished(main: &Path, source: &Source) -> bool { + let new_main = sibling(main, "atlas.new.db"); + new_main.exists() + && db::open_at(&new_main).ok().and_then(|c| Source::saved(&c).ok().flatten()).as_ref() == Some(source) && store::shard_paths(main).iter().all(|p| { p.exists() && db::open_at(p) diff --git a/tests/convert.rs b/tests/convert.rs index af4ed7c4..fcd12488 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -351,3 +351,46 @@ fn a_swap_whose_checkpoint_is_held_back_is_refused() { .unwrap(); assert_eq!(late, 7); } + +/// A conversion that finished copying and was stopped before the swap only +/// picks up from that copy while the old database is the one it copied: one +/// written to (or put back from another backup) since is copied again, soo +/// nothing added to it is left out. +#[test] +fn a_stopped_conversion_copies_again_when_the_old_database_changed() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + db::create_db_at(&main).unwrap(); + + let stopped = std::panic::catch_unwind(|| { + convert::run(&main, &|m| assert!(!m.contains("checking NZBs"), "stop here")).unwrap(); + }); + assert!(stopped.is_err()); + + // the old database gets a newer release after the copy + { + let conn = Connection::open(&main).unwrap(); + conn.execute( + "insert into releases (id, name, group_name, poster, posted_date, size, complete, parts, file_total) + values (500, 'Late.Release', 'alt.binaries.a', 'p', '2026-10-03 10:00:00', 9, 1, 1, 1)", + [], + ) + .unwrap(); + conn.execute( + "insert into articles (release_id, message_id, subject, filename, part, total_parts, bytes, file_total) + values (500, '', 's', 'late.bin', 1, 1, 9, 1)", + [], + ) + .unwrap(); + } + + let messages = std::cell::RefCell::new(Vec::new()); + let (releases, articles) = convert::run(&main, &|m| messages.borrow_mut().push(m.to_string())).unwrap(); + assert!(!messages.borrow().iter().any(|m| m.contains("copy finished earlier")), "{messages:?}"); + assert_eq!(releases, 41); + assert_eq!(articles, (1..=40).map(|r| r % 7 + 1).sum::() + 1); + let conn = db::open_with_shards(&main).unwrap(); + let id: i64 = conn.query_row("select id from releases where name = 'Late.Release'", [], |r| r.get(0)).unwrap(); + assert_eq!(store::articles(&conn, id).unwrap().len(), 1); +} From 5e7ccca15187670f2d0efe931c9cfac3ab70f19d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:34:36 -0500 Subject: [PATCH 096/159] A conversion's swap cut short between its renames is finished or undone at start atlas.new.db is marked swap_ready once everything before the swap is done. With no atlas.db, setting up (under the exclusive lock) puts a ready atlas.new.db in place, else atlas.old.db back. A failed second rename puts the old database back straight away. Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++++- src/db.rs | 8 ++++++++ tests/convert.rs | 41 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 97 insertions(+), 1 deletion(-) diff --git a/src/convert.rs b/src/convert.rs index 1d5742ec..22572d53 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -79,6 +79,9 @@ pub fn run_alone(main: &Path, progress: &dyn Fn(&str)) -> Result anyhow!("the database is in use (indexing, a compaction or another conversion); try again later"), None => e, })?; + if let Some(said) = recover_cut_swap(main)? { + progress(&said); + } if !needed(main) { return Ok(None); } @@ -135,6 +138,12 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; checkpoint(&conn).with_context(|| format!("folding {}'s WAL in", path.display()))?; } + { + // from here atlas.new.db is whole: a swap cut short finishes at the next start + let conn = db::open_at(&new_main)?; + conn.execute("insert or replace into meta (key, value) values ('swap_ready', 1)", [])?; + checkpoint(&conn).context("folding the new main database's WAL in")?; + } drop(old); let backup = sibling(main, "atlas.old.db"); remove_db(&backup); @@ -148,7 +157,11 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { } // its -wal and -shm go aside with it, whatever they still hold rename_db(main, &backup).context("moving the old database aside")?; - rename_db(&new_main, main).context("putting the new main database in place")?; + if let Err(e) = rename_db(&new_main, main) { + // the old one back, soo there is a main database to start from + let _ = rename_db(&backup, main); + return Err(e).context("putting the new main database in place"); + } progress(&format!( "converted {moved_releases} releases and {moved_articles} articles in {} ({orphans} articles without a release left out). \ @@ -159,6 +172,40 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { Ok((moved_releases, moved_articles)) } +/// A swap that was cut short between moving the old database aside and +/// putting the new one in place leaves no main database. Finishes it when +/// `atlas.new.db` got through everything before the swap, else puts +/// `atlas.old.db` back (and the next start converts again). Run under the +/// exclusive lock. What it did, if anything. +pub fn recover_cut_swap(main: &Path) -> Result> { + if main.try_exists()? { + return Ok(None); + } + let (new_main, backup) = (sibling(main, "atlas.new.db"), sibling(main, "atlas.old.db")); + if new_main.try_exists()? && swap_ready(&new_main) { + rename_db(&new_main, main).context("putting the converted main database in place")?; + return Ok(Some(format!( + "a conversion was cut short putting {} in place; it's in place now (the old database is {})", + main.display(), + backup.display() + ))); + } + if backup.try_exists()? { + rename_db(&backup, main).context("putting the old database back")?; + return Ok(Some(format!( + "a conversion was cut short after moving {} aside; it's back in place", + main.display() + ))); + } + Ok(None) +} + +fn swap_ready(new_main: &Path) -> bool { + db::open_at(new_main) + .and_then(|c| c.query_row("select value from meta where key = 'swap_ready'", [], |r| r.get(0)).optional()) + .is_ok_and(|v: Option| v == Some(1)) +} + type OldRelease = (i64, ReleaseFields); type ReleaseFields = ( Option, diff --git a/src/db.rs b/src/db.rs index 510a832d..319ed2a2 100644 --- a/src/db.rs +++ b/src/db.rs @@ -136,6 +136,14 @@ pub fn create_db() -> anyhow::Result> { /// while a compaction runs, and nothing was set up (a compaction only runs /// on a database that is). pub fn create_db_holding(path: &Path) -> anyhow::Result> { + // a conversion's swap cut short leaves no main database: finished or + // undone first, alone (busy means someone is using the database, soo it's there) + if !path.try_exists()? + && let Ok(_alone) = crate::compact::Lock::take(path) + && let Some(said) = crate::convert::recover_cut_swap(path)? + { + crate::ui::warn(&said); + } let Some(held) = crate::compact::try_hold_off_compaction(path)? else { return Ok(None) }; create_db_at(path)?; Ok(Some(held)) diff --git a/tests/convert.rs b/tests/convert.rs index fcd12488..ff146dcc 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -394,3 +394,44 @@ fn a_stopped_conversion_copies_again_when_the_old_database_changed() { let id: i64 = conn.query_row("select id from releases where name = 'Late.Release'", [], |r| r.get(0)).unwrap(); assert_eq!(store::articles(&conn, id).unwrap().len(), 1); } + +/// Stopped between moving the old database aside and putting the new one in +/// place: the next start finishes the swap. +#[test] +fn a_swap_cut_after_the_old_database_moved_aside_is_finished_at_start() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + let before = old_nzbs(&main); + db::create_db_at(&main).unwrap(); + convert::run(&main, &|_| {}).unwrap(); + // as it was before the second rename + std::fs::rename(&main, dir.path().join("atlas.new.db")).unwrap(); + + drop(db::create_db_holding(&main).unwrap().expect("set up")); + assert!(!dir.path().join("atlas.new.db").exists()); + assert!(dir.path().join("atlas.old.db").exists()); + assert!(!convert::needed(&main)); + let conn = db::open_with_shards(&main).unwrap(); + assert_eq!(store::totals(&conn).unwrap().0, before.len() as i64); +} + +/// Moved aside with a new main database that never got to the swap: the +/// next start puts the old database back, and converting goes on from it. +#[test] +fn an_old_database_moved_aside_without_a_finished_new_one_is_put_back() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + db::create_db_at(&main).unwrap(); + let stopped = std::panic::catch_unwind(|| { + convert::run(&main, &|m| assert!(!m.contains("checking NZBs"), "stop here")).unwrap(); + }); + assert!(stopped.is_err()); + std::fs::rename(&main, dir.path().join("atlas.old.db")).unwrap(); + + drop(db::create_db_holding(&main).unwrap().expect("set up")); + assert!(!dir.path().join("atlas.old.db").exists()); + assert!(convert::needed(&main), "the old database is back"); + assert_eq!(convert::run_alone(&main, &|_| {}).unwrap().map(|(r, _)| r), Some(40)); +} From 7d54218c4898aae32b79019a09a9adf7e6faa629 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 00:44:53 -0500 Subject: [PATCH 097/159] A split group's home backfill sweeps on for what its day chunks missed Once no day chunk a server could take is left in any split group, a split group's pass on its home server goes on with the cursor backfill from where the split froze it down to the server's first article. Date searches go by forgeable Date headers and neighbouring days on other servers can leave numbers between them; the sweep adds what the chunks missed and the segments key drops the rest. The dashboard counts the sweep as backfill left once the chunks are done. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 12 ++++ src/indexer.rs | 27 ++++++++- src/stats_dashboard.rs | 17 ++++-- tests/split_forged_sweep.rs | 107 ++++++++++++++++++++++++++++++++++++ 4 files changed, 157 insertions(+), 6 deletions(-) create mode 100644 tests/split_forged_sweep.rs diff --git a/src/chunks.rs b/src/chunks.rs index 5f351e0c..b896cd1f 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -240,6 +240,18 @@ pub fn forget_deepest(conn: &Connection, group: &str, server: &str) -> Result<() Ok(()) } +/// Whether any chunk of `groups`: (group, oldest day the server keeps) is +/// still to do (pending or claimed) on a day the server keeps. +pub fn waiting(conn: &Connection, groups: &[(String, i64)]) -> Result { + let mut stmt = conn.prepare_cached("select 1 from backfill_chunks where grp = ? and day >= ? and state != 2")?; + for (g, oldest) in groups { + if stmt.exists(params![g, oldest])? { + return Ok(true); + } + } + Ok(false) +} + /// groups with chunks still to do pub fn split_groups(conn: &Connection) -> Result> { conn.prepare("select distinct grp from backfill_chunks where state != 2 order by grp")? diff --git a/src/indexer.rs b/src/indexer.rs index 6301646b..d6c27a44 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -436,6 +436,16 @@ where Err(e) if e.downcast_ref::().is_some() => Ok(Progress::default()), r => r, }, + // nothing for this server: once no chunk it could take is left in + // any split group, its own backfill sweeps on from where the split + // froze the cursor down to its first article. date searches go by + // Date headers posters can forge, and neighbouring days done on + // other servers can leave numbers between them; the sweep picks up + // whatever the chunks missed (what they got is dropped as a duplicate) + None if sweep_due(ctx, db, &ctx.pool.host(server)).await? => { + let pass = Pass { ctx, settings, db, group, server, key }; + pass.backfill(state, first, last, progress).await + } None => { // nothing pending: in backfill mode the group rests like a finished backfill let idle = settings.mode == "backfill"; @@ -469,6 +479,20 @@ where } } +/// Whether a split group's cursor backfill on `host` may sweep: no day chunk +/// of any split group is left that it could take or that is still running. +/// Chunks come first, the sweep only checks after them. +async fn sweep_due(ctx: &PassContext, db: &Db, host: &str) -> Result { + let host = host.to_string(); + let states = ctx.states.clone(); + on_db(db, move |conn| { + let groups: Vec<(String, i64)> = + crate::chunks::split_groups(conn)?.into_iter().map(|g| (g.clone(), states.keeps_from(&g, &host))).collect(); + Ok(!crate::chunks::waiting(conn, &groups)?) + }) + .await +} + /// how long a big group that couldnt be split waits before it is probed again const SPLIT_RECHECK: Duration = Duration::from_secs(3600); @@ -930,7 +954,8 @@ where /// also reaches `safety` (`CHUNK_SAFETY`) numbers past where its search put it (the /// articles a neighbour has too are dropped as duplicates when saved): a /// shift up to that many articles is covered, a forged run moving a search -/// further can still leave a gap. +/// further can still leave a gap, for the home server's sweep once the +/// chunks are done (see `run_pass`). pub async fn chunk_range( pool: &Pool, server: usize, diff --git a/src/stats_dashboard.rs b/src/stats_dashboard.rs index dbdab9f9..9c02123b 100644 --- a/src/stats_dashboard.rs +++ b/src/stats_dashboard.rs @@ -736,9 +736,10 @@ fn backfill_at(quick: &Quick, now: i64) -> Backfill { b.unmeasured = seen.iter().filter(|g| !best.contains_key(*g)).count(); // a split group's cursors stand still: its day chunks say how far it is, - // as that share of its article numbers + // as that share of its article numbers. once they are all done its home + // cursor sweeps on for what they missed, and the cursor says it again for (group, (total, covered, _)) in best.iter_mut() { - if let Some(&(done, chunks)) = quick.group_chunks.get(group).filter(|c| c.1 > 0) { + if let Some(&(done, chunks)) = quick.group_chunks.get(group).filter(|c| c.1 > 0 && c.0 < c.1) { *covered = (*total as i128 * done.clamp(0, chunks) as i128 / chunks as i128) as i64; } } @@ -1317,7 +1318,7 @@ mod tests { } #[test] - fn split_groups_progress_follows_their_chunks_not_their_cursors() { + fn split_groups_progress_follows_their_chunks_then_their_sweep() { let row = |key: &str| db::GroupProgress { key: key.into(), live_cursor: 1000, @@ -1333,10 +1334,16 @@ mod tests { let b = backfill_at(&quick, 1_780_000_000); assert_eq!((b.total, b.covered, b.remaining, b.done), (3000, 0, 3000, 0), "no chunks: the cursors"); - // s: 1 of 4 days done, t: all 6, u is not split + // s: 1 of 4 days done, t: all 6 (its sweep from the cursor to go), u is not split quick.group_chunks = BTreeMap::from([("alt.binaries.s".into(), (1, 4)), ("alt.binaries.t".into(), (6, 6))]); let b = backfill_at(&quick, 1_780_000_000); - assert_eq!((b.total, b.covered, b.remaining, b.done), (3000, 1250, 1750, 1)); + assert_eq!((b.total, b.covered, b.remaining, b.done), (3000, 250, 2750, 0)); + assert!(b.behind.contains(&("alt.binaries.t".into(), 1000, 0.0))); + + // t's sweep halfway down + quick.progress[1].backfill_cursor = 500; + let b = backfill_at(&quick, 1_780_000_000); + assert_eq!((b.covered, b.remaining), (250 + 500, 2250)); assert_eq!(b.behind[0], ("alt.binaries.u".into(), 1000, 0.0)); assert!(b.behind.contains(&("alt.binaries.s".into(), 750, 25.0))); } diff --git a/tests/split_forged_sweep.rs b/tests/split_forged_sweep.rs new file mode 100644 index 00000000..f54cecac --- /dev/null +++ b/tests/split_forged_sweep.rs @@ -0,0 +1,107 @@ +//! A split group on two servers, the one that keeps only the last 20 days +//! with forged Dates from the first of the 30 in each of its first windows: +//! it looks as deep as the other and its day chunks miss what it doesnt +//! keep (here: every chunk done before indexing starts, as such a server +//! finishes them empty). Once the chunks are done the home server's +//! cursor backfill sweeps on from where the split froze it, and every post +//! is indexed. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset`, +/// only those from day `from_day` on +fn posts(offset: u64, from_day: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (from_day * 40..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn chunks_a_forged_shallow_server_missed_are_swept_up_after() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + // "localhost" (the group's home) keeps all 30 days; "127.0.0.1" the last + // 20, with 4 posts in each of its first 3 windows of 100 numbers dated + // the first day + let long = Server::new(posts(1, 0)); + let mut short_posts = posts(500_001, 10); + for window in 0..3 { + for n in 0..4 { + short_posts[window * 100 + n * 20].date = "Thu, 01 Jan 2026 00:30:00 +0000".into(); + } + } + let short = Server::new(short_posts); + let (pl, ps) = (spawn_server(long), spawn_server(short)); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": ps, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": pl, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + drop(atlas::db::create_db().unwrap()); + let main = home.path().join("atlas.db"); + { + // the 30 days split and done by the shallow server, nothing indexed + let conn = atlas::db::open_at(&main).unwrap(); + let first_day = atlas::chunks::unix_day(1_767_225_600); + atlas::chunks::add(&conn, GROUP, first_day + 29, first_day).unwrap(); + let now = chrono::Utc::now().timestamp(); + while let Some(claim) = atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], "127.0.0.1", now).unwrap() + { + assert!(atlas::chunks::finish(&conn, &claim, now).unwrap()); + } + } + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + if total > 0 && done == total && articles == 1200 { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); +} From 3c238756f0d4b0956a4003abc1fd919677ac1c3f Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:01:17 -0500 Subject: [PATCH 098/159] Every carrier of a split group sweeps its own numbers once the chunks are done The home's completion sweep stops at its own first article: when the home keeps less than another carrier, what the date-based chunks missed of the days only the deeper one keeps was never revisited. Once a split group's chunks are all done, an idle worker on each other carrier sweeps the group on that server's own cursor (one sweep per server at a time, after any chunk it could take) down to its first article. Each finished sweep is noted in backfill_sweeps; the split is complete when every carrier's is. Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 49 +++++++++++++ src/chunks.rs | 40 ++++++++++- src/indexer.rs | 83 +++++++++++++++++++++- tests/split_shallow_home_sweep.rs | 110 ++++++++++++++++++++++++++++++ 4 files changed, 279 insertions(+), 3 deletions(-) create mode 100644 tests/split_shallow_home_sweep.rs diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index ae957f24..9f7c4cbe 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -276,6 +276,8 @@ struct Scheduler { skip: Mutex>>, /// consecutive day chunk errors per (group, server) chunk_errors: Mutex>, + /// servers one of whose workers sweeps a split group (see `take_sweep`) + sweeping: Mutex>, /// groups resting after going idle or after an error wait_until: Mutex>, /// consecutive errors per group @@ -492,6 +494,39 @@ async fn take_chunk(sched: &Scheduler, server: usize, db: &Db) -> Option Option { + let tier = sched.ctx.pool.indexing_tier(); + if !tier.contains(&server) || !sched.sweeping.lock().unwrap().insert(server) { + return None; + } + + let skip: HashSet = { + let now = Instant::now(); + let mut skip = sched.skip.lock().unwrap(); + skip.retain(|_, until| until.is_none_or(|t| t > now)); + skip.keys().filter(|(_, s)| *s == server).map(|(g, _)| g.clone()).collect() + }; + let mode = sched.settings.read().unwrap().mode.clone(); + let groups: Vec = chunk_groups(&mode, &sched.groups.read().unwrap(), &skip) + .into_iter() + .filter(|g| sched.ctx.pool.pick_server_in(&tier, g) != server) + .collect(); + let found = match crate::indexer::sweep_to_take(db, sched.ctx.pool.host(server), groups).await { + Ok(found) => found, + Err(e) => { + ui::error(&format!("couldnt look for a split group to sweep: {e}")); + None + } + }; + if found.is_none() { + sched.sweeping.lock().unwrap().remove(&server); + } + found +} + /// One worker on `server`: index whichever of its groups is due next, again and again. /// All workers share one db connection, soo their writes queue up in order /// instead of racing for sqlite's write lock (and timing out on a busy db). @@ -510,6 +545,19 @@ async fn worker(sched: Arc, server: usize, db: Db) { sched.finish_chunk(chunk.group, server, result); continue; } + // or, once a split group's chunks are done, sweep this server's + // numbers of it for what they missed (one worker per server at a time) + if let Some(group) = take_sweep(&sched, server, &db).await { + let settings = sched.settings.read().unwrap().clone(); + let stats = sched.stats.clone(); + let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); + let run = crate::indexer::run_sweep(&sched.ctx, &settings, &db, &group, server, &mut progress); + let result = unless_stopped(&sched.ctx.stop, run).await; + sched.sweeping.lock().unwrap().remove(&server); + let Some(result) = result else { break }; + sched.finish_chunk(group, server, result); + continue; + } nap(Duration::from_secs(1), || sched.stopping()).await; continue; }; @@ -640,6 +688,7 @@ async fn run_servers( busy: Mutex::new(HashSet::new()), skip: Mutex::new(HashMap::new()), chunk_errors: Mutex::new(HashMap::new()), + sweeping: Mutex::new(HashSet::new()), wait_until: Mutex::new(HashMap::new()), errors: Mutex::new(HashMap::new()), failed: Mutex::new(HashMap::new()), diff --git a/src/chunks.rs b/src/chunks.rs index b896cd1f..a7636c97 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -13,7 +13,8 @@ const DONE: i64 = 2; /// Initialize the backfill_chunks table if it doesn't exist, and give one /// made before chunks kept their finish time its done_at column. Also the -/// server that goes back furthest, by split group (see `deepest`). +/// server that goes back furthest, by split group (see `deepest`), and the +/// servers whose sweep of a split group is done (see `swept`). pub fn create(conn: &Connection) -> Result<()> { conn.execute_batch( "create table if not exists backfill_chunks ( @@ -30,6 +31,11 @@ pub fn create(conn: &Connection) -> Result<()> { server TEXT NOT NULL, oldest_at INTEGER, runner_up_at INTEGER + ) without rowid; + create table if not exists backfill_sweeps ( + grp TEXT NOT NULL, + server TEXT NOT NULL, + primary key (grp, server) ) without rowid;", )?; add_column(conn, "backfill_chunks", "done_at")?; @@ -252,6 +258,38 @@ pub fn waiting(conn: &Connection, groups: &[(String, i64)]) -> Result { Ok(false) } +/// Whether every day chunk of split `group` is done. +pub fn chunks_done(conn: &Connection, group: &str) -> Result { + Ok(is_split(conn, group)? + && !conn.prepare_cached("select 1 from backfill_chunks where grp = ? and state != 2")?.exists([group])?) +} + +/// Note `server`'s sweep of split `group` as done: its cursor backfill got +/// down to its first article after the day chunks (see `indexer::run_sweep`). +pub fn set_swept(conn: &Connection, group: &str, server: &str) -> Result<()> { + conn.execute("insert or ignore into backfill_sweeps (grp, server) values (?, ?)", [group, server])?; + Ok(()) +} + +/// Whether `server`'s sweep of split `group` is done. +pub fn swept(conn: &Connection, group: &str, server: &str) -> Result { + conn.prepare_cached("select 1 from backfill_sweeps where grp = ? and server = ?")?.exists([group, server]) +} + +/// Whether split `group` is complete: every day chunk done and every one of +/// `servers` (the ones carrying it) swept down to its first article. +pub fn complete(conn: &Connection, group: &str, servers: &[String]) -> Result { + if !chunks_done(conn, group)? { + return Ok(false); + } + for s in servers { + if !swept(conn, group, s)? { + return Ok(false); + } + } + Ok(true) +} + /// groups with chunks still to do pub fn split_groups(conn: &Connection) -> Result> { conn.prepare("select distinct grp from backfill_chunks where state != 2 order by grp")? diff --git a/src/indexer.rs b/src/indexer.rs index d6c27a44..3a7ae476 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -442,7 +442,12 @@ where // Date headers posters can forge, and neighbouring days done on // other servers can leave numbers between them; the sweep picks up // whatever the chunks missed (what they got is dropped as a duplicate) + // the other carriers sweep their own numbers the same way (see `run_sweep`) None if sweep_due(ctx, db, &ctx.pool.host(server)).await? => { + if state.backfill_cursor.min(last) < first { + let (g, host) = (group.to_string(), ctx.pool.host(server)); + on_db(db, move |conn| Ok(crate::chunks::set_swept(conn, &g, &host)?)).await?; + } let pass = Pass { ctx, settings, db, group, server, key }; pass.backfill(state, first, last, progress).await } @@ -736,6 +741,80 @@ pub async fn claim_chunk( .await } +/// A split group whose day chunks are all done that `host`, not its home, +/// still has to sweep, among `groups`. +pub async fn sweep_to_take(db: &Db, host: String, groups: Vec) -> Result> { + on_db(db, move |conn| { + for g in groups { + if crate::chunks::chunks_done(conn, &g)? && !crate::chunks::swept(conn, &g, &host)? { + return Ok(Some(g)); + } + } + Ok(None) + }) + .await +} + +/// One batch of the sweep of split `group` on `server`, a carrier that is +/// not its home, once its day chunks are done: like the home's (see +/// `run_pass`), the server's own cursor backfill from where its backfill +/// got (its high mark when it has none, where its newest chunk ended) down +/// to its first article. The chunks go by forgeable Date headers: when the +/// home keeps less than this server, what they missed of the days only this +/// one keeps is here. Noted as swept once at its first article (or when it +/// doesnt carry the group); the split is complete when every carrier is. +pub async fn run_sweep

( + ctx: &PassContext, + settings: &PassSettings, + db: &Db, + group: &str, + server: usize, + progress: &mut P, +) -> Result +where + P: FnMut(&Progress) + ?Sized, +{ + let (g, host) = (group.to_string(), ctx.pool.host(server)); + let swept = || { + let (g, host) = (g.clone(), host.clone()); + on_db(db, move |conn| Ok(crate::chunks::set_swept(conn, &g, &host)?)) + }; + // this server alone, like a day chunk + let (_count, first, last, _name) = match ctx.pool.group_on(server, group).await { + Ok(info) => info, + Err(e) if e.code() == Some(411) => { + swept().await?; + return Err(NotCarried { group: g, host }.into()); + } + Err(e) => return Err(e.into()), + }; + let (first, last) = (first as i64, last as i64); + let key = cursor_key(&ctx.pool, server, group); + let cursor = match load_cursors(db, &key, group, server == 0).await? { + Some(s) => s.backfill_cursor.min(last), + None => { + let k = key.clone(); + on_db(db, move |conn| Ok(db::init_group_state(conn, &k, last)?)).await?; + last + } + }; + if cursor < first { + swept().await?; + println!("[SWEEP] {group} on {host} done"); + return Ok(Progress::default()); + } + + // the cursor backfill's batch, without touching the group's run state: + // that is the home's + let start = first.max(cursor - settings.batch_size.max(1) + 1); + let pass = Pass { ctx, settings, db, group, server, key: key.clone() }; + let (saved, complete) = pass.process_range(start, cursor, "SWEEP", progress).await?; + if complete { + on_db(db, move |conn| Ok(db::update_backfill_cursor(conn, &key, start - 1)?)).await?; + } + Ok(saved) +} + /// a day chunk also takes this much on each side: post dates are only /// roughly in article number order, duplicates are dropped when saved pub const CHUNK_OVERLAP: i64 = 3600; @@ -954,8 +1033,8 @@ where /// also reaches `safety` (`CHUNK_SAFETY`) numbers past where its search put it (the /// articles a neighbour has too are dropped as duplicates when saved): a /// shift up to that many articles is covered, a forged run moving a search -/// further can still leave a gap, for the home server's sweep once the -/// chunks are done (see `run_pass`). +/// further can still leave a gap, for the carriers' sweeps once the +/// chunks are done (see `run_pass` and `run_sweep`). pub async fn chunk_range( pool: &Pool, server: usize, diff --git a/tests/split_shallow_home_sweep.rs b/tests/split_shallow_home_sweep.rs new file mode 100644 index 00000000..20f2ae2d --- /dev/null +++ b/tests/split_shallow_home_sweep.rs @@ -0,0 +1,110 @@ +//! A split group on two servers, its home the one that keeps only the last +//! 20 days with forged Dates from the first of the 30 in each of its first +//! windows: it looks as deep as the other and its day chunks miss what it +//! doesnt keep (here: every chunk done before indexing starts, as such a +//! server finishes them empty). The home's sweep stops at its own first +//! article; once the chunks are done the deep server sweeps its own +//! numbers too, every post is indexed and the split is complete once both +//! servers' sweeps are. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset`, +/// only those from day `from_day` on +fn posts(offset: u64, from_day: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (from_day * 40..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn deep_only_posts_a_shallow_home_missed_are_swept_by_the_deep_server() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + // "127.0.0.1" keeps all 30 days; "localhost" (the group's home) the last + // 20, with 4 posts in each of its first 3 windows of 100 numbers dated + // the first day + let long = Server::new(posts(500_001, 0)); + let mut short_posts = posts(1, 10); + for window in 0..3 { + for n in 0..4 { + short_posts[window * 100 + n * 20].date = "Thu, 01 Jan 2026 00:30:00 +0000".into(); + } + } + let short = Server::new(short_posts); + let (pl, ps) = (spawn_server(long), spawn_server(short)); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pl, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": ps, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + drop(atlas::db::create_db().unwrap()); + let main = home.path().join("atlas.db"); + { + // the 30 days split and done by the shallow home, nothing indexed + let conn = atlas::db::open_at(&main).unwrap(); + let first_day = atlas::chunks::unix_day(1_767_225_600); + atlas::chunks::add(&conn, GROUP, first_day + 29, first_day).unwrap(); + let now = chrono::Utc::now().timestamp(); + while let Some(claim) = atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], "localhost", now).unwrap() + { + assert!(atlas::chunks::finish(&conn, &claim, now).unwrap()); + } + } + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + let hosts = ["127.0.0.1".to_string(), "localhost".to_string()]; + let complete = atlas::chunks::complete(&conn, GROUP, &hosts).unwrap(); + if total > 0 && done == total && articles == 1200 && complete { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}, complete {complete}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); +} From c1c608dedb5cc3db53bde6b7f372cd87eac927de Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:06:00 -0500 Subject: [PATCH 099/159] A split group's sweep waits only for its own day chunks The home's sweep waited while any split group had a chunk the server could take or that was still running, soo another group's backlog could hold it back past the retention of what its chunks missed. Only the group's own chunks hold it now; idle workers take other groups' chunks on their own. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 25 +++----- tests/split_sweep_own_chunks.rs | 109 ++++++++++++++++++++++++++++++++ 2 files changed, 119 insertions(+), 15 deletions(-) create mode 100644 tests/split_sweep_own_chunks.rs diff --git a/src/indexer.rs b/src/indexer.rs index 3a7ae476..b387f9bb 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -436,14 +436,14 @@ where Err(e) if e.downcast_ref::().is_some() => Ok(Progress::default()), r => r, }, - // nothing for this server: once no chunk it could take is left in - // any split group, its own backfill sweeps on from where the split + // nothing for this server: once no chunk of this group it could + // take is left, its own backfill sweeps on from where the split // froze the cursor down to its first article. date searches go by // Date headers posters can forge, and neighbouring days done on // other servers can leave numbers between them; the sweep picks up // whatever the chunks missed (what they got is dropped as a duplicate) // the other carriers sweep their own numbers the same way (see `run_sweep`) - None if sweep_due(ctx, db, &ctx.pool.host(server)).await? => { + None if sweep_due(ctx, db, group, &ctx.pool.host(server)).await? => { if state.backfill_cursor.min(last) < first { let (g, host) = (group.to_string(), ctx.pool.host(server)); on_db(db, move |conn| Ok(crate::chunks::set_swept(conn, &g, &host)?)).await?; @@ -484,18 +484,13 @@ where } } -/// Whether a split group's cursor backfill on `host` may sweep: no day chunk -/// of any split group is left that it could take or that is still running. -/// Chunks come first, the sweep only checks after them. -async fn sweep_due(ctx: &PassContext, db: &Db, host: &str) -> Result { - let host = host.to_string(); - let states = ctx.states.clone(); - on_db(db, move |conn| { - let groups: Vec<(String, i64)> = - crate::chunks::split_groups(conn)?.into_iter().map(|g| (g.clone(), states.keeps_from(&g, &host))).collect(); - Ok(!crate::chunks::waiting(conn, &groups)?) - }) - .await +/// Whether split `group`'s cursor backfill on `host` may sweep: no day +/// chunk of it is left that the server could take or that is still running. +/// Its chunks come first; other groups' chunks dont hold its sweep back +/// (idle workers take those anyway), their retention wont wait for them. +async fn sweep_due(ctx: &PassContext, db: &Db, group: &str, host: &str) -> Result { + let wanted = [(group.to_string(), ctx.states.keeps_from(group, host))]; + on_db(db, move |conn| Ok(!crate::chunks::waiting(conn, &wanted)?)).await } /// how long a big group that couldnt be split waits before it is probed again diff --git a/tests/split_sweep_own_chunks.rs b/tests/split_sweep_own_chunks.rs new file mode 100644 index 00000000..60712705 --- /dev/null +++ b/tests/split_sweep_own_chunks.rs @@ -0,0 +1,109 @@ +//! Two split groups: one whose day chunks are all done (the forged shallow +//! server of split_forged_sweep finished them empty) and another whose +//! chunk is still running on a server not indexing here. The first group's +//! sweep doesnt wait for the other's chunks, only for its own: every post of +//! it is indexed. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset`, +/// only those from day `from_day` on +fn posts(offset: u64, from_day: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (from_day * 40..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn a_groups_sweep_waits_only_for_its_own_chunks() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + // "localhost" (the group's home) keeps all 30 days; "127.0.0.1" the last + // 20, with 4 posts in each of its first 3 windows of 100 numbers dated + // the first day + let long = Server::new(posts(1, 0)); + let mut short_posts = posts(500_001, 10); + for window in 0..3 { + for n in 0..4 { + short_posts[window * 100 + n * 20].date = "Thu, 01 Jan 2026 00:30:00 +0000".into(); + } + } + let short = Server::new(short_posts); + let (pl, ps) = (spawn_server(long), spawn_server(short)); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": ps, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": pl, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + drop(atlas::db::create_db().unwrap()); + let main = home.path().join("atlas.db"); + { + // the 30 days split and done by the shallow server, nothing indexed + let conn = atlas::db::open_at(&main).unwrap(); + let first_day = atlas::chunks::unix_day(1_767_225_600); + atlas::chunks::add(&conn, GROUP, first_day + 29, first_day).unwrap(); + let now = chrono::Utc::now().timestamp(); + while let Some(claim) = atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], "127.0.0.1", now).unwrap() + { + assert!(atlas::chunks::finish(&conn, &claim, now).unwrap()); + } + // another split group with a day still running elsewhere + atlas::chunks::add(&conn, "alt.binaries.other", first_day + 29, first_day + 29).unwrap(); + let elsewhere = [("alt.binaries.other".to_string(), i64::MIN)]; + assert!(atlas::chunks::claim(&conn, &elsewhere, "elsewhere", now).unwrap().is_some()); + } + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + if total > 0 && done == total && articles == 1200 { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); +} From 06d12fb0aa6d30ac61590adf639d75452d776532 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:09:55 -0500 Subject: [PATCH 100/159] A stopped conversion copies again when only the old cursors moved The resumed-copy check went by release and article counts and highest ids alone: scans of empty ranges move group cursors without changing those, and another backup can match them, soo the swap could put back stale cursors. The source identity also takes a digest of every groups row now. Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 52 ++++++++++++++++++++++++++++++++++++++++++------ tests/convert.rs | 29 +++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 6 deletions(-) diff --git a/src/convert.rs b/src/convert.rs index 22572d53..2790452f 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -22,6 +22,7 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::time::Instant; use anyhow::{Context, Result, anyhow, bail}; +use rusqlite::types::ValueRef; use rusqlite::{Connection, OpenFlags, OptionalExtension, params}; use crate::compact::{checkpoint, rename_db}; @@ -693,12 +694,15 @@ fn copy( } /// What the old database held when a copy started: its release and article -/// counts and highest ids. A copy is only picked up again from the same old -/// database; one written to or put back from another backup since differs. +/// counts and highest ids, and a digest of its `groups` rows (the cursors: +/// scans of empty ranges move them without adding anything). A copy is only +/// picked up again from the same old database; one written to or put back +/// from another backup since differs. #[derive(Debug, PartialEq)] -struct Source([i64; 4]); +struct Source([i64; 5]); -const SOURCE_KEYS: [&str; 4] = ["source_releases", "source_max_release", "source_articles", "source_max_article"]; +const SOURCE_KEYS: [&str; 5] = + ["source_releases", "source_max_release", "source_articles", "source_max_article", "source_groups"]; impl Source { fn of(old: &Connection) -> Result { @@ -706,7 +710,7 @@ impl Source { old.query_row("select count(*), coalesce(max(id), 0) from releases", [], |r| Ok((r.get(0)?, r.get(1)?)))?; let (articles, max_article) = old.query_row("select count(*), coalesce(max(id), 0) from articles", [], |r| Ok((r.get(0)?, r.get(1)?)))?; - Ok(Source([releases, max_release, articles, max_article])) + Ok(Source([releases, max_release, articles, max_article, groups_digest(old)?])) } /// into the new main database's meta, as the copy starts @@ -718,7 +722,7 @@ impl Source { } fn saved(conn: &Connection) -> Result> { - let mut values = [0; 4]; + let mut values = [0; 5]; for (key, value) in SOURCE_KEYS.iter().zip(values.iter_mut()) { let Some(v) = conn.query_row("select value from meta where key = ?", [key], |r| r.get(0)).optional()? else { @@ -730,6 +734,42 @@ impl Source { } } +/// FNV-1a over every column of every `groups` row in name order, stable +/// across builds (it's kept in the new database's meta between runs) +fn groups_digest(old: &Connection) -> Result { + let mut hash: u64 = 0xcbf2_9ce4_8422_2325; + let mut eat = |bytes: &[u8]| { + for b in bytes { + hash = (hash ^ *b as u64).wrapping_mul(0x0100_0000_01b3); + } + }; + let mut stmt = old.prepare("select * from groups order by name")?; + let columns = stmt.column_count(); + let mut rows = stmt.query([])?; + while let Some(r) = rows.next()? { + for i in 0..columns { + // the type too, soo null and '' and 0 differ + match r.get_ref(i)? { + ValueRef::Null => eat(b"n"), + ValueRef::Integer(v) => { + eat(b"i"); + eat(&v.to_le_bytes()); + } + ValueRef::Real(v) => { + eat(b"r"); + eat(&v.to_le_bytes()); + } + ValueRef::Text(v) | ValueRef::Blob(v) => { + eat(b"t"); + eat(&(v.len() as u64).to_le_bytes()); + eat(v); + } + } + } + } + Ok(hash as i64) +} + /// The shards are complete from an earlier run, copied from the old database /// as it is now (`source`): every shard writer marks its shard once its /// articles are sorted into place. diff --git a/tests/convert.rs b/tests/convert.rs index ff146dcc..03a8f82d 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -395,6 +395,35 @@ fn a_stopped_conversion_copies_again_when_the_old_database_changed() { assert_eq!(store::articles(&conn, id).unwrap().len(), 1); } +/// Scans of empty ranges move an old database's cursors without adding a +/// release or article: a stopped conversion copies again then too, soo the +/// swap doesnt put back the cursors from before and redo those scans. +#[test] +fn a_stopped_conversion_copies_again_when_only_the_cursors_moved() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + db::create_db_at(&main).unwrap(); + + let stopped = std::panic::catch_unwind(|| { + convert::run(&main, &|m| assert!(!m.contains("checking NZBs"), "stop here")).unwrap(); + }); + assert!(stopped.is_err()); + + Connection::open(&main) + .unwrap() + .execute("update groups set backfill_cursor = 7 where name = 'alt.binaries.b'", []) + .unwrap(); + + let messages = std::cell::RefCell::new(Vec::new()); + convert::run(&main, &|m| messages.borrow_mut().push(m.to_string())).unwrap(); + assert!(!messages.borrow().iter().any(|m| m.contains("copy finished earlier")), "{messages:?}"); + let conn = db::open_at(&main).unwrap(); + let cursor: i64 = + conn.query_row("select backfill_cursor from groups where name = 'alt.binaries.b'", [], |r| r.get(0)).unwrap(); + assert_eq!(cursor, 7); +} + /// Stopped between moving the old database aside and putting the new one in /// place: the next start finishes the swap. #[test] From 532c176ed9c5d87434685514336b1bbed516a442 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:16:55 -0500 Subject: [PATCH 101/159] Dropping a fallback copy takes it out of the release and shard totals A copy of a sealed segment saved as a row past a save's decode budget was counted in its release's size and parts and the shard's article total; sealing the file again or compacting dropped the row but kept the counts. Both now take the dropped copies back out, to what one copy gives. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 35 +++++++++++++++++++++++++++++--- src/store.rs | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 3 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 1d9f4d62..9336db2a 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -504,9 +504,15 @@ fn compact_shard( // it goes before the blob is counted, the way `seal_rows` drops it if !segs.is_empty() { let held: HashSet<(&[u8], i64)> = segs.iter().map(|s| (s.local.as_slice(), s.domain)).collect(); - let had = file_rows.len(); - file_rows.retain(|r| !held.contains(&(r.local.as_slice(), r.domain))); - copies += (had - file_rows.len()) as i64; + let (dropped, kept): (Vec, Vec) = + file_rows.into_iter().partition(|r| held.contains(&(r.local.as_slice(), r.domain))); + file_rows = kept; + if !dropped.is_empty() { + // out of the release's and the shard's totals too, copied as they were + let bytes = dropped.iter().map(|r| r.bytes.unwrap_or(0)).sum(); + store::uncount_copies(&tx, f.get(1)?, bytes, dropped.len() as i64)?; + copies += dropped.len() as i64; + } } // rows a blob cant hold exactly (a negative part, no size) stay rows @@ -1095,6 +1101,19 @@ mod tests { assert_eq!(blob_segs_with_known_domains(&main).len() as i64, count); } + /// `file`'s release's size and parts, and its shard's article total + fn release_totals(shard: &Path, file: i64) -> (i64, i64, i64) { + db::open_at(shard) + .unwrap() + .query_row( + "select r.size, r.parts, (select value from meta where key = 'articles') + from releases r join files f on f.release_id = r.id where f.id = ?", + [file], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .unwrap() + } + /// A loose row a sealed file's blob already has (same message-id) goes /// when compaction seals the file, instead of becoming a second copy in /// the blob for good. @@ -1108,6 +1127,7 @@ mod tests { let count = article_total(&main); let (path, file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + let once = release_totals(&path, file); { let conn = db::open_at(&path).unwrap(); let blob: Vec = conn.query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); @@ -1118,11 +1138,20 @@ mod tests { ) .unwrap(); conn.execute("update files set touched_at = 0 where id = ?", [file]).unwrap(); + // counted the way a save past its decode budget counts it + conn.execute( + "update releases set size = size + ?, parts = parts + 1 + where id = (select release_id from files where id = ?)", + params![seg.bytes, file], + ) + .unwrap(); + store::add_totals(&conn, 0, 1).unwrap(); } assert_eq!(article_total(&main), count + 1); run(&main, &|_| {}, &no_stop()).unwrap(); assert_eq!(article_total(&main), count, "the copy went, not into the blob"); + assert_eq!(release_totals(&path, file), once, "and out of its release's and the shard's totals"); assert_eq!(loose(&main), 0); assert_eq!(all_articles(&main), before, "every NZB reads back the same"); } diff --git a/src/store.rs b/src/store.rs index 6f5305a3..07c75a8a 100644 --- a/src/store.rs +++ b/src/store.rs @@ -717,6 +717,11 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { conn.prepare_cached("delete from segments where file_id = ? and local = ? and domain = ?")? .execute(params![file_id, copy.local, copy.domain])?; } + if !copies.is_empty() { + let release_id: i64 = + conn.prepare_cached("select release_id from files where id = ?")?.query_row([file_id], |r| r.get(0))?; + uncount_copies(conn, release_id, copies.iter().map(|c| c.bytes).sum(), copies.len() as i64)?; + } // too much for one blob in memory: the rest stays rows, the blob as it is if segs.len() + rows.len() > SEAL_MAX_SEGMENTS as usize { return Ok(0); @@ -1133,6 +1138,16 @@ pub(crate) fn add_totals(conn: &Connection, releases: i64, articles: i64) -> Res Ok(()) } +/// Take `count` dropped copies of `bytes` in all out of release +/// `release_id`'s size and parts and the shard's article total: the save +/// that kept them as rows counted them (see `SealedCache`). +pub(crate) fn uncount_copies(conn: &Connection, release_id: i64, bytes: i64, count: i64) -> Result<()> { + conn.prepare_cached("update releases set size = size - ?, parts = parts - ? where id = ?")? + .execute(params![bytes, count, release_id])?; + conn.prepare_cached("update meta set value = value - ? where key = 'articles'")?.execute([count])?; + Ok(()) +} + /// Save releases from anywhere (AI search): each to its group's shard, in one /// transaction per shard. pub fn save(main: &Path, releases: &[Release]) -> Result<()> { @@ -1642,6 +1657,46 @@ mod tests { assert_eq!(seal_file(&conn, a).unwrap(), 3, "the copy isnt added"); } + /// A copy saved as a row counted in its release's size and parts and the + /// shard's article total: dropping it when the file is sealed again + /// takes it out of them too, back to what one copy gives. + #[test] + fn dropping_a_copy_takes_it_out_of_the_release_and_shard_totals() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let a: i64 = conn.query_row("select id from files where filename = 'a.rar'", [], |r| r.get(0)).unwrap(); + seal_file(&conn, a).unwrap(); + let totals = || -> (i64, i64, i64) { + conn.query_row( + "select r.size, r.parts, (select value from meta where key = 'articles') + from releases r join files f on f.release_id = r.id where f.id = ?", + [a], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)), + ) + .unwrap() + }; + let once = totals(); + + // the copy as a save past its decode budget puts it in + let first = sealed_segments(&conn, a).unwrap().unwrap().remove(0); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", + params![a, first.local, first.domain, first.part, first.bytes], + ) + .unwrap(); + conn.execute( + "update releases set size = size + ?, parts = parts + 1 + where id = (select release_id from files where id = ?)", + params![first.bytes, a], + ) + .unwrap(); + add_totals(&conn, 0, 1).unwrap(); + assert_ne!(totals(), once); + + seal_file(&conn, a).unwrap(); + assert_eq!(totals(), once); + } + /// A row a full blob already has is dropped, not left a row because /// adding it would go past the cap. #[test] From 520f3d87760406036b1198c97722ae22b57bc212 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:27:04 -0500 Subject: [PATCH 102/159] A carrier's sweep cursor doesnt count as a second home in the split homes test Co-Authored-By: Claude Opus 5.5 --- tests/split_homes.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/split_homes.rs b/tests/split_homes.rs index 6f775c10..5e117eb4 100644 --- a/tests/split_homes.rs +++ b/tests/split_homes.rs @@ -103,14 +103,19 @@ fn a_server_without_the_group_doesnt_move_it() { let conn = atlas::db::open_with_shards(&main).unwrap(); assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); - let cursors: Vec = conn - .prepare("select name from groups where name like ? order by name") + // (cursor, whether a normal pass ran on it): the home's passes save the + // server's bounds, a carrier's sweep (its own cursor, see run_sweep) doesnt + let cursors: Vec<(String, bool)> = conn + .prepare("select name, last_article is not null from groups where name like ? order by name") .unwrap() - .query_map([format!("{SPLIT_GROUP}%")], |r| r.get(0)) + .query_map([format!("{SPLIT_GROUP}%")], |r| Ok((r.get(0)?, r.get(1)?))) .unwrap() .collect::>() .unwrap(); - assert_eq!(cursors.len(), 1, "the group stayed on one home server: {cursors:?}"); + let homes = cursors.iter().filter(|(_, home)| *home).count(); + assert_eq!(homes, 1, "the group stayed on one home server: {cursors:?}"); + let carriers = [format!("{SPLIT_GROUP}@127.0.0.1"), format!("{SPLIT_GROUP}@localhost")]; + assert!(cursors.iter().all(|(name, _)| carriers.contains(name)), "only carriers have cursors: {cursors:?}"); let chunk_servers: Vec = conn .prepare("select distinct server from backfill_chunks where state = 2 order by server") From e163025fdefbd4c8e0289fedc2a88eb14d07d588 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:27:37 -0500 Subject: [PATCH 103/159] Reaching a split back undoes its carriers' sweeps Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/chunks.rs b/src/chunks.rs index a7636c97..ac4214a4 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -82,7 +82,8 @@ pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> /// before the split's oldest one back to `oldest_day`. The old oldest day /// was done (if it was) only from where the server going back furthest then /// started: it is to do again, and that server is forgotten (see `deepest`). -/// A claim on it is cleared too, so its worker's finish does nothing. +/// A claim on it is cleared too, so its worker's finish does nothing, and +/// the carriers' sweeps are to do again. /// Also when `oldest_day` is the oldest day but `oldest_at` is before where /// that server started in it. Returns the chunks added or to do again. pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i64) -> Result { @@ -116,6 +117,8 @@ pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i6 params![group, old], )?; tx.execute("delete from backfill_deepest where grp = ?", [group])?; + // a carrier's sweep stopped at its first article then: it may keep older ones now + tx.execute("delete from backfill_sweeps where grp = ?", [group])?; tx.commit()?; Ok(added + redo) } @@ -406,6 +409,25 @@ mod tests { assert_eq!(day(claim(&c, &groups, "b", 1001)), Some(10)); } + /// a carrier swept down to its first article before the split reached + /// back sweeps again: its first article may be older now + #[test] + fn reaching_back_undoes_the_sweeps() { + let c = conn(); + add(&c, "g", 12, 10).unwrap(); + c.execute("update backfill_chunks set state = 2", []).unwrap(); + set_deepest(&c, "g", "a", 10 * 86_400 + 18 * 3600).unwrap(); + set_swept(&c, "g", "b").unwrap(); + set_swept(&c, "other", "b").unwrap(); + + assert_eq!(reach_back(&c, "g", 10, 10 * 86_400 + 20 * 3600).unwrap(), 0, "not further"); + assert!(swept(&c, "g", "b").unwrap(), "kept when nothing changed"); + + assert_eq!(reach_back(&c, "g", 9, 9 * 86_400).unwrap(), 2); + assert!(!swept(&c, "g", "b").unwrap(), "to sweep again"); + assert!(swept(&c, "other", "b").unwrap(), "other groups' sweeps stay"); + } + #[test] fn stale_claims_are_taken_over() { let c = conn(); From e867337a79c4087126bac237941c16aff6c8ca4c Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:28:14 -0500 Subject: [PATCH 104/159] Wiping the database takes a conversion's old and new main databases too Co-Authored-By: Claude Opus 5.5 --- src/db.rs | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/src/db.rs b/src/db.rs index 319ed2a2..ad0214cf 100644 --- a/src/db.rs +++ b/src/db.rs @@ -150,7 +150,8 @@ pub fn create_db_holding(path: &Path) -> anyhow::Result> { } /// Settings > wipe: every shard, with their sidecars and what a compaction -/// leaves (`.compact.db`, `.precompact.db`), then the main database. Under +/// leaves (`.compact.db`, `.precompact.db`), a conversion's `atlas.old.db` +/// and `atlas.new.db`, then the main database. Under /// the exclusive compaction lock, soo refused (`Busy`) while the indexer, a /// write from outside it or a compaction has the database. Leaves nothing to /// set up again from: the next `create_db` makes a new one. The main @@ -165,6 +166,10 @@ pub fn wipe(main: &Path) -> anyhow::Result<()> { dbs.push(crate::compact::with_suffix(&shard, "precompact")); dbs.push(shard); } + // a conversion's backup or undone new main database would be put back + // as the main database at the next start (see `convert::recover_cut_swap`) + dbs.push(main.with_file_name("atlas.old.db")); + dbs.push(main.with_file_name("atlas.new.db")); dbs.push(main.to_path_buf()); for db in dbs { for suffix in ["", "-wal", "-shm", "-journal"] { @@ -751,6 +756,34 @@ mod tests { assert!(group_progress(&open_at(&main).unwrap()).unwrap().is_empty(), "no cursors"); } + /// a conversion's atlas.old.db (kept after it) or atlas.new.db (a swap + /// undone) would be put back as the main database at the next start + #[test] + fn a_wipe_takes_a_conversions_leftovers_too() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + create_db_at(&main).unwrap(); + init_group_state(&open_at(&main).unwrap(), "alt.binaries.a@news.x", 500).unwrap(); + let mut leftovers = Vec::new(); + for name in ["atlas.old.db", "atlas.new.db"] { + let db = dir.path().join(name); + std::fs::copy(&main, &db).unwrap(); + for suffix in ["-wal", "-shm", "-journal"] { + let sidecar = PathBuf::from(format!("{}{suffix}", db.display())); + std::fs::write(&sidecar, b"").unwrap(); + leftovers.push(sidecar); + } + leftovers.push(db); + } + + wipe(&main).unwrap(); + for f in &leftovers { + assert!(!f.exists(), "{} is gone", f.display()); + } + create_db_holding(&main).unwrap(); + assert!(group_progress(&open_at(&main).unwrap()).unwrap().is_empty(), "nothing came back"); + } + #[test] fn a_wipe_that_cant_remove_a_shard_keeps_the_main_database() { let dir = tempfile::tempdir().unwrap(); From cf19e37ca63d570903d47638d11a57baee770a91 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:29:25 -0500 Subject: [PATCH 105/159] A group never falls over to a server kept out of indexing Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 17 ++++++----------- tests/multi_server.rs | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/src/nntp.rs b/src/nntp.rs index a6a16a35..4e2f4ce6 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1425,8 +1425,8 @@ impl Pool { Ok(info) } - /// GROUP on server `prefer`, falling over (in priority order) to a server - /// that carries it. Returns the server used. + /// GROUP on server `prefer`, falling over to an indexing server that + /// carries it. Returns the server used. pub async fn select_group_on(&self, prefer: usize, group: &str) -> Result<(usize, (u64, u64, u64, String))> { let first_err = match self.select_on(prefer, group).await { Ok(r) => return Ok((prefer, r)), @@ -1435,15 +1435,10 @@ impl Pool { Err(e) => return Err(e), }; - let usable = |i: &usize| *i != prefer && !self.servers[*i].no_index.load(Ordering::Relaxed); - let indexing: Vec = self.indexing_servers().into_iter().filter(usable).collect(); - let candidates: Vec = self - .ranked(&indexing, group) - .into_iter() - .chain((0..self.servers.len()).filter(|i| usable(i) && !indexing.contains(i))) - .collect(); - - for i in candidates { + // indexing servers only: one with `index: false` (a metered block + // account) is for article lookups, never a group's home + let indexing: Vec = self.indexing_servers().into_iter().filter(|&i| i != prefer).collect(); + for i in self.ranked(&indexing, group) { if let Ok(r) = self.select_on(i, group).await { println!("{group} not on {}, using {}", self.servers[prefer].cfg.host, self.servers[i].cfg.host); self.homes.lock().unwrap().insert(group.to_string(), i); diff --git a/tests/multi_server.rs b/tests/multi_server.rs index c04bca7b..246d9df8 100644 --- a/tests/multi_server.rs +++ b/tests/multi_server.rs @@ -157,3 +157,23 @@ fn name_lookups_fall_back_on_a_missing_article() { assert!(pool.first_names(jobs).iter().all(Option::is_some)); assert_eq!(has.bodies_sent.load(Ordering::SeqCst), 10); } + +/// A group the indexing servers dont carry isnt indexed on a server with +/// `index: false` (a metered block account kept for article lookups) that does. +#[test] +fn a_group_never_falls_over_to_a_server_kept_out_of_indexing() { + let posts: Vec = (1..=10).map(|n| post(n, &format!(r#""thing{n}.rar" yEnc (1/1)"#), 10, vec![])).collect(); + let indexing = Server::new(posts.clone()); + indexing.dropped.store(true, Ordering::SeqCst); + let block = Server::new(posts); + let (p1, p2) = (spawn_server(indexing), spawn_server(block)); + + let mut kept_out = mock(p2, "secret", 2, 2); + kept_out.index = Some(false); + let pool = BlockingPool::new(&[mock(p1, "secret", 2, 1), kept_out]); + pool.connect().unwrap(); + + let err = pool.select_group(GROUP).expect_err("only the block account carries it"); + assert_eq!(err.code(), Some(411), "{err}"); + assert_eq!(pool.active_index(), 0, "still on the indexing server"); +} From ac50239241ef6199613ed9a75e98efd4fbdf5470 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:30:46 -0500 Subject: [PATCH 106/159] A due sweep comes before other split groups' day chunks Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 117 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 93 insertions(+), 24 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 9f7c4cbe..0ad29a70 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -527,36 +527,56 @@ async fn take_sweep(sched: &Scheduler, server: usize, db: &Db) -> Option found } +/// What a worker with no group of its own does. +enum IdleWork { + Chunk(crate::chunks::Claim), + Sweep(String), +} + +/// Work for an idle worker on `server`: a due sweep of a split group whose +/// chunks are done (see `take_sweep`) before any day chunk, soo another +/// group's endless chunks dont hold it off until what it would find ages +/// out. One worker per server sweeps at a time, the others take chunks. +async fn take_idle_work(sched: &Scheduler, server: usize, db: &Db) -> Option { + if let Some(group) = take_sweep(sched, server, db).await { + return Some(IdleWork::Sweep(group)); + } + take_chunk(sched, server, db).await.map(IdleWork::Chunk) +} + /// One worker on `server`: index whichever of its groups is due next, again and again. /// All workers share one db connection, soo their writes queue up in order /// instead of racing for sqlite's write lock (and timing out on a busy db). async fn worker(sched: Arc, server: usize, db: Db) { while !sched.stopping() { let Some(group) = sched.take_group(server) else { - // nothing of its own: help with a split group's day chunks. not - // marked busy, a group's chunks run on several servers at once - if let Some(chunk) = take_chunk(&sched, server, &db).await { - let settings = sched.settings.read().unwrap().clone(); - let stats = sched.stats.clone(); - let group = chunk.group.clone(); - let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); - let run = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &chunk, server, &mut progress); - let Some(result) = unless_stopped(&sched.ctx.stop, run).await else { break }; - sched.finish_chunk(chunk.group, server, result); - continue; - } - // or, once a split group's chunks are done, sweep this server's - // numbers of it for what they missed (one worker per server at a time) - if let Some(group) = take_sweep(&sched, server, &db).await { - let settings = sched.settings.read().unwrap().clone(); - let stats = sched.stats.clone(); - let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); - let run = crate::indexer::run_sweep(&sched.ctx, &settings, &db, &group, server, &mut progress); - let result = unless_stopped(&sched.ctx.stop, run).await; - sched.sweeping.lock().unwrap().remove(&server); - let Some(result) = result else { break }; - sched.finish_chunk(group, server, result); - continue; + match take_idle_work(&sched, server, &db).await { + // help with a split group's day chunks. not marked busy, a + // group's chunks run on several servers at once + Some(IdleWork::Chunk(chunk)) => { + let settings = sched.settings.read().unwrap().clone(); + let stats = sched.stats.clone(); + let group = chunk.group.clone(); + let mut progress = + |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); + let run = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &chunk, server, &mut progress); + let Some(result) = unless_stopped(&sched.ctx.stop, run).await else { break }; + sched.finish_chunk(chunk.group, server, result); + continue; + } + Some(IdleWork::Sweep(group)) => { + let settings = sched.settings.read().unwrap().clone(); + let stats = sched.stats.clone(); + let mut progress = + |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); + let run = crate::indexer::run_sweep(&sched.ctx, &settings, &db, &group, server, &mut progress); + let result = unless_stopped(&sched.ctx.stop, run).await; + sched.sweeping.lock().unwrap().remove(&server); + let Some(result) = result else { break }; + sched.finish_chunk(group, server, result); + continue; + } + None => {} } nap(Duration::from_secs(1), || sched.stopping()).await; continue; @@ -1011,4 +1031,53 @@ mod tests { assert_eq!(chunk_groups("dynamic", &groups, &HashSet::new()).len(), 2); assert!(chunk_groups("live", &groups, &HashSet::new()).is_empty(), "live never backfills"); } + + /// a sweep due on a server comes before another group's day chunks + #[test] + fn a_due_sweep_comes_before_other_groups_chunks() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let pool = Pool::new(&[UsenetServer::new("a.test", "u", "p", 119), UsenetServer::new("b.test", "u", "p", 119)]); + // "done" split with its chunks all done, "busy" with many to go + let conn = db::open_at(&main).unwrap(); + crate::chunks::add(&conn, "done", 20_000, 19_990).unwrap(); + conn.execute("update backfill_chunks set state = 2 where grp = 'done'", []).unwrap(); + crate::chunks::add(&conn, "busy", 20_000, 10_000).unwrap(); + // the server that isnt done's home sweeps it + let server = 1 - pool.pick_server("done"); + let sched = Scheduler { + ctx: PassContext { + pool: Arc::new(pool), + states: RunStates::default(), + stop: Default::default(), + verbose: false, + }, + settings: RwLock::new(PassSettings { mode: "backfill".into(), ..PassSettings::default() }), + groups: RwLock::new(vec!["busy".into(), "done".into()]), + plan: vec![], + workers: 2, + next: Default::default(), + busy: Default::default(), + skip: Default::default(), + chunk_errors: Default::default(), + sweeping: Default::default(), + wait_until: Default::default(), + errors: Default::default(), + failed: Default::default(), + stats: Arc::new(Mutex::new(Stats::new())), + wind_down: AtomicBool::new(false), + compact_due: AtomicBool::new(false), + compact_after: None, + auto_compact: AtomicBool::new(false), + passes: AtomicUsize::new(0), + }; + let db = shared_db(conn); + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async { + assert!(matches!(take_idle_work(&sched, server, &db).await, Some(IdleWork::Sweep(g)) if g == "done")); + // one sweep per server at a time: the next worker takes a chunk + assert!(matches!(take_idle_work(&sched, server, &db).await, Some(IdleWork::Chunk(c)) if c.group == "busy")); + }); + } } From 41e0e4145ff54d76ae1498f3adc1fc66aee1b0cf Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:37:50 -0500 Subject: [PATCH 107/159] Days before every server's first post are dropped from a split A split made from forged first dates can reach back years; those chunks waited for a server forever and kept the split, and its sweeps, from completing. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 23 ++++++++++ src/indexer.rs | 41 +++++++++++++++++ tests/date_search.rs | 9 ++-- tests/split_bogus_days.rs | 92 +++++++++++++++++++++++++++++++++++++++ 4 files changed, 161 insertions(+), 4 deletions(-) create mode 100644 tests/split_bogus_days.rs diff --git a/src/chunks.rs b/src/chunks.rs index ac4214a4..2810ead3 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -123,6 +123,17 @@ pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i6 Ok(added + redo) } +/// Drop split `group`'s chunks older than `day` that arent done: days no +/// carrier keeps (a split reaching back that far was made from forged +/// dates), which would wait for a server forever and keep the split from +/// completing. Returns the chunks dropped. +pub fn drop_before(conn: &Connection, group: &str, day: i64) -> Result { + conn.execute( + &format!("delete from backfill_chunks where grp = ? and day < ? and state != {DONE}"), + params![group, day], + ) +} + /// Check if a group has any chunks in backfill. pub fn is_split(conn: &Connection, group: &str) -> Result { conn.prepare_cached("select 1 from backfill_chunks where grp = ? limit 1")?.exists([group]) @@ -428,6 +439,18 @@ mod tests { assert!(swept(&c, "other", "b").unwrap(), "other groups' sweeps stay"); } + #[test] + fn days_before_are_dropped_unless_done() { + let c = conn(); + add(&c, "g", 12, 5).unwrap(); + add(&c, "h", 12, 5).unwrap(); + c.execute("update backfill_chunks set state = 2 where grp = 'g' and day = 6", []).unwrap(); + claim(&c, &[("g".to_string(), i64::MIN)], "a", 1000).unwrap(); + assert_eq!(drop_before(&c, "g", 8).unwrap(), 2, "days 5 and 7"); + assert_eq!(oldest_day(&c, "g").unwrap(), Some(6), "a done day stays"); + assert_eq!(progress(&c, "h").unwrap(), (0, 8), "other groups untouched"); + } + #[test] fn stale_claims_are_taken_over() { let c = conn(); diff --git a/src/indexer.rs b/src/indexer.rs index b387f9bb..2f63e28b 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -52,6 +52,9 @@ pub struct GroupRunState { /// give to another), the oldest day it keeps of the group (as found by a /// day chunk too old for it), until it's looked at again pub keeps_from: HashMap, + /// likewise the day of its first post, `i64::MAX` when it has none or + /// doesnt carry the group (see `drop_unkept_days`) + pub first_post_days: HashMap, } impl Default for GroupRunState { @@ -63,6 +66,7 @@ impl Default for GroupRunState { no_split_until: None, reach_back_after: None, keeps_from: HashMap::new(), + first_post_days: HashMap::new(), } } } @@ -102,6 +106,20 @@ impl RunStates { self.with(group, |st| st.keeps_from.insert(host.to_string(), (day, Instant::now() + KEEPS_RECHECK))); } + /// Note `day` as the day of the server `host`'s first post of `group`, + /// until it's looked at again. + fn first_post_on(&self, group: &str, host: &str, day: i64) { + self.with(group, |st| st.first_post_days.insert(host.to_string(), (day, Instant::now() + KEEPS_RECHECK))); + } + + /// The day of the server `host`'s first post of `group`, `i64::MIN` when not known. + fn first_post_day(&self, group: &str, host: &str) -> i64 { + let now = Instant::now(); + let states = self.0.lock().unwrap(); + let found = states.get(group).and_then(|s| s.first_post_days.get(host)); + found.filter(|(_, until)| *until > now).map_or(i64::MIN, |(day, _)| *day) + } + /// The groups whose oldest day on the server `host` is known, with that day. pub fn kept_days(&self, host: &str) -> HashMap { let now = Instant::now(); @@ -677,6 +695,25 @@ fn split_bounds(newest: &Newest, home_oldest: i64, oldest_at: i64, today: i64) - (oldest_day >= SPLIT_OLDEST_DAY && newest_day >= oldest_day).then_some((newest_day, oldest_day)) } +/// Once every indexing server turned a day chunk of `group` down as too old +/// for it, drop its chunks of days before the first post of all of them: +/// no server has anything from those, and a split made from forged first +/// dates can reach back years. Left alone, those chunks wait for a server +/// forever and the split never completes (its sweeps never run). Best +/// effort: a failure is only logged. +async fn drop_unkept_days(ctx: &PassContext, db: &Db, group: &str) { + let first = + ctx.pool.indexing_servers().into_iter().map(|i| ctx.states.first_post_day(group, &ctx.pool.host(i))).min(); + // i64::MIN: a server not asked yet (or a while ago) + let Some(first) = first.filter(|&d| d != i64::MIN) else { return }; + let g = group.to_string(); + match on_db(db, move |conn| Ok(crate::chunks::drop_before(conn, &g, first)?)).await { + Ok(0) => {} + Ok(n) => println!("[CHUNK] {group}: {n} days older than any server keeps, dropped (forged Date headers?)"), + Err(e) => println!("[CHUNK] {group}: couldnt drop the days no server keeps: {e:#}"), + } +} + /// A day chunk's server doesnt carry its group (GROUP answered 411). #[derive(Debug)] pub struct NotCarried { @@ -905,6 +942,8 @@ where let found = match ctx.pool.group_on(server, group).await { Ok(info) => info, Err(e) if e.code() == Some(411) => { + // it has no post of it (see `drop_unkept_days`) + ctx.states.first_post_on(group, &ctx.pool.host(server), i64::MAX); // if it was noted as going back furthest, the oldest day goes to the next one let (g, host) = (group.to_string(), ctx.pool.host(server)); if let Err(e) = on_db(db, move |conn| Ok(crate::chunks::forget_deepest(conn, &g, &host)?)).await { @@ -964,6 +1003,7 @@ where let oldest_day = keeps_from.map_or(i64::MAX, |t| crate::chunks::unix_day(t - 1) + 1); let host = ctx.pool.host(server); ctx.states.keep_from(group, &host, oldest_day); + ctx.states.first_post_on(group, &host, oldest.map_or(i64::MAX, crate::chunks::unix_day)); println!("[CHUNK] {group} day {day} is older than {host} keeps, leaving it to the other servers"); // a server that doesnt keep this day keeps none of the split's oldest // either: if it was noted as going back furthest, its retention moved @@ -972,6 +1012,7 @@ where if let Err(e) = on_db(db, move |conn| Ok(crate::chunks::forget_deepest(conn, &g, &h)?)).await { println!("[CHUNK] {group}: couldnt forget the server going back furthest: {e:#}"); } + drop_unkept_days(ctx, db, group).await; return failed(TooOld { group: group.to_string(), host, oldest_day }.into()).await; } // the split's days and, for its newest, how far down this server's diff --git a/tests/date_search.rs b/tests/date_search.rs index aa3ae5d9..ed506b03 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -431,11 +431,12 @@ fn a_day_older_than_the_server_keeps_is_given_back() { let empty = run(first_day + 1).unwrap(); assert_eq!(empty.articles, 2, "only the overlap hours"); let conn = atlas::db::open_at(&main).unwrap(); - let state = |day: i64| -> i64 { - conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).unwrap() + let state = |day: i64| -> Option { + conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).ok() }; - assert_eq!(state(first_day - 1), 0, "given back, still pending"); - assert_eq!(state(first_day + 1), 2, "an empty day it keeps is done"); + // the only server: no server has a post that old, the day is dropped + assert_eq!(state(first_day - 1), None, "before every server's first post, dropped"); + assert_eq!(state(first_day + 1), Some(2), "an empty day it keeps is done"); } /// Stopping drops a chunk part way (here on a request stuck on the network): diff --git a/tests/split_bogus_days.rs b/tests/split_bogus_days.rs new file mode 100644 index 00000000..7570ef35 --- /dev/null +++ b/tests/split_bogus_days.rs @@ -0,0 +1,92 @@ +//! A split group on two servers that reaches back 200 days before either +//! keeps anything, as one made from forged Date headers in a carrier's +//! first windows would: once every carrier said it doesnt keep those days +//! they are dropped, soo the split completes (its sweeps run) and every +//! post is indexed, instead of the days waiting for a server forever. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset`, +/// only those from day `from_day` on +fn posts(offset: u64, from_day: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (from_day * 40..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn days_no_carrier_keeps_are_dropped() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + let (pa, pb) = (spawn_server(Server::new(posts(1, 0))), spawn_server(Server::new(posts(500_001, 0)))); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pa, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": pb, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + drop(atlas::db::create_db().unwrap()); + let main = home.path().join("atlas.db"); + let first_day = atlas::chunks::unix_day(1_767_225_600); + { + // the 30 days and 200 before them that no server keeps + let conn = atlas::db::open_at(&main).unwrap(); + atlas::chunks::add(&conn, GROUP, first_day + 29, first_day - 200).unwrap(); + } + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let deadline = Instant::now() + Duration::from_secs(60); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + let swept = ["127.0.0.1", "localhost"].iter().any(|h| atlas::chunks::swept(&conn, GROUP, h).unwrap()); + if total > 0 && done == total && articles == 1200 && swept { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}, swept {swept}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + let conn = atlas::db::open_with_shards(&main).unwrap(); + assert_eq!(atlas::store::totals(&conn).unwrap().1, 1200, "every post once"); + let oldest = atlas::chunks::oldest_day(&conn, GROUP).unwrap().unwrap(); + assert!(oldest >= first_day - 1, "the days nobody keeps are gone: {oldest} vs {first_day}"); +} From b016b68f073db42a4dcee95e4dcc434d7fdf9aad Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:57:15 -0500 Subject: [PATCH 108/159] A server not carrying a group stays noted as such, so its first-post evidence doesnt expire Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 2f63e28b..33d9fc39 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -53,8 +53,10 @@ pub struct GroupRunState { /// day chunk too old for it), until it's looked at again pub keeps_from: HashMap, /// likewise the day of its first post, `i64::MAX` when it has none or - /// doesnt carry the group (see `drop_unkept_days`) - pub first_post_days: HashMap, + /// doesnt carry the group (see `drop_unkept_days`); a server not carrying + /// the group is noted for good (no expiry): the scheduler skips it for + /// good too + pub first_post_days: HashMap)>, } impl Default for GroupRunState { @@ -109,7 +111,12 @@ impl RunStates { /// Note `day` as the day of the server `host`'s first post of `group`, /// until it's looked at again. fn first_post_on(&self, group: &str, host: &str, day: i64) { - self.with(group, |st| st.first_post_days.insert(host.to_string(), (day, Instant::now() + KEEPS_RECHECK))); + self.with(group, |st| st.first_post_days.insert(host.to_string(), (day, Some(Instant::now() + KEEPS_RECHECK)))); + } + + /// Note the server `host` as not carrying `group`, with no expiry. + fn not_carrying(&self, group: &str, host: &str) { + self.with(group, |st| st.first_post_days.insert(host.to_string(), (i64::MAX, None))); } /// The day of the server `host`'s first post of `group`, `i64::MIN` when not known. @@ -117,7 +124,7 @@ impl RunStates { let now = Instant::now(); let states = self.0.lock().unwrap(); let found = states.get(group).and_then(|s| s.first_post_days.get(host)); - found.filter(|(_, until)| *until > now).map_or(i64::MIN, |(day, _)| *day) + found.filter(|(_, until)| until.is_none_or(|u| u > now)).map_or(i64::MIN, |(day, _)| *day) } /// The groups whose oldest day on the server `host` is known, with that day. @@ -943,7 +950,7 @@ where Ok(info) => info, Err(e) if e.code() == Some(411) => { // it has no post of it (see `drop_unkept_days`) - ctx.states.first_post_on(group, &ctx.pool.host(server), i64::MAX); + ctx.states.not_carrying(group, &ctx.pool.host(server)); // if it was noted as going back furthest, the oldest day goes to the next one let (g, host) = (group.to_string(), ctx.pool.host(server)); if let Err(e) = on_db(db, move |conn| Ok(crate::chunks::forget_deepest(conn, &g, &host)?)).await { @@ -1535,6 +1542,24 @@ mod tests { assert!(states.kept_days("b.example").is_empty()); } + #[test] + fn a_server_not_carrying_a_group_stays_noted_but_other_first_posts_expire() { + let states = RunStates::default(); + states.not_carrying("g", "a.example"); + states.first_post_on("g", "b.example", 20_000); + assert_eq!(states.first_post_day("g", "b.example"), 20_000); + let past = Instant::now() - Duration::from_secs(1); + states.with("g", |st| { + for (_, until) in st.first_post_days.values_mut() { + if until.is_some() { + *until = Some(past); + } + } + }); + assert_eq!(states.first_post_day("g", "a.example"), i64::MAX, "no expiry for a non-carrier"); + assert_eq!(states.first_post_day("g", "b.example"), i64::MIN, "an ordinary first post expires"); + } + #[test] fn slices_cover_the_range() { assert_eq!(make_slices(1, 10, 4, false), vec![(1, 4), (5, 8), (9, 10)]); From 5f8356ee5d3b89df5f4cd8586173a2a5472151e5 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:57:15 -0500 Subject: [PATCH 109/159] A file with a message-id too long for a blob stays rows, and a blob always decodes under its cap Co-Authored-By: Claude Opus 5.5 --- src/blob.rs | 21 ++++++++++++++++++++- src/compact.rs | 6 ++++-- src/store.rs | 41 ++++++++++++++++++++++++++++++++++++++--- 3 files changed, 62 insertions(+), 6 deletions(-) diff --git a/src/blob.rs b/src/blob.rs index 50d77ad5..c57204d7 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -75,8 +75,17 @@ pub fn decode(blob: &[u8]) -> Result> { parse(&zstd::stream::decode_all(blob)?, usize::MAX) } -/// the most a segment takes unpacked, for bounding what a blob may expand to +/// the most local bytes a segment may have to be sealed: a file with a longer +/// one stays rows (a message-id is 250 bytes at most, a stored one a domain +/// suffix less) +pub const MAX_LOCAL: usize = 512; + +/// the most a segment takes unpacked, for bounding what a blob may expand to: +/// its local bytes (`MAX_LOCAL`, and up to 253 more when a compaction stores +/// the message-id with its domain suffix again) and four varints of 10 bytes +/// at most, 32 with the length's const MAX_SEG_RAW: usize = 1024; +const _: () = assert!(MAX_LOCAL + 253 + 32 <= MAX_SEG_RAW); /// `decode` for a blob of at most `max` segments: one that says it has more, /// or unpacks to more than `max` segments could take, is an error and is @@ -143,6 +152,16 @@ mod tests { assert!(decode_capped(b"garbage", 10).is_err()); } + #[test] + fn the_longest_sealable_segment_decodes_under_the_cap() { + let segs = + vec![ + Seg { part: Some(i64::MAX - 1), bytes: i64::MIN, domain: i64::MAX, local: vec![7; MAX_LOCAL + 253] }; + 3 + ]; + assert_eq!(decode_capped(&encode(&segs), 3).unwrap(), segs); + } + #[test] fn segments_come_back_exactly() { let segs = vec![ diff --git a/src/compact.rs b/src/compact.rs index 9336db2a..3e330d2b 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -515,8 +515,10 @@ fn compact_shard( } } - // rows a blob cant hold exactly (a negative part, no size) stay rows - let fits = file_rows.iter().all(|r| r.part.is_none_or(|p| p >= 0) && r.bytes.is_some()); + // rows a blob cant hold exactly (a negative part, no size, a long message-id) stay rows + let fits = file_rows + .iter() + .all(|r| r.part.is_none_or(|p| p >= 0) && r.bytes.is_some() && r.local.len() <= blob::MAX_LOCAL); let seen: Vec = f.get(8)?; // and files with more segments than a blob takes stay rows let small = (segs.len() + file_rows.len()) as i64 <= store::SEAL_MAX_SEGMENTS; diff --git a/src/store.rs b/src/store.rs index 07c75a8a..df2960ae 100644 --- a/src/store.rs +++ b/src/store.rs @@ -704,7 +704,8 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { return Ok(segs.len()); } // the blob has no room for a negative part number: such a file stays rows - if rows.iter().any(|r| r.part.is_some_and(|p| p < 0)) { + // nor one whose message-id is longer than a blob decodes + if rows.iter().any(|r| r.part.is_some_and(|p| p < 0) || r.local.len() > crate::blob::MAX_LOCAL) { return Ok(0); } // a row the blob already has (saved past a save's decode budget, see @@ -745,8 +746,9 @@ pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) let mut stmt = conn.prepare_cached(&format!( "select f.id, f.expected, f.seen, f.touched_at, f.blob is not null, exists (select 1 from segments s where s.file_id = f.id), - exists (select 1 from segments s where s.file_id = f.id and s.part < 0) or {} + exists (select 1 from segments s where s.file_id = f.id and (s.part < 0 or length(s.local) > {})) or {} from files f where f.id > ? order by f.id limit ?", + crate::blob::MAX_LOCAL, too_many_rows() ))?; let mut ids = Vec::new(); @@ -774,8 +776,9 @@ fn still_due(conn: &Connection, file_id: i64, now: i64) -> Result { conn.prepare_cached(&format!( "select f.expected, f.seen, f.touched_at, f.blob is not null, exists (select 1 from segments s where s.file_id = f.id), - exists (select 1 from segments s where s.file_id = f.id and s.part < 0) or {} + exists (select 1 from segments s where s.file_id = f.id and (s.part < 0 or length(s.local) > {})) or {} from files f where f.id = ?", + crate::blob::MAX_LOCAL, too_many_rows() ))? .query_row([file_id], |r| { @@ -1896,6 +1899,38 @@ mod tests { assert_eq!(seal_file(&conn, ids[1]).unwrap(), 0); } + #[test] + fn a_file_with_an_oversized_message_id_stays_rows_and_saves_succeed() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let now: i64 = conn.query_row("select unixepoch()", [], |r| r.get(0)).unwrap(); + let b: i64 = conn.query_row("select id from files where filename = 'b.rar'", [], |r| r.get(0)).unwrap(); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, zeroblob(5000), 0, 9, 1)", + [b], + ) + .unwrap(); + conn.execute("update files set touched_at = ?", [now - SEAL_AGE - 1]).unwrap(); + assert!(!sealable(&conn, 0, 100, now).unwrap().0.contains(&b)); + assert_eq!(seal_file(&conn, b).unwrap(), 0); + let blob: Option> = conn.query_row("select blob from files where id = ?", [b], |r| r.get(0)).unwrap(); + assert!(blob.is_none() || crate::blob::decode_capped(&blob.unwrap(), SEAL_MAX_SEGMENTS as usize).is_ok()); + let again = Release { + name: "r".into(), + group: "alt.binaries.t".into(), + articles: vec![Article { + message_id: "".into(), + filename: Some("b.rar".into()), + part: Some(10), + total_parts: Some(3), + bytes: 5, + ..Default::default() + }], + ..Default::default() + }; + save(&main, &[again]).unwrap(); + } + /// `n` more rows under a file, as a poster could add them fn add_rows(conn: &Connection, file_id: i64, n: i64) { conn.execute( From 8550b70694d1e6119d211256c8e2130a4da40bea Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:58:12 -0500 Subject: [PATCH 110/159] Servers sharing a host are named by host:port (and user) in cursors, claims and sweeps Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 3 ++- src/nntp.rs | 43 ++++++++++++++++++++++++++++++++++++++++--- tests/multi_server.rs | 5 +++-- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 33d9fc39..379256ea 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -372,7 +372,8 @@ pub struct PassContext { } /// Article numbers differ between providers, soo with several servers the -/// cursors are kept per server as `group@host`. One server keeps the plain +/// cursors are kept per server as `group@host` (`Pool::host`, see +/// `server_keys`). One server keeps the plain /// group name like before. fn cursor_key(pool: &Pool, server: usize, group: &str) -> String { if pool.len() <= 1 { group.to_string() } else { format!("{group}@{}", pool.host(server).to_lowercase()) } diff --git a/src/nntp.rs b/src/nntp.rs index 4e2f4ce6..1a24c81c 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -752,6 +752,8 @@ fn gzip_header_len(b: &[u8]) -> Option> { /// One server's connections, capped at its `connections` setting. struct Server { cfg: UsenetServer, + /// what names this server in stored state, see `server_keys` + key: String, idle: Mutex>, permits: Arc, down_until: Mutex>, @@ -1020,14 +1022,36 @@ impl Drop for Unsaved { } } +/// What names each server in stored state (cursors, chunk claims, sweeps): +/// its host when no other server has it (what it always was), else +/// `host:port`, and `user@host:port` when another has the same host and port +/// too. Never the password. +pub fn server_keys(servers: &[UsenetServer]) -> Vec { + let same = |a: &UsenetServer, b: &UsenetServer| a.host.eq_ignore_ascii_case(&b.host); + servers + .iter() + .map(|s| { + if servers.iter().filter(|o| same(s, o)).count() < 2 { + return s.host.clone(); + } + let hp = format!("{}:{}", s.host, s.port); + let shared = servers.iter().filter(|o| same(s, o) && o.port == s.port).count() > 1; + if shared { format!("{}@{hp}", s.username) } else { hp } + }) + .collect() +} + impl Pool { pub fn new(servers: &[UsenetServer]) -> Pool { + let keys = server_keys(servers); Pool { servers: servers .iter() - .map(|cfg| { + .zip(keys) + .map(|(cfg, key)| { Arc::new(Server { cfg: cfg.clone(), + key, idle: Mutex::new(Vec::new()), permits: Arc::new(Semaphore::new(cfg.connections().max(1) as usize)), down_until: Mutex::new(None), @@ -1107,8 +1131,9 @@ impl Pool { self.servers.get(self.active_index()).map(|s| s.cfg.host.clone()).unwrap_or_default() } + /// server `i`'s name in stored state (see `server_keys`) pub fn host(&self, i: usize) -> String { - self.servers.get(i).map(|s| s.cfg.host.clone()).unwrap_or_default() + self.servers.get(i).map(|s| s.key.clone()).unwrap_or_default() } /// requests server `i` takes at once @@ -1201,7 +1226,7 @@ impl Pool { let mut scored: Vec<(f64, usize)> = candidates .iter() .map(|&i| { - let key = format!("{group}\0{}", self.servers[i].cfg.host); + let key = format!("{group}\0{}", self.servers[i].key); // splitmix64's finalizer: fnv alone barely changes between hosts let mut z = fnv(key.as_bytes()); z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); @@ -2259,6 +2284,18 @@ pub fn yenc_decode(lines: &[Vec]) -> Option> { mod tests { /// the dates the first windows count by judge a server's retention: the earliest /// answers, and one more than a day older than an earlier one is unsure + #[test] + fn servers_sharing_a_host_are_told_apart_in_stored_state() { + let s = |h: &str, user: &str, port: u16| UsenetServer::new(h, user, "secret", port); + let alone = [s("A.example", "u", 563), s("b.example", "u", 563)]; + assert_eq!(server_keys(&alone), ["A.example", "b.example"], "a unique host stays as it was"); + let ports = [s("a.example", "u", 563), s("A.example", "u", 119), s("b.example", "u", 563)]; + assert_eq!(server_keys(&ports), ["a.example:563", "A.example:119", "b.example"]); + let users = [s("a.example", "x", 563), s("a.example", "y", 563)]; + assert_eq!(server_keys(&users), ["x@a.example:563", "y@a.example:563"]); + assert_eq!(Pool::new(&users).host(1), "y@a.example:563"); + } + #[test] fn retention_from_the_first_windows() { use super::{Retention, retention_of}; diff --git a/tests/multi_server.rs b/tests/multi_server.rs index 246d9df8..faf49988 100644 --- a/tests/multi_server.rs +++ b/tests/multi_server.rs @@ -72,9 +72,10 @@ fn failover_and_parallel_requests() { assert!((2..=4).contains(&peak), "expected 2-4 parallel connections to the busy server, saw {peak}"); assert!(backup.peak.load(Ordering::SeqCst) <= 2); - // cursors are kept per server once there are several + // cursors are kept per server once there are several, by host:port as + // these share a host let key: String = conn.query_row("select name from groups", [], |r| r.get(0)).unwrap(); - assert_eq!(key, format!("{GROUP}@127.0.0.1")); + assert_eq!(key, format!("{GROUP}@127.0.0.1:{p2}")); } /// A server that agrees to compression but sends junk gets it turned off, From 6cb88a2bc30d5670df5442a5802b47eccad04ff5 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:58:58 -0500 Subject: [PATCH 111/159] A converted shard is made durable before it is marked copied Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/src/convert.rs b/src/convert.rs index 2790452f..0a322db3 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -71,6 +71,20 @@ fn open_for_conversion(path: &Path) -> rusqlite::Result { Ok(conn) } +/// Mark a shard filled by `open_for_conversion` as completely copied (a +/// stopped conversion resumes after it, trusting the mark). Its pages were +/// written unsynced and unjournaled, soo the shard goes durable first (WAL, +/// full sync, every page folded into the file and synced) and the mark is +/// written after: it can never be on disk ahead of the pages it vouches for. +fn mark_copied(conn: &Connection) -> Result<()> { + conn.execute_batch("pragma synchronous = full")?; + conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; + conn.execute("insert or replace into meta (key, value) values ('copied', 0)", [])?; + checkpoint(conn).context("making a copied shard durable")?; + conn.execute("insert or replace into meta (key, value) values ('copied', 1)", [])?; + Ok(()) +} + /// `--convert`: `run` under the exclusive database lock for its whole run, /// refused while the indexer, a write, a compaction or another conversion /// holds it (two at once would write the same shards and `atlas.new.db`). @@ -403,8 +417,7 @@ fn move_articles( )? as i64; conn.execute_batch("drop table segments_load")?; store::add_totals(&conn, 0, added)?; - // this shard's copy is complete (a stopped conversion resumes after it) - conn.execute("insert or replace into meta (key, value) values ('copied', 1)", [])?; + mark_copied(&conn)?; Ok((*read_total, added)) })); } @@ -788,3 +801,34 @@ fn copy_finished(main: &Path, source: &Source) -> bool { .unwrap_or(false) }) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_copied_shard_is_durable_before_it_is_marked() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("shard.db"); + let conn = open_for_conversion(&path).unwrap(); + conn.execute_batch("create table meta(key text primary key, value); create table t(x)").unwrap(); + conn.execute("insert into t values (1)", []).unwrap(); + let mode = |c: &Connection| c.query_row("pragma journal_mode", [], |r| r.get::<_, String>(0)).unwrap(); + assert_eq!(mode(&conn), "off"); + mark_copied(&conn).unwrap(); + // fully synced, journaled, and the data is in the file itself + assert_eq!(mode(&conn), "wal"); + assert_eq!(conn.query_row("pragma synchronous", [], |r| r.get::<_, i64>(0)).unwrap(), 2); + let mark: i64 = conn.query_row("select value from meta where key = 'copied'", [], |r| r.get(0)).unwrap(); + assert_eq!(mark, 1); + // the file alone (without the WAL, as after a crash that lost the + // unsynced tail) has the rows, and not yet the mark written last + let alone = dir.path().join("alone.db"); + std::fs::copy(&path, &alone).unwrap(); + let alone = Connection::open(&alone).unwrap(); + assert_eq!(alone.query_row("select count(*) from t", [], |r| r.get::<_, i64>(0)).unwrap(), 1); + let marked: Option = + alone.query_row("select value from meta where key = 'copied'", [], |r| r.get(0)).optional().unwrap(); + assert_ne!(marked, Some(1)); + } +} From ff7c90b0778146e9b7d6083fe99241c94ecff322 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 02:16:47 -0500 Subject: [PATCH 112/159] A split's days older than any other server goes back stop once one has no article dated in it Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 65 ++++++++++++++++++++++++--- tests/split_forged_2000.rs | 90 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 150 insertions(+), 5 deletions(-) create mode 100644 tests/split_forged_2000.rs diff --git a/src/indexer.rs b/src/indexer.rs index 379256ea..010f6136 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -912,6 +912,22 @@ impl Drop for GiveBackOnDrop<'_> { } } +/// A day chunk of `group` that only one server claims to have (its dates +/// reach back further than any other's) came out with no article dated in +/// that day: its dates went back further than its articles do (forged), and +/// each older day would take a chunk to find that out again. They are dropped; what those days hold is +/// the sweeps' (see `run_sweep`). Best effort: a failure is only logged. +async fn drop_older_days(db: &Db, group: &str, day: i64) { + let g = group.to_string(); + match on_db(db, move |conn| Ok(crate::chunks::drop_before(conn, &g, day)?)).await { + Ok(0) => {} + Ok(n) => { + println!("[CHUNK] {group} day {day} has no article dated in it, the {n} older days are left to the sweeps") + } + Err(e) => println!("[CHUNK] {group}: couldnt drop the days older than an empty one: {e:#}"), + } +} + async fn index_chunk

( ctx: &PassContext, settings: &PassSettings, @@ -977,12 +993,21 @@ where }; // from when the server is taken to keep days whole let mut keeps_from = oldest; + // every carrier's first post is noted, a day it keeps or not: a forged + // run in the dates must not leave `drop_unkept_days` without evidence + ctx.states.first_post_on(group, &ctx.pool.host(server), oldest.map_or(i64::MAX, crate::chunks::unix_day)); + // this day is older than any other server goes back: only this server + // may have it, on the word of its own (forgeable) dates + let mut alone = false; let keeps_day = match oldest { // a day older than the second furthest server goes back is the // furthest one's alone: a server only looks deep enough by the dates // its posters set Some(t) if t <= day * 86_400 => match goes_back_furthest(ctx, db, group, server, (t, sure)).await { - Ok((true, _)) => true, + Ok((true, runner_up)) => { + alone = runner_up.is_none_or(|r| r >= (day + 1) * 86_400); + true + } Ok((false, runner_up)) => { keeps_from = keeps_from.max(runner_up); runner_up.is_none_or(|r| r <= day * 86_400) @@ -1043,16 +1068,23 @@ where }; if start > end { finish().await?; + if alone { + drop_older_days(db, group, day).await; + } return Ok(Progress::default()); } let pass = Pass { ctx, settings, db, group, server, key: cursor_key(&ctx.pool, server, group) }; - match pass.process_range(start as i64, end as i64, "CHUNK", progress).await { - Ok((saved, true)) => { + let window = alone.then_some((day * 86_400, (day + 1) * 86_400)); + match pass.process_range_dated(start as i64, end as i64, "CHUNK", window, progress).await { + Ok((saved, true, corroborated)) => { finish().await?; + if alone && !corroborated { + drop_older_days(db, group, day).await; + } Ok(saved) } - Ok((saved, false)) => { + Ok((saved, false, _)) => { release().await?; Ok(saved) } @@ -1260,6 +1292,24 @@ impl Pass<'_> { where P: FnMut(&Progress) + ?Sized, { + let (saved, complete, _) = self.process_range_dated(start, end, kind, None, progress).await?; + Ok((saved, complete)) + } + + /// `process_range`, also whether any article retrieved is dated within + /// `window` (unix seconds, from up to before), false when there is none. + async fn process_range_dated

( + &self, + start: i64, + end: i64, + kind: &str, + window: Option<(i64, i64)>, + progress: &mut P, + ) -> Result<(Progress, bool, bool)> + where + P: FnMut(&Progress) + ?Sized, + { + let mut in_window = false; let (pool, group) = (&self.ctx.pool, self.group); // no slice bigger than the whole unsaved budget: it would hold more // headers than the cap allows @@ -1302,6 +1352,11 @@ impl Pass<'_> { continue; } + if let Some((from, to)) = window.filter(|_| !in_window) { + in_window = headers + .iter() + .any(|h| crate::dates::posted_timestamp(&h.date).is_some_and(|t| (from..to).contains(&t))); + } let dated = slice_date(&headers); match save_slice(pool, self.db, group, headers).await { Ok(p) => { @@ -1341,7 +1396,7 @@ impl Pass<'_> { } // stopped early: what got saved stays, the cursor waits for the rest - Ok((saved, done == total)) + Ok((saved, done == total, in_window)) } } diff --git a/tests/split_forged_2000.rs b/tests/split_forged_2000.rs new file mode 100644 index 00000000..02c14ad5 --- /dev/null +++ b/tests/split_forged_2000.rs @@ -0,0 +1,90 @@ +//! A split group on two servers, one with its first 300 articles dated in +//! 2000 (forged): the split reaches back thousands of days no article is +//! dated in. Chunks are only serviced down to where an article was found, +//! the rest dropped, soo the split completes (its sweeps run, which index +//! the forged-dated articles) after a handful of chunks, not thousands. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset`, +/// only those from day `from_day` on +fn posts(offset: u64, from_day: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (from_day * 40..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn forged_dates_in_2000_make_only_a_few_chunks() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + let clean = Server::new(posts(1, 0)); + let mut forged_posts = posts(500_001, 0); + for p in forged_posts.iter_mut().take(300) { + p.date = "Wed, 05 Jan 2000 00:00:00 +0000".into(); + } + let (pc, pf) = (spawn_server(clean), spawn_server(Server::new(forged_posts))); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pc, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": pf, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let deadline = Instant::now() + Duration::from_secs(90); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + let swept = ["127.0.0.1", "localhost"].iter().all(|h| atlas::chunks::swept(&conn, GROUP, h).unwrap()); + if total > 0 && done == total && swept && articles >= 1200 { + break; + } + assert!(Instant::now() < deadline, "articles {articles}, chunks {done}/{total}, swept {swept}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + let conn = atlas::db::open_with_shards(&main).unwrap(); + let chunks: i64 = conn.query_row("select count(*) from backfill_chunks", [], |r| r.get(0)).unwrap(); + assert!(chunks < 100, "{chunks} chunks left of a split reaching back to 2000"); +} From 3916d40defd82e4a6953ec1a8d07798016e2020f Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 02:29:14 -0500 Subject: [PATCH 113/159] A lost atlas.db after a finished conversion doesnt bring the old database back over live shards Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 25 +++++++++++++++++++++++++ tests/convert.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/convert.rs b/src/convert.rs index 0a322db3..11cf41c8 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -206,6 +206,21 @@ pub fn recover_cut_swap(main: &Path) -> Result> { ))); } if backup.try_exists()? { + // no conversion under way (it would have left atlas.new.db) yet shards + // with releases: a conversion finished long ago and atlas.db went + // missing since. the old database back would be converted again, and + // that fresh copy would wipe the shards and all indexed since + if !new_main.try_exists()? && shards_hold_releases(main) { + bail!( + "{} is missing, but the shards next to it hold releases from a finished conversion; \ + not putting {} back (converting it again would wipe the shards). \ + restore {} from a backup, or move the shards (atlas.s*.db) aside to start over from {}", + main.display(), + backup.display(), + main.display(), + backup.display() + ); + } rename_db(&backup, main).context("putting the old database back")?; return Ok(Some(format!( "a conversion was cut short after moving {} aside; it's back in place", @@ -215,6 +230,16 @@ pub fn recover_cut_swap(main: &Path) -> Result> { Ok(None) } +/// Any shard next to `main` has a release (read only: nothing is created) +fn shards_hold_releases(main: &Path) -> bool { + store::shard_paths(main).iter().any(|p| { + p.exists() + && Connection::open_with_flags(p, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX) + .and_then(|c| c.query_row("select exists(select 1 from releases)", [], |r| r.get::<_, bool>(0))) + .unwrap_or(false) + }) +} + fn swap_ready(new_main: &Path) -> bool { db::open_at(new_main) .and_then(|c| c.query_row("select value from meta where key = 'swap_ready'", [], |r| r.get(0)).optional()) diff --git a/tests/convert.rs b/tests/convert.rs index 03a8f82d..7a1b2c0e 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -464,3 +464,29 @@ fn an_old_database_moved_aside_without_a_finished_new_one_is_put_back() { assert!(convert::needed(&main), "the old database is back"); assert_eq!(convert::run_alone(&main, &|_| {}).unwrap().map(|(r, _)| r), Some(40)); } + +/// Long after a finished conversion, atlas.db lost while atlas.old.db and +/// the shards (with everything indexed since) are still there: putting the +/// old database back would convert again and the fresh copy would wipe the +/// shards. Refused, saying what to do, and nothing is touched. +#[test] +fn a_lost_main_database_after_a_conversion_does_not_bring_the_old_one_back() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + db::create_db_at(&main).unwrap(); + convert::run(&main, &|_| {}).unwrap(); + let releases = store::totals(&db::open_with_shards(&main).unwrap()).unwrap().0; + assert!(releases > 0); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", main.display())); + } + + let refused = convert::recover_cut_swap(&main).unwrap_err().to_string(); + assert!(refused.contains("atlas.old.db") && refused.contains("shards"), "{refused}"); + assert!(dir.path().join("atlas.old.db").exists()); + assert!(!main.exists()); + for path in store::shard_paths(&main) { + assert!(path.exists()); + } +} From 646efc581681d63ce0669c24f6a0fe817fa79441 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 02:33:39 -0500 Subject: [PATCH 114/159] A conversion keeps a release's shard per release, not a byte per id up to the highest Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 47 +++++++++++++++++++++++++++++++---------------- tests/convert.rs | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 16 deletions(-) diff --git a/src/convert.rs b/src/convert.rs index 11cf41c8..83fde5c8 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -120,12 +120,12 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { let (max_id, shard_of_old, moved_releases, moved_articles, orphans) = if copy_finished(main, &source) { progress("converting the database: the copy finished earlier, checking it"); let max_id: i64 = old.query_row("select coalesce(max(id), 0) from releases", [], |r| r.get(0))?; - let mut shard_of_old = vec![u8::MAX; max_id as usize + 1]; - let mut stmt = old.prepare("select id, group_name from releases")?; + let mut shard_of_old = ShardOf::default(); + let mut stmt = old.prepare("select id, group_name from releases order by id")?; let mut rows = stmt.query([])?; while let Some(r) = rows.next()? { let (id, group): (i64, Option) = (r.get(0)?, r.get(1)?); - shard_of_old[id as usize] = store::shard_of(group.as_deref().unwrap_or("")) as u8; + shard_of_old.push(id, store::shard_of(group.as_deref().unwrap_or(""))); } drop(rows); drop(stmt); @@ -246,6 +246,23 @@ fn swap_ready(new_main: &Path) -> bool { .is_ok_and(|v: Option| v == Some(1)) } +/// Old release id -> the shard it went to, one entry per release (ids can +/// have gaps of any size, soo not a slot per id up to the highest). Filled +/// in id order, looked up by binary search. +#[derive(Default)] +struct ShardOf(Vec<(i64, u8)>); + +impl ShardOf { + fn push(&mut self, id: i64, shard: usize) { + debug_assert!(self.0.last().is_none_or(|&(last, _)| last < id), "releases come in id order"); + self.0.push((id, shard as u8)); + } + + fn get(&self, id: i64) -> Option { + self.0.binary_search_by_key(&id, |&(id, _)| id).ok().map(|i| self.0[i].1 as usize) + } +} + type OldRelease = (i64, ReleaseFields); type ReleaseFields = ( Option, @@ -264,7 +281,7 @@ fn move_releases( main: &Path, old: &Connection, total: i64, - shard_of_old: &mut [u8], + shard_of_old: &mut ShardOf, progress: &dyn Fn(&str), ) -> Result { std::thread::scope(|s| -> Result { @@ -312,7 +329,7 @@ fn move_releases( let mut stmt = old.prepare( "select id, name, group_name, poster, posted_date, size, complete, parts, file_total, display_name, - is_obfuscated from releases", + is_obfuscated from releases order by id", )?; let mut rows = stmt.query([])?; let mut buffers: Vec> = vec![Vec::new(); SHARDS]; @@ -322,7 +339,7 @@ fn move_releases( let id: i64 = r.get(0)?; let group: Option = r.get(2)?; let shard = store::shard_of(group.as_deref().unwrap_or("")); - shard_of_old[id as usize] = shard as u8; + shard_of_old.push(id, shard); buffers[shard].push(( id, ( @@ -375,7 +392,7 @@ type OldArticle = (i64, Article); fn move_articles( main: &Path, total: i64, - shard_of_old: &[u8], + shard_of_old: &ShardOf, started: Instant, progress: &dyn Fn(&str), ) -> Result<(i64, i64)> { @@ -470,16 +487,16 @@ fn move_articles( read.fetch_add(1, Ordering::Relaxed); let release_id: Option = r.get(0)?; let message_id: Option = r.get(1)?; - let shard = release_id.and_then(|id| shard_of_old.get(id as usize)).copied().unwrap_or(u8::MAX); + let shard = release_id.and_then(|id| shard_of_old.get(id)); let (Some(old_id), Some(message_id)) = (release_id, message_id.filter(|m| !m.is_empty())) else { orphans.fetch_add(1, Ordering::Relaxed); continue; }; - if shard == u8::MAX { + let Some(shard) = shard else { orphans.fetch_add(1, Ordering::Relaxed); continue; - } + }; let article = Article { message_id, subject: r.get::<_, Option>(2)?.unwrap_or_default(), @@ -490,7 +507,6 @@ fn move_articles( file_total: r.get(7)?, ..Article::default() }; - let shard = shard as usize; buffers[shard].push((store::global_id(old_id, shard), article)); if buffers[shard].len() >= BATCH { sent.fetch_add(BATCH as i64, Ordering::Relaxed); @@ -555,7 +571,7 @@ fn move_articles( /// Compare `CHECK_SAMPLE` releases, spread over the whole database, and the /// newest `CHECK_TAIL` between the old database and the shards. -fn check(main: &Path, old: &Connection, max_id: i64, shard_of_old: &[u8]) -> Result<()> { +fn check(main: &Path, old: &Connection, max_id: i64, shard_of_old: &ShardOf) -> Result<()> { let new = Connection::open_in_memory()?; store::attach(&new, main)?; @@ -598,7 +614,7 @@ fn check(main: &Path, old: &Connection, max_id: i64, shard_of_old: &[u8]) -> Res if !seen.insert(was.id) { continue; } - let shard = shard_of_old[was.id as usize] as usize; + let shard = shard_of_old.get(was.id).ok_or_else(|| anyhow!("release {} has no shard", was.id))?; let id = store::global_id(was.id, shard); let now = new.query_row( &format!( @@ -660,7 +676,7 @@ fn copy( source: &Source, started: Instant, progress: &dyn Fn(&str), -) -> Result<(i64, Vec, i64, i64, i64)> { +) -> Result<(i64, ShardOf, i64, i64, i64)> { let new_main = sibling(main, "atlas.new.db"); // 1. the new main database with the cursors remove_db(&new_main); @@ -699,8 +715,7 @@ fn copy( let max_id: i64 = old.query_row("select coalesce(max(id), 0) from releases", [], |r| r.get(0))?; let total_releases: i64 = old.query_row("select count(*) from releases", [], |r| r.get(0))?; progress(&format!("converting the database: {} releases", total_releases)); - // old id -> shard (255 = no such release) - let mut shard_of_old = vec![u8::MAX; max_id as usize + 1]; + let mut shard_of_old = ShardOf::default(); let moved_releases = move_releases(main, old, total_releases, &mut shard_of_old, progress)?; progress("converting the database: building the release indexes and search index"); diff --git a/tests/convert.rs b/tests/convert.rs index 7a1b2c0e..42340f68 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -490,3 +490,46 @@ fn a_lost_main_database_after_a_conversion_does_not_bring_the_old_one_back() { assert!(path.exists()); } } + +/// Release ids with a huge gap (AUTOINCREMENT after a reset, a hand-set id): +/// the conversion keeps per release what shard it went to, not a slot for +/// every id up to the highest, also when it picks up a stopped run. +#[test] +fn a_huge_sparse_release_id_converts_without_a_slot_per_id() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + let far = 1i64 << 56; + { + let conn = Connection::open(&main).unwrap(); + conn.execute( + "insert into releases (id, name, group_name, poster, posted_date, size, complete, parts, file_total) + values (?, 'Far.Away', 'alt.binaries.a', 'p ', '2026-10-02 10:11:12', 100, 1, 1, 1)", + [far], + ) + .unwrap(); + conn.execute( + "insert into articles (release_id, message_id, subject, filename, part, total_parts, bytes, file_total) + values (?, '', '\"far.rar\" yEnc (1/1)', 'far.rar', 1, 1, 100, 1)", + [far], + ) + .unwrap(); + } + let before = old_nzbs(&main); + db::create_db_at(&main).unwrap(); + + // stopped as the check starts, then picked up + let stopped = std::panic::catch_unwind(|| { + convert::run(&main, &|m| assert!(!m.contains("checking NZBs"), "stop here")).unwrap(); + }); + assert!(stopped.is_err()); + convert::run(&main, &|_| {}).unwrap(); + + let conn = db::open_with_shards(&main).unwrap(); + assert_eq!(store::totals(&conn).unwrap().0, before.len() as i64); + for (name, nzb_before, _) in &before { + let id: i64 = conn.query_row("select id from releases where name = ?", [name], |r| r.get(0)).unwrap(); + let now = atlas::search::get_release_with(&conn, id).unwrap().unwrap(); + assert_eq!(&nzb::render_nzb(&now, &store::articles(&conn, id).unwrap()), nzb_before, "{name}"); + } +} From 75aa13f3d5a8261954ec7a26056e70990a9f3b7a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 02:56:26 -0500 Subject: [PATCH 115/159] A server's key comes from its own settings, and cursors under an older key are adopted The host on its default port, else host:port, plus #key only when the server sets one: adding or removing another server no longer renames it. Homes are still ranked by host, soo they dont move either. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + src/config.rs | 9 ++++ src/indexer.rs | 78 +++++++++++++++++++++------ src/nntp.rs | 89 ++++++++++++++++++++++++------- tests/date_search.rs | 31 ++++++----- tests/split_bogus_days.rs | 3 +- tests/split_forged_2000.rs | 3 +- tests/split_forged_early.rs | 4 +- tests/split_forged_sweep.rs | 3 +- tests/split_homes.rs | 5 +- tests/split_retention.rs | 4 +- tests/split_shallow_home_sweep.rs | 7 +-- tests/split_sweep_own_chunks.rs | 3 +- 13 files changed, 176 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index eac450ef..a9263f24 100644 --- a/README.md +++ b/README.md @@ -156,6 +156,7 @@ Atlas keeps any other keys you add to the file when it saves it. | `priority` | `99` | Order of the servers for failover and for par2 and nfo lookups among equally busy servers. Lower values come first. Servers with equal priority keep their order in the file. | | `index` | `true` | Whether the server takes part in indexing. `false` keeps it for article lookups only, for example a block account whose data you don't want to spend on headers. | | `compress` | `true` | Requests gzip-compressed header listings. Servers without compression get plain requests, and Atlas turns compression off for a server that sends unreadable data. | +| `key` | | Sets the server apart in Atlas's stored progress (cursors, day chunks, sweeps). Atlas names a server by its host, plus `:port` when the port isn't the default for its SSL setting, and adds `#key` when this is set. Adding or removing other servers never changes the name. Set it only for a second account on the same host and port whose provider numbers articles differently; otherwise both share one progress. | The old single-server layout, with `host`, `username`, `password`, and `port` at the top level, still works and becomes a one-server list. diff --git a/src/config.rs b/src/config.rs index 6c05da67..e14e3460 100644 --- a/src/config.rs +++ b/src/config.rs @@ -48,6 +48,10 @@ pub struct UsenetServer { /// take part in indexing (header downloads), default on. off keeps e.g. a /// block account for downloads and article lookups only pub index: Option, + /// set apart in stored state (cursors, chunk claims, sweeps) from other + /// accounts on the same host and port, see `nntp::server_keys`. Only + /// for a second account on a provider that numbers articles differently + pub key: Option, } impl UsenetServer { @@ -62,6 +66,7 @@ impl UsenetServer { priority: 1, compress: None, index: None, + key: None, } } @@ -95,6 +100,7 @@ impl UsenetServer { priority: v.get("priority").and_then(as_int).unwrap_or(DEFAULT_PRIORITY), compress: v.get("compress").and_then(as_bool), index: v.get("index").and_then(as_bool), + key: v.get("key").and_then(Value::as_str).map(str::trim).filter(|k| !k.is_empty()).map(String::from), }) } @@ -117,6 +123,9 @@ impl UsenetServer { if let Some(i) = self.index { m.insert("index".into(), json!(i)); } + if let Some(k) = &self.key { + m.insert("key".into(), json!(k)); + } Value::Object(m) } } diff --git a/src/indexer.rs b/src/indexer.rs index 010f6136..8b0cdc5e 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -379,26 +379,51 @@ fn cursor_key(pool: &Pool, server: usize, group: &str) -> String { if pool.len() <= 1 { group.to_string() } else { format!("{group}@{}", pool.host(server).to_lowercase()) } } -async fn load_cursors(db: &Db, key: &str, group: &str, legacy: bool) -> Result> { +async fn load_cursors( + ctx: &PassContext, + db: &Db, + key: &str, + group: &str, + server: usize, +) -> Result> { let (key, group) = (key.to_string(), group.to_string()); + let legacy = if ctx.pool.len() <= 1 { Vec::new() } else { ctx.pool.legacy_keys(server) }; + on_db(db, move |conn| cursors_or_adopted(conn, &key, &group, server == 0, &legacy)).await +} - on_db(db, move |conn| { - if let Some(state) = db::get_group_state(conn, &key)? { - return Ok(Some(state)); - } +/// The cursors saved under `key`, else adopted: saved under one of the +/// server's `legacy` keys (what an earlier build named it, see +/// `nntp::legacy_server_keys`) they move to `key`, once; saved under the +/// plain group name (before a second server was added) they belong to the +/// first server +fn cursors_or_adopted( + conn: &Connection, + key: &str, + group: &str, + first_server: bool, + legacy: &[String], +) -> Result> { + if let Some(state) = db::get_group_state(conn, key)? { + return Ok(Some(state)); + } - // cursors saved before a second server was added belong to the first server - if legacy - && key != group - && let Some(state) = db::get_group_state(conn, &group)? - { - db::save_group_state(conn, &key, state)?; - return Ok(Some(state)); + for old in legacy.iter().map(|k| format!("{group}@{k}")) { + if db::get_group_state(conn, &old)?.is_some() { + conn.execute("delete from groups where name = ?", [key])?; + conn.execute("update groups set name = ? where name = ?", [key, old.as_str()])?; + return Ok(db::get_group_state(conn, key)?); } + } - Ok(None) - }) - .await + if first_server + && key != group + && let Some(state) = db::get_group_state(conn, group)? + { + db::save_group_state(conn, key, state)?; + return Ok(Some(state)); + } + + Ok(None) } /// One pass over `group`: a batch of live or backfill articles depending on @@ -420,7 +445,7 @@ where let (first, last) = (first as i64, last as i64); let key = cursor_key(&ctx.pool, server, group); - let state = match load_cursors(db, &key, group, server == 0).await? { + let state = match load_cursors(ctx, db, &key, group, server).await? { Some(s) if last >= s.live_cursor => s, // first time both cursors start at the top. if the server renumbered // (last went backwards) the group got reset soo start over the same way @@ -830,7 +855,7 @@ where }; let (first, last) = (first as i64, last as i64); let key = cursor_key(&ctx.pool, server, group); - let cursor = match load_cursors(db, &key, group, server == 0).await? { + let cursor = match load_cursors(ctx, db, &key, group, server).await? { Some(s) => s.backfill_cursor.min(last), None => { let k = key.clone(); @@ -1587,6 +1612,25 @@ impl Indexer { mod tests { use super::*; + #[test] + fn cursors_saved_under_a_servers_old_key_are_adopted_once() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let conn = db::open_at(&main).unwrap(); + let state = db::GroupState { live_cursor: 900, backfill_cursor: 500 }; + db::save_group_state(&conn, "g@x@a.example:563", state).unwrap(); + let legacy = ["a.example:563".to_string(), "x@a.example:563".to_string()]; + assert_eq!(cursors_or_adopted(&conn, "g@a.example", "g", false, &legacy).unwrap(), Some(state)); + assert_eq!(db::get_group_state(&conn, "g@x@a.example:563").unwrap(), None, "moved, not copied"); + assert_eq!(db::get_group_state(&conn, "g@a.example").unwrap(), Some(state)); + // nothing to adopt: nothing made up + assert_eq!(cursors_or_adopted(&conn, "g@b.example", "g", false, &[]).unwrap(), None); + // the plain group name still goes to the first server + db::save_group_state(&conn, "h", state).unwrap(); + assert_eq!(cursors_or_adopted(&conn, "h@a.example", "h", true, &legacy).unwrap(), Some(state)); + } + #[test] fn what_a_server_keeps_is_remembered_by_its_host_not_its_place_in_the_pool() { let states = RunStates::default(); diff --git a/src/nntp.rs b/src/nntp.rs index 1a24c81c..70a5369f 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -754,6 +754,8 @@ struct Server { cfg: UsenetServer, /// what names this server in stored state, see `server_keys` key: String, + /// what earlier builds named it, see `legacy_server_keys` + legacy_keys: Vec, idle: Mutex>, permits: Arc, down_until: Mutex>, @@ -1022,21 +1024,45 @@ impl Drop for Unsaved { } } -/// What names each server in stored state (cursors, chunk claims, sweeps): -/// its host when no other server has it (what it always was), else -/// `host:port`, and `user@host:port` when another has the same host and port -/// too. Never the password. +/// What names each server in stored state (cursors, chunk claims, sweeps), +/// from its own settings alone: adding or removing another server never +/// changes it (that would orphan its cursors). The host on the default port +/// for its ssl setting (563 with ssl, 119 without; what it always was), else +/// `host:port`, and `#key` after either when the server sets `key`. Two +/// accounts on the same host and port share it (the same provider numbers +/// articles the same) unless one sets a `key`. Never the user or password. pub fn server_keys(servers: &[UsenetServer]) -> Vec { - let same = |a: &UsenetServer, b: &UsenetServer| a.host.eq_ignore_ascii_case(&b.host); + servers.iter().map(server_key).collect() +} + +fn server_key(s: &UsenetServer) -> String { + let default_port = if s.use_ssl() { 563 } else { 119 }; + let base = if s.port == default_port { s.host.clone() } else { format!("{}:{}", s.host, s.port) }; + match &s.key { + Some(k) => format!("{base}#{k}"), + None => base, + } +} + +/// Per server, lowercased, what earlier builds named it in stored state +/// (`host`, `host:port`, `user@host:port`, depending on the other servers +/// then) and that no server is named now: cursors saved under one are its +/// own, adopted when none are saved under its key (see `indexer`) +pub fn legacy_server_keys(servers: &[UsenetServer]) -> Vec> { + let now: Vec = servers.iter().map(|s| server_key(s).to_lowercase()).collect(); servers .iter() .map(|s| { - if servers.iter().filter(|o| same(s, o)).count() < 2 { - return s.host.clone(); + let host = s.host.to_lowercase(); + let hp = format!("{host}:{}", s.port); + let user = format!("{}@{hp}", s.username.to_lowercase()); + let mut old = Vec::new(); + for k in [host, hp, user] { + if !now.contains(&k) && !old.contains(&k) { + old.push(k); + } } - let hp = format!("{}:{}", s.host, s.port); - let shared = servers.iter().filter(|o| same(s, o) && o.port == s.port).count() > 1; - if shared { format!("{}@{hp}", s.username) } else { hp } + old }) .collect() } @@ -1044,14 +1070,17 @@ pub fn server_keys(servers: &[UsenetServer]) -> Vec { impl Pool { pub fn new(servers: &[UsenetServer]) -> Pool { let keys = server_keys(servers); + let legacy = legacy_server_keys(servers); Pool { servers: servers .iter() .zip(keys) - .map(|(cfg, key)| { + .zip(legacy) + .map(|((cfg, key), legacy_keys)| { Arc::new(Server { cfg: cfg.clone(), key, + legacy_keys, idle: Mutex::new(Vec::new()), permits: Arc::new(Semaphore::new(cfg.connections().max(1) as usize)), down_until: Mutex::new(None), @@ -1131,6 +1160,11 @@ impl Pool { self.servers.get(self.active_index()).map(|s| s.cfg.host.clone()).unwrap_or_default() } + /// what server `i` was named in stored state before (see `legacy_server_keys`) + pub fn legacy_keys(&self, i: usize) -> Vec { + self.servers.get(i).map(|s| s.legacy_keys.clone()).unwrap_or_default() + } + /// server `i`'s name in stored state (see `server_keys`) pub fn host(&self, i: usize) -> String { self.servers.get(i).map(|s| s.key.clone()).unwrap_or_default() @@ -1226,7 +1260,11 @@ impl Pool { let mut scored: Vec<(f64, usize)> = candidates .iter() .map(|&i| { - let key = format!("{group}\0{}", self.servers[i].key); + // by host (and an explicit `key`), not port: a group's home + // stays where it was before ports were part of server keys + let cfg = &self.servers[i].cfg; + let key = + format!("{group}\0{}{}", cfg.host, cfg.key.as_ref().map(|k| format!("#{k}")).unwrap_or_default()); // splitmix64's finalizer: fnv alone barely changes between hosts let mut z = fnv(key.as_bytes()); z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); @@ -2285,15 +2323,26 @@ mod tests { /// the dates the first windows count by judge a server's retention: the earliest /// answers, and one more than a day older than an earlier one is unsure #[test] - fn servers_sharing_a_host_are_told_apart_in_stored_state() { + fn a_servers_key_is_its_own_and_doesnt_change_with_the_others() { let s = |h: &str, user: &str, port: u16| UsenetServer::new(h, user, "secret", port); - let alone = [s("A.example", "u", 563), s("b.example", "u", 563)]; - assert_eq!(server_keys(&alone), ["A.example", "b.example"], "a unique host stays as it was"); - let ports = [s("a.example", "u", 563), s("A.example", "u", 119), s("b.example", "u", 563)]; - assert_eq!(server_keys(&ports), ["a.example:563", "A.example:119", "b.example"]); - let users = [s("a.example", "x", 563), s("a.example", "y", 563)]; - assert_eq!(server_keys(&users), ["x@a.example:563", "y@a.example:563"]); - assert_eq!(Pool::new(&users).host(1), "y@a.example:563"); + let first = s("A.example", "x", 563); + // the default port for its ssl setting: the plain host, like always + assert_eq!(server_keys(std::slice::from_ref(&first)), ["A.example"]); + // a second account on the same host and port, another on another + // port, and one with an explicit key: the first one's key stays + let mut keyed = s("a.example", "y", 563); + keyed.key = Some("block".into()); + let all = [first.clone(), s("a.example", "y", 563), s("a.example", "z", 119), s("a.example", "w", 443), keyed]; + assert_eq!(server_keys(&all), ["A.example", "a.example", "a.example", "a.example:443", "a.example#block"]); + let mut plain = s("a.example", "v", 563); + plain.ssl = Some(false); + assert_eq!(server_keys(&[plain]), ["a.example:563"], "563 isnt the default without ssl"); + assert_eq!(Pool::new(&all).host(4), "a.example#block"); + // what the keys used to be, for cursors saved under them: never + // another server's key now + let old = legacy_server_keys(&all); + assert_eq!(old[0], ["a.example:563", "x@a.example:563"]); + assert_eq!(old[3], ["w@a.example:443"]); } #[test] diff --git a/tests/date_search.rs b/tests/date_search.rs index ed506b03..2a66a4e4 100644 --- a/tests/date_search.rs +++ b/tests/date_search.rs @@ -601,7 +601,7 @@ fn the_oldest_day_moves_on_when_the_deepest_server_drops_the_group() { // the 01:00 server is noted as the deepest assert!(run(1).unwrap_err().downcast_ref::().is_some()); - assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("127.0.0.1")); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some(pool.pool.host(0).as_str())); // then drops the group, and finds out on its next chunk deep_server.dropped.store(true, std::sync::atomic::Ordering::SeqCst); @@ -612,7 +612,7 @@ fn the_oldest_day_moves_on_when_the_deepest_server_drops_the_group() { let saved = run(1).expect("the next deepest carrier does the oldest day"); assert_eq!(saved.articles, 7); assert_eq!(state(), 2); - assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("localhost")); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some(pool.pool.host(1).as_str())); } /// The server noted as going back furthest still carries the group, but its @@ -668,7 +668,7 @@ fn the_oldest_day_moves_on_when_the_deepest_server_no_longer_keeps_it() { // the 01:00 server is noted as the deepest assert!(run(1).unwrap_err().downcast_ref::().is_some()); - assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("127.0.0.1")); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some(pool.pool.host(0).as_str())); // then keeps only from the next day on, and finds out on its next chunk deep_server.posts.lock().unwrap().retain(|p| p.number > 25); @@ -680,7 +680,7 @@ fn the_oldest_day_moves_on_when_the_deepest_server_no_longer_keeps_it() { let saved = run(1).expect("the next deepest carrier does the oldest day"); assert_eq!(saved.articles, 7); assert_eq!(state(), 2); - assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some("localhost")); + assert_eq!(atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), Some(pool.pool.host(1).as_str())); } /// A split made while the servers kept 5 days, then a server that keeps 10 @@ -712,9 +712,12 @@ fn a_split_reaches_back_when_a_deeper_server_joins() { let day0 = atlas::chunks::unix_day(start.timestamp()); let conn = atlas::db::open_at(&main).unwrap(); atlas::chunks::add(&conn, GROUP, day0 + 9, day0 + 5).unwrap(); - conn.execute("update backfill_chunks set state = 2, server = '127.0.0.1', done_at = 1 where day = ?", [day0 + 5]) - .unwrap(); - atlas::chunks::set_deepest(&conn, GROUP, "127.0.0.1", start.timestamp() + 121 * 3600).unwrap(); + conn.execute( + "update backfill_chunks set state = 2, server = ?, done_at = 1 where day = ?", + rusqlite::params![pool.pool.host(0), day0 + 5], + ) + .unwrap(); + atlas::chunks::set_deepest(&conn, GROUP, &pool.pool.host(0), start.timestamp() + 121 * 3600).unwrap(); let ctx = atlas::indexer::PassContext { pool: pool.pool.clone(), @@ -744,16 +747,16 @@ fn a_split_reaches_back_when_a_deeper_server_joins() { // asked again (a chunk the pass ran asks who keeps the day): the new one assert_eq!( atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), - Some("localhost"), + Some(pool.pool.host(1).as_str()), "the deepest server is asked again" ); // and the new days get indexed: the new oldest by the server that has it for day in [day0 + 4, day0] { - let chunk = atlas::chunks::Claim { group: GROUP.into(), day, server: "localhost".into(), claimed_at: 1 }; + let chunk = atlas::chunks::Claim { group: GROUP.into(), day, server: pool.pool.host(1), claimed_at: 1 }; conn.execute( - "update backfill_chunks set state = 1, server = 'localhost', claimed_at = 1 where grp = ? and day = ?", - rusqlite::params![GROUP, day], + "update backfill_chunks set state = 1, server = ?, claimed_at = 1 where grp = ? and day = ?", + rusqlite::params![chunk.server, GROUP, day], ) .unwrap(); let saved = pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 1, &mut |_| {})).unwrap(); @@ -790,9 +793,9 @@ fn a_split_reaches_back_when_home_no_longer_keeps_its_cursor() { let day0 = atlas::chunks::unix_day(start.timestamp()); let conn = atlas::db::open_at(&main).unwrap(); atlas::chunks::add(&conn, GROUP, day0 + 9, day0 + 5).unwrap(); - atlas::chunks::set_deepest(&conn, GROUP, "127.0.0.1", start.timestamp() + 121 * 3600).unwrap(); + atlas::chunks::set_deepest(&conn, GROUP, &pool.pool.host(0), start.timestamp() + 121 * 3600).unwrap(); let state = atlas::db::GroupState { live_cursor: 1240, backfill_cursor: 5 }; - atlas::db::save_group_state(&conn, &format!("{GROUP}@127.0.0.1"), state).unwrap(); + atlas::db::save_group_state(&conn, &format!("{GROUP}@{}", pool.pool.host(0).to_lowercase()), state).unwrap(); let ctx = atlas::indexer::PassContext { pool: pool.pool.clone(), @@ -989,7 +992,7 @@ fn a_split_redoes_its_oldest_day_when_a_server_goes_back_further_in_it() { // asked again (a chunk the pass ran asks who keeps the day): the new one assert_eq!( atlas::chunks::deepest(&conn, GROUP).unwrap().as_deref(), - Some("localhost"), + Some(pool.pool.host(1).as_str()), "the deepest server is asked again" ); assert_eq!(run_day(day0, 1).articles, 24, "01:00 to midnight and the hour after"); diff --git a/tests/split_bogus_days.rs b/tests/split_bogus_days.rs index 7570ef35..07f12efa 100644 --- a/tests/split_bogus_days.rs +++ b/tests/split_bogus_days.rs @@ -66,6 +66,7 @@ fn days_no_carrier_keeps_are_dropped() { let stop = Arc::new(AtomicBool::new(false)); let cfg = atlas::config::load_config().unwrap(); + let keys = atlas::nntp::server_keys(&cfg.servers); let runner = { let stop = stop.clone(); std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) @@ -76,7 +77,7 @@ fn days_no_carrier_keeps_are_dropped() { let conn = atlas::db::open_with_shards(&main).unwrap(); let (_, articles) = atlas::store::totals(&conn).unwrap(); let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); - let swept = ["127.0.0.1", "localhost"].iter().any(|h| atlas::chunks::swept(&conn, GROUP, h).unwrap()); + let swept = keys.iter().any(|h| atlas::chunks::swept(&conn, GROUP, h).unwrap()); if total > 0 && done == total && articles == 1200 && swept { break; } diff --git a/tests/split_forged_2000.rs b/tests/split_forged_2000.rs index 02c14ad5..d6d148f4 100644 --- a/tests/split_forged_2000.rs +++ b/tests/split_forged_2000.rs @@ -64,6 +64,7 @@ fn forged_dates_in_2000_make_only_a_few_chunks() { let stop = Arc::new(AtomicBool::new(false)); let cfg = atlas::config::load_config().unwrap(); + let keys = atlas::nntp::server_keys(&cfg.servers); let runner = { let stop = stop.clone(); std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) @@ -75,7 +76,7 @@ fn forged_dates_in_2000_make_only_a_few_chunks() { let conn = atlas::db::open_with_shards(&main).unwrap(); let (_, articles) = atlas::store::totals(&conn).unwrap(); let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); - let swept = ["127.0.0.1", "localhost"].iter().all(|h| atlas::chunks::swept(&conn, GROUP, h).unwrap()); + let swept = keys.iter().all(|h| atlas::chunks::swept(&conn, GROUP, h).unwrap()); if total > 0 && done == total && swept && articles >= 1200 { break; } diff --git a/tests/split_forged_early.rs b/tests/split_forged_early.rs index b558938d..fab3b964 100644 --- a/tests/split_forged_early.rs +++ b/tests/split_forged_early.rs @@ -89,8 +89,8 @@ fn a_forged_early_date_on_a_shallow_servers_first_article_loses_no_days() { atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-21T00:00:00+00:00").unwrap().timestamp()); let old_by_short: i64 = conn .query_row( - "select count(*) from backfill_chunks where server = 'localhost' and day < ?", - [first_short_day], + "select count(*) from backfill_chunks where server = ? and day < ?", + rusqlite::params![format!("localhost:{ps}"), first_short_day], |r| r.get(0), ) .unwrap(); diff --git a/tests/split_forged_sweep.rs b/tests/split_forged_sweep.rs index f54cecac..b4434f4d 100644 --- a/tests/split_forged_sweep.rs +++ b/tests/split_forged_sweep.rs @@ -76,7 +76,8 @@ fn chunks_a_forged_shallow_server_missed_are_swept_up_after() { let first_day = atlas::chunks::unix_day(1_767_225_600); atlas::chunks::add(&conn, GROUP, first_day + 29, first_day).unwrap(); let now = chrono::Utc::now().timestamp(); - while let Some(claim) = atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], "127.0.0.1", now).unwrap() + while let Some(claim) = + atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], &format!("127.0.0.1:{ps}"), now).unwrap() { assert!(atlas::chunks::finish(&conn, &claim, now).unwrap()); } diff --git a/tests/split_homes.rs b/tests/split_homes.rs index 5e117eb4..3ab8f713 100644 --- a/tests/split_homes.rs +++ b/tests/split_homes.rs @@ -80,6 +80,7 @@ fn a_server_without_the_group_doesnt_move_it() { let stop = Arc::new(AtomicBool::new(false)); let cfg = atlas::config::load_config().unwrap(); + let keys = atlas::nntp::server_keys(&cfg.servers); let runner = { let stop = stop.clone(); std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) @@ -114,7 +115,7 @@ fn a_server_without_the_group_doesnt_move_it() { .unwrap(); let homes = cursors.iter().filter(|(_, home)| *home).count(); assert_eq!(homes, 1, "the group stayed on one home server: {cursors:?}"); - let carriers = [format!("{SPLIT_GROUP}@127.0.0.1"), format!("{SPLIT_GROUP}@localhost")]; + let carriers = [format!("{SPLIT_GROUP}@{}", keys[0]), format!("{SPLIT_GROUP}@{}", keys[1])]; assert!(cursors.iter().all(|(name, _)| carriers.contains(name)), "only carriers have cursors: {cursors:?}"); let chunk_servers: Vec = conn @@ -125,5 +126,5 @@ fn a_server_without_the_group_doesnt_move_it() { .collect::>() .unwrap(); assert!(c.accepted.load(Ordering::SeqCst) > 0, "the third server was asked"); - assert_eq!(chunk_servers, vec!["127.0.0.1".to_string(), "localhost".to_string()], "only the carriers did chunks"); + assert_eq!(chunk_servers, keys[..2].to_vec(), "only the carriers did chunks"); } diff --git a/tests/split_retention.rs b/tests/split_retention.rs index e31556ae..8d533df5 100644 --- a/tests/split_retention.rs +++ b/tests/split_retention.rs @@ -90,8 +90,8 @@ fn days_older_than_a_servers_retention_go_to_the_server_that_has_them() { atlas::chunks::unix_day(chrono::DateTime::parse_from_rfc3339("2026-01-21T00:00:00+00:00").unwrap().timestamp()); let old_by_short: i64 = conn .query_row( - "select count(*) from backfill_chunks where server = 'localhost' and day < ?", - [first_short_day], + "select count(*) from backfill_chunks where server = ? and day < ?", + rusqlite::params![format!("localhost:{ps}"), first_short_day], |r| r.get(0), ) .unwrap(); diff --git a/tests/split_shallow_home_sweep.rs b/tests/split_shallow_home_sweep.rs index 20f2ae2d..e194b0f5 100644 --- a/tests/split_shallow_home_sweep.rs +++ b/tests/split_shallow_home_sweep.rs @@ -77,7 +77,8 @@ fn deep_only_posts_a_shallow_home_missed_are_swept_by_the_deep_server() { let first_day = atlas::chunks::unix_day(1_767_225_600); atlas::chunks::add(&conn, GROUP, first_day + 29, first_day).unwrap(); let now = chrono::Utc::now().timestamp(); - while let Some(claim) = atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], "localhost", now).unwrap() + while let Some(claim) = + atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], &format!("localhost:{ps}"), now).unwrap() { assert!(atlas::chunks::finish(&conn, &claim, now).unwrap()); } @@ -85,6 +86,7 @@ fn deep_only_posts_a_shallow_home_missed_are_swept_by_the_deep_server() { let stop = Arc::new(AtomicBool::new(false)); let cfg = atlas::config::load_config().unwrap(); + let keys = atlas::nntp::server_keys(&cfg.servers); let runner = { let stop = stop.clone(); std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) @@ -95,8 +97,7 @@ fn deep_only_posts_a_shallow_home_missed_are_swept_by_the_deep_server() { let conn = atlas::db::open_with_shards(&main).unwrap(); let (_, articles) = atlas::store::totals(&conn).unwrap(); let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); - let hosts = ["127.0.0.1".to_string(), "localhost".to_string()]; - let complete = atlas::chunks::complete(&conn, GROUP, &hosts).unwrap(); + let complete = atlas::chunks::complete(&conn, GROUP, &keys).unwrap(); if total > 0 && done == total && articles == 1200 && complete { break; } diff --git a/tests/split_sweep_own_chunks.rs b/tests/split_sweep_own_chunks.rs index 60712705..3e5884e8 100644 --- a/tests/split_sweep_own_chunks.rs +++ b/tests/split_sweep_own_chunks.rs @@ -74,7 +74,8 @@ fn a_groups_sweep_waits_only_for_its_own_chunks() { let first_day = atlas::chunks::unix_day(1_767_225_600); atlas::chunks::add(&conn, GROUP, first_day + 29, first_day).unwrap(); let now = chrono::Utc::now().timestamp(); - while let Some(claim) = atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], "127.0.0.1", now).unwrap() + while let Some(claim) = + atlas::chunks::claim(&conn, &[(GROUP.to_string(), i64::MIN)], &format!("127.0.0.1:{ps}"), now).unwrap() { assert!(atlas::chunks::finish(&conn, &claim, now).unwrap()); } From 82fba25a4b442065500c6fd46864bfe25a1be726 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 03:06:33 -0500 Subject: [PATCH 116/159] Only a window of the days one server alone has is chunks at once, extended only when they hold enough Days older than the next deepest server goes back stand on the deep server's own Date headers: one forged article a day kept thousands of them as chunks. At most 60 of them are pending at once, the older ones left to that server's sweep, and the window moves back only while the days done held 100 articles a day on average. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 109 +++++++++++++++++++++++++++++++++--- tests/split_forged_daily.rs | 107 +++++++++++++++++++++++++++++++++++ 2 files changed, 207 insertions(+), 9 deletions(-) create mode 100644 tests/split_forged_daily.rs diff --git a/src/indexer.rs b/src/indexer.rs index 8b0cdc5e..8381df8b 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -57,8 +57,37 @@ pub struct GroupRunState { /// the group is noted for good (no expiry): the scheduler skips it for /// good too pub first_post_days: HashMap)>, + /// the split's days only one server has, see `Speculative` + pub speculative: Speculative, } +/// Days of a split older than the next deepest server goes back are only +/// the deepest one's, on the word of its own Date headers: forged, one +/// article a day can make thousands of them look real, each a chunk of +/// date searches. At most `reach` of them (counted back from the first day +/// the next deepest keeps) are chunks at once, the older ones are left to +/// the deep server's sweep (see `run_sweep`). Reaching the oldest of them +/// reaches `SPECULATIVE_WINDOW` days further only when the ones done held +/// `SPECULATIVE_YIELD` articles a day on average. Kept in memory: after a +/// restart the window starts over (what was dropped is the sweep's). +#[derive(Clone, Debug)] +pub struct Speculative { + pub reach: i64, + /// days done, and the articles dated in them + pub days: i64, + pub articles: i64, +} + +impl Default for Speculative { + fn default() -> Self { + Speculative { reach: SPECULATIVE_WINDOW, days: 0, articles: 0 } + } +} + +/// see `Speculative` +const SPECULATIVE_WINDOW: i64 = 60; +const SPECULATIVE_YIELD: i64 = 100; + impl Default for GroupRunState { fn default() -> Self { GroupRunState { @@ -69,6 +98,7 @@ impl Default for GroupRunState { reach_back_after: None, keeps_from: HashMap::new(), first_post_days: HashMap::new(), + speculative: Speculative::default(), } } } @@ -953,6 +983,39 @@ async fn drop_older_days(db: &Db, group: &str, day: i64) { } } +/// A day only this server has (`day`, of the window from `floor`, see +/// `Speculative`) is done with `dated` articles in it. When it was the +/// window's oldest and the window's days held enough a day, chunks for the +/// days before it, back to the server's first post (`oldest`). Best effort: +/// a failure is only logged. +async fn reach_further( + ctx: &PassContext, + db: &Db, + group: &str, + (day, floor, oldest): (i64, i64, Option), + dated: i64, +) { + let further = ctx.states.with(group, |st| { + let s = &mut st.speculative; + s.days += 1; + s.articles += dated; + let worth = s.articles >= SPECULATIVE_YIELD * s.days; + if day == floor && worth { + s.reach += SPECULATIVE_WINDOW; + } + day == floor && worth + }); + let first = oldest.map_or(floor, crate::chunks::unix_day); + if !further || first >= floor { + return; + } + let (g, from) = (group.to_string(), (floor - SPECULATIVE_WINDOW).max(first)); + match on_db(db, move |conn| Ok(crate::chunks::add(conn, &g, floor - 1, from)?)).await { + Ok(n) => println!("[CHUNK] {group}: the days only one server has hold articles, {n} more day chunks"), + Err(e) => println!("[CHUNK] {group}: couldnt add the days further back: {e:#}"), + } +} + async fn index_chunk

( ctx: &PassContext, settings: &PassSettings, @@ -1024,6 +1087,8 @@ where // this day is older than any other server goes back: only this server // may have it, on the word of its own (forgeable) dates let mut alone = false; + // and then the first day the next deepest server keeps + let mut runner_up_day = None; let keeps_day = match oldest { // a day older than the second furthest server goes back is the // furthest one's alone: a server only looks deep enough by the dates @@ -1031,6 +1096,7 @@ where Some(t) if t <= day * 86_400 => match goes_back_furthest(ctx, db, group, server, (t, sure)).await { Ok((true, runner_up)) => { alone = runner_up.is_none_or(|r| r >= (day + 1) * 86_400); + runner_up_day = runner_up.filter(|_| alone).map(crate::chunks::unix_day); true } Ok((false, runner_up)) => { @@ -1091,6 +1157,28 @@ where Ok(range) => range, Err(e) => return failed(e.into()).await, }; + // days only this server has are bounded all together, see `Speculative` + let floor = match runner_up_day { + Some(r) => { + let floor = r - ctx.states.with(group, |st| st.speculative.reach); + let g = group.to_string(); + let dropped = on_db(db, move |conn| Ok(crate::chunks::drop_before(conn, &g, floor)?)).await; + match dropped { + Ok(0) => {} + Ok(n) => println!( + "[CHUNK] {group}: {n} days further back than {} days before the other servers go back are left to the sweeps", + r - floor + ), + Err(e) => return failed(e).await, + } + // this one was among them (claimed, not done): nothing to do + if day < floor { + return Ok(Progress::default()); + } + Some(floor) + } + None => None, + }; if start > end { finish().await?; if alone { @@ -1102,10 +1190,12 @@ where let pass = Pass { ctx, settings, db, group, server, key: cursor_key(&ctx.pool, server, group) }; let window = alone.then_some((day * 86_400, (day + 1) * 86_400)); match pass.process_range_dated(start as i64, end as i64, "CHUNK", window, progress).await { - Ok((saved, true, corroborated)) => { + Ok((saved, true, dated_in_day)) => { finish().await?; - if alone && !corroborated { + if alone && dated_in_day == 0 { drop_older_days(db, group, day).await; + } else if let Some(floor) = floor { + reach_further(ctx, db, group, (day, floor, oldest), dated_in_day).await; } Ok(saved) } @@ -1321,8 +1411,8 @@ impl Pass<'_> { Ok((saved, complete)) } - /// `process_range`, also whether any article retrieved is dated within - /// `window` (unix seconds, from up to before), false when there is none. + /// `process_range`, also how many articles retrieved are dated within + /// `window` (unix seconds, from up to before), 0 when there is none. async fn process_range_dated

( &self, start: i64, @@ -1330,11 +1420,11 @@ impl Pass<'_> { kind: &str, window: Option<(i64, i64)>, progress: &mut P, - ) -> Result<(Progress, bool, bool)> + ) -> Result<(Progress, bool, i64)> where P: FnMut(&Progress) + ?Sized, { - let mut in_window = false; + let mut in_window = 0i64; let (pool, group) = (&self.ctx.pool, self.group); // no slice bigger than the whole unsaved budget: it would hold more // headers than the cap allows @@ -1377,10 +1467,11 @@ impl Pass<'_> { continue; } - if let Some((from, to)) = window.filter(|_| !in_window) { - in_window = headers + if let Some((from, to)) = window { + in_window += headers .iter() - .any(|h| crate::dates::posted_timestamp(&h.date).is_some_and(|t| (from..to).contains(&t))); + .filter(|h| crate::dates::posted_timestamp(&h.date).is_some_and(|t| (from..to).contains(&t))) + .count() as i64; } let dated = slice_date(&headers); match save_slice(pool, self.db, group, headers).await { diff --git a/tests/split_forged_daily.rs b/tests/split_forged_daily.rs new file mode 100644 index 00000000..4a032505 --- /dev/null +++ b/tests/split_forged_daily.rs @@ -0,0 +1,107 @@ +//! A split group on two servers, one with an article dated in every day +//! from 2000 on before its real ones (forged): each of those thousands of +//! days looks corroborated by its one article. Only a window of the days +//! older than the other server goes back is serviced as chunks at once, and +//! one article a day doesnt earn more: the rest is left to the deep +//! server's sweep, which still indexes every article. +//! +//! One test, and the environment is set before any thread starts. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use common::{GROUP, Server, post_at, spawn_server}; + +/// 40 posts a day for 30 days from 2026-01-01, numbered from `offset` +fn posts(offset: u64) -> Vec { + let start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + (0..1200u64) + .map(|i| { + let when = start + chrono::Duration::minutes(i as i64 * 36); + let mut p = post_at( + offset + i, + &format!(r#""rel{}.part{}.rar" yEnc (1/1)"#, i / 10, i % 10 + 1), + &when.to_rfc2822(), + ); + p.message_id = format!(""); + p + }) + .collect() +} + +#[test] +fn forged_dates_one_a_day_back_to_2000_service_only_a_window_of_chunks() { + let home = tempfile::tempdir().unwrap(); + // SAFETY: only test in this binary, set before any thread is spawned + unsafe { + std::env::set_var("ATLAS_HOME", home.path()); + std::env::set_var("ATLAS_NO_KEYRING", "1"); + std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); + } + + // one article noon of every day from 2000-01-05 to 2025-12-31, then the real ones + let first = chrono::DateTime::parse_from_rfc3339("2000-01-05T12:00:00+00:00").unwrap(); + let split_start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); + let forged_days = (split_start - first).num_days() as u64 + 1; + let mut deep: Vec = (0..forged_days) + .map(|d| { + let when = first + chrono::Duration::days(d as i64); + let mut p = post_at(400_001 + d, &format!(r#""old{d}.rar" yEnc (1/1)"#), &when.to_rfc2822()); + p.message_id = format!(""); + p + }) + .collect(); + deep.extend(posts(400_001 + forged_days)); + let (pc, pd) = (spawn_server(Server::new(posts(1))), spawn_server(Server::new(deep))); + let config = serde_json::json!({ + "usenet_servers": [ + {"host": "127.0.0.1", "username": "bob", "password": "secret", "port": pc, "ssl": false, "connections": 4, "priority": 1}, + {"host": "localhost", "username": "bob", "password": "secret", "port": pd, "ssl": false, "connections": 4, "priority": 1} + ], + "groups": [GROUP], + "index_mode": "backfill", + "batch_size": 100, + "request_size": 50, + "split_min_backlog": 200 + }); + std::fs::write(home.path().join("config.json"), config.to_string()).unwrap(); + atlas::db::create_db().unwrap(); + + let stop = Arc::new(AtomicBool::new(false)); + let cfg = atlas::config::load_config().unwrap(); + let keys = atlas::nntp::server_keys(&cfg.servers); + let runner = { + let stop = stop.clone(); + std::thread::spawn(move || atlas::bg_indexer::run_until(cfg, stop)) + }; + + let main = home.path().join("atlas.db"); + let every = 1200 + forged_days as i64; + let deadline = Instant::now() + Duration::from_secs(180); + loop { + let conn = atlas::db::open_with_shards(&main).unwrap(); + let (_, articles) = atlas::store::totals(&conn).unwrap(); + let (done, total) = atlas::chunks::progress(&conn, GROUP).unwrap_or((0, 0)); + let swept = keys.iter().all(|h| atlas::chunks::swept(&conn, GROUP, h).unwrap()); + if total > 0 && done == total && swept && articles == every { + break; + } + assert!(Instant::now() < deadline, "articles {articles} of {every}, chunks {done}/{total}, swept {swept}"); + std::thread::sleep(Duration::from_millis(200)); + } + stop.store(true, Ordering::Relaxed); + assert_eq!(runner.join().unwrap(), 0); + + let conn = atlas::db::open_with_shards(&main).unwrap(); + let speculative: i64 = conn + .query_row( + "select count(*) from backfill_chunks where grp = ? and state = 2 and day < ?", + rusqlite::params![GROUP, atlas::chunks::unix_day(split_start.timestamp())], + |r| r.get(0), + ) + .unwrap(); + assert!(speculative <= 60, "{speculative} days older than the other server goes back were serviced"); +} From e499147fa9b5e9544b77f9a734213eb4d7ad4ce7 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 03:21:42 -0500 Subject: [PATCH 117/159] Reaching back keeps to the speculative window, kept in the database The hourly reach_back re-added the days pruned as only the deepest server's and reset the group's sweeps. It no longer adds days past the window, adds days the window allows without redoing or resetting anything, and the window is kept per group in backfill_speculative so a restart doesnt reset it. Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 82 ++++++++++++++++++++++++++++++++++++++ src/indexer.rs | 104 +++++++++++++++++++++---------------------------- 2 files changed, 127 insertions(+), 59 deletions(-) diff --git a/src/chunks.rs b/src/chunks.rs index 2810ead3..d61422f6 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -36,6 +36,13 @@ pub fn create(conn: &Connection) -> Result<()> { grp TEXT NOT NULL, server TEXT NOT NULL, primary key (grp, server) + ) without rowid; + create table if not exists backfill_speculative ( + grp TEXT PRIMARY KEY, + runner_up_day INTEGER NOT NULL, + reach INTEGER NOT NULL, + days INTEGER NOT NULL, + articles INTEGER NOT NULL ) without rowid;", )?; add_column(conn, "backfill_chunks", "done_at")?; @@ -89,9 +96,22 @@ pub fn add(conn: &Connection, group: &str, newest_day: i64, oldest_day: i64) -> pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i64) -> Result { let tx = conn.unchecked_transaction()?; let Some(old) = self::oldest_day(&tx, group)? else { return Ok(0) }; + // never past the window of days only the deepest server has + let spec = speculative(&tx, group)?; + let floor = spec.as_ref().map_or(i64::MIN, |s| s.runner_up_day - s.reach); + if oldest_day < floor { + if floor >= old { + return Ok(0); + } + return add_speculative(&tx, group, old, floor).and_then(|n| tx.commit().map(|_| n)); + } if oldest_day > old { return Ok(0); } + if spec.as_ref().is_some_and(|s| old <= s.runner_up_day) && oldest_day < old { + // only days the deepest server alone has: added, nothing redone + return add_speculative(&tx, group, old, oldest_day).and_then(|n| tx.commit().map(|_| n)); + } if oldest_day == old { let since: Option = tx .query_row("select oldest_at from backfill_deepest where grp = ?", [group], |r| r.get(0)) @@ -123,6 +143,48 @@ pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i6 Ok(added + redo) } +/// Chunks for the days before `old` back to `from`, all of them days only +/// the deepest server has: they dont change what any sweep covers. +fn add_speculative(tx: &Connection, group: &str, old: i64, from: i64) -> Result { + let mut insert = tx.prepare_cached("insert or ignore into backfill_chunks (grp, day, state) values (?, ?, ?)")?; + let mut added = 0; + for day in (from..old).rev() { + added += insert.execute(params![group, day, PENDING])?; + } + Ok(added) +} + +/// A split's days older than the next deepest server goes back stand on the +/// deepest one's own (forgeable) Date headers. At most `reach` of them, +/// counted back from `runner_up_day` (the first day the next deepest +/// keeps), are chunks at once; the older ones are left to the deep server's +/// sweep. `days` of them were done holding `articles` dated in them. Kept +/// per group in the database, soo a restart or `reach_back` doesnt undo it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Speculative { + pub runner_up_day: i64, + pub reach: i64, + pub days: i64, + pub articles: i64, +} + +pub fn speculative(conn: &Connection, group: &str) -> Result> { + conn.query_row( + "select runner_up_day, reach, days, articles from backfill_speculative where grp = ?", + [group], + |r| Ok(Speculative { runner_up_day: r.get(0)?, reach: r.get(1)?, days: r.get(2)?, articles: r.get(3)? }), + ) + .optional() +} + +pub fn set_speculative(conn: &Connection, group: &str, s: &Speculative) -> Result<()> { + conn.execute( + "insert or replace into backfill_speculative (grp, runner_up_day, reach, days, articles) values (?, ?, ?, ?, ?)", + params![group, s.runner_up_day, s.reach, s.days, s.articles], + )?; + Ok(()) +} + /// Drop split `group`'s chunks older than `day` that arent done: days no /// carrier keeps (a split reaching back that far was made from forged /// dates), which would wait for a server forever and keep the split from @@ -334,6 +396,26 @@ mod tests { assert_eq!(runner_up(&c, "g").unwrap(), None); } + #[test] + fn reaching_back_keeps_to_the_speculative_window() { + let c = conn(); + // days 100.. the next deepest keeps, 40..99 the window, older pruned + add(&c, "g", 120, 40).unwrap(); + set_speculative(&c, "g", &Speculative { runner_up_day: 100, reach: 60, days: 3, articles: 7 }).unwrap(); + set_swept(&c, "g", "a").unwrap(); + // the hourly look finds the deep server back in 2000 again: nothing + assert_eq!(reach_back(&c, "g", 10, 10 * 86_400).unwrap(), 0); + assert_eq!(oldest_day(&c, "g").unwrap(), Some(40)); + assert!(swept(&c, "g", "a").unwrap(), "the sweep isnt to do again"); + // the window kept across a restart + assert_eq!(speculative(&c, "g").unwrap().map(|s| (s.reach, s.days, s.articles)), Some((60, 3, 7))); + // a wider window: the days in it, sweeps left alone + set_speculative(&c, "g", &Speculative { runner_up_day: 100, reach: 70, days: 3, articles: 7 }).unwrap(); + assert_eq!(reach_back(&c, "g", 5, 5 * 86_400).unwrap(), 10); + assert_eq!(oldest_day(&c, "g").unwrap(), Some(30)); + assert!(swept(&c, "g", "a").unwrap()); + } + /// the day of a claim fn day(claimed: Result>) -> Option { claimed.unwrap().map(|c| c.day) diff --git a/src/indexer.rs b/src/indexer.rs index 8381df8b..a213750b 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -57,34 +57,11 @@ pub struct GroupRunState { /// the group is noted for good (no expiry): the scheduler skips it for /// good too pub first_post_days: HashMap)>, - /// the split's days only one server has, see `Speculative` - pub speculative: Speculative, } -/// Days of a split older than the next deepest server goes back are only -/// the deepest one's, on the word of its own Date headers: forged, one -/// article a day can make thousands of them look real, each a chunk of -/// date searches. At most `reach` of them (counted back from the first day -/// the next deepest keeps) are chunks at once, the older ones are left to -/// the deep server's sweep (see `run_sweep`). Reaching the oldest of them -/// reaches `SPECULATIVE_WINDOW` days further only when the ones done held -/// `SPECULATIVE_YIELD` articles a day on average. Kept in memory: after a -/// restart the window starts over (what was dropped is the sweep's). -#[derive(Clone, Debug)] -pub struct Speculative { - pub reach: i64, - /// days done, and the articles dated in them - pub days: i64, - pub articles: i64, -} - -impl Default for Speculative { - fn default() -> Self { - Speculative { reach: SPECULATIVE_WINDOW, days: 0, articles: 0 } - } -} - -/// see `Speculative` +/// the days of a split only its deepest server has that are chunks at once +/// (see `chunks::Speculative`), and the articles a day those done have to +/// hold on average to reach this many further const SPECULATIVE_WINDOW: i64 = 60; const SPECULATIVE_YIELD: i64 = 100; @@ -98,7 +75,6 @@ impl Default for GroupRunState { reach_back_after: None, keeps_from: HashMap::new(), first_post_days: HashMap::new(), - speculative: Speculative::default(), } } } @@ -984,35 +960,32 @@ async fn drop_older_days(db: &Db, group: &str, day: i64) { } /// A day only this server has (`day`, of the window from `floor`, see -/// `Speculative`) is done with `dated` articles in it. When it was the +/// `chunks::Speculative`) is done with `dated` articles in it. When it was the /// window's oldest and the window's days held enough a day, chunks for the /// days before it, back to the server's first post (`oldest`). Best effort: /// a failure is only logged. -async fn reach_further( - ctx: &PassContext, - db: &Db, - group: &str, - (day, floor, oldest): (i64, i64, Option), - dated: i64, -) { - let further = ctx.states.with(group, |st| { - let s = &mut st.speculative; +async fn reach_further(db: &Db, group: &str, (day, floor, oldest): (i64, i64, Option), dated: i64) { + let first = oldest.map_or(floor, crate::chunks::unix_day); + let g = group.to_string(); + let added = on_db(db, move |conn| { + let Some(mut s) = crate::chunks::speculative(conn, &g)? else { return Ok(0) }; s.days += 1; s.articles += dated; - let worth = s.articles >= SPECULATIVE_YIELD * s.days; - if day == floor && worth { + let further = day == floor && s.articles >= SPECULATIVE_YIELD * s.days && first < floor; + if further { s.reach += SPECULATIVE_WINDOW; } - day == floor && worth - }); - let first = oldest.map_or(floor, crate::chunks::unix_day); - if !further || first >= floor { - return; - } - let (g, from) = (group.to_string(), (floor - SPECULATIVE_WINDOW).max(first)); - match on_db(db, move |conn| Ok(crate::chunks::add(conn, &g, floor - 1, from)?)).await { + crate::chunks::set_speculative(conn, &g, &s)?; + if !further { + return Ok(0); + } + Ok(crate::chunks::add(conn, &g, floor - 1, (floor - SPECULATIVE_WINDOW).max(first))?) + }) + .await; + match added { + Ok(0) => {} Ok(n) => println!("[CHUNK] {group}: the days only one server has hold articles, {n} more day chunks"), - Err(e) => println!("[CHUNK] {group}: couldnt add the days further back: {e:#}"), + Err(e) => println!("[CHUNK] {group}: couldnt note the days only one server has: {e:#}"), } } @@ -1157,20 +1130,33 @@ where Ok(range) => range, Err(e) => return failed(e.into()).await, }; - // days only this server has are bounded all together, see `Speculative` + // days only this server has are bounded all together, see `chunks::Speculative` let floor = match runner_up_day { Some(r) => { - let floor = r - ctx.states.with(group, |st| st.speculative.reach); let g = group.to_string(); - let dropped = on_db(db, move |conn| Ok(crate::chunks::drop_before(conn, &g, floor)?)).await; - match dropped { - Ok(0) => {} - Ok(n) => println!( - "[CHUNK] {group}: {n} days further back than {} days before the other servers go back are left to the sweeps", - r - floor - ), + let dropped = on_db(db, move |conn| { + let s = match crate::chunks::speculative(conn, &g)? { + Some(s) => crate::chunks::Speculative { runner_up_day: r, ..s }, + None => { + crate::chunks::Speculative { runner_up_day: r, reach: SPECULATIVE_WINDOW, days: 0, articles: 0 } + } + }; + crate::chunks::set_speculative(conn, &g, &s)?; + let floor = r - s.reach; + Ok((floor, crate::chunks::drop_before(conn, &g, floor)?)) + }) + .await; + let floor = match dropped { + Ok((floor, 0)) => floor, + Ok((floor, n)) => { + println!( + "[CHUNK] {group}: {n} days further back than {} days before the other servers go back are left to the sweeps", + r - floor + ); + floor + } Err(e) => return failed(e).await, - } + }; // this one was among them (claimed, not done): nothing to do if day < floor { return Ok(Progress::default()); @@ -1195,7 +1181,7 @@ where if alone && dated_in_day == 0 { drop_older_days(db, group, day).await; } else if let Some(floor) = floor { - reach_further(ctx, db, group, (day, floor, oldest), dated_in_day).await; + reach_further(db, group, (day, floor, oldest), dated_in_day).await; } Ok(saved) } From c66528668bd8571e5d89aa3db210504879ac2b51 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 03:31:21 -0500 Subject: [PATCH 118/159] Each window of the days one server alone has meets the yield on its own Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/indexer.rs b/src/indexer.rs index a213750b..4c0808a7 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -973,7 +973,11 @@ async fn reach_further(db: &Db, group: &str, (day, floor, oldest): (i64, i64, Op s.articles += dated; let further = day == floor && s.articles >= SPECULATIVE_YIELD * s.days && first < floor; if further { + // each extension has to hold enough a day on its own: a dense + // first window doesnt pay for the sparse ones after it s.reach += SPECULATIVE_WINDOW; + s.days = 0; + s.articles = 0; } crate::chunks::set_speculative(conn, &g, &s)?; if !further { @@ -1689,6 +1693,32 @@ impl Indexer { mod tests { use super::*; + #[test] + fn each_speculative_window_has_to_hold_enough_on_its_own() { + let rt = tokio::runtime::Builder::new_current_thread().build().unwrap(); + rt.block_on(each_speculative_window()); + } + + async fn each_speculative_window() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let db = shared_db(db::open_at(&main).unwrap()); + let (r, g) = (20_000, "g"); + let start = crate::chunks::Speculative { runner_up_day: r, reach: SPECULATIVE_WINDOW, days: 0, articles: 0 }; + on_db(&db, move |c| Ok(crate::chunks::set_speculative(c, g, &start)?)).await.unwrap(); + let floor = r - SPECULATIVE_WINDOW; + // a dense window: its oldest day is done with plenty of articles + reach_further(&db, g, (floor, floor, Some(0)), 100_000).await; + let s = on_db(&db, move |c| Ok(crate::chunks::speculative(c, g)?)).await.unwrap().unwrap(); + assert_eq!((s.reach, s.days, s.articles), (2 * SPECULATIVE_WINDOW, 0, 0)); + // the next, sparse one doesnt ride on that: no further chunks + let floor = r - s.reach; + reach_further(&db, g, (floor, floor, Some(0)), 1).await; + let s = on_db(&db, move |c| Ok(crate::chunks::speculative(c, g)?)).await.unwrap().unwrap(); + assert_eq!(s.reach, 2 * SPECULATIVE_WINDOW); + } + #[test] fn cursors_saved_under_a_servers_old_key_are_adopted_once() { let dir = tempfile::tempdir().unwrap(); From bb8f1f4670d9e322d74cba1769a9f48dec3a1cb6 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 03:31:38 -0500 Subject: [PATCH 119/159] A plain 119 and an ssl 563 on one host are two servers with two keys Co-Authored-By: Claude Opus 5.5 --- src/nntp.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/nntp.rs b/src/nntp.rs index 70a5369f..c4a56497 100644 --- a/src/nntp.rs +++ b/src/nntp.rs @@ -1026,9 +1026,9 @@ impl Drop for Unsaved { /// What names each server in stored state (cursors, chunk claims, sweeps), /// from its own settings alone: adding or removing another server never -/// changes it (that would orphan its cursors). The host on the default port -/// for its ssl setting (563 with ssl, 119 without; what it always was), else -/// `host:port`, and `#key` after either when the server sets `key`. Two +/// changes it (that would orphan its cursors). The plain host on 563 with ssl +/// (what it always was for the usual server), else `host:port` (so a plain +/// 119 and an ssl 563 on one host are two servers), and `#key` after either when the server sets `key`. Two /// accounts on the same host and port share it (the same provider numbers /// articles the same) unless one sets a `key`. Never the user or password. pub fn server_keys(servers: &[UsenetServer]) -> Vec { @@ -1036,8 +1036,7 @@ pub fn server_keys(servers: &[UsenetServer]) -> Vec { } fn server_key(s: &UsenetServer) -> String { - let default_port = if s.use_ssl() { 563 } else { 119 }; - let base = if s.port == default_port { s.host.clone() } else { format!("{}:{}", s.host, s.port) }; + let base = if s.port == 563 && s.use_ssl() { s.host.clone() } else { format!("{}:{}", s.host, s.port) }; match &s.key { Some(k) => format!("{base}#{k}"), None => base, @@ -2326,14 +2325,19 @@ mod tests { fn a_servers_key_is_its_own_and_doesnt_change_with_the_others() { let s = |h: &str, user: &str, port: u16| UsenetServer::new(h, user, "secret", port); let first = s("A.example", "x", 563); - // the default port for its ssl setting: the plain host, like always + // 563 with ssl: the plain host, like always assert_eq!(server_keys(std::slice::from_ref(&first)), ["A.example"]); // a second account on the same host and port, another on another // port, and one with an explicit key: the first one's key stays let mut keyed = s("a.example", "y", 563); keyed.key = Some("block".into()); let all = [first.clone(), s("a.example", "y", 563), s("a.example", "z", 119), s("a.example", "w", 443), keyed]; - assert_eq!(server_keys(&all), ["A.example", "a.example", "a.example", "a.example:443", "a.example#block"]); + assert_eq!(server_keys(&all), ["A.example", "a.example", "a.example:119", "a.example:443", "a.example#block"]); + // a plain 119 and an ssl 563 on one host never share a key + let mut plain119 = s("a.example", "u", 119); + plain119.ssl = Some(false); + let keys = server_keys(&[first.clone(), plain119]); + assert_eq!(keys, ["A.example", "a.example:119"]); let mut plain = s("a.example", "v", 563); plain.ssl = Some(false); assert_eq!(server_keys(&[plain]), ["a.example:563"], "563 isnt the default without ssl"); From 69071587e173c85b39773bed767e74abf67d5958 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 03:32:03 -0500 Subject: [PATCH 120/159] Domain use is counted for the ids present, not for every id up to the highest Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 3e330d2b..c1d8e609 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -18,7 +18,7 @@ //! between moving the original aside and the copy in (a crash) is undone by //! the next start or compaction, see `recover_cut_swaps`. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -382,13 +382,12 @@ fn compact_shard( // how many articles use each domain, as rows and inside sealed blobs say("counting domains"); - let max_domain: i64 = conn.query_row("select coalesce(max(id), 0) from old.domains", [], |r| r.get(0))?; - let mut uses = vec![0u32; max_domain as usize + 1]; + // only the ids in use: earlier compactions leave the ids sparse + let mut uses: HashMap = HashMap::new(); { let mut used = |d: i64| { - if let Some(n) = uses.get_mut(d as usize) { - *n = n.saturating_add(1); - } + let n = uses.entry(d).or_insert(0); + *n = n.saturating_add(1); }; let mut stmt = conn.prepare("select domain from old.segments")?; let mut rows = stmt.query([])?; @@ -409,7 +408,7 @@ fn compact_shard( } } } - let shared = |d: i64| d != 0 && uses.get(d as usize).is_some_and(|n| *n >= SHARED_AFTER); + let shared = |d: i64| d != 0 && uses.get(&d).is_some_and(|n| *n >= SHARED_AFTER); halt(stop, shard)?; say("copying releases"); @@ -1018,6 +1017,26 @@ mod tests { assert_eq!(all_articles(&main), before, "an article already there isnt saved twice"); } + #[test] + fn a_huge_sparse_domain_id_costs_no_memory_to_count() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + // ids as sparse as earlier compactions can leave them + for path in store::shard_paths(&main) { + let conn = db::open_at(&path).unwrap(); + conn.execute_batch( + "update segments set domain = domain + 4000000000000 where domain != 0; + update domains set id = id + 4000000000000;", + ) + .unwrap(); + } + let shrunk = run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(shrunk.domains_dropped, 120); + assert_eq!(all_articles(&main), before, "every NZB reads back the same"); + } + /// the file of release `name` in its group's shard: (shard path, file id) fn file_of(main: &Path, name: &str, group: &str) -> (PathBuf, i64) { let path = store::shard_path(main, store::shard_of(group)); From bf2e8f88adf2f049687b8609f9322c4d567df980 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 03:36:43 -0500 Subject: [PATCH 121/159] Purging broken releases takes what it deleted off the totals inside its own transaction Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 84 +++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 73 insertions(+), 11 deletions(-) diff --git a/src/store.rs b/src/store.rs index df2960ae..b763ed6c 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1261,21 +1261,38 @@ pub fn totals(conn: &Connection) -> Result<(i64, i64)> { } /// Delete incomplete releases (and their files and articles) from every shard. +/// What goes is counted inside the transaction that deletes it and taken off +/// the shard's totals there, soo the writers saving to the shard at the same +/// time (purge holds only the shared guard) never leave them wrong. pub fn purge_incomplete(main: &Path) -> Result<()> { for path in shard_paths(main) { let conn = db::open_shard(&path)?; - let removed: i64 = conn.query_row("select count(*) from releases where complete = 0", [], |r| r.get(0))?; - conn.execute_batch( - "begin; - delete from segments where file_id in - (select f.id from files f join releases r on r.id = f.release_id where r.complete = 0); + // the write lock from the start: the counts are of what is deleted + let tx = rusqlite::Transaction::new_unchecked(&conn, rusqlite::TransactionBehavior::Immediate)?; + let removed: i64 = tx.query_row("select count(*) from releases where complete = 0", [], |r| r.get(0))?; + let doomed = "select f.id from files f join releases r on r.id = f.release_id where r.complete = 0"; + let loose: i64 = + tx.query_row(&format!("select count(*) from segments where file_id in ({doomed})"), [], |r| r.get(0))?; + let mut sealed = 0i64; + { + let mut stmt = + tx.prepare(&format!("select blob from files where blob is not null and id in ({doomed})"))?; + let mut rows = stmt.query([])?; + while let Some(r) = rows.next()? { + let b: Vec = r.get(0)?; + sealed += crate::blob::decode(&b).map_err(blob_error)?.len() as i64; + } + } + tx.execute_batch(&format!( + "delete from segments where file_id in ({doomed}); delete from files where release_id in (select id from releases where complete = 0); - delete from releases where complete = 0; - commit;", - )?; - let articles = article_count(&conn, "main")?; - conn.execute("update meta set value = max(value - ?, 0) where key = 'releases'", [removed])?; - conn.execute("update meta set value = ? where key = 'articles'", [articles])?; + delete from releases where complete = 0;" + ))?; + let mut stmt = tx.prepare("update meta set value = max(value - ?, 0) where key = ?")?; + stmt.execute(params![removed, "releases"])?; + stmt.execute(params![loose + sealed, "articles"])?; + drop(stmt); + tx.commit()?; let _ = conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(())); conn.execute_batch("vacuum")?; } @@ -2106,6 +2123,51 @@ mod tests { assert_eq!(writer.seal_some(&mut conn, now + 2).unwrap(), 0); } + /// what purging takes off the totals is what it deleted, counted in its + /// own transaction: the rest of the totals, including what writers added + /// in between, stays as it is + #[test] + fn purging_takes_only_what_it_deleted_off_the_totals() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let group = "alt.binaries.t"; + let release = |name: &str, parts: i64, have: i64| Release { + name: name.into(), + group: group.into(), + articles: (1..=have) + .map(|p| Article { + message_id: format!("<{name}-{p}@x>"), + filename: Some("a.rar".into()), + part: Some(p), + total_parts: Some(parts), + bytes: 10, + ..Default::default() + }) + .collect(), + ..Default::default() + }; + // two broken releases (3 + 2 articles) and a whole one + save(&main, &[release("Broken1", 5, 3), release("Broken2", 4, 2), release("Whole1", 2, 2)]).unwrap(); + let shard = shard_path(&main, shard_of(group)); + let conn = db::open_at(&shard).unwrap(); + let totals = |c: &Connection| -> (i64, i64) { + let get = |k: &str| c.query_row("select value from meta where key = ?", [k], |r| r.get(0)).unwrap(); + (get("releases"), get("articles")) + }; + assert_eq!(totals(&conn), (3, 7)); + // a writer in another connection added a release and its count, and + // another's not yet seen in the rows (3 more in the total) + save(&main, &[release("Whole2", 3, 3)]).unwrap(); + conn.execute("update meta set value = value + 3 where key = 'articles'", []).unwrap(); + assert_eq!(totals(&conn), (4, 13)); + + purge_incomplete(&main).unwrap(); + assert_eq!(totals(&conn), (2, 8), "only the 2 releases and 5 articles that were deleted went"); + let left: i64 = conn.query_row("select count(*) from releases", [], |r| r.get(0)).unwrap(); + assert_eq!(left, 2); + } + #[test] fn a_failed_save_leaves_no_domain_behind_in_the_writer() { let dir = tempfile::tempdir().unwrap(); From 75ddd9ac319c1e30c2cd830aff324f16bbe49566 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 03:55:36 -0500 Subject: [PATCH 122/159] A due recovery sweep is taken before a worker's normal groups, soo busy home groups cant starve it Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 151 ++++++++++++++++++++++++++++------------------ 1 file changed, 93 insertions(+), 58 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 0ad29a70..41a05853 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -527,21 +527,26 @@ async fn take_sweep(sched: &Scheduler, server: usize, db: &Db) -> Option found } -/// What a worker with no group of its own does. -enum IdleWork { +/// What a worker does next. +enum Work { + Group(String), Chunk(crate::chunks::Claim), Sweep(String), } -/// Work for an idle worker on `server`: a due sweep of a split group whose -/// chunks are done (see `take_sweep`) before any day chunk, soo another -/// group's endless chunks dont hold it off until what it would find ages -/// out. One worker per server sweeps at a time, the others take chunks. -async fn take_idle_work(sched: &Scheduler, server: usize, db: &Db) -> Option { +/// Next work for a worker on `server`. A due sweep of a split group whose +/// chunks are done (see `take_sweep`) comes first, before its normal groups, +/// soo home groups that keep every worker busy dont hold it off until what +/// it would find ages out. One worker per server sweeps at a time, the +/// others index their groups or take day chunks. +async fn next_work(sched: &Scheduler, server: usize, db: &Db) -> Option { if let Some(group) = take_sweep(sched, server, db).await { - return Some(IdleWork::Sweep(group)); + return Some(Work::Sweep(group)); } - take_chunk(sched, server, db).await.map(IdleWork::Chunk) + if let Some(group) = sched.take_group(server) { + return Some(Work::Group(group)); + } + take_chunk(sched, server, db).await.map(Work::Chunk) } /// One worker on `server`: index whichever of its groups is due next, again and again. @@ -549,37 +554,35 @@ async fn take_idle_work(sched: &Scheduler, server: usize, db: &Db) -> Option, server: usize, db: Db) { while !sched.stopping() { - let Some(group) = sched.take_group(server) else { - match take_idle_work(&sched, server, &db).await { - // help with a split group's day chunks. not marked busy, a - // group's chunks run on several servers at once - Some(IdleWork::Chunk(chunk)) => { - let settings = sched.settings.read().unwrap().clone(); - let stats = sched.stats.clone(); - let group = chunk.group.clone(); - let mut progress = - |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); - let run = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &chunk, server, &mut progress); - let Some(result) = unless_stopped(&sched.ctx.stop, run).await else { break }; - sched.finish_chunk(chunk.group, server, result); - continue; - } - Some(IdleWork::Sweep(group)) => { - let settings = sched.settings.read().unwrap().clone(); - let stats = sched.stats.clone(); - let mut progress = - |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); - let run = crate::indexer::run_sweep(&sched.ctx, &settings, &db, &group, server, &mut progress); - let result = unless_stopped(&sched.ctx.stop, run).await; - sched.sweeping.lock().unwrap().remove(&server); - let Some(result) = result else { break }; - sched.finish_chunk(group, server, result); - continue; - } - None => {} + let group = match next_work(&sched, server, &db).await { + Some(Work::Group(group)) => group, + // help with a split group's day chunks. not marked busy, a + // group's chunks run on several servers at once + Some(Work::Chunk(chunk)) => { + let settings = sched.settings.read().unwrap().clone(); + let stats = sched.stats.clone(); + let group = chunk.group.clone(); + let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); + let run = crate::indexer::run_chunk(&sched.ctx, &settings, &db, &chunk, server, &mut progress); + let Some(result) = unless_stopped(&sched.ctx.stop, run).await else { break }; + sched.finish_chunk(chunk.group, server, result); + continue; + } + Some(Work::Sweep(group)) => { + let settings = sched.settings.read().unwrap().clone(); + let stats = sched.stats.clone(); + let mut progress = |p: &Progress| stats.lock().unwrap().tick(p.articles, p.bytes, p.releases, &group); + let run = crate::indexer::run_sweep(&sched.ctx, &settings, &db, &group, server, &mut progress); + let result = unless_stopped(&sched.ctx.stop, run).await; + sched.sweeping.lock().unwrap().remove(&server); + let Some(result) = result else { break }; + sched.finish_chunk(group, server, result); + continue; + } + None => { + nap(Duration::from_secs(1), || sched.stopping()).await; + continue; } - nap(Duration::from_secs(1), || sched.stopping()).await; - continue; }; let settings = sched.settings.read().unwrap().clone(); @@ -1032,21 +1035,8 @@ mod tests { assert!(chunk_groups("live", &groups, &HashSet::new()).is_empty(), "live never backfills"); } - /// a sweep due on a server comes before another group's day chunks - #[test] - fn a_due_sweep_comes_before_other_groups_chunks() { - let dir = tempfile::tempdir().unwrap(); - let main = dir.path().join("atlas.db"); - db::create_db_at(&main).unwrap(); - let pool = Pool::new(&[UsenetServer::new("a.test", "u", "p", 119), UsenetServer::new("b.test", "u", "p", 119)]); - // "done" split with its chunks all done, "busy" with many to go - let conn = db::open_at(&main).unwrap(); - crate::chunks::add(&conn, "done", 20_000, 19_990).unwrap(); - conn.execute("update backfill_chunks set state = 2 where grp = 'done'", []).unwrap(); - crate::chunks::add(&conn, "busy", 20_000, 10_000).unwrap(); - // the server that isnt done's home sweeps it - let server = 1 - pool.pick_server("done"); - let sched = Scheduler { + fn scheduler(pool: Pool, groups: Vec) -> Scheduler { + Scheduler { ctx: PassContext { pool: Arc::new(pool), states: RunStates::default(), @@ -1054,7 +1044,7 @@ mod tests { verbose: false, }, settings: RwLock::new(PassSettings { mode: "backfill".into(), ..PassSettings::default() }), - groups: RwLock::new(vec!["busy".into(), "done".into()]), + groups: RwLock::new(groups), plan: vec![], workers: 2, next: Default::default(), @@ -1071,13 +1061,58 @@ mod tests { compact_after: None, auto_compact: AtomicBool::new(false), passes: AtomicUsize::new(0), - }; + } + } + + /// a sweep due on a server comes before another group's day chunks + #[test] + fn a_due_sweep_comes_before_other_groups_chunks() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let pool = Pool::new(&[UsenetServer::new("a.test", "u", "p", 119), UsenetServer::new("b.test", "u", "p", 119)]); + // "done" split with its chunks all done, "busy" with many to go + let conn = db::open_at(&main).unwrap(); + crate::chunks::add(&conn, "done", 20_000, 19_990).unwrap(); + conn.execute("update backfill_chunks set state = 2 where grp = 'done'", []).unwrap(); + crate::chunks::add(&conn, "busy", 20_000, 10_000).unwrap(); + // the server that isnt done's home sweeps it + let server = 1 - pool.pick_server("done"); + let sched = scheduler(pool, vec!["busy".into(), "done".into()]); let db = shared_db(conn); let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); rt.block_on(async { - assert!(matches!(take_idle_work(&sched, server, &db).await, Some(IdleWork::Sweep(g)) if g == "done")); + assert_eq!(take_sweep(&sched, server, &db).await.as_deref(), Some("done")); // one sweep per server at a time: the next worker takes a chunk - assert!(matches!(take_idle_work(&sched, server, &db).await, Some(IdleWork::Chunk(c)) if c.group == "busy")); + assert!(take_sweep(&sched, server, &db).await.is_none()); + assert!(matches!(take_chunk(&sched, server, &db).await, Some(c) if c.group == "busy")); + }); + } + + /// home groups that keep every worker busy dont hold a due sweep off + #[test] + fn a_due_sweep_runs_while_home_groups_keep_workers_busy() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let pool = Pool::new(&[UsenetServer::new("a.test", "u", "p", 119), UsenetServer::new("b.test", "u", "p", 119)]); + let conn = db::open_at(&main).unwrap(); + crate::chunks::add(&conn, "done", 20_000, 19_990).unwrap(); + conn.execute("update backfill_chunks set state = 2 where grp = 'done'", []).unwrap(); + let server = 1 - pool.pick_server("done"); + // more home groups on that server than it has workers + let homes: Vec = + (0..).map(|i| format!("home{i}")).filter(|g| pool.pick_server(g) == server).take(4).collect(); + let mut groups = homes.clone(); + groups.push("done".into()); + let sched = scheduler(pool, groups); + let db = shared_db(conn); + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async { + assert!(matches!(next_work(&sched, server, &db).await, Some(Work::Sweep(g)) if g == "done")); + // one sweeper per server: the others keep to their groups + assert!(matches!(next_work(&sched, server, &db).await, Some(Work::Group(_)))); + assert!(matches!(next_work(&sched, server, &db).await, Some(Work::Group(_)))); }); } } From 3727fbe89f96a074dea3425dbc571b7fdc792966 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:08:13 -0500 Subject: [PATCH 123/159] A release saved again with no parts yet is counted once, found by the id the upsert returns Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/store.rs b/src/store.rs index b763ed6c..4300fb19 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1064,7 +1064,8 @@ impl ShardWriter { .optional()?; profile::UPSERT.add_since(t); let Some((release_id, old_size, old_parts, old_file_total)) = row else { continue }; - if old_parts.is_none() { + // inserted, not merged: the id that came back is the one proposed + if release_id == id { new_releases += 1; } @@ -1677,6 +1678,26 @@ mod tests { assert_eq!(seal_file(&conn, a).unwrap(), 3, "the copy isnt added"); } + /// A release saved again with no articles of its own (its `parts` still + /// NULL) is the same release: the shard's release total counts it once. + #[test] + fn upserting_a_release_with_null_parts_twice_counts_it_once() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let bare = || Release { name: "Bare".into(), group: "alt.binaries.t".into(), ..Default::default() }; + let releases = || -> i64 { + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + conn.query_row("select value from meta where key = 'releases'", [], |r| r.get(0)).unwrap() + }; + save(&main, &[bare()]).unwrap(); + let once = releases(); + save(&main, &[bare()]).unwrap(); + save(&main, &[bare()]).unwrap(); + assert_eq!(once, 1); + assert_eq!(releases(), once); + } + /// A copy saved as a row counted in its release's size and parts and the /// shard's article total: dropping it when the file is sealed again /// takes it out of them too, back to what one copy gives. From 6c8b62160b41244c14002cef3afbbf02ff79e900 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:08:23 -0500 Subject: [PATCH 124/159] A sealed segment whose message-id outgrows a blob's bound when its domain is dropped is stored as a row Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/src/compact.rs b/src/compact.rs index c1d8e609..85af0746 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -489,6 +489,9 @@ fn compact_shard( // its blob, with every message-id stored the way its rows are let old_blob: Option> = f.get(10)?; let mut segs = Vec::new(); + // old blob segments whose rewritten message-id is past what a blob + // takes (a dropped domain's suffix made whole again) become rows + let mut spilled = Vec::new(); for seg in old_blob.as_deref().map(|b| unseal(shard, id, b)).transpose()?.unwrap_or_default() { let suffix: Option = if seg.domain != 0 && !shared(seg.domain) { suffix_of.query_row([seg.domain], |r| r.get(0)).optional()? @@ -496,8 +499,13 @@ fn compact_shard( None }; let (local, domain) = rewrite(shard, id, seg.local, seg.domain, shared(seg.domain), suffix.as_deref())?; - segs.push(Seg { local, domain, ..seg }); + if local.len() > blob::MAX_LOCAL { + spilled.push(Row { file_id: id, local, domain, part: seg.part, bytes: Some(seg.bytes) }); + } else { + segs.push(Seg { local, domain, ..seg }); + } } + file_rows.extend(spilled); // a row the blob already has (the same message-id) isnt copied: // it goes before the blob is counted, the way `seal_rows` drops it @@ -1177,6 +1185,38 @@ mod tests { assert_eq!(all_articles(&main), before, "every NZB reads back the same"); } + /// A sealed segment whose message-id grows past what a blob takes when its + /// domain is dropped stays a row, so no blob outgrows `decode_capped`. + #[test] + fn a_dropped_domains_long_message_id_leaves_the_blob_as_a_row() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}, &no_stop()).unwrap(); + let (path, file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + { + let conn = db::open_at(&path).unwrap(); + let suffix = format!("@{}>", "d".repeat(240)); + conn.execute("insert into domains (suffix) values (?)", [&suffix]).unwrap(); + let d: i64 = conn.query_row("select id from domains where suffix = ?", [&suffix], |r| r.get(0)).unwrap(); + let blob: Vec = conn.query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + let mut segs = crate::blob::decode(&blob).unwrap(); + let mut local = vec![0u8]; + local.extend(std::iter::repeat_n(b'a', 300)); + segs.push(Seg { part: Some(99), bytes: 5, domain: d, local }); + conn.execute("update files set blob = ? where id = ?", params![crate::blob::encode(&segs), file]).unwrap(); + } + let before = all_articles(&main); + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(all_articles(&main), before, "every NZB reads back the same"); + let conn = db::open_at(&path).unwrap(); + let blob: Vec = conn.query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + assert!(crate::blob::decode(&blob).unwrap().iter().all(|s| s.local.len() <= crate::blob::MAX_LOCAL)); + let rows: i64 = + conn.query_row("select count(*) from segments where file_id = ?", [file], |r| r.get(0)).unwrap(); + assert_eq!(rows, 1, "the long one is a row"); + } + #[test] fn a_file_over_the_cap_is_copied_as_rows_and_its_nzb_is_the_same() { let dir = tempfile::tempdir().unwrap(); From 1fb36fa70a5472ebd04e78342c7beb25eec967ef Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:16:23 -0500 Subject: [PATCH 125/159] A stopped conversion resumes only for the same old database: its own identity, file sizes and times, not just counts Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 98 +++++++++++++++++++++++++++++++++++++----------- tests/convert.rs | 28 ++++++++++++++ 2 files changed, 105 insertions(+), 21 deletions(-) diff --git a/src/convert.rs b/src/convert.rs index 83fde5c8..90e0ac75 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -116,7 +116,7 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { // a run that got through the copy and was stopped during the check // picks up there instead of copying everything again - let source = Source::of(&old)?; + let source = Source::of(&old, main)?; let (max_id, shard_of_old, moved_releases, moved_articles, orphans) = if copy_finished(main, &source) { progress("converting the database: the copy finished earlier, checking it"); let max_id: i64 = old.query_row("select coalesce(max(id), 0) from releases", [], |r| r.get(0))?; @@ -743,50 +743,106 @@ fn copy( let total_articles: i64 = old.query_row("select coalesce(max(id), 0) from articles", [], |r| r.get(0))?; let (moved_articles, orphans) = move_articles(main, total_articles, &shard_of_old, started, progress)?; + // the copy's own connections to the old database have closed (the last one + // folds its -wal in), soo its files are as a stopped run will find them + let conn = db::open_at(&new_main)?; + Source::of(old, main)?.save(&conn)?; + Ok((max_id, shard_of_old, moved_releases, moved_articles, orphans)) } -/// What the old database held when a copy started: its release and article -/// counts and highest ids, and a digest of its `groups` rows (the cursors: -/// scans of empty ranges move them without adding anything). A copy is only -/// picked up again from the same old database; one written to or put back -/// from another backup since differs. +/// What the old database was when a copy started: its release and article +/// counts and highest ids, a digest of its `groups` rows (the cursors: scans +/// of empty ranges move them without adding anything), an identity written +/// into its own meta on the first attempt, and the size and modification time +/// of its file and its -wal (a change that keeps every count, an edit to one +/// release, still moves those). A copy is only picked up again from the same +/// old database; one written to or put back from another backup since differs. #[derive(Debug, PartialEq)] -struct Source([i64; 5]); - -const SOURCE_KEYS: [&str; 5] = - ["source_releases", "source_max_release", "source_articles", "source_max_article", "source_groups"]; +struct Source(Vec<(&'static str, String)>); impl Source { - fn of(old: &Connection) -> Result { - let (releases, max_release) = + fn of(old: &Connection, main: &Path) -> Result { + let (releases, max_release): (i64, i64) = old.query_row("select count(*), coalesce(max(id), 0) from releases", [], |r| Ok((r.get(0)?, r.get(1)?)))?; - let (articles, max_article) = + let (articles, max_article): (i64, i64) = old.query_row("select count(*), coalesce(max(id), 0) from articles", [], |r| Ok((r.get(0)?, r.get(1)?)))?; - Ok(Source([releases, max_release, articles, max_article, groups_digest(old)?])) + // the identity first: writing it is a change to the files stat'd below + let uuid = source_identity(main)?; + let stat = |path: PathBuf| -> String { + // an empty -wal is as good as none: opening a database touches it + let Ok(m) = std::fs::metadata(&path) else { return "none".into() }; + if m.len() == 0 && path.to_string_lossy().ends_with("-wal") { + return "none".into(); + } + let nanos = + m.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos()); + format!("{}:{}", m.len(), nanos.unwrap_or(0)) + }; + let wal = PathBuf::from(format!("{}-wal", main.display())); + Ok(Source(vec![ + ("source_releases", releases.to_string()), + ("source_max_release", max_release.to_string()), + ("source_articles", articles.to_string()), + ("source_max_article", max_article.to_string()), + ("source_groups", groups_digest(old)?.to_string()), + ("source_uuid", uuid), + ("source_db_file", stat(main.to_path_buf())), + ("source_wal_file", stat(wal)), + ])) } /// into the new main database's meta, as the copy starts fn save(&self, conn: &Connection) -> Result<()> { - for (key, value) in SOURCE_KEYS.iter().zip(self.0) { + for (key, value) in &self.0 { conn.execute("insert or replace into meta (key, value) values (?, ?)", params![key, value])?; } Ok(()) } - fn saved(conn: &Connection) -> Result> { - let mut values = [0; 5]; - for (key, value) in SOURCE_KEYS.iter().zip(values.iter_mut()) { - let Some(v) = conn.query_row("select value from meta where key = ?", [key], |r| r.get(0)).optional()? + fn saved(conn: &Connection, like: &Source) -> Result> { + let mut values = Vec::new(); + for (key, _) in &like.0 { + let Some(v) = + conn.query_row("select cast(value as text) from meta where key = ?", [key], |r| r.get(0)).optional()? else { return Ok(None); }; - *value = v; + values.push((*key, v)); } Ok(Some(Source(values))) } } +/// The old database's random identity, written into its meta the first time +/// a conversion is tried on it and read back after that. Its -wal is folded +/// in here too: whichever connection closes last does that anyway, and it +/// would change the files a stopped run is checked against, soo it's done +/// first, before they are looked at. +fn source_identity(main: &Path) -> Result { + let conn = Connection::open(main).context("opening the old database to identify it")?; + conn.busy_timeout(std::time::Duration::from_secs(30))?; + let read = |conn: &Connection| -> Option { + conn.query_row("select cast(value as text) from meta where key = 'source_uuid'", [], |r| r.get(0)).ok() + }; + let uuid = match read(&conn) { + Some(uuid) => uuid, + None => { + let mut bytes = [0u8; 16]; + getrandom::fill(&mut bytes).map_err(|e| anyhow!("no random bytes for the source identity: {e}"))?; + let uuid: String = bytes.iter().map(|b| format!("{b:02x}")).collect(); + conn.execute_batch("create table if not exists meta (key text primary key, value)")?; + conn.execute("insert or ignore into meta (key, value) values ('source_uuid', ?)", [&uuid])?; + read(&conn).ok_or_else(|| anyhow!("the source identity was not written"))? + } + }; + // best effort, never waited for: a reader holding it back only means a + // stopped run is copied again + conn.busy_timeout(std::time::Duration::ZERO)?; + let _ = conn.query_row("pragma wal_checkpoint(truncate)", [], |_| Ok(())); + Ok(uuid) +} + /// FNV-1a over every column of every `groups` row in name order, stable /// across builds (it's kept in the new database's meta between runs) fn groups_digest(old: &Connection) -> Result { @@ -829,7 +885,7 @@ fn groups_digest(old: &Connection) -> Result { fn copy_finished(main: &Path, source: &Source) -> bool { let new_main = sibling(main, "atlas.new.db"); new_main.exists() - && db::open_at(&new_main).ok().and_then(|c| Source::saved(&c).ok().flatten()).as_ref() == Some(source) + && db::open_at(&new_main).ok().and_then(|c| Source::saved(&c, source).ok().flatten()).as_ref() == Some(source) && store::shard_paths(main).iter().all(|p| { p.exists() && db::open_at(p) diff --git a/tests/convert.rs b/tests/convert.rs index 42340f68..384bb348 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -395,6 +395,34 @@ fn a_stopped_conversion_copies_again_when_the_old_database_changed() { assert_eq!(store::articles(&conn, id).unwrap().len(), 1); } +/// A change that keeps every count, id and cursor (here a rename) is still a +/// change to the old database: the stopped copy is thrown away, not trusted. +#[test] +fn a_stopped_conversion_copies_again_when_a_release_changed_under_the_same_counts() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + db::create_db_at(&main).unwrap(); + + let stopped = std::panic::catch_unwind(|| { + convert::run(&main, &|m| assert!(!m.contains("checking NZBs"), "stop here")).unwrap(); + }); + assert!(stopped.is_err()); + + Connection::open(&main) + .unwrap() + .execute("update releases set name = name || '.v2' where name = 'Release.17'", []) + .unwrap(); + + let messages = std::cell::RefCell::new(Vec::new()); + convert::run(&main, &|m| messages.borrow_mut().push(m.to_string())).unwrap(); + assert!(!messages.borrow().iter().any(|m| m.contains("copy finished earlier")), "{messages:?}"); + let conn = db::open_with_shards(&main).unwrap(); + let renamed: i64 = + conn.query_row("select count(*) from releases where name like '%.v2'", [], |r| r.get(0)).unwrap(); + assert_eq!(renamed, 1); +} + /// Scans of empty ranges move an old database's cursors without adding a /// release or article: a stopped conversion copies again then too, soo the /// swap doesnt put back the cursors from before and redo those scans. From b9ac720332540a5dabf9ba7181044eb5fd7653b7 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:16:50 -0500 Subject: [PATCH 126/159] A worker that just swept takes a due group of its own next, so a lone worker doesnt sweep forever Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 47 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 41 insertions(+), 6 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 41a05853..974da910 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -538,8 +538,14 @@ enum Work { /// chunks are done (see `take_sweep`) comes first, before its normal groups, /// soo home groups that keep every worker busy dont hold it off until what /// it would find ages out. One worker per server sweeps at a time, the -/// others index their groups or take day chunks. -async fn next_work(sched: &Scheduler, server: usize, db: &Db) -> Option { +/// others index their groups or take day chunks. `after_sweep`: the worker's +/// last pick was a sweep, soo a due group of its own goes before the next. +async fn next_work(sched: &Scheduler, server: usize, db: &Db, after_sweep: bool) -> Option { + // right after a sweep a due normal group goes first, soo a worker that + // is alone on its server alternates instead of sweeping forever + if after_sweep && let Some(group) = sched.take_group(server) { + return Some(Work::Group(group)); + } if let Some(group) = take_sweep(sched, server, db).await { return Some(Work::Sweep(group)); } @@ -553,8 +559,11 @@ async fn next_work(sched: &Scheduler, server: usize, db: &Db) -> Option { /// All workers share one db connection, soo their writes queue up in order /// instead of racing for sqlite's write lock (and timing out on a busy db). async fn worker(sched: Arc, server: usize, db: Db) { + let mut after_sweep = false; while !sched.stopping() { - let group = match next_work(&sched, server, &db).await { + let work = next_work(&sched, server, &db, after_sweep).await; + after_sweep = matches!(work, Some(Work::Sweep(_))); + let group = match work { Some(Work::Group(group)) => group, // help with a split group's day chunks. not marked busy, a // group's chunks run on several servers at once @@ -1109,10 +1118,36 @@ mod tests { let db = shared_db(conn); let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); rt.block_on(async { - assert!(matches!(next_work(&sched, server, &db).await, Some(Work::Sweep(g)) if g == "done")); + assert!(matches!(next_work(&sched, server, &db, false).await, Some(Work::Sweep(g)) if g == "done")); // one sweeper per server: the others keep to their groups - assert!(matches!(next_work(&sched, server, &db).await, Some(Work::Group(_)))); - assert!(matches!(next_work(&sched, server, &db).await, Some(Work::Group(_)))); + assert!(matches!(next_work(&sched, server, &db, false).await, Some(Work::Group(_)))); + assert!(matches!(next_work(&sched, server, &db, false).await, Some(Work::Group(_)))); + }); + } + + /// a worker alone on its server alternates a due sweep with its home group + #[test] + fn a_lone_worker_alternates_a_due_sweep_with_its_home_group() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let pool = Pool::new(&[UsenetServer::new("a.test", "u", "p", 119), UsenetServer::new("b.test", "u", "p", 119)]); + let conn = db::open_at(&main).unwrap(); + crate::chunks::add(&conn, "done", 20_000, 19_990).unwrap(); + conn.execute("update backfill_chunks set state = 2 where grp = 'done'", []).unwrap(); + let server = 1 - pool.pick_server("done"); + let home = (0..).map(|i| format!("home{i}")).find(|g| pool.pick_server(g) == server).unwrap(); + let sched = scheduler(pool, vec![home.clone(), "done".into()]); + let db = shared_db(conn); + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); + rt.block_on(async { + // the sweep first, as before + assert!(matches!(next_work(&sched, server, &db, false).await, Some(Work::Sweep(g)) if g == "done")); + sched.sweeping.lock().unwrap().remove(&server); + // then the due home group, though the sweep is still due + assert!(matches!(next_work(&sched, server, &db, true).await, Some(Work::Group(g)) if g == home)); + // and the sweep again after the group + assert!(matches!(next_work(&sched, server, &db, false).await, Some(Work::Sweep(g)) if g == "done")); }); } } From b0a16d85f18148f4bae26f4d4fd8e4edc8a4ee3c Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:41:36 -0500 Subject: [PATCH 127/159] A late row is a copy of a blob's segment by its message-id, stored whole or packed, in sealing and in compaction Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 63 +++++++++++++++++++++++++++++++++++++++++++++++--- src/store.rs | 59 +++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 116 insertions(+), 6 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 85af0746..e62e1374 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -510,9 +510,17 @@ fn compact_shard( // a row the blob already has (the same message-id) isnt copied: // it goes before the blob is counted, the way `seal_rows` drops it if !segs.is_empty() { - let held: HashSet<(&[u8], i64)> = segs.iter().map(|s| (s.local.as_slice(), s.domain)).collect(); - let (dropped, kept): (Vec, Vec) = - file_rows.into_iter().partition(|r| held.contains(&(r.local.as_slice(), r.domain))); + // (the same message-id, whichever way each is stored now) + let mut key = |local: &[u8], domain: i64| -> Result { + let suffix: Option = + if domain == 0 { None } else { suffix_of.query_row([domain], |r| r.get(0)).optional()? }; + Ok(store::dedup_key(local, domain, suffix.as_deref())) + }; + let held: HashSet = segs.iter().map(|s| key(&s.local, s.domain)).collect::>()?; + let (mut dropped, mut kept) = (Vec::new(), Vec::new()); + for r in file_rows { + if held.contains(&key(&r.local, r.domain)?) { dropped.push(r) } else { kept.push(r) } + } file_rows = kept; if !dropped.is_empty() { // out of the release's and the shard's totals too, copied as they were @@ -1185,6 +1193,55 @@ mod tests { assert_eq!(all_articles(&main), before, "every NZB reads back the same"); } + /// A segment stored whole in a blob (before its domain became shared) and + /// the same message-id posted again, packed under the shared domain, are + /// one article: compaction drops the row. + #[test] + fn compacting_drops_a_packed_row_whose_blob_has_the_same_id_whole() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}, &no_stop()).unwrap(); + let before = all_articles(&main); + let count = article_total(&main); + + let (path, file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + let once = release_totals(&path, file); + { + let conn = db::open_at(&path).unwrap(); + let blob: Vec = conn.query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + let mut segs = crate::blob::decode(&blob).unwrap(); + let at = segs.iter().position(|s| s.domain != 0).expect("a packed segment"); + let seg = segs[at].clone(); + let suffix: String = + conn.query_row("select suffix from domains where id = ?", [seg.domain], |r| r.get(0)).unwrap(); + // the blob has it whole, the late row packed + segs[at].local = store::whole(&store::decode(&seg.local, Some(&suffix))); + segs[at].domain = 0; + conn.execute("update files set blob = ? where id = ?", params![crate::blob::encode(&segs), file]).unwrap(); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", + params![file, seg.local, seg.domain, seg.part, seg.bytes], + ) + .unwrap(); + conn.execute("update files set touched_at = 0 where id = ?", [file]).unwrap(); + conn.execute( + "update releases set size = size + ?, parts = parts + 1 + where id = (select release_id from files where id = ?)", + params![seg.bytes, file], + ) + .unwrap(); + store::add_totals(&conn, 0, 1).unwrap(); + } + assert_eq!(article_total(&main), count + 1); + + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(article_total(&main), count, "the late copy went"); + assert_eq!(release_totals(&path, file), once); + assert_eq!(loose(&main), 0); + assert_eq!(all_articles(&main), before); + } + /// A sealed segment whose message-id grows past what a blob takes when its /// domain is dropped stays a row, so no blob outgrows `decode_capped`. #[test] diff --git a/src/store.rs b/src/store.rs index 4300fb19..ac73ce00 100644 --- a/src/store.rs +++ b/src/store.rs @@ -463,6 +463,17 @@ impl Domains { } } +/// What decides two stored segments are the same article: the message-id as +/// text, however it is stored (whole, packed, or packed the old way under a +/// domain). A domain with no suffix row can't be told apart from another +/// id, soo it keeps its own (domain, local) as the key. +pub(crate) fn dedup_key(local: &[u8], domain: i64, suffix: Option<&str>) -> String { + match (domain, suffix) { + (0, _) | (_, Some(_)) => decode(local, suffix), + _ => format!("\0{domain}\0{}", local.iter().map(|b| format!("{b:02x}")).collect::()), + } +} + /// A message-id back from its packed local part and its domain's suffix /// (none for domain 0, kept whole). pub(crate) fn decode(local: &[u8], suffix: Option<&str>) -> String { @@ -711,9 +722,25 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { // a row the blob already has (saved past a save's decode budget, see // `SealedCache`) isnt added twice: it goes, before the blob is counted, // soo a full blob doesnt keep it a row - let held: HashSet<(&[u8], i64)> = segs.iter().map(|s| (s.local.as_slice(), s.domain)).collect(); - let (copies, rows): (Vec, Vec) = - rows.into_iter().partition(|r| held.contains(&(r.local.as_slice(), r.domain))); + // (the same message-id, even stored whole in the blob and packed in the + // row, or the other way round, when a domain got shared in between) + let mut suffixes: HashMap> = HashMap::new(); + let mut key = |s: &crate::blob::Seg| -> Result { + if s.domain != 0 && !suffixes.contains_key(&s.domain) { + let suffix = conn + .prepare_cached("select suffix from domains where id = ?")? + .query_row([s.domain], |r| r.get(0)) + .optional()?; + suffixes.insert(s.domain, suffix); + } + Ok(dedup_key(&s.local, s.domain, suffixes.get(&s.domain).and_then(|x| x.as_deref()))) + }; + let held: HashSet = segs.iter().map(&mut key).collect::>()?; + let (mut copies, mut fresh) = (Vec::new(), Vec::new()); + for r in rows { + if held.contains(&key(&r)?) { copies.push(r) } else { fresh.push(r) } + } + let rows = fresh; for copy in &copies { conn.prepare_cached("delete from segments where file_id = ? and local = ? and domain = ?")? .execute(params![file_id, copy.local, copy.domain])?; @@ -1678,6 +1705,32 @@ mod tests { assert_eq!(seal_file(&conn, a).unwrap(), 3, "the copy isnt added"); } + /// An article saved whole before its domain was shared, and again packed + /// after: the same message-id, so sealing drops the row and its counts. + #[test] + fn resealing_drops_a_packed_row_whose_blob_has_the_same_id_whole() { + let (_dir, main) = sealed_fixture(); + let conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + let a: i64 = conn.query_row("select id from files where filename = 'a.rar'", [], |r| r.get(0)).unwrap(); + assert_eq!(seal_file(&conn, a).unwrap(), 3); + let held = sealed_segments(&conn, a).unwrap().unwrap(); + let a1 = held.iter().find(|s| s.local == whole("")).expect(" stored whole"); + let d: i64 = conn.query_row("select id from domains where suffix = '@x>'", [], |r| r.get(0)).unwrap(); + let articles_before: i64 = + conn.query_row("select value from meta where key = 'articles'", [], |r| r.get(0)).unwrap(); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", + params![a, pack_local("a1"), d, a1.part, a1.bytes], + ) + .unwrap(); + add_totals(&conn, 0, 1).unwrap(); + assert_eq!(seal_file(&conn, a).unwrap(), 3, "the packed copy isnt added"); + let loose: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(loose, 1, "only the other file's row is left"); + let articles: i64 = conn.query_row("select value from meta where key = 'articles'", [], |r| r.get(0)).unwrap(); + assert_eq!(articles, articles_before); + } + /// A release saved again with no articles of its own (its `parts` still /// NULL) is the same release: the shard's release total counts it once. #[test] From dff0a0fd8b8fc8915384e9af1b45f3decc53e130 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:44:52 -0500 Subject: [PATCH 128/159] A successful atlas --compact notes last_compact, so auto compaction waits its interval after it Co-Authored-By: Claude Opus 5.5 --- src/main.rs | 10 ++++++++-- tests/compact_command.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) create mode 100644 tests/compact_command.rs diff --git a/src/main.rs b/src/main.rs index 11123051..79ed51de 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,6 @@ use std::process::ExitCode; -use atlas::{app, bg_indexer, compact, convert, paths, procs}; +use atlas::{app, bg_indexer, compact, convert, db, paths, procs, store}; fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); @@ -68,7 +68,13 @@ fn run_compact() -> i32 { // nothing sets it: only the indexer stops a compaction early let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); match compact::run(&paths::database(), &|msg| println!("{msg}"), &stop) { - Ok(_) => 0, + Ok(_) => { + // noted like the indexer's own compaction does, soo the auto one waits its interval + if let Ok(conn) = db::open_at(&paths::database()) { + let _ = store::set_meta(&conn, "last_compact", chrono::Utc::now().timestamp()); + } + 0 + } Err(e) => { println!("couldnt compact: {e:#}"); 1 diff --git a/tests/compact_command.rs b/tests/compact_command.rs new file mode 100644 index 00000000..247e6cf9 --- /dev/null +++ b/tests/compact_command.rs @@ -0,0 +1,27 @@ +//! `atlas --compact` notes the time like the indexer's own compaction does, +//! soo auto compaction doesnt run again right after it. + +use std::process::Command; + +#[test] +fn a_successful_compact_command_records_when_it_ran() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + let last = || { + let conn = atlas::db::open_at(&main).unwrap(); + atlas::store::get_meta(&conn, "last_compact").unwrap() + }; + assert_eq!(last(), None); + + let before = chrono::Utc::now().timestamp(); + let out = Command::new(env!("CARGO_BIN_EXE_atlas")) + .arg("--compact") + .env("ATLAS_HOME", home.path()) + .env("ATLAS_NO_KEYRING", "1") + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stdout)); + let at = last().expect("last_compact is set"); + assert!(at >= before && at <= chrono::Utc::now().timestamp(), "{at}"); +} From 1c48c57a72360e4f482e39aa4e5dda4729c83c12 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:56:39 -0500 Subject: [PATCH 129/159] A spilled blob segment and its loose duplicate are one row in compaction, with the dropped copy taken out of the totals When a dropped domain made both whole and too long for a blob, the segment spilled into rows beside its identical loose row and both hit the segments key. The rows of a file are now deduplicated by message-id as a whole, not just against the blob. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 58 insertions(+), 5 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index e62e1374..3de886d9 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -507,19 +507,20 @@ fn compact_shard( } file_rows.extend(spilled); - // a row the blob already has (the same message-id) isnt copied: - // it goes before the blob is counted, the way `seal_rows` drops it - if !segs.is_empty() { + // a row the blob already has (the same message-id) isnt copied, nor + // is a second row of one (a spilled segment and its loose copy): + // they go before the blob is counted, the way `seal_rows` drops them + if !file_rows.is_empty() { // (the same message-id, whichever way each is stored now) let mut key = |local: &[u8], domain: i64| -> Result { let suffix: Option = if domain == 0 { None } else { suffix_of.query_row([domain], |r| r.get(0)).optional()? }; Ok(store::dedup_key(local, domain, suffix.as_deref())) }; - let held: HashSet = segs.iter().map(|s| key(&s.local, s.domain)).collect::>()?; + let mut held: HashSet = segs.iter().map(|s| key(&s.local, s.domain)).collect::>()?; let (mut dropped, mut kept) = (Vec::new(), Vec::new()); for r in file_rows { - if held.contains(&key(&r.local, r.domain)?) { dropped.push(r) } else { kept.push(r) } + if held.insert(key(&r.local, r.domain)?) { kept.push(r) } else { dropped.push(r) } } file_rows = kept; if !dropped.is_empty() { @@ -1274,6 +1275,58 @@ mod tests { assert_eq!(rows, 1, "the long one is a row"); } + /// A sealed segment and its loose duplicate, the only users of a domain: + /// dropping it makes both too long for a blob, and the two are one article + /// stored once, not a clash on the segments key. + #[test] + fn a_dropped_domains_long_blob_segment_and_its_loose_copy_are_one_row() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}, &no_stop()).unwrap(); + let (path, file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + { + let conn = db::open_at(&path).unwrap(); + let suffix = format!("@{}>", "d".repeat(240)); + conn.execute("insert into domains (suffix) values (?)", [&suffix]).unwrap(); + let d: i64 = conn.query_row("select id from domains where suffix = ?", [&suffix], |r| r.get(0)).unwrap(); + let blob: Vec = conn.query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + let mut segs = crate::blob::decode(&blob).unwrap(); + let mut local = vec![0u8]; + local.extend(std::iter::repeat_n(b'a', 300)); + segs.push(Seg { part: Some(99), bytes: 5, domain: d, local: local.clone() }); + conn.execute("update files set blob = ? where id = ?", params![crate::blob::encode(&segs), file]).unwrap(); + // the same message-id again, loose, counted as the save that kept it counted it + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", + params![file, local, d, 99, 5], + ) + .unwrap(); + conn.execute( + "update releases set size = size + 10, parts = parts + 2 + where id = (select release_id from files where id = ?)", + [file], + ) + .unwrap(); + store::add_totals(&conn, 0, 2).unwrap(); + } + let before = all_articles(&main); + let count = article_total(&main); + let totals = release_totals(&path, file); + + run(&main, &|_| {}, &no_stop()).unwrap(); + let count_in = |all: &[(i64, Vec)]| all.iter().map(|(_, a)| a.len()).sum::(); + assert_eq!(count_in(&all_articles(&main)), count_in(&before) - 1, "the NZBs lose only the copy"); + assert_eq!(article_total(&main), count - 1, "the copy went out of the shard's total"); + assert_eq!(release_totals(&path, file), (totals.0 - 5, totals.1 - 1, totals.2 - 1), "and the release's"); + let conn = db::open_at(&path).unwrap(); + let rows: i64 = + conn.query_row("select count(*) from segments where file_id = ?", [file], |r| r.get(0)).unwrap(); + assert_eq!(rows, 1, "one row"); + let blob: Vec = conn.query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + assert!(crate::blob::decode(&blob).unwrap().iter().all(|s| s.local.len() <= crate::blob::MAX_LOCAL)); + } + #[test] fn a_file_over_the_cap_is_copied_as_rows_and_its_nzb_is_the_same() { let dir = tempfile::tempdir().unwrap(); From 0a3b553993f7a001673b072fcd9f654ad79a17b9 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:15:17 -0500 Subject: [PATCH 130/159] A loose copy in the streamed tail of a big file is dropped like one in its buffered rows A file with more rows than a blob takes had its rows past the buffered prefix inserted without the message-id dedup: a spilled blob segment's loose copy there was ignored by the segments key yet counted as copied, failing the check on every retry. The tail is now deduplicated against the same set, its copies taken out of the release's and the shard's totals, and only rows that went in are counted. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 106 ++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 88 insertions(+), 18 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 3de886d9..e80ecc41 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -468,8 +468,8 @@ fn compact_shard( let id: Option = file.map(|f| f.get(0)).transpose()?; // rows whose file isnt there (purged, or past the last file) stay rows while let Some(row) = pending.take_if(|r| id.is_none_or(|id| r.file_id < id)) { - insert_row(&tx, &row)?; - (copied, in_tx) = (copied + 1, in_tx + 1); + copied += insert_row(&tx, &row)?; + in_tx += 1; if (copied as usize).is_multiple_of(STOP_EVERY) { halt(stop, shard)?; } @@ -509,15 +509,12 @@ fn compact_shard( // a row the blob already has (the same message-id) isnt copied, nor // is a second row of one (a spilled segment and its loose copy): - // they go before the blob is counted, the way `seal_rows` drops them + // they go before the blob is counted, the way `seal_rows` drops them. + // `held` stays for the streamed tail below (there is none without rows here) + let mut held: HashSet = HashSet::new(); if !file_rows.is_empty() { - // (the same message-id, whichever way each is stored now) - let mut key = |local: &[u8], domain: i64| -> Result { - let suffix: Option = - if domain == 0 { None } else { suffix_of.query_row([domain], |r| r.get(0)).optional()? }; - Ok(store::dedup_key(local, domain, suffix.as_deref())) - }; - let mut held: HashSet = segs.iter().map(|s| key(&s.local, s.domain)).collect::>()?; + let mut key = |local: &[u8], domain: i64| dedup_key(&mut suffix_of, local, domain); + held = segs.iter().map(|s| key(&s.local, s.domain)).collect::>()?; let (mut dropped, mut kept) = (Vec::new(), Vec::new()); for r in file_rows { if held.insert(key(&r.local, r.domain)?) { kept.push(r) } else { dropped.push(r) } @@ -557,15 +554,21 @@ fn compact_shard( values.push(blob.map_or(Value::Null, Value::Blob)); tx.prepare_cached(&format!("insert into files ({FILE_COLUMNS}) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))? .execute(params_from_iter(values))?; + copied += segs.len() as i64; for row in &file_rows { - insert_row(&tx, row)?; + copied += insert_row(&tx, row)?; } - copied += (segs.len() + file_rows.len()) as i64; in_tx += 1 + segs.len() + file_rows.len(); - // the rest of a file too big to buffer, a row at a time + // the rest of a file too big to buffer, a row at a time, a copy of + // a row before it dropped the same way + let (mut tail_bytes, mut tail_copies) = (0i64, 0i64); while let Some(row) = pending.take_if(|r| r.file_id == id) { - insert_row(&tx, &row)?; - (copied, in_tx) = (copied + 1, in_tx + 1); + if held.insert(dedup_key(&mut suffix_of, &row.local, row.domain)?) { + copied += insert_row(&tx, &row)?; + } else { + (tail_bytes, tail_copies) = (tail_bytes + row.bytes.unwrap_or(0), tail_copies + 1); + } + in_tx += 1; if (copied as usize).is_multiple_of(STOP_EVERY) { halt(stop, shard)?; } @@ -576,6 +579,10 @@ fn compact_shard( } pending = next_row(shard, &mut rows, &shared)?; } + if tail_copies > 0 { + store::uncount_copies(&tx, f.get(1)?, tail_bytes, tail_copies)?; + copies += tail_copies; + } if in_tx >= BATCH { tx.commit()?; tx = conn.transaction()?; @@ -689,10 +696,19 @@ fn next_row(shard: usize, rows: &mut rusqlite::Rows, shared: &dyn Fn(i64) -> boo Ok(Some(Row { file_id, local, domain, part: r.get(3)?, bytes: r.get(4)? })) } -fn insert_row(conn: &Connection, r: &Row) -> Result<()> { - conn.prepare_cached("insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)")? +/// the message-id a copied (local, domain) stands for, whichever way it is stored now +fn dedup_key(suffix_of: &mut rusqlite::Statement, local: &[u8], domain: i64) -> Result { + let suffix: Option = + if domain == 0 { None } else { suffix_of.query_row([domain], |r| r.get(0)).optional()? }; + Ok(store::dedup_key(local, domain, suffix.as_deref())) +} + +/// 1 when the row went in, 0 when the copy already had it +fn insert_row(conn: &Connection, r: &Row) -> Result { + let n = conn + .prepare_cached("insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)")? .execute(params![r.file_id, r.local, r.domain, r.part, r.bytes])?; - Ok(()) + Ok(n as i64) } /// The copy holds the same releases, files and articles (rows and inside @@ -1327,6 +1343,60 @@ mod tests { assert!(crate::blob::decode(&blob).unwrap().iter().all(|s| s.local.len() <= crate::blob::MAX_LOCAL)); } + /// The same, in a file with more rows than a blob takes: the loose copy + /// comes in the streamed tail, past the rows held to seal, and is still + /// one row with the copy out of the totals, not a failed check every retry. + #[test] + fn a_long_blob_segments_loose_copy_past_the_buffered_rows_is_one_row() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}, &no_stop()).unwrap(); + let (path, file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + { + let conn = db::open_at(&path).unwrap(); + let suffix = format!("@{}>", "d".repeat(240)); + conn.execute("insert into domains (suffix) values (?)", [&suffix]).unwrap(); + let d: i64 = conn.query_row("select id from domains where suffix = ?", [&suffix], |r| r.get(0)).unwrap(); + let blob: Vec = conn.query_row("select blob from files where id = ?", [file], |r| r.get(0)).unwrap(); + let mut segs = crate::blob::decode(&blob).unwrap(); + let mut local = vec![0u8]; + local.extend(std::iter::repeat_n(b'a', 300)); + segs.push(Seg { part: Some(99), bytes: 5, domain: d, local: local.clone() }); + conn.execute("update files set blob = ? where id = ?", params![crate::blob::encode(&segs), file]).unwrap(); + // rows past what a blob takes, sorting before the copy so it comes after them + conn.execute( + "with recursive n(i) as (select 1 union all select i + 1 from n where i < ?2) + insert into segments (file_id, local, domain, part, bytes) + select ?1, cast(x'00' || cast('A' || i as blob) as blob), 0, 100 + i, 1 from n", + params![file, store::SEAL_MAX_SEGMENTS + 1], + ) + .unwrap(); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)", + params![file, local, d, 99, 5], + ) + .unwrap(); + conn.execute( + "update releases set size = size + 10 + ?2, parts = parts + 2 + ?2 + where id = (select release_id from files where id = ?1)", + params![file, store::SEAL_MAX_SEGMENTS + 1], + ) + .unwrap(); + store::add_totals(&conn, 0, 2 + store::SEAL_MAX_SEGMENTS + 1).unwrap(); + } + let count = article_total(&main); + let totals = release_totals(&path, file); + + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(article_total(&main), count - 1, "the copy went out of the shard's total"); + assert_eq!(release_totals(&path, file), (totals.0 - 5, totals.1 - 1, totals.2 - 1), "and the release's"); + let conn = db::open_at(&path).unwrap(); + let rows: i64 = + conn.query_row("select count(*) from segments where file_id = ?", [file], |r| r.get(0)).unwrap(); + assert_eq!(rows, store::SEAL_MAX_SEGMENTS + 2, "the padding and one long row"); + } + #[test] fn a_file_over_the_cap_is_copied_as_rows_and_its_nzb_is_the_same() { let dir = tempfile::tempdir().unwrap(); From acf80ce0bda5505b3efe83756f5a17715bb8302e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:15:51 -0500 Subject: [PATCH 131/159] A chunk claim taken over leaves the speculative window and older days to the new owner After CLAIM_TIMEOUT another worker can take a chunk still being processed; `chunks::finish` then changes nothing, yet the old worker went on to count the day's yield, reach further, or drop older days on what it saw. `finish_chunk` now does those only when this claim is what made the chunk done. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 93 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 75 insertions(+), 18 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index 4c0808a7..e9e44d45 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -993,6 +993,32 @@ async fn reach_further(db: &Db, group: &str, (day, floor, oldest): (i64, i64, Op } } +/// `chunk` is done with `dated` articles dated in its day. Only when this +/// claim is what made it done does what the day showed count: a claim taken +/// over (gone stale while it ran) leaves the speculative window and the older +/// days to the worker that has it now. `alone`, `floor` and `oldest` are as +/// `index_chunk` found them. +async fn finish_chunk( + db: &Db, + chunk: &crate::chunks::Claim, + (alone, floor, oldest): (bool, Option, Option), + dated: i64, +) -> Result<()> { + let (group, day) = (chunk.group.as_str(), chunk.day); + let c = chunk.clone(); + let now = chrono::Utc::now().timestamp(); + if !on_db(db, move |conn| Ok(crate::chunks::finish(conn, &c, now)?)).await? { + println!("[CHUNK] {group} day {day}: taken over by another worker, leaving it to that one"); + return Ok(()); + } + if alone && dated == 0 { + drop_older_days(db, group, day).await; + } else if let Some(floor) = floor { + reach_further(db, group, (day, floor, oldest), dated).await; + } + Ok(()) +} + async fn index_chunk

( ctx: &PassContext, settings: &PassSettings, @@ -1009,14 +1035,6 @@ where let c = chunk.clone(); on_db(db, move |conn| Ok(crate::chunks::release(conn, &c)?)) }; - let finish = async || { - let c = chunk.clone(); - let now = chrono::Utc::now().timestamp(); - if !on_db(db, move |conn| Ok(crate::chunks::finish(conn, &c, now)?)).await? { - println!("[CHUNK] {group} day {day}: taken over by another worker, leaving it to that one"); - } - anyhow::Ok(()) - }; // give the chunk back after `e`, and return `e`: failing to give it back // is only logged (the claim goes stale and gets taken over) let failed = async |e: anyhow::Error| { @@ -1170,10 +1188,7 @@ where None => None, }; if start > end { - finish().await?; - if alone { - drop_older_days(db, group, day).await; - } + finish_chunk(db, chunk, (alone, floor, oldest), 0).await?; return Ok(Progress::default()); } @@ -1181,12 +1196,7 @@ where let window = alone.then_some((day * 86_400, (day + 1) * 86_400)); match pass.process_range_dated(start as i64, end as i64, "CHUNK", window, progress).await { Ok((saved, true, dated_in_day)) => { - finish().await?; - if alone && dated_in_day == 0 { - drop_older_days(db, group, day).await; - } else if let Some(floor) = floor { - reach_further(db, group, (day, floor, oldest), dated_in_day).await; - } + finish_chunk(db, chunk, (alone, floor, oldest), dated_in_day).await?; Ok(saved) } Ok((saved, false, _)) => { @@ -1719,6 +1729,53 @@ mod tests { assert_eq!(s.reach, 2 * SPECULATIVE_WINDOW); } + #[test] + fn a_chunk_taken_over_leaves_the_older_days_and_the_window_alone() { + let rt = tokio::runtime::Builder::new_current_thread().build().unwrap(); + rt.block_on(a_chunk_taken_over()); + } + + async fn a_chunk_taken_over() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let db = shared_db(db::open_at(&main).unwrap()); + let (r, g) = (20_000, "g"); + let floor = r - SPECULATIVE_WINDOW; + let start = crate::chunks::Speculative { runner_up_day: r, reach: SPECULATIVE_WINDOW, days: 0, articles: 0 }; + let claim = on_db(&db, move |c| { + crate::chunks::add(c, g, floor, floor - 5)?; + crate::chunks::set_speculative(c, g, &start)?; + Ok(crate::chunks::claim(c, &[(g.to_string(), i64::MIN)], "a", 0)?.unwrap()) + }) + .await + .unwrap(); + assert_eq!(claim.day, floor); + let days = || { + on_db(&db, move |c| Ok(c.query_row("select count(*) from backfill_chunks", [], |r| r.get::<_, i64>(0))?)) + }; + let window = || on_db(&db, move |c| Ok(crate::chunks::speculative(c, g)?.unwrap())); + + // its claim went stale and another worker has it now + on_db(&db, move |c| Ok(c.execute("update backfill_chunks set claimed_at = 99 where day = ?", [floor])?)) + .await + .unwrap(); + // no dated article in the day: the older days stay + finish_chunk(&db, &claim, (true, None, Some(0)), 0).await.unwrap(); + assert_eq!(days().await.unwrap(), 6); + // a dense day: the window doesnt count it, nor reach further + finish_chunk(&db, &claim, (true, Some(floor), Some(0)), 100_000).await.unwrap(); + let s = window().await.unwrap(); + assert_eq!((s.reach, s.days, s.articles), (SPECULATIVE_WINDOW, 0, 0)); + assert_eq!(days().await.unwrap(), 6); + + // the claim that has it does both + let mut now = claim.clone(); + now.claimed_at = 99; + finish_chunk(&db, &now, (true, None, Some(0)), 0).await.unwrap(); + assert_eq!(days().await.unwrap(), 1, "the older days went to the sweeps"); + } + #[test] fn cursors_saved_under_a_servers_old_key_are_adopted_once() { let dir = tempfile::tempdir().unwrap(); From fcff8ca4b7913435fe2726c3826e418d6a93e5e4 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:16:04 -0500 Subject: [PATCH 132/159] --convert finishes a swap cut short instead of saying there is nothing to convert With atlas.db renamed aside mid swap, `convert::needed` is false and `--convert` stopped before `run_alone`, which finishes or undoes the swap. It now asks `convert::to_do`: a conversion needed, or atlas.db missing next to atlas.new.db or atlas.old.db. Co-Authored-By: Claude Opus 5.5 --- src/convert.rs | 8 ++++++++ src/main.rs | 3 ++- tests/convert.rs | 21 +++++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/convert.rs b/src/convert.rs index 90e0ac75..456cc734 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -46,6 +46,14 @@ pub fn needed(main: &Path) -> bool { main.exists() && db::open_at(main).and_then(|c| db::has_old_layout(&c)).unwrap_or(false) } +/// Whether `--convert` has anything to do: a conversion `needed`, or a swap +/// cut short (atlas.db missing next to atlas.new.db or atlas.old.db) for +/// `run_alone` to finish or undo first. +pub fn to_do(main: &Path) -> bool { + needed(main) + || (!main.exists() && (sibling(main, "atlas.new.db").exists() || sibling(main, "atlas.old.db").exists())) +} + fn sibling(main: &Path, name: &str) -> PathBuf { main.with_file_name(name) } diff --git a/src/main.rs b/src/main.rs index 79ed51de..eb4b8ccc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -37,7 +37,8 @@ fn main() -> ExitCode { /// `--convert`: the one time move into the shards, in the foreground. fn run_convert() -> i32 { let main = paths::database(); - if !convert::needed(&main) { + // a swap cut short is finished (or undone) by `run_alone`, not skipped + if !convert::to_do(&main) { println!("{} is already converted (or doesnt exist)", main.display()); return 0; } diff --git a/tests/convert.rs b/tests/convert.rs index 384bb348..7dd3cd45 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -473,6 +473,27 @@ fn a_swap_cut_after_the_old_database_moved_aside_is_finished_at_start() { assert_eq!(store::totals(&conn).unwrap().0, before.len() as i64); } +/// `--convert` after a swap cut short: atlas.db is missing, soo it isnt +/// `needed`, yet there is work: the swap is finished, not "nothing to convert". +#[test] +fn a_convert_after_a_cut_swap_finishes_the_swap() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + let before = old_nzbs(&main); + db::create_db_at(&main).unwrap(); + convert::run(&main, &|_| {}).unwrap(); + std::fs::rename(&main, dir.path().join("atlas.new.db")).unwrap(); + + assert!(!convert::needed(&main)); + assert!(convert::to_do(&main), "the cut swap is something to do"); + assert_eq!(convert::run_alone(&main, &|_| {}).unwrap(), None); + assert!(!dir.path().join("atlas.new.db").exists()); + assert!(!convert::to_do(&main), "and done"); + let conn = db::open_with_shards(&main).unwrap(); + assert_eq!(store::totals(&conn).unwrap().0, before.len() as i64); +} + /// Moved aside with a new main database that never got to the swap: the /// next start puts the old database back, and converting goes on from it. #[test] From 850e60e0def2dabd9f8d7dbc9af570ff528f6d64 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:28:59 -0500 Subject: [PATCH 133/159] A fallback copy of a sealed article doesnt leave its file's parts or totals changed Past its decode budget a save keeps a repost of a sealed article as a row, not knowing it is one, and folded its total, file total and subject into the file. Such a row now counts only its part, and sealing, when it drops copies, works the file's parts out again from the blob and the rows left and the release's completeness with them. Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 86 insertions(+), 2 deletions(-) diff --git a/src/store.rs b/src/store.rs index ac73ce00..313b1945 100644 --- a/src/store.rs +++ b/src/store.rs @@ -749,6 +749,19 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { let release_id: i64 = conn.prepare_cached("select release_id from files where id = ?")?.query_row([file_id], |r| r.get(0))?; uncount_copies(conn, release_id, copies.iter().map(|c| c.bytes).sum(), copies.len() as i64)?; + // a copy's part was counted in the file's parts when it was saved: they + // are what the blob and the rows left have, and so is the release's + // completeness + let mut seen = Vec::new(); + for p in segs.iter().chain(&rows).filter_map(|s| s.part) { + insert_part(&mut seen, p); + } + conn.prepare_cached("update files set seen = ? where id = ?")?.execute(params![seen, file_id])?; + let file_total: Option = conn + .prepare_cached("select file_total from releases where id = ?")? + .query_row([release_id], |r| r.get(0))?; + conn.prepare_cached("update releases set complete = ? where id = ?")? + .execute(params![release_complete(conn, release_id, file_total)? as i64, release_id])?; } // too much for one blob in memory: the rest stays rows, the blob as it is if segs.len() + rows.len() > SEAL_MAX_SEGMENTS as usize { @@ -855,9 +868,12 @@ pub(crate) struct SealedCache { /// segments decoded so far decoded: usize, max_decoded: usize, + /// the last `contains` was past the budget: its false only means not known + pub(crate) guessed: bool, } impl SealedCache { + #[cfg(test)] pub(crate) fn new() -> Self { Self::with_limits(SEALED_CACHE_MAX_SEGMENTS, SEALED_DECODE_BUDGET) } @@ -871,12 +887,14 @@ impl SealedCache { max_segments, decoded: 0, max_decoded, + guessed: false, } } /// the article (local, domain) is already in file `file_id`'s blob pub(crate) fn contains(&mut self, conn: &Connection, file_id: i64, local: &[u8], domain: i64) -> Result { self.uses += 1; + self.guessed = false; let key = (local.to_vec(), domain); if let Some((used, set)) = self.files.get_mut(&file_id) { self.by_use.remove(used); @@ -885,6 +903,7 @@ impl SealedCache { return Ok(set.contains(&key)); } if self.decoded >= self.max_decoded { + self.guessed = true; return Ok(false); } let set: SegmentSet = @@ -921,6 +940,8 @@ pub struct ShardWriter { seal_after: i64, /// when the last walk ran (unix seconds) walked_at: Option, + /// segments of sealed files a save decodes at most (see `SealedCache`) + decode_budget: usize, } /// files sealed per writer tick at most @@ -944,6 +965,7 @@ impl ShardWriter { completed_ids: HashSet::new(), seal_after: 0, walked_at: None, + decode_budget: SEALED_DECODE_BUDGET, } } @@ -1049,7 +1071,7 @@ impl ShardWriter { let shard = self.shard; let domains = &mut self.domains; // blobs of sealed files that get late articles, decoded once each - let mut sealed = SealedCache::new(); + let mut sealed = SealedCache::with_limits(SEALED_CACHE_MAX_SEGMENTS, self.decode_budget); // files this save completed, for sealing once it's committed let mut completed = Vec::new(); let tx = conn.transaction()?; @@ -1113,7 +1135,16 @@ impl ShardWriter { let before = added.len(); for a in articles { if add_segment(&tx, domains, &f, a, &mut sealed)? { - f.add(a); + if f.sealed && sealed.guessed { + // maybe a copy of what the blob has: only its part + // counts, till sealing the file again tells (`seal_rows` + // works the parts out again from what is left) + if let Some(p) = a.part { + insert_part(&mut f.seen, p); + } + } else { + f.add(a); + } added.push(a); } } @@ -2197,6 +2228,59 @@ mod tests { assert_eq!(writer.seal_some(&mut conn, now + 2).unwrap(), 0); } + /// A save past its decode budget keeps a repost of a sealed article as a + /// row, not knowing it's one: a part or total it carries that the + /// original didnt must not make its file falsely complete or incomplete, + /// neither while it's a row nor once sealing drops it. + #[test] + fn a_fallback_copy_with_another_part_or_total_leaves_completeness_as_it_was() { + let (_dir, main) = sealed_fixture(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + for id in conn.prepare("select id from files").unwrap().query_map([], |r| r.get(0)).unwrap() { + seal_file(&conn, id.unwrap()).unwrap(); + } + let file = |conn: &Connection, name: &str| -> (Option, Vec) { + conn.query_row("select expected, seen from files where filename = ?", [name], |r| { + Ok((r.get(0)?, r.get(1)?)) + }) + .unwrap() + }; + let complete = + |conn: &Connection| -> bool { conn.query_row("select complete from releases", [], |r| r.get(0)).unwrap() }; + let (a, b) = (file(&conn, "a.rar"), file(&conn, "b.rar")); + assert!(!complete(&conn), "b.rar has 1 of 2"); + + // reposts of a1 claiming 4 parts, and of b1 claiming to be part 2 + let copy = |id: &str, name: &str, part: i64, total: i64| Article { + message_id: id.into(), + subject: format!("\"{name}\" yEnc ({part}/{total})"), + filename: Some(name.into()), + part: Some(part), + total_parts: Some(total), + bytes: 100 + part, + ..Default::default() + }; + let mut writer = ShardWriter::new(shard); + writer.decode_budget = 0; + let release = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![copy("", "a.rar", 1, 4), copy("", "b.rar", 2, 2)], + ..Default::default() + }; + writer.save(&mut conn, &Ids::new(&main), [std::slice::from_ref(&release)]).unwrap(); + let rows: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(rows, 2, "both kept as rows, past the budget"); + assert_eq!(file(&conn, "a.rar").0, a.0, "a.rar still takes 3 parts"); + + for id in conn.prepare("select id from files").unwrap().query_map([], |r| r.get(0)).unwrap() { + seal_file(&conn, id.unwrap()).unwrap(); + } + assert_eq!((file(&conn, "a.rar"), file(&conn, "b.rar")), (a, b), "the copies went, and what they said"); + assert!(!complete(&conn), "b.rar still has 1 of 2"); + } + /// what purging takes off the totals is what it deleted, counted in its /// own transaction: the rest of the totals, including what writers added /// in between, stays as it is From 2a7e0f7930bc8030b626e1bb81f4e029b14af3d7 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:50:34 -0500 Subject: [PATCH 134/159] atlas --compact refuses shards whose main database is missing instead of making an empty one Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 9 ++++++++ src/main.rs | 3 ++- tests/compact_command.rs | 45 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/compact.rs b/src/compact.rs index e80ecc41..c363be6d 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -272,6 +272,15 @@ fn interruptible(conn: &Connection, stop: &Arc) -> Result<()> { /// `stop` is set, shards not done are left as they were (and an error says so). pub fn run(main: &Path, progress: &(dyn Fn(&str) + Sync), stop: &Arc) -> Result { let _lock = Lock::take(main)?; + // a conversion's swap cut short is finished (or undone) like at a start; + // shards with no main database at all are refused: the main database + // the next start made would hand out their ids again + if let Some(said) = crate::convert::recover_cut_swap(main)? { + progress(&said); + } + if !main.try_exists()? && store::exists(main) { + bail!("{} is missing but its shards are there; put it back from a backup first", main.display()); + } for line in recover_cut_swaps(main)? { progress(&line); } diff --git a/src/main.rs b/src/main.rs index eb4b8ccc..e3fb064d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -71,7 +71,8 @@ fn run_compact() -> i32 { match compact::run(&paths::database(), &|msg| println!("{msg}"), &stop) { Ok(_) => { // noted like the indexer's own compaction does, soo the auto one waits its interval - if let Ok(conn) = db::open_at(&paths::database()) { + // never made here: an empty main database would pass for the real one + if let Ok(conn) = db::open_shard(&paths::database()) { let _ = store::set_meta(&conn, "last_compact", chrono::Utc::now().timestamp()); } 0 diff --git a/tests/compact_command.rs b/tests/compact_command.rs index 247e6cf9..647af21c 100644 --- a/tests/compact_command.rs +++ b/tests/compact_command.rs @@ -25,3 +25,48 @@ fn a_successful_compact_command_records_when_it_ran() { let at = last().expect("last_compact is set"); assert!(at >= before && at <= chrono::Utc::now().timestamp(), "{at}"); } + +#[test] +fn a_compact_command_refuses_shards_whose_main_database_is_missing() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + for suffix in ["", "-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", main.display())); + } + + let out = Command::new(env!("CARGO_BIN_EXE_atlas")) + .arg("--compact") + .env("ATLAS_HOME", home.path()) + .env("ATLAS_NO_KEYRING", "1") + .output() + .unwrap(); + assert!(!out.status.success(), "{}", String::from_utf8_lossy(&out.stdout)); + assert!(String::from_utf8_lossy(&out.stdout).contains("missing"), "{}", String::from_utf8_lossy(&out.stdout)); + // not made empty: the next start would hand out the shards' ids again + assert!(!main.exists()); + assert!(atlas::db::create_db_at(&main).is_err(), "the next start still refuses"); +} + +#[test] +fn a_compact_command_finishes_a_conversion_swap_cut_short_first() { + let home = tempfile::tempdir().unwrap(); + let main = home.path().join("atlas.db"); + atlas::db::create_db_at(&main).unwrap(); + // cut short after moving the main database aside: it's put back + std::fs::rename(&main, home.path().join("atlas.old.db")).unwrap(); + for suffix in ["-wal", "-shm"] { + let _ = std::fs::remove_file(format!("{}{suffix}", main.display())); + } + + let out = Command::new(env!("CARGO_BIN_EXE_atlas")) + .arg("--compact") + .env("ATLAS_HOME", home.path()) + .env("ATLAS_NO_KEYRING", "1") + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stdout)); + assert!(main.exists()); + let conn = atlas::db::open_at(&main).unwrap(); + assert!(atlas::store::get_meta(&conn, "last_compact").unwrap().is_some()); +} From f5414bc43cfd7437badb2d2bdd3c342ee07f7532 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 05:56:44 -0500 Subject: [PATCH 135/159] A new article past the decode budget has its totals and subject held back till sealing, not lost Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 97 ++++++++++++++++++++++++++++++++++ src/store.rs | 140 ++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 230 insertions(+), 7 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index c363be6d..a528dc9a 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -460,6 +460,8 @@ fn compact_shard( let open = || Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY); let (files_read, rows_read) = (open()?, open()?); let mut suffix_of = files_read.prepare("select suffix from domains where id = ?")?; + let mut held_of = files_read + .prepare("select message_id, subject, part, total_parts, file_total from held_back where file_id = ?")?; let mut files_stmt = files_read.prepare(&format!("select {FILE_COLUMNS} from files order by id"))?; let mut files = files_stmt.query([])?; let mut rows_stmt = rows_read.prepare( @@ -514,6 +516,22 @@ fn compact_shard( segs.push(Seg { local, domain, ..seg }); } } + // what rows a save couldnt tell from copies said (see `store::seal_rows`): + // kept for the rows that are new, dropped for copies of the blob's + let mut held_back: Vec<(String, Value, Value, Value, Value)> = held_of + .query_map([id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)))? + .collect::>()?; + if !held_back.is_empty() { + let mut key = |local: &[u8], domain: i64| dedup_key(&mut suffix_of, local, domain); + let mut in_blob = HashSet::new(); + for s in &segs { + in_blob.insert(key(&s.local, s.domain)?); + } + for r in &spilled { + in_blob.insert(key(&r.local, r.domain)?); + } + held_back.retain(|h| !in_blob.contains(&h.0)); + } file_rows.extend(spilled); // a row the blob already has (the same message-id) isnt copied, nor @@ -544,7 +562,9 @@ fn compact_shard( let seen: Vec = f.get(8)?; // and files with more segments than a blob takes stay rows let small = (segs.len() + file_rows.len()) as i64 <= store::SEAL_MAX_SEGMENTS; + // nor files with something held back: sealing them folds it in let seal = !file_rows.is_empty() + && held_back.is_empty() && fits && small && store::due(f.get(6)?, &seen, f.get(9)?, old_blob.is_some(), now); @@ -563,6 +583,13 @@ fn compact_shard( values.push(blob.map_or(Value::Null, Value::Blob)); tx.prepare_cached(&format!("insert into files ({FILE_COLUMNS}) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))? .execute(params_from_iter(values))?; + for h in held_back { + tx.prepare_cached( + "insert into held_back (file_id, message_id, subject, part, total_parts, file_total) + values (?, ?, ?, ?, ?, ?)", + )? + .execute(params![id, h.0, h.1, h.2, h.3, h.4])?; + } copied += segs.len() as i64; for row in &file_rows { copied += insert_row(&tx, row)?; @@ -1080,6 +1107,76 @@ mod tests { } /// the file of release `name` in its group's shard: (shard path, file id) + /// a shard with release Rel: a.rar sealed whole (1/1) and b.rar sealed + /// with 1 of 2, and a row added to b.rar the way a save past its decode + /// budget leaves one: (message-id, part, total) held back, its part + /// counted. The shard, b.rar's id and its release's id. + fn held_back_fixture(main: &Path, (id, part, total): (&str, i64, i64)) -> (PathBuf, i64, i64) { + db::create_db_at(main).unwrap(); + let art = |file: &str, part: i64, total: i64, id: &str| Article { + message_id: id.into(), + subject: format!("\"{file}\" yEnc ({part}/{total})"), + filename: Some(file.into()), + part: Some(part), + total_parts: Some(total), + bytes: 100, + ..Default::default() + }; + let release = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![art("a.rar", 1, 1, ""), art("b.rar", 1, 2, "")], + ..Default::default() + }; + store::save(main, &[release]).unwrap(); + let path = store::shard_path(main, store::shard_of("alt.binaries.t")); + let conn = db::open_at(&path).unwrap(); + let file: i64 = conn.query_row("select id from files where filename = 'b.rar'", [], |r| r.get(0)).unwrap(); + for f in conn.prepare("select id from files").unwrap().query_map([], |r| r.get::<_, i64>(0)).unwrap() { + store::seal_file(&conn, f.unwrap()).unwrap(); + } + let release: i64 = conn.query_row("select release_id from files where id = ?", [file], |r| r.get(0)).unwrap(); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, 0, ?, 100)", + params![file, store::whole(id), part], + ) + .unwrap(); + conn.execute( + "insert into held_back (file_id, message_id, subject, part, total_parts) values (?, ?, ?, ?, ?)", + params![file, id, format!("\"b.rar\" yEnc ({part}/{total})"), part, total], + ) + .unwrap(); + let mut seen = Vec::new(); + for p in [1, part] { + store::insert_part(&mut seen, p); + } + conn.execute("update files set seen = ? where id = ?", params![seen, file]).unwrap(); + let complete = part == 2; + conn.execute( + "update releases set complete = ?, size = size + 100, parts = parts + 1 where id = ?", + params![complete, release], + ) + .unwrap(); + store::add_totals(&conn, 0, 1).unwrap(); + (path, file, release) + } + + /// A new row's held back total survives compaction (which leaves its + /// file a row), and sealing the file afterwards folds it in. + #[test] + fn compacting_keeps_what_a_new_row_held_back() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + let (path, file, _) = held_back_fixture(&main, ("", 3, 3)); + run(&main, &|_| {}, &no_stop()).unwrap(); + let conn = db::open_at(&path).unwrap(); + let held: i64 = conn.query_row("select count(*) from held_back", [], |r| r.get(0)).unwrap(); + assert_eq!(held, 1); + store::seal_file(&conn, file).unwrap(); + let expected: i64 = conn.query_row("select expected from files where id = ?", [file], |r| r.get(0)).unwrap(); + assert_eq!(expected, 3); + } + fn file_of(main: &Path, name: &str, group: &str) -> (PathBuf, i64) { let path = store::shard_path(main, store::shard_of(group)); let id = db::open_at(&path) diff --git a/src/store.rs b/src/store.rs index 313b1945..83ae178f 100644 --- a/src/store.rs +++ b/src/store.rs @@ -184,6 +184,18 @@ pub fn build_shard(conn: &Connection) -> Result<()> { primary key (file_id, local, domain) ) without rowid; + -- what a row a save couldnt tell from a copy of its sealed file's + -- article said about the file, folded in when sealing tells (`seal_rows`) + create table if not exists held_back ( + file_id INTEGER NOT NULL, + message_id TEXT NOT NULL, + subject TEXT, + part INTEGER, + total_parts INTEGER, + file_total INTEGER, + primary key (file_id, message_id) + ) without rowid; + -- running totals for the stats pages: releases, articles create table if not exists meta (key TEXT PRIMARY KEY, value INTEGER); insert or ignore into meta (key, value) values ('releases', 0), ('articles', 0); @@ -623,6 +635,13 @@ pub(crate) fn add_segment( let added = conn .prepare_cached("insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)")? .execute(params![f.id, local, domain, a.part, a.bytes])?; + if added > 0 && f.sealed && sealed.guessed { + conn.prepare_cached( + "insert or replace into held_back (file_id, message_id, subject, part, total_parts, file_total) + values (?, ?, ?, ?, ?, ?)", + )? + .execute(params![f.id, a.message_id, a.subject, a.part, a.total_parts, a.file_total])?; + } Ok(added > 0) } @@ -741,6 +760,31 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { if held.contains(&key(&r)?) { copies.push(r) } else { fresh.push(r) } } let rows = fresh; + // what the rows a save couldnt tell from copies said: the copies' goes, + // the rest's is folded into the file now it's known to be new + let mut held: HashMap = conn + .prepare_cached("select message_id, subject, part, total_parts, file_total from held_back where file_id = ?")? + .query_map([file_id], |r| { + Ok(Article { + message_id: r.get(0)?, + subject: r.get::<_, Option>(1)?.unwrap_or_default(), + part: r.get(2)?, + total_parts: r.get(3)?, + file_total: r.get(4)?, + ..Default::default() + }) + })? + .map(|a| a.map(|a| (a.message_id.clone(), a))) + .collect::>()?; + let mut news = Vec::new(); + if !held.is_empty() { + conn.prepare_cached("delete from held_back where file_id = ?")?.execute([file_id])?; + for r in &rows { + if let Some(a) = held.remove(&key(r)?) { + news.push(a); + } + } + } for copy in &copies { conn.prepare_cached("delete from segments where file_id = ? and local = ? and domain = ?")? .execute(params![file_id, copy.local, copy.domain])?; @@ -757,6 +801,27 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { insert_part(&mut seen, p); } conn.prepare_cached("update files set seen = ? where id = ?")?.execute(params![seen, file_id])?; + } + if !news.is_empty() { + let (release_id, filename): (i64, String) = conn + .prepare_cached("select release_id, filename from files where id = ?")? + .query_row([file_id], |r| Ok((r.get(0)?, r.get(1)?)))?; + let mut f = file(conn, release_id, &filename)?; + for a in &news { + f.add(a); + } + conn.prepare_cached( + "update files set subject = ?, subject_part = ?, subject_mid = ?, expected = ?, file_total = ? where id = ?", + )? + .execute(params![f.subject, f.subject_part, f.subject_mid, f.expected, f.file_total, file_id])?; + if let Some(ft) = news.iter().filter_map(|a| a.file_total).max() { + conn.prepare_cached("update releases set file_total = max(coalesce(file_total, ?), ?) where id = ?")? + .execute(params![ft, ft, release_id])?; + } + } + if !copies.is_empty() || !news.is_empty() { + let release_id: i64 = + conn.prepare_cached("select release_id from files where id = ?")?.query_row([file_id], |r| r.get(0))?; let file_total: Option = conn .prepare_cached("select file_total from releases where id = ?")? .query_row([release_id], |r| r.get(0))?; @@ -1129,23 +1194,26 @@ impl ShardWriter { } } - let mut added: Vec<&Article> = Vec::new(); + // and whether each might be a copy of a sealed article (see `SealedCache`) + let mut added: Vec<(&Article, bool)> = Vec::new(); for (name, articles) in by_file { let mut f = file(&tx, release_id, name)?; let before = added.len(); for a in articles { if add_segment(&tx, domains, &f, a, &mut sealed)? { - if f.sealed && sealed.guessed { + let unsure = f.sealed && sealed.guessed; + if unsure { // maybe a copy of what the blob has: only its part - // counts, till sealing the file again tells (`seal_rows` - // works the parts out again from what is left) + // counts, the rest is held back till sealing the file + // again tells (`seal_rows` works the parts out again + // from what is left, and folds in what new rows said) if let Some(p) = a.part { insert_part(&mut f.seen, p); } } else { f.add(a); } - added.push(a); + added.push((a, unsure)); } } if added.len() > before { @@ -1163,11 +1231,16 @@ impl ShardWriter { new_articles += added.len() as i64; let t = Instant::now(); - let file_total = added.iter().filter_map(|a| a.file_total).chain(old_file_total).max(); + let file_total = added + .iter() + .filter(|(_, unsure)| !unsure) + .filter_map(|(a, _)| a.file_total) + .chain(old_file_total) + .max(); let old_parts = old_parts.unwrap_or(0); let earlier_size = if old_parts > 0 { old_size.unwrap_or(0) } else { 0 }; update_stats.execute(params![ - earlier_size + added.iter().map(|a| a.bytes).sum::(), + earlier_size + added.iter().map(|(a, _)| a.bytes).sum::(), release_complete(&tx, release_id, file_total)? as i64, old_parts + added.len() as i64, file_total, @@ -1344,6 +1417,7 @@ pub fn purge_incomplete(main: &Path) -> Result<()> { } tx.execute_batch(&format!( "delete from segments where file_id in ({doomed}); + delete from held_back where file_id in ({doomed}); delete from files where release_id in (select id from releases where complete = 0); delete from releases where complete = 0;" ))?; @@ -2279,6 +2353,58 @@ mod tests { } assert_eq!((file(&conn, "a.rar"), file(&conn, "b.rar")), (a, b), "the copies went, and what they said"); assert!(!complete(&conn), "b.rar still has 1 of 2"); + let held: i64 = conn.query_row("select count(*) from held_back", [], |r| r.get(0)).unwrap(); + assert_eq!(held, 0, "what the copies said is gone with them"); + } + + /// A genuinely new article a save past its decode budget keeps as a row + /// has its total, file total and subject held back, not lost: sealing + /// the file again, once it knows the row isnt a copy, folds them in. + #[test] + fn a_new_article_past_the_decode_budget_gets_its_totals_at_sealing() { + let (_dir, main) = sealed_fixture(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + for id in conn.prepare("select id from files").unwrap().query_map([], |r| r.get(0)).unwrap() { + seal_file(&conn, id.unwrap()).unwrap(); + } + let expected = |conn: &Connection, name: &str| -> Option { + conn.query_row("select expected from files where filename = ?", [name], |r| r.get(0)).unwrap() + }; + let release = |conn: &Connection| -> (bool, Option) { + conn.query_row("select complete, file_total from releases", [], |r| Ok((r.get(0)?, r.get(1)?))).unwrap() + }; + + // a.rar turns out to have a 4th part, and b.rar gets its 2nd (of 2 files) + let new = |id: &str, name: &str, part: i64, total: i64| Article { + message_id: id.into(), + subject: format!("\"{name}\" yEnc ({part}/{total})"), + filename: Some(name.into()), + part: Some(part), + total_parts: Some(total), + file_total: Some(2), + bytes: 100 + part, + ..Default::default() + }; + let mut writer = ShardWriter::new(shard); + writer.decode_budget = 0; + let rel = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![new("", "a.rar", 4, 4), new("", "b.rar", 2, 2)], + ..Default::default() + }; + writer.save(&mut conn, &Ids::new(&main), [std::slice::from_ref(&rel)]).unwrap(); + assert_eq!(expected(&conn, "a.rar"), Some(3), "held back while it could be a copy"); + assert_eq!(release(&conn).1, None); + + for id in conn.prepare("select id from files").unwrap().query_map([], |r| r.get(0)).unwrap() { + seal_file(&conn, id.unwrap()).unwrap(); + } + assert_eq!(expected(&conn, "a.rar"), Some(4), "not a copy: its total counts"); + assert_eq!(release(&conn), (true, Some(2)), "every file has its parts, and the file total"); + let held: i64 = conn.query_row("select count(*) from held_back", [], |r| r.get(0)).unwrap(); + assert_eq!(held, 0); } /// what purging takes off the totals is what it deleted, counted in its From ae69130c0a96fed0cb33754cba32f6d97bf9bdfa Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:01:09 -0500 Subject: [PATCH 136/159] Compaction dropping fallback copies works their file's parts and release's completeness out again Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 36 ++++++++++++++++++++++++++++++++++++ src/store.rs | 24 ++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/src/compact.rs b/src/compact.rs index a528dc9a..c999a49e 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -456,6 +456,8 @@ fn compact_shard( let now = chrono::Utc::now().timestamp(); // rows dropped as copies of what their file's blob already has let (mut copied, mut sealed, mut copies) = (0i64, 0i64, 0i64); + // files that lost copies: their parts are worked out again once copied + let mut recount = Vec::new(); { let open = || Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY); let (files_read, rows_read) = (open()?, open()?); @@ -552,6 +554,7 @@ fn compact_shard( let bytes = dropped.iter().map(|r| r.bytes.unwrap_or(0)).sum(); store::uncount_copies(&tx, f.get(1)?, bytes, dropped.len() as i64)?; copies += dropped.len() as i64; + recount.push(id); } } @@ -618,6 +621,7 @@ fn compact_shard( if tail_copies > 0 { store::uncount_copies(&tx, f.get(1)?, tail_bytes, tail_copies)?; copies += tail_copies; + recount.push(id); } if in_tx >= BATCH { tx.commit()?; @@ -625,6 +629,12 @@ fn compact_shard( in_tx = 0; } } + // the parts the dropped copies were counted in are what is left, and + // so is their release's completeness (once all its files are in) + recount.dedup(); + for id in recount { + store::recount_parts(&tx, id)?; + } tx.commit()?; } say(&format!("sealed {sealed} files")); @@ -1177,6 +1187,32 @@ mod tests { assert_eq!(expected, 3); } + /// Compaction drops a row that copies b.rar's part 1 but claimed part 2: + /// the file's parts and its release's completeness go back to what the + /// blob has (1 of 2), and what the copy held back goes with it. + #[test] + fn compacting_a_copy_away_takes_its_part_out_of_completeness() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + let (path, file, release) = held_back_fixture(&main, ("", 2, 2)); + let complete = |path: &Path| -> bool { + db::open_at(path) + .unwrap() + .query_row("select complete from releases where id = ?", [release], |r| r.get(0)) + .unwrap() + }; + assert!(complete(&path), "the copy's part 2 made it look complete"); + run(&main, &|_| {}, &no_stop()).unwrap(); + assert!(!complete(&path), "b.rar has 1 of 2"); + let conn = db::open_at(&path).unwrap(); + let seen: Vec = conn.query_row("select seen from files where id = ?", [file], |r| r.get(0)).unwrap(); + let mut one = Vec::new(); + store::insert_part(&mut one, 1); + assert_eq!(seen, one); + let held: i64 = conn.query_row("select count(*) from held_back", [], |r| r.get(0)).unwrap(); + assert_eq!(held, 0); + } + fn file_of(main: &Path, name: &str, group: &str) -> (PathBuf, i64) { let path = store::shard_path(main, store::shard_of(group)); let id = db::open_at(&path) diff --git a/src/store.rs b/src/store.rs index 83ae178f..c00863c0 100644 --- a/src/store.rs +++ b/src/store.rs @@ -839,6 +839,30 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { Ok(segs.len()) } +/// File `file_id`'s parts worked out again from its blob and rows, and its +/// release's completeness with them: after dropping copies whose parts were +/// counted (see `SealedCache`). +pub(crate) fn recount_parts(conn: &Connection, file_id: i64) -> Result<()> { + let mut seen = Vec::new(); + for p in sealed_segments(conn, file_id)?.unwrap_or_default().iter().filter_map(|s| s.part) { + insert_part(&mut seen, p); + } + let parts: Vec> = conn + .prepare_cached("select part from segments where file_id = ?")? + .query_map([file_id], |r| r.get(0))? + .collect::>()?; + for p in parts.into_iter().flatten() { + insert_part(&mut seen, p); + } + conn.prepare_cached("update files set seen = ? where id = ?")?.execute(params![seen, file_id])?; + let (release_id, file_total): (i64, Option) = conn + .prepare_cached("select r.id, r.file_total from files f join releases r on r.id = f.release_id where f.id = ?")? + .query_row([file_id], |r| Ok((r.get(0)?, r.get(1)?)))?; + conn.prepare_cached("update releases set complete = ? where id = ?")? + .execute(params![release_complete(conn, release_id, file_total)? as i64, release_id])?; + Ok(()) +} + /// The next `limit` files after `after_id`, and which of them a writer /// seals: ones with rows that are complete and not sealed yet, or untouched /// for `SEAL_AGE` (a sealed file with late rows waits for this). Files never From e47daf8efe7441d922f2cc4054f17417f7c8b044 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:15:06 -0500 Subject: [PATCH 137/159] Compacting a shard from before sealing gives it the held_back table first Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 27 ++++++++++++++++++++++++++- src/store.rs | 27 +++++++++++++++------------ 2 files changed, 41 insertions(+), 13 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index c999a49e..c9d983a0 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -369,7 +369,7 @@ fn compact_shard( { let conn = db::open_at(&path)?; checkpoint(&conn).context("folding the original's WAL in")?; - // a shard from before sealing gets its (empty) seal columns + // a shard from before sealing gets its (empty) seal columns and tables store::migrate_shard(&conn)?; } let before = size(&path); @@ -1096,6 +1096,31 @@ mod tests { assert_eq!(all_articles(&main), before, "an article already there isnt saved twice"); } + #[test] + fn compacting_shards_from_before_sealing_adds_what_they_lack_and_keeps_every_nzb() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let before = all_articles(&main); + let count = article_total(&main); + // back to the shard schema before sealing: no held_back, no seal columns + for path in store::shard_paths(&main) { + db::open_at(&path) + .unwrap() + .execute_batch( + "drop table held_back; + alter table files drop column blob; + alter table files drop column touched_at;", + ) + .unwrap(); + } + + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(all_articles(&main), before, "every NZB reads back the same"); + assert_eq!(article_total(&main), count); + assert_eq!(loose(&main), 0, "every file was due, so all are sealed"); + } + #[test] fn a_huge_sparse_domain_id_costs_no_memory_to_count() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/store.rs b/src/store.rs index c00863c0..82e6cc7f 100644 --- a/src/store.rs +++ b/src/store.rs @@ -184,6 +184,21 @@ pub fn build_shard(conn: &Connection) -> Result<()> { primary key (file_id, local, domain) ) without rowid; + -- running totals for the stats pages: releases, articles + create table if not exists meta (key TEXT PRIMARY KEY, value INTEGER); + insert or ignore into meta (key, value) values ('releases', 0), ('articles', 0); + ", + )?; + migrate_shard(conn) +} + +/// What a shard made before sealing lacks: `files.touched_at` (when +/// articles were last added) and `files.blob` (a sealed file's articles), in +/// the same order `create_shard` has them, and the `held_back` table. Adding +/// a nullable column doesnt rewrite the table. +pub fn migrate_shard(conn: &Connection) -> Result<()> { + conn.execute_batch( + " -- what a row a save couldnt tell from a copy of its sealed file's -- article said about the file, folded in when sealing tells (`seal_rows`) create table if not exists held_back ( @@ -195,20 +210,8 @@ pub fn build_shard(conn: &Connection) -> Result<()> { file_total INTEGER, primary key (file_id, message_id) ) without rowid; - - -- running totals for the stats pages: releases, articles - create table if not exists meta (key TEXT PRIMARY KEY, value INTEGER); - insert or ignore into meta (key, value) values ('releases', 0), ('articles', 0); ", )?; - migrate_shard(conn) -} - -/// Columns a shard made before sealing lacks: `files.touched_at` (when -/// articles were last added) and `files.blob` (a sealed file's articles), in -/// the same order `create_shard` has them. Adding a nullable column doesnt -/// rewrite the table. -pub fn migrate_shard(conn: &Connection) -> Result<()> { let cols: Vec = conn.prepare("pragma table_info(files)")?.query_map([], |r| r.get(1))?.collect::>()?; for (col, kind) in [("touched_at", "INTEGER"), ("blob", "BLOB")] { From d9c60dff89df8cb7b65c9b8981caaa5a2c96ee82 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:23:21 -0500 Subject: [PATCH 138/159] Compaction dedups a huge file's streamed tail against the copy, not a set of every id Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 91 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 89 insertions(+), 2 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index c9d983a0..74980a8a 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -601,9 +601,14 @@ fn compact_shard( // the rest of a file too big to buffer, a row at a time, a copy of // a row before it dropped the same way let (mut tail_bytes, mut tail_copies) = (0i64, 0i64); + #[cfg(test)] + let held_before_tail = held.len(); + // `held` (the blob and the buffered rows, bounded) isnt added to: + // a tail copy of a tail row is found in the copy database instead while let Some(row) = pending.take_if(|r| r.file_id == id) { - if held.insert(dedup_key(&mut suffix_of, &row.local, row.domain)?) { - copied += insert_row(&tx, &row)?; + let key = dedup_key(&mut suffix_of, &row.local, row.domain)?; + if !held.contains(&key) && !has_other_form(&tx, &row, &key)? && insert_row(&tx, &row)? == 1 { + copied += 1; } else { (tail_bytes, tail_copies) = (tail_bytes + row.bytes.unwrap_or(0), tail_copies + 1); } @@ -618,6 +623,8 @@ fn compact_shard( } pending = next_row(shard, &mut rows, &shared)?; } + #[cfg(test)] + TAIL_HELD_GROWTH.fetch_max(held.len() - held_before_tail, Ordering::Relaxed); if tail_copies > 0 { store::uncount_copies(&tx, f.get(1)?, tail_bytes, tail_copies)?; copies += tail_copies; @@ -749,6 +756,32 @@ fn dedup_key(suffix_of: &mut rusqlite::Statement, local: &[u8], domain: i64) -> Ok(store::dedup_key(local, domain, suffix.as_deref())) } +/// The copy already has `r`'s file's article `key` stored the other way: whole +/// when `r` is packed under a domain, or packed under its domain (one the copy +/// kept) when `r` is whole. The same way is the segments key's to catch. +fn has_other_form(conn: &Connection, r: &Row, key: &str) -> Result { + let other = if r.domain != 0 { + Some((store::whole(key), 0)) + } else if let Some((local, suffix)) = store::split_message_id(key) { + conn.prepare_cached("select id from domains where suffix = ?")? + .query_row([suffix], |x| x.get::<_, i64>(0)) + .optional()? + .map(|d| (store::pack_local(local), d)) + } else { + None + }; + let Some((local, domain)) = other else { return Ok(false) }; + Ok(conn + .prepare_cached("select 1 from segments where file_id = ? and local = ? and domain = ?")? + .query_row(params![r.file_id, local, domain], |_| Ok(())) + .optional()? + .is_some()) +} + +/// the most ids `compact_shard` added to `held` while streaming a file's tail +#[cfg(test)] +static TAIL_HELD_GROWTH: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + /// 1 when the row went in, 0 when the copy already had it fn insert_row(conn: &Connection, r: &Row) -> Result { let n = conn @@ -1564,6 +1597,60 @@ mod tests { assert_eq!(rows, store::SEAL_MAX_SEGMENTS + 2, "the padding and one long row"); } + /// A file a poster padded with millions of rows: the streamed tail is + /// deduplicated against the copy itself, not a set of every id it has, + /// and an article stored both whole and packed in the tail is one row. + #[test] + fn a_huge_files_tail_is_deduplicated_without_holding_its_ids() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}, &no_stop()).unwrap(); + let (path, file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + let tail = store::SEAL_MAX_SEGMENTS + 100; + { + let conn = db::open_at(&path).unwrap(); + let d: i64 = conn.query_row("select id from domains where suffix = '@ngPost>'", [], |r| r.get(0)).unwrap(); + // whole ids sorting before the two copies below, well past what a blob takes + conn.execute( + "with recursive n(i) as (select 1 union all select i + 1 from n where i < ?2) + insert into segments (file_id, local, domain, part, bytes) + select ?1, cast(x'00' || cast('!' || i as blob) as blob), 0, 100 + i, 1 from n", + params![file, tail], + ) + .unwrap(); + // one article twice: whole, and packed under its shared domain + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, 0, 99, 5)", + params![file, store::whole("")], + ) + .unwrap(); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, 99, 5)", + params![file, store::pack_local("zzz9"), d], + ) + .unwrap(); + conn.execute( + "update releases set size = size + 10 + ?2, parts = parts + 2 + ?2 + where id = (select release_id from files where id = ?1)", + params![file, tail], + ) + .unwrap(); + store::add_totals(&conn, 0, 2 + tail).unwrap(); + } + let count = article_total(&main); + let totals = release_totals(&path, file); + + run(&main, &|_| {}, &no_stop()).unwrap(); + assert_eq!(TAIL_HELD_GROWTH.load(Ordering::Relaxed), 0, "no id of the tail was held"); + assert_eq!(article_total(&main), count - 1, "the copy went out of the shard's total"); + assert_eq!(release_totals(&path, file), (totals.0 - 5, totals.1 - 1, totals.2 - 1), "and the release's"); + let conn = db::open_at(&path).unwrap(); + let rows: i64 = + conn.query_row("select count(*) from segments where file_id = ?", [file], |r| r.get(0)).unwrap(); + assert_eq!(rows, tail + 1, "the padding and the article once"); + } + #[test] fn a_file_over_the_cap_is_copied_as_rows_and_its_nzb_is_the_same() { let dir = tempfile::tempdir().unwrap(); From e560f61c32b1f60230823e5549e21bb375aa8c45 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:29:12 -0500 Subject: [PATCH 139/159] A file too big to seal still gets what it held back settled by the seal walk Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 272 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 209 insertions(+), 63 deletions(-) diff --git a/src/store.rs b/src/store.rs index 82e6cc7f..f64466a6 100644 --- a/src/store.rs +++ b/src/store.rs @@ -720,6 +720,7 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { .prepare_cached("select count(*) from (select 1 from segments where file_id = ? limit ?)")? .query_row(params![file_id, SEAL_MAX_SEGMENTS + 1], |r| r.get(0))?; if counted > SEAL_MAX_SEGMENTS { + settle_held_back(conn, file_id, &segs)?; return Ok(0); } let rows: Vec = conn @@ -739,6 +740,7 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { // the blob has no room for a negative part number: such a file stays rows // nor one whose message-id is longer than a blob decodes if rows.iter().any(|r| r.part.is_some_and(|p| p < 0) || r.local.len() > crate::blob::MAX_LOCAL) { + settle_held_back(conn, file_id, &segs)?; return Ok(0); } // a row the blob already has (saved past a save's decode budget, see @@ -747,16 +749,7 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { // (the same message-id, even stored whole in the blob and packed in the // row, or the other way round, when a domain got shared in between) let mut suffixes: HashMap> = HashMap::new(); - let mut key = |s: &crate::blob::Seg| -> Result { - if s.domain != 0 && !suffixes.contains_key(&s.domain) { - let suffix = conn - .prepare_cached("select suffix from domains where id = ?")? - .query_row([s.domain], |r| r.get(0)) - .optional()?; - suffixes.insert(s.domain, suffix); - } - Ok(dedup_key(&s.local, s.domain, suffixes.get(&s.domain).and_then(|x| x.as_deref()))) - }; + let mut key = |s: &crate::blob::Seg| seg_key(conn, &mut suffixes, s); let held: HashSet = segs.iter().map(&mut key).collect::>()?; let (mut copies, mut fresh) = (Vec::new(), Vec::new()); for r in rows { @@ -765,20 +758,8 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { let rows = fresh; // what the rows a save couldnt tell from copies said: the copies' goes, // the rest's is folded into the file now it's known to be new - let mut held: HashMap = conn - .prepare_cached("select message_id, subject, part, total_parts, file_total from held_back where file_id = ?")? - .query_map([file_id], |r| { - Ok(Article { - message_id: r.get(0)?, - subject: r.get::<_, Option>(1)?.unwrap_or_default(), - part: r.get(2)?, - total_parts: r.get(3)?, - file_total: r.get(4)?, - ..Default::default() - }) - })? - .map(|a| a.map(|a| (a.message_id.clone(), a))) - .collect::>()?; + let mut held: HashMap = + held_back(conn, file_id, -1)?.into_iter().map(|a| (a.message_id.clone(), a)).collect(); let mut news = Vec::new(); if !held.is_empty() { conn.prepare_cached("delete from held_back where file_id = ?")?.execute([file_id])?; @@ -805,31 +786,9 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { } conn.prepare_cached("update files set seen = ? where id = ?")?.execute(params![seen, file_id])?; } - if !news.is_empty() { - let (release_id, filename): (i64, String) = conn - .prepare_cached("select release_id, filename from files where id = ?")? - .query_row([file_id], |r| Ok((r.get(0)?, r.get(1)?)))?; - let mut f = file(conn, release_id, &filename)?; - for a in &news { - f.add(a); - } - conn.prepare_cached( - "update files set subject = ?, subject_part = ?, subject_mid = ?, expected = ?, file_total = ? where id = ?", - )? - .execute(params![f.subject, f.subject_part, f.subject_mid, f.expected, f.file_total, file_id])?; - if let Some(ft) = news.iter().filter_map(|a| a.file_total).max() { - conn.prepare_cached("update releases set file_total = max(coalesce(file_total, ?), ?) where id = ?")? - .execute(params![ft, ft, release_id])?; - } - } + fold_in(conn, file_id, &news)?; if !copies.is_empty() || !news.is_empty() { - let release_id: i64 = - conn.prepare_cached("select release_id from files where id = ?")?.query_row([file_id], |r| r.get(0))?; - let file_total: Option = conn - .prepare_cached("select file_total from releases where id = ?")? - .query_row([release_id], |r| r.get(0))?; - conn.prepare_cached("update releases set complete = ? where id = ?")? - .execute(params![release_complete(conn, release_id, file_total)? as i64, release_id])?; + update_complete(conn, file_id)?; } // too much for one blob in memory: the rest stays rows, the blob as it is if segs.len() + rows.len() > SEAL_MAX_SEGMENTS as usize { @@ -842,6 +801,135 @@ fn seal_rows(conn: &Connection, file_id: i64) -> Result { Ok(segs.len()) } +/// the message-id a stored segment stands for (`dedup_key`), its domain's +/// suffix looked up once per domain +fn seg_key(conn: &Connection, suffixes: &mut HashMap>, s: &crate::blob::Seg) -> Result { + if s.domain != 0 && !suffixes.contains_key(&s.domain) { + let suffix = conn + .prepare_cached("select suffix from domains where id = ?")? + .query_row([s.domain], |r| r.get(0)) + .optional()?; + suffixes.insert(s.domain, suffix); + } + Ok(dedup_key(&s.local, s.domain, suffixes.get(&s.domain).and_then(|x| x.as_deref()))) +} + +/// what file `file_id`'s rows held back, `limit` at most (-1: all) +fn held_back(conn: &Connection, file_id: i64, limit: i64) -> Result> { + conn.prepare_cached( + "select message_id, subject, part, total_parts, file_total from held_back where file_id = ? limit ?", + )? + .query_map(params![file_id, limit], |r| { + Ok(Article { + message_id: r.get(0)?, + subject: r.get::<_, Option>(1)?.unwrap_or_default(), + part: r.get(2)?, + total_parts: r.get(3)?, + file_total: r.get(4)?, + ..Default::default() + }) + })? + .collect() +} + +/// What new articles held back said about file `file_id`, folded in +fn fold_in(conn: &Connection, file_id: i64, news: &[Article]) -> Result<()> { + if news.is_empty() { + return Ok(()); + } + let (release_id, filename): (i64, String) = conn + .prepare_cached("select release_id, filename from files where id = ?")? + .query_row([file_id], |r| Ok((r.get(0)?, r.get(1)?)))?; + let mut f = file(conn, release_id, &filename)?; + for a in news { + f.add(a); + } + conn.prepare_cached( + "update files set subject = ?, subject_part = ?, subject_mid = ?, expected = ?, file_total = ? where id = ?", + )? + .execute(params![f.subject, f.subject_part, f.subject_mid, f.expected, f.file_total, file_id])?; + if let Some(ft) = news.iter().filter_map(|a| a.file_total).max() { + conn.prepare_cached("update releases set file_total = max(coalesce(file_total, ?), ?) where id = ?")? + .execute(params![ft, ft, release_id])?; + } + Ok(()) +} + +/// file `file_id`'s release's completeness worked out again +fn update_complete(conn: &Connection, file_id: i64) -> Result<()> { + let (release_id, file_total): (i64, Option) = conn + .prepare_cached("select r.id, r.file_total from files f join releases r on r.id = f.release_id where f.id = ?")? + .query_row([file_id], |r| Ok((r.get(0)?, r.get(1)?)))?; + conn.prepare_cached("update releases set complete = ? where id = ?")? + .execute(params![release_complete(conn, release_id, file_total)? as i64, release_id])?; + Ok(()) +} + +/// The ways message-id `id` can be stored as a row: whole, packed under its +/// domain (if it has a row), and packed as text the way before locals were +/// packed by alphabet. +fn stored_forms(conn: &Connection, id: &str) -> Result, i64)>> { + let mut forms = vec![(whole(id), 0)]; + if let Some((local, suffix)) = split_message_id(id) + && let Some(d) = conn + .prepare_cached("select id from domains where suffix = ?")? + .query_row([suffix], |r| r.get::<_, i64>(0)) + .optional()? + { + forms.push((pack_local(local), d)); + let mut text = vec![TEXT]; + text.extend_from_slice(local.as_bytes()); + forms.push((text, d)); + } + Ok(forms) +} + +/// What a file that wont seal (too many rows, or rows a blob cant hold) held +/// back, settled without sealing it: the rows that are copies of an article +/// in its blob `segs` go, out of the totals with what they said, and the new +/// ones' totals and subject are folded in. `SEAL_MAX_SEGMENTS` entries a +/// time at most, the rest on the next walk. +fn settle_held_back(conn: &Connection, file_id: i64, segs: &[crate::blob::Seg]) -> Result<()> { + let entries = held_back(conn, file_id, SEAL_MAX_SEGMENTS)?; + if entries.is_empty() { + return Ok(()); + } + let mut suffixes = HashMap::new(); + let in_blob: HashSet = segs.iter().map(|s| seg_key(conn, &mut suffixes, s)).collect::>()?; + let (mut bytes, mut copies, mut news) = (0i64, 0i64, Vec::new()); + for a in entries { + conn.prepare_cached("delete from held_back where file_id = ? and message_id = ?")? + .execute(params![file_id, a.message_id])?; + if !in_blob.contains(&a.message_id) { + news.push(a); + continue; + } + for (local, domain) in stored_forms(conn, &a.message_id)? { + let gone: Option> = conn + .prepare_cached("delete from segments where file_id = ? and local = ? and domain = ? returning bytes")? + .query_row(params![file_id, local, domain], |r| r.get(0)) + .optional()?; + if let Some(b) = gone { + (bytes, copies) = (bytes + b.unwrap_or(0), copies + 1); + } + } + } + if copies > 0 { + let release_id: i64 = + conn.prepare_cached("select release_id from files where id = ?")?.query_row([file_id], |r| r.get(0))?; + uncount_copies(conn, release_id, bytes, copies)?; + } + fold_in(conn, file_id, &news)?; + if copies > 0 { + // the parts are what the blob and the rows left have + recount_parts(conn, file_id) + } else if !news.is_empty() { + update_complete(conn, file_id) + } else { + Ok(()) + } +} + /// File `file_id`'s parts worked out again from its blob and rows, and its /// release's completeness with them: after dropping copies whose parts were /// counted (see `SealedCache`). @@ -850,27 +938,23 @@ pub(crate) fn recount_parts(conn: &Connection, file_id: i64) -> Result<()> { for p in sealed_segments(conn, file_id)?.unwrap_or_default().iter().filter_map(|s| s.part) { insert_part(&mut seen, p); } - let parts: Vec> = conn - .prepare_cached("select part from segments where file_id = ?")? - .query_map([file_id], |r| r.get(0))? - .collect::>()?; - for p in parts.into_iter().flatten() { - insert_part(&mut seen, p); + { + let mut stmt = conn.prepare_cached("select part from segments where file_id = ? and part is not null")?; + let mut parts = stmt.query([file_id])?; + while let Some(r) = parts.next()? { + insert_part(&mut seen, r.get(0)?); + } } conn.prepare_cached("update files set seen = ? where id = ?")?.execute(params![seen, file_id])?; - let (release_id, file_total): (i64, Option) = conn - .prepare_cached("select r.id, r.file_total from files f join releases r on r.id = f.release_id where f.id = ?")? - .query_row([file_id], |r| Ok((r.get(0)?, r.get(1)?)))?; - conn.prepare_cached("update releases set complete = ? where id = ?")? - .execute(params![release_complete(conn, release_id, file_total)? as i64, release_id])?; - Ok(()) + update_complete(conn, file_id) } /// The next `limit` files after `after_id`, and which of them a writer /// seals: ones with rows that are complete and not sealed yet, or untouched /// for `SEAL_AGE` (a sealed file with late rows waits for this). Files never /// touched since the upgrade are left to compaction, and files with a -/// negative part number, or more than `SEAL_MAX_SEGMENTS` rows, never seal. +/// negative part number, or more than `SEAL_MAX_SEGMENTS` rows, never seal +/// (they are taken only to settle what they held back, `settle_held_back`). /// Returns the ids and the last id looked /// at, for walking the table `limit` files at a time: `last == after_id` /// means the end. @@ -878,7 +962,8 @@ pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) let mut stmt = conn.prepare_cached(&format!( "select f.id, f.expected, f.seen, f.touched_at, f.blob is not null, exists (select 1 from segments s where s.file_id = f.id), - exists (select 1 from segments s where s.file_id = f.id and (s.part < 0 or length(s.local) > {})) or {} + exists (select 1 from segments s where s.file_id = f.id and (s.part < 0 or length(s.local) > {})) or {}, + exists (select 1 from held_back h where h.file_id = f.id) from files f where f.id > ? order by f.id limit ?", crate::blob::MAX_LOCAL, too_many_rows() @@ -889,7 +974,11 @@ pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) while let Some(r) = rows.next()? { let id: i64 = r.get(0)?; last = id; - let (has_rows, never): (bool, bool) = (r.get(5)?, r.get(6)?); + let (has_rows, never, held): (bool, bool, bool) = (r.get(5)?, r.get(6)?, r.get(7)?); + // one that never seals still gets what it held back settled + if has_rows && never && held { + ids.push(id); + } if !has_rows || never { continue; } @@ -2434,6 +2523,63 @@ mod tests { assert_eq!(held, 0); } + /// A file past the most a blob takes never seals, but what a save past + /// its decode budget held back for it is still settled: a copy of a + /// sealed article goes with what it said, a new one's totals count. + #[test] + fn what_a_file_too_big_to_seal_held_back_is_settled_anyway() { + let (_dir, main) = sealed_fixture(); + let shard = shard_of("alt.binaries.t"); + let mut conn = db::open_at(&shard_path(&main, shard)).unwrap(); + for id in conn.prepare("select id from files").unwrap().query_map([], |r| r.get(0)).unwrap() { + seal_file(&conn, id.unwrap()).unwrap(); + } + let a: i64 = conn.query_row("select id from files where filename = 'a.rar'", [], |r| r.get(0)).unwrap(); + let state = |conn: &Connection| -> (Option, Vec) { + conn.query_row("select expected, seen from files where id = ?", [a], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + }; + let before = state(&conn); + let article = |id: &str, part: i64, total: i64| Article { + message_id: id.into(), + subject: format!("\"a.rar\" yEnc ({part}/{total})"), + filename: Some("a.rar".into()), + part: Some(part), + total_parts: Some(total), + bytes: 100 + part, + ..Default::default() + }; + let mut writer = ShardWriter::new(shard); + writer.decode_budget = 0; + // a repost of a1 claiming 5 parts, and a genuinely new 4th of 4 + let rel = Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![article("", 1, 5), article("", 4, 4)], + ..Default::default() + }; + writer.save(&mut conn, &Ids::new(&main), [std::slice::from_ref(&rel)]).unwrap(); + let held = + |conn: &Connection| -> i64 { conn.query_row("select count(*) from held_back", [], |r| r.get(0)).unwrap() }; + assert_eq!(held(&conn), 2); + let rows = |conn: &Connection| -> i64 { + conn.query_row("select count(*) from segments where file_id = ?", [a], |r| r.get(0)).unwrap() + }; + add_rows(&conn, a, SEAL_MAX_SEGMENTS); + let articles: i64 = conn.query_row("select value from meta where key = 'articles'", [], |r| r.get(0)).unwrap(); + + let now: i64 = conn.query_row("select unixepoch()", [], |r| r.get(0)).unwrap(); + assert!(sealable(&conn, 0, 100, now).unwrap().0.contains(&a), "walked to for what it held back"); + assert_eq!(seal_file(&conn, a).unwrap(), 0, "still too big to seal"); + assert_eq!(held(&conn), 0, "settled"); + assert_eq!(rows(&conn), SEAL_MAX_SEGMENTS + 1, "the copy went, the new one and the padding stay"); + let after: i64 = conn.query_row("select value from meta where key = 'articles'", [], |r| r.get(0)).unwrap(); + assert_eq!(after, articles - 1, "the copy out of the shard's total"); + assert_eq!(state(&conn).0, Some(4), "the new one's total counts, not the copy's"); + assert_ne!(state(&conn).1, before.1); + assert!(!sealable(&conn, 0, 100, now).unwrap().0.contains(&a), "and it's skipped again"); + } + /// what purging takes off the totals is what it deleted, counted in its /// own transaction: the rest of the totals, including what writers added /// in between, stays as it is From c53984cbac4245ea6eeb688d1d874917c06a7735 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:35:05 -0500 Subject: [PATCH 140/159] A message-id already under another file of its release isnt saved again Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 103 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 96 insertions(+), 7 deletions(-) diff --git a/src/store.rs b/src/store.rs index f64466a6..70e2a7a7 100644 --- a/src/store.rs +++ b/src/store.rs @@ -605,11 +605,14 @@ pub(crate) fn put_file(conn: &Connection, f: &FileState) -> Result<()> { } /// Add one article to a file; false when it was already there, as a row or -/// in the file's sealed blob. +/// in the file's sealed blob, or in another file of its release (`others`, +/// the ids of those and whether each is sealed: one message-id saved under +/// two parsed file names is one article). pub(crate) fn add_segment( conn: &Connection, domains: &mut Domains, f: &FileState, + others: &[(i64, bool)], a: &Article, sealed: &mut SealedCache, ) -> Result { @@ -635,6 +638,13 @@ pub(crate) fn add_segment( return Ok(false); } } + // `guessed` stays about this file's blob, which the caller asks about + let guessed = sealed.guessed; + let elsewhere = !others.is_empty() && in_other_file(conn, others, &a.message_id, sealed)?; + sealed.guessed = guessed; + if elsewhere { + return Ok(false); + } let added = conn .prepare_cached("insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)")? .execute(params![f.id, local, domain, a.part, a.bytes])?; @@ -648,6 +658,23 @@ pub(crate) fn add_segment( Ok(added > 0) } +/// Message-id `id` is in one of `others` (file ids of a release, and whether +/// each is sealed): as a row stored any way, or in a sealed blob (past the +/// decode budget a blob not held is taken not to have it, see `SealedCache`). +fn in_other_file(conn: &Connection, others: &[(i64, bool)], id: &str, sealed: &mut SealedCache) -> Result { + for (local, domain) in stored_forms(conn, id)? { + for &(file_id, is_sealed) in others { + let row = conn + .prepare_cached("select 1 from segments where file_id = ? and local = ? and domain = ?")? + .exists(params![file_id, local, domain])?; + if row || (is_sealed && sealed.contains(conn, file_id, &local, domain)?) { + return Ok(true); + } + } + } + Ok(false) +} + /// a release is complete when every file has exactly its parts, and there are /// as many files as the post said fn release_complete(conn: &Connection, release_id: i64, file_total: Option) -> Result { @@ -1314,9 +1341,14 @@ impl ShardWriter { let mut added: Vec<(&Article, bool)> = Vec::new(); for (name, articles) in by_file { let mut f = file(&tx, release_id, name)?; + // the release's other files, checked for the same message-id + let others: Vec<(i64, bool)> = tx + .prepare_cached("select id, blob is not null from files where release_id = ? and id != ?")? + .query_map(params![release_id, f.id], |r| Ok((r.get(0)?, r.get(1)?)))? + .collect::>()?; let before = added.len(); for a in articles { - if add_segment(&tx, domains, &f, a, &mut sealed)? { + if add_segment(&tx, domains, &f, &others, a, &mut sealed)? { let unsure = f.sealed && sealed.guessed; if unsure { // maybe a copy of what the blob has: only its part @@ -1337,6 +1369,13 @@ impl ShardWriter { if !f.sealed && f.expected.is_some_and(|e| is_exactly(&f.seen, e)) { completed.push(f.id); } + } else { + // a file just made whose articles all were in other files + tx.prepare_cached( + "delete from files where id = ? and touched_at is null and blob is null + and not exists (select 1 from segments where file_id = ?)", + )? + .execute(params![f.id, f.id])?; } } profile::ARTICLES.add_since(t); @@ -1742,7 +1781,7 @@ mod tests { let article = Article { message_id: format!("<{:032x}@nyuu>", 7), part: Some(1), ..Default::default() }; let mut fresh = Domains::default(); assert!( - add_segment(&conn, &mut fresh, &file, &article, &mut SealedCache::new()).unwrap(), + add_segment(&conn, &mut fresh, &file, &[], &article, &mut SealedCache::new()).unwrap(), "first time: stored whole" ); for n in 0..SHARED_AFTER { @@ -1750,7 +1789,7 @@ mod tests { } assert!(conn.prepare("select 1 from domains where suffix = '@nyuu>'").unwrap().exists([]).unwrap()); assert!( - !add_segment(&conn, &mut fresh, &file, &article, &mut SealedCache::new()).unwrap(), + !add_segment(&conn, &mut fresh, &file, &[], &article, &mut SealedCache::new()).unwrap(), "same article again: not saved twice" ); let segments: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); @@ -1779,7 +1818,7 @@ mod tests { ) .unwrap(); assert!( - !add_segment(&conn, &mut Domains::default(), &file, &legacy, &mut SealedCache::new()).unwrap(), + !add_segment(&conn, &mut Domains::default(), &file, &[], &legacy, &mut SealedCache::new()).unwrap(), "legacy text row found" ); let segments: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); @@ -2127,9 +2166,12 @@ mod tests { assert!(f.sealed); let article = Article { message_id: "".into(), part: Some(1), ..Default::default() }; - assert!(!add_segment(&conn, &mut domains, &f, &article, &mut SealedCache::new()).unwrap()); + assert!(!add_segment(&conn, &mut domains, &f, &[], &article, &mut SealedCache::new()).unwrap()); let other = Article { message_id: "".into(), part: Some(2), ..Default::default() }; - assert!(add_segment(&conn, &mut domains, &f, &other, &mut SealedCache::new()).unwrap(), "a new one is a row"); + assert!( + add_segment(&conn, &mut domains, &f, &[], &other, &mut SealedCache::new()).unwrap(), + "a new one is a row" + ); let loose: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); assert_eq!(loose, 1); } @@ -2580,6 +2622,53 @@ mod tests { assert!(!sealable(&conn, 0, 100, now).unwrap().0.contains(&a), "and it's skipped again"); } + /// One message-id under another file name of its release (another + /// carrier's subject) is the same article: not saved again, neither + /// beside a row nor beside a sealed blob, and no empty file is left. + #[test] + fn an_article_under_another_file_of_its_release_isnt_saved_twice() { + let (_dir, main) = sealed_fixture(); + let shard = shard_path(&main, shard_of("alt.binaries.t")); + let state = || { + let conn = db::open_with_shards(&main).unwrap(); + let id: i64 = conn.query_row("select id from releases", [], |r| r.get(0)).unwrap(); + let totals: (i64, i64, bool) = conn + .query_row("select size, parts, complete from releases", [], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))) + .unwrap(); + let shard = db::open_at(&shard).unwrap(); + let files: i64 = shard.query_row("select count(*) from files", [], |r| r.get(0)).unwrap(); + let total: i64 = + shard.query_row("select value from meta where key = 'articles'", [], |r| r.get(0)).unwrap(); + (articles(&conn, id).unwrap(), totals, files, total) + }; + let again = |id: &str| Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: vec![Article { + message_id: id.into(), + subject: "\"c.rar\" yEnc (1/3)".into(), + filename: Some("c.rar".into()), + part: Some(1), + total_parts: Some(3), + bytes: 101, + ..Default::default() + }], + ..Default::default() + }; + let before = state(); + // a row of a.rar, and one stored packed under its domain + save(&main, &[again(""), again("<0abc12def34@ngPost>")]).unwrap(); + assert_eq!(state(), before, "beside a row"); + + let conn = db::open_at(&shard).unwrap(); + for id in conn.prepare("select id from files").unwrap().query_map([], |r| r.get(0)).unwrap() { + seal_file(&conn, id.unwrap()).unwrap(); + } + let before = state(); + save(&main, &[again(""), again("")]).unwrap(); + assert_eq!(state(), before, "beside a blob"); + } + /// what purging takes off the totals is what it deleted, counted in its /// own transaction: the rest of the totals, including what writers added /// in between, stays as it is From ebc381fc76aa3e3512ce60a6daedd2d9aebd20b2 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:52:18 -0500 Subject: [PATCH 141/159] A release with more files checks a new article against them all with one index lookup release_ids keeps a keyed hash of every message-id of a release with more than one file (sealed or not), filled the first time it gets a second file or is saved to after an upgrade, copied by compaction and cleared by purge: no per-file scan, no blob decode, no guessing past the decode budget. Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 245 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 210 insertions(+), 35 deletions(-) diff --git a/src/store.rs b/src/store.rs index 70e2a7a7..93a5de1f 100644 --- a/src/store.rs +++ b/src/store.rs @@ -210,8 +210,25 @@ pub fn migrate_shard(conn: &Connection) -> Result<()> { file_total INTEGER, primary key (file_id, message_id) ) without rowid; + + -- every message-id of a release with more than one file, by its keyed + -- hash (`id_hash`), and the file it is in: one lookup tells whether + -- another file of the release has it. A release is in it once its + -- (release_id, 0, 0) row is (`index_release`). + create table if not exists release_ids ( + release_id INTEGER NOT NULL, + id_hash INTEGER NOT NULL, + file_id INTEGER NOT NULL, + primary key (release_id, id_hash) + ) without rowid; ", )?; + // the hash key, secret soo posts cant be made to collide + for key in ["id_key0", "id_key1"] { + let mut bytes = [0u8; 8]; + getrandom::fill(&mut bytes).map_err(|e| rusqlite::Error::ToSqlConversionFailure(e.to_string().into()))?; + conn.execute("insert or ignore into meta (key, value) values (?, ?)", params![key, i64::from_le_bytes(bytes)])?; + } let cols: Vec = conn.prepare("pragma table_info(files)")?.query_map([], |r| r.get(1))?.collect::>()?; for (col, kind) in [("touched_at", "INTEGER"), ("blob", "BLOB")] { @@ -605,17 +622,30 @@ pub(crate) fn put_file(conn: &Connection, f: &FileState) -> Result<()> { } /// Add one article to a file; false when it was already there, as a row or -/// in the file's sealed blob, or in another file of its release (`others`, -/// the ids of those and whether each is sealed: one message-id saved under -/// two parsed file names is one article). +/// in the file's sealed blob, or in another file of its release (`index`, +/// the release and the hash key when it has more than one file: one +/// message-id saved under two parsed file names is one article). pub(crate) fn add_segment( conn: &Connection, domains: &mut Domains, f: &FileState, - others: &[(i64, bool)], + index: Option<(i64, &IdKey)>, a: &Article, sealed: &mut SealedCache, ) -> Result { + // the release's index has every id of its other files, sealed or not: no guess + let hash = index.map(|(_, key)| key.hash(&a.message_id)); + #[cfg(test)] + if hash.is_some() { + LOOKUPS.set(LOOKUPS.get() + 1); + } + if let (Some((release_id, _)), Some(hash)) = (index, hash) + && conn + .prepare_cached("select 1 from release_ids where release_id = ? and id_hash = ? and file_id != ?")? + .exists(params![release_id, hash, f.id])? + { + return Ok(false); + } let (local, domain) = domains.encode(conn, &a.message_id)?; let stored = |sealed: &mut SealedCache, local: &[u8], domain: i64| -> Result { let row = conn @@ -638,13 +668,6 @@ pub(crate) fn add_segment( return Ok(false); } } - // `guessed` stays about this file's blob, which the caller asks about - let guessed = sealed.guessed; - let elsewhere = !others.is_empty() && in_other_file(conn, others, &a.message_id, sealed)?; - sealed.guessed = guessed; - if elsewhere { - return Ok(false); - } let added = conn .prepare_cached("insert or ignore into segments (file_id, local, domain, part, bytes) values (?, ?, ?, ?, ?)")? .execute(params![f.id, local, domain, a.part, a.bytes])?; @@ -655,24 +678,73 @@ pub(crate) fn add_segment( )? .execute(params![f.id, a.message_id, a.subject, a.part, a.total_parts, a.file_total])?; } + if added > 0 + && let (Some((release_id, _)), Some(hash)) = (index, hash) + { + conn.prepare_cached("insert or ignore into release_ids (release_id, id_hash, file_id) values (?, ?, ?)")? + .execute(params![release_id, hash, f.id])?; + } Ok(added > 0) } -/// Message-id `id` is in one of `others` (file ids of a release, and whether -/// each is sealed): as a row stored any way, or in a sealed blob (past the -/// decode budget a blob not held is taken not to have it, see `SealedCache`). -fn in_other_file(conn: &Connection, others: &[(i64, bool)], id: &str, sealed: &mut SealedCache) -> Result { - for (local, domain) in stored_forms(conn, id)? { - for &(file_id, is_sealed) in others { - let row = conn - .prepare_cached("select 1 from segments where file_id = ? and local = ? and domain = ?")? - .exists(params![file_id, local, domain])?; - if row || (is_sealed && sealed.contains(conn, file_id, &local, domain)?) { - return Ok(true); - } +#[cfg(test)] +thread_local! { + /// lookups in other files of a release, for counting their cost + static LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The key of `release_ids`' hashes, the shard's own. +pub(crate) struct IdKey(u64, u64); + +impl IdKey { + pub(crate) fn of(conn: &Connection) -> Result { + let get = + |key: &str| -> Result { conn.query_row("select value from meta where key = ?", [key], |r| r.get(0)) }; + Ok(IdKey(get("id_key0")? as u64, get("id_key1")? as u64)) + } + + /// a message-id's hash, as `dedup_key` has it; never 0 (the release's own row) + pub(crate) fn hash(&self, id: &str) -> i64 { + #[allow(deprecated)] + let mut h = std::hash::SipHasher::new_with_keys(self.0, self.1); + std::hash::Hasher::write(&mut h, id.as_bytes()); + match std::hash::Hasher::finish(&h) as i64 { + 0 => 1, + n => n, } } - Ok(false) +} + +/// Release `release_id` in `release_ids`, every message-id of its files +/// added the first time (once it has a second file, or after an upgrade). +pub(crate) fn index_release(conn: &Connection, key: &IdKey, release_id: i64) -> Result<()> { + let marked = + conn.prepare_cached("select 1 from release_ids where release_id = ? and id_hash = 0")?.exists([release_id])?; + if marked { + return Ok(()); + } + let ids: Vec = conn + .prepare_cached("select id from files where release_id = ?")? + .query_map([release_id], |r| r.get(0))? + .collect::>()?; + let mut suffixes = HashMap::new(); + for file_id in ids { + let mut segs = sealed_segments(conn, file_id)?.unwrap_or_default(); + let mut rows = conn.prepare_cached("select local, domain from segments where file_id = ?")?; + let more = rows.query_map([file_id], |r| { + Ok(crate::blob::Seg { local: r.get(0)?, domain: r.get(1)?, part: None, bytes: 0 }) + })?; + for s in more { + segs.push(s?); + } + for s in &segs { + conn.prepare_cached("insert or ignore into release_ids (release_id, id_hash, file_id) values (?, ?, ?)")? + .execute(params![release_id, key.hash(&seg_key(conn, &mut suffixes, s)?), file_id])?; + } + } + conn.prepare_cached("insert or ignore into release_ids (release_id, id_hash, file_id) values (?, 0, 0)")? + .execute([release_id])?; + Ok(()) } /// a release is complete when every file has exactly its parts, and there are @@ -1283,6 +1355,7 @@ impl ShardWriter { // files this save completed, for sealing once it's committed let mut completed = Vec::new(); let tx = conn.transaction()?; + let key = IdKey::of(&tx)?; let (mut new_releases, mut new_articles) = (0i64, 0i64); { let mut upsert = tx.prepare_cached( @@ -1341,14 +1414,18 @@ impl ShardWriter { let mut added: Vec<(&Article, bool)> = Vec::new(); for (name, articles) in by_file { let mut f = file(&tx, release_id, name)?; - // the release's other files, checked for the same message-id - let others: Vec<(i64, bool)> = tx - .prepare_cached("select id, blob is not null from files where release_id = ? and id != ?")? - .query_map(params![release_id, f.id], |r| Ok((r.get(0)?, r.get(1)?)))? - .collect::>()?; + // a release with other files is checked for the same message-id + // in all of them by its index, one lookup an article + let others = tx + .prepare_cached("select 1 from files where release_id = ? and id != ? limit 1")? + .exists(params![release_id, f.id])?; + if others { + index_release(&tx, &key, release_id)?; + } + let index = others.then_some((release_id, &key)); let before = added.len(); for a in articles { - if add_segment(&tx, domains, &f, &others, a, &mut sealed)? { + if add_segment(&tx, domains, &f, index, a, &mut sealed)? { let unsure = f.sealed && sealed.guessed; if unsure { // maybe a copy of what the blob has: only its part @@ -1573,6 +1650,7 @@ pub fn purge_incomplete(main: &Path) -> Result<()> { tx.execute_batch(&format!( "delete from segments where file_id in ({doomed}); delete from held_back where file_id in ({doomed}); + delete from release_ids where release_id in (select id from releases where complete = 0); delete from files where release_id in (select id from releases where complete = 0); delete from releases where complete = 0;" ))?; @@ -1781,7 +1859,7 @@ mod tests { let article = Article { message_id: format!("<{:032x}@nyuu>", 7), part: Some(1), ..Default::default() }; let mut fresh = Domains::default(); assert!( - add_segment(&conn, &mut fresh, &file, &[], &article, &mut SealedCache::new()).unwrap(), + add_segment(&conn, &mut fresh, &file, None, &article, &mut SealedCache::new()).unwrap(), "first time: stored whole" ); for n in 0..SHARED_AFTER { @@ -1789,7 +1867,7 @@ mod tests { } assert!(conn.prepare("select 1 from domains where suffix = '@nyuu>'").unwrap().exists([]).unwrap()); assert!( - !add_segment(&conn, &mut fresh, &file, &[], &article, &mut SealedCache::new()).unwrap(), + !add_segment(&conn, &mut fresh, &file, None, &article, &mut SealedCache::new()).unwrap(), "same article again: not saved twice" ); let segments: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); @@ -1818,7 +1896,7 @@ mod tests { ) .unwrap(); assert!( - !add_segment(&conn, &mut Domains::default(), &file, &[], &legacy, &mut SealedCache::new()).unwrap(), + !add_segment(&conn, &mut Domains::default(), &file, None, &legacy, &mut SealedCache::new()).unwrap(), "legacy text row found" ); let segments: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); @@ -2166,10 +2244,10 @@ mod tests { assert!(f.sealed); let article = Article { message_id: "".into(), part: Some(1), ..Default::default() }; - assert!(!add_segment(&conn, &mut domains, &f, &[], &article, &mut SealedCache::new()).unwrap()); + assert!(!add_segment(&conn, &mut domains, &f, None, &article, &mut SealedCache::new()).unwrap()); let other = Article { message_id: "".into(), part: Some(2), ..Default::default() }; assert!( - add_segment(&conn, &mut domains, &f, &[], &other, &mut SealedCache::new()).unwrap(), + add_segment(&conn, &mut domains, &f, None, &other, &mut SealedCache::new()).unwrap(), "a new one is a row" ); let loose: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); @@ -2669,6 +2747,103 @@ mod tests { assert_eq!(state(), before, "beside a blob"); } + /// Past the decode budget a sealed file of the release is still known to + /// have the message-id: the release's index says so, without its blob. + #[test] + fn a_cross_file_copy_past_the_decode_budget_isnt_saved() { + let (_dir, main) = sealed_fixture(); + let shard = shard_path(&main, shard_of("alt.binaries.t")); + let conn = db::open_at(&shard).unwrap(); + for id in conn.prepare("select id from files").unwrap().query_map([], |r| r.get(0)).unwrap() { + seal_file(&conn, id.unwrap()).unwrap(); + } + let count = + || -> i64 { conn.query_row("select value from meta where key = 'articles'", [], |r| r.get(0)).unwrap() }; + let before = count(); + let mut writer = ShardWriter::new(shard_of("alt.binaries.t")); + writer.decode_budget = 0; + save_with(&mut writer, &main, one_file_release("c.rar", &["", ""])); + assert_eq!(count(), before); + let loose: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap(); + assert_eq!(loose, 0); + } + + /// A release saved before the index (an upgraded shard) gets it the + /// first time it's written to, and copies across its files are found. + #[test] + fn a_release_from_before_the_index_gets_it_when_saved_to() { + let (_dir, main) = sealed_fixture(); + let shard = shard_path(&main, shard_of("alt.binaries.t")); + let conn = db::open_at(&shard).unwrap(); + conn.execute("delete from release_ids", []).unwrap(); + let id: i64 = conn.query_row("select id from files where filename = 'a.rar'", [], |r| r.get(0)).unwrap(); + seal_file(&conn, id).unwrap(); + save(&main, &[one_file_release("c.rar", &["", "<0abc12def34@ngPost>", ""])]).unwrap(); + let files: i64 = conn.query_row("select count(*) from files", [], |r| r.get(0)).unwrap(); + assert_eq!(files, 2, "no c.rar: all of it was in a.rar and b.rar"); + let indexed: i64 = conn.query_row("select count(*) from release_ids", [], |r| r.get(0)).unwrap(); + assert_eq!(indexed, 5, "4 ids and the release's own row"); + } + + /// release Rel with one file `name` of the given message-ids + fn one_file_release(name: &str, ids: &[&str]) -> Release { + Release { + name: "Rel".into(), + group: "alt.binaries.t".into(), + articles: ids + .iter() + .enumerate() + .map(|(n, id)| Article { + message_id: (*id).into(), + subject: format!("\"{name}\" yEnc ({}/9)", n + 1), + filename: Some(name.into()), + part: Some(n as i64 + 1), + total_parts: Some(9), + bytes: 10, + ..Default::default() + }) + .collect(), + ..Default::default() + } + } + + /// Saving new articles to a release with 2,000 files looks each up in + /// the other files once, as with 2 files: not once per file. + #[test] + fn a_release_with_many_files_costs_no_more_per_article() { + let cost = |files: usize| -> usize { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let names: Vec = (0..files).map(|n| format!("")).collect(); + let mut release = one_file_release("f", &[]); + release.articles = names + .iter() + .enumerate() + .map(|(n, id)| Article { + message_id: id.clone(), + filename: Some(format!("f{n}.rar")), + part: Some(1), + total_parts: Some(9), + bytes: 10, + ..Default::default() + }) + .collect(); + save(&main, &[release]).unwrap(); + let ids: Vec = (0..20).map(|n| format!("")).collect(); + let ids: Vec<&str> = ids.iter().map(|s| s.as_str()).collect(); + let later = one_file_release("z.rar", &ids); + let mut conn = db::open_at(&shard_path(&main, shard_of("alt.binaries.t"))).unwrap(); + LOOKUPS.set(0); + ShardWriter::new(shard_of("alt.binaries.t")) + .save(&mut conn, &Ids::new(&main), [std::slice::from_ref(&later)]) + .unwrap(); + LOOKUPS.get() + }; + assert_eq!(cost(2_000), 20, "one an article"); + assert_eq!(cost(2), 20); + } + /// what purging takes off the totals is what it deleted, counted in its /// own transaction: the rest of the totals, including what writers added /// in between, stays as it is From 9d7499d41ddc397058adca8723d3d151fa4e9500 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 06:52:18 -0500 Subject: [PATCH 142/159] Compaction streams a file's held back entries and keeps the release index Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 96 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 77 insertions(+), 19 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 74980a8a..4376a742 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -520,20 +520,50 @@ fn compact_shard( } // what rows a save couldnt tell from copies said (see `store::seal_rows`): // kept for the rows that are new, dropped for copies of the blob's - let mut held_back: Vec<(String, Value, Value, Value, Value)> = held_of - .query_map([id], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)))? - .collect::>()?; - if !held_back.is_empty() { - let mut key = |local: &[u8], domain: i64| dedup_key(&mut suffix_of, local, domain); - let mut in_blob = HashSet::new(); - for s in &segs { - in_blob.insert(key(&s.local, s.domain)?); + // streamed, never held: only the blob's ids (bounded) are + let mut held_back = 0usize; + let mut in_blob: Option> = None; + let mut held = held_of.query([id])?; + while let Some(h) = held.next()? { + let in_blob = match &mut in_blob { + Some(set) => set, + None => { + let mut key = |local: &[u8], domain: i64| dedup_key(&mut suffix_of, local, domain); + let mut set = HashSet::new(); + for s in &segs { + set.insert(key(&s.local, s.domain)?); + } + for r in &spilled { + set.insert(key(&r.local, r.domain)?); + } + in_blob.insert(set) + } + }; + let message_id: String = h.get(0)?; + if in_blob.contains(&message_id) { + continue; } - for r in &spilled { - in_blob.insert(key(&r.local, r.domain)?); + tx.prepare_cached( + "insert into held_back (file_id, message_id, subject, part, total_parts, file_total) + values (?, ?, ?, ?, ?, ?)", + )? + .execute(params![ + id, + message_id, + h.get::<_, Value>(1)?, + h.get::<_, Value>(2)?, + h.get::<_, Value>(3)?, + h.get::<_, Value>(4)? + ])?; + held_back += 1; + in_tx += 1; + if in_tx >= BATCH { + tx.commit()?; + tx = conn.transaction()?; + in_tx = 0; } - held_back.retain(|h| !in_blob.contains(&h.0)); } + drop(held); file_rows.extend(spilled); // a row the blob already has (the same message-id) isnt copied, nor @@ -567,7 +597,7 @@ fn compact_shard( let small = (segs.len() + file_rows.len()) as i64 <= store::SEAL_MAX_SEGMENTS; // nor files with something held back: sealing them folds it in let seal = !file_rows.is_empty() - && held_back.is_empty() + && held_back == 0 && fits && small && store::due(f.get(6)?, &seen, f.get(9)?, old_blob.is_some(), now); @@ -586,13 +616,6 @@ fn compact_shard( values.push(blob.map_or(Value::Null, Value::Blob)); tx.prepare_cached(&format!("insert into files ({FILE_COLUMNS}) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))? .execute(params_from_iter(values))?; - for h in held_back { - tx.prepare_cached( - "insert into held_back (file_id, message_id, subject, part, total_parts, file_total) - values (?, ?, ?, ?, ?, ?)", - )? - .execute(params![id, h.0, h.1, h.2, h.3, h.4])?; - } copied += segs.len() as i64; for row in &file_rows { copied += insert_row(&tx, row)?; @@ -642,6 +665,11 @@ fn compact_shard( for id in recount { store::recount_parts(&tx, id)?; } + // the releases' message-id index: its files and their ids are the same + tx.execute_batch( + "insert into release_ids select * from old.release_ids + where file_id = 0 or file_id in (select id from files)", + )?; tx.commit()?; } say(&format!("sealed {sealed} files")); @@ -1245,6 +1273,36 @@ mod tests { assert_eq!(expected, 3); } + /// More held back entries than a batch take are streamed across: the new + /// ones kept, the blob's copies dropped, and the releases' message-id + /// index comes along. + #[test] + fn compacting_streams_many_held_back_entries_and_keeps_the_index() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + let (path, file, _) = held_back_fixture(&main, ("", 2, 2)); + let many = BATCH as i64 + 7; + { + let conn = db::open_at(&path).unwrap(); + let mut insert = conn + .prepare("insert into held_back (file_id, message_id, part, total_parts) values (?, ?, ?, 2)") + .unwrap(); + for n in 0..many { + insert.execute(params![file, format!(""), n + 3]).unwrap(); + } + } + let ids = |path: &Path| -> i64 { + db::open_at(path).unwrap().query_row("select count(*) from release_ids", [], |r| r.get(0)).unwrap() + }; + let indexed = ids(&path); + assert!(indexed > 0, "two files: the release is indexed"); + run(&main, &|_| {}, &no_stop()).unwrap(); + let conn = db::open_at(&path).unwrap(); + let held: i64 = conn.query_row("select count(*) from held_back", [], |r| r.get(0)).unwrap(); + assert_eq!(held, many, "the copy's entry dropped, every new one kept"); + assert_eq!(ids(&path), indexed); + } + /// Compaction drops a row that copies b.rar's part 1 but claimed part 2: /// the file's parts and its release's completeness go back to what the /// blob has (1 of 2), and what the copy held back goes with it. From 50afe4f954d3acbbf37ade68d097cd6ebd616d2f Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:07:00 -0500 Subject: [PATCH 143/159] Indexing a release streams a file's loose rows instead of collecting them Files past the seal cap stay loose, so collecting every row before hashing was unbounded; the rows now go from the cursor one at a time. Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 45 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/src/store.rs b/src/store.rs index 93a5de1f..ae752daf 100644 --- a/src/store.rs +++ b/src/store.rs @@ -729,17 +729,18 @@ pub(crate) fn index_release(conn: &Connection, key: &IdKey, release_id: i64) -> .collect::>()?; let mut suffixes = HashMap::new(); for file_id in ids { - let mut segs = sealed_segments(conn, file_id)?.unwrap_or_default(); - let mut rows = conn.prepare_cached("select local, domain from segments where file_id = ?")?; - let more = rows.query_map([file_id], |r| { - Ok(crate::blob::Seg { local: r.get(0)?, domain: r.get(1)?, part: None, bytes: 0 }) - })?; - for s in more { - segs.push(s?); + let mut insert = + conn.prepare_cached("insert or ignore into release_ids (release_id, id_hash, file_id) values (?, ?, ?)")?; + // the blob is bounded by SEAL_MAX_SEGMENTS; the rows are not, so they + // stream from the cursor one at a time + for s in sealed_segments(conn, file_id)?.unwrap_or_default() { + insert.execute(params![release_id, key.hash(&seg_key(conn, &mut suffixes, &s)?), file_id])?; } - for s in &segs { - conn.prepare_cached("insert or ignore into release_ids (release_id, id_hash, file_id) values (?, ?, ?)")? - .execute(params![release_id, key.hash(&seg_key(conn, &mut suffixes, s)?), file_id])?; + let mut rows = conn.prepare_cached("select local, domain from segments where file_id = ?")?; + let mut cursor = rows.query([file_id])?; + while let Some(r) = cursor.next()? { + let s = crate::blob::Seg { local: r.get(0)?, domain: r.get(1)?, part: None, bytes: 0 }; + insert.execute(params![release_id, key.hash(&seg_key(conn, &mut suffixes, &s)?), file_id])?; } } conn.prepare_cached("insert or ignore into release_ids (release_id, id_hash, file_id) values (?, 0, 0)")? @@ -2785,6 +2786,30 @@ mod tests { assert_eq!(indexed, 5, "4 ids and the release's own row"); } + /// A file past the seal cap stays loose rows; indexing its release + /// hashes them one by one from the cursor and indexes every one. + #[test] + fn indexing_a_release_with_a_huge_loose_file_indexes_every_row() { + let (_dir, main) = sealed_fixture(); + let shard = shard_path(&main, shard_of("alt.binaries.t")); + let conn = db::open_at(&shard).unwrap(); + conn.execute("delete from release_ids", []).unwrap(); + let id: i64 = conn.query_row("select id from files where filename = 'a.rar'", [], |r| r.get(0)).unwrap(); + let rows = SEAL_MAX_SEGMENTS + 10; + conn.execute( + "with recursive n(i) as (select 1 union all select i + 1 from n where i < ?) + insert or ignore into segments (file_id, local, domain, part, bytes) + select ?, cast('big' || i as blob), 0, i, 1 from n", + params![rows, id], + ) + .unwrap(); + let release_id: i64 = conn.query_row("select release_id from files where id = ?", [id], |r| r.get(0)).unwrap(); + index_release(&conn, &IdKey::of(&conn).unwrap(), release_id).unwrap(); + let indexed: i64 = + conn.query_row("select count(*) from release_ids where file_id = ?", [id], |r| r.get(0)).unwrap(); + assert_eq!(indexed, rows + 3, "every row, and the blob's 3 ids"); + } + /// release Rel with one file `name` of the given message-ids fn one_file_release(name: &str, ids: &[&str]) -> Release { Release { From ba29ba251c3946cb4befbbe227c4d56a72f7cca4 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:07:37 -0500 Subject: [PATCH 144/159] A server's explicit key keeps its case in the cursor key Only the host part of the cursor key is lowercased, so keys that differ by case no longer collide. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/indexer.rs b/src/indexer.rs index e9e44d45..ad9e799d 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -382,7 +382,15 @@ pub struct PassContext { /// `server_keys`). One server keeps the plain /// group name like before. fn cursor_key(pool: &Pool, server: usize, group: &str) -> String { - if pool.len() <= 1 { group.to_string() } else { format!("{group}@{}", pool.host(server).to_lowercase()) } + if pool.len() <= 1 { + return group.to_string(); + } + // only the host (and port) is case-insensitive, an explicit `#key` isnt + let host = pool.host(server); + match host.split_once('#') { + Some((h, k)) => format!("{group}@{}#{k}", h.to_lowercase()), + None => format!("{group}@{}", host.to_lowercase()), + } } async fn load_cursors( @@ -1703,6 +1711,21 @@ impl Indexer { mod tests { use super::*; + /// `#key`s that differ by case are two servers, and the host in a key is + /// lowercased as before + #[test] + fn cursor_keys_keep_the_case_of_a_servers_key() { + let mut upper = crate::config::UsenetServer::new("A.Example", "u", "p", 563); + upper.key = Some("Block".into()); + let mut lower = upper.clone(); + lower.key = Some("block".into()); + let plain = crate::config::UsenetServer::new("B.Example", "u", "p", 563); + let pool = Pool::new(&[upper, lower, plain]); + assert_eq!(cursor_key(&pool, 0, "g"), "g@a.example#Block"); + assert_eq!(cursor_key(&pool, 1, "g"), "g@a.example#block"); + assert_eq!(cursor_key(&pool, 2, "g"), "g@b.example"); + } + #[test] fn each_speculative_window_has_to_hold_enough_on_its_own() { let rt = tokio::runtime::Builder::new_current_thread().build().unwrap(); From 0df0948ef940f7b3e40ec20d9554aa95bace86a7 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:13:13 -0500 Subject: [PATCH 145/159] Compaction checks the stop flag while it streams a file's held back entries Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/src/compact.rs b/src/compact.rs index 4376a742..8438f510 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -260,6 +260,20 @@ fn halt(stop: &AtomicBool, shard: usize) -> Result<()> { Ok(()) } +/// test hook: the stop flags (by address) to set the first time the held +/// back stream looks at them, with how many times it has +#[cfg(test)] +static HELD_CHECKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +#[cfg(test)] +fn held_check(stop: &AtomicBool) { + let at = stop as *const AtomicBool as usize; + if let Some(e) = HELD_CHECKS.lock().unwrap().iter_mut().find(|e| e.0 == at) { + e.1 += 1; + stop.store(true, Ordering::Relaxed); + } +} + /// Have SQLite give up long statements (a bulk insert, an index build) once /// `stop` is set: they fail with an interrupt, like any other error. fn interruptible(conn: &Connection, stop: &Arc) -> Result<()> { @@ -524,7 +538,15 @@ fn compact_shard( let mut held_back = 0usize; let mut in_blob: Option> = None; let mut held = held_of.query([id])?; + let mut streamed = 0usize; while let Some(h) = held.next()? { + // copies and kept entries alike: a huge file has millions + streamed += 1; + if streamed.is_multiple_of(STOP_EVERY) { + #[cfg(test)] + held_check(stop); + halt(stop, shard)?; + } let in_blob = match &mut in_blob { Some(set) => set, None => { @@ -1273,6 +1295,34 @@ mod tests { assert_eq!(expected, 3); } + /// A stop during a huge held back stream ends it at the next look, not + /// after the whole file's entries. + #[test] + fn a_stop_during_a_large_held_back_stream_ends_it_promptly() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + let (path, file, _) = held_back_fixture(&main, ("", 2, 2)); + { + let mut conn = db::open_at(&path).unwrap(); + let tx = conn.transaction().unwrap(); + { + let mut insert = tx + .prepare("insert into held_back (file_id, message_id, part, total_parts) values (?, ?, ?, 2)") + .unwrap(); + for n in 0..(STOP_EVERY as i64 * 3) { + insert.execute(params![file, format!(""), n + 3]).unwrap(); + } + } + tx.commit().unwrap(); + } + let stop = no_stop(); + HELD_CHECKS.lock().unwrap().push((Arc::as_ptr(&stop) as usize, 0)); + let err = run(&main, &|_| {}, &stop).unwrap_err(); + assert!(format!("{err:#}").contains("stopped"), "{err:#}"); + let looks = HELD_CHECKS.lock().unwrap().iter().find(|e| e.0 == Arc::as_ptr(&stop) as usize).unwrap().1; + assert_eq!(looks, 1, "stopped at the first look, not after 3 of them"); + } + /// More held back entries than a batch take are streamed across: the new /// ones kept, the blob's copies dropped, and the releases' message-id /// index comes along. From bbf6b0eeee77f38388e85821d52ef83dba1b6fe1 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:31:51 -0500 Subject: [PATCH 146/159] A subject claiming a part past its file's total or past MAX_PARTS is dropped Co-Authored-By: Claude Opus 5.5 --- src/parser.rs | 36 ++++++++++++++++++++++++++++++++++++ src/store.rs | 2 +- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/parser.rs b/src/parser.rs index 1eaaeb4f..2794dc67 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -4,6 +4,10 @@ use std::sync::LazyLock; use indexmap::IndexMap; use regex::Regex; +/// most parts a file can claim. a subject claiming more is forged: the part +/// bitmap grows with the part number, so it would cost storage per header +pub const MAX_PARTS: i64 = 100_000; + #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Article { pub number: u64, @@ -99,6 +103,10 @@ pub fn parse_subject(subject: &str) -> Option { (Some(p), Some(t)) => (p.as_str().parse().ok()?, t.as_str().parse().ok()?), _ => (1, 1), }; + // a part past the file's own total, or past any real file, is forged + if part > MAX_PARTS || total_parts > MAX_PARTS || (total_parts != 0 && part > total_parts) { + return None; + } let (mut file_index, mut file_total) = (None, None); @@ -138,12 +146,20 @@ fn remap_bracket_parts(articles: &mut [Article]) { continue; } + // a bracket counter past any real file is forged, not a part number + if idxs.iter().any(|&i| articles[i].file_index.is_some_and(|n| n > MAX_PARTS)) { + continue; + } + let total = idxs .iter() .map(|&i| articles[i].file_total.unwrap_or(0)) .chain(std::iter::once(idxs.len() as i64)) .max() .unwrap_or(0); + if total > MAX_PARTS { + continue; + } for &i in idxs { let a = &mut articles[i]; @@ -252,6 +268,26 @@ mod tests { assert_eq!((p.file_index, p.file_total), (Some(1), Some(10))); } + #[test] + fn forged_part_numbers_are_unparsable() { + assert!(parse_subject(r#""a.rar" yEnc (1000000/1)"#).is_none()); + assert!(parse_subject(r#""a.rar" yEnc (2/1)"#).is_none()); + assert!(parse_subject(r#""a.rar" yEnc (1/1000000)"#).is_none()); + assert!(parse_subject(r#""a.rar" yEnc (1/1)"#).is_some()); + } + + #[test] + fn forged_headers_dont_grow_seen_blobs() { + let mut f = crate::store::FileState::default(); + for i in 0..1000 { + let subject = format!(r#""a.rar" yEnc (1000000/1) {i}"#); + if let Some(p) = parse_subject(&subject) { + f.add(&Article { part: Some(p.part), total_parts: Some(p.total_parts), ..Default::default() }); + } + } + assert!(f.seen.is_empty()); + } + #[test] fn strips_stacked_suffixes() { let p = parse_subject(r#""show.s01e01.vol03+04.par2" yEnc (2/3)"#).unwrap(); diff --git a/src/store.rs b/src/store.rs index ae752daf..2fe183e4 100644 --- a/src/store.rs +++ b/src/store.rs @@ -520,7 +520,7 @@ pub(crate) fn decode(local: &[u8], suffix: Option<&str>) -> String { /// one bit per part number present pub(crate) fn insert_part(bits: &mut Vec, part: i64) { // a bad part number from a broken subject shouldnt allocate a huge bitmap - if !(0..=1_000_000).contains(&part) { + if !(0..=crate::parser::MAX_PARTS).contains(&part) { return; } let (byte, bit) = ((part / 8) as usize, part % 8); From b3e731c4a26ddfbf574e94cb5cbf310fce43d4c3 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:33:10 -0500 Subject: [PATCH 147/159] The held back stop hook is removed by a guard when its test ends Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 42 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 8438f510..7755edf7 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -265,6 +265,31 @@ fn halt(stop: &AtomicBool, shard: usize) -> Result<()> { #[cfg(test)] static HELD_CHECKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +#[cfg(test)] +struct HeldCheck(usize); + +/// registers a stop flag with the hook above until the guard drops, soo a +/// flag's address freed and reused by another test never finds it still there +#[cfg(test)] +impl HeldCheck { + fn on(stop: &Arc) -> HeldCheck { + let at = Arc::as_ptr(stop) as usize; + HELD_CHECKS.lock().unwrap().push((at, 0)); + HeldCheck(at) + } + + fn looks(&self) -> usize { + HELD_CHECKS.lock().unwrap().iter().find(|e| e.0 == self.0).unwrap().1 + } +} + +#[cfg(test)] +impl Drop for HeldCheck { + fn drop(&mut self) { + HELD_CHECKS.lock().unwrap().retain(|e| e.0 != self.0); + } +} + #[cfg(test)] fn held_check(stop: &AtomicBool) { let at = stop as *const AtomicBool as usize; @@ -1295,6 +1320,18 @@ mod tests { assert_eq!(expected, 3); } + /// The stop hook goes with its guard: nothing is left in the registry for + /// another test's flag to meet. + #[test] + fn the_stop_hook_is_removed_when_its_guard_drops() { + let stop = no_stop(); + let check = HeldCheck::on(&stop); + assert!(HELD_CHECKS.lock().unwrap().iter().any(|e| e.0 == check.0)); + let at = check.0; + drop(check); + assert!(HELD_CHECKS.lock().unwrap().iter().all(|e| e.0 != at)); + } + /// A stop during a huge held back stream ends it at the next look, not /// after the whole file's entries. #[test] @@ -1316,11 +1353,10 @@ mod tests { tx.commit().unwrap(); } let stop = no_stop(); - HELD_CHECKS.lock().unwrap().push((Arc::as_ptr(&stop) as usize, 0)); + let check = HeldCheck::on(&stop); let err = run(&main, &|_| {}, &stop).unwrap_err(); assert!(format!("{err:#}").contains("stopped"), "{err:#}"); - let looks = HELD_CHECKS.lock().unwrap().iter().find(|e| e.0 == Arc::as_ptr(&stop) as usize).unwrap().1; - assert_eq!(looks, 1, "stopped at the first look, not after 3 of them"); + assert_eq!(check.looks(), 1, "stopped at the first look, not after 3 of them"); } /// More held back entries than a batch take are streamed across: the new From e4b2942995f52ec742442bb6952d9134f7ff2a1e Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:34:20 -0500 Subject: [PATCH 148/159] Compaction checks the stop flag every STOP_EVERY rows of a file's tail it looks at Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 58 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 5 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 7755edf7..94275d34 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -263,7 +263,7 @@ fn halt(stop: &AtomicBool, shard: usize) -> Result<()> { /// test hook: the stop flags (by address) to set the first time the held /// back stream looks at them, with how many times it has #[cfg(test)] -static HELD_CHECKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +static HELD_CHECKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); #[cfg(test)] struct HeldCheck(usize); @@ -274,13 +274,18 @@ struct HeldCheck(usize); impl HeldCheck { fn on(stop: &Arc) -> HeldCheck { let at = Arc::as_ptr(stop) as usize; - HELD_CHECKS.lock().unwrap().push((at, 0)); + HELD_CHECKS.lock().unwrap().push((at, 0, 0)); HeldCheck(at) } fn looks(&self) -> usize { HELD_CHECKS.lock().unwrap().iter().find(|e| e.0 == self.0).unwrap().1 } + + /// the rows the loop had looked at when it last looked + fn examined(&self) -> usize { + HELD_CHECKS.lock().unwrap().iter().find(|e| e.0 == self.0).unwrap().2 + } } #[cfg(test)] @@ -291,10 +296,11 @@ impl Drop for HeldCheck { } #[cfg(test)] -fn held_check(stop: &AtomicBool) { +fn held_check(stop: &AtomicBool, examined: usize) { let at = stop as *const AtomicBool as usize; if let Some(e) = HELD_CHECKS.lock().unwrap().iter_mut().find(|e| e.0 == at) { e.1 += 1; + e.2 = examined; stop.store(true, Ordering::Relaxed); } } @@ -569,7 +575,7 @@ fn compact_shard( streamed += 1; if streamed.is_multiple_of(STOP_EVERY) { #[cfg(test)] - held_check(stop); + held_check(stop, streamed); halt(stop, shard)?; } let in_blob = match &mut in_blob { @@ -675,6 +681,7 @@ fn compact_shard( let held_before_tail = held.len(); // `held` (the blob and the buffered rows, bounded) isnt added to: // a tail copy of a tail row is found in the copy database instead + let mut examined = 0usize; while let Some(row) = pending.take_if(|r| r.file_id == id) { let key = dedup_key(&mut suffix_of, &row.local, row.domain)?; if !held.contains(&key) && !has_other_form(&tx, &row, &key)? && insert_row(&tx, &row)? == 1 { @@ -683,7 +690,11 @@ fn compact_shard( (tail_bytes, tail_copies) = (tail_bytes + row.bytes.unwrap_or(0), tail_copies + 1); } in_tx += 1; - if (copied as usize).is_multiple_of(STOP_EVERY) { + // rows looked at, not copied: a tail of copies doesnt advance `copied` + examined += 1; + if examined.is_multiple_of(STOP_EVERY) { + #[cfg(test)] + held_check(stop, examined); halt(stop, shard)?; } if in_tx >= BATCH { @@ -1359,6 +1370,43 @@ mod tests { assert_eq!(check.looks(), 1, "stopped at the first look, not after 3 of them"); } + /// A stop during a huge tail of copies (rows `copied` doesnt count) is + /// looked at every STOP_EVERY rows examined. + #[test] + fn a_stop_during_a_tail_of_copies_ends_it_by_rows_examined() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + run(&main, &|_| {}, &no_stop()).unwrap(); + let (path, file) = file_of(&main, "Rel.1", "alt.binaries.g1"); + { + let conn = db::open_at(&path).unwrap(); + let d: i64 = conn.query_row("select id from domains where suffix = '@ngPost>'", [], |r| r.get(0)).unwrap(); + // past what a blob takes, then as many whole ids as a stop look is + // apart; each one again packed after it, a copy of the one before + let n = store::SEAL_MAX_SEGMENTS + 1 + STOP_EVERY as i64; + conn.execute( + "with recursive n(i) as (select 1 union all select i + 1 from n where i < ?2) + insert into segments (file_id, local, domain, part, bytes) + select ?1, cast(x'00' || cast('!' || i as blob) as blob), 0, 100 + i, 1 from n", + params![file, n], + ) + .unwrap(); + let mut insert = conn + .prepare("insert into segments (file_id, local, domain, part, bytes) values (?, ?, ?, 1, 1)") + .unwrap(); + for i in 1..=STOP_EVERY as i64 * 2 { + insert.execute(params![file, store::pack_local(&format!("!{i}")), d]).unwrap(); + } + } + let stop = no_stop(); + let check = HeldCheck::on(&stop); + let err = run(&main, &|_| {}, &stop).unwrap_err(); + assert!(format!("{err:#}").contains("stopped"), "{err:#}"); + assert_eq!(check.looks(), 1); + assert_eq!(check.examined(), STOP_EVERY, "the first look is after STOP_EVERY rows of the tail"); + } + /// More held back entries than a batch take are streamed across: the new /// ones kept, the blob's copies dropped, and the releases' message-id /// index comes along. From 0f39c807e2559ec77632c333ce5a1403d88e778d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:35:27 -0500 Subject: [PATCH 149/159] A sweep chosen before the split reached back isnt noted done after it Co-Authored-By: Claude Opus 5.5 --- src/chunks.rs | 54 +++++++++++++++++++++++++++++++++++++++++++++----- src/indexer.rs | 19 +++++++++++++----- 2 files changed, 63 insertions(+), 10 deletions(-) diff --git a/src/chunks.rs b/src/chunks.rs index d61422f6..e91ac095 100644 --- a/src/chunks.rs +++ b/src/chunks.rs @@ -37,6 +37,10 @@ pub fn create(conn: &Connection) -> Result<()> { server TEXT NOT NULL, primary key (grp, server) ) without rowid; + create table if not exists backfill_sweep_gen ( + grp TEXT PRIMARY KEY, + gen INTEGER NOT NULL + ) without rowid; create table if not exists backfill_speculative ( grp TEXT PRIMARY KEY, runner_up_day INTEGER NOT NULL, @@ -139,6 +143,11 @@ pub fn reach_back(conn: &Connection, group: &str, oldest_day: i64, oldest_at: i6 tx.execute("delete from backfill_deepest where grp = ?", [group])?; // a carrier's sweep stopped at its first article then: it may keep older ones now tx.execute("delete from backfill_sweeps where grp = ?", [group])?; + // and a sweep that started before this doesnt get to note itself done (see `set_swept`) + tx.execute( + "insert into backfill_sweep_gen (grp, gen) values (?, 1) on conflict (grp) do update set gen = gen + 1", + [group], + )?; tx.commit()?; Ok(added + redo) } @@ -340,10 +349,25 @@ pub fn chunks_done(conn: &Connection, group: &str) -> Result { && !conn.prepare_cached("select 1 from backfill_chunks where grp = ? and state != 2")?.exists([group])?) } +/// The split generation of `group`: counts the times its split reached back +/// (see `reach_back`), which undoes what a sweep covered. +pub fn sweep_generation(conn: &Connection, group: &str) -> Result { + Ok(conn + .query_row("select gen from backfill_sweep_gen where grp = ?", [group], |r| r.get(0)) + .optional()? + .unwrap_or(0)) +} + /// Note `server`'s sweep of split `group` as done: its cursor backfill got /// down to its first article after the day chunks (see `indexer::run_sweep`). -pub fn set_swept(conn: &Connection, group: &str, server: &str) -> Result<()> { - conn.execute("insert or ignore into backfill_sweeps (grp, server) values (?, ?)", [group, server])?; +/// `generation` is the group's (see `sweep_generation`) when the sweep was +/// chosen: one from before the split reached back is stale and notes nothing. +pub fn set_swept(conn: &Connection, group: &str, server: &str, generation: i64) -> Result<()> { + conn.execute( + "insert or ignore into backfill_sweeps (grp, server) + select ?1, ?2 where coalesce((select gen from backfill_sweep_gen where grp = ?1), 0) = ?3", + params![group, server, generation], + )?; Ok(()) } @@ -402,7 +426,7 @@ mod tests { // days 100.. the next deepest keeps, 40..99 the window, older pruned add(&c, "g", 120, 40).unwrap(); set_speculative(&c, "g", &Speculative { runner_up_day: 100, reach: 60, days: 3, articles: 7 }).unwrap(); - set_swept(&c, "g", "a").unwrap(); + set_swept(&c, "g", "a", 0).unwrap(); // the hourly look finds the deep server back in 2000 again: nothing assert_eq!(reach_back(&c, "g", 10, 10 * 86_400).unwrap(), 0); assert_eq!(oldest_day(&c, "g").unwrap(), Some(40)); @@ -510,8 +534,8 @@ mod tests { add(&c, "g", 12, 10).unwrap(); c.execute("update backfill_chunks set state = 2", []).unwrap(); set_deepest(&c, "g", "a", 10 * 86_400 + 18 * 3600).unwrap(); - set_swept(&c, "g", "b").unwrap(); - set_swept(&c, "other", "b").unwrap(); + set_swept(&c, "g", "b", 0).unwrap(); + set_swept(&c, "other", "b", 0).unwrap(); assert_eq!(reach_back(&c, "g", 10, 10 * 86_400 + 20 * 3600).unwrap(), 0, "not further"); assert!(swept(&c, "g", "b").unwrap(), "kept when nothing changed"); @@ -521,6 +545,26 @@ mod tests { assert!(swept(&c, "other", "b").unwrap(), "other groups' sweeps stay"); } + /// a sweep chosen before the split reached back, finishing after, doesnt + /// note itself done: it covered what is older now only down to the old first article + #[test] + fn a_sweep_from_before_reaching_back_is_not_noted() { + let c = conn(); + add(&c, "g", 12, 10).unwrap(); + c.execute("update backfill_chunks set state = 2", []).unwrap(); + set_deepest(&c, "g", "a", 10 * 86_400 + 18 * 3600).unwrap(); + let started = sweep_generation(&c, "g").unwrap(); + + assert_eq!(reach_back(&c, "g", 9, 9 * 86_400).unwrap(), 2); + set_swept(&c, "g", "b", started).unwrap(); + assert!(!swept(&c, "g", "b").unwrap(), "stale, left to do"); + + let now = sweep_generation(&c, "g").unwrap(); + assert_ne!(now, started); + set_swept(&c, "g", "b", now).unwrap(); + assert!(swept(&c, "g", "b").unwrap(), "one started since is noted"); + } + #[test] fn days_before_are_dropped_unless_done() { let c = conn(); diff --git a/src/indexer.rs b/src/indexer.rs index ad9e799d..c802a994 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -492,9 +492,13 @@ where // a split group's backfill is day chunks, this server takes the next one let host = ctx.pool.host(server); let wanted = [(group.to_string(), ctx.states.keeps_from(group, &host))]; - let claimed = - on_db(db, move |conn| Ok(crate::chunks::claim(conn, &wanted, &host, chrono::Utc::now().timestamp())?)) - .await?; + // the split's generation as of the claim: a sweep noted after the split reached back isnt + let g = group.to_string(); + let (claimed, generation) = on_db(db, move |conn| { + let generation = crate::chunks::sweep_generation(conn, &g)?; + Ok((crate::chunks::claim(conn, &wanted, &host, chrono::Utc::now().timestamp())?, generation)) + }) + .await?; let r = match claimed { // a day this server doesnt keep is left to the others, it isnt an error Some(chunk) => match run_chunk(ctx, settings, db, &chunk, server, progress).await { @@ -511,7 +515,7 @@ where None if sweep_due(ctx, db, group, &ctx.pool.host(server)).await? => { if state.backfill_cursor.min(last) < first { let (g, host) = (group.to_string(), ctx.pool.host(server)); - on_db(db, move |conn| Ok(crate::chunks::set_swept(conn, &g, &host)?)).await?; + on_db(db, move |conn| Ok(crate::chunks::set_swept(conn, &g, &host, generation)?)).await?; } let pass = Pass { ctx, settings, db, group, server, key }; pass.backfill(state, first, last, progress).await @@ -854,9 +858,14 @@ where P: FnMut(&Progress) + ?Sized, { let (g, host) = (group.to_string(), ctx.pool.host(server)); + // noted as swept only if the split hasnt reached back since (see `set_swept`) + let generation = { + let g = g.clone(); + on_db(db, move |conn| Ok(crate::chunks::sweep_generation(conn, &g)?)).await? + }; let swept = || { let (g, host) = (g.clone(), host.clone()); - on_db(db, move |conn| Ok(crate::chunks::set_swept(conn, &g, &host)?)) + on_db(db, move |conn| Ok(crate::chunks::set_swept(conn, &g, &host, generation)?)) }; // this server alone, like a day chunk let (_count, first, last, _name) = match ctx.pool.group_on(server, group).await { From 4021482c9da6e74f613b7d81d488c65028d5b565 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:41:01 -0500 Subject: [PATCH 150/159] A speculative window is judged when its last day is done, and a window the reach moved past is ignored Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 57 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index c802a994..cd8b4457 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -981,14 +981,22 @@ async fn drop_older_days(db: &Db, group: &str, day: i64) { /// window's oldest and the window's days held enough a day, chunks for the /// days before it, back to the server's first post (`oldest`). Best effort: /// a failure is only logged. -async fn reach_further(db: &Db, group: &str, (day, floor, oldest): (i64, i64, Option), dated: i64) { +async fn reach_further(db: &Db, group: &str, (_day, floor, oldest): (i64, i64, Option), dated: i64) { let first = oldest.map_or(floor, crate::chunks::unix_day); let g = group.to_string(); let added = on_db(db, move |conn| { let Some(mut s) = crate::chunks::speculative(conn, &g)? else { return Ok(0) }; + // a day of a window the reach has moved past is not the current one's + if floor != s.runner_up_day - s.reach { + return Ok(0); + } s.days += 1; s.articles += dated; - let further = day == floor && s.articles >= SPECULATIVE_YIELD * s.days && first < floor; + // the window is judged when its last day is done, not when its oldest is + let running = conn + .prepare_cached("select 1 from backfill_chunks where grp = ? and day >= ? and day < ? and state != 2")? + .exists(rusqlite::params![g, floor, floor + SPECULATIVE_WINDOW])?; + let further = !running && s.articles >= SPECULATIVE_YIELD * s.days && first < floor; if further { // each extension has to hold enough a day on its own: a dense // first window doesnt pay for the sparse ones after it @@ -1761,6 +1769,51 @@ mod tests { assert_eq!(s.reach, 2 * SPECULATIVE_WINDOW); } + #[test] + fn a_speculative_window_is_judged_once_every_day_of_it_is_done() { + let rt = tokio::runtime::Builder::new_current_thread().build().unwrap(); + rt.block_on(a_window_judged_when_done()); + } + + async fn a_window_judged_when_done() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let db = shared_db(db::open_at(&main).unwrap()); + let (r, g) = (20_000, "g"); + let floor = r - SPECULATIVE_WINDOW; + let start = crate::chunks::Speculative { runner_up_day: r, reach: SPECULATIVE_WINDOW, days: 0, articles: 0 }; + on_db(&db, move |c| { + // three days of the window, one older + crate::chunks::add(c, g, floor + 2, floor)?; + Ok(crate::chunks::set_speculative(c, g, &start)?) + }) + .await + .unwrap(); + let window = || on_db(&db, move |c| Ok(crate::chunks::speculative(c, g)?.unwrap())); + let done = + |day: i64| on_db(&db, move |c| Ok(c.execute("update backfill_chunks set state = 2 where day = ?", [day])?)); + + // the floor day is done and dense, the rest of the window is still running + done(floor).await.unwrap(); + reach_further(&db, g, (floor, floor, Some(0)), 100_000).await; + let s = window().await.unwrap(); + assert_eq!((s.reach, s.days, s.articles), (SPECULATIVE_WINDOW, 1, 100_000), "counted, not judged yet"); + + // the last one in judges the window on all of them + done(floor + 1).await.unwrap(); + reach_further(&db, g, (floor + 1, floor, Some(0)), 1).await; + done(floor + 2).await.unwrap(); + reach_further(&db, g, (floor + 2, floor, Some(0)), 1).await; + let s = window().await.unwrap(); + assert_eq!((s.reach, s.days, s.articles), (2 * SPECULATIVE_WINDOW, 0, 0)); + + // a day of the window before it, finishing late, is not the new window's + reach_further(&db, g, (floor + 2, floor, Some(0)), 100_000).await; + let s = window().await.unwrap(); + assert_eq!((s.reach, s.days, s.articles), (2 * SPECULATIVE_WINDOW, 0, 0), "ignored"); + } + #[test] fn a_chunk_taken_over_leaves_the_older_days_and_the_window_alone() { let rt = tokio::runtime::Builder::new_current_thread().build().unwrap(); From 781cca52fb5515ec009ee5cf3f3fe8a83dd55b4a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:38:16 -0500 Subject: [PATCH 151/159] The forged daily split test forges six years of days, not 26, and waits longer on a slow runner Each chunk of the speculative window cost more the more articles the deep server held, and ubuntu's 2-core runner ran out of its 180 s while still making progress (58 of 90 chunks). The window and the sweep it proves are the same with 2190 forged days. Co-Authored-By: Claude Opus 5.5 --- tests/split_forged_daily.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/split_forged_daily.rs b/tests/split_forged_daily.rs index 4a032505..ed6c6f6d 100644 --- a/tests/split_forged_daily.rs +++ b/tests/split_forged_daily.rs @@ -1,5 +1,5 @@ //! A split group on two servers, one with an article dated in every day -//! from 2000 on before its real ones (forged): each of those thousands of +//! of the six years before its real ones (forged): each of those thousands of //! days looks corroborated by its one article. Only a window of the days //! older than the other server goes back is serviced as chunks at once, and //! one article a day doesnt earn more: the rest is left to the deep @@ -33,7 +33,7 @@ fn posts(offset: u64) -> Vec { } #[test] -fn forged_dates_one_a_day_back_to_2000_service_only_a_window_of_chunks() { +fn forged_dates_one_a_day_for_six_years_service_only_a_window_of_chunks() { let home = tempfile::tempdir().unwrap(); // SAFETY: only test in this binary, set before any thread is spawned unsafe { @@ -42,8 +42,9 @@ fn forged_dates_one_a_day_back_to_2000_service_only_a_window_of_chunks() { std::env::set_var("ATLAS_SAB_DIR", home.path().join("no-sabnzbd")); } - // one article noon of every day from 2000-01-05 to 2025-12-31, then the real ones - let first = chrono::DateTime::parse_from_rfc3339("2000-01-05T12:00:00+00:00").unwrap(); + // one article noon of every day from 2020-01-05 to 2025-12-31, then the + // real ones: thousands of days, few enough articles for a slow runner + let first = chrono::DateTime::parse_from_rfc3339("2020-01-05T12:00:00+00:00").unwrap(); let split_start = chrono::DateTime::parse_from_rfc3339("2026-01-01T00:00:00+00:00").unwrap(); let forged_days = (split_start - first).num_days() as u64 + 1; let mut deep: Vec = (0..forged_days) @@ -80,7 +81,8 @@ fn forged_dates_one_a_day_back_to_2000_service_only_a_window_of_chunks() { let main = home.path().join("atlas.db"); let every = 1200 + forged_days as i64; - let deadline = Instant::now() + Duration::from_secs(180); + // a 2-core runner services its window of chunks many times slower + let deadline = Instant::now() + Duration::from_secs(300); loop { let conn = atlas::db::open_with_shards(&main).unwrap(); let (_, articles) = atlas::store::totals(&conn).unwrap(); From 6c3cad074c0de3839ad893e288da24dfd7bf9004 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:40:51 -0500 Subject: [PATCH 152/159] Compaction counts each domain's uses in a database file of its own, not in memory A shard can have as many domains as a poster makes up, and four shards are compacted at once: a map of them all could run out of memory. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 133 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 100 insertions(+), 33 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 94275d34..9894e2af 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -18,7 +18,7 @@ //! between moving the original aside and the copy in (a crash) is undone by //! the next start or compaction, see `recover_cut_swaps`. -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -436,33 +436,8 @@ fn compact_shard( // how many articles use each domain, as rows and inside sealed blobs say("counting domains"); - // only the ids in use: earlier compactions leave the ids sparse - let mut uses: HashMap = HashMap::new(); - { - let mut used = |d: i64| { - let n = uses.entry(d).or_insert(0); - *n = n.saturating_add(1); - }; - let mut stmt = conn.prepare("select domain from old.segments")?; - let mut rows = stmt.query([])?; - let mut n = 0usize; - while let Some(r) = rows.next()? { - used(r.get(0)?); - n += 1; - if n.is_multiple_of(STOP_EVERY) { - halt(stop, shard)?; - } - } - let mut stmt = conn.prepare("select id, blob from old.files where blob is not null")?; - let mut rows = stmt.query([])?; - while let Some(r) = rows.next()? { - halt(stop, shard)?; - for seg in unseal(shard, r.get(0)?, &r.get::<_, Vec>(1)?)? { - used(seg.domain); - } - } - } - let shared = |d: i64| d != 0 && uses.get(&d).is_some_and(|n| *n >= SHARED_AFTER); + let uses = DomainUses::count(&path, shard, stop)?; + let shared = |d: i64| -> Result { Ok(d != 0 && uses.shared(d)?) }; halt(stop, shard)?; say("copying releases"); @@ -481,7 +456,7 @@ fn compact_shard( let mut rows = stmt.query([])?; while let Some(r) = rows.next()? { let (id, suffix): (i64, String) = (r.get(0)?, r.get(1)?); - if shared(id) { + if shared(id)? { insert.execute(params![id, suffix])?; kept += 1; } else { @@ -551,12 +526,13 @@ fn compact_shard( // takes (a dropped domain's suffix made whole again) become rows let mut spilled = Vec::new(); for seg in old_blob.as_deref().map(|b| unseal(shard, id, b)).transpose()?.unwrap_or_default() { - let suffix: Option = if seg.domain != 0 && !shared(seg.domain) { + let suffix: Option = if seg.domain != 0 && !shared(seg.domain)? { suffix_of.query_row([seg.domain], |r| r.get(0)).optional()? } else { None }; - let (local, domain) = rewrite(shard, id, seg.local, seg.domain, shared(seg.domain), suffix.as_deref())?; + let (local, domain) = + rewrite(shard, id, seg.local, seg.domain, shared(seg.domain)?, suffix.as_deref())?; if local.len() > blob::MAX_LOCAL { spilled.push(Row { file_id: id, local, domain, part: seg.part, bytes: Some(seg.bytes) }); } else { @@ -766,6 +742,68 @@ fn compact_shard( Ok(Shrunk { before, after, domains_kept: kept, domains_dropped: dropped }) } +/// How many articles of a shard use each domain, as rows and inside sealed +/// blobs, counted in a database file of its own next to the shard: a shard +/// can have as many domains as a poster cares to make up, three articles +/// each, and four shards are compacted at once, soo they arent held in +/// memory. The file goes when this does. +struct DomainUses { + conn: Option, + path: PathBuf, +} + +impl DomainUses { + fn count(shard_path: &Path, shard: usize, stop: &Arc) -> Result { + let path = with_suffix(shard_path, "domains"); + remove_db(&path); + let uses = DomainUses { conn: Some(Connection::open(&path)?), path }; + let conn = uses.conn.as_ref().expect("open till dropped"); + interruptible(conn, stop)?; + conn.query_row("pragma journal_mode = off", [], |_| Ok(()))?; + conn.execute_batch( + "pragma synchronous = off; + create table uses (id integer primary key, n integer not null);", + )?; + conn.execute("attach database ? as old", [shard_path.to_string_lossy()])?; + conn.execute("insert into uses select domain, count(*) from old.segments group by domain", [])?; + halt(stop, shard)?; + let read = Connection::open_with_flags(shard_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; + let mut stmt = read.prepare("select id, blob from files where blob is not null")?; + let mut rows = stmt.query([])?; + let mut used = conn.prepare("insert into uses values (?, 1) on conflict (id) do update set n = n + 1")?; + conn.execute_batch("begin")?; + while let Some(r) = rows.next()? { + halt(stop, shard)?; + for seg in unseal(shard, r.get(0)?, &r.get::<_, Vec>(1)?)? { + used.execute([seg.domain])?; + } + } + conn.execute_batch("commit")?; + drop(used); + Ok(uses) + } + + /// whether enough articles use `domain` for it to stay + fn shared(&self, domain: i64) -> Result { + let n: Option = self + .conn + .as_ref() + .expect("open till dropped") + .prepare_cached("select n from uses where id = ?")? + .query_row([domain], |r| r.get(0)) + .optional()?; + Ok(n.is_some_and(|n| n >= SHARED_AFTER as i64)) + } +} + +impl Drop for DomainUses { + fn drop(&mut self) { + // closed first: an open file cant be removed everywhere + drop(self.conn.take()); + remove_db(&self.path); + } +} + /// the files table's columns, blob last const FILE_COLUMNS: &str = "id, release_id, filename, subject, subject_part, subject_mid, expected, file_total, seen, touched_at, blob"; @@ -828,10 +866,10 @@ struct Row { } /// the next row of `select file_id, local, domain, part, bytes, suffix`, rewritten -fn next_row(shard: usize, rows: &mut rusqlite::Rows, shared: &dyn Fn(i64) -> bool) -> Result> { +fn next_row(shard: usize, rows: &mut rusqlite::Rows, shared: &dyn Fn(i64) -> Result) -> Result> { let Some(r) = rows.next()? else { return Ok(None) }; let (file_id, domain, suffix): (i64, i64, Option) = (r.get(0)?, r.get(2)?, r.get(5)?); - let (local, domain) = rewrite(shard, file_id, r.get(1)?, domain, shared(domain), suffix.as_deref())?; + let (local, domain) = rewrite(shard, file_id, r.get(1)?, domain, shared(domain)?, suffix.as_deref())?; Ok(Some(Row { file_id, local, domain, part: r.get(3)?, bytes: r.get(4)? })) } @@ -1169,6 +1207,34 @@ mod tests { assert_eq!(domains(main), 120 + 5, "every made up domain has a row, ngPost one per shard used"); } + #[test] + fn domain_uses_are_counted_on_disk_and_the_file_goes_with_them() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + for path in store::shard_paths(&main) { + let conn = db::open_at(&path).unwrap(); + checkpoint(&conn).unwrap(); + let rows: Vec<(i64, i64)> = conn + .prepare("select domain, count(*) from segments group by domain") + .unwrap() + .query_map([], |r| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .unwrap(); + drop(conn); + let file = with_suffix(&path, "domains"); + let uses = DomainUses::count(&path, 0, &no_stop()).unwrap(); + assert!(file.exists(), "counted in a file, not in memory"); + for (d, n) in rows { + assert_eq!(uses.shared(d).unwrap(), n >= SHARED_AFTER as i64, "domain {d} used {n} times"); + } + assert!(!uses.shared(i64::MAX).unwrap(), "an unused domain isnt shared"); + drop(uses); + assert!(!file.exists(), "removed once done with"); + } + } + #[test] fn compacting_drops_single_use_domains_repacks_seals_and_keeps_every_nzb() { let dir = tempfile::tempdir().unwrap(); @@ -1193,6 +1259,7 @@ mod tests { } for path in store::shard_paths(&main) { assert!(!with_suffix(&path, "precompact").exists(), "originals removed once all are done"); + assert!(!with_suffix(&path, "domains").exists(), "the domain counts removed"); let mode: String = db::open_at(&path).unwrap().query_row("pragma journal_mode", [], |r| r.get(0)).unwrap(); assert_eq!(mode, "wal"); } From 50844256a890603e24ac78b33a2c6308adff213d Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:41:40 -0500 Subject: [PATCH 153/159] A lone server with an explicit key keeps its cursors under that key The plain group cursor stays only for a lone unkeyed server: one left over from a server since removed would have the keyed one skip ranges. Co-Authored-By: Claude Opus 5.5 --- src/indexer.rs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/indexer.rs b/src/indexer.rs index cd8b4457..a40434a5 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -379,14 +379,15 @@ pub struct PassContext { /// Article numbers differ between providers, soo with several servers the /// cursors are kept per server as `group@host` (`Pool::host`, see -/// `server_keys`). One server keeps the plain -/// group name like before. +/// `server_keys`). One server keeps the plain group name like before, unless +/// it has an explicit `#key`: that names it wherever it is in the list, and a +/// plain cursor may be another server's left from before. fn cursor_key(pool: &Pool, server: usize, group: &str) -> String { - if pool.len() <= 1 { - return group.to_string(); - } // only the host (and port) is case-insensitive, an explicit `#key` isnt let host = pool.host(server); + if pool.len() <= 1 && !host.contains('#') { + return group.to_string(); + } match host.split_once('#') { Some((h, k)) => format!("{group}@{}#{k}", h.to_lowercase()), None => format!("{group}@{}", host.to_lowercase()), @@ -401,7 +402,7 @@ async fn load_cursors( server: usize, ) -> Result> { let (key, group) = (key.to_string(), group.to_string()); - let legacy = if ctx.pool.len() <= 1 { Vec::new() } else { ctx.pool.legacy_keys(server) }; + let legacy = if key == group { Vec::new() } else { ctx.pool.legacy_keys(server) }; on_db(db, move |conn| cursors_or_adopted(conn, &key, &group, server == 0, &legacy)).await } @@ -1743,6 +1744,16 @@ mod tests { assert_eq!(cursor_key(&pool, 2, "g"), "g@b.example"); } + /// a lone server keeps the plain group name, unless it has a `#key` + #[test] + fn a_lone_keyed_server_keeps_its_keyed_cursor() { + let plain = crate::config::UsenetServer::new("A.Example", "u", "p", 563); + let mut keyed = crate::config::UsenetServer::new("B.Example", "u", "p", 563); + keyed.key = Some("Block".into()); + assert_eq!(cursor_key(&Pool::new(&[plain]), 0, "g"), "g"); + assert_eq!(cursor_key(&Pool::new(&[keyed]), 0, "g"), "g@b.example#Block"); + } + #[test] fn each_speculative_window_has_to_hold_enough_on_its_own() { let rt = tokio::runtime::Builder::new_current_thread().build().unwrap(); From bb7199a3ab62487bfccabac0f0d3a6b35f529bd5 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:45:04 -0500 Subject: [PATCH 154/159] The compaction check compares a sample of releases by a digest of their articles, none held A loose file can have any number of articles, and both the original's and the copy's were held at once. Each is now a count and a sum of row hashes, whatever their order; a copy that lost second copies of a message-id is worked out in a database file of its own. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 124 +++++++++++++++++++++++++++++++++++++++++++++---- src/search.rs | 2 +- src/store.rs | 33 ++++++++----- 3 files changed, 137 insertions(+), 22 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 9894e2af..a494643a 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -960,22 +960,69 @@ fn check(original: &Path, copy: &Path, shard: usize, copied: i64, copies: i64, s ) .ok(); let Some(id) = found else { continue }; - let (a, b) = (store::articles(&old, id)?, store::articles(&new, id)?); - if a != b && !(copies > 0 && same_but_copies(&a, &b)) { + if digest(&old, id)? != digest(&new, id)? && !(copies > 0 && same_but_copies(&old, &new, id, copy)?) { bail!("shard {shard}: release {id} reads back differently from the copy; the original was kept"); } } Ok(()) } -/// `copy` is `original` with only rows dropped that were a second copy of a -/// message-id (the one kept is one of the original's). -fn same_but_copies(original: &[crate::search::ArticleRow], copy: &[crate::search::ArticleRow]) -> bool { - fn ids(rows: &[crate::search::ArticleRow]) -> HashSet<&str> { - rows.iter().map(|r| r.message_id.as_str()).collect() - } - let kept = ids(copy); - kept.len() == copy.len() && kept == ids(original) && copy.iter().all(|r| original.contains(r)) +/// A 128 bit hash of an article +fn row_hash(row: &crate::search::ArticleRow) -> u128 { + use std::hash::{DefaultHasher, Hash, Hasher}; + let half = |salt: u8| { + let mut h = DefaultHasher::new(); + (salt, row).hash(&mut h); + h.finish() as u128 + }; + half(0) << 64 | half(1) +} + +/// Release `id`'s articles as how many and the sum of their hashes: the +/// same whatever order they come in, and none held (a loose file can have +/// any number) +fn digest(conn: &Connection, id: i64) -> Result<(i64, u128)> { + let (mut n, mut sum) = (0i64, 0u128); + store::each_article(conn, id, &mut |row| { + n += 1; + sum = sum.wrapping_add(row_hash(&row)); + Ok(()) + })?; + Ok((n, sum)) +} + +/// Release `id` reads back from `copy` the way it does from `original` with +/// only rows dropped that were a second copy of a message-id (the one kept is +/// one of the original's). Worked out in a database file next to `copy_path` +/// rather than in memory, removed after. +fn same_but_copies(original: &Connection, copy: &Connection, id: i64, copy_path: &Path) -> Result { + let path = with_suffix(copy_path, "check"); + remove_db(&path); + let same = (|| -> Result { + let scratch = Connection::open(&path)?; + scratch.query_row("pragma journal_mode = off", [], |_| Ok(()))?; + scratch.execute_batch( + "pragma synchronous = off; + create table a (id text not null, h blob not null); + create table b (id text not null, h blob not null); + begin;", + )?; + for (conn, table) in [(original, "a"), (copy, "b")] { + let mut insert = scratch.prepare(&format!("insert into {table} values (?, ?)"))?; + store::each_article(conn, id, &mut |row| { + insert.execute(params![row.message_id, row_hash(&row).to_be_bytes()])?; + Ok(()) + })?; + } + scratch.execute_batch("commit")?; + let none = |sql: &str| -> Result { Ok(!scratch.prepare(sql)?.exists([])?) }; + Ok(none("select 1 from b group by id having count(*) > 1")? + && none("select id from a except select id from b")? + && none("select id from b except select id from a")? + && none("select h from b except select h from a")?) + })(); + remove_db(&path); + same } #[cfg(test)] @@ -1207,6 +1254,63 @@ mod tests { assert_eq!(domains(main), 120 + 5, "every made up domain has a row, ngPost one per shard used"); } + /// The sample is compared by digest, order aside; a copy that lost a + /// second copy of a message-id is told apart from one that reads back + /// differently in a file of its own, removed after. + #[test] + fn the_check_compares_digests_and_works_copies_out_on_disk() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + let (shard, path) = store::shard_paths(&main) + .into_iter() + .enumerate() + .find(|(_, p)| store::article_count(&db::open_at(p).unwrap(), "main").unwrap() > 0) + .unwrap(); + checkpoint(&db::open_at(&path).unwrap()).unwrap(); + let copy = with_suffix(&path, "compact"); + std::fs::copy(&path, ©).unwrap(); + let n = store::article_count(&db::open_at(&path).unwrap(), "main").unwrap(); + let checks = |copies: i64| { + let r = check(&path, ©, shard, n, copies, &no_stop()); + assert!(!with_suffix(©, "check").exists(), "no scratch file left"); + r + }; + checks(0).unwrap(); + + // the original with a second copy of a message-id, stored whole next to its packed one + let conn = db::open_at(&path).unwrap(); + let (file_id, local, domain, part, bytes, suffix): (i64, Vec, i64, Option, i64, String) = conn + .query_row( + "select s.file_id, s.local, s.domain, s.part, s.bytes, d.suffix + from segments s join domains d on d.id = s.domain limit 1", + [], + |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)), + ) + .unwrap(); + let (whole, none) = rewrite(shard, file_id, local, domain, false, Some(&suffix)).unwrap(); + assert_eq!(none, 0); + conn.execute( + "insert into segments (file_id, local, domain, part, bytes) values (?, ?, 0, ?, ?)", + params![file_id, whole, part, bytes], + ) + .unwrap(); + drop(conn); + checks(1).unwrap(); + + // a copy whose article reads back differently + let conn = db::open_at(©).unwrap(); + conn.execute( + "update segments set bytes = bytes + 1 + where (file_id, local, domain) = (select file_id, local, domain from segments limit 1)", + [], + ) + .unwrap(); + drop(conn); + let e = checks(1).unwrap_err().to_string(); + assert!(e.contains("reads back differently"), "{e}"); + } + #[test] fn domain_uses_are_counted_on_disk_and_the_file_goes_with_them() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/search.rs b/src/search.rs index 0f48972c..bda7eca0 100644 --- a/src/search.rs +++ b/src/search.rs @@ -17,7 +17,7 @@ pub struct ReleaseRow { } /// One article of a release, joined with its release's poster/date. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct ArticleRow { pub message_id: String, pub filename: Option, diff --git a/src/store.rs b/src/store.rs index 2fe183e4..5001d822 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1536,6 +1536,18 @@ pub fn save(main: &Path, releases: &[Release]) -> Result<()> { /// A release's articles, ordered by filename then part (ties by message-id), /// for building its NZB. `conn` has the shards attached. pub fn articles(conn: &Connection, release_id: i64) -> Result> { + let mut rows = Vec::new(); + each_article(conn, release_id, &mut |row| { + rows.push(row); + Ok(()) + })?; + rows.sort_by(|a, b| (&a.filename, a.part, &a.message_id).cmp(&(&b.filename, b.part, &b.message_id))); + Ok(rows) +} + +/// A release's articles one at a time, in no particular order, none held. +/// `conn` has the shards attached. +pub fn each_article(conn: &Connection, release_id: i64, each: &mut dyn FnMut(ArticleRow) -> Result<()>) -> Result<()> { let s = shard_of_id(release_id); // rows and blobs from one snapshot: a file sealed between two separate // reads would show its articles twice (or not at all). a caller already @@ -1560,7 +1572,9 @@ pub fn articles(conn: &Connection, release_id: i64) -> Result> { posted_date: r.get(8)?, }) })?; - let mut rows: Vec = rows.collect::>()?; + for row in rows { + each(row?)?; + } // sealed files: their blobs, next to any rows that came after sealing let mut sealed = conn.prepare(&format!( @@ -1568,22 +1582,20 @@ pub fn articles(conn: &Connection, release_id: i64) -> Result> { from s{s}.files f join s{s}.releases r on r.id = f.release_id where f.release_id = ? and f.blob is not null" ))?; + let mut suffix_of = conn.prepare(&format!("select suffix from s{s}.domains where id = ?"))?; + // per blob, soo what is held stays within what one blob takes let mut suffixes: HashMap> = HashMap::new(); let mut blob_rows = sealed.query([release_id])?; while let Some(r) = blob_rows.next()? { + suffixes.clear(); let blob: Vec = r.get(0)?; let filename: String = r.get(1)?; for seg in crate::blob::decode(&blob).map_err(blob_error)? { let suffix = match suffixes.entry(seg.domain) { Entry::Occupied(e) => e.into_mut(), - Entry::Vacant(e) => e.insert( - conn.query_row(&format!("select suffix from s{s}.domains where id = ?"), [seg.domain], |r| { - r.get(0) - }) - .optional()?, - ), + Entry::Vacant(e) => e.insert(suffix_of.query_row([seg.domain], |r| r.get(0)).optional()?), }; - rows.push(ArticleRow { + each(ArticleRow { message_id: decode(&seg.local, suffix.as_deref()), filename: (!filename.is_empty()).then(|| filename.clone()), part: seg.part, @@ -1592,11 +1604,10 @@ pub fn articles(conn: &Connection, release_id: i64) -> Result> { subject: r.get(3)?, poster: r.get(4)?, posted_date: r.get(5)?, - }); + })?; } } - rows.sort_by(|a, b| (&a.filename, a.part, &a.message_id).cmp(&(&b.filename, b.part, &b.message_id))); - Ok(rows) + Ok(()) } /// articles in shard `schema` (`s3`, or `main` for a shard opened on its From 561c277b6477e3082b742b3054d4008601ab5f9b Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:18:37 -0500 Subject: [PATCH 155/159] The domain count lets go of the original shard before the swap renames it Its database file attached the shard and stayed open till the end of the compaction, and Windows wont rename an open file: it is detached once counted, and the count is dropped before the check. Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/compact.rs b/src/compact.rs index a494643a..6c4bdf4b 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -715,6 +715,9 @@ fn compact_shard( insert into releases_fts(releases_fts) values('rebuild');", )?; drop(conn); + // nothing holds the original open past here: the swap renames it, and + // Windows wont rename an open file + drop(uses); { let conn = db::open_at(©)?; interruptible(&conn, stop)?; @@ -766,6 +769,10 @@ impl DomainUses { )?; conn.execute("attach database ? as old", [shard_path.to_string_lossy()])?; conn.execute("insert into uses select domain, count(*) from old.segments group by domain", [])?; + // the shard isnt kept open by this file's connection: the swap renames + // it, and Windows wont rename an open file + conn.execute_batch("detach database old")?; + debug_assert_eq!(attached(conn), ["main"]); halt(stop, shard)?; let read = Connection::open_with_flags(shard_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?; let mut stmt = read.prepare("select id, blob from files where blob is not null")?; @@ -804,6 +811,11 @@ impl Drop for DomainUses { } } +/// the schemas attached to `conn`, `main` first +fn attached(conn: &Connection) -> Vec { + conn.prepare("pragma database_list").and_then(|mut s| s.query_map([], |r| r.get(1))?.collect()).unwrap_or_default() +} + /// the files table's columns, blob last const FILE_COLUMNS: &str = "id, release_id, filename, subject, subject_part, subject_mid, expected, file_total, seen, touched_at, blob"; From 4bae787bc5cf2ab020d58a7e97a9cb9ce0c48912 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:28:36 -0500 Subject: [PATCH 156/159] A wipe takes a compaction's scratch databases too, the domain counts and the release check Co-Authored-By: Claude Opus 5.5 --- src/db.rs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/db.rs b/src/db.rs index ad0214cf..92eb624e 100644 --- a/src/db.rs +++ b/src/db.rs @@ -150,7 +150,8 @@ pub fn create_db_holding(path: &Path) -> anyhow::Result> { } /// Settings > wipe: every shard, with their sidecars and what a compaction -/// leaves (`.compact.db`, `.precompact.db`), a conversion's `atlas.old.db` +/// leaves (`.compact.db`, `.precompact.db`, and its scratch `.domains.db` +/// and `.compact.check.db`), a conversion's `atlas.old.db` /// and `atlas.new.db`, then the main database. Under /// the exclusive compaction lock, soo refused (`Busy`) while the indexer, a /// write from outside it or a compaction has the database. Leaves nothing to @@ -162,7 +163,10 @@ pub fn wipe(main: &Path) -> anyhow::Result<()> { let _exclusive = crate::compact::Lock::take(main)?; let mut dbs = Vec::new(); for shard in store::shard_paths(main) { - dbs.push(crate::compact::with_suffix(&shard, "compact")); + let copy = crate::compact::with_suffix(&shard, "compact"); + dbs.push(crate::compact::with_suffix(©, "check")); + dbs.push(copy); + dbs.push(crate::compact::with_suffix(&shard, "domains")); dbs.push(crate::compact::with_suffix(&shard, "precompact")); dbs.push(shard); } @@ -731,6 +735,14 @@ mod tests { let leftovers = [ crate::compact::with_suffix(&shard, "compact"), crate::compact::with_suffix(&shard, "precompact"), + // a compaction's scratch: the domain counts and a release check + crate::compact::with_suffix(&shard, "domains"), + PathBuf::from(format!("{}-wal", crate::compact::with_suffix(&shard, "domains").display())), + crate::compact::with_suffix(&crate::compact::with_suffix(&shard, "compact"), "check"), + PathBuf::from(format!( + "{}-journal", + crate::compact::with_suffix(&crate::compact::with_suffix(&shard, "compact"), "check").display() + )), PathBuf::from(format!("{}-wal", shard.display())), PathBuf::from(format!("{}-shm", shard.display())), ]; From 05be498cd5f80b5ab7cdcd0ef4d14655e80a65d5 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:34:56 -0500 Subject: [PATCH 157/159] The plain cursors go only to the server that kept them, recorded while it was alone Co-Authored-By: Claude Opus 5.5 --- src/bg_indexer.rs | 8 ++++- src/indexer.rs | 91 +++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 92 insertions(+), 7 deletions(-) diff --git a/src/bg_indexer.rs b/src/bg_indexer.rs index 974da910..b1cf0167 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -733,7 +733,13 @@ async fn run_servers( }); let db = match db::open().and_then(|conn| db::tune_for_writing(&conn).map(|_| conn)) { - Ok(conn) => shared_db(conn), + Ok(conn) => { + // before any pass: whose the plain cursors are (see claim_plain_cursors) + if let Err(e) = crate::indexer::claim_plain_cursors(&conn, &sched.ctx.pool) { + ui::warn(&format!("couldnt record whose the group cursors are: {e:#}")); + } + shared_db(conn) + } Err(e) => { ui::error(&format!("couldnt open database: {e}")); return false; diff --git a/src/indexer.rs b/src/indexer.rs index a40434a5..3964ded9 100644 --- a/src/indexer.rs +++ b/src/indexer.rs @@ -394,6 +394,41 @@ fn cursor_key(pool: &Pool, server: usize, group: &str) -> String { } } +/// Whose the plain (identity-less) cursors are, in the main database's +/// meta: they hold article numbers of one provider, and the order of the +/// servers says nothing about which. +const PLAIN_CURSORS_OF: &str = "plain_cursors_of"; + +/// With one indexing server the plain cursors are its own: recorded, soo +/// once more servers are added only it adopts them. A lone server under the +/// plain name is the one writing them, soo it takes them over from whoever +/// had them before. With several servers and nothing recorded (cursors kept +/// by a build from before) they are no one's: each server starts fresh. +pub fn claim_plain_cursors(conn: &Connection, pool: &Pool) -> Result<()> { + let indexing = pool.indexing_servers(); + let [only] = indexing.as_slice() else { return Ok(()) }; + let writes_plain = cursor_key(pool, *only, "g") == "g"; + if writes_plain || plain_cursors_owner(conn)?.is_none() { + conn.execute( + "insert or replace into main.meta (key, value) values (?, ?)", + rusqlite::params![PLAIN_CURSORS_OF, pool.host(*only)], + )?; + } + Ok(()) +} + +fn plain_cursors_owner(conn: &Connection) -> Result> { + use rusqlite::OptionalExtension; + Ok(conn + .query_row("select cast(value as text) from main.meta where key = ?", [PLAIN_CURSORS_OF], |r| r.get(0)) + .optional()?) +} + +/// whether the server named `host` (`Pool::host`) kept the plain cursors +fn owns_plain_cursors(conn: &Connection, host: &str) -> Result { + Ok(plain_cursors_owner(conn)?.as_deref() == Some(host)) +} + async fn load_cursors( ctx: &PassContext, db: &Db, @@ -403,19 +438,24 @@ async fn load_cursors( ) -> Result> { let (key, group) = (key.to_string(), group.to_string()); let legacy = if key == group { Vec::new() } else { ctx.pool.legacy_keys(server) }; - on_db(db, move |conn| cursors_or_adopted(conn, &key, &group, server == 0, &legacy)).await + let host = ctx.pool.host(server); + on_db(db, move |conn| { + let owns_plain = key != group && owns_plain_cursors(conn, &host)?; + cursors_or_adopted(conn, &key, &group, owns_plain, &legacy) + }) + .await } /// The cursors saved under `key`, else adopted: saved under one of the /// server's `legacy` keys (what an earlier build named it, see /// `nntp::legacy_server_keys`) they move to `key`, once; saved under the -/// plain group name (before a second server was added) they belong to the -/// first server +/// plain group name (before a second server was added) only by the server +/// that kept them (`owns_plain`, see `claim_plain_cursors`) fn cursors_or_adopted( conn: &Connection, key: &str, group: &str, - first_server: bool, + owns_plain: bool, legacy: &[String], ) -> Result> { if let Some(state) = db::get_group_state(conn, key)? { @@ -430,7 +470,7 @@ fn cursors_or_adopted( } } - if first_server + if owns_plain && key != group && let Some(state) = db::get_group_state(conn, group)? { @@ -1886,11 +1926,50 @@ mod tests { assert_eq!(db::get_group_state(&conn, "g@a.example").unwrap(), Some(state)); // nothing to adopt: nothing made up assert_eq!(cursors_or_adopted(&conn, "g@b.example", "g", false, &[]).unwrap(), None); - // the plain group name still goes to the first server + // the plain group name goes to the server that kept it db::save_group_state(&conn, "h", state).unwrap(); assert_eq!(cursors_or_adopted(&conn, "h@a.example", "h", true, &legacy).unwrap(), Some(state)); } + /// a lone server's plain cursors are its own: adding a server that sorts + /// before it doesnt hand them to the new one + #[test] + fn plain_cursors_stay_with_the_server_that_kept_them() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let conn = db::open_at(&main).unwrap(); + let state = db::GroupState { live_cursor: 900, backfill_cursor: 500 }; + db::save_group_state(&conn, "g", state).unwrap(); + + let old = crate::config::UsenetServer::new("old.example", "u", "p", 563); + let lone = Pool::new(std::slice::from_ref(&old)); + claim_plain_cursors(&conn, &lone).unwrap(); + assert_eq!(cursor_key(&lone, 0, "g"), "g", "still the plain name on its own"); + + // a new server, ahead of it by priority + let mut new = crate::config::UsenetServer::new("new.example", "u", "p", 563); + new.priority = 0; + let both = Pool::new(&[new, old]); + claim_plain_cursors(&conn, &both).unwrap(); + assert_eq!(both.host(0), "new.example", "the new one sorts first"); + let adopted = |i: usize| { + let key = cursor_key(&both, i, "g"); + cursors_or_adopted(&conn, &key, "g", owns_plain_cursors(&conn, &both.host(i)).unwrap(), &[]).unwrap() + }; + assert_eq!(adopted(0), None, "the new server starts fresh"); + assert_eq!(adopted(1), Some(state), "the old one keeps its place"); + + // plain cursors from before anyone was recorded, with two servers: no one's + db::create_db_at(&dir.path().join("other.db")).unwrap(); + let conn2 = db::open_at(&dir.path().join("other.db")).unwrap(); + db::save_group_state(&conn2, "g", state).unwrap(); + claim_plain_cursors(&conn2, &both).unwrap(); + for i in 0..2 { + assert!(!owns_plain_cursors(&conn2, &both.host(i)).unwrap(), "ambiguous, left alone"); + } + } + #[test] fn what_a_server_keeps_is_remembered_by_its_host_not_its_place_in_the_pool() { let states = RunStates::default(); From 929c37f85cfd0419f22b8b8aff693fcf3337b499 Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:40:12 -0500 Subject: [PATCH 158/159] A copies only file that goes takes the release's index with it once one file is left Co-Authored-By: Claude Opus 5.5 --- src/store.rs | 43 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/src/store.rs b/src/store.rs index 5001d822..67c058be 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1449,11 +1449,20 @@ impl ShardWriter { } } else { // a file just made whose articles all were in other files - tx.prepare_cached( - "delete from files where id = ? and touched_at is null and blob is null - and not exists (select 1 from segments where file_id = ?)", - )? - .execute(params![f.id, f.id])?; + let gone = tx + .prepare_cached( + "delete from files where id = ? and touched_at is null and blob is null + and not exists (select 1 from segments where file_id = ?)", + )? + .execute(params![f.id, f.id])?; + // down to one file its index is no longer kept up (see + // `others` above): dropped, to be made again by the next file + let others = tx + .prepare_cached("select 1 from files where release_id = ? limit 1 offset 1")? + .exists([release_id])?; + if gone > 0 && !others { + tx.prepare_cached("delete from release_ids where release_id = ?")?.execute([release_id])?; + } } } profile::ARTICLES.add_since(t); @@ -2780,6 +2789,30 @@ mod tests { assert_eq!(loose, 0); } + /// A second file made only of copies goes again, and with it the index it + /// started: left behind, the sole file's later articles would never be put + /// in it, and a copy of one of them in a new file would go unnoticed. + #[test] + fn a_copies_only_file_leaves_no_stale_index_behind() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + db::create_db_at(&main).unwrap(); + let shard = shard_path(&main, shard_of("alt.binaries.t")); + let conn = db::open_at(&shard).unwrap(); + let count = || -> i64 { conn.query_row("select count(*) from segments", [], |r| r.get(0)).unwrap() }; + save(&main, &[one_file_release("a.rar", &["", ""])]).unwrap(); + save(&main, &[one_file_release("b.rar", &[""])]).unwrap(); + let files: i64 = conn.query_row("select count(*) from files", [], |r| r.get(0)).unwrap(); + assert_eq!(files, 1, "b.rar was only a copy"); + let indexed: i64 = conn.query_row("select count(*) from release_ids", [], |r| r.get(0)).unwrap(); + assert_eq!(indexed, 0, "and its index went with it"); + + save(&main, &[one_file_release("a.rar", &[""])]).unwrap(); + let before = count(); + save(&main, &[one_file_release("b.rar", &[""])]).unwrap(); + assert_eq!(count(), before, "a copy of a later article is still found"); + } + /// A release saved before the index (an upgraded shard) gets it the /// first time it's written to, and copies across its files are found. #[test] From f7a771fcd5fdbd0d036881a4a79b6865f6a4390a Mon Sep 17 00:00:00 2001 From: xbmc4lyfe <273732874+xbmc4lyfe@users.noreply.github.com> Date: Tue, 6 Oct 2026 10:52:24 -0500 Subject: [PATCH 159/159] Opening the main database never makes one, and an empty one made in a conversion's swap is taken out of the way Co-Authored-By: Claude Opus 5.5 --- src/compact.rs | 2 +- src/convert.rs | 57 +++++++++++++++++++++++++++++++++++++++------ src/db.rs | 18 ++++++++++++--- src/store.rs | 4 ++-- tests/convert.rs | 60 ++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 128 insertions(+), 13 deletions(-) diff --git a/src/compact.rs b/src/compact.rs index 6c4bdf4b..aa89f05d 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -2328,7 +2328,7 @@ mod tests { fn a_checkpoint_a_reader_holds_back_is_refused() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("x.db"); - let writer = db::open_at(&path).unwrap(); + let writer = db::create_at(&path).unwrap(); writer.execute_batch("pragma journal_mode = wal; pragma wal_autocheckpoint = 0; create table t (x)").unwrap(); let reader = db::open_at(&path).unwrap(); reader.execute_batch("begin; select count(*) from t").unwrap(); diff --git a/src/convert.rs b/src/convert.rs index 456cc734..c036d86a 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -51,7 +51,45 @@ pub fn needed(main: &Path) -> bool { /// `run_alone` to finish or undo first. pub fn to_do(main: &Path) -> bool { needed(main) - || (!main.exists() && (sibling(main, "atlas.new.db").exists() || sibling(main, "atlas.old.db").exists())) + || ((!main.exists() || is_empty_interloper(main)) + && (sibling(main, "atlas.new.db").exists() || sibling(main, "atlas.old.db").exists())) +} + +/// An atlas.db with nothing in it: no bytes, or not a single table. What a +/// read made (a build that still made one on opening) in the moment a +/// conversion's swap had no main database. Looked at read only, and closed +/// again before this returns (it may be removed next, which Windows refuses +/// for a file still open). +pub fn is_empty_interloper(main: &Path) -> bool { + match std::fs::metadata(main) { + Ok(m) if m.len() == 0 => return true, + Ok(m) if m.is_file() => {} + _ => return false, + } + Connection::open_with_flags(main, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX) + .and_then(|c| c.query_row("select not exists(select 1 from sqlite_master)", [], |r| r.get::<_, bool>(0))) + .unwrap_or(false) +} + +/// Removes an empty interloper (see `is_empty_interloper`) at `main`, with +/// its sidecars. Whoever made it may still have it open: then it stays, and +/// that is the error. +fn remove_interloper(main: &Path) -> std::io::Result<()> { + std::fs::remove_file(main)?; + remove_db(main); + Ok(()) +} + +/// `rename_db(from, main)`, through an empty interloper at `main` (made in +/// the moment there was no main database): taken out, and tried again. +fn rename_into_place(from: &Path, main: &Path) -> std::io::Result<()> { + match rename_db(from, main) { + Err(e) if is_empty_interloper(main) => { + remove_interloper(main).map_err(|_| e)?; + rename_db(from, main) + } + done => done, + } } fn sibling(main: &Path, name: &str) -> PathBuf { @@ -69,7 +107,7 @@ fn remove_db(path: &Path) { /// the file) and no syncing. A crash only means converting again from the /// old database; the shards go back to WAL before the swap. fn open_for_conversion(path: &Path) -> rusqlite::Result { - let conn = db::open_at(path)?; + let conn = db::create_at(path)?; conn.query_row("pragma journal_mode = off", [], |_| Ok(()))?; conn.execute_batch( "pragma synchronous = off; @@ -180,9 +218,9 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { } // its -wal and -shm go aside with it, whatever they still hold rename_db(main, &backup).context("moving the old database aside")?; - if let Err(e) = rename_db(&new_main, main) { + if let Err(e) = rename_into_place(&new_main, main) { // the old one back, soo there is a main database to start from - let _ = rename_db(&backup, main); + let _ = rename_into_place(&backup, main); return Err(e).context("putting the new main database in place"); } @@ -201,10 +239,15 @@ pub fn run(main: &Path, progress: &dyn Fn(&str)) -> Result<(i64, i64)> { /// `atlas.old.db` back (and the next start converts again). Run under the /// exclusive lock. What it did, if anything. pub fn recover_cut_swap(main: &Path) -> Result> { + let (new_main, backup) = (sibling(main, "atlas.new.db"), sibling(main, "atlas.old.db")); if main.try_exists()? { - return Ok(None); + // an empty one made in the swap's moment is in the way: out with it + let cut = (new_main.try_exists()? && swap_ready(&new_main)) || backup.try_exists()?; + if !(cut && is_empty_interloper(main)) { + return Ok(None); + } + remove_interloper(main).with_context(|| format!("removing the empty {} in the way", main.display()))?; } - let (new_main, backup) = (sibling(main, "atlas.new.db"), sibling(main, "atlas.old.db")); if new_main.try_exists()? && swap_ready(&new_main) { rename_db(&new_main, main).context("putting the converted main database in place")?; return Ok(Some(format!( @@ -689,7 +732,7 @@ fn copy( // 1. the new main database with the cursors remove_db(&new_main); { - let conn = db::open_at(&new_main)?; + let conn = db::create_at(&new_main)?; conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; conn.execute_batch("create table groups(name TEXT PRIMARY KEY, live_cursor INTEGER, backfill_cursor INTEGER)")?; let cols: Vec = old diff --git a/src/db.rs b/src/db.rs index 92eb624e..cc6545de 100644 --- a/src/db.rs +++ b/src/db.rs @@ -30,7 +30,19 @@ pub fn open_with_shards(path: &Path) -> Result { Ok(conn) } +/// The database at `path`, which has to be there already: opening never +/// makes one. A read (search, the dashboard) during a conversion's swap, +/// with no main database for a moment, would otherwise leave an empty one +/// in the way of the new one. Only setting up makes one, see `create_at`. pub fn open_at(path: &Path) -> Result { + use rusqlite::OpenFlags; + let flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX; + set_up(Connection::open_with_flags(path, flags)?) +} + +/// The database at `path`, made (empty) when missing: for setting up +/// (`create_db_at`, a new shard), not for reads. +pub fn create_at(path: &Path) -> Result { set_up(Connection::open(path)?) } @@ -138,7 +150,7 @@ pub fn create_db() -> anyhow::Result> { pub fn create_db_holding(path: &Path) -> anyhow::Result> { // a conversion's swap cut short leaves no main database: finished or // undone first, alone (busy means someone is using the database, soo it's there) - if !path.try_exists()? + if (!path.try_exists()? || crate::convert::is_empty_interloper(path)) && let Ok(_alone) = crate::compact::Lock::take(path) && let Some(said) = crate::convert::recover_cut_swap(path)? { @@ -196,7 +208,7 @@ pub fn create_db_at(path: &Path) -> anyhow::Result<()> { if !path.try_exists()? { refuse_orphaned_shards(path)?; } - let conn = open_at(path)?; + let conn = create_at(path)?; // wal soo the indexer can write while search reads conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; @@ -698,7 +710,7 @@ mod tests { assert!(!has_old_layout(&open_at(&main).unwrap()).unwrap()); let old = dir.path().join("old.db"); - open_at(&old).unwrap().execute_batch("create table releases (id INTEGER PRIMARY KEY, name TEXT)").unwrap(); + create_at(&old).unwrap().execute_batch("create table releases (id INTEGER PRIMARY KEY, name TEXT)").unwrap(); create_db_at(&old).unwrap(); assert!(has_old_layout(&open_at(&old).unwrap()).unwrap()); assert!(!store::shard_path(&old, 0).exists(), "no shards until it is converted"); diff --git a/src/store.rs b/src/store.rs index 67c058be..543d1083 100644 --- a/src/store.rs +++ b/src/store.rs @@ -118,7 +118,7 @@ pub fn create_main(conn: &Connection) -> Result<()> { /// A shard's tables, if missing. pub fn create_shard(path: &Path) -> Result<()> { - build_shard(&db::open_at(path)?) + build_shard(&db::create_at(path)?) } /// `create_shard` on a connection the caller opened (and may have set up to @@ -2280,7 +2280,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("atlas.s0.db"); { - let conn = db::open_at(&path).unwrap(); + let conn = db::create_at(&path).unwrap(); conn.execute_batch( "create table files (id INTEGER PRIMARY KEY, release_id INTEGER NOT NULL, filename TEXT NOT NULL, subject TEXT, subject_part INTEGER, subject_mid TEXT, expected INTEGER, file_total INTEGER, diff --git a/tests/convert.rs b/tests/convert.rs index 7dd3cd45..ca1f7e20 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -473,6 +473,66 @@ fn a_swap_cut_after_the_old_database_moved_aside_is_finished_at_start() { assert_eq!(store::totals(&conn).unwrap().0, before.len() as i64); } +/// A search or the dashboard during the swap, with no main database for a +/// moment, doesnt make one: opening is not setting up. +#[test] +fn a_read_during_the_swap_makes_no_main_database() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + assert!(db::open_with_shards(&main).is_err()); + assert!(db::open_at(&main).is_err()); + assert!(!main.exists(), "nothing made in the way of the new one"); +} + +/// An empty atlas.db made in the swap's window (by a build that still made +/// one on a read) is in the way of the swap: taken out, and the swap is +/// finished (atlas.new.db ready) or the old database put back. +#[test] +fn an_empty_main_database_made_during_the_swap_is_taken_out() { + for (made_by_open, ready) in [(false, true), (true, true), (false, false), (true, false)] { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + let before = old_nzbs(&main); + db::create_db_at(&main).unwrap(); + if ready { + convert::run(&main, &|_| {}).unwrap(); + std::fs::rename(&main, dir.path().join("atlas.new.db")).unwrap(); + } else { + std::fs::rename(&main, dir.path().join("atlas.old.db")).unwrap(); + } + // the interloper: zero bytes, or a database with nothing in it + if made_by_open { + rusqlite::Connection::open(&main).unwrap().query_row("pragma journal_mode = wal", [], |_| Ok(())).unwrap(); + } else { + std::fs::write(&main, b"").unwrap(); + } + + drop(db::create_db_holding(&main).unwrap().expect("set up")); + assert!(!dir.path().join("atlas.new.db").exists()); + if ready { + assert!(!convert::needed(&main)); + let conn = db::open_with_shards(&main).unwrap(); + assert_eq!(store::totals(&conn).unwrap().0, before.len() as i64); + } else { + assert!(!dir.path().join("atlas.old.db").exists()); + assert!(convert::needed(&main), "the old database is back"); + } + } +} + +/// A main database with something in it is never taken for an interloper. +#[test] +fn a_main_database_with_tables_is_left_alone_beside_a_cut_swap() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + old_database(&main); + std::fs::copy(&main, dir.path().join("atlas.old.db")).unwrap(); + assert_eq!(convert::recover_cut_swap(&main).unwrap(), None); + assert!(dir.path().join("atlas.old.db").exists()); + assert!(convert::needed(&main), "still the same one"); +} + /// `--convert` after a swap cut short: atlas.db is missing, soo it isnt /// `needed`, yet there is work: the swap is finished, not "nothing to convert". #[test]