From dc02b74817dff8f569e3935b120bc660ef396d1c Mon Sep 17 00:00:00 2001 From: thekevinbot <248217931+thekevinbot@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:34:27 -0500 Subject: [PATCH 1/4] Test that a folder a glob reaches but cannot list fails the scan --- packages/rust/tests/unlistable_folder.rs | 158 +++++++++++++++++++++++ 1 file changed, 158 insertions(+) create mode 100644 packages/rust/tests/unlistable_folder.rs diff --git a/packages/rust/tests/unlistable_folder.rs b/packages/rust/tests/unlistable_folder.rs new file mode 100644 index 00000000..c16a53f8 --- /dev/null +++ b/packages/rust/tests/unlistable_folder.rs @@ -0,0 +1,158 @@ +//! Integration tests: a folder a glob reaches that exists but cannot be listed +//! fails the scan with an error naming it, where a missing folder is no rows. +//! Real filesystem permissions, so Unix only. +#![cfg(unix)] + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; + +use dirsql::{DirSQL, Value}; +use tempfile::TempDir; + +/// Make `dir` traversable but not listable. Returns false when the process +/// bypasses permission checks (root), since the test's premise cannot hold. +fn make_unlistable(dir: &Path) -> bool { + fs::set_permissions(dir, fs::Permissions::from_mode(0o311)).unwrap(); + fs::read_dir(dir).is_err() +} + +fn make_listable(dir: &Path) { + fs::set_permissions(dir, fs::Permissions::from_mode(0o755)).unwrap(); +} + +/// `root/data/open/a.ndjson` and `root/data/locked/b.ndjson`, `locked` made +/// unlistable; `None` when it cannot be. +fn tree() -> Option<(TempDir, std::path::PathBuf)> { + let root = TempDir::new().unwrap(); + let open = root.path().join("data/open"); + let locked = root.path().join("data/locked"); + fs::create_dir_all(&open).unwrap(); + fs::create_dir_all(&locked).unwrap(); + fs::write(open.join("a.ndjson"), "{\"k\":\"a\"}\n").unwrap(); + fs::write(locked.join("b.ndjson"), "{\"k\":\"b\"}\n").unwrap(); + if !make_unlistable(&locked) { + make_listable(&locked); + return None; + } + Some((root, locked)) +} + +fn parsed(root: &Path) -> DirSQL { + DirSQL::builder() + .root(root) + .path_table_parser("cat") + .build() + .unwrap() +} + +fn assert_names(message: &str, locked: &Path) { + assert!( + message.contains(&locked.display().to_string()), + "the error must name the unlistable folder: {message}" + ); +} + +#[test] +fn a_parsed_path_table_over_an_unlistable_folder_fails_naming_it() { + let Some((root, locked)) = tree() else { + return; + }; + let result = parsed(root.path()).query("SELECT * FROM './data/**/*.ndjson'"); + make_listable(&locked); + + let message = result + .expect_err("an unlistable folder must fail the query") + .to_string(); + assert_names(&message, &locked); +} + +#[test] +fn a_parsed_literal_path_inside_an_unlistable_folder_fails_naming_it() { + let Some((root, locked)) = tree() else { + return; + }; + let result = parsed(root.path()).query("SELECT * FROM './data/locked/b.ndjson'"); + make_listable(&locked); + + let message = result + .expect_err("an unlistable folder must fail the query") + .to_string(); + assert_names(&message, &locked); +} + +#[test] +fn a_parsed_path_table_over_a_missing_folder_is_still_a_listable_one() { + let Some((root, locked)) = tree() else { + return; + }; + let rows = parsed(root.path()).query("SELECT k FROM './data/{open,missing}/*.ndjson'"); + make_listable(&locked); + + assert_eq!(rows.unwrap()[0]["k"], Value::Text("a".into())); +} + +fn config(root: &Path, glob: &str) -> std::path::PathBuf { + let config = root.join(".dirsql.toml"); + fs::write( + &config, + format!( + "[[table]]\nname = \"recs\"\nglob = \"{glob}\"\non-file = \"cat\"\n\ + ddl = \"CREATE TABLE recs (k TEXT)\"\n" + ), + ) + .unwrap(); + config +} + +fn config_build(root: &Path, glob: &str) -> dirsql::Result { + DirSQL::builder() + .root(root) + .config(config(root, glob)) + .build() +} + +#[test] +fn a_config_table_over_an_unlistable_folder_fails_its_build_naming_it() { + let Some((root, locked)) = tree() else { + return; + }; + let result = config_build(root.path(), "data/**/*.ndjson"); + make_listable(&locked); + + let message = result + .err() + .expect("an unlistable folder must fail the build") + .to_string(); + assert_names(&message, &locked); +} + +#[test] +fn a_config_table_over_a_missing_folder_builds_with_no_rows() { + let root = TempDir::new().unwrap(); + let db = config_build(root.path(), "missing/*.ndjson").unwrap(); + + let rows = db.query("SELECT COUNT(*) AS n FROM recs").unwrap(); + assert_eq!(rows[0]["n"], Value::Integer(0)); +} + +#[test] +fn a_config_table_through_a_link_to_an_unlistable_folder_fails_its_build_naming_it() { + let Some((root, locked)) = tree() else { + return; + }; + let index = root.path().join("index"); + fs::create_dir(&index).unwrap(); + std::os::unix::fs::symlink(&locked, index.join("link")).unwrap(); + let result = DirSQL::builder() + .root(&index) + .config(config(&index, "link/*.ndjson")) + .build(); + make_listable(&locked); + + let message = result + .err() + .expect("an unlistable folder must fail the build") + .to_string(); + assert_names(&message, &index.join("link")); +} From 89d3ffeb52c9b57adcd71cc2be2ca6442205b0ba Mon Sep 17 00:00:00 2001 From: thekevinbot <248217931+thekevinbot@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:44:23 -0500 Subject: [PATCH 2/4] Fail the scan on a folder a glob reaches but cannot list A config table's build and a parsed path-table's query now fail naming the folder; a missing folder still holds nothing. Streamed path-tables and the watcher's rescans still skip it. --- agents/reference/product-principles.md | 1 + docs/reference/glob.md | 1 + .../2026-11-18-unlistable-folder-fails.md | 3 + .../2026-11-18-unlistable-folder-fails.md | 32 +++++ packages/rust/src/lib.rs | 96 ++++++++++--- packages/rust/src/listing.rs | 115 +++++++++++---- packages/rust/src/parsed_vtab.rs | 3 +- packages/rust/src/scanner.rs | 134 ++++++++++++++---- packages/rust/src/vtab.rs | 4 +- packages/rust/tests/scanner.rs | 5 +- 10 files changed, 317 insertions(+), 77 deletions(-) create mode 100644 packages/rust/changelog.d/2026-11-18-unlistable-folder-fails.md create mode 100644 packages/rust/migrations.d/2026-11-18-unlistable-folder-fails.md diff --git a/agents/reference/product-principles.md b/agents/reference/product-principles.md index 90550348..3b96479d 100644 --- a/agents/reference/product-principles.md +++ b/agents/reference/product-principles.md @@ -18,6 +18,7 @@ Path globbing matches `bash -O globstar` with `dotglob` off, exactly. That is th - `'./'` and a named directory list one level. - `node_modules` is skipped unless the path names it. - Files only; no directory rows. +- A folder that exists but cannot be listed is an error, not an empty folder. To check a glob change, compare its output with `bash -O globstar -O nullglob` on the same tree. A divergence with no written reason is a bug. diff --git a/docs/reference/glob.md b/docs/reference/glob.md index a347b4b1..6e07d145 100644 --- a/docs/reference/glob.md +++ b/docs/reference/glob.md @@ -162,6 +162,7 @@ A test runs every row against dirsql as a path-table and, with the leading | `gitignore` | Inside a git repo, `.gitignore` files hide files and directories a wildcard matches, never one the pattern spells out. `--no-ignore` turns it off. | A query over a repo should not drown in build output. | | `directory-name` | A pattern's last component that names a directory lists the files directly inside it, like `ls docs`. A trailing `/` is `*` appended. | A table is rows of files, and `ls` is the shell habit. | | `files-only` | A pattern that matches a directory but no file returns nothing. | Every row is a file. | +| `unlistable` | A folder the pattern reaches that exists but cannot be listed is an error naming it: a config table fails its build and a parsed path-table its query. Bash skips it silently. A folder that does not exist still holds nothing. | An empty result that is really a failed read looks like a true answer. | `.git` needs no rule of its own: the dotfile rule hides it. diff --git a/packages/rust/changelog.d/2026-11-18-unlistable-folder-fails.md b/packages/rust/changelog.d/2026-11-18-unlistable-folder-fails.md new file mode 100644 index 00000000..c47d7a19 --- /dev/null +++ b/packages/rust/changelog.d/2026-11-18-unlistable-folder-fails.md @@ -0,0 +1,3 @@ +**Changed** + +- **A folder a glob reaches that exists but cannot be listed is now an error naming it, for config tables and parsed path-tables.** A config table's build fails, and so does a query over a parsed path-table (one read through `--on-file`), with `cannot list folder '': `. Before, the folder was read as empty and the result came back short with exit status 0. A folder that does not exist still holds nothing. Bash skips such a folder silently, so this is a listed divergence from bash. `scanner::scan_directory_reporting`, `scanner::scan_glob` and `scanner::scan_glob_checking_root` now return `Result<_, scanner::UnlistableFolder>`. diff --git a/packages/rust/migrations.d/2026-11-18-unlistable-folder-fails.md b/packages/rust/migrations.d/2026-11-18-unlistable-folder-fails.md new file mode 100644 index 00000000..f1f324ca --- /dev/null +++ b/packages/rust/migrations.d/2026-11-18-unlistable-folder-fails.md @@ -0,0 +1,32 @@ +### A folder that cannot be listed fails config tables and parsed path-tables + +#### Summary + +A folder a glob reaches that exists but cannot be listed (its open fails, or a read fails part-way) used to be read as empty. It now fails a config table's build and a parsed path-table's query with an error naming the folder; the CLI exits non-zero and the SDKs raise. A missing folder still holds nothing. Three public Rust scanner functions now return a `Result`. + +#### Required changes + +| Surface | Before | After | +| --- | --- | --- | +| `dirsql::scanner::scan_directory_reporting` | returns `Vec` | returns `Result, UnlistableFolder>` | +| `dirsql::scanner::scan_glob` | returns `Vec` | returns `Result, UnlistableFolder>` | +| `dirsql::scanner::scan_glob_checking_root` | returns `Vec` | returns `Result, UnlistableFolder>` | + +#### Deprecations removed + +_None._ + +#### Behavior changes without code changes + +`DirSQL::builder().build()` over a config table, and `query` over a parsed path-table, fail with `cannot list folder '': ` where they used to return the rows of every other folder. In the Rust SDK the build error is `DirSqlError::Io` carrying the OS error kind; the query error is a SQLite module error. + +#### Verification + +```bash +mkdir -p data/open data/locked +echo '{"k":1}' > data/open/a.ndjson +chmod 311 data/locked +dirsql --on-file cat "SELECT * FROM './data/**/*.ndjson'" +``` + +Expected (as a non-root user): exit status 1 and an error containing `cannot list folder` and `data/locked`. diff --git a/packages/rust/src/lib.rs b/packages/rust/src/lib.rs index b3f67295..2f2c7387 100644 --- a/packages/rust/src/lib.rs +++ b/packages/rust/src/lib.rs @@ -81,7 +81,7 @@ use crate::persist::{ resolve_persist_path, upsert_file, write_meta, }; use crate::progress::Progress; -use crate::scanner::{Found, scan_directory_reporting}; +use crate::scanner::{Found, UnlistableFolder, scan_directory_reporting}; use crate::watcher::{FileEvent, WatchFault, WatchScope, Watcher}; use futures_channel::mpsc::{UnboundedReceiver, UnboundedSender, unbounded}; use std::collections::{BTreeMap, HashMap, HashSet}; @@ -683,7 +683,7 @@ type ScanFn<'a> = &'a dyn Fn( &mut dyn FnMut(u64), &mut dyn FnMut(&Path, &str), &(dyn Fn(&Path) + Sync), -) -> Vec; +) -> std::result::Result, UnlistableFolder>; impl DirSQL { /// Start building a `DirSQL`. See [`DirSQLBuilder`] for the available @@ -1980,7 +1980,7 @@ impl DirSQL { // The walk reports a running count rather than a fraction: it does // not know how many files there are until it has found them all. let mut progress = Progress::scanning(); - let (scanned, seen) = scan_groups( + let scanned = scan_groups( &groups, scan, &mut progress, @@ -1997,6 +1997,7 @@ impl DirSQL { }, ); drop(feeds); + let (scanned, seen) = scanned.map_err(std::io::Error::from)?; progress.finish(seen); for warning in empty_table_warnings(&tables, &anchors, &scanned) { eprintln!("{warning}"); @@ -2915,7 +2916,7 @@ fn scan_groups( progress: &mut Progress, on_match: &mut dyn FnMut(&Path, &str), on_link: &(dyn Fn(&Path) + Sync), -) -> (Vec, u64) { +) -> std::result::Result<(Vec, u64), UnlistableFolder> { let mut seen = 0; let mut scanned = Vec::new(); for group in groups { @@ -2929,9 +2930,9 @@ fn scan_groups( }, on_match, on_link, - )); + )?); } - (scanned, seen) + Ok((scanned, seen)) } fn compile_groups( @@ -4134,12 +4135,12 @@ mod internal_tests { _matcher: &TableMatcher, on_file: &mut dyn FnMut(u64), _on_match: &mut dyn FnMut(&Path, &str), - ) -> Vec { + ) -> std::result::Result, UnlistableFolder> { self.calls.set(self.calls.get() + 1); for (index, _) in self.found.iter().enumerate() { on_file(index as u64 + 1); } - self.found.clone() + Ok(self.found.clone()) } } @@ -4185,7 +4186,7 @@ mod internal_tests { wait_for_db.recv_timeout(Duration::from_secs(5)).is_ok(), "database creation must finish before the scan completes" ); - Vec::new() + Ok(Vec::new()) }; let new_db = move || { wait_for_scan.recv_timeout(Duration::from_secs(5)).unwrap(); @@ -4220,7 +4221,7 @@ mod internal_tests { wait_for_ddl.recv_timeout(Duration::from_secs(5)).is_ok(), "table DDL must finish before the scan completes" ); - Vec::new() + Ok(Vec::new()) }; let ddl = move |db: &Db, tables: &[Table]| { wait_for_scan.recv_timeout(Duration::from_secs(5)).unwrap(); @@ -4254,7 +4255,7 @@ mod internal_tests { let called = Arc::clone(&ddl_called); let prepared = DirSQL::prepare_resolved_with_setup( resolved, - &|_, _, _, _, _| Vec::new(), + &|_, _, _, _, _| Ok(Vec::new()), Db::new, move |_, _| { called.store(true, Ordering::SeqCst); @@ -4327,7 +4328,7 @@ mod internal_tests { let called = Arc::clone(&ddl_called); let prepared = DirSQL::prepare_resolved_with_setup( resolved, - &|_, _, _, _, _| Vec::new(), + &|_, _, _, _, _| Ok(Vec::new()), Db::new, move |_, _| { called.store(true, Ordering::SeqCst); @@ -4464,11 +4465,11 @@ mod internal_tests { .recv_timeout(std::time::Duration::from_secs(5)) .is_ok(), ); - vec![Found { + Ok(vec![Found { path: found.clone(), rel_path: "a.txt".into(), table_name: "items".into(), - }] + }]) }) .unwrap(); assert!(hook_saw_it_mid_walk.get()); @@ -4484,7 +4485,7 @@ mod internal_tests { resolved.no_ignore = no_ignore; DirSQL::prepare_resolved_with(resolved, &|_, matcher, _, _, _| { honored.set(Some(matcher.respects_gitignore())); - Vec::new() + Ok(Vec::new()) }) .unwrap(); assert_eq!(honored.get(), Some(!no_ignore)); @@ -5019,7 +5020,7 @@ mod internal_tests { _: &mut dyn FnMut(&Path, &str), _: &(dyn Fn(&Path) + Sync)| { report(3); - vec![found_at(anchor, &anchor.join("f.txt"), "t")] + Ok(vec![found_at(anchor, &anchor.join("f.txt"), "t")]) }; let (scanned, seen) = scan_groups( @@ -5028,12 +5029,71 @@ mod internal_tests { &mut Progress::scanning(), &mut |_, _| {}, &|_| {}, - ); + ) + .unwrap(); assert_eq!(seen, 6); assert_eq!(scanned.len(), 2); } + #[test] + fn scan_groups_fails_on_a_folder_a_scan_could_not_list() { + let tables = vec![ + anchored_table("a", "*.txt", "/one"), + anchored_table("b", "*.txt", "/two"), + ]; + let (groups, _, _) = compile_groups(&tables, &[], Path::new("/idx")).unwrap(); + let scan = |anchor: &Path, + _: &TableMatcher, + _: &mut dyn FnMut(u64), + _: &mut dyn FnMut(&Path, &str), + _: &(dyn Fn(&Path) + Sync)| { + if anchor.ends_with("two") { + return Err(unlistable(anchor)); + } + Ok(vec![found_at(anchor, &anchor.join("f.txt"), "t")]) + }; + + let failed = scan_groups( + &groups, + &scan, + &mut Progress::scanning(), + &mut |_, _| {}, + &|_| {}, + ) + .unwrap_err(); + + assert!(failed.path.ends_with("two"), "{failed}"); + } + + fn unlistable(path: &Path) -> UnlistableFolder { + UnlistableFolder { + path: path.to_path_buf(), + source: std::io::Error::from(std::io::ErrorKind::PermissionDenied), + } + } + + #[test] + fn a_build_fails_naming_a_folder_its_scan_could_not_list() { + let dir = TempDir::new().unwrap(); + let locked = dir.path().join("locked"); + let failed = DirSQL::prepare_resolved_with( + resolved_over(dir.path(), vec![txt_table()], false), + &|_, _, _, _, _| Err(unlistable(&locked)), + ) + .err() + .unwrap(); + + let DirSqlError::Io(io) = &failed else { + panic!("not an io error: {failed:?}"); + }; + assert_eq!(io.kind(), std::io::ErrorKind::PermissionDenied); + assert!( + failed.to_string().contains(&locked.display().to_string()), + "{failed}" + ); + } + #[test] fn delete_subtree_surfaces_db_poison() { let (_dir, db, _abs, _rel) = upsert_fixture(); @@ -9144,7 +9204,7 @@ mod internal_tests { let link = dir.path().join("link"); let prepared = DirSQL::prepare_resolved_with(resolved, &|_, _, _, _, on_link| { on_link(&link); - Vec::new() + Ok(Vec::new()) }) .unwrap(); assert_eq!(prepared.links, vec![link.clone()]); diff --git a/packages/rust/src/listing.rs b/packages/rust/src/listing.rs index 3318b3fc..41e48052 100644 --- a/packages/rust/src/listing.rs +++ b/packages/rust/src/listing.rs @@ -166,8 +166,8 @@ type Names = Owned; impl Listing { /// The entries of `dir` in the byte order of their names; none when it - /// cannot be read. - pub(crate) fn read(dir: &Path) -> Listing { + /// does not exist or is not a directory. + pub(crate) fn read(dir: &Path) -> std::io::Result { Listing::sorted(|emit| read_chunks(dir, emit), &Chunk::sort) } @@ -175,15 +175,15 @@ impl Listing { /// the first chunk, a thread of its own `sort`s each chunk while the next /// is read, and the sorted chunks are then merged on every core. fn sorted( - read: impl FnOnce(&mut dyn FnMut(Chunk)), + read: impl FnOnce(&mut dyn FnMut(Chunk)) -> std::io::Result<()>, sort: &(dyn Fn(&mut Chunk) + Sync), - ) -> Listing { + ) -> std::io::Result { let (send, receive) = std::sync::mpsc::channel::(); let mut receive = Some(receive); let mut first = None; std::thread::scope(|scope| { let mut sorter = None; - read(&mut |chunk| { + let read = read(&mut |chunk| { if sorter.is_none() { let Some(earlier) = first.take() else { first = Some(chunk); @@ -196,7 +196,7 @@ impl Listing { send.send(chunk).expect("the sorter is waiting"); }); drop(send); - match sorter { + let listing = match sorter { Some(sorter) => merge(sorter.join().expect("sorting does not panic")), None => { let mut listing = Listing::default(); @@ -206,7 +206,8 @@ impl Listing { listing.sort(); listing } - } + }; + read.map(|()| listing) }) } @@ -341,46 +342,62 @@ fn open_dir(dir: &Path) -> std::io::Result { } /// The entries of `dir` in the order the filesystem lists them, handed to -/// `emit` a chunk at a time as they are read; none when it cannot be read. -pub(crate) fn read_chunks(dir: &Path, emit: &mut dyn FnMut(Chunk)) { +/// `emit` a chunk at a time as they are read; none when it does not exist or +/// is not a directory. +pub(crate) fn read_chunks(dir: &Path, emit: &mut dyn FnMut(Chunk)) -> std::io::Result<()> { let mut chunker = Chunker::new(emit); - read_into(dir, &mut chunker); + let read = read_into(dir, &mut chunker); chunker.finish(); + read +} + +/// `Ok` for a folder that is not there to list, which a glob takes as one +/// holding nothing; `err` itself otherwise. +fn absent_as_empty(err: std::io::Error) -> std::io::Result<()> { + use std::io::ErrorKind; + match err.kind() { + ErrorKind::NotFound | ErrorKind::NotADirectory => Ok(()), + _ => Err(err), + } } /// Uses `Dir`, not `RawDir`: on a deep tree of small directories the walk ran /// about twice as slow reading through `RawDir`, with no gain on a flat /// directory of a million entries. #[cfg(unix)] -fn read_into(dir: &Path, listing: &mut Chunker<'_>) { +fn read_into(dir: &Path, listing: &mut Chunker<'_>) -> std::io::Result<()> { use rustix::fs::Dir; use std::os::unix::ffi::OsStrExt; - let Ok(fd) = open_dir(dir) else { - return; + let fd = match open_dir(dir) { + Ok(fd) => fd, + Err(err) => return absent_as_empty(err), }; - let Ok(mut entries) = Dir::new(fd) else { - return; - }; - while let Some(Ok(entry)) = entries.read() { + let mut entries = Dir::new(fd)?; + while let Some(entry) = entries.read() { + let entry = entry?; let name = entry.file_name().to_bytes(); if name == b"." || name == b".." { continue; } listing.push(OsStr::from_bytes(name), seen(entry.file_type())); } + Ok(()) } #[cfg(any(test, not(unix)))] -fn read_dir_into(dir: &Path, listing: &mut Chunker<'_>) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; +fn read_dir_into(dir: &Path, listing: &mut Chunker<'_>) -> std::io::Result<()> { + let entries = match std::fs::read_dir(dir) { + Ok(entries) => entries, + Err(err) => return absent_as_empty(err), }; - for entry in entries.filter_map(Result::ok) { + for entry in entries { + let entry = entry?; let seen = entry.file_type().map_or(Seen::Other, |kind| { seen_flags(kind.is_symlink(), kind.is_dir(), kind.is_file()) }); listing.push(&entry.file_name(), seen); } + Ok(()) } #[cfg(any(test, not(unix)))] @@ -506,7 +523,7 @@ mod tests { std::fs::File::create(dir.path().join(format!("f{i}"))).unwrap(); } let mut sizes = Vec::new(); - read_chunks(dir.path(), &mut |chunk| sizes.push(chunk.entries.len())); + read_chunks(dir.path(), &mut |chunk| sizes.push(chunk.entries.len())).unwrap(); assert_eq!(sizes, [CHUNK_ENTRIES, 1]); } @@ -527,7 +544,14 @@ mod tests { fn sorted_from(chunks: Vec) -> Listing { let mut chunks = chunks.into_iter(); - Listing::sorted(|emit| chunks.by_ref().for_each(&mut *emit), &Chunk::sort) + Listing::sorted( + |emit| { + chunks.by_ref().for_each(&mut *emit); + Ok(()) + }, + &Chunk::sort, + ) + .unwrap() } fn named_and_seen(listing: &Listing) -> Vec<(String, Seen)> { @@ -608,9 +632,11 @@ mod tests { sorted_early = *done; drop(done); chunks.by_ref().for_each(&mut *emit); + Ok(()) }, &sort, - ); + ) + .unwrap(); assert!( sorted_early, "no chunk was sorted until the whole directory was read" @@ -636,7 +662,10 @@ mod tests { for (name, _) in &expected { std::fs::File::create(dir.path().join(name)).unwrap(); } - assert_eq!(named_and_seen(&Listing::read(dir.path())), expected); + assert_eq!( + named_and_seen(&Listing::read(dir.path()).unwrap()), + expected + ); } #[test] @@ -658,11 +687,14 @@ mod tests { ); } - fn read_with(read: fn(&Path, &mut Chunker<'_>), dir: &Path) -> Vec<(String, Seen)> { + fn read_with( + read: fn(&Path, &mut Chunker<'_>) -> std::io::Result<()>, + dir: &Path, + ) -> Vec<(String, Seen)> { let mut listing = Listing::default(); let mut emit = |chunk| listing.add(chunk); let mut chunker = Chunker::new(&mut emit); - read(dir, &mut chunker); + read(dir, &mut chunker).unwrap(); chunker.finish(); listing.sort(); listing @@ -694,7 +726,7 @@ mod tests { #[test] fn read_lists_each_entry_of_a_directory_sorted_and_classified() { let dir = fixture(); - let listing = Listing::read(dir.path()); + let listing = Listing::read(dir.path()).unwrap(); let got: Vec<_> = listing .entries() .iter() @@ -730,16 +762,39 @@ mod tests { } #[test] - fn an_unreadable_directory_lists_nothing() { + fn a_missing_path_or_a_file_lists_nothing() { let dir = fixture(); let file = dir.path().join("file"); let missing = dir.path().join("missing"); for path in [&file, &missing] { - assert!(Listing::read(path).entries().is_empty()); + assert!(Listing::read(path).unwrap().entries().is_empty()); assert!(read_with(read_dir_into, path).is_empty()); } } + #[test] + fn only_a_folder_that_is_not_there_counts_as_empty() { + use std::io::{Error, ErrorKind}; + assert!(absent_as_empty(Error::from(ErrorKind::NotFound)).is_ok()); + assert!(absent_as_empty(Error::from(ErrorKind::NotADirectory)).is_ok()); + for kind in [ErrorKind::PermissionDenied, ErrorKind::Other] { + let err = absent_as_empty(Error::from(kind)).unwrap_err(); + assert_eq!(err.kind(), kind); + } + } + + #[test] + fn a_failed_read_fails_the_sorted_listing() { + let failed = Listing::sorted( + |emit| { + chunks_of(numbered(3)).into_iter().for_each(&mut *emit); + Err(std::io::Error::other("read failed part-way")) + }, + &Chunk::sort, + ); + assert_eq!(failed.err().unwrap().to_string(), "read failed part-way"); + } + #[cfg(unix)] #[test] fn every_file_type_maps_to_what_it_was_seen_as() { diff --git a/packages/rust/src/parsed_vtab.rs b/packages/rust/src/parsed_vtab.rs index 87a1c409..a039b864 100644 --- a/packages/rust/src/parsed_vtab.rs +++ b/packages/rust/src/parsed_vtab.rs @@ -156,7 +156,8 @@ impl TableSource for ParsedTable { // A parsed path-table honors the same skip rules a stat path-table does // (node_modules/.git, gitignore, plus any configured ignore), so a // parsed `SELECT * FROM './'` doesn't drown in dependency trees. - let rel_paths = scan_glob_checking_root(&root, &glob, &ignore, gitignore, check_root); + let rel_paths = scan_glob_checking_root(&root, &glob, &ignore, gitignore, check_root) + .map_err(|err| Error::ModuleError(err.to_string()))?; let run = |rel: &[PathBuf]| run_parser(&command, &index_root, &root, rel); let rows = collect_rows(&rel_paths, &run)?; diff --git a/packages/rust/src/scanner.rs b/packages/rust/src/scanner.rs index 5abd30a9..4b4d2bcf 100644 --- a/packages/rust/src/scanner.rs +++ b/packages/rust/src/scanner.rs @@ -7,7 +7,7 @@ use ignore::Match; use std::borrow::Cow; use std::ffi::OsStr; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, Mutex, PoisonError}; /// A root-relative path as dirsql stores and reports it: `/`-separated on /// every platform, so globs, `file_path` keys and `path` columns agree. @@ -32,16 +32,58 @@ fn with_slashes(path: &str, native: char) -> String { /// Walk a directory tree and return all file paths paired with their matching table name. /// Ignored paths and directories are skipped. Only files (not directories) are returned. +/// A folder that cannot be listed contributes nothing. pub fn scan_directory(root: &Path, matcher: &TableMatcher) -> Vec<(PathBuf, String)> { - paired(scan_directory_reporting( + paired(scan_below( + root, root, matcher, &mut |_| {}, &mut |_, _| {}, &ignore_link, + &ignore_unlistable, )) } +/// A folder a walk reached that exists but could not be listed. +#[derive(Debug, thiserror::Error)] +#[error("cannot list folder '{}': {source}", .path.display())] +pub struct UnlistableFolder { + pub path: PathBuf, + #[source] + pub source: std::io::Error, +} + +impl From for std::io::Error { + fn from(err: UnlistableFolder) -> Self { + std::io::Error::new(err.source.kind(), err) + } +} + +/// The first folder, in path order, a walk could not list. +#[derive(Default)] +struct Unlisted(Mutex>); + +impl Unlisted { + fn note(&self, dir: &Path, source: std::io::Error) { + let mut first = self.0.lock().unwrap_or_else(PoisonError::into_inner); + if first + .as_ref() + .is_none_or(|first| dir < first.path.as_path()) + { + *first = Some(UnlistableFolder { + path: dir.to_path_buf(), + source, + }); + } + } + + fn into_result(self) -> Result<(), UnlistableFolder> { + let first = self.0.into_inner().unwrap_or_else(PoisonError::into_inner); + first.map_or(Ok(()), Err) + } +} + /// A file a scan matched to a table: its path, the same path relative to the /// scan root as `/`-separated text, and the table. #[derive(Debug, Clone, PartialEq, Eq)] @@ -70,14 +112,29 @@ fn paired(found: Vec) -> Vec<(PathBuf, String)> { /// The count is files *visited*, not the pairs returned: a file matching two /// tables' globs is one file the walk paid for, and two rows of work for the /// phase after it. +/// +/// Fails naming the first folder, in path order, that exists but cannot be +/// listed. pub fn scan_directory_reporting( root: &Path, matcher: &TableMatcher, on_file: &mut dyn FnMut(u64), on_match: &mut dyn FnMut(&Path, &str), on_link: &(dyn Fn(&Path) + Sync), -) -> Vec { - scan_below(root, root, matcher, on_file, on_match, on_link) +) -> Result, UnlistableFolder> { + let unlisted = Unlisted::default(); + let found = scan_below( + root, + root, + matcher, + on_file, + on_match, + on_link, + &|dir, err| { + unlisted.note(dir, err); + }, + ); + unlisted.into_result().map(|()| found) } /// [`scan_directory`] restricted to the subtree at `dir`, a directory beneath @@ -92,7 +149,7 @@ pub fn scan_subtree(root: &Path, dir: &Path, matcher: &TableMatcher) -> Vec<(Pat } /// [`scan_subtree`], telling `on_link` the path of each symlinked directory -/// the walk enters. +/// the walk enters. A folder that cannot be listed contributes nothing. pub fn scan_subtree_reporting( root: &Path, dir: &Path, @@ -106,6 +163,7 @@ pub fn scan_subtree_reporting( &mut |_| {}, &mut |_, _| {}, on_link, + &ignore_unlistable, )) } @@ -140,6 +198,7 @@ pub fn scan_dirs(root: &Path, start: &Path, ignore: &TableMatcher) -> Vec Vec { let mut results = Vec::new(); let mut seen: u64 = 0; @@ -181,6 +241,7 @@ fn scan_below( frames: repo.map_or_else(Vec::new, |top| gitignores_above(start, top, &Frame::load)), dirs: false, on_link, + on_unlistable, }; walk( root, @@ -227,12 +288,15 @@ fn scan_below( /// filter what lies below it, never `root` itself, so naming an ignored /// directory still scans it. [`scan_glob_checking_root`] lifts that for a /// root that is only the literal prefix of a wildcard. +/// +/// Fails naming the first folder, in path order, that exists but cannot be +/// listed; a missing one holds nothing. pub fn scan_glob( root: &Path, glob: &PathGlob, ignore: &TableMatcher, gitignore: bool, -) -> Vec { +) -> Result, UnlistableFolder> { scan_glob_checking_root(root, glob, ignore, gitignore, false) } @@ -245,7 +309,7 @@ pub fn scan_glob_checking_root( ignore: &TableMatcher, gitignore: bool, check_root: bool, -) -> Vec { +) -> Result, UnlistableFolder> { let mut paths = Vec::new(); scan_glob_rows( root, @@ -255,8 +319,8 @@ pub fn scan_glob_checking_root( check_root, &|rel_path| rel_path, &mut |rel_path| paths.push(rel_path), - ); - paths + )?; + Ok(paths) } /// [`scan_glob_checking_root`], each matched path made into `row` on the @@ -270,15 +334,16 @@ pub(crate) fn scan_glob_rows( check_root: bool, row: &(dyn Fn(PathBuf) -> T + Sync), visit: &mut dyn FnMut(T), -) { +) -> Result<(), UnlistableFolder> { if gitignore && check_root && !holds_git(root) && is_gitignored_path(root, true) { - return; + return Ok(()); } let repo = if gitignore { enclosing_repo(root, &holds_git) } else { None }; + let unlisted = Unlisted::default(); let walker = Walk { ignore, glob: Some(glob), @@ -287,6 +352,7 @@ pub(crate) fn scan_glob_rows( frames: repo.map_or_else(Vec::new, |top| gitignores_above(root, top, &Frame::load)), dirs: false, on_link: &ignore_link, + on_unlistable: &|dir, err| unlisted.note(dir, err), }; walk( root, @@ -297,6 +363,7 @@ pub(crate) fn scan_glob_rows( &|rel_path, _| row(rel_path), visit, ); + unlisted.into_result() } /// Whether a walked file is a row of the table: it matches the glob and no @@ -590,8 +657,9 @@ pub(crate) fn parse_gitignore_arg(arg: &str) -> Result { /// are pruned/skipped too, starting from the walker's frames: the ones in /// force above `start` when a repo encloses it. Inside a directory holding /// `.git`, its `.gitignore` files apply. Symlinks are followed only as the -/// glob allows, and not at all without one; a broken link or an unreadable -/// directory contributes nothing. +/// glob allows, and not at all without one; a broken link or a missing +/// directory contributes nothing, and one that cannot be listed is handed to +/// the walker's `on_unlistable`. fn walk( root: &Path, start: &Path, @@ -665,7 +733,10 @@ impl<'a> Place<'a> { if let Some(Part { listing, range }) = self.part.take() { return self.judge(&listing, &listing.entries()[range], keep_name, keep, leaf); } - let listing = Listing::read(&self.dir); + let listing = Listing::read(&self.dir).unwrap_or_else(|err| { + (self.walk.on_unlistable)(&self.dir, err); + Listing::default() + }); if self.walk.gitignore && listing.holds(OsStr::new(".git")) && holds_git(&self.dir) { self.walk.in_repo = true; self.walk.frames.clear(); @@ -840,10 +911,14 @@ struct Walk<'a> { dirs: bool, /// Told the path of each symlinked directory the walk enters. on_link: &'a (dyn Fn(&Path) + Sync), + /// Told each directory the walk reaches that exists but cannot be listed. + on_unlistable: &'a (dyn Fn(&Path, std::io::Error) + Sync), } fn ignore_link(_: &Path) {} +fn ignore_unlistable(_: &Path, _: std::io::Error) {} + /// `rel.join(name)` in one allocation: the walk builds one per entry on every /// worker thread, and `join`'s grow-on-push contends the allocator's arenas. fn child_path(rel: &Path, name: &OsStr) -> PathBuf { @@ -1128,7 +1203,8 @@ mod tests { &mut |count| counts.push(count), &mut |_, _| {}, &ignore_link, - ); + ) + .unwrap(); assert_eq!( rows, @@ -1780,6 +1856,7 @@ mod tests { frames, dirs: false, on_link: &ignore_link, + on_unlistable: &ignore_unlistable, } } @@ -2107,6 +2184,7 @@ mod tests { frames: Vec::new(), dirs: false, on_link: &ignore_link, + on_unlistable: &ignore_unlistable, }; assert!(walk.follows(true, &[2], Kind::File)); assert!(!walk.follows(true, &[1], Kind::File)); @@ -2125,6 +2203,7 @@ mod tests { frames: Vec::new(), dirs: false, on_link: &ignore_link, + on_unlistable: &ignore_unlistable, }; assert!(walk.follows(false, &[1], Kind::Dir)); assert!(!walk.follows(false, &[2], Kind::Dir)); @@ -2143,6 +2222,7 @@ mod tests { frames: Vec::new(), dirs: false, on_link: &ignore_link, + on_unlistable: &ignore_unlistable, }; assert!(walk.follows(false, &[], Kind::Dir)); } @@ -2197,8 +2277,9 @@ mod tests { fs::write(repo.path().join("dist/out.log"), "").unwrap(); fs::write(repo.path().join("a.log"), "").unwrap(); let none = TableMatcher::new(&[], &[]).unwrap(); - let scan = - |pattern: &str| scan_glob(repo.path(), &compile_glob(pattern).unwrap(), &none, true); + let scan = |pattern: &str| { + scan_glob(repo.path(), &compile_glob(pattern).unwrap(), &none, true).unwrap() + }; assert_eq!(scan("a.log"), vec![PathBuf::from("a.log")]); assert_eq!(scan("dist/out.log"), vec![PathBuf::from("dist/out.log")]); @@ -2240,7 +2321,7 @@ mod tests { let none = TableMatcher::new(&[], &[]).unwrap(); let glob = compile_glob("*").unwrap(); let scan = |dir: &str, check_root: bool| { - scan_glob_checking_root(&repo.path().join(dir), &glob, &none, true, check_root) + scan_glob_checking_root(&repo.path().join(dir), &glob, &none, true, check_root).unwrap() }; assert!(scan("dist", true).is_empty()); @@ -2260,7 +2341,7 @@ mod tests { let glob = compile_glob("*.js").unwrap(); assert_eq!( - scan_glob_checking_root(&repo.path().join("src"), &glob, &none, true, true), + scan_glob_checking_root(&repo.path().join("src"), &glob, &none, true, true).unwrap(), vec![PathBuf::from("a.js")] ); } @@ -2276,7 +2357,7 @@ mod tests { let glob = compile_glob("*.js").unwrap(); assert_eq!( - scan_glob_checking_root(&outer.path().join("inner"), &glob, &none, true, true), + scan_glob_checking_root(&outer.path().join("inner"), &glob, &none, true, true).unwrap(), vec![PathBuf::from("a.js")] ); } @@ -2330,9 +2411,10 @@ mod tests { rel }, &mut |row| rows.push(row), - ); + ) + .unwrap(); - assert_eq!(rows, scan_glob(dir.path(), &glob, &none, false)); + assert_eq!(rows, scan_glob(dir.path(), &glob, &none, false).unwrap()); assert!( overlapped.load(Ordering::SeqCst), "rows were made one at a time" @@ -2357,10 +2439,11 @@ mod tests { false, &|rel| (MADE_ON.with(|on| std::ptr::from_ref(on).addr()), rel), &mut |row| rows.push(row), - ); + ) + .unwrap(); let paths: Vec = rows.iter().map(|(_, rel)| rel.clone()).collect(); - assert_eq!(paths, scan_glob(dir.path(), &glob, &none, false)); + assert_eq!(paths, scan_glob(dir.path(), &glob, &none, false).unwrap()); let threads: std::collections::HashSet<_> = rows.iter().map(|(made_on, _)| made_on).collect(); assert!(threads.len() > 1, "every row was made on one thread"); @@ -2402,7 +2485,8 @@ mod tests { *lock.lock().unwrap() = true; changed.notify_all(); }, - ); + ) + .unwrap(); assert!( last_made_after.load(Ordering::SeqCst), diff --git a/packages/rust/src/vtab.rs b/packages/rust/src/vtab.rs index af1c66e4..df5e5816 100644 --- a/packages/rust/src/vtab.rs +++ b/packages/rust/src/vtab.rs @@ -525,7 +525,9 @@ impl TableSource for ScanSpec { // The scan runs per statement rather than at CREATE, which is what // makes reads live: each statement sees the filesystem as it is now. let mut chunk = Vec::with_capacity(STREAM_CHUNK_ROWS); - scan_glob_rows( + // A statement's rows have no way to fail yet, so a folder that cannot + // be listed holds nothing here. + let _ = scan_glob_rows( &self.root, &self.glob, &self.ignore, diff --git a/packages/rust/tests/scanner.rs b/packages/rust/tests/scanner.rs index 33c05499..4f2fbcfd 100644 --- a/packages/rust/tests/scanner.rs +++ b/packages/rust/tests/scanner.rs @@ -194,7 +194,7 @@ fn scan_glob_stops_outer_gitignore_rules_at_nested_repo() { let ignore = TableMatcher::new(&[], &[]).unwrap(); let glob = compile_glob("**").unwrap(); - let results = scan_glob(outer.path(), &glob, &ignore, true); + let results = scan_glob(outer.path(), &glob, &ignore, true).unwrap(); assert_eq!(results, vec![std::path::PathBuf::from("repo/z.log")]); } @@ -214,7 +214,7 @@ fn scan_glob_applies_gitignore_only_inside_a_repo() { let ignore = TableMatcher::new(&[], &[]).unwrap(); let glob = compile_glob("**").unwrap(); - let results = scan_glob(outer.path(), &glob, &ignore, true); + let results = scan_glob(outer.path(), &glob, &ignore, true).unwrap(); assert_eq!(results, vec![std::path::PathBuf::from("zz-sibling/z.log")]); } @@ -241,6 +241,7 @@ fn scan_paths(root: &TempDir, pattern: &str) -> Vec { let ignore = TableMatcher::new(&[], &[]).unwrap(); let glob = compile_glob(pattern).unwrap(); scan_glob(root.path(), &glob, &ignore, false) + .unwrap() .into_iter() .map(|p| { p.components() From af86824c678032870241d1a4e35b5ce67c718bcb Mon Sep 17 00:00:00 2001 From: thekevinbot <248217931+thekevinbot@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:59:07 -0500 Subject: [PATCH 3/4] e2e attestation for bot/1740-unlistable-folder-fails-1118 --- .../bot-1740-unlistable-folder-fails-1118.json | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 packages/python/e2e-attestations/bot-1740-unlistable-folder-fails-1118.json diff --git a/packages/python/e2e-attestations/bot-1740-unlistable-folder-fails-1118.json b/packages/python/e2e-attestations/bot-1740-unlistable-folder-fails-1118.json new file mode 100644 index 00000000..159228b3 --- /dev/null +++ b/packages/python/e2e-attestations/bot-1740-unlistable-folder-fails-1118.json @@ -0,0 +1,7 @@ +{ + "command": "uv run python -m pytest tests/e2e/on_file_query_test.py tests/e2e/on_file_failure_test.py tests/e2e/query_contract_test.py tests/e2e/glob_speed_recursive_test.py tests/e2e/glob_speed_symlink_test.py tests/e2e/many_dirs_speed_test.py tests/e2e/parent_then_child_test.py -x -q", + "ran_at": 1795021146, + "exit_code": 0, + "commit": "57438a24cfe8bee2dfe32f8258722fc028c2e34c", + "branch": "bot/1740-unlistable-folder-fails-1118" +} From e0a8817a612ba7db26e16f4e73c2e3f94a6a777f Mon Sep 17 00:00:00 2001 From: thekevinbot <248217931+thekevinbot@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:00:22 -0500 Subject: [PATCH 4/4] e2e attestation for bot/1740-unlistable-folder-fails-1118 --- .../bot-1740-unlistable-folder-fails-1118.json | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 packages/ts/e2e-attestations/bot-1740-unlistable-folder-fails-1118.json diff --git a/packages/ts/e2e-attestations/bot-1740-unlistable-folder-fails-1118.json b/packages/ts/e2e-attestations/bot-1740-unlistable-folder-fails-1118.json new file mode 100644 index 00000000..0f442c95 --- /dev/null +++ b/packages/ts/e2e-attestations/bot-1740-unlistable-folder-fails-1118.json @@ -0,0 +1,7 @@ +{ + "command": "pnpm test:e2e", + "ran_at": 1795021222, + "exit_code": 0, + "commit": "af86824c678032870241d1a4e35b5ce67c718bcb", + "branch": "bot/1740-unlistable-folder-fails-1118" +}