Incremental engine for long horizon agents 🌟 Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
fix(rust-sdk): local-files entries change kind; Doris validates its database name (#2775)
LJ 🥥🌴d03bf5dff5dd
diff --git a/rust/sdk/cocoindex/src/connectors/doris.rs b/rust/sdk/cocoindex/src/connectors/doris.rsindex db0d966b..25e8c39d 100644--- a/rust/sdk/cocoindex/src/connectors/doris.rs+++ b/rust/sdk/cocoindex/src/connectors/doris.rs@@ -184,6 +184,10 @@ impl DorisConnection {/// port (used for DDL/DELETE) and builds an HTTP client for Stream Load. The/// `database` must already exist.pub async fn connect(config: DorisConfig) -> Result<Self> {+ // The database name is spliced into DDL, `DELETE` and the Stream Load+ // URL, so it gets the identifier allow-list too (as in Python, after+ // CVE-2026-28438).+ validate_ident(&config.database, "database name")?;for (name, value) in [("retry_base_delay", config.retry_base_delay),("retry_max_delay", config.retry_max_delay),@@ -1818,19 +1822,24 @@ fn json_scalar_to_stable_key(value: &JsonValue) -> Result<StableKey> {fn sql_value_literal(value: &JsonValue) -> String {match value {JsonValue::String(s) => {- let escaped = s.replace('\\', "\\\\").replace('\'', "\\'");- format!("'{escaped}'")+ format!("'{}'", escape_string_literal(s))}JsonValue::Bool(b) => if *b { "1" } else { "0" }.to_string(),JsonValue::Number(n) => n.to_string(),JsonValue::Null => "NULL".to_string(),- other => {- let escaped = other.to_string().replace('\\', "\\\\").replace('\'', "\\'");- format!("'{escaped}'")- }+ other => format!("'{}'", escape_string_literal(&other.to_string())),}}+/// The body of a single-quoted MySQL string literal: `\`, `'` and U+0000+/// (which would end the statement text early in some MySQL-protocol parsers)+/// escaped.+fn escape_string_literal(s: &str) -> String {+ s.replace('\\', "\\\\")+ .replace('\'', "\\'")+ .replace('\0', "\\0")+}+// ---------------------------------------------------------------------------// Validation// ---------------------------------------------------------------------------@@ -2012,6 +2021,22 @@ mod tests {assert_eq!(sql_value_literal(&JsonValue::from("a\\b")), "'a\\\\b'");assert_eq!(sql_value_literal(&JsonValue::from(7)), "7");assert_eq!(sql_value_literal(&JsonValue::from(true)), "1");+ assert_eq!(sql_value_literal(&JsonValue::from("a\0b")), "'a\\0b'");+ assert_eq!(+ sql_value_literal(&JsonValue::from("x' OR '1'='1")),+ "'x\\' OR \\'1\\'=\\'1'"+ );+ }++ #[tokio::test]+ async fn connect_rejects_a_database_name_outside_the_identifier_allow_list() {+ for bad in ["db`; DROP DATABASE x; --", "", "my-db", "a b"] {+ let err = DorisConnection::connect(DorisConfig::new("127.0.0.1", bad))+ .await+ .err()+ .expect("rejected before connecting");+ assert!(err.to_string().contains("database name"), "{bad:?}: {err}");+ }}#[test]diff --git a/rust/sdk/cocoindex/src/resources/fs.rs b/rust/sdk/cocoindex/src/resources/fs.rsindex 70448e4f..3e55acda 100644--- a/rust/sdk/cocoindex/src/resources/fs.rs+++ b/rust/sdk/cocoindex/src/resources/fs.rs@@ -1134,9 +1134,17 @@ enum FsOp {WriteFile {content: Vec<u8>,create_parent_dirs: bool,+ /// A previous run declared a directory here: remove that directory+ /// (with what is under it) before writing the file.+ #[serde(default)]+ replaces_dir: bool,},CreateDir {create_parent_dirs: bool,+ /// A previous run declared a file here: remove it before creating the+ /// directory.+ #[serde(default)]+ replaces_file: bool,},RemoveFile,RemoveDir,@@ -1190,6 +1198,10 @@ impl TargetHandler<FsEntry> for FileHandler {if desired.is_none() && prev.is_empty() && !prev_may_be_missing {return Ok(None);}+ // What a previous run declared here: a directory, a file, or both+ // (when the previous state is uncertain).+ let was_dir = prev.iter().any(|p| *p == dir_fingerprint());+ let was_file = prev.iter().any(|p| *p != dir_fingerprint());let op = match desired {Some(FsEntry::File {content,@@ -1197,10 +1209,14 @@ impl TargetHandler<FsEntry> for FileHandler {}) => FsOp::WriteFile {content,create_parent_dirs,+ replaces_dir: was_dir,+ },+ Some(FsEntry::Dir { create_parent_dirs }) => FsOp::CreateDir {+ create_parent_dirs,+ replaces_file: was_file,},- Some(FsEntry::Dir { create_parent_dirs }) => FsOp::CreateDir { create_parent_dirs },// A removed entry: a directory if it was tracked as one.- None if prev.iter().any(|p| *p == dir_fingerprint()) => FsOp::RemoveDir,+ None if was_dir => FsOp::RemoveDir,None => FsOp::RemoveFile,};Ok(Some(TargetReconcileOutput {@@ -1240,6 +1256,17 @@ fn entry_path(key: &StableKey) -> Result<(Option<String>, PathBuf)> {/// Apply a batch of entry actions: directories are created before the files/// in them, and files are removed before the directories they were in.+///+/// An entry declared as a file where a previous run declared a directory (or+/// the other way round) replaces what that run created; something of the other+/// kind that CocoIndex didn't create is an error, as it would be in Python.+///+/// Two keys can name one entry: names that differ only in case on a+/// case-insensitive file system, or a path through a symlinked directory. When+/// an update moves an entry from one key to the other, the write for the new+/// key and the removal for the old key arrive in one batch; the removal is+/// skipped there, since it would remove the entry just written (Python's+/// `_apply_entry_actions` does the same).fn apply_fs_actions(actions: Vec<(PathBuf, FsOp)>) -> std::io::Result<()> {let mut creates = Vec::new();let mut writes = Vec::new();@@ -1247,17 +1274,26 @@ fn apply_fs_actions(actions: Vec<(PathBuf, FsOp)>) -> std::io::Result<()> {let mut dir_removes = Vec::new();for (path, op) in actions {match op {- FsOp::CreateDir { create_parent_dirs } => creates.push((path, create_parent_dirs)),+ FsOp::CreateDir {+ create_parent_dirs,+ replaces_file,+ } => creates.push((path, create_parent_dirs, replaces_file)),FsOp::WriteFile {content,create_parent_dirs,- } => writes.push((path, content, create_parent_dirs)),+ replaces_dir,+ } => writes.push((path, content, create_parent_dirs, replaces_dir)),FsOp::RemoveFile => file_removes.push(path),FsOp::RemoveDir => dir_removes.push(path),}}+ let track_written = !file_removes.is_empty() || !dir_removes.is_empty();+ let mut written = std::collections::HashSet::new();creates.sort_by(|a, b| a.0.cmp(&b.0));- for (path, create_parent_dirs) in creates {+ for (path, create_parent_dirs, replaces_file) in creates {+ if replaces_file && is_kind(&path, false) {+ remove_file_if_exists(&path)?;+ }if create_parent_dirs {std::fs::create_dir_all(&path)?;} else if let Err(e) = std::fs::create_dir(&path)@@ -1265,30 +1301,86 @@ fn apply_fs_actions(actions: Vec<(PathBuf, FsOp)>) -> std::io::Result<()> {{return Err(e);}+ if track_written && let Some(id) = entry_identity(&path) {+ written.insert(id);+ }}- for (path, content, create_parent_dirs) in writes {+ for (path, content, create_parent_dirs, replaces_dir) in writes {+ if replaces_dir && is_kind(&path, true) {+ std::fs::remove_dir_all(&path)?;+ }if create_parent_dirs && let Some(parent) = path.parent() {std::fs::create_dir_all(parent)?;}std::fs::write(&path, &content)?;+ if track_written && let Some(id) = entry_identity(&path) {+ written.insert(id);+ }}+ let written_here = |path: &Path| {+ !written.is_empty()+ && std::fs::symlink_metadata(path)+ .ok()+ .and_then(|m| identity_of(&m))+ .is_some_and(|id| written.contains(&id))+ };for path in file_removes {- match std::fs::remove_file(&path) {- Ok(()) => {}- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}- Err(e) => return Err(e),+ if !written_here(&path) {+ remove_file_if_exists(&path)?;}}// Deepest first, so a removed tree's subdirectories go before it.dir_removes.sort_by(|a, b| b.cmp(a));for path in dir_removes {- if path.is_dir() {+ if path.is_dir() && !written_here(&path) {std::fs::remove_dir_all(&path)?;}}Ok(())}+/// Whether `path` is a directory (`dir`) or something else, without following+/// a symlink at `path` itself. `false` when nothing is there.+fn is_kind(path: &Path, dir: bool) -> bool {+ std::fs::symlink_metadata(path).is_ok_and(|m| m.is_dir() == dir)+}++/// Remove a file; nothing there (or a file where a parent directory was+/// expected) is not an error.+fn remove_file_if_exists(path: &Path) -> std::io::Result<()> {+ match std::fs::remove_file(path) {+ Ok(()) => Ok(()),+ Err(e)+ if matches!(+ e.kind(),+ std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory+ ) =>+ {+ Ok(())+ }+ Err(e) => Err(e),+ }+}++/// The identity of the entry at `path` (following symlinks, as a write does).+fn entry_identity(path: &Path) -> Option<(u64, u64)> {+ std::fs::metadata(path).ok().and_then(|m| identity_of(&m))+}++/// `(device, inode)`; `None` where the platform reports no inode numbers. On+/// Windows, where the standard library exposes no stable file index, the+/// moved-entry check is skipped.+#[cfg(unix)]+fn identity_of(metadata: &std::fs::Metadata) -> Option<(u64, u64)> {+ use std::os::unix::fs::MetadataExt as _;+ (metadata.ino() != 0).then(|| (metadata.dev(), metadata.ino()))+}++#[cfg(not(unix))]+fn identity_of(_metadata: &std::fs::Metadata) -> Option<(u64, u64)> {+ None+}+fn file_sink() -> TargetActionSink<FsAction> {TargetActionSink::from_async_fn_with_ctx(move |host_ctx, actions: Vec<TargetAction<FsAction>>| async move {@@ -1499,12 +1591,14 @@ mod tests {FsOp::WriteFile {content: b"A".to_vec(),create_parent_dirs: false,+ replaces_dir: false,},),(root.join("sub"),FsOp::CreateDir {create_parent_dirs: false,+ replaces_file: false,},),])@@ -1517,6 +1611,7 @@ mod tests {FsOp::WriteFile {content: b"B".to_vec(),create_parent_dirs: false,+ replaces_dir: false,},)]);assert!(missing.is_err());@@ -1525,6 +1620,7 @@ mod tests {FsOp::WriteFile {content: b"B".to_vec(),create_parent_dirs: true,+ replaces_dir: false,},)]).unwrap();diff --git a/rust/sdk/cocoindex/tests/bigquery_target.rs b/rust/sdk/cocoindex/tests/bigquery_target.rsindex 20053b51..428a9e53 100644--- a/rust/sdk/cocoindex/tests/bigquery_target.rs+++ b/rust/sdk/cocoindex/tests/bigquery_target.rs@@ -602,3 +602,200 @@ async fn bigquery_live_upsert_and_delete() -> Result<()> {.await;result}++/// A column list, each `(name, BigQuery type, required)`.+type BqCols = Vec<(&'static str, &'static str, bool)>;++fn bq_schema(cols: &BqCols, pk: &[&str]) -> Result<TableSchema> {+ TableSchema::new(+ cols.iter().map(|(name, ty, required)| {+ let def = ColumnDef::new(*ty);+ (*name, if *required { def.not_null() } else { def })+ }),+ pk.iter().copied(),+ )+}++/// One run declaring JSON `rows` into `analytics.<table>`.+async fn declare_json(+ conn: &BigQueryConnection,+ db_path: &Path,+ table: &'static str,+ cols: BqCols,+ pk: &'static [&'static str],+ rows: Vec<JsonValue>,+) -> Result<()> {+ let app = Environment::builder()+ .db_path(db_path)+ .provide_key(&BQ, conn.clone())+ .build()+ .await?+ .app("BigQueryEdgeTest")+ .await?;+ app.run(move |ctx| async move {+ let target =+ bigquery::mount_table_target(&ctx, &BQ, "analytics", table, bq_schema(&cols, pk)?)+ .await?;+ for row in &rows {+ target.declare_row(&ctx, row)?;+ }+ Ok(())+ })+ .await?;+ Ok(())+}++/// Schema evolution between runs issues the DDL Python's connector does: an+/// added column is `ADD COLUMN` (nullable: BigQuery rejects a REQUIRED add), a+/// removed one `DROP COLUMN`, a retyped or re-nullabled one is dropped and+/// added again with the rows rewritten, and a primary-key change recreates+/// the table.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn bigquery_schema_evolution_issues_column_ddl() -> Result<()> {+ let Some(server) = bigquery_server().await else {+ return Ok(());+ };+ let conn = connection(&server);+ let tmp = tempfile::tempdir().unwrap();+ let db = tmp.path().join("db");+ let row = json!({"id": 1, "a": "x", "b": 2, "c": "y"});+ let run = |cols: BqCols, pk: &'static [&'static str]| {+ let conn = conn.clone();+ let db = db.clone();+ let row = row.clone();+ async move { declare_json(&conn, &db, "evo", cols, pk, vec![row]).await }+ };+ let ddl = |queries: Vec<(String, Vec<JsonValue>)>| -> Vec<String> {+ queries+ .into_iter()+ .map(|(q, _)| q)+ .filter(|q| !q.starts_with("MERGE") && !q.starts_with("DELETE"))+ .collect()+ };++ run(vec![("id", "INT64", true), ("a", "STRING", false)], &["id"]).await?;+ server.reset().await;+ let server = bigquery_server_on(server).await.unwrap();+ run(+ vec![+ ("id", "INT64", true),+ ("a", "STRING", false),+ ("b", "INT64", true),+ ],+ &["id"],+ )+ .await?;+ assert_eq!(+ ddl(received_queries(&server).await),+ ["ALTER TABLE `analytics.evo` ADD COLUMN `b` INT64"]+ );++ server.reset().await;+ let server = bigquery_server_on(server).await.unwrap();+ run(+ vec![+ ("id", "INT64", true),+ ("a", "STRING", true),+ ("c", "STRING", false),+ ],+ &["id"],+ )+ .await?;+ let mut statements = ddl(received_queries(&server).await);+ statements.sort();+ assert_eq!(+ statements,+ [+ "ALTER TABLE `analytics.evo` ADD COLUMN `a` STRING",+ "ALTER TABLE `analytics.evo` ADD COLUMN `c` STRING",+ "ALTER TABLE `analytics.evo` DROP COLUMN IF EXISTS `a`",+ "ALTER TABLE `analytics.evo` DROP COLUMN IF EXISTS `b`",+ ]+ );+ // A lossy change rewrites the row.+ assert!(+ received_queries(&server)+ .await+ .iter()+ .any(|(q, _)| q.starts_with("MERGE")),+ "the row is rewritten after a lossy column change"+ );++ server.reset().await;+ let server = bigquery_server_on(server).await.unwrap();+ run(+ vec![+ ("id", "INT64", true),+ ("a", "STRING", true),+ ("c", "STRING", false),+ ],+ &["id", "a"],+ )+ .await?;+ let statements = ddl(received_queries(&server).await);+ assert_eq!(+ statements,+ [+ "DROP TABLE IF EXISTS `analytics.evo`",+ "CREATE SCHEMA IF NOT EXISTS `analytics`",+ "CREATE TABLE `analytics.evo` (`id` INT64 NOT NULL, `a` STRING NOT NULL, `c` STRING, \+ PRIMARY KEY (`id`, `a`) NOT ENFORCED)",+ ]+ );+ Ok(())+}++/// Rows go in `MERGE` statements of at most 2,000 parameters: with 2 columns+/// that is 1,000 rows, so 1,000 rows → 1 statement and 1,001 → 2; deletes of+/// a single-column key take 2,000 keys per statement.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn bigquery_batches_follow_the_parameter_limit() -> Result<()> {+ let cols: BqCols = vec![("id", "INT64", true), ("v", "STRING", false)];+ for (n, merges) in [(1usize, 1usize), (1000, 1), (1001, 2), (2001, 3)] {+ let Some(server) = bigquery_server().await else {+ return Ok(());+ };+ let conn = connection(&server);+ let tmp = tempfile::tempdir().unwrap();+ let rows = (0..n as i64)+ .map(|id| json!({"id": id, "v": "x"}))+ .collect();+ declare_json(+ &conn,+ &tmp.path().join("db"),+ "batch",+ cols.clone(),+ &["id"],+ rows,+ )+ .await?;+ let queries = received_queries(&server).await;+ let count = queries+ .iter()+ .filter(|(q, _)| q.starts_with("MERGE"))+ .count();+ assert_eq!(count, merges, "{n} rows");+ assert!(queries.iter().all(|(_, params)| params.len() <= 2000));+ if n == 2001 {+ server.reset().await;+ let server = bigquery_server_on(server).await.unwrap();+ declare_json(+ &conn,+ &tmp.path().join("db"),+ "batch",+ cols.clone(),+ &["id"],+ vec![],+ )+ .await?;+ let deletes: Vec<usize> = received_queries(&server)+ .await+ .iter()+ .filter(|(q, _)| q.starts_with("DELETE"))+ .map(|(_, params)| params.len())+ .collect();+ assert_eq!(deletes, [2000, 1]);+ }+ }+ Ok(())+}diff --git a/rust/sdk/cocoindex/tests/fs_target.rs b/rust/sdk/cocoindex/tests/fs_target.rsindex ccbee50e..f7841859 100644--- a/rust/sdk/cocoindex/tests/fs_target.rs+++ b/rust/sdk/cocoindex/tests/fs_target.rs@@ -182,3 +182,267 @@ async fn a_root_under_a_context_dir_follows_the_directory_between_runs() {);assert!(!first.exists());}++/// One `update` of the app `name` over `db`.+async fn update_once<F, Fut>(db: &std::path::Path, name: &str, f: F) -> cocoindex::Result<()>+where+ F: FnOnce(cocoindex::Ctx) -> Fut + Send + 'static,+ Fut: std::future::Future<Output = cocoindex::Result<()>> + Send + 'static,+{+ let app = App::builder(name).db_path(db).build().await?;+ app.update(f).await+}++/// An entry declared as a directory where a previous run declared a file (and+/// the other way round) replaces it, along with what was under the directory.+#[tokio::test]+async fn a_file_and_a_directory_replace_each_other_at_one_path() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("lmdb");+ let out = dir.path().join("out");++ let o = out.clone();+ update_once(&db, "fs_kind", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_file(&ctx, "x", b"file")+ })+ .await+ .unwrap();+ assert!(out.join("x").is_file());++ let o = out.clone();+ update_once(&db, "fs_kind", move |ctx| async move {+ let t = DirTarget::mount(&ctx, &o)?;+ t.declare_dir_target(&ctx, "x", false)?+ .declare_file(&ctx, "inner.txt", b"inner")+ })+ .await+ .unwrap();+ assert_eq!(std::fs::read(out.join("x/inner.txt")).unwrap(), b"inner");++ let o = out.clone();+ update_once(&db, "fs_kind", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_file(&ctx, "x", b"file again")+ })+ .await+ .unwrap();+ assert_eq!(std::fs::read(out.join("x")).unwrap(), b"file again");++ // Something CocoIndex didn't create is never replaced: a directory the+ // user made where a new file is declared fails the run and stays.+ std::fs::create_dir(out.join("y")).unwrap();+ std::fs::write(out.join("y/user.txt"), b"mine").unwrap();+ let o = out.clone();+ let result = update_once(&db, "fs_kind", move |ctx| async move {+ let t = DirTarget::mount(&ctx, &o)?;+ t.declare_file(&ctx, "x", b"file again")?;+ t.declare_file(&ctx, "y", b"clobber?")+ })+ .await;+ assert!(result.is_err());+ assert_eq!(std::fs::read(out.join("y/user.txt")).unwrap(), b"mine");+}++/// When a declared file moves from one name to another that names the same+/// file (here through a symlinked directory; on a case-insensitive file system,+/// a change of case), the removal of the old name doesn't remove the file just+/// written under the new one.+#[cfg(unix)]+#[tokio::test]+async fn a_file_moved_to_another_name_for_the_same_entry_is_kept() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("lmdb");+ let out = dir.path().join("out");+ std::fs::create_dir_all(out.join("real")).unwrap();+ std::os::unix::fs::symlink("real", out.join("link")).unwrap();++ let o = out.clone();+ update_once(&db, "fs_alias", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_file(&ctx, "real/a.txt", b"v1")+ })+ .await+ .unwrap();+ let o = out.clone();+ update_once(&db, "fs_alias", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_file(&ctx, "link/a.txt", b"v2")+ })+ .await+ .unwrap();+ assert_eq!(std::fs::read(out.join("real/a.txt")).unwrap(), b"v2");+}++/// Names that leave the directory, or name nothing in it, are rejected when+/// declared; nothing is written outside the directory.+#[tokio::test]+async fn names_that_leave_the_directory_are_rejected() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("lmdb");+ let out = dir.path().join("out");+ for name in [+ "..",+ "../x",+ "a/../../x",+ "a/../b",+ "/etc/passwd",+ "",+ ".",+ "./",+ "sub/..",+ ] {+ let o = out.clone();+ let result = update_once(&db, "fs_names", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_file(&ctx, name, b"x")+ })+ .await;+ assert!(result.is_err(), "{name:?} must be rejected");+ let o = out.clone();+ let result = update_once(&db, "fs_names", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_dir_target(&ctx, name, true)?;+ Ok(())+ })+ .await;+ assert!(result.is_err(), "{name:?} must be rejected as a directory");+ }+ assert!(!dir.path().join("x").exists());+ let entries: Vec<_> = std::fs::read_dir(&out).unwrap().collect();+ assert!(entries.is_empty(), "{entries:?}");+}++/// Two names for one entry in one run (`a` and `./a`) are one key: the second+/// declaration fails the run instead of racing the first.+#[tokio::test]+async fn one_entry_declared_twice_fails_the_run() {+ let dir = tempfile::tempdir().unwrap();+ let out = dir.path().join("out");+ let o = out.clone();+ let result = update_once(&dir.path().join("lmdb"), "fs_dup", move |ctx| async move {+ let t = DirTarget::mount(&ctx, &o)?;+ t.declare_file(&ctx, "a", b"one")?;+ t.declare_file(&ctx, "./a", b"two")+ })+ .await;+ let err = result.unwrap_err().to_string();+ assert!(err.contains("already declared"), "{err}");+}++/// Unicode names and names that differ only in case are distinct entries on a+/// case-sensitive file system; a name over the file system's limit fails the+/// run with the OS error.+#[tokio::test]+async fn unicode_case_and_overlong_names() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("lmdb");+ let out = dir.path().join("out");+ let o = out.clone();+ update_once(&db, "fs_unicode", move |ctx| async move {+ let t = DirTarget::mount(&ctx, &o)?;+ t.declare_file(&ctx, "ünïcödé 🎉.txt", b"u")?;+ t.declare_file(&ctx, "Case.txt", b"upper")?;+ t.declare_file(&ctx, "with space & $ymbols;.txt", b"s")+ })+ .await+ .unwrap();+ assert_eq!(std::fs::read(out.join("ünïcödé 🎉.txt")).unwrap(), b"u");+ assert_eq!(std::fs::read(out.join("Case.txt")).unwrap(), b"upper");++ let o = out.clone();+ let long = "n".repeat(300);+ let result = update_once(&db, "fs_unicode", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_file(&ctx, &long, b"x")+ })+ .await;+ assert!(result.is_err());+}++/// A file that can't be written (a read-only directory) fails the run; once+/// the directory is writable again, the next run writes it.+#[cfg(unix)]+#[tokio::test]+async fn a_read_only_directory_fails_the_run_and_the_next_run_repairs() {+ use std::os::unix::fs::PermissionsExt as _;+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("lmdb");+ let out = dir.path().join("out");+ std::fs::create_dir_all(&out).unwrap();+ std::fs::set_permissions(&out, std::fs::Permissions::from_mode(0o555)).unwrap();+ if std::fs::write(out.join("probe"), b"").is_ok() {+ eprintln!("skipping: running with permission to write a read-only directory (root?)");+ return;+ }+ let run = || {+ let o = out.clone();+ let db = db.clone();+ async move {+ update_once(&db, "fs_readonly", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_file(&ctx, "a.txt", b"A")+ })+ .await+ }+ };+ let err = run().await.unwrap_err();+ assert!(+ err.to_string().to_lowercase().contains("permission"),+ "{err}"+ );+ std::fs::set_permissions(&out, std::fs::Permissions::from_mode(0o755)).unwrap();+ run().await.unwrap();+ assert_eq!(std::fs::read(out.join("a.txt")).unwrap(), b"A");+}++/// `drop_state` removes exactly what the app declared: its files and declared+/// directories (with what is under them, as in Python), not the user's files+/// next to them.+#[tokio::test]+async fn drop_state_removes_exactly_the_declared_entries() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("lmdb");+ let out = dir.path().join("out");+ std::fs::create_dir_all(&out).unwrap();+ std::fs::write(out.join("user.txt"), b"mine").unwrap();+ let app = App::builder("fs_drop").db_path(&db).build().await.unwrap();+ let o = out.clone();+ app.update(move |ctx| async move {+ let t = DirTarget::mount(&ctx, &o)?;+ t.declare_file(&ctx, "a.txt", b"A")?;+ t.declare_dir_target(&ctx, "sub", false)?+ .declare_file(&ctx, "b.txt", b"B")+ })+ .await+ .unwrap();+ app.drop_state().await.unwrap();+ let mut left: Vec<String> = std::fs::read_dir(&out)+ .unwrap()+ .map(|e| e.unwrap().file_name().into_string().unwrap())+ .collect();+ left.sort();+ assert_eq!(left, ["user.txt"]);+}++/// A file someone else changed or removed between runs is rewritten only when+/// its declared content changes (the target tracks what it wrote, not what is+/// on disk), as in Python.+#[tokio::test]+async fn a_file_changed_by_someone_else_is_rewritten_when_its_content_changes() {+ let dir = tempfile::tempdir().unwrap();+ let db = dir.path().join("lmdb");+ let out = dir.path().join("out");+ let run = |content: &'static [u8]| {+ let o = out.clone();+ let db = db.clone();+ async move {+ update_once(&db, "fs_external", move |ctx| async move {+ DirTarget::mount(&ctx, &o)?.declare_file(&ctx, "a.txt", content)+ })+ .await+ .unwrap()+ }+ };+ run(b"v1").await;+ std::fs::remove_file(out.join("a.txt")).unwrap();+ run(b"v1").await;+ assert!(+ !out.join("a.txt").exists(),+ "unchanged content: not rewritten"+ );+ run(b"v2").await;+ assert_eq!(std::fs::read(out.join("a.txt")).unwrap(), b"v2");+}diff --git a/rust/sdk/cocoindex/tests/preview.rs b/rust/sdk/cocoindex/tests/preview.rsindex b4cbd380..33770b02 100644--- a/rust/sdk/cocoindex/tests/preview.rs+++ b/rust/sdk/cocoindex/tests/preview.rs@@ -506,10 +506,14 @@ enum FileOp {content: Vec<u8>,#[allow(dead_code)]create_parent_dirs: bool,+ #[allow(dead_code)]+ replaces_dir: bool,},CreateDir {#[allow(dead_code)]create_parent_dirs: bool,+ #[allow(dead_code)]+ replaces_file: bool,},RemoveFile,RemoveDir,diff --git a/rust/sdk/cocoindex/tests/snowflake_target.rs b/rust/sdk/cocoindex/tests/snowflake_target.rsindex 723108bd..7f53984a 100644--- a/rust/sdk/cocoindex/tests/snowflake_target.rs+++ b/rust/sdk/cocoindex/tests/snowflake_target.rs@@ -584,3 +584,72 @@ async fn snowflake_live_upsert_and_delete() -> Result<()> {.await;result}++/// Rows per `MERGE` (bindings / 3 columns) of every `MERGE` the server got.+async fn merge_row_counts(server: &MockServer) -> Vec<usize> {+ received_statements(server)+ .await+ .iter()+ .filter(|(sql, _)| sql.starts_with("MERGE"))+ .map(|(_, bindings)| bindings.as_object().map_or(0, |b| b.len()) / 3)+ .collect()+}++/// Rows go in `MERGE` statements of at most 4,000 bindings: 1,333 rows of 3+/// columns per statement. A statement the server rejects mid-batch fails the+/// run, and the next run sends every row again, so nothing is lost.+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]+async fn snowflake_batches_follow_the_binding_limit_and_a_failure_is_retried() -> Result<()> {+ let items = |n: i64| -> Vec<Item> { (0..n).map(|id| item(id, "x", &[])).collect() };+ for (n, expected) in [(1, vec![1]), (1333, vec![1333]), (1334, vec![1333, 1])] {+ let Some(server) = snowflake_server().await else {+ return Ok(());+ };+ let tmp = tempfile::tempdir().unwrap();+ declare(+ &connection(&server),+ &tmp.path().join("db"),+ items(n),+ options(),+ )+ .await?;+ let mut counts = merge_row_counts(&server).await;+ counts.sort_unstable_by(|a, b| b.cmp(a));+ assert_eq!(counts, expected, "{n} rows");+ }++ let Some(server) = mock_server().await else {+ return Ok(());+ };+ // The first MERGE fails; everything else succeeds.+ Mock::given(method("POST"))+ .and(path("/queries/v1/query-request"))+ .and(wiremock::matchers::body_string_contains("MERGE"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "success": false,+ "message": "boom",+ "code": "100038",+ "data": null,+ })))+ .up_to_n_times(1)+ .with_priority(1)+ .mount(&server)+ .await;+ mount_snowflake(&server).await;+ let conn = connection(&server);+ let tmp = tempfile::tempdir().unwrap();+ let db = tmp.path().join("db");+ let err = declare(&conn, &db, items(3000), options())+ .await+ .unwrap_err();+ assert!(err.to_string().contains("boom"), "{err}");+ server.reset().await;+ mount_snowflake(&server).await;+ declare(&conn, &db, items(3000), options()).await?;+ let sent: usize = merge_row_counts(&server).await.iter().sum();+ assert_eq!(+ sent, 3000,+ "the next run sends every row of the failed batch"+ );+ Ok(())+}diff --git a/rust/sdk/cocoindex/tests/sqlite_target_edge.rs b/rust/sdk/cocoindex/tests/sqlite_target_edge.rsnew file mode 100644index 00000000..55d237c4--- /dev/null+++ b/rust/sdk/cocoindex/tests/sqlite_target_edge.rs@@ -0,0 +1,590 @@+//! Edge cases of the SQLite table target: schema evolution, identifiers, value+//! edge cases, batch boundaries, atomic batches, a locked database, tables+//! changed by someone else, `drop_state`, and `vec0` tables when the+//! `sqlite-vec` library is available (`SQLITE_VEC_EXTENSION`).+#![cfg(feature = "sqlite")]++use cocoindex::connectors::sqlite;+use cocoindex::{App, Environment, Result};+use serde_json::{Value, json};+use sqlx::Row as _;++cocoindex::context_key!(+ static DB: sqlite::Database, key = "sqlite_target_edge_test_db"+);++mod common;++async fn temp_db() -> (sqlite::Database, tempfile::TempDir) {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("target.db");+ let db = sqlite::Database::connect(path.to_str().unwrap())+ .await+ .unwrap();+ (db, dir)+}++async fn build_app(db: &sqlite::Database) -> (App, tempfile::TempDir) {+ common::record_sql_statements();+ let dir = tempfile::tempdir().unwrap();+ let app = Environment::builder()+ .db_path(dir.path().join(".cocoindex_db"))+ .provide_key(&DB, db.clone())+ .build()+ .await+ .unwrap()+ .app("SqliteEdgeTest")+ .await+ .unwrap();+ (app, dir)+}++/// A column list, each `(name, type, nullable)`.+type Cols = Vec<(&'static str, &'static str, bool)>;++fn schema_of(cols: &Cols, pk: &[&str]) -> Result<sqlite::TableSchema> {+ sqlite::TableSchema::new(+ cols.iter().map(|(name, ty, nullable)| {+ let def = sqlite::ColumnDef::new(*ty);+ (*name, if *nullable { def } else { def.not_null() })+ }),+ pk.iter().copied(),+ )+}++async fn run_rows_with(+ app: &App,+ table: &'static str,+ cols: Cols,+ pk: &'static [&'static str],+ options: sqlite::SqliteTableOptions,+ rows: Vec<Value>,+) -> Result<()> {+ app.run(move |ctx| async move {+ let target = sqlite::mount_table_target_with_options(+ &ctx,+ &DB,+ table,+ schema_of(&cols, pk)?,+ options,+ )+ .await?;+ for row in &rows {+ target.declare_row(&ctx, row)?;+ }+ Ok(())+ })+ .await?;+ Ok(())+}++async fn run_rows(+ app: &App,+ table: &'static str,+ cols: Cols,+ pk: &'static [&'static str],+ rows: Vec<Value>,+) -> Result<()> {+ run_rows_with(app, table, cols, pk, Default::default(), rows).await+}++/// Every row of `table` as a JSON object, ordered by `order_by`.+async fn rows_json(db: &sqlite::Database, table: &str, order_by: &str) -> Vec<Value> {+ let rows = sqlx::query(&format!("SELECT * FROM {table} ORDER BY {order_by}"))+ .fetch_all(db.pool())+ .await+ .unwrap();+ rows.iter()+ .map(|row| {+ use sqlx::{Column as _, TypeInfo as _, ValueRef as _};+ let mut map = serde_json::Map::new();+ for (i, col) in row.columns().iter().enumerate() {+ let raw = row.try_get_raw(i).unwrap();+ let value = if raw.is_null() {+ Value::Null+ } else {+ match raw.type_info().name() {+ "INTEGER" => json!(row.get::<i64, _>(i)),+ "REAL" => json!(row.get::<f64, _>(i)),+ "BLOB" => json!(row.get::<Vec<u8>, _>(i)),+ _ => json!(row.get::<String, _>(i)),+ }+ };+ map.insert(col.name().to_string(), value);+ }+ Value::Object(map)+ })+ .collect()+}++async fn count(db: &sqlite::Database, table: &str) -> i64 {+ sqlx::query_scalar(&format!("SELECT count(*) FROM {table}"))+ .fetch_one(db.pool())+ .await+ .unwrap()+}++/// Making a column required and back keeps the rows: SQLite has no `ALTER+/// COLUMN`, so the column is dropped and added again and the rows rewritten,+/// as in Python.+#[tokio::test]+async fn nullable_column_becomes_required_and_back() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ let nullable: Cols = vec![("id", "INTEGER", false), ("note", "TEXT", true)];+ let required: Cols = vec![("id", "INTEGER", false), ("note", "TEXT", false)];+ let rows = vec![json!({"id": 1, "note": "a"})];+ run_rows(&app, "t", nullable.clone(), &["id"], rows.clone())+ .await+ .unwrap();+ run_rows(&app, "t", required, &["id"], rows).await.unwrap();+ assert_eq!(+ rows_json(&db, "t", "id").await,+ vec![json!({"id": 1, "note": "a"})]+ );+ run_rows(+ &app,+ "t",+ nullable,+ &["id"],+ vec![+ json!({"id": 1, "note": "a"}),+ json!({"id": 2, "note": null}),+ ],+ )+ .await+ .unwrap();+ assert_eq!(+ rows_json(&db, "t", "id").await,+ vec![+ json!({"id": 1, "note": "a"}),+ json!({"id": 2, "note": null})+ ]+ );+}++/// A renamed column is dropped and the new one added and filled.+#[tokio::test]+async fn renamed_and_retyped_columns_are_repopulated() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ run_rows(+ &app,+ "t",+ vec![+ ("id", "INTEGER", false),+ ("a", "TEXT", true),+ ("n", "INTEGER", true),+ ],+ &["id"],+ vec![json!({"id": 1, "a": "v", "n": 5})],+ )+ .await+ .unwrap();+ run_rows(+ &app,+ "t",+ vec![+ ("id", "INTEGER", false),+ ("b", "TEXT", true),+ ("n", "REAL", true),+ ],+ &["id"],+ vec![json!({"id": 1, "b": "v", "n": 5.5})],+ )+ .await+ .unwrap();+ assert_eq!(+ rows_json(&db, "t", "id").await,+ vec![json!({"id": 1, "b": "v", "n": 5.5})]+ );+}++/// A primary-key change rebuilds the table with the rows rewritten.+#[tokio::test]+async fn primary_key_change_rebuilds_the_table() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ let cols: Cols = vec![+ ("a", "TEXT", false),+ ("b", "INTEGER", false),+ ("v", "TEXT", true),+ ];+ let rows = vec![+ json!({"a": "x", "b": 1, "v": "one"}),+ json!({"a": "x", "b": 2, "v": "two"}),+ ];+ run_rows(&app, "t", cols.clone(), &["a"], vec![rows[0].clone()])+ .await+ .unwrap();+ run_rows(&app, "t", cols, &["a", "b"], rows.clone())+ .await+ .unwrap();+ assert_eq!(rows_json(&db, "t", "a, b").await, rows);+}++/// Reserved words and mixed case are quoted in DDL and DML.+#[tokio::test]+async fn reserved_and_mixed_case_identifiers() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ let cols: Cols = vec![+ ("select", "INTEGER", false),+ ("Order", "TEXT", false),+ ("group", "TEXT", true),+ ];+ run_rows(+ &app,+ "Table",+ cols.clone(),+ &["select", "Order"],+ vec![+ json!({"select": 1, "Order": "x", "group": "g"}),+ json!({"select": 2, "Order": "y"}),+ ],+ )+ .await+ .unwrap();+ run_rows(+ &app,+ "Table",+ cols,+ &["select", "Order"],+ vec![json!({"select": 2, "Order": "y", "group": "h"})],+ )+ .await+ .unwrap();+ assert_eq!(+ rows_json(&db, "\"Table\"", "\"select\"").await,+ vec![json!({"select": 2, "Order": "y", "group": "h"})]+ );+ for bad in ["", "a\"b", "a b", "1x", "名前", "a;b"] {+ assert!(+ schema_of(&vec![(bad, "TEXT", false)], &[bad]).is_err(),+ "{bad:?}"+ );+ }+}++#[tokio::test]+async fn edge_values_round_trip() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ let cols: Cols = vec![+ ("id", "INTEGER", false),+ ("t", "TEXT", true),+ ("i", "INTEGER", true),+ ("f", "REAL", true),+ ("b", "BLOB", true),+ ("j", "JSON", true),+ ];+ let huge = "y".repeat(4 * 1024 * 1024);+ let rows = vec![+ json!({"id": 1, "t": "", "i": i64::MAX, "f": -0.0, "b": [], "j": {"a": [1, {"b": null}]}}),+ json!({"id": 2, "t": "nul\u{0}inside ünïcödé 🎉", "i": i64::MIN, "f": 1e308, "b": [0, 255]}),+ json!({"id": 3, "t": huge.clone(), "b": vec![9u8; 1 << 20]}),+ ];+ run_rows(&app, "t", cols.clone(), &["id"], rows)+ .await+ .unwrap();+ let got = rows_json(&db, "t", "id").await;+ assert_eq!(got[0]["t"], json!(""));+ assert_eq!(got[0]["i"], json!(i64::MAX));+ assert_eq!(got[0]["b"], json!([]));+ assert_eq!(got[0]["j"], json!("{\"a\":[1,{\"b\":null}]}"));+ assert_eq!(got[1]["t"], json!("nul\u{0}inside ünïcödé 🎉"));+ assert_eq!(got[1]["i"], json!(i64::MIN));+ assert_eq!(got[2]["t"].as_str().map(str::len), Some(huge.len()));+ assert_eq!(got[2]["b"].as_array().map(Vec::len), Some(1 << 20));++ for (row, expected) in [+ (json!({"id": 4, "i": u64::MAX}), "integer column"),+ (json!({"id": 4, "i": 1.5}), "integer column"),+ (json!({"id": 4, "f": "x"}), "real column"),+ (json!({"id": 4, "b": [256]}), "BLOB array"),+ (json!({"id": null}), "null"),+ ] {+ let err = run_rows(&app, "t", cols.clone(), &["id"], vec![row.clone()])+ .await+ .unwrap_err();+ assert!(err.to_string().contains(expected), "{row}: {err}");+ }+}++#[derive(serde::Serialize)]+struct FloatRow {+ id: i64,+ f: f64,+}++#[tokio::test]+async fn non_finite_floats_are_rejected() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {+ let err = app+ .run(move |ctx| async move {+ let cols: Cols = vec![("id", "INTEGER", false), ("f", "REAL", true)];+ let t =+ sqlite::mount_table_target(&ctx, &DB, "t", schema_of(&cols, &["id"])?).await?;+ t.declare_row(&ctx, &FloatRow { id: 1, f: value })+ })+ .await+ .unwrap_err();+ assert!(err.to_string().contains("non-finite"), "{err}");+ }+}++/// A two-column table fits 16,383 rows in one statement (the 32,766-parameter+/// bind limit): 16,383 rows → 1 statement, 16,384 → 2.+#[tokio::test]+async fn batch_boundaries_follow_the_bind_limit() {+ let cols: Cols = vec![("id", "INTEGER", false), ("v", "TEXT", true)];+ for (n, statements) in [(1usize, 1usize), (16_383, 1), (16_384, 2)] {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ let table: &'static str = Box::leak(format!("b{n}").into_boxed_str());+ let rows = (0..n as i64)+ .map(|id| json!({"id": id, "v": "x"}))+ .collect();+ run_rows(&app, table, cols.clone(), &["id"], rows)+ .await+ .unwrap();+ assert_eq!(count(&db, table).await, n as i64);+ let inserts = common::sql_statements_containing(&format!("INSERT INTO \"{table}\" "));+ assert_eq!(inserts.len(), statements, "{n} rows");+ }+}++/// A batch is one transaction: a row the database rejects (here a CHECK+/// constraint on a user-managed table) rolls back the whole batch, and the+/// next run with the row fixed writes all of them.+#[tokio::test]+async fn a_batch_is_atomic_and_the_next_run_repairs() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ sqlx::query("CREATE TABLE t (id INTEGER PRIMARY KEY NOT NULL, v INTEGER CHECK (v < 1000))")+ .execute(db.pool())+ .await+ .unwrap();+ let cols: Cols = vec![("id", "INTEGER", false), ("v", "INTEGER", true)];+ let user = || sqlite::SqliteTableOptions {+ managed_by: cocoindex::ManagedBy::User,+ ..Default::default()+ };+ let rows = |bad: bool| -> Vec<Value> {+ (0..40_000)+ .map(|id| json!({"id": id, "v": if bad && id == 39_999 { 5000 } else { id % 1000 }}))+ .collect()+ };+ let err = run_rows_with(&app, "t", cols.clone(), &["id"], user(), rows(true))+ .await+ .unwrap_err();+ assert!(err.to_string().contains("CHECK"), "{err}");+ assert_eq!(count(&db, "t").await, 0, "the failed batch is rolled back");+ run_rows_with(&app, "t", cols, &["id"], user(), rows(false))+ .await+ .unwrap();+ assert_eq!(count(&db, "t").await, 40_000);+}++/// Another connection holding the write lock past the busy timeout fails the+/// run; once it lets go, the next run applies the change.+#[tokio::test]+async fn a_locked_database_fails_the_run_and_the_next_run_repairs() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("locked.db");+ let db = sqlite::Database::connect_with_options(+ path.to_str().unwrap(),+ sqlite::ConnectOptions {+ busy_timeout: std::time::Duration::from_millis(200),+ vec_extension: None,+ },+ )+ .await+ .unwrap();+ let (app, _a) = build_app(&db).await;+ let cols: Cols = vec![("id", "INTEGER", false), ("v", "TEXT", true)];+ run_rows(+ &app,+ "t",+ cols.clone(),+ &["id"],+ vec![json!({"id": 1, "v": "a"})],+ )+ .await+ .unwrap();++ let other = sqlite::Database::connect(path.to_str().unwrap())+ .await+ .unwrap();+ let mut conn = other.pool().acquire().await.unwrap();+ sqlx::query("BEGIN IMMEDIATE")+ .execute(&mut *conn)+ .await+ .unwrap();+ let err = run_rows(+ &app,+ "t",+ cols.clone(),+ &["id"],+ vec![json!({"id": 1, "v": "b"})],+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("locked"), "{err}");+ sqlx::query("ROLLBACK").execute(&mut *conn).await.unwrap();+ drop(conn);++ run_rows(&app, "t", cols, &["id"], vec![json!({"id": 1, "v": "b"})])+ .await+ .unwrap();+ assert_eq!(+ rows_json(&db, "t", "id").await,+ vec![json!({"id": 1, "v": "b"})]+ );+}++/// A table someone else dropped between runs is created again (empty but for+/// the rows that changed), as in Python; a column someone else dropped is not+/// noticed until the schema changes (the target tracks the schema it applied).+#[tokio::test]+async fn a_table_dropped_by_someone_else_is_created_again() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ let cols: Cols = vec![("id", "INTEGER", false), ("v", "TEXT", true)];+ run_rows(+ &app,+ "t",+ cols.clone(),+ &["id"],+ vec![json!({"id": 1, "v": "a"})],+ )+ .await+ .unwrap();+ sqlx::query("DROP TABLE t")+ .execute(db.pool())+ .await+ .unwrap();+ run_rows(+ &app,+ "t",+ cols,+ &["id"],+ vec![json!({"id": 1, "v": "a"}), json!({"id": 2, "v": "b"})],+ )+ .await+ .unwrap();+ assert_eq!(+ rows_json(&db, "t", "id").await,+ vec![json!({"id": 2, "v": "b"})]+ );+}++/// Declaring one primary key twice in a component fails the run.+#[tokio::test]+async fn duplicate_primary_key_in_one_run() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ let err = run_rows(+ &app,+ "t",+ vec![("id", "INTEGER", false), ("v", "TEXT", true)],+ &["id"],+ vec![json!({"id": 1, "v": "a"}), json!({"id": 1, "v": "b"})],+ )+ .await+ .unwrap_err();+ assert!(err.to_string().contains("already declared"), "{err}");+}++/// `drop_state` drops the tables the app created and nothing else.+#[tokio::test]+async fn drop_state_removes_exactly_what_the_app_created() {+ let (db, _d) = temp_db().await;+ let (app, _a) = build_app(&db).await;+ sqlx::query("CREATE TABLE other (id INTEGER)")+ .execute(db.pool())+ .await+ .unwrap();+ let cols: Cols = vec![("id", "INTEGER", false)];+ app.run(move |ctx| async move {+ for name in ["a", "b"] {+ let t = sqlite::mount_table_target(&ctx, &DB, name, schema_of(&cols, &["id"])?).await?;+ t.declare_row(&ctx, &json!({"id": 1}))?;+ }+ Ok(())+ })+ .await+ .unwrap();+ app.drop_state().await.unwrap();+ let tables: Vec<String> =+ sqlx::query_scalar("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name")+ .fetch_all(db.pool())+ .await+ .unwrap();+ assert_eq!(tables, ["other"]);+}++/// With `sqlite-vec`: a vector dimension change rebuilds the `vec0` table+/// with the new vectors, and a vector of the wrong length fails the run.+#[tokio::test]+async fn vec0_dimension_change_and_wrong_length() {+ let Ok(extension) = std::env::var("SQLITE_VEC_EXTENSION") else {+ eprintln!("skipping sqlite-vec test; SQLITE_VEC_EXTENSION is not set");+ return;+ };+ let dir = tempfile::tempdir().unwrap();+ let db =+ sqlite::Database::connect_with_vec(dir.path().join("v.db").to_str().unwrap(), &extension)+ .await+ .unwrap();+ let (app, _a) = build_app(&db).await;+ let vec0 = || sqlite::SqliteTableOptions {+ virtual_table_def: Some(sqlite::Vec0TableDef::default()),+ ..Default::default()+ };+ run_rows_with(+ &app,+ "v",+ vec![("id", "INTEGER", false), ("e", "float[3]", false)],+ &["id"],+ vec0(),+ vec![json!({"id": 1, "e": [1.0, 0.0, 0.0]})],+ )+ .await+ .unwrap();+ run_rows_with(+ &app,+ "v",+ vec![("id", "INTEGER", false), ("e", "float[4]", false)],+ &["id"],+ vec0(),+ vec![+ json!({"id": 1, "e": [1.0, 0.0, 0.0, 0.0]}),+ json!({"id": 2, "e": [0.0, 1.0, 0.0, 0.0]}),+ ],+ )+ .await+ .unwrap();+ let nearest: Vec<i64> =+ sqlx::query_scalar("SELECT id FROM v WHERE e MATCH '[0, 0.9, 0.1, 0]' AND k = 1")+ .fetch_all(db.pool())+ .await+ .unwrap();+ assert_eq!(nearest, vec![2]);+ let err = run_rows_with(+ &app,+ "v",+ vec![("id", "INTEGER", false), ("e", "float[4]", false)],+ &["id"],+ vec0(),+ vec![json!({"id": 3, "e": [1.0, 2.0]})],+ )+ .await+ .unwrap_err();+ assert!(+ err.to_string().to_lowercase().contains("dimension"),+ "{err}"+ );+}