diff --git a/.gitignore b/.gitignore index e5d6f45c..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 @@ -66,3 +67,7 @@ __pycache__/ *.pyc mock_nntp_server.py dev_nntp_server.py + +# git worktrees for isolated work +/.worktrees/ +/.superpowers/ 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..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"] } @@ -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/README.md b/README.md index ade09b07..a9263f24 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,12 +132,15 @@ 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. | | `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. 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. @@ -150,17 +153,18 @@ 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. | +| `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. ### 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. +- **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: @@ -173,8 +177,8 @@ 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. -- 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. +- New groups, `index_mode`, `batch_size`, `request_size`, and `auto_run_compact` apply immediately. +- 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 @@ -235,11 +239,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 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 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. + +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. @@ -252,10 +262,16 @@ 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. +### Compacting a database + +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. 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. 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. @@ -279,7 +295,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 @@ -342,7 +358,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 8ec95fbc..56eabf90 100644 --- a/config.example.json +++ b/config.example.json @@ -42,6 +42,8 @@ "alt.binaries.boneless" ], "index_mode": "backfill", + "auto_run_compact": false, + "max_unsaved_headers": 500000, "api_port": 9090, "api_host": "0.0.0.0" } 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()`. 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). 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/ai.rs b/src/ai.rs index f09b9de1..d32550a6 100644 --- a/src/ai.rs +++ b/src/ai.rs @@ -128,6 +128,12 @@ 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. 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; + } let client = client_for(config); let mut saved = 0; diff --git a/src/app.rs b/src/app.rs index 26c4e39a..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); } @@ -707,11 +710,24 @@ 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; + } } + // 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 => { @@ -824,6 +840,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 c4be1901..b1cf0167 100644 --- a/src/bg_indexer.rs +++ b/src/bg_indexer.rs @@ -11,9 +11,10 @@ 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, 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; @@ -27,6 +28,12 @@ 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); +/// 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 { config.servers.iter().filter(|s| !s.host.is_empty() && !s.password.is_empty()).cloned().collect() @@ -162,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 @@ -214,11 +221,22 @@ 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(), 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, } } @@ -253,6 +271,13 @@ struct Scheduler { next: Mutex>, /// groups a worker is on right now busy: 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>, + /// 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 @@ -262,6 +287,12 @@ 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, + /// 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, } @@ -355,6 +386,35 @@ 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) => {} + // 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); + } + 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(); @@ -386,19 +446,152 @@ 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); } } +/// 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 { + // 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: 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; + } + + let oldest = sched.ctx.states.kept_days(&host); + match crate::indexer::claim_chunk(db, host, groups, oldest).await { + Ok(chunk) => chunk, + Err(e) => { + ui::error(&format!("couldnt claim a day chunk: {e}")); + None + } + } +} + +/// A split group whose day chunks are done for an idle worker on `server` +/// to sweep (see `indexer::run_sweep`): one this server is not the home of +/// and hasnt swept, none while another of its workers sweeps. +async fn take_sweep(sched: &Scheduler, server: usize, db: &Db) -> 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 +} + +/// What a worker does next. +enum Work { + Group(String), + Chunk(crate::chunks::Claim), + Sweep(String), +} + +/// 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. `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)); + } + 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. /// 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 Some(group) = sched.take_group(server) else { - nap(Duration::from_secs(1), || sched.stopping()).await; - continue; + 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 + 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; + } }; let settings = sched.settings.read().unwrap().clone(); @@ -414,9 +607,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, 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; @@ -426,12 +619,20 @@ 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; } + 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(); @@ -452,6 +653,28 @@ async fn watch_config(sched: Arc, servers: Vec) { } } +/// 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()); + // 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).max(sched.compact_after.unwrap_or(UNIX_EPOCH)); + while !sched.stopping() { + 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); + 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) { @@ -466,14 +689,16 @@ 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), 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(); let plan = plan_workers(config); @@ -493,19 +718,31 @@ async fn run_servers( workers, next: Mutex::new(HashMap::new()), 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()), stats, wind_down: AtomicBool::new(false), + compact_due: AtomicBool::new(false), + compact_after, + auto_compact: AtomicBool::new(config.auto_run_compact), passes: AtomicUsize::new(0), }); 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; + return false; } }; @@ -521,6 +758,7 @@ async fn run_servers( } tasks.spawn(watch_config(sched.clone(), servers)); tasks.spawn(report(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() { @@ -531,15 +769,90 @@ 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) +} + +/// 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. 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(); + 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, &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 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:#}")); + stats.lock().unwrap().error_count += 1; + } + Err(e) => { + ui::error(&format!("auto compaction stopped: {e}")); + stats.lock().unwrap().error_count += 1; + } + } + + // 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 Compacted::ShardMissing; + } + + if !stopped && let Ok(conn) = db::open_at(&main) { + let _ = crate::store::set_meta(&conn, "last_compact", chrono::Utc::now().timestamp()); + } + Compacted::Ran } -async fn supervise(stop: Arc, stats: Arc>) { +/// Index until stopping. Returns the exit code: not 0 when a compaction held +/// 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(); + // 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 = writing; + let mut started = false; 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; }; @@ -549,7 +862,24 @@ async fn supervise(stop: Arc, stats: Arc>) { break; } - let pool = Arc::new(Pool::new(&servers)); + 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).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 { @@ -560,14 +890,28 @@ 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(), compact_after).await; 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), + Compacted::ShardMissing => break, + } + } } + 0 } 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; }; @@ -581,32 +925,43 @@ pub fn run() -> i32 { return 1; } - if let Err(e) = db::create_db() { - 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 - 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(_) => {} + // 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)) => match crate::compact::refuse_unresolved_backups(&paths::database()) { + Ok(()) => held, Err(e) => { - ui::error(&format!("couldnt convert the database, nothing was changed: {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); + return 1; } - if let Err(e) = db::create_db() { - ui::error(&format!("couldnt open the converted database: {e}")); + 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 + let main = paths::database(); + 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)); @@ -616,12 +971,36 @@ 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 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 { + 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() { @@ -648,9 +1027,133 @@ 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(), writing)); + if code != 0 { + return code; + } write_status(false, "", &config.index_mode, false, "stopped", false, 0); 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"); + } + + fn scheduler(pool: Pool, groups: Vec) -> Scheduler { + 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(groups), + 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), + } + } + + /// 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_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!(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, 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, 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")); + }); + } +} diff --git a/src/blob.rs b/src/blob.rs new file mode 100644 index 00000000..c57204d7 --- /dev/null +++ b/src/blob.rs @@ -0,0 +1,227 @@ +//! 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 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))); + 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> { + parse(&zstd::stream::decode_all(blob)?, usize::MAX) +} + +/// 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 +/// 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; + 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)? { + 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 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 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![ + 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/chunks.rs b/src/chunks.rs new file mode 100644 index 00000000..e91ac095 --- /dev/null +++ b/src/chunks.rs @@ -0,0 +1,680 @@ +//! 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; + +/// 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`), 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 ( + grp TEXT NOT NULL, + day INTEGER NOT NULL, + state INTEGER NOT NULL, + server TEXT, + claimed_at INTEGER, + done_at INTEGER, + primary key (grp, day) + ) without rowid; + create table if not exists backfill_deepest ( + grp TEXT PRIMARY KEY, + 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; + 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, + reach INTEGER NOT NULL, + days INTEGER NOT NULL, + articles INTEGER NOT NULL + ) without rowid;", + )?; + add_column(conn, "backfill_chunks", "done_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. +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(&format!("alter table {table} add column {column} INTEGER")) { + // the indexer and the menu can both add it at once + Err(_) if has()? => Ok(()), + r => r, + } +} + +/// 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 tx = conn.unchecked_transaction()?; + 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..=newest_day).rev() { + added += insert.execute(params![group, day, PENDING])?; + } + } + tx.commit()?; + Ok(added) +} + +/// 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`). +/// 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 { + 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)) + .optional()? + .flatten(); + if since.is_none_or(|since| oldest_at >= since) { + 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])?; + } + } + 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 in ({DONE}, {CLAIMED})" + ), + 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])?; + // 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) +} + +/// 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 +/// 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]) +} + +/// 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> { + if groups.is_empty() { + return Ok(None); + } + let rows = vec!["(?, ?)"; groups.len()].join(", "); + let sql = format!( + "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::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()?; + Ok(found.map(|(group, day)| Claim { group, day, server: host.to_string(), claimed_at: now })) +} + +/// 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 = ?, done_at = ? + where grp = ? and day = ? and state = {CLAIMED} and server = ? and claimed_at = ?" + ), + params![DONE, now, claim.group, claim.day, claim.server, claim.claimed_at], + )?; + Ok(n > 0) +} + +/// 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(n > 0) +} + +/// (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)?)) + }) +} + +/// 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)) +} + +/// 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> { + 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`, 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(()) +} + +/// 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. +pub fn forget_deepest(conn: &Connection, group: &str, server: &str) -> Result<()> { + conn.execute("delete from backfill_deepest where grp = ? and server = ?", [group, server])?; + 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) +} + +/// 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])?) +} + +/// 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`). +/// `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(()) +} + +/// 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")? + .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 + } + + /// 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); + } + + #[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", 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)); + 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) + } + + #[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(), i64::MIN)]; + + 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, 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)); + assert_eq!(claim(&c, &groups, "a", 1000).unwrap(), None); + 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 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)); + } + + /// 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", 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"); + + 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"); + } + + /// 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(); + 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(); + add(&c, "g", 5, 5).unwrap(); + 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!(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(); + 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, done_at + 60).unwrap()); + let row = |c: &Connection| { + 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()), 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] + fn only_listed_groups_and_unsplit_groups() { + let c = conn(); + add(&c, "g", 5, 5).unwrap(); + 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!(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] + 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(), i64::MIN)]; + 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(|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(); + assert_eq!(claim(&c_c, &groups, "c", 1000).unwrap(), None); + } +} diff --git a/src/compact.rs b/src/compact.rs index e1e8e314..aa89f05d 100644 --- a/src/compact.rs +++ b/src/compact.rs @@ -4,19 +4,31 @@ //! - 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) //! //! 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. 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::collections::HashSet; 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}; -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}; @@ -27,7 +39,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")) } @@ -38,10 +51,193 @@ 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. +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 { + 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. +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())); + 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) } +/// `atlas.compacting` next to `main`: a compaction holds it locked +/// 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") +} + +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())) +} + +/// 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, "the indexer, another compaction or a database write holds the lock") + } +} + +impl std::error::Error for Busy {} + +/// 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 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 { + 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. +pub fn try_hold_off_compaction(main: &Path) -> Result> { + let file = open_lock(main)?; + match file.try_lock_shared() { + 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"), + } +} + +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). +pub(crate) struct Lock(std::fs::File); + +impl Lock { + pub(crate) fn take(main: &Path) -> Result { + 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"), + } + } +} + +impl Drop for Lock { + fn drop(&mut self) { + let _ = self.0.unlock(); + } +} + +/// 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) 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. +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(unresolved_message(&path, &original)); + continue; + } + 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())); + } + Ok(said) +} + /// What compacting one shard did. #[derive(Debug, Default, Clone, Copy)] pub struct Shrunk { @@ -51,30 +247,140 @@ 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(()) +} + +/// 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)] +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, 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)] +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, 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); + } +} + +/// 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 { + 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); + } if !store::exists(main) { bail!("{} has no shards (convert it first)", main.display()); } 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) { + 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 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; 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) { + remove_db(&with_suffix(&path, "precompact")); + } else if path.exists() { + 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); } } - // every shard is done and checked: the originals can go - for shard in store::shard_paths(main) { - remove_db(&with_suffix(&shard, "precompact")); + 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("; ")); } progress(&format!( "compacted {:.1}GB into {:.1}GB in {}: kept {} shared domains, dropped {} single use ones", @@ -87,15 +393,29 @@ 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)?; + // 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 { 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 and tables + store::migrate_shard(&conn)?; } let before = size(&path); @@ -103,6 +423,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; @@ -113,26 +434,15 @@ 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 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); - } - } - } - let shared = |d: i64| d != 0 && uses.get(d as usize).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)?) }; - say("copying releases and files"); + halt(stop, shard)?; + 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;", )?; @@ -146,7 +456,7 @@ fn compact_shard(main: &Path, shard: usize, progress: &(dyn Fn(&str) + Sync)) -> 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 { @@ -157,77 +467,473 @@ 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) + halt(stop, shard)?; + say(&format!("copying files and articles ({kept} shared domains, dropping {dropped}), sealing those due")); + 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 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 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( "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(shard, &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; + 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)) { + copied += insert_row(&tx, &row)?; + in_tx += 1; + if (copied as usize).is_multiple_of(STOP_EVERY) { + halt(stop, 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 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)?; + } + + // 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()? + } else { + None + }; + 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 { + 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 + // 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])?; + 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, streamed); + halt(stop, shard)?; + } + 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; + } + 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; + } + } + drop(held); + file_rows.extend(spilled); + + // 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. + // `held` stays for the streamed tail below (there is none without rows here) + let mut held: HashSet = HashSet::new(); + if !file_rows.is_empty() { + 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) } + } + 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; + recount.push(id); + } + } + + // 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; + // nor files with something held back: sealing them folds it in + let seal = !file_rows.is_empty() + && held_back == 0 + && 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, + 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))?; + copied += segs.len() as i64; + for row in &file_rows { + copied += insert_row(&tx, row)?; + } + in_tx += 1 + segs.len() + file_rows.len(); + // 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 + 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 { + copied += 1; + } else { + (tail_bytes, tail_copies) = (tail_bytes + row.bytes.unwrap_or(0), tail_copies + 1); + } + in_tx += 1; + // 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 { + tx.commit()?; + tx = conn.transaction()?; + in_tx = 0; + } + 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; + recount.push(id); + } if in_tx >= BATCH { tx.commit()?; tx = conn.transaction()?; 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)?; + } + // 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")); + 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(©)?; + // 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)?; + store::build_shard(&conn)?; + } // the check: same rows, same NZBs + halt(stop, shard)?; say("checking"); - check(&path, ©, shard, copied)?; + check(&path, ©, shard, copied, copies, 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(()))?; + 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"); - 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())); - } + 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)); 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. -fn check(original: &Path, copy: &Path, shard: usize, copied: i64) -> Result<()> { +/// 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", [])?; + // 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")?; + 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 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"; + +/// 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. `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 +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(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())?; + Ok(Some(Row { file_id, local, domain, part: r.get(3)?, bytes: r.get(4)? })) +} + +/// 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())) +} + +/// 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 + .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(n as i64) +} + +/// The copy holds the same releases, files and articles (rows and inside +/// 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, copies: 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) }; @@ -235,13 +941,20 @@ 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 - copies != b { + bail!( + "shard {shard}: {b} articles in the copy, {a} in the original ({copies} copies dropped); the original was kept" + ); + } + if copied != b { bail!("shard {shard}: some articles came out as duplicates; the original was kept"); } @@ -250,6 +963,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"), @@ -258,19 +972,161 @@ fn check(original: &Path, copy: &Path, shard: usize, copied: i64) -> Result<()> ) .ok(); let Some(id) = found else { continue }; - let (a, b) = (store::articles(&old, id)?, store::articles(&new, id)?); - if 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(()) } +/// 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)] mod tests { use super::*; use crate::parser::{Article, Release}; + fn no_stop() -> Arc { + 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}" + ); + } + + 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(); + 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(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.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!(hold_off_compaction(&main).is_ok()); + } + + #[test] + fn a_second_compaction_at_once_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let main = dir.path().join("atlas.db"); + 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 fn all_articles(main: &Path) -> Vec<(i64, Vec)> { let conn = db::open_with_shards(main).unwrap(); @@ -284,13 +1140,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() + } - // releases over several groups: a shared domain, and made up ones per article + 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 + } + + /// 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 +1206,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 +1221,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,31 +1237,145 @@ 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"); + } + + /// 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 }; - assert_eq!(domains(&main), 120 + 5, "every made up domain has a row, ngPost one per shard used"); - let before = all_articles(&main); + checks(0).unwrap(); - let shrunk = run(&main, &|_| {}).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(); + 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(); + 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, &|_| {}, &no_stop()).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"); + 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"); } @@ -376,4 +1397,973 @@ mod tests { store::save(&main, &[more]).unwrap(); 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(); + 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) + /// 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); + } + + /// 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] + 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(); + let check = HeldCheck::on(&stop); + let err = run(&main, &|_| {}, &stop).unwrap_err(); + assert!(format!("{err:#}").contains("stopped"), "{err:#}"); + 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. + #[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. + #[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) + .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, &|_| {}, &no_stop()).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, &|_| {}, &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); + 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); + } + + /// `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. + #[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 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 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(); + // 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"); + } + + /// 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] + 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"); + } + + /// 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)); + } + + /// 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"); + } + + /// 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(); + 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(); + let main = dir.path().join("atlas.db"); + legacy_fixture(&main); + 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, &|_| {}, &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(); + 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, &|_| {}, &no_stop()).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]); + } + + /// 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); + } + + /// 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); + } + + #[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()); + } + + /// 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::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(); + 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()); + } } diff --git a/src/config.rs b/src/config.rs index 21d17226..e14e3460 100644 --- a/src/config.rs +++ b/src/config.rs @@ -14,14 +14,23 @@ 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; +/// 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; /// One usenet provider. Lower `priority` is tried first. #[derive(Clone, Debug, PartialEq, Eq)] @@ -39,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 { @@ -53,6 +66,7 @@ impl UsenetServer { priority: 1, compress: None, index: None, + key: None, } } @@ -86,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), }) } @@ -108,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) } } @@ -124,8 +142,14 @@ 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, + /// 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 { @@ -140,7 +164,10 @@ impl Default for Config { api_key: None, batch_size: None, request_size: None, + split_min_backlog: None, parallel_groups: None, + auto_run_compact: false, + max_unsaved_headers: None, } } } @@ -191,6 +218,19 @@ 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: 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); + crate::nntp::unsaved_cap(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 { + self.split_min_backlog.unwrap_or(SPLIT_MIN_BACKLOG).max(1) + } + /// the highest priority server pub fn primary(&self) -> Option<&UsenetServer> { self.servers.first() @@ -253,11 +293,18 @@ 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) .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(); @@ -304,9 +351,41 @@ 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), 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 { + 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 @@ -435,6 +514,14 @@ 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)); + } + + if cfg.auto_run_compact { + out.insert("auto_run_compact".into(), json!(true)); + } + write_json(&Value::Object(out), private) } @@ -551,6 +638,61 @@ 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 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 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(); + 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); + } + + /// 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] diff --git a/src/convert.rs b/src/convert.rs index c0ece811..c036d86a 100644 --- a/src/convert.rs +++ b/src/convert.rs @@ -22,8 +22,10 @@ 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}; use crate::db; use crate::parser::Article; use crate::search::{ArticleRow, ReleaseRow}; @@ -34,6 +36,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; @@ -42,6 +46,52 @@ 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() || 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 { main.with_file_name(name) } @@ -57,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; @@ -67,6 +117,39 @@ 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`). +/// 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 let Some(said) = recover_cut_swap(main)? { + progress(&said); + } + 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)> { @@ -79,15 +162,16 @@ 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, 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))?; - 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); @@ -96,39 +180,48 @@ 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 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()))?; + } + { + // 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); { - // 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(()))?; + conn.busy_timeout(std::time::Duration::from_secs(5))?; + checkpoint(&conn).context("folding the old database's WAL in")?; } - 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())); + // 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_into_place(&new_main, main) { + // the old one back, soo there is a main database to start from + let _ = rename_into_place(&backup, main); + return Err(e).context("putting the new main database in place"); } progress(&format!( @@ -140,6 +233,87 @@ 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> { + let (new_main, backup) = (sibling(main, "atlas.new.db"), sibling(main, "atlas.old.db")); + if main.try_exists()? { + // 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()))?; + } + 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()? { + // 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", + main.display() + ))); + } + 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()) + .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, @@ -158,7 +332,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 { @@ -206,7 +380,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]; @@ -216,7 +390,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, ( @@ -269,7 +443,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)> { @@ -324,6 +498,7 @@ fn move_articles( } } tx.commit()?; + domains.committed(); } // into place in key order: an append, sorted on disk @@ -335,8 +510,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)) })); } @@ -364,16 +538,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(), @@ -384,7 +558,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); @@ -447,9 +620,9 @@ fn move_articles( }) } -/// Compare `CHECK_SAMPLE` releases, spread over the whole database, between -/// the old database and the shards. -fn check(main: &Path, old: &Connection, max_id: i64, shard_of_old: &[u8]) -> Result<()> { +/// 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: &ShardOf) -> Result<()> { let new = Connection::open_in_memory()?; store::attach(&new, main)?; @@ -477,14 +650,22 @@ 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; } - 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!( @@ -543,14 +724,15 @@ 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)> { +) -> 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); { - 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 @@ -565,6 +747,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 @@ -583,8 +766,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"); @@ -612,13 +794,149 @@ 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)) } -/// 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 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(Vec<(&'static str, String)>); + +impl Source { + 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): (i64, i64) = + old.query_row("select count(*), coalesce(max(id), 0) from articles", [], |r| Ok((r.get(0)?, r.get(1)?)))?; + // 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 &self.0 { + conn.execute("insert or replace into meta (key, value) values (?, ?)", params![key, value])?; + } + Ok(()) + } + + 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); + }; + 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 { + 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. +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, source).ok().flatten()).as_ref() == Some(source) && store::shard_paths(main).iter().all(|p| { p.exists() && db::open_at(p) @@ -630,3 +948,34 @@ fn copy_finished(main: &Path) -> 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)); + } +} diff --git a/src/db.rs b/src/db.rs index db528ed0..cc6545de 100644 --- a/src/db.rs +++ b/src/db.rs @@ -8,8 +8,10 @@ use std::fs; use std::path::Path; use std::time::Duration; +use anyhow::Context; use rusqlite::{Connection, OptionalExtension, params}; +use crate::compact::WriteGuard; use crate::parser::Release; use crate::paths; use crate::store; @@ -28,8 +30,32 @@ 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 { - let conn = Connection::open(path)?; + 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)?) +} + +/// 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,19 +133,82 @@ 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> { + // 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()? || crate::convert::is_empty_interloper(path)) + && 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)) +} + +/// Settings > wipe: every shard, with their sidecars and what a compaction +/// 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 +/// 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::new(); + for shard in store::shard_paths(main) { + 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); + } + // 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"] { + 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. -pub fn create_db_at(path: &Path) -> Result<()> { - let conn = open_at(path)?; +/// 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 = create_at(path)?; // wal soo the indexer can write while search reads conn.query_row("pragma journal_mode = wal", [], |_| Ok(()))?; @@ -142,11 +231,87 @@ pub fn create_db_at(path: &Path) -> Result<()> { } if has_old_layout(&conn)? { - return migrate_old(&conn); + 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)?; - for shard in store::shard_paths(path) { + 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 { + 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. 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); + } + 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() || used) { + 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 from a database in use: {}. not making empty ones in their place; put them back first", + each.join(", ") + ); + } + for shard in shards { store::create_shard(&shard)?; } Ok(()) @@ -264,17 +429,23 @@ 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, and holds off a +/// compaction until saved. +pub fn save_releases_bulk(releases: &[Release]) -> anyhow::Result<()> { if releases.is_empty() { return Ok(()); } - store::save(&paths::database(), releases) + let main = paths::database(); + let _writing = crate::compact::hold_off_compaction(&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, and holds off a compaction until done. +pub fn purge_broken() -> anyhow::Result { let main = paths::database(); + 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(); @@ -404,6 +575,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(); @@ -538,9 +710,181 @@ 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"); } + + /// 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"), + // 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())), + ]; + 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::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"); + 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"); + } + + /// 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(); + 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()); + } + + #[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 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(); + 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())); + } } diff --git a/src/indexer.rs b/src/indexer.rs index 6edc6535..3964ded9 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; @@ -8,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}; @@ -43,11 +44,38 @@ 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, + /// a split group's servers are looked at for older days again then + pub reach_back_after: Option, + /// 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, + /// likewise the day of its first post, `i64::MAX` when it has none or + /// 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)>, } +/// 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; + 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, + reach_back_after: None, + keeps_from: HashMap::new(), + first_post_days: HashMap::new(), + } } } @@ -73,6 +101,48 @@ impl RunStates { groups.iter().all(|g| states.get(g).is_some_and(|s| s.idle)) } + /// 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(host)); + found.filter(|(_, until)| *until > now).map_or(i64::MIN, |(day, _)| *day) + } + + /// 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))); + } + + /// 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, 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. + 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.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. + 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(host).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() { @@ -89,6 +159,10 @@ 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, + /// article numbers a day chunk reaches past its ends (`CHUNK_SAFETY`) + pub chunk_safety: u64, } impl Default for PassSettings { @@ -97,6 +171,8 @@ 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, + chunk_safety: CHUNK_SAFETY, } } } @@ -113,6 +189,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 { @@ -121,32 +211,63 @@ 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 { + 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 = (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)) + .spawn(move || writer(shard, &path, &ids, jobs, every)) .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) { +/// 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_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); - - 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_timeout(idle) { + Ok(job) => job, + // 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]; while batch.len() < MAX_BATCH { match jobs.try_recv() { @@ -155,15 +276,17 @@ 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 { Ok(conn) => { - let saved = store.save(conn, ids, batch.iter().map(|job| job.releases.as_slice())); - 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())), }; @@ -171,16 +294,55 @@ 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 { + // 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); + false + } + Err(TryRecvError::Empty) => saved, + Err(TryRecvError::Disconnected) => false, + }; + 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 { /// 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(()) }; @@ -216,34 +378,109 @@ 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 -/// group name like before. +/// cursors are kept per server as `group@host` (`Pool::host`, see +/// `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 { group.to_string() } else { format!("{group}@{}", pool.host(server).to_lowercase()) } + // 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()), + } } -async fn load_cursors(db: &Db, key: &str, group: &str, legacy: bool) -> Result> { - let (key, group) = (key.to_string(), group.to_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(()) +} - on_db(db, move |conn| { - if let Some(state) = db::get_group_state(conn, &key)? { - return Ok(Some(state)); - } +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()?) +} - // 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)); - } +/// 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)) +} - Ok(None) +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 key == group { Vec::new() } else { ctx.pool.legacy_keys(server) }; + 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) only by the server +/// that kept them (`owns_plain`, see `claim_plain_cursors`) +fn cursors_or_adopted( + conn: &Connection, + key: &str, + group: &str, + owns_plain: bool, + legacy: &[String], +) -> Result> { + if let Some(state) = db::get_group_state(conn, key)? { + 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)?); + } + } + + if owns_plain + && 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 /// the mode, on server `prefer` (or whichever server carries the group). /// `progress` hears about every slice as it is saved. Safe to run for many @@ -263,7 +500,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 @@ -279,8 +516,67 @@ 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, 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); + let wanted = [(group.to_string(), ctx.states.keeps_from(group, &host))]; + // 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 { + Err(e) if e.downcast_ref::().is_some() => Ok(Progress::default()), + r => r, + }, + // 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, 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, generation)?)).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"; + 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 +594,791 @@ where } } +/// 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 +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 +/// 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, last): (u64, u64), + cursor: u64, +) -> 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)).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 { + 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 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)); + 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"); + 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`. 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(newest_day)).await? + else { + return Ok(()); + }; + let g = group.to_string(); + 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(()) +} + +/// 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, +} + +/// 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: Newest, +) -> Result> { + // 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. 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 + // 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, high, _)) = ctx.pool.group_on(other, group).await else { continue }; + carriers += 1; + 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 { + return Ok(None); + } + + 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(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 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, 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 { + 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 && 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 { + 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 {} + +/// 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<(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 +} + +/// 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)); + // 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, generation)?)) + }; + // 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(ctx, db, &key, group, server).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; + +/// 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 +/// 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, + db: &Db, + chunk: &crate::chunks::Claim, + 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:#}"); + } + } +} + +/// 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:#}"), + } +} + +/// A day only this server has (`day`, of the window from `floor`, see +/// `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(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; + // 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 + s.reach += SPECULATIVE_WINDOW; + s.days = 0; + s.articles = 0; + } + 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 note the days only one server has: {e:#}"), + } +} + +/// `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, + db: &Db, + chunk: &crate::chunks::Claim, + server: usize, + progress: &mut P, +) -> Result +where + P: FnMut(&Progress) + ?Sized, +{ + let (group, day) = (chunk.group.as_str(), chunk.day); + let release = || { + let c = chunk.clone(); + on_db(db, move |conn| Ok(crate::chunks::release(conn, &c)?)) + }; + // 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, 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) if e.code() == Some(411) => { + // it has no post of it (see `drop_unkept_days`) + 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 { + 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, + }; + let (_count, first, last, _name) = found; + + // 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 keeps it whole, the one that goes back + // furthest on it does what there is + // (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; + // 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; + // 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 + // its posters set + 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)) => { + 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 { + 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, sure)).await { + Ok((furthest, _)) => furthest, + Err(e) => return failed(e).await, + } + } + } + _ => false, + }; + if !keeps_day { + // the first day it keeps whole + 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 + // 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:#}"); + } + 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 + // 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, + }; + 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, + }; + // days only this server has are bounded all together, see `chunks::Speculative` + let floor = match runner_up_day { + Some(r) => { + let g = group.to_string(); + 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()); + } + Some(floor) + } + None => None, + }; + if start > end { + finish_chunk(db, chunk, (alone, floor, oldest), 0).await?; + return Ok(Progress::default()); + } + + 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, dated_in_day)) => { + finish_chunk(db, chunk, (alone, floor, oldest), dated_in_day).await?; + Ok(saved) + } + Ok((saved, false, _)) => { + release().await?; + Ok(saved) + } + Err(e) => failed(e).await, + } +} + +/// 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. +/// +/// 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, for the carriers' sweeps once the +/// chunks are done (see `run_pass` and `run_sweep`). +pub async fn chunk_range( + pool: &Pool, + server: usize, + group: &str, + (first, last): (u64, u64), + day: i64, + (oldest_day, newest_day): (i64, i64), + (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 { + 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).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).saturating_add(safety).min(cursor) + }; + Ok((start, end)) +} + +/// 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)?, 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)); + } + + // 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()), + }; + 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 => {} + } + } + // 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> { ctx: &'a PassContext, settings: &'a PassSettings, @@ -392,9 +1473,29 @@ 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 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, + end: i64, + kind: &str, + window: Option<(i64, i64)>, + progress: &mut P, + ) -> Result<(Progress, bool, i64)> + where + P: FnMut(&Progress) + ?Sized, + { + let mut in_window = 0i64; 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()); @@ -405,10 +1506,13 @@ 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 - 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; } @@ -429,6 +1533,12 @@ impl Pass<'_> { continue; } + if let Some((from, to)) = window { + in_window += headers + .iter() + .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 { Ok(p) => { @@ -468,7 +1578,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)) } } @@ -633,8 +1743,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 { @@ -655,6 +1769,236 @@ 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"); + } + + /// 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(); + 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 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(); + 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(); + 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 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(); + // 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 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)]); @@ -663,4 +2007,101 @@ 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_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), 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)), + "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] + 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()]); + } + + #[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); + } } diff --git a/src/lib.rs b/src/lib.rs index 71f14364..bfac527e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,8 @@ 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; pub mod convert; diff --git a/src/main.rs b/src/main.rs index 9c9697a7..e3fb064d 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(); @@ -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; } @@ -45,8 +46,13 @@ fn run_convert() -> i32 { println!("stop indexing first"); return 1; } - match convert::run(&main, &|msg| println!("{msg}")) { - Ok(_) => 0, + // 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 + } Err(e) => { println!("couldnt convert, nothing was changed: {e:#}"); 1 @@ -60,8 +66,17 @@ fn run_compact() -> i32 { println!("stop indexing first"); return 1; } - match compact::run(&paths::database(), &|msg| println!("{msg}")) { - Ok(_) => 0, + // 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(_) => { + // noted like the indexer's own compaction does, soo the auto one waits its interval + // 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 + } Err(e) => { println!("couldnt compact: {e:#}"); 1 diff --git a/src/nntp.rs b/src/nntp.rs index c4364324..c4a56497 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; @@ -42,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)) @@ -155,8 +162,14 @@ 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); +/// 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, @@ -193,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| plausible_post_time(&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>, @@ -277,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 { @@ -378,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); + } } } @@ -460,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}"), @@ -654,6 +752,10 @@ 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, + /// what earlier builds named it, see `legacy_server_keys` + legacy_keys: Vec, idle: Mutex>, permits: Arc, down_until: Mutex>, @@ -662,18 +764,39 @@ 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, /// 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) @@ -753,6 +876,69 @@ pub struct ServerStat { pub text_bytes: u64, } +/// 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 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; +/// 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. /// @@ -767,24 +953,143 @@ pub struct Pool { ready: AtomicBool, failed_over_at: Mutex>, 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, +} + +/// 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 = unsaved_cap(cap); + 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, + /// 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 { + /// 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); + } + 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 is held + self.budget.now.fetch_sub(self.permit.num_permits() + self.over, Ordering::Relaxed); + } +} + +/// 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 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 { + servers.iter().map(server_key).collect() +} + +fn server_key(s: &UsenetServer) -> String { + 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, + } +} + +/// 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| { + 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); + } + } + old + }) + .collect() } impl Pool { pub fn new(servers: &[UsenetServer]) -> Pool { + let keys = server_keys(servers); + let legacy = legacy_server_keys(servers); Pool { servers: servers .iter() - .map(|cfg| { + .zip(keys) + .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), 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), + waiting: AtomicUsize::new(0), headers: AtomicU64::new(0), wire: AtomicU64::new(0), text: AtomicU64::new(0), @@ -795,6 +1100,8 @@ impl Pool { ready: AtomicBool::new(false), 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), } } @@ -803,6 +1110,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, over: 0 } + } + pub fn len(&self) -> usize { self.servers.len() } @@ -819,8 +1159,14 @@ 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.cfg.host.clone()).unwrap_or_default() + self.servers.get(i).map(|s| s.key.clone()).unwrap_or_default() } /// requests server `i` takes at once @@ -864,6 +1210,24 @@ 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; + } + + // 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); @@ -884,6 +1248,37 @@ 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| { + // 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); + 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) @@ -910,7 +1305,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 = { @@ -1055,19 +1453,30 @@ 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) } + /// 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)> { @@ -1078,8 +1487,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)), @@ -1088,21 +1497,13 @@ impl Pool { Err(e) => return Err(e), }; - let candidates: Vec = self - .indexing_servers() - .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 - }); - - 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); return Ok((i, r)); } } @@ -1110,15 +1511,352 @@ impl Pool { Err(first_err) } + /// 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. One request: + /// listings are sorted, the first rows say. + async fn posted_at(&self, i: usize, group: &str, number: u64, look: u64) -> Result> { + 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 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. + /// 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. The + /// 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(); + // 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? { + return self.first_before(i, group, &skipped, hit).await.map(Some); + } + read_to = at + look; + if size < DATE_SCAN_MAX { + at = read_to; + size *= 2; + } else { + 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) + } + + /// 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`. + async fn last_in(&self, i: usize, group: &str, from: u64, end: u64) -> Result> { + // 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.last_at(i, group, to - look, look).await? { + return self.last_after(i, group, &skipped, hit).await.map(Some); + } + read_from = to - look; + if size < DATE_SCAN_MAX { + to = read_from; + size *= 2; + } else { + 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) + } + + /// `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.last_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.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.last_at(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> { + 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 + /// 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 { + // 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; + 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 + { + 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) = newer { + 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, + } + } + } + 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)) + } + + /// 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, @@ -1183,8 +1921,16 @@ 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`) + /// 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, @@ -1196,8 +1942,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 { @@ -1210,19 +1956,31 @@ 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) + && !e.is_empty_range() && !e.is_permanent() { 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; } } @@ -1234,7 +1992,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()); @@ -1266,7 +2024,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); } @@ -1279,10 +2037,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 { @@ -1319,6 +2089,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 @@ -1362,7 +2134,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 { @@ -1547,6 +2319,55 @@ 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 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); + // 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: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"); + 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] + 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; @@ -1649,7 +2470,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 }) @@ -1695,13 +2516,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}"); }); } @@ -1746,6 +2616,47 @@ 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] + 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] 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/profile.rs b/src/profile.rs index f7e07827..18cd979b 100644 --- a/src/profile.rs +++ b/src/profile.rs @@ -74,6 +74,10 @@ 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, + /// 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, @@ -89,6 +93,8 @@ 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), + writer_seal_errors: AtomicU64::new(0), xover_ns: AtomicU64::new(0), xovers: AtomicU64::new(0), lease_wait_ns: AtomicU64::new(0), @@ -114,6 +120,8 @@ 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), + "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/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/stats_dashboard.rs b/src/stats_dashboard.rs index af243517..9c02123b 100644 --- a/src/stats_dashboard.rs +++ b/src/stats_dashboard.rs @@ -83,17 +83,39 @@ struct Quick { releases_approx: i64, db_bytes: u64, 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) { + 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 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() } 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() }; @@ -101,6 +123,8 @@ 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 = load_chunks_stats(&conn); + q.group_chunks = load_group_chunks(&conn); q } @@ -328,6 +352,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) @@ -365,6 +392,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 }, @@ -706,6 +735,15 @@ 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. 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 && c.0 < c.1) { + *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 { @@ -778,6 +816,20 @@ fn draw_backfill(f: &mut Frame, app: &App, area: Rect) { note("counts are article numbers, gaps on the server included"), ]; let mut progress = progress; + 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)))); } @@ -1036,7 +1088,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", @@ -1259,6 +1317,49 @@ mod tests { assert_eq!(b.reached, Some(base + 10 * day)); } + #[test] + fn split_groups_progress_follows_their_chunks_then_their_sweep() { + 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 (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, 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))); + } + + #[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); @@ -1299,6 +1400,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)), @@ -1313,6 +1415,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); @@ -1378,7 +1481,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::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, @@ -1407,6 +1510,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%)") @@ -1417,4 +1521,36 @@ 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); + + 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(); + 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(); + 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); + 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, "finished in the last hour, though claimed before it"); + } } diff --git a/src/store.rs b/src/store.rs index f20592fc..543d1083 100644 --- a/src/store.rs +++ b/src/store.rs @@ -16,12 +16,13 @@ //! 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, VecDeque}; 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}; @@ -55,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()) @@ -92,12 +111,19 @@ 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. pub fn create_shard(path: &Path) -> Result<()> { - let conn = db::open_at(path)?; + build_shard(&db::create_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( " @@ -142,7 +168,9 @@ pub fn create_shard(path: &Path) -> Result<()> { subject_mid TEXT, expected INTEGER, file_total INTEGER, - seen BLOB NOT NULL + seen BLOB NOT NULL, + touched_at INTEGER, + blob BLOB ); create unique index if not exists files_key on files(release_id, filename); @@ -160,7 +188,55 @@ 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) +} + +/// 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 ( + 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; + + -- 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")] { + if !cols.iter().any(|c| c == col) { + conn.execute(&format!("alter table files add column {col} {kind}"), [])?; + } + } + Ok(()) } // ---------------------------------------------------------------- ids @@ -202,12 +278,81 @@ 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; 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); @@ -218,23 +363,47 @@ 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 +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('<')?; @@ -255,6 +424,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 @@ -274,7 +446,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 @@ -294,14 +466,43 @@ 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(); + } +} + +/// 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::()), } } @@ -319,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); @@ -355,6 +556,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 { @@ -385,7 +588,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| { @@ -397,6 +600,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()?; @@ -410,31 +614,140 @@ 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, 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, + 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 + .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 { + 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()); + 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])?; + 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])?; + } + 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) } +#[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, + } + } +} + +/// 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 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])?; + } + 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)")? + .execute([release_id])?; + Ok(()) +} + /// 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 { @@ -452,6 +765,448 @@ 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; + +/// 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)) +} + +/// 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_capped(&b, SEAL_MAX_SEGMENTS as usize).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). +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(); + // 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 > SEAL_MAX_SEGMENTS { + settle_held_back(conn, file_id, &segs)?; + return Ok(0); + } + 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 + // 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 + // `SealedCache`) isnt added twice: it goes, before the blob is counted, + // soo a full blob doesnt keep it a row + // (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| 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 { + 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 = + 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])?; + 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])?; + } + 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)?; + // 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])?; + } + fold_in(conn, file_id, &news)?; + if !copies.is_empty() || !news.is_empty() { + 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 { + 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()) +} + +/// 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`). +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 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])?; + 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 +/// (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. +pub(crate) fn sealable(conn: &Connection, after_id: i64, limit: usize, now: i64) -> Result<(Vec, 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 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() + ))?; + 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, 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; + } + let seen: Vec = r.get(2)?; + 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(&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 length(s.local) > {})) or {} + from files f where f.id = ?", + crate::blob::MAX_LOCAL, + too_many_rows() + ))? + .query_row([file_id], |r| { + 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 && !never && touched.is_some() && due(r.get(0)?, &seen, touched, 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 { + let complete = !sealed && expected.is_some_and(|e| is_exactly(seen, e)); + complete || touched.is_none_or(|t| t < now - SEAL_AGE) +} + +/// 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; + +/// 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 { + /// 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, + /// 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) + } + + 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, + 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); + *used = self.uses; + self.by_use.insert(self.uses, file_id); + return Ok(set.contains(&key)); + } + if self.decoded >= self.max_decoded { + self.guessed = true; + 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); + } + 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) + } +} + // ---------------------------------------------------------------- saving /// Saves releases into one shard: upsert the release, add its new articles, @@ -459,11 +1214,115 @@ fn release_complete(conn: &Connection, release_id: i64, file_total: Option) pub struct ShardWriter { pub shard: usize, domains: Domains, + /// 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, + /// segments of sealed files a save decodes at most (see `SealedCache`) + decode_budget: usize, } +/// 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); + +/// 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() } + ShardWriter { + shard, + domains: Domains::default(), + completed: VecDeque::new(), + completed_ids: HashSet::new(), + seal_after: 0, + walked_at: None, + decode_budget: SEALED_DECODE_BUDGET, + } + } + + 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, 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 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 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]; + } + 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()?; + Ok(sealed) } /// Releases of this shard's groups, in one transaction. The same release @@ -473,10 +1332,31 @@ 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; + // blobs of sealed files that get late articles, decoded once each + 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()?; + let key = IdKey::of(&tx)?; let (mut new_releases, mut new_articles) = (0i64, 0i64); { let mut upsert = tx.prepare_cached( @@ -515,7 +1395,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; } @@ -530,18 +1411,58 @@ 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)?; + // 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.id, a)? { - f.add(a); - added.push(a); + 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 + // 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, unsure)); } } 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); + } + } else { + // a file just made whose articles all were in other files + 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); @@ -552,11 +1473,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, @@ -571,6 +1497,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 } } @@ -584,6 +1515,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<()> { @@ -593,7 +1534,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(()) @@ -604,7 +1545,23 @@ 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 + // 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 @@ -624,9 +1581,56 @@ pub fn articles(conn: &Connection, release_id: i64) -> Result> { posted_date: r.get(8)?, }) })?; - let mut rows: Vec = rows.collect::>()?; - rows.sort_by(|a, b| (&a.filename, a.part, &a.message_id).cmp(&(&b.filename, b.part, &b.message_id))); - Ok(rows) + for row in rows { + each(row?)?; + } + + // 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 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(suffix_of.query_row([seg.domain], |r| r.get(0)).optional()?), + }; + each(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)?, + })?; + } + } + Ok(()) +} + +/// 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 @@ -642,21 +1646,40 @@ 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_at(&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); + let conn = db::open_shard(&path)?; + // 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 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; - commit;", - )?; - let articles: i64 = conn.query_row("select count(*) from segments", [], |r| r.get(0))?; - 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")?; } @@ -667,6 +1690,94 @@ 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_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::()); + } + } + } + + /// 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] + 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(); + 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 = [ @@ -698,6 +1809,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(); @@ -723,14 +1879,49 @@ 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, None, &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, 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(); 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, 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(); + assert_eq!(segments, 2); } #[test] @@ -761,4 +1952,1103 @@ 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); + } + + /// 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"); + } + + /// 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] + 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. + #[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] + 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(); + 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, None, &article, &mut SealedCache::new()).unwrap()); + let other = Article { message_id: "".into(), part: Some(2), ..Default::default() }; + assert!( + 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(); + 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::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, + 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 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 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( + "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(); + 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(); + 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"); + } + + #[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 + 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); + } + + /// 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"); + 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); + } + + /// 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"); + } + + /// 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"); + } + + /// 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 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] + 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"); + } + + /// 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 { + 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 + #[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(); + 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(); + 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] + 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"); + } } diff --git a/tests/auto_compact.rs b/tests/auto_compact.rs new file mode 100644 index 00000000..5a5384ba --- /dev/null +++ b/tests/auto_compact.rs @@ -0,0 +1,99 @@ +//! 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}; + +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 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); + 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); + 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); + // 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"); + 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(); + 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); + 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)); + } + // 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/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); +} 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)); +} diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 8aff3fd1..2909ace5 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 { @@ -55,6 +57,16 @@ 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, + /// 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, + /// once set, GROUP answers 411, like a provider that dropped the group + pub dropped: std::sync::atomic::AtomicBool, } impl Server { @@ -81,6 +93,11 @@ impl Server { stalls_left: AtomicUsize::new(0), stalled: AtomicUsize::new(0), accepted: AtomicUsize::new(0), + bodies_sent: AtomicUsize::new(0), + body_delay: Duration::ZERO, + empty_is_420: false, + reported_low: None, + dropped: Default::default(), }) } } @@ -131,7 +148,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) { @@ -162,7 +191,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"), @@ -176,16 +205,18 @@ 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 first = posts.iter().map(|p| p.number).min().unwrap_or(0); + let posts = posts_lock(); + 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()); } "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"); @@ -210,20 +241,23 @@ 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(); - if hits.is_empty() { - send(&mut out, b"423 no articles in that range"); + let posts = posts_lock(); + let lo = posts.partition_point(|p| p.number < a); + 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; } - 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 - ); - listing.extend_from_slice(row.as_bytes()); + if hits().next().is_none() { + send(&mut out, b"423 no articles in that range"); + continue; } - listing.extend_from_slice(b".\r\n"); if compressed && state.compress_broken { send(&mut out, b"224 overview follows [COMPRESS=GZIP]"); @@ -231,18 +265,32 @@ 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.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) => { + 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 @@ -265,18 +313,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/compact_command.rs b/tests/compact_command.rs new file mode 100644 index 00000000..647af21c --- /dev/null +++ b/tests/compact_command.rs @@ -0,0 +1,72 @@ +//! `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}"); +} + +#[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()); +} diff --git a/tests/compact_lock.rs b/tests/compact_lock.rs new file mode 100644 index 00000000..f4720786 --- /dev/null +++ b/tests/compact_lock.rs @@ -0,0 +1,101 @@ +//! 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); + + // 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); + 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(); +} diff --git a/tests/convert.rs b/tests/convert.rs index 04ce80ac..ca1f7e20 100644 --- a/tests/convert.rs +++ b/tests/convert.rs @@ -251,3 +251,394 @@ 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"); +} + +/// 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); +} + +/// 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); +} + +/// 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); +} + +/// 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. +#[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] +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); +} + +/// 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] +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] +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)); +} + +/// 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()); + } +} + +/// 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}"); + } +} diff --git a/tests/date_search.rs b/tests/date_search.rs new file mode 100644 index 00000000..2a66a4e4 --- /dev/null +++ b/tests/date_search.rs @@ -0,0 +1,1387 @@ +//! 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}; + +/// 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 { + 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 { + 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"); +} + +/// 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(); + // 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(), + 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); + 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 + assert_eq!(saved.articles, 24); + let conn = atlas::db::open_at(&main).unwrap(); + 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, +/// 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); +} + +/// 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_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 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); +} + +/// 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); +} + +/// 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. +#[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() { + 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(); + + let day = atlas::chunks::unix_day(minute_of(3_000_001)); + let main_conn = atlas::db::open_at(&main).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(), + 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); + 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); + let conn = atlas::db::open_at(&main).unwrap(); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 3)); +} + +/// 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(); + // 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(), + 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); + 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 + assert_eq!(saved.articles, 720 - 150 + 30); + let conn = atlas::db::open_at(&main).unwrap(); + assert_eq!(atlas::chunks::progress(&conn, GROUP).unwrap(), (1, 3)); +} + +/// 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, + &exact(), + &db, + &atlas::chunks::Claim { + group: "alt.binaries.other".into(), + day: 20_455, + server: "127.0.0.1".into(), + claimed_at: 1, + }, + 0, + &mut |_| {}, + )) + .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| { + let chunk = claimed(&main, GROUP, day); + pool.block_on(atlas::indexer::run_chunk(&ctx, &exact(), &db, &chunk, 0, &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, &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(); + let state = |day: i64| -> Option { + conn.query_row("select state from backfill_chunks where day = ?", [day], |r| r.get(0)).ok() + }; + // 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): +/// 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. +#[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, &exact(), &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); +} + +/// 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, &exact(), &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(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); + 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(pool.pool.host(1).as_str())); +} + +/// 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, &exact(), &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(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); + 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(pool.pool.host(1).as_str())); +} + +/// 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 = ?, 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(), + 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, + chunk_safety: 0, + }; + 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"); + // 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(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: pool.pool.host(1), 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(); + 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); + } +} + +/// 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, &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}@{}", pool.pool.host(0).to_lowercase()), 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, + chunk_safety: 0, + }; + 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. +#[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, + chunk_safety: 0, + }; + 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" + ); +} + +/// 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, + chunk_safety: 0, + }; + 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. +#[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, + chunk_safety: 0, + }; + 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(), &exact(), &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"); + // 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(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"); + assert_eq!(state(day0), 2); +} + +/// (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(); + // 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(), + 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); + 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}"); + } +} + +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)); +} + +/// 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, &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)); + 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, 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, &exact(), &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, 0), + ); + 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"); + } +} + +/// 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/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) + }); + } +} diff --git a/tests/multi_server.rs b/tests/multi_server.rs index 74d3b283..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, @@ -104,3 +105,76 @@ 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); +} + +/// 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"); +} diff --git a/tests/save_memory.rs b/tests/save_memory.rs new file mode 100644 index 00000000..d58edf5e --- /dev/null +++ b/tests/save_memory.rs @@ -0,0 +1,113 @@ +//! 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, + ..Default::default() + }; + 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); +} diff --git a/tests/server_quirks.rs b/tests/server_quirks.rs index 9e7b4539..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() @@ -61,6 +63,55 @@ 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]); +} + +/// 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"); +} diff --git a/tests/split_backfill.rs b/tests/split_backfill.rs new file mode 100644 index 00000000..b8371fc9 --- /dev/null +++ b/tests/split_backfill.rs @@ -0,0 +1,93 @@ +//! 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")); + } + + // 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": [ + {"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"); + 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_bogus_days.rs b/tests/split_bogus_days.rs new file mode 100644 index 00000000..07f12efa --- /dev/null +++ b/tests/split_bogus_days.rs @@ -0,0 +1,93 @@ +//! 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 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 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 = keys.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}"); +} diff --git a/tests/split_forged_2000.rs b/tests/split_forged_2000.rs new file mode 100644 index 00000000..d6d148f4 --- /dev/null +++ b/tests/split_forged_2000.rs @@ -0,0 +1,91 @@ +//! 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 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 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 = keys.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"); +} diff --git a/tests/split_forged_daily.rs b/tests/split_forged_daily.rs new file mode 100644 index 00000000..ed6c6f6d --- /dev/null +++ b/tests/split_forged_daily.rs @@ -0,0 +1,109 @@ +//! A split group on two servers, one with an article dated in every day +//! 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 +//! 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_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 { + 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 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) + .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; + // 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(); + 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"); +} diff --git a/tests/split_forged_early.rs b/tests/split_forged_early.rs new file mode 100644 index 00000000..fab3b964 --- /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 = ? and day < ?", + rusqlite::params![format!("localhost:{ps}"), 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"); +} diff --git a/tests/split_forged_sweep.rs b/tests/split_forged_sweep.rs new file mode 100644 index 00000000..b4434f4d --- /dev/null +++ b/tests/split_forged_sweep.rs @@ -0,0 +1,108 @@ +//! 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)], &format!("127.0.0.1:{ps}"), 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"); +} diff --git a/tests/split_homes.rs b/tests/split_homes.rs new file mode 100644 index 00000000..3ab8f713 --- /dev/null +++ b/tests/split_homes.rs @@ -0,0 +1,130 @@ +//! 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 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` +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.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": third, "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 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 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"); + + // (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| Ok((r.get(0)?, r.get(1)?))) + .unwrap() + .collect::>() + .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}@{}", 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 + .prepare("select distinct server from backfill_chunks where state = 2 order by server") + .unwrap() + .query_map([], |r| r.get(0)) + .unwrap() + .collect::>() + .unwrap(); + assert!(c.accepted.load(Ordering::SeqCst) > 0, "the third server was asked"); + 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 new file mode 100644 index 00000000..8d533df5 --- /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 = ? and day < ?", + rusqlite::params![format!("localhost:{ps}"), 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"); +} diff --git a/tests/split_shallow_home_sweep.rs b/tests/split_shallow_home_sweep.rs new file mode 100644 index 00000000..e194b0f5 --- /dev/null +++ b/tests/split_shallow_home_sweep.rs @@ -0,0 +1,111 @@ +//! 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)], &format!("localhost:{ps}"), 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 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 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 complete = atlas::chunks::complete(&conn, GROUP, &keys).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"); +} diff --git a/tests/split_sweep_own_chunks.rs b/tests/split_sweep_own_chunks.rs new file mode 100644 index 00000000..3e5884e8 --- /dev/null +++ b/tests/split_sweep_own_chunks.rs @@ -0,0 +1,110 @@ +//! 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)], &format!("127.0.0.1:{ps}"), 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"); +} diff --git a/tests/unsaved_cap.rs b/tests/unsaved_cap.rs new file mode 100644 index 00000000..f04b62ee --- /dev/null +++ b/tests/unsaved_cap.rs @@ -0,0 +1,129 @@ +//! 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 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 +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 +} + +/// `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, groups: 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: 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(); + 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"); + // 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"); + + let peak = pool.unsaved_peak(); + assert!(peak <= cap, "{peak} headers unsaved at once, the cap is {cap}"); + 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 + 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, 16); +} + +/// 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, 4); +}