From d2d3446d8a5eafeb4be78fa24b68eb7493504c3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 12:41:21 -0300 Subject: [PATCH 01/10] Build with Rust 1.100 The package already builds with the stable toolchain, so the pinned one now matches what ships. Members inherit the edition and minimum Rust version from the workspace, and Clippy reads the latter from there. Cargo 1.100 warns about workspace.package fields no member inherits, so homepage and authors go. A test hands its path to the reader thread without a clone. --- CONTRIBUTING.md | 2 +- Cargo.toml | 4 +--- README.md | 2 +- apps/big-docinfo/Cargo.toml | 4 ++-- apps/big-search/Cargo.toml | 4 ++-- apps/big-search/fuzz/Cargo.toml | 2 +- apps/big-search/src/extract/tests.rs | 3 +-- clippy.toml | 1 - crates/foundation/big-docinfo/Cargo.toml | 4 ++-- crates/foundation/big-indexd-client/Cargo.toml | 4 ++-- crates/foundation/big-search-config/Cargo.toml | 4 ++-- rust-toolchain.toml | 2 +- 12 files changed, 16 insertions(+), 20 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2d4d179..240c6d3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -13,7 +13,7 @@ file names and contents you would not want public. ## Building and testing -You need Rust 1.98.1 (rustup picks it up from `rust-toolchain.toml`), SQLite 3, +You need Rust 1.100.0 (rustup picks it up from `rust-toolchain.toml`), SQLite 3, poppler and shared-mime-info. ```sh diff --git a/Cargo.toml b/Cargo.toml index 5e4071e..3d16333 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,11 +48,9 @@ redundant_test_prefix = "warn" [workspace.package] edition = "2024" -rust-version = "1.98.1" +rust-version = "1.100.0" license = "MIT" repository = "https://github.com/biglinux/bigsearch" -homepage = "https://github.com/biglinux/bigsearch" -authors = ["BigLinux contributors"] [profile.dev] debug = "line-tables-only" diff --git a/README.md b/README.md index fceafa3..e043161 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ documents. Requirements: - Linux with inotify, and systemd for the user service. -- Rust 1.98.1; with rustup, `rust-toolchain.toml` selects it. +- Rust 1.100.0; with rustup, `rust-toolchain.toml` selects it. - SQLite 3; poppler (`pdftotext`) for PDF content and `antiword` for Word 97-2003 documents. - shared-mime-info, which names a file's type from its name. diff --git a/apps/big-docinfo/Cargo.toml b/apps/big-docinfo/Cargo.toml index 2b99132..259cffe 100644 --- a/apps/big-docinfo/Cargo.toml +++ b/apps/big-docinfo/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "big-docinfo-cli" version = "0.1.0" -edition = "2024" -rust-version = "1.98.1" +edition.workspace = true +rust-version.workspace = true description = "Suggests a file name for a document from what it says, and renames it without ever overwriting" license.workspace = true repository.workspace = true diff --git a/apps/big-search/Cargo.toml b/apps/big-search/Cargo.toml index f122562..ac40843 100644 --- a/apps/big-search/Cargo.toml +++ b/apps/big-search/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "big-search" version = "0.1.0" -edition = "2024" -rust-version = "1.98.1" +edition.workspace = true +rust-version.workspace = true description = "Lean unprivileged filename + content search for the Linux desktop" license.workspace = true repository.workspace = true diff --git a/apps/big-search/fuzz/Cargo.toml b/apps/big-search/fuzz/Cargo.toml index f7ec027..31e98be 100644 --- a/apps/big-search/fuzz/Cargo.toml +++ b/apps/big-search/fuzz/Cargo.toml @@ -3,7 +3,7 @@ name = "big-search-fuzz" version = "0.0.0" publish = false edition = "2024" -rust-version = "1.98.1" +rust-version = "1.100.0" [package.metadata] cargo-fuzz = true diff --git a/apps/big-search/src/extract/tests.rs b/apps/big-search/src/extract/tests.rs index 865dc1e..ebd8286 100644 --- a/apps/big-search/src/extract/tests.rs +++ b/apps/big-search/src/extract/tests.rs @@ -12,9 +12,8 @@ fn readers_pass_over_fifo() { let path = dir.join(name); crate::test_env::make_fifo(&path); let (done_tx, done_rx) = std::sync::mpsc::channel(); - let reader_path = path.clone(); std::thread::spawn(move || { - let _ = done_tx.send(content(&reader_path)); + let _ = done_tx.send(content(&path)); }); let text = done_rx .recv_timeout(std::time::Duration::from_secs(10)) diff --git a/clippy.toml b/clippy.toml index b2c7086..e3a67c1 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,4 +1,3 @@ -msrv = "1.98.1" allow-unwrap-in-tests = true allow-expect-in-tests = true diff --git a/crates/foundation/big-docinfo/Cargo.toml b/crates/foundation/big-docinfo/Cargo.toml index 5808605..3ed0095 100644 --- a/crates/foundation/big-docinfo/Cargo.toml +++ b/crates/foundation/big-docinfo/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "big-docinfo" version = "0.1.0" -edition = "2024" -rust-version = "1.98.1" +edition.workspace = true +rust-version.workspace = true description = "Reads the kind, date, author and key sentences of a document from its text, and suggests a file name, without any model" license.workspace = true repository.workspace = true diff --git a/crates/foundation/big-indexd-client/Cargo.toml b/crates/foundation/big-indexd-client/Cargo.toml index 9eb2c57..b1f1f8c 100644 --- a/crates/foundation/big-indexd-client/Cargo.toml +++ b/crates/foundation/big-indexd-client/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "big-indexd-client" version = "0.1.0" -edition = "2024" -rust-version = "1.98.1" +edition.workspace = true +rust-version.workspace = true description = "Lightweight client and wire types for the big-indexd (big-search) Unix-socket protocol" license.workspace = true repository.workspace = true diff --git a/crates/foundation/big-search-config/Cargo.toml b/crates/foundation/big-search-config/Cargo.toml index 70f27e7..233fb93 100644 --- a/crates/foundation/big-search-config/Cargo.toml +++ b/crates/foundation/big-search-config/Cargo.toml @@ -1,8 +1,8 @@ [package] name = "big-search-config" version = "0.1.0" -edition = "2024" -rust-version = "1.98.1" +edition.workspace = true +rust-version.workspace = true description = "Reader and writer for the big-search configuration file, shared by the daemon and the desktop" license.workspace = true repository.workspace = true diff --git a/rust-toolchain.toml b/rust-toolchain.toml index b0cd3b6..b17b266 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,4 +1,4 @@ [toolchain] -channel = "1.98.1" +channel = "1.100.0" components = ["clippy", "rustfmt"] profile = "minimal" From c61ae18ef7f7110c1188f330b16d877f29390d35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 22:20:02 -0300 Subject: [PATCH 02/10] Read optional prefixes and suffixes with trim_prefix strip_prefix(..).unwrap_or(..) and its suffix form read as the str::trim_prefix and trim_suffix of Rust 1.100. --- apps/big-search/src/extract_mail.rs | 2 +- apps/big-search/src/origin/downloads.rs | 4 ++-- crates/foundation/big-search-config/src/edit.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/big-search/src/extract_mail.rs b/apps/big-search/src/extract_mail.rs index 9ab84b4..ac0cc74 100644 --- a/apps/big-search/src/extract_mail.rs +++ b/apps/big-search/src/extract_mail.rs @@ -129,7 +129,7 @@ fn multipart_text(kind: &str, content_type: &str, body: &str, depth: usize) -> O .split(delimiter.as_str()) .skip(1) .take_while(|part| !part.starts_with("--")) - .map(|part| split_message(part.strip_prefix('\n').unwrap_or(part))) + .map(|part| split_message(part.trim_prefix('\n'))) .collect(); // An alternative's plain text and its HTML say the same: keep one. let plain = parts diff --git a/apps/big-search/src/origin/downloads.rs b/apps/big-search/src/origin/downloads.rs index 7789520..560248a 100644 --- a/apps/big-search/src/origin/downloads.rs +++ b/apps/big-search/src/origin/downloads.rs @@ -98,7 +98,7 @@ pub(super) fn read_xdg_origin_domain(path: &Path) -> Option { /// list or a file's xattr, so anything but a plain host name or IP literal is /// refused rather than stored and later printed. pub(crate) fn domain_from_url(url: &str) -> Option { - let url = url.strip_prefix("blob:").unwrap_or(url); + let url = url.trim_prefix("blob:"); let after_scheme = url.split_once("://")?.1; let authority = after_scheme.split(['/', '?', '#']).next()?; let authority = authority.rsplit('@').next()?; @@ -111,7 +111,7 @@ pub(crate) fn domain_from_url(url: &str) -> Option { valid.then_some(literal)? } else { let name = authority.split(':').next()?; - let name = name.strip_prefix("www.").unwrap_or(name); + let name = name.trim_prefix("www."); let valid = name.len() <= 253 && name .bytes() diff --git a/crates/foundation/big-search-config/src/edit.rs b/crates/foundation/big-search-config/src/edit.rs index 0267ec8..1e57f29 100644 --- a/crates/foundation/big-search-config/src/edit.rs +++ b/crates/foundation/big-search-config/src/edit.rs @@ -383,7 +383,7 @@ pub(crate) fn edit_file( } else if text.is_empty() { (Vec::new(), "\n") } else { - let body = text.strip_suffix('\n').unwrap_or(&text); + let body = text.trim_suffix('\n'); (body.split('\n').map(String::from).collect(), "\n") }; let before = lines.clone(); From 63394de9ca0bdb4b8af7bfa814c2d27697d231d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 22:20:03 -0300 Subject: [PATCH 03/10] big-search: decode owned bytes through one function Files, archive members, pdftotext and antiword output decode through extract::lossy_utf8: valid UTF-8 becomes the string without a copy, and invalid sequences are replaced only after from_utf8 fails. Clippy refuses String::from_utf8_lossy_owned, which validates through Utf8Chunks without from_utf8's word-at-a-time ASCII path: on the test notebook it decoded 750 MB of HTML in 1208 ms against 315 ms. --- apps/big-search/src/extract.rs | 18 +++++++++++------- apps/big-search/src/extract/epub.rs | 4 ++-- apps/big-search/src/extract_pdf.rs | 9 ++------- clippy.toml | 1 + 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/apps/big-search/src/extract.rs b/apps/big-search/src/extract.rs index 51c4e04..be85060 100644 --- a/apps/big-search/src/extract.rs +++ b/apps/big-search/src/extract.rs @@ -420,22 +420,26 @@ fn looks_binary(buf: &[u8]) -> bool { buf.is_empty() || buf.iter().take(8192).any(|&b| b == 0) } +/// `bytes` as text, each invalid UTF-8 sequence as U+FFFD; valid text, nearly +/// all of it, becomes the string without a copy. `String::from_utf8_lossy_owned` +/// validates through `Utf8Chunks`, without `from_utf8`'s word-at-a-time ASCII +/// path. +pub(crate) fn lossy_utf8(bytes: Vec) -> String { + String::from_utf8(bytes).unwrap_or_else(std::string::FromUtf8Error::into_utf8_lossy) +} + /// Decode a text blob: reject empty or binary (NUL in the first chunk), else /// UTF-8, lossily where it has to be. Split out from `read_text` so the decode /// path is fuzzable; it is the path `read_text` really takes, so what the /// fuzzer drives is what runs. /// -/// The bytes are consumed: almost every file read is already valid UTF-8, and -/// then they simply become the string. `from_utf8_lossy(&buf).into_owned()` -/// would copy the whole file a second time even when nothing is replaced. +/// The bytes are consumed so valid UTF-8, almost every file, becomes the +/// string without a second copy. pub fn text_from_bytes(buf: Vec) -> Option { if looks_binary(&buf) { return None; } - Some(match String::from_utf8(buf) { - Ok(text) => text, - Err(invalid) => String::from_utf8_lossy(invalid.as_bytes()).into_owned(), - }) + Some(lossy_utf8(buf)) } pub(crate) fn truncate_to_char_boundary(text: &mut String, max_bytes: usize) { diff --git a/apps/big-search/src/extract/epub.rs b/apps/big-search/src/extract/epub.rs index 17a419f..ad36abb 100644 --- a/apps/big-search/src/extract/epub.rs +++ b/apps/big-search/src/extract/epub.rs @@ -28,7 +28,7 @@ pub(super) fn read_epub(path: &Path) -> Option<(String, Option)> { .take(limit as u64) .read_to_end(&mut bytes) .ok()?; - Some(String::from_utf8_lossy(&bytes).into_owned()) + Some(crate::extract::lossy_utf8(bytes)) }; let container = part("META-INF/container.xml", cap)?; let opf_path = epub_package(container.as_bytes())?; @@ -153,5 +153,5 @@ fn percent_decoded(href: &str) -> String { out.push(bytes[i]); i += 1; } - String::from_utf8_lossy(&out).into_owned() + crate::extract::lossy_utf8(out) } diff --git a/apps/big-search/src/extract_pdf.rs b/apps/big-search/src/extract_pdf.rs index 4b9858c..d26f769 100644 --- a/apps/big-search/src/extract_pdf.rs +++ b/apps/big-search/src/extract_pdf.rs @@ -20,12 +20,7 @@ use std::time::Duration; pub(crate) fn read_pdf(path: &Path) -> Option { let cap = crate::extract::max_extract_bytes(); let bytes = pdftotext_capped(path, cap, &[])?; - // Valid UTF-8 (every ordinary PDF) becomes the string without a second copy. - let text = match String::from_utf8(bytes) { - Ok(text) => text, - Err(invalid) => String::from_utf8_lossy(invalid.as_bytes()).into_owned(), - }; - text_layer(text, cap) + text_layer(crate::extract::lossy_utf8(bytes), cap) } /// Pages read to describe a PDF. Its title, kind and date are in its opening, @@ -125,7 +120,7 @@ fn pdftotext_capped(path: &Path, max_bytes: usize, options: &[&str]) -> Option Option { let cap = crate::extract::max_extract_bytes(); let bytes = run_capped("antiword", path, cap, &["-m", "UTF-8.txt", "-w", "0"])?; - text_layer(String::from_utf8_lossy(&bytes).into_owned(), cap) + text_layer(crate::extract::lossy_utf8(bytes), cap) } /// Runs `program` (`pdftotext` to stdout, `pdfinfo` or `antiword`) on diff --git a/clippy.toml b/clippy.toml index e3a67c1..be24ece 100644 --- a/clippy.toml +++ b/clippy.toml @@ -27,6 +27,7 @@ disallowed-methods = [ { path = "std::io::stdin", reason = "stdin blocks; the daemon has no interactive input" }, { path = "zip::read::ZipArchive::new", reason = "open archives through extract::capped_zip, which refuses one declaring too many entries" }, { path = "libc::statvfs", reason = "ask history::disk (identity, disk_capacity), which reads f_fsid and the free space" }, + { path = "std::string::String::from_utf8_lossy_owned", reason = "decode through extract::lossy_utf8, whose from_utf8 validates ASCII a word at a time" }, { path = "std::os::unix::fs::MetadataExt::dev", reason = "a file kept across a restart is told by history::identity: btrfs draws st_dev anew at each mount" }, ] From bc9a6c4e54dfd7c2a7a408b364a01a82fc9c22b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 13:01:37 -0300 Subject: [PATCH 04/10] big-search: match the design notes to the code The design notes described a NOT EXISTS stale pass and a paths_after backfill that no longer exist, reflink dedupe as always on, a start that always repairs the name index, and one extraction worker on any dual-core CPU. They now state what the code does, list every module, and the README links BigDesktop's real repository. --- README.md | 2 +- apps/big-search/DESIGN.md | 117 +++++++++++++++++++-------------- apps/big-search/src/content.rs | 4 +- 3 files changed, 70 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index e043161..182dc8d 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ The indexes and state live in `~/.local/share/big-search/`; the socket is `cargo build` compiles only the daemon; add `--workspace` for `big-docinfo` and the libraries. The settings window that edits `config.toml` belongs to -[BigDesktop](https://github.com/biglinux/big), which takes the two +[BigDesktop](https://github.com/biglinux/bigdesktop), which takes the two libraries above from this repository. ## Help diff --git a/apps/big-search/DESIGN.md b/apps/big-search/DESIGN.md index 60349a8..250606a 100644 --- a/apps/big-search/DESIGN.md +++ b/apps/big-search/DESIGN.md @@ -46,9 +46,10 @@ Measured on one real home folder: ## 2. Shape -One binary: `big-search daemon` is the service, every other subcommand is a -client. The core is synchronous: standard threads and channels, no async -runtime. +One binary: `big-search daemon` is the service and the search and control +subcommands are its clients; `reindex`, `count`, `list` and `config` work on +the files directly. The core is synchronous: standard threads and channels, no +async runtime. ```text daemon (user service, unprivileged) @@ -79,15 +80,18 @@ A query never waits for extraction, and indexing yields the CPU to queries |---|---| | `scan.rs`, `scan_roots.rs` | the walk of visible files; resolving configured roots and top-level symlinks | | `watch.rs` | inotify, coalescing, overflow rescans, segment compaction | -| `content.rs`, `content_dedupe.rs` | the background content pass; reading reflinked copies once | -| `extract*.rs`, `mime.rs`, `meta.rs` | text, media type and metadata of an untrusted file | +| `mounts.rs` | which mount holds a path, from `/proc/self/mountinfo`; removable and network sources | +| `content.rs`, `content_dedupe.rs` | the background content pass; reading reflinked copies once, when enabled | +| `extract*.rs`, `mime.rs`, `meta.rs`, `prominent.rs` | text, media type and metadata of an untrusted file; the lines it sets as its title | | `index.rs`, `nosync_dir.rs`, `cjk_tokenizer.rs` | the two tantivy indexes, their analyzers and directory | +| `fold.rs`, `simplified_chinese.rs` | case and script folding; Traditional to Simplified Chinese | | `query.rs` | name, content and combined search, ranking, page lookup | | `catalogue.rs` | the `path -> (mtime, size)` catalogue | | `ipc.rs` | the socket server | | `throttle.rs` | background priority, the indexer's cgroup, backfill pacing | | `history.rs`, `origin.rs`, `browser_downloads.rs` | earlier versions and where a file came from | | `settings.rs`, `config.rs` | configuration and XDG paths | +| `index_cmd.rs`, `config_cmd.rs` | the `daemon` and `reindex` commands, which hold the index writers; the `config` command | ## 3. Indexes @@ -122,15 +126,18 @@ never the bottleneck, and cost 104 MB of RSS. Both indexes and the state store are a cache derived from the filesystem, so the daemon never calls `fsync` on the indexes (`nosync_dir.rs`). The worst a forced reboot costs is documents whose commits did not reach the disk. Each -start compares the name index with the catalogue and re-adds the name -documents the catalogue still lists (`index::repair_deflated_against_state`); -a stale or missing document whose catalogue row is current, a content document -included, needs `big-search rebuild`, since a rescan compares the disk with -the catalogue only. A torn index fails to open and -`index::open_or_create` recreates it. Measured over ten minutes of near-idle -churn, tantivy's syncs were 145 calls to write a few kilobytes, and 4.07 GB of -logical writes landed as 17.9 GB at the block layer. The directory also watches -`meta.json` with inotify instead of letting tantivy poll it every 500 ms. +start compares the name index's document count with the catalogue's. A +deficit of up to 1 % of the catalogue (at least 1000 documents) re-adds the +missing name documents (`index::repair_deflated_against_state`); a larger +deficit, or a surplus past 20 % (at least 10,000), recreates the name index and +clears the catalogue, so the start walks every folder. A stale or missing +document whose catalogue row is current, a content document included, needs +`big-search rebuild`, since a rescan compares the disk with the catalogue +only. A torn index fails to open and `index::open_or_create` recreates it. +Measured over ten minutes of near-idle churn, tantivy's syncs were 145 calls to +write a few kilobytes, and 4.07 GB of logical writes landed as 17.9 GB at the +block layer. The directory also watches `meta.json` with inotify instead of +letting tantivy poll it every 500 ms. ### Segments and reads @@ -144,13 +151,14 @@ A cold query pays per segment, about 70 to 100 ms each on a 5400 rpm disk, and tantivy's merge policy leaves 7 to 12 segments and never merges a large one for its deletes (the daemon's largest segments held a third of dead documents). So when a content backfill pass finishes, off battery, each index is merged into -one segment once a tenth of it changed, and otherwise its small segments are -joined into one (`watch::compact_when_worth_it`, `index::worth_compacting`). On -the notebook, over 18,000 simulated edits this wrote less than the default -policy (334 against 355 MB) and left at most 2 segments instead of 4: cold -queries took 124 to 374 ms instead of 335 to 655 ms, and 55 to 213 ms right -after a full merge. On the notebook's own index a full merge took 61 MB to 32 MB -and cold queries from 743 to 1041 ms down to 42 to 62 ms. +one segment once a tenth of it changed, and otherwise, with three segments or +more, its small segments are joined into one (`watch::compact_when_worth_it`, +`index::worth_compacting`). On the notebook, over 18,000 simulated edits this +wrote less than the default policy (334 against 355 MB) and left at most 2 +segments instead of 4: cold queries took 124 to 374 ms instead of 335 to 655 +ms, and 55 to 213 ms right after a full merge. On the notebook's own index a +full merge took 61 MB to 32 MB and cold queries from 743 to 1041 ms down to 42 +to 62 ms. SQLite FTS5, measured on the same machine and corpus, was 7 to 65x slower on common terms with a warm cache, slower to build and larger, so the engine is @@ -188,8 +196,9 @@ cost nothing measurable cold ("zz relatorio" 1013 ms against "relatorio zz" 1019 ms, both dominated by opening the indexes). Every word also matches its plural or singular by suffix rules on folded words -(`query::inflections`: Portuguese and Spanish -ões, -ais, -eis, -ns, -res, -zes -and -s; English -es after x, ch and sh), ranked below the word as typed. +of four letters or more (`query::inflections`: Portuguese and Spanish -ões, +-ães, -ãos, -ais, -eis, -óis, -uis, -ns, -res, -zes, -ses and -s; English -es +after x, ch and sh), ranked below the word as typed. Snowball was measured on this index's own 5.5-million-term vocabulary first: on folded words it joined none of 670 -ões, 421 -ais, 261 -eis and 194 -ns pairs to their singulars, merged "casa" with "caso", "casado" and "case", and @@ -258,13 +267,13 @@ test 3 % larger. Traditional Chinese characters are folded to their simplified forms (`simplified_chinese.rs`: 3079 pairs from ICU's `Traditional-Simplified` -transform taken one character at a time, under the Unicode License v3 notice -the file carries), so "会议记录" finds "會議記錄" and back, in names and content. -A character table needs no dictionary: zh_CN and zh_TW message pairs that differ -only in characters are all found across scripts, none without it. Pairs whose -words differ by region (文档/文件, 打印/列印, 音频/音訊) are found 24 % of the time -(9 % without); joining those needs a phrase list, which this does not attempt. -Japanese results are unaffected. +transform taken one character at a time, under the Unicode License v3 in +`LICENSES/Unicode-3.0.txt`), so "会议记录" finds "會議記錄" and back, in names +and content. A character table needs no dictionary: zh_CN and zh_TW message +pairs that differ only in characters are all found across scripts, none +without it. Pairs whose words differ by region (文档/文件, 打印/列印, +音频/音訊) are found 24 % of the time (9 % without); joining those needs a +phrase list, which this does not attempt. Japanese results are unaffected. ### Memory and build @@ -307,10 +316,12 @@ nothing above it is tested: a `.gitignore` above a source speaks only for what lies below it. The walk reads each folder's files once on the way down; the watcher reads them only for a path new to the catalogue. The global excludes file is read once per run, as the effective rules are. -Symlinks are never followed during the walk; a symlinked folder at the top of a -root is resolved into a root of its own by `scan_roots::resolve_roots` according -to the symlink policy, and network mounts, virtual mounts and operating-system -trees are rejected as roots. The walk runs at background priority (section 7). +Symlinks are never followed during the walk. With `follow_symlinks` on (off by +default), a symlinked folder at the top of a root is resolved into a root of +its own by `scan_roots::resolve_roots_with_policy`: a target on anything but a +known local filesystem is skipped, and under the default `personal-local` +policy so are operating-system trees. The walk runs at background priority +(section 7). ## 5. Watch @@ -338,15 +349,17 @@ hidden and gitignored churn never wakes the daemon. ## 6. Extraction -The content pass runs a small pool of extraction workers: 2, or 1 on a -low-memory or dual-core machine (`content::default_workers`; +The content pass runs a small pool of extraction workers: 2, or 1 when the +service may use less than 6 GiB of memory or the machine has two logical CPUs +or fewer (`content::default_workers`; `BIG_SEARCH_CONTENT_WORKERS` overrides it, up to 4). Workers extract concurrently and a single writer applies the results through a bounded channel, so workers block when the writer falls behind. A changed file is left alone for `content_cooldown_secs` (900 s by default) before its text is read again, so a document being edited is not re-read on every save. Files whose `(mtime, size)` -match the state store are never read again, and reflinked copies sharing the -same physical extents are read once (`content_dedupe.rs`). +match the state store are never read again. With `BIG_SEARCH_DEDUP_CONTENT` +set (off by default), reflinked copies sharing the same physical extents are +read once (`content_dedupe.rs`). | Format | Method | |---|---| @@ -357,7 +370,7 @@ same physical extents are read once (`content_dedupe.rs`). | EPUB | container, package and spine chapters, read as HTML | | `eml` | headers and the plain or HTML body: MIME parts, base64, quoted-printable, RFC 2047 (`extract_mail.rs`) | | RTF | control words, `\'hh` and `\u` escapes, skipped destinations (`extract_rtf.rs`) | -| `doc` (OLE2) | `antiword` subprocess; an RTF file saved as `.doc` goes to the RTF reader | +| `doc` | refused past `office_max_mb`; OLE2 through the `antiword` subprocess, an RTF file saved as `.doc` through the RTF reader, plain text as text | Every indexed file is untrusted input. Subprocesses get argv arrays, never a shell, a null stdin and a capped stdout, with `RLIMIT_AS`, a CPU-time limit and @@ -368,7 +381,8 @@ are refused past `office_max_mb` (0 chooses 64 or 256 MiB by machine), 4096 entries or 512 slides or sheets; each part's decompressed size is capped, and so is the markup read from one archive (four extraction caps). Plain text and PDF have optional size limits (`text_max_mb`, `pdf_max_mb`, 0 by -default) and PDF a deadline (`pdf_timeout_secs`, 5 s). +default), and PDF and Word documents a time budget (`pdf_timeout_secs`, 5 s of +work; section 7). ### PDF through `pdftotext` @@ -595,16 +609,19 @@ a 64 MiB mmap window. Peak memory does not grow with the catalogue: -- A reconcile (`scan::sync`, overflow and rebuild) records the paths it sees in - a temporary `current_scan_seen` `WITHOUT ROWID` table as the walker emits - them, flushing pending state changes every 2048 rows. -- Stale paths are selected with `NOT EXISTS` against that table in ordered - 2048-row pages, so deletion never holds the whole stale set. +- A reconcile (`scan::sync`, overflow and rebuild) records the paths the + walker emits in a temporary `current_scan_seen` `WITHOUT ROWID` table. +- That table and the catalogue are then read side by side in path order, 2048 + rows at a time (`State::scan_changes_after`). The merge yields each new, + changed and gone path, so deletion never holds the whole stale set, and + pending state changes are flushed every 2048 rows. - The roots of offline removable and network sources are marked seen before - the stale pass, so an unplugged device keeps its catalogue. -- The content backfill streams the name catalogue (`paths_after`) and picks a - batch bounded by count and by estimated bytes to read, so expensive PDFs and - office files cannot take over the memory. + that comparison, so an unplugged device keeps its catalogue. +- The content backfill picks each batch with one SQL join of the name and + content catalogues, resumed from a cursor + (`content::pending_catalog_batch_after`) and bounded by count and by + estimated bytes to read, so expensive PDFs and office files cannot take over + the memory. - `big-search count` without `--under` reads tantivy's document count. - PDF page lookup uses the same capped `pdftotext` reader as indexing. @@ -649,7 +666,7 @@ or `0`, `false`, `no` or `off`, in any case; any other value is ignored. | `BIG_SEARCH_ORIGIN`, `BIG_SEARCH_ORIGIN_WATCH`, `BIG_SEARCH_ORIGIN_BROWSER_HISTORY` | `[origin]` `enabled` (and the watch it starts), `browser_history` | | `BIG_SEARCH_ORIGIN_XATTR`, `BIG_SEARCH_ORIGIN_QUERY`, `BIG_SEARCH_ORIGIN_MAX_BATCH` | origin from extended attributes, origin in query results, origin paths gathered before a write | | `BIG_SEARCH_META_SNIFF`, `_AUDIO`, `_VIDEO`, `_IMAGE`, `BIG_SEARCH_META_MAX_MB` | metadata by content type and its read cap (`meta.rs`) | -| `BIG_SEARCH_CONTENT_WORKERS`, `BIG_SEARCH_DEDUP_CONTENT` | extraction workers (up to 4), reading reflinked copies once | +| `BIG_SEARCH_CONTENT_WORKERS`, `BIG_SEARCH_DEDUP_CONTENT` | extraction workers (up to 4), reading reflinked copies once (off by default) | | `BIG_SEARCH_BACKGROUND_WRITER_MB`, `BIG_SEARCH_BULK_WRITER_MB`, `BIG_SEARCH_CONTENT_WRITER_MB` | tantivy writer memory | | `BIG_SEARCH_BENCH` | prints timings from `reindex` | diff --git a/apps/big-search/src/content.rs b/apps/big-search/src/content.rs index 3b7be99..5930b56 100644 --- a/apps/big-search/src/content.rs +++ b/apps/big-search/src/content.rs @@ -211,8 +211,8 @@ const CATALOG_PATH_BATCH: usize = 2048; const DEFAULT_CATALOG_CONTENT_BATCH: usize = 1000; /// Default worker count: 2 on desktop-class machines (the DESIGN.md §6 pool -/// width), 1 on low-memory or dual-core hardware so extraction never dominates -/// the machine. +/// width), 1 on low-memory hardware or two logical CPUs or fewer, so extraction +/// never dominates the machine. pub(crate) fn default_workers() -> usize { let cores = std::thread::available_parallelism() .map(std::num::NonZero::get) From b4fd068dcff56f1c1507f16d4ed66bc2d5ebeaf1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 17:18:53 -0300 Subject: [PATCH 05/10] big-search: read HTML markup by bytes with memchr html_text lowercased a copy of every page, built " Option { (!text.is_empty()).then_some(text) } -/// Elements that sit inside a line of text: the others separate words. -const INLINE_TAGS: &[&str] = &[ - "a", "abbr", "b", "bdi", "bdo", "cite", "code", "data", "dfn", "em", "font", "i", "kbd", - "mark", "q", "s", "samp", "small", "span", "strong", "sub", "sup", "time", "u", "var", "wbr", +/// Whether `name`, lowercase, is an element that sits inside a line of text: +/// the others separate words. +fn is_inline_element(name: &[u8]) -> bool { + matches!( + name, + b"a" | b"abbr" + | b"b" + | b"bdi" + | b"bdo" + | b"cite" + | b"code" + | b"data" + | b"dfn" + | b"em" + | b"font" + | b"i" + | b"kbd" + | b"mark" + | b"q" + | b"s" + | b"samp" + | b"small" + | b"span" + | b"strong" + | b"sub" + | b"sup" + | b"time" + | b"u" + | b"var" + | b"wbr" + ) +} + +/// Openings, lowercase, of the elements that end a line: a prefix, so `` and `
`. +const BLOCK_TAG_OPENINGS: &[&[u8]] = &[ + b" Option { + memchr::memchr_iter(needle[0], haystack).find(|&at| { + haystack + .get(at..at + needle.len()) + .is_some_and(|found| found.eq_ignore_ascii_case(needle)) + }) +} + /// The readable text of HTML: scripts and styles dropped, block elements as /// line breaks, entities decoded. Enough to read a saved page's /// title and dates, not a renderer. +/// +/// Markup is matched by bytes with ASCII case ignored: every byte it looks for +/// is ASCII, so each position found is a char boundary. pub fn html_text(html: &str) -> String { - let lower = html.to_ascii_lowercase(); - let mut out = String::with_capacity(html.len() / 2); + let bytes = html.as_bytes(); + // What is kept is cut from the page, so its length nearly always fits. + let mut out = String::with_capacity(html.len()); let mut at = 0; - while let Some(open) = lower[at..].find('<').map(|i| at + i) { + while let Some(open) = memchr::memchr(b'<', &bytes[at..]).map(|i| at + i) { out.push_str(&html[at..open]); - let tag_end = lower[open..].find('>').map_or(html.len(), |i| open + i + 1); - let tag = &lower[open..tag_end]; + let tag_end = memchr::memchr(b'>', &bytes[open..]).map_or(html.len(), |i| open + i + 1); + let tag = &bytes[open..tag_end]; + // The tag's start, lowercased once: every opening compared fits in it, + // and the NUL padding of a shorter tag matches none of them. + let mut head = [0u8; 8]; + let head_len = tag.len().min(head.len()); + head[..head_len].copy_from_slice(&tag[..head_len]); + head.make_ascii_lowercase(); // An unclosed script or style runs to the end, as in a browser; searching // again from every later opener would make the scan quadratic. - let skip_to = ["script", "style"].iter().find_map(|name| { - tag.starts_with(&format!("<{name}")).then(|| { - lower[tag_end..] - .find(&format!(" String { } if block { out.push('\n'); - } else if skip_to.is_none() && !name.is_empty() && !INLINE_TAGS.contains(&name) { + } else if skip_to.is_none() && !name.is_empty() && !inline { // A table cell, a list or any other box ends the word before it. out.push(' '); } at = skip_to.unwrap_or(tag_end).min(html.len()); } out.push_str(&html[at.min(html.len())..]); - decode_entities(&out) + decode_entities(out) } -/// `&`, ` `, `—`, `—` and the like as characters. -fn decode_entities(s: &str) -> String { - let mut out = String::with_capacity(s.len()); - let mut rest = s; - while let Some(at) = rest.find('&') { +/// `&`, ` `, `—`, `—` and the like as characters; text +/// without an `&` is returned as it is. +fn decode_entities(text: String) -> String { + let Some(first) = memchr::memchr(b'&', text.as_bytes()) else { + return text; + }; + let mut out = String::with_capacity(text.len()); + out.push_str(&text[..first]); + let mut rest = &text[first..]; + while let Some(at) = memchr::memchr(b'&', rest.as_bytes()) { out.push_str(&rest[..at]); rest = &rest[at..]; // Only as far as the longest HTML5 name: a search to the end for every @@ -353,27 +424,8 @@ fn decode_entities(s: &str) -> String { .take(33) .position(|&b| b == b';') .map(|end| &rest[1..=end]); - let decoded = |e: &str| -> Option> { - if e == "nbsp" { - return Some(" ".into()); - } - match e.strip_prefix('#') { - Some(number) => number - .strip_prefix(['x', 'X']) - .map_or_else( - || number.parse().ok(), - |hex| u32::from_str_radix(hex, 16).ok(), - ) - .and_then(char::from_u32) - .map(|c| c.to_string().into()), - None => quick_xml::escape::resolve_html5_entity(e).map(Into::into), - } - }; - match entity.and_then(|e| Some((e, decoded(e)?))) { - Some((e, text)) => { - out.push_str(&text); - rest = &rest[e.len() + 2..]; - } + match entity { + Some(entity) if push_entity(entity, &mut out) => rest = &rest[entity.len() + 2..], _ => { out.push('&'); rest = &rest[1..]; @@ -384,6 +436,31 @@ fn decode_entities(s: &str) -> String { out } +/// Pushes the character an entity's name or number (between `&` and `;`) +/// stands for; false, pushing nothing, when it stands for none. +fn push_entity(entity: &str, out: &mut String) -> bool { + if entity == "nbsp" { + out.push(' '); + return true; + } + if let Some(number) = entity.strip_prefix('#') { + let code = match number.strip_prefix(['x', 'X']) { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => number.parse().ok(), + }; + let Some(c) = code.and_then(char::from_u32) else { + return false; + }; + out.push(c); + return true; + } + let Some(text) = quick_xml::escape::resolve_html5_entity(entity) else { + return false; + }; + out.push_str(text); + true +} + /// Extract text for a file identified by content sniffing (no usable extension): /// PDF via `pdftotext`, HTML as its readable text, anything else `text/*` as /// plain text. Used by the metadata pass so an extension-less document is still @@ -417,7 +494,7 @@ fn text_input_size(path: &Path) -> Option { /// A blob with no text in it: empty, or holding a NUL byte early on. fn looks_binary(buf: &[u8]) -> bool { - buf.is_empty() || buf.iter().take(8192).any(|&b| b == 0) + buf.is_empty() || memchr::memchr(0, &buf[..buf.len().min(8192)]).is_some() } /// `bytes` as text, each invalid UTF-8 sequence as U+FFFD; valid text, nearly diff --git a/apps/big-search/src/extract/epub.rs b/apps/big-search/src/extract/epub.rs index ad36abb..9304e13 100644 --- a/apps/big-search/src/extract/epub.rs +++ b/apps/big-search/src/extract/epub.rs @@ -71,7 +71,7 @@ fn xml_attribute(e: &quick_xml::events::BytesStart<'_>, name: &str) -> Option std::borrow::Cow<'_, str> { use unicode_normalization::{IsNormalized, UnicodeNormalization, is_nfkc_quick}; - if text.is_ascii() || is_nfkc_quick(text.chars()) == IsNormalized::Yes { - return std::borrow::Cow::Borrowed(text); - } + let bytes = text.as_bytes(); let cap = max_extract_bytes(); - let mut out = String::with_capacity(text.len().min(cap)); - for c in text.nfkc() { + // Created at the first run that changes; `text[copied..]` is not in it yet. + let mut out: Option = None; + let mut copied = 0; + let mut at = 0; + while let Some(non_ascii) = first_non_ascii(&bytes[at..]).map(|i| at + i) { + // The ASCII character before a run may take its combining marks. + let start = non_ascii.saturating_sub(1).max(at); + let end = bytes[non_ascii..] + .iter() + .position(u8::is_ascii) + .map_or(bytes.len(), |i| non_ascii + i); + let run = &text[start..end]; + if is_nfkc_quick(run.chars()) != IsNormalized::Yes { + let out = out.get_or_insert_with(|| String::with_capacity(text.len().min(cap))); + if !push_str_within_cap(out, &text[copied..start], cap) + || !push_within_cap(out, run.nfkc(), cap) + { + return std::borrow::Cow::Owned(std::mem::take(out)); + } + copied = end; + } + at = end; + } + match out { + None => std::borrow::Cow::Borrowed(text), + Some(mut out) => { + push_str_within_cap(&mut out, &text[copied..], cap); + std::borrow::Cow::Owned(out) + } + } +} + +/// [`push_within_cap`] for text already normalized: whole when it fits. +fn push_str_within_cap(out: &mut String, text: &str, cap: usize) -> bool { + if out.len() + text.len() <= cap { + out.push_str(text); + return true; + } + push_within_cap(out, text.chars(), cap) +} + +/// Pushes `chars` while they fit in `cap` bytes; false at the first that does +/// not, which is left out with all after it. +fn push_within_cap(out: &mut String, chars: impl Iterator, cap: usize) -> bool { + for c in chars { if out.len() + c.len_utf8() > cap { - break; + return false; } out.push(c); } - std::borrow::Cow::Owned(out) + true +} + +/// The index of the first byte of `bytes` above ASCII, 16 bytes at a time +/// until the block that holds it. +fn first_non_ascii(bytes: &[u8]) -> Option { + let (blocks, _) = bytes.as_chunks::<16>(); + let ascii_blocks = blocks + .iter() + .position(|block| !block.is_ascii()) + .unwrap_or(blocks.len()); + let skipped = ascii_blocks * 16; + bytes[skipped..] + .iter() + .position(|b| !b.is_ascii()) + .map(|i| skipped + i) } /// The folding of lowercase text that `AsciiFoldingFilter` leaves to others: @@ -108,6 +168,34 @@ thread_local! { mod tests { use super::*; + /// Oracle: `nfkc()` over the whole text, which `compose` cuts into runs. + /// Every string of up to four characters from marks of several combining + /// classes, Hangul jamo, compatibility characters and ASCII. + #[test] + fn composed_runs_equal_whole_text_nfkc() { + use unicode_normalization::UnicodeNormalization; + const ALPHABET: [char; 22] = [ + 'a', 'e', 'n', ' ', 'é', '\u{0301}', '\u{0327}', '\u{0323}', '\u{0315}', '\u{0345}', + '\u{1100}', '\u{1161}', '\u{11A8}', '\u{AC00}', '\u{FB01}', '\u{2026}', '\u{00A0}', + '\u{FF21}', '\u{304B}', '\u{3099}', '\u{0F73}', '\u{1E0B}', + ]; + let mut text = String::new(); + let mut digits = [0usize; 4]; + for len in 1..=digits.len() { + let combinations = ALPHABET.len().pow(u32::try_from(len).unwrap()); + for mut n in 0..combinations { + text.clear(); + for digit in &mut digits[..len] { + *digit = n % ALPHABET.len(); + n /= ALPHABET.len(); + text.push(ALPHABET[*digit]); + } + let whole: String = text.nfkc().collect(); + assert_eq!(compose(&text), whole, "{}", text.escape_unicode()); + } + } + } + #[test] fn composed_text_stops_at_extraction_cap() { let _lock = crate::test_env::ENV_LOCK From b93559b3926f61c4bfe472e84ce15efc363f2b31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 21:27:05 -0300 Subject: [PATCH 07/10] big-search: merge each index once at the end of reindex Reindex writes the name and content indexes with no merges and merges each into one segment when its pass ends, also when the pass fails halfway. On the reference notebook this cut CPU time from 106 to 92 s and disk writes from 148 to 117 MB, and left one segment per index, so cold queries read less; the run takes 91 to 99 s instead of 78 to 79 s, since the final merge runs alone. The daemon keeps tantivy's merge policy, because its queries run while it indexes. --- apps/big-search/DESIGN.md | 8 ++++++++ apps/big-search/src/content.rs | 26 +++++++++++++++++--------- apps/big-search/src/content/tests.rs | 5 +++++ apps/big-search/src/index.rs | 18 ++++++++++++++++++ apps/big-search/src/index_cmd.rs | 10 ++++++++-- apps/big-search/src/scan.rs | 9 ++++----- 6 files changed, 60 insertions(+), 16 deletions(-) diff --git a/apps/big-search/DESIGN.md b/apps/big-search/DESIGN.md index 250606a..becde82 100644 --- a/apps/big-search/DESIGN.md +++ b/apps/big-search/DESIGN.md @@ -160,6 +160,14 @@ ms, and 55 to 213 ms right after a full merge. On the notebook's own index a full merge took 61 MB to 32 MB and cold queries from 743 to 1041 ms down to 42 to 62 ms. +`reindex` writes both indexes without merges and merges each into one segment +at the end (`index::merge_into_one_segment`): tantivy's policy rewrites the same +documents in every larger merge. On the notebook's corpus this cut CPU time +from 106 to 92 s and disk writes from 148 to 117 MB, and cold queries took a +third to two thirds less time; the run took 91 to 99 s instead of 78 to 79 s, +since the final merge runs alone, and peaked at 145 MB instead of 128 MB. The daemon +keeps tantivy's policy, because its queries run while it indexes. + SQLite FTS5, measured on the same machine and corpus, was 7 to 65x slower on common terms with a warm cache, slower to build and larger, so the engine is tantivy. diff --git a/apps/big-search/src/content.rs b/apps/big-search/src/content.rs index 5930b56..53a3712 100644 --- a/apps/big-search/src/content.rs +++ b/apps/big-search/src/content.rs @@ -244,8 +244,9 @@ fn content_channel_capacity() -> usize { } /// Index all pending content/metadata by streaming the name catalogue from -/// SQLite in bounded batches. This avoids constructing `Vec` for the -/// full catalogue during a reindex or daemon backfill. +/// SQLite in bounded batches, for `reindex`. This avoids constructing +/// `Vec` for the full catalogue. Nothing merges until the pass ends in +/// one segment ([`crate::index::merge_into_one_segment`]). /// /// # Errors /// @@ -256,9 +257,19 @@ pub fn index_pending_catalog(index: &Index) -> Result { return Ok(0); } let f = content_fields(index)?; - // One writer for the whole pass: a writer per batch, dropped without - // waiting, leaves its merges running, and they pile up across batches. let mut writer = crate::index::content_writer(index).context("content writer")?; + writer.set_merge_policy(Box::new(tantivy::indexer::NoMergePolicy)); + let pass = index_catalog_batches(&mut writer, &f); + // A pass that fails halfway has committed its batches: merged, they cost + // the daemon's queries one segment instead of one per batch. + let merged = crate::index::merge_into_one_segment(writer).context("merge the content index"); + let indexed = pass?; + merged?; + Ok(indexed) +} + +/// The batches of [`index_pending_catalog`], each committed through `writer`. +fn index_catalog_batches(writer: &mut IndexWriter, f: &ContentFields) -> Result { let mut indexed_total = 0u64; let mut cursor: CatalogCursor = None; loop { @@ -274,8 +285,8 @@ pub fn index_pending_catalog(index: &Index) -> Result { break; } let read = index_content_limited_with_writer( - &mut writer, - &f, + writer, + f, batch.files, Some(catalog_content_batch_limit()), )?; @@ -284,9 +295,6 @@ pub fn index_pending_catalog(index: &Index) -> Result { break; } } - writer - .wait_merging_threads() - .context("wait content merges")?; Ok(indexed_total) } diff --git a/apps/big-search/src/content/tests.rs b/apps/big-search/src/content/tests.rs index e2438a9..0d81037 100644 --- a/apps/big-search/src/content/tests.rs +++ b/apps/big-search/src/content/tests.rs @@ -534,6 +534,11 @@ fn catalog_pass_indexes_every_batch() { 3, "every batch of the pass is extracted" ); + assert_eq!( + index.searchable_segment_ids().unwrap().len(), + 1, + "the pass ends in one segment" + ); let content_state = catalogue::State::load( &crate::config::state_db_path(), crate::catalogue::CONTENT_NAMESPACE, diff --git a/apps/big-search/src/index.rs b/apps/big-search/src/index.rs index 2606d58..e487053 100644 --- a/apps/big-search/src/index.rs +++ b/apps/big-search/src/index.rs @@ -727,6 +727,24 @@ fn writer_memory_budget_mb(env_name: &str, default_mb: usize) -> usize { .saturating_mul(1 << 20) } +/// Merges every segment of the writer's index into one, then closes the +/// writer. `reindex` writes with [`tantivy::indexer::NoMergePolicy`] and ends +/// here whatever it wrote: tantivy's policy merges the small segments as they +/// appear and rewrites the same documents again in each larger merge, and one +/// merge at the end writes them once and leaves the single segment a cold +/// query reads fastest. +/// +/// # Errors +/// +/// Returns an error when the segments cannot be listed or a merge fails. +pub fn merge_into_one_segment(mut writer: IndexWriter) -> Result<()> { + let segments = writer.index().searchable_segment_ids()?; + if segments.len() > 1 { + writer.merge(&segments).wait().context("merge segments")?; + } + writer.wait_merging_threads().context("wait merges") +} + fn low_impact_writer(index: &Index, memory_budget: usize) -> Result> { let options = IndexWriterOptions::builder() .num_worker_threads(1) diff --git a/apps/big-search/src/index_cmd.rs b/apps/big-search/src/index_cmd.rs index 2997817..f73219a 100644 --- a/apps/big-search/src/index_cmd.rs +++ b/apps/big-search/src/index_cmd.rs @@ -42,7 +42,12 @@ pub(super) fn cmd_reindex(roots: &[String]) -> Result<()> { }; let t0 = Instant::now(); - let sync_outcome = scan::sync(&index, &scan_roots, &mut state)?; + let mut name_writer = index::bulk_writer(&index)?; + name_writer.set_merge_policy(Box::new(tantivy::indexer::NoMergePolicy)); + let synced = scan::sync(&mut name_writer, &scan_roots, &mut state); + let merged = index::merge_into_one_segment(name_writer).context("merge the name index"); + let sync_outcome = synced?; + merged?; let names = index::document_count(&index.reader()?); println!( "indexed {names} names in {:.2}s", @@ -830,7 +835,8 @@ fn sync_with_retry( const RETRY_DELAY: std::time::Duration = std::time::Duration::from_secs(10); let mut last_error = None; for attempt in 1..=ATTEMPTS { - match scan::sync(index, roots, state) { + match index::bulk_writer(index).and_then(|mut writer| scan::sync(&mut writer, roots, state)) + { Ok(count) => return Ok(count), Err(e) => { log::warn!("sync attempt {attempt}/{ATTEMPTS} failed: {e:#}"); diff --git a/apps/big-search/src/scan.rs b/apps/big-search/src/scan.rs index d147625..393686b 100644 --- a/apps/big-search/src/scan.rs +++ b/apps/big-search/src/scan.rs @@ -7,7 +7,7 @@ use ignore::WalkBuilder; use std::io::ErrorKind::{NotFound, PermissionDenied}; use std::path::{Path, PathBuf}; use std::sync::PoisonError; -use tantivy::{Index, IndexWriter, TantivyDocument, Term}; +use tantivy::{IndexWriter, TantivyDocument, Term}; mod scope; pub(crate) use scope::work_tree_root; @@ -259,11 +259,10 @@ pub fn visible_dirs(root: &Path) -> Vec { /// /// Returns an error when the catalogue cannot be read or written, or the index cannot be /// committed. -pub fn sync(index: &Index, roots: &[PathBuf], state: &mut State) -> Result { - let f = crate::index::fields(index)?; - let mut writer = crate::index::bulk_writer(index)?; +pub fn sync(writer: &mut IndexWriter, roots: &[PathBuf], state: &mut State) -> Result { + let f = crate::index::fields(writer.index())?; let mut visible_dirs = Vec::new(); - let outcome = reconcile_roots(&mut writer, &f, state, roots, None, &mut |dir| { + let outcome = reconcile_roots(writer, &f, state, roots, None, &mut |dir| { visible_dirs.push(dir.to_path_buf()) })?; state.persist()?; From 4ad29449efc8f0232e29b4fbfff1f6fdc6092a4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 22:13:08 -0300 Subject: [PATCH 08/10] big-search: move the HTML reader into its own module --- apps/big-search/src/extract.rs | 198 +-------------------------- apps/big-search/src/extract/html.rs | 202 ++++++++++++++++++++++++++++ 2 files changed, 205 insertions(+), 195 deletions(-) create mode 100644 apps/big-search/src/extract/html.rs diff --git a/apps/big-search/src/extract.rs b/apps/big-search/src/extract.rs index 7efcca5..3dacd8b 100644 --- a/apps/big-search/src/extract.rs +++ b/apps/big-search/src/extract.rs @@ -3,10 +3,13 @@ //! lighter than in-process Rust PDF libraries (DESIGN.md, "Extraction"). //! Word 97-2003 `.doc` the same way through `antiword`. mod epub; +mod html; pub(crate) use crate::extract_pdf::read_pdf; use crate::fold::{fold_lower, fold_lower_into}; use epub::read_epub; +pub use html::html_text; +use html::{decode_entities, html_element}; use std::io::Read; use std::path::Path; @@ -266,201 +269,6 @@ fn markdown_headings(text: &str) -> Vec { level(1).chain(level(2)).collect() } -/// The text of the first `…` of an HTML page, tags inside removed. -fn html_element(html: &str, tag: &str) -> Option { - let lower = html.to_ascii_lowercase(); - let open = lower.find(&format!("<{tag}"))?; - let start = open + lower[open..].find('>')? + 1; - let end = start + lower[start..].find(&format!(">().join(" "); - (!text.is_empty()).then_some(text) -} - -/// Whether `name`, lowercase, is an element that sits inside a line of text: -/// the others separate words. -fn is_inline_element(name: &[u8]) -> bool { - matches!( - name, - b"a" | b"abbr" - | b"b" - | b"bdi" - | b"bdo" - | b"cite" - | b"code" - | b"data" - | b"dfn" - | b"em" - | b"font" - | b"i" - | b"kbd" - | b"mark" - | b"q" - | b"s" - | b"samp" - | b"small" - | b"span" - | b"strong" - | b"sub" - | b"sup" - | b"time" - | b"u" - | b"var" - | b"wbr" - ) -} - -/// Openings, lowercase, of the elements that end a line: a prefix, so `` and `
`. -const BLOCK_TAG_OPENINGS: &[&[u8]] = &[ - b" Option { - memchr::memchr_iter(needle[0], haystack).find(|&at| { - haystack - .get(at..at + needle.len()) - .is_some_and(|found| found.eq_ignore_ascii_case(needle)) - }) -} - -/// The readable text of HTML: scripts and styles dropped, block elements as -/// line breaks, entities decoded. Enough to read a saved page's -/// title and dates, not a renderer. -/// -/// Markup is matched by bytes with ASCII case ignored: every byte it looks for -/// is ASCII, so each position found is a char boundary. -pub fn html_text(html: &str) -> String { - let bytes = html.as_bytes(); - // What is kept is cut from the page, so its length nearly always fits. - let mut out = String::with_capacity(html.len()); - let mut at = 0; - while let Some(open) = memchr::memchr(b'<', &bytes[at..]).map(|i| at + i) { - out.push_str(&html[at..open]); - let tag_end = memchr::memchr(b'>', &bytes[open..]).map_or(html.len(), |i| open + i + 1); - let tag = &bytes[open..tag_end]; - // The tag's start, lowercased once: every opening compared fits in it, - // and the NUL padding of a shorter tag matches none of them. - let mut head = [0u8; 8]; - let head_len = tag.len().min(head.len()); - head[..head_len].copy_from_slice(&tag[..head_len]); - head.make_ascii_lowercase(); - // An unclosed script or style runs to the end, as in a browser; searching - // again from every later opener would make the scan quadratic. - let skip_to = SKIPPED_ELEMENTS.iter().find_map(|&(opening, closing)| { - head.starts_with(opening).then(|| { - find_ignore_ascii_case(&bytes[tag_end..], closing) - .map_or(html.len(), |i| tag_end + i) - }) - }); - let block = BLOCK_TAG_OPENINGS - .iter() - .any(|opening| head.starts_with(opening)); - let name_start = tag - .iter() - .position(|&b| b != b'<' && b != b'/') - .unwrap_or(tag.len()); - let name = &tag[name_start..]; - let name = &name[..name - .iter() - .position(|b| !b.is_ascii_alphanumeric()) - .unwrap_or(name.len())]; - // No inline element's name is longer than the buffer. - let mut lowered = [0u8; 8]; - let inline = name.len() <= lowered.len() && { - let lowered = &mut lowered[..name.len()]; - lowered.copy_from_slice(name); - lowered.make_ascii_lowercase(); - is_inline_element(lowered) - }; - // What an image or a link says of itself is read too; markup is not. - for attribute in [&b" alt="[..], b" title="] { - let Some(found) = find_ignore_ascii_case(tag, attribute) else { - continue; - }; - let value = &html[open + found + attribute.len()..tag_end]; - if let Some("e @ (b'"' | b'\'')) = value.as_bytes().first() - && let Some(len) = memchr::memchr(quote, &value.as_bytes()[1..]) - { - out.push(' '); - out.push_str(&value[1..=len]); - out.push(' '); - } - } - if block { - out.push('\n'); - } else if skip_to.is_none() && !name.is_empty() && !inline { - // A table cell, a list or any other box ends the word before it. - out.push(' '); - } - at = skip_to.unwrap_or(tag_end).min(html.len()); - } - out.push_str(&html[at.min(html.len())..]); - decode_entities(out) -} - -/// `&`, ` `, `—`, `—` and the like as characters; text -/// without an `&` is returned as it is. -fn decode_entities(text: String) -> String { - let Some(first) = memchr::memchr(b'&', text.as_bytes()) else { - return text; - }; - let mut out = String::with_capacity(text.len()); - out.push_str(&text[..first]); - let mut rest = &text[first..]; - while let Some(at) = memchr::memchr(b'&', rest.as_bytes()) { - out.push_str(&rest[..at]); - rest = &rest[at..]; - // Only as far as the longest HTML5 name: a search to the end for every - // `&` is quadratic. `;` is ASCII, so its index is a char boundary. - let entity = rest.as_bytes()[1..] - .iter() - .take(33) - .position(|&b| b == b';') - .map(|end| &rest[1..=end]); - match entity { - Some(entity) if push_entity(entity, &mut out) => rest = &rest[entity.len() + 2..], - _ => { - out.push('&'); - rest = &rest[1..]; - } - } - } - out.push_str(rest); - out -} - -/// Pushes the character an entity's name or number (between `&` and `;`) -/// stands for; false, pushing nothing, when it stands for none. -fn push_entity(entity: &str, out: &mut String) -> bool { - if entity == "nbsp" { - out.push(' '); - return true; - } - if let Some(number) = entity.strip_prefix('#') { - let code = match number.strip_prefix(['x', 'X']) { - Some(hex) => u32::from_str_radix(hex, 16).ok(), - None => number.parse().ok(), - }; - let Some(c) = code.and_then(char::from_u32) else { - return false; - }; - out.push(c); - return true; - } - let Some(text) = quick_xml::escape::resolve_html5_entity(entity) else { - return false; - }; - out.push_str(text); - true -} - /// Extract text for a file identified by content sniffing (no usable extension): /// PDF via `pdftotext`, HTML as its readable text, anything else `text/*` as /// plain text. Used by the metadata pass so an extension-less document is still diff --git a/apps/big-search/src/extract/html.rs b/apps/big-search/src/extract/html.rs new file mode 100644 index 0000000..2464175 --- /dev/null +++ b/apps/big-search/src/extract/html.rs @@ -0,0 +1,202 @@ +//! HTML as text: what web pages, EPUB chapters and mail parts are indexed as, +//! and the title and first heading a page is described by. + +/// The text of the first `…` of an HTML page, tags inside removed. +pub(super) fn html_element(html: &str, tag: &str) -> Option { + let lower = html.to_ascii_lowercase(); + let open = lower.find(&format!("<{tag}"))?; + let start = open + lower[open..].find('>')? + 1; + let end = start + lower[start..].find(&format!(">().join(" "); + (!text.is_empty()).then_some(text) +} + +/// Whether `name`, lowercase, is an element that sits inside a line of text: +/// the others separate words. +fn is_inline_element(name: &[u8]) -> bool { + matches!( + name, + b"a" | b"abbr" + | b"b" + | b"bdi" + | b"bdo" + | b"cite" + | b"code" + | b"data" + | b"dfn" + | b"em" + | b"font" + | b"i" + | b"kbd" + | b"mark" + | b"q" + | b"s" + | b"samp" + | b"small" + | b"span" + | b"strong" + | b"sub" + | b"sup" + | b"time" + | b"u" + | b"var" + | b"wbr" + ) +} + +/// Openings, lowercase, of the elements that end a line: a prefix, so `` and `
`. +const BLOCK_TAG_OPENINGS: &[&[u8]] = &[ + b" Option { + memchr::memchr_iter(needle[0], haystack).find(|&at| { + haystack + .get(at..at + needle.len()) + .is_some_and(|found| found.eq_ignore_ascii_case(needle)) + }) +} + +/// The readable text of HTML: scripts and styles dropped, block elements as +/// line breaks, entities decoded. Enough to read a saved page's +/// title and dates, not a renderer. +/// +/// Markup is matched by bytes with ASCII case ignored: every byte it looks for +/// is ASCII, so each position found is a char boundary. +pub fn html_text(html: &str) -> String { + let bytes = html.as_bytes(); + // What is kept is cut from the page, so its length nearly always fits. + let mut out = String::with_capacity(html.len()); + let mut at = 0; + while let Some(open) = memchr::memchr(b'<', &bytes[at..]).map(|i| at + i) { + out.push_str(&html[at..open]); + let tag_end = memchr::memchr(b'>', &bytes[open..]).map_or(html.len(), |i| open + i + 1); + let tag = &bytes[open..tag_end]; + // The tag's start, lowercased once: every opening compared fits in it, + // and the NUL padding of a shorter tag matches none of them. + let mut head = [0u8; 8]; + let head_len = tag.len().min(head.len()); + head[..head_len].copy_from_slice(&tag[..head_len]); + head.make_ascii_lowercase(); + // An unclosed script or style runs to the end, as in a browser; searching + // again from every later opener would make the scan quadratic. + let skip_to = SKIPPED_ELEMENTS.iter().find_map(|&(opening, closing)| { + head.starts_with(opening).then(|| { + find_ignore_ascii_case(&bytes[tag_end..], closing) + .map_or(html.len(), |i| tag_end + i) + }) + }); + let block = BLOCK_TAG_OPENINGS + .iter() + .any(|opening| head.starts_with(opening)); + let name_start = tag + .iter() + .position(|&b| b != b'<' && b != b'/') + .unwrap_or(tag.len()); + let name = &tag[name_start..]; + let name = &name[..name + .iter() + .position(|b| !b.is_ascii_alphanumeric()) + .unwrap_or(name.len())]; + // No inline element's name is longer than the buffer. + let mut lowered = [0u8; 8]; + let inline = name.len() <= lowered.len() && { + let lowered = &mut lowered[..name.len()]; + lowered.copy_from_slice(name); + lowered.make_ascii_lowercase(); + is_inline_element(lowered) + }; + push_described_text(&html[open..tag_end], &mut out); + if block { + out.push('\n'); + } else if skip_to.is_none() && !name.is_empty() && !inline { + // A table cell, a list or any other box ends the word before it. + out.push(' '); + } + at = skip_to.unwrap_or(tag_end).min(html.len()); + } + out.push_str(&html[at.min(html.len())..]); + decode_entities(out) +} + +/// What an image or a link says of itself, the quoted `alt` and `title` of +/// `tag`, each between spaces; the rest of the markup is not text. +fn push_described_text(tag: &str, out: &mut String) { + for attribute in [&b" alt="[..], b" title="] { + let Some(found) = find_ignore_ascii_case(tag.as_bytes(), attribute) else { + continue; + }; + let value = &tag[found + attribute.len()..]; + if let Some("e @ (b'"' | b'\'')) = value.as_bytes().first() + && let Some(len) = memchr::memchr(quote, &value.as_bytes()[1..]) + { + out.push(' '); + out.push_str(&value[1..=len]); + out.push(' '); + } + } +} + +/// `&`, ` `, `—`, `—` and the like as characters; text +/// without an `&` is returned as it is. +pub(super) fn decode_entities(text: String) -> String { + let Some(first) = memchr::memchr(b'&', text.as_bytes()) else { + return text; + }; + let mut out = String::with_capacity(text.len()); + out.push_str(&text[..first]); + let mut rest = &text[first..]; + while let Some(at) = memchr::memchr(b'&', rest.as_bytes()) { + out.push_str(&rest[..at]); + rest = &rest[at..]; + // Only as far as the longest HTML5 name: a search to the end for every + // `&` is quadratic. `;` is ASCII, so its index is a char boundary. + let entity = rest.as_bytes()[1..] + .iter() + .take(33) + .position(|&b| b == b';') + .map(|end| &rest[1..=end]); + match entity { + Some(entity) if push_entity(entity, &mut out) => rest = &rest[entity.len() + 2..], + _ => { + out.push('&'); + rest = &rest[1..]; + } + } + } + out.push_str(rest); + out +} + +/// Pushes the character an entity's name or number (between `&` and `;`) +/// stands for; false, pushing nothing, when it stands for none. +fn push_entity(entity: &str, out: &mut String) -> bool { + if entity == "nbsp" { + out.push(' '); + return true; + } + if let Some(number) = entity.strip_prefix('#') { + let code = match number.strip_prefix(['x', 'X']) { + Some(hex) => u32::from_str_radix(hex, 16).ok(), + None => number.parse().ok(), + }; + let Some(c) = code.and_then(char::from_u32) else { + return false; + }; + out.push(c); + return true; + } + let Some(text) = quick_xml::escape::resolve_html5_entity(entity) else { + return false; + }; + out.push_str(text); + true +} From c00192f14770a1f8225c34b345abc52ddde4c885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 22:19:38 -0300 Subject: [PATCH 09/10] big-search: find a page's title without a lowercase copy of it --- apps/big-search/src/extract/html.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/big-search/src/extract/html.rs b/apps/big-search/src/extract/html.rs index 2464175..a9604b4 100644 --- a/apps/big-search/src/extract/html.rs +++ b/apps/big-search/src/extract/html.rs @@ -3,10 +3,10 @@ /// The text of the first `…` of an HTML page, tags inside removed. pub(super) fn html_element(html: &str, tag: &str) -> Option { - let lower = html.to_ascii_lowercase(); - let open = lower.find(&format!("<{tag}"))?; - let start = open + lower[open..].find('>')? + 1; - let end = start + lower[start..].find(&format!("', &bytes[open..])? + 1; + let end = start + find_ignore_ascii_case(&bytes[start..], format!(">().join(" "); (!text.is_empty()).then_some(text) From 0665aa441775d7985927c6d386bbcebfce7131d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bruno=20Gon=C3=A7alves?= Date: Thu, 26 Nov 2026 22:33:40 -0300 Subject: [PATCH 10/10] Name BigDesktop in the README without a link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 182dc8d..e4a2a69 100644 --- a/README.md +++ b/README.md @@ -123,7 +123,7 @@ The indexes and state live in `~/.local/share/big-search/`; the socket is `cargo build` compiles only the daemon; add `--workspace` for `big-docinfo` and the libraries. The settings window that edits `config.toml` belongs to -[BigDesktop](https://github.com/biglinux/bigdesktop), which takes the two +BigDesktop, which takes the two libraries above from this repository. ## Help