From b6b767027a49c6b32db5be22279bb476ad927347 Mon Sep 17 00:00:00 2001 From: Rainer M Krug Date: Tue, 27 Oct 2026 16:43:11 +0100 Subject: [PATCH 1/6] chore: development version 0.3.4.9000 Co-Authored-By: Claude Opus 5.5 --- DESCRIPTION | 2 +- NEWS.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 60352c3..f229702 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Package: openalexVectorComp Type: Package Title: Embedding Vectorization and Distance-Based Scoring Workflows -Version: 0.3.4 +Version: 0.3.4.9000 Authors@R: c( person(given = "Rainer M", family = "Krug", role = c("aut", "cre"), email = "Rainer@krugs.de"), person(given = "ChatGPT", family = "Assistant", role = "ctb") diff --git a/NEWS.md b/NEWS.md index caf9728..50bbb57 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # openalexVectorComp news +## development version + ## 0.3.4 ### Bug Fixes From 2f289a3f18aacc09b48095b089e5fac321a45fa3 Mon Sep 17 00:00:00 2001 From: Rainer M Krug Date: Tue, 27 Oct 2026 17:01:28 +0100 Subject: [PATCH 2/6] docs: README with live version badges, current install instructions The README hard-coded "Current development version: 0.3.0" and the 0.3.0 highlights, and installed from a local zip. It now shows live badges (r-universe, main, dev, CI, coverage) grouped like the org README, points to NEWS.md for changes, and installs from r-universe or GitHub dev. CLAUDE.md: CI matrix and triggers as they are now. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- README.md | 44 +++++++++++++++++++++----------------------- 2 files changed, 22 insertions(+), 24 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 2ce5ffd..77f78d4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,7 +33,7 @@ devtools::check(args = c("--no-manual", "--no-multiarch", "--no-examples", "--ig pkgdown::build_site() ``` -CI (`.github/workflows/pr-checks.yml`) runs `R CMD check` across Ubuntu (release/oldrel-1/devel), macOS, and Windows, **skipping vignette execution and examples**. Match this locally before committing. +CI (`.github/workflows/pr-checks.yml`) runs `R CMD check` on pushes to `main` and `dev` and on pull requests into `main`, across Ubuntu (release/oldrel-1), macOS and Windows (release), **skipping vignette execution and examples**. Match this locally before committing. ## Architecture diff --git a/README.md b/README.md index ce45894..42df7c5 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,12 @@ -[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.19607514.svg)](https://doi.org/10.5281/zenodo.19607514) -[![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://lifecycle.r-lib.org/articles/stages.html) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -[![Codecov](https://codecov.io/gh/openalexPro/openalexVectorComp/graph/badge.svg)](https://app.codecov.io/gh/openalexPro/openalexVectorComp) +[![r-universe](https://openalexpro.r-universe.dev/openalexVectorComp/badges/version)](https://openalexpro.r-universe.dev/openalexVectorComp) [![main](https://img.shields.io/github/r-package/v/openalexPro/openalexVectorComp/main?label=main)](https://github.com/openalexPro/openalexVectorComp/tree/main) [![CI main](https://img.shields.io/github/actions/workflow/status/openalexPro/openalexVectorComp/pr-checks.yml?branch=main&label=CI%20main)](https://github.com/openalexPro/openalexVectorComp/actions/workflows/pr-checks.yml?query=branch%3Amain) [![Codecov](https://codecov.io/gh/openalexPro/openalexVectorComp/graph/badge.svg)](https://app.codecov.io/gh/openalexPro/openalexVectorComp) -# openalexVectorComp +[![dev](https://img.shields.io/github/r-package/v/openalexPro/openalexVectorComp/dev?label=dev)](https://github.com/openalexPro/openalexVectorComp/tree/dev) [![CI dev](https://img.shields.io/github/actions/workflow/status/openalexPro/openalexVectorComp/pr-checks.yml?branch=dev&label=CI%20dev)](https://github.com/openalexPro/openalexVectorComp/actions/workflows/pr-checks.yml?query=branch%3Adev) -**Embedding of Corpora**, implemented in R. +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.19607514.svg)](https://doi.org/10.5281/zenodo.19607514) [![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://lifecycle.r-lib.org/articles/stages.html) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) -## Version +# openalexVectorComp -Current development version: **0.3.0**. +**Embedding of Corpora**, implemented in R. - Embeddings served by **TEI** (Text Embeddings Inference; Hugging Face). - Embeddings via a **backend-neutral interface** (`hf`, `openai`, `tei`). @@ -17,17 +14,9 @@ Current development version: **0.3.0**. (`distance_ridge()` + `score_ridge()`) + threshold calibration. - Works great with DuckDB/Arrow pipelines. -## 0.3.0 Highlights - -- Demo defaults now use a shared structure: - - `demos/openalex` - - `demos/openai` -- OpenAI demo uses an explicit two-phase async workflow: - - render now (submit/poll briefly), - - finalize later (status/collect/compare) if batch is still pending. -- Added tutorial-style demo narratives with clearer explanation of workflow - choices, costs/latency trade-offs, and interpretation of direct-vs-batch - embedding differences. +The badges show the released version (r-universe, built from `main`) and the +development version (`dev`); what changed in each release is in +[NEWS.md](NEWS.md). ## Development Continuity @@ -35,14 +24,23 @@ See `DEVELOPMENT_CONTINUITY.md` for design principles, architectural decisions, and the required pre-commit update checklist that keeps development context continuous for both humans and AI agents. -## Install (local) +## Installation + +Released version, from the openalexPro r-universe: ```r -# install.packages("devtools") -devtools::install_local("openalexVectorComp") +install.packages( + "openalexVectorComp", + repos = c("https://openalexpro.r-universe.dev", "https://cloud.r-project.org") +) ``` -Or build & install from the zip you downloaded. +Development version (the `dev` branch), from GitHub: + +```r +# install.packages("remotes") +remotes::install_github("openalexPro/openalexVectorComp", ref = "dev") +``` ## Runtime dependencies From bd2f24a10927d71125eb045608e85f33661cc237 Mon Sep 17 00:00:00 2001 From: Rainer M Krug Date: Tue, 27 Oct 2026 18:28:04 +0100 Subject: [PATCH 3/6] test: raise offline test coverage to ~98.8% Add offline tests (httr2 mocked responses, mocked bindings, tempdir fixtures) for the OpenAI Batch HTTP layer, batch state/status/collect/ submit helpers, HF/OpenAI/TEI backend adapters, embed_corpus verbose and dry-run paths, distance/score/calibration edge cases and the demo runners. No changes under R/. Two tests are skipped as known bugs: existing-hash loading in embed_corpus() and .ovc_load_existing_hash() passes the label partition as open_dataset()'s `schema`, so unchanged rows are never skipped. Co-Authored-By: Claude Opus 5.5 --- tests/testthat/helper-offline.R | 19 + tests/testthat/test-backend-adapters.R | 263 +++++++++ .../test-clean-abstract-for-embedding.R | 8 + tests/testthat/test-demo-openai-finalize.R | 106 ++++ tests/testthat/test-demo-runner.R | 115 ++++ tests/testthat/test-distance-functions.R | 336 ++++++++++++ tests/testthat/test-embedding-offline.R | 166 ++++++ tests/testthat/test-openai-batch-http.R | 197 +++++++ tests/testthat/test-openai-batch.R | 512 ++++++++++++++++++ tests/testthat/test-plot-embeddings.R | 11 + 10 files changed, 1733 insertions(+) create mode 100644 tests/testthat/helper-offline.R create mode 100644 tests/testthat/test-backend-adapters.R create mode 100644 tests/testthat/test-openai-batch-http.R diff --git a/tests/testthat/helper-offline.R b/tests/testthat/helper-offline.R new file mode 100644 index 0000000..1293948 --- /dev/null +++ b/tests/testthat/helper-offline.R @@ -0,0 +1,19 @@ +# Offline test helpers: no network, no keyring. + +# Set (or unset, with `value = NA`) OVC_API_TOKEN for the calling test only. +ovc_local_token <- function(value = "test-token", env = parent.frame()) { + old <- Sys.getenv("OVC_API_TOKEN", unset = NA) + if (is.na(value)) { + Sys.unsetenv("OVC_API_TOKEN") + } else { + Sys.setenv(OVC_API_TOKEN = value) + } + restore <- substitute( + if (is.na(OLD)) Sys.unsetenv("OVC_API_TOKEN") else Sys.setenv(OVC_API_TOKEN = OLD), + list(OLD = old) + ) + do.call(base::on.exit, list(restore, add = TRUE), envir = env) + invisible(value) +} + +ovc_ns <- function(name) getFromNamespace(name, "openalexVectorComp") diff --git a/tests/testthat/test-backend-adapters.R b/tests/testthat/test-backend-adapters.R new file mode 100644 index 0000000..f855f6e --- /dev/null +++ b/tests/testthat/test-backend-adapters.R @@ -0,0 +1,263 @@ +# Offline tests for backend adapters: HTTP is mocked with httr2. + +testthat::test_that("backend_specter2_tei builds a TEI backend and validates inputs", { + b <- backend_specter2_tei() + testthat::expect_identical(b$provider, "tei") + testthat::expect_identical(b$embed_url, "http://localhost:8080/embed") + testthat::expect_identical(b$base_url, "http://localhost:8080/embed") + testthat::expect_identical(b$model, "allenai/specter2_proximity_merged") + + b2 <- backend_specter2_tei(port = 9001, host = "gpu-box", model = "m") + testthat::expect_identical(b2$embed_url, "http://gpu-box:9001/embed") + testthat::expect_identical(b2$model, "m") + + testthat::expect_error(backend_specter2_tei(port = 0), "`port` must be a positive integer") + testthat::expect_error( + suppressWarnings(backend_specter2_tei(port = "x")), + "`port` must be a positive integer" + ) + testthat::expect_error(backend_specter2_tei(host = ""), "`host` must be a non-empty string") + testthat::expect_error(backend_specter2_tei(host = c("a", "b")), "`host` must be a non-empty string") +}) + +testthat::test_that("backend_read handles flat embed_url, invalid and unknown YAML", { + fn <- tempfile(fileext = ".yaml") + yaml::write_yaml( + list( + provider = "tei", + base_url = "http://localhost:3000", + model = "m", + embed_url = "http://tei.local:8080/embed/" + ), + fn + ) + cfg <- backend_read(fn) + testthat::expect_identical(cfg$embed_url, "http://tei.local:8080/embed") + testthat::expect_identical(cfg$base_url, "http://tei.local:8080/embed") + + fn_hf <- tempfile(fileext = ".yaml") + yaml::write_yaml( + list(provider = "hf", embed_url = "https://example.test/custom/"), + fn_hf + ) + cfg_hf <- backend_read(fn_hf) + testthat::expect_identical(cfg_hf$embed_url, "https://example.test/custom") + # Non-TEI providers keep their base_url. + testthat::expect_identical(cfg_hf$base_url, "https://router.huggingface.co/hf-inference") + + fn_scalar <- tempfile(fileext = ".yaml") + writeLines("just a string", fn_scalar) + testthat::expect_error(backend_read(fn_scalar), "does not contain a valid YAML object") + + fn_unknown <- tempfile(fileext = ".yaml") + yaml::write_yaml(list(something = "else"), fn_unknown) + testthat::expect_error(backend_read(fn_unknown), "recognized backend configuration format") +}) + +testthat::test_that("backend_save and backend_embed_texts validate backend objects", { + testthat::expect_error( + backend_save(backend = list(), fn = tempfile()), + "`backend` must be a configuration object" + ) + testthat::expect_error( + backend_embed_texts(texts = "a", backend = list()), + "`backend` must be a configuration object" + ) +}) + +testthat::test_that(".embedding_request_base adds bearer token only when set", { + req_base <- ovc_ns(".embedding_request_base") + + ovc_local_token(NA) + req <- req_base("https://example.test/embed", list()) + testthat::expect_identical(httr2::req_get_method(req), "POST") + testthat::expect_null(httr2::req_get_headers(req, "reveal")$Authorization) + + ovc_local_token("tok-1") + req2 <- req_base("https://example.test/embed", list()) + testthat::expect_identical( + httr2::req_get_headers(req2, "reveal")$Authorization, + "Bearer tok-1" + ) +}) + +testthat::test_that(".embedding_as_matrix passes matrices and converts data frames", { + as_matrix <- ovc_ns(".embedding_as_matrix") + m <- matrix(1:4, nrow = 2) + testthat::expect_identical(as_matrix(m), m) + df <- data.frame(a = c(1, 2), b = c(3, 4)) + testthat::expect_equal(unname(as_matrix(df)), matrix(c(1, 2, 3, 4), nrow = 2)) +}) + +testthat::test_that("HF backend posts batched inputs and builds the embedding matrix", { + ovc_local_token("hf-tok") + calls <- list() + httr2::local_mocked_responses(function(req) { + body <- httr2::req_get_body(req) + calls[[length(calls) + 1L]] <<- list( + url = httr2::req_get_url(req), + auth = httr2::req_get_headers(req, "reveal")$Authorization, + inputs = unlist(body$inputs) + ) + n <- length(body$inputs) + httr2::response_json(body = lapply(seq_len(n), function(i) c(i, 10 * i))) + }) + + backend <- backend_config(provider = "hf", max_batch_size = 2, retries = 0) + out <- backend_embed_texts(c("a", "b", "c"), backend) + + testthat::expect_equal(dim(out), c(3L, 2L)) + testthat::expect_identical(colnames(out), c("V1", "V2")) + testthat::expect_equal(unname(out[, 1]), c(1, 2, 1)) + testthat::expect_length(calls, 2L) + testthat::expect_identical( + calls[[1]]$url, + "https://router.huggingface.co/hf-inference/models/BAAI/bge-small-en-v1.5" + ) + testthat::expect_identical(calls[[1]]$auth, "Bearer hf-tok") + testthat::expect_identical(calls[[1]]$inputs, c("a", "b")) + testthat::expect_identical(calls[[2]]$inputs, "c") +}) + +testthat::test_that("OpenAI backend posts model and input and parses data", { + ovc_local_token("oa-tok") + seen <- NULL + httr2::local_mocked_responses(function(req) { + seen <<- list(url = httr2::req_get_url(req), body = httr2::req_get_body(req)) + httr2::response_json(body = list( + object = "list", + data = list( + list(index = 0L, embedding = c(0.1, 0.2, 0.3)), + list(index = 1L, embedding = c(0.4, 0.5, 0.6)) + ) + )) + }) + + backend <- backend_config(provider = "openai", model = "text-embedding-3-large", retries = 0) + out <- backend_embed_texts(c("x", "y"), backend) + + testthat::expect_equal(dim(out), c(2L, 3L)) + testthat::expect_equal(unname(out[2, ]), c(0.4, 0.5, 0.6)) + testthat::expect_identical(seen$url, "https://api.openai.com/v1/embeddings") + testthat::expect_identical(seen$body$model, "text-embedding-3-large") + testthat::expect_identical(unlist(seen$body$input), c("x", "y")) +}) + +testthat::test_that("OpenAI adapter handles alternative and malformed `data` shapes", { + oa_fun <- ovc_ns(".embedding_embed_texts_openai") + backend <- list( + provider = "openai", + base_url = "https://api.openai.com/v1", + model = "text-embedding-3-small", + max_batch_size = 4L, + retries = 0L + ) + run_with <- function(res, texts = c("a", "b")) { + testthat::with_mocked_bindings( + oa_fun(texts, backend), + .embedding_with_retry = function(backend, fn) res, + .package = "openalexVectorComp" + ) + } + + # Already-extracted vectors are accepted as-is. + out <- run_with(list(data = list(c(1, 2), c(3, 4)))) + testthat::expect_equal(unname(out), matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)) + + testthat::expect_error( + run_with(list(data = data.frame(index = 0:1, object = "embedding"))), + "did not include `embedding`" + ) + testthat::expect_error( + run_with(list(data = c("not", "numeric"))), + "unsupported shape" + ) + testthat::expect_error( + run_with(list(data = list(list(embedding = c(1, 2)))), texts = c("a", "b")), + "Embedding count mismatch: got 1 vectors for 2 submitted texts" + ) +}) + +testthat::test_that("TEI backend probes /info and embeds via the server embed url", { + calls <- character() + httr2::local_mocked_responses(function(req) { + url <- httr2::req_get_url(req) + calls <<- c(calls, url) + if (grepl("/info$", url)) { + return(httr2::response_json(body = list( + model_id = "BAAI/bge-base", + served_model_name = "bge-served", + embedding_size = 2L, + max_client_batch_size = 2L + ))) + } + n <- length(httr2::req_get_body(req)$inputs) + httr2::response_json(body = lapply(seq_len(n), function(i) c(i, -i))) + }) + + backend <- backend_config(provider = "tei", base_url = "http://tei.test:3000", retries = 0) + info <- backend_info(backend) + testthat::expect_identical(info$provider, "tei") + testthat::expect_identical(info$model_id, "bge-served") + testthat::expect_identical(info$dim, 2L) + testthat::expect_identical(info$max_batch_size, 2L) + testthat::expect_identical(info$raw$model$requested_id, "BAAI/bge-base") + testthat::expect_identical(info$raw$server$embed_url, "http://tei.test:3000/embed") + + calls <- character() + out <- backend_embed_texts(c("a", "b", "c"), backend) + testthat::expect_equal(dim(out), c(3L, 2L)) + testthat::expect_equal(unname(out[, 2]), c(-1, -2, -1)) + testthat::expect_identical( + calls, + c( + "http://tei.test:3000/info", + "http://tei.test:3000/embed", + "http://tei.test:3000/embed" + ) + ) +}) + +testthat::test_that("TEI info falls back to backend metadata when /info is unreachable", { + httr2::local_mocked_responses(function(req) httr2::response(status_code = 503L)) + + with_model <- backend_info( + backend_config(provider = "tei", base_url = "http://tei.test", model = "my-model") + ) + testthat::expect_identical(with_model$model_id, "my-model") + testthat::expect_true(is.na(with_model$dim)) + testthat::expect_identical(with_model$max_batch_size, 128L) + testthat::expect_identical(with_model$raw$embed_url, "http://tei.test/embed") + + no_model <- backend_info(list( + provider = "tei", + base_url = "http://tei.test", + embed_url = "http://tei.test/pipeline/feature-extraction/org/model-x", + model = NULL, + max_batch_size = 16L + )) + testthat::expect_identical(no_model$model_id, "org/model-x") + testthat::expect_identical(no_model$max_batch_size, 16L) +}) + +testthat::test_that("TEI adapter errors on embedding count mismatch", { + tei_fun <- ovc_ns(".embedding_embed_texts_tei") + testthat::expect_error( + testthat::with_mocked_bindings( + tei_fun( + texts = c("a", "b"), + backend = list( + provider = "tei", + base_url = "http://tei.test", + model = "m", + max_batch_size = 4L, + retries = 0L + ) + ), + .embedding_probe_tei = function(embed_url) NULL, + .embedding_with_retry = function(backend, fn) list(c(1, 2)), + .package = "openalexVectorComp" + ), + "Embedding count mismatch: got 1 vectors for 2 submitted texts" + ) +}) diff --git a/tests/testthat/test-clean-abstract-for-embedding.R b/tests/testthat/test-clean-abstract-for-embedding.R index 39bbfb8..c3636b7 100644 --- a/tests/testthat/test-clean-abstract-for-embedding.R +++ b/tests/testthat/test-clean-abstract-for-embedding.R @@ -71,3 +71,11 @@ testthat::test_that("clean_abstract_for_embedding mode thresholds differ", { strict <- clean_abstract_for_embedding(df, mode = "strict", no_abstract_policy = "discard") testthat::expect_gte(nrow(lenient), nrow(strict)) }) + +testthat::test_that("clean_abstract_for_embedding validates its input", { + testthat::expect_error(clean_abstract_for_embedding("x"), "`df` must be a data frame") + testthat::expect_error( + clean_abstract_for_embedding(data.frame(id = "a", title = "t")), + "`df` must contain columns: abstract" + ) +}) diff --git a/tests/testthat/test-demo-openai-finalize.R b/tests/testthat/test-demo-openai-finalize.R index 254b41d..2429051 100644 --- a/tests/testthat/test-demo-openai-finalize.R +++ b/tests/testthat/test-demo-openai-finalize.R @@ -159,3 +159,109 @@ testthat::test_that("demo_finalize_openai_batch accepts api_key argument for tok testthat::expect_match(out$message, "No batch submission state found") testthat::expect_identical(Sys.getenv("OVC_API_TOKEN", unset = ""), "") }) + +testthat::test_that("demo_finalize_openai_batch validates arguments and workspace", { + testthat::expect_error(demo_finalize_openai_batch(demo_dir = ""), "`demo_dir` must be a non-empty") + testthat::expect_error(demo_finalize_openai_batch(demo_dir = "x", label = ""), "`label` must be a non-empty") + testthat::expect_error(demo_finalize_openai_batch(demo_dir = "x", api_key = ""), "`api_key` must be NULL or") + testthat::expect_error(demo_finalize_openai_batch(demo_dir = "x", refresh_remote = NA), "`refresh_remote` must be") + testthat::expect_error(demo_finalize_openai_batch(demo_dir = "x", verbose = "no"), "`verbose` must be") + + td <- tempfile("ovc_finalize_missing_") + dir.create(td) + testthat::expect_error(demo_finalize_openai_batch(td, verbose = FALSE), "Missing backend config") + backend_save(backend_config(provider = "openai"), fn = file.path(td, "demo_backend.yaml")) + testthat::expect_error(demo_finalize_openai_batch(td, verbose = FALSE), "Missing demo project directory") + + demo_dir <- make_demo_openai_workspace() + emb <- file.path(demo_dir, "project", "embeddings") + dir.create(file.path(emb, "model_id=a"), recursive = TRUE) + dir.create(file.path(emb, "model_id=b"), recursive = TRUE) + testthat::expect_error( + demo_finalize_openai_batch(demo_dir, verbose = FALSE), + "Expected exactly one model_id directory" + ) +}) + +testthat::test_that("demo_finalize_openai_batch reports pending batches and restores the token", { + demo_dir <- make_demo_openai_workspace() + project_dir <- file.path(demo_dir, "project") + jsonlite::write_json( + list( + version = 1L, + provider = "openai", + model_id = "text-embedding-3-small", + label = "corpus_batch", + backend = list(base_url = "https://api.openai.test/v1", timeout = 60, retries = 0), + jobs = list() + ), + path = file.path(project_dir, "openai_batch_state_label=corpus_batch.json"), + auto_unbox = TRUE + ) + + ovc_local_token("outer-token") + testthat::expect_message( + out <- demo_finalize_openai_batch(demo_dir, api_key = "inner", verbose = TRUE), + "Batch still pending" + ) + testthat::expect_false(out$comparison_ready) + testthat::expect_identical(out$collect$checked_jobs, 0L) + testthat::expect_identical(Sys.getenv("OVC_API_TOKEN"), "outer-token") +}) + +testthat::test_that("demo_finalize_openai_batch announces a written comparison when verbose", { + demo_dir <- make_demo_openai_workspace() + project_dir <- file.path(demo_dir, "project") + df <- data.frame(id = c("A", "B"), V1 = c(1, 0), V2 = c(0, 1)) + write_demo_label_embeddings(project_dir, "corpus", df) + write_demo_label_embeddings(project_dir, "corpus_batch", df) + file.create(file.path(project_dir, "openai_batch_state_label=corpus_batch.json")) + + testthat::expect_message( + out <- testthat::with_mocked_bindings( + demo_finalize_openai_batch(demo_dir, verbose = TRUE), + batch_status_openai = function(...) data.frame(), + batch_collect_openai = function(...) list(downloaded_jobs = 0L), + .package = "openalexVectorComp" + ), + "Batch comparison written successfully" + ) + testthat::expect_true(out$comparison_ready) + testthat::expect_equal(out$summary_df$mean_cosine_similarity, 1) + summary <- yaml::read_yaml(out$summary_yaml) + testthat::expect_identical(summary$matched_ids, 2L) +}) + +testthat::test_that(".ovc_compare_direct_vs_batch validates inputs and handles zero vectors", { + compare <- ovc_ns(".ovc_compare_direct_vs_batch") + mk <- function(direct, batch) { + demo_dir <- make_demo_openai_workspace() + project_dir <- file.path(demo_dir, "project") + write_demo_label_embeddings(project_dir, "corpus", direct) + write_demo_label_embeddings(project_dir, "corpus_batch", batch) + function() compare(project_dir, "model_id=text-embedding-3-small", batch_label = "corpus_batch") + } + ok <- data.frame(id = c("A", "B"), V1 = c(1, 0), V2 = c(0, 1)) + empty <- ok[0, ] + + testthat::expect_error(mk(empty, ok)(), "Direct embeddings are empty") + testthat::expect_error(mk(ok, empty)(), "Batch embeddings are empty") + testthat::expect_error( + mk(ok, data.frame(id = c("A", "B"), W1 = 1))(), + "Could not find common embedding columns" + ) + testthat::expect_error( + mk(ok, data.frame(id = c("X", "Y"), V1 = 1, V2 = 1))(), + "No overlapping ids" + ) + + res <- mk( + data.frame(id = c("A", "B"), V1 = c(0, 3), V2 = c(0, 4)), + data.frame(id = c("A", "B"), V1 = c(1, 3), V2 = c(0, 4.5)) + )() + cmp <- res$comparison_df[order(res$comparison_df$id), ] + testthat::expect_true(is.na(cmp$cosine_similarity[1])) + testthat::expect_equal(cmp$max_abs_diff, c(1, 0.5)) + testthat::expect_identical(res$matched_ids, 2L) + testthat::expect_identical(res$vcols, c("V1", "V2")) +}) diff --git a/tests/testthat/test-demo-runner.R b/tests/testthat/test-demo-runner.R index 0383213..014785b 100644 --- a/tests/testthat/test-demo-runner.R +++ b/tests/testthat/test-demo-runner.R @@ -167,3 +167,118 @@ testthat::test_that("run_demo_openai requires api_key and configures OpenAI back testthat::expect_identical(as.character(backend$model), "text-embedding-3-small") testthat::expect_false(out$rendered) }) + +testthat::test_that("run_demo_openalex validates its arguments", { + d <- tempfile("ovc_demo_val_") + testthat::expect_error(run_demo_openalex(demo_dir = ""), "`demo_dir` must be a non-empty") + testthat::expect_error(run_demo_openalex(demo_dir = d, render = NA), "`render` must be TRUE or FALSE") + testthat::expect_error(run_demo_openalex(demo_dir = d, max_corpus = 0), "`max_corpus` must be a positive") + testthat::expect_error(run_demo_openalex(demo_dir = d, max_reference = Inf), "`max_reference` must be a positive") + testthat::expect_error(run_demo_openalex(demo_dir = d, overwrite = "yes"), "`overwrite` must be TRUE or FALSE") + testthat::expect_error(run_demo_openalex(demo_dir = d, quarto_file = ""), "`quarto_file` must be a non-empty") + testthat::expect_error( + run_demo_openalex(demo_dir = d, render = FALSE, backend = "hf"), + "`backend` must be NULL or a backend config" + ) + testthat::expect_false(dir.exists(d)) +}) + +testthat::test_that("run_demo_openalex defaults to the HF backend and reports when verbose", { + d <- file.path(tempfile("ovc_demo_default_"), "demo") + testthat::expect_message( + out <- run_demo_openalex(demo_dir = d, render = FALSE, max_corpus = 3, max_reference = 2, verbose = TRUE), + "Demo workspace prepared at" + ) + b <- backend_read(out$backend_yaml) + testthat::expect_identical(b$provider, "hf") + testthat::expect_identical(b$model, "BAAI/bge-small-en-v1.5") + testthat::expect_equal(nrow(arrow::read_parquet(file.path(out$corpus_dir, "corpus_small.parquet"))), 3L) +}) + +testthat::test_that("run_demo_openalex render requires a token for hosted providers", { + ovc_local_token(NA) + d <- tempfile("ovc_demo_notoken_") + testthat::expect_error( + run_demo_openalex(demo_dir = d, render = TRUE, backend = ovc_hf_backend(), verbose = FALSE), + "`OVC_API_TOKEN` is required for provider `hf`" + ) +}) + +testthat::test_that("run_demo_openalex render calls quarto in the demo dir", { + testthat::skip_if_not_installed("quarto") + d <- tempfile("ovc_demo_render_mock_") + wd_before <- getwd() + seen <- NULL + testthat::local_mocked_bindings( + quarto_render = function(input, ...) { + seen <<- list(input = input, wd = getwd()) + invisible(NULL) + }, + .package = "quarto" + ) + + msgs <- testthat::capture_messages( + out <- run_demo_openalex( + demo_dir = d, + render = TRUE, + backend = backend_config(provider = "tei", model = "m"), + max_corpus = 2, + max_reference = 2, + verbose = TRUE + ) + ) + testthat::expect_match(paste(msgs, collapse = ""), "Rendering Quarto analysis: openalex_demo_analysis.qmd") + testthat::expect_true(out$rendered) + testthat::expect_identical(seen$input, "openalex_demo_analysis.qmd") + testthat::expect_identical(normalizePath(seen$wd), normalizePath(d)) + testthat::expect_identical(getwd(), wd_before) +}) + +testthat::test_that("run_demo_openai validates model, restores token and prints commands", { + d <- tempfile("ovc_demo_openai_cmd_") + testthat::expect_error( + run_demo_openai(api_key = "k", demo_dir = d, model = " ", render = FALSE), + "`model` must be a non-empty" + ) + + ovc_local_token("previous-token") + msgs <- testthat::capture_messages( + out <- run_demo_openai(api_key = " k2 ", demo_dir = d, render = FALSE, max_corpus = 2, max_reference = 1, verbose = TRUE) + ) + txt <- paste(msgs, collapse = "") + testthat::expect_match(txt, "OpenAI batch status command:") + testthat::expect_match(txt, "batch_status_openai\\(") + testthat::expect_match(txt, "OpenAI batch finalize command:") + testthat::expect_match(out$openai_batch_finalize_command, "demo_finalize_openai_batch\\(") + testthat::expect_match(out$openai_batch_status_command, "label = \"corpus_batch\"") + testthat::expect_identical(Sys.getenv("OVC_API_TOKEN"), "previous-token") +}) + +testthat::test_that("demo fixture helpers report missing files and columns", { + copy_fixture <- ovc_ns(".ovc_copy_demo_fixture") + demo_path <- ovc_ns(".ovc_demo_path") + td <- tempfile("ovc_fixture_") + dir.create(td) + + testthat::expect_error( + copy_fixture(file.path(td, "missing.parquet"), file.path(td, "out"), "x.parquet", 5), + "Demo fixture does not exist" + ) + src <- file.path(td, "bad.parquet") + arrow::write_parquet(data.frame(id = "a", title = "t"), src) + testthat::expect_error( + copy_fixture(src, file.path(td, "out"), "x.parquet", 5), + "missing required columns: abstract" + ) + + testthat::expect_error( + demo_path("ovc_demo/does-not-exist.txt"), + "Could not resolve installed or local inst path" + ) + + dir.create(file.path(td, "inst", "local_only"), recursive = TRUE) + file.create(file.path(td, "inst", "local_only", "f.txt")) + old <- setwd(td) + on.exit(setwd(old), add = TRUE) + testthat::expect_identical(demo_path("local_only/f.txt"), file.path("inst", "local_only", "f.txt")) +}) diff --git a/tests/testthat/test-distance-functions.R b/tests/testthat/test-distance-functions.R index 3497624..750bc97 100644 --- a/tests/testthat/test-distance-functions.R +++ b/tests/testthat/test-distance-functions.R @@ -459,3 +459,339 @@ testthat::test_that("distances joins prototype and ridge datasets by id", { testthat::expect_equal(joined$distance, c(0.4, -0.2)) testthat::expect_equal(joined$relevance_score, c(0.8, 0.1)) }) + +# Small fixture writer: `emb` must contain id, label, V* (and optionally batch). +write_label_embeddings <- function(dir, emb, partitioning = c("label", "batch")) { + dir.create(dir, recursive = TRUE, showWarnings = FALSE) + if (!"batch" %in% names(emb)) emb$batch <- 1L + arrow::write_dataset(emb, path = dir, format = "parquet", partitioning = partitioning) + dir +} + +small_ridge_emb <- function() { + data.frame( + id = c("R1", "R2", "R3", "R4", "C1", "C2"), + V1 = c(1, 1.2, 0.8, 1.1, 1, -1), + V2 = c(0.1, -0.1, 0.05, 0, 0, 0.2), + label = c(rep("reference", 4), "corpus", "corpus"), + stringsAsFactors = FALSE + ) +} + +testthat::test_that("distance_ridge and fit_ridge validate labels and regularization", { + testthat::expect_error(distance_ridge(tempdir(), reference_label = ""), "`reference_label` must be") + testthat::expect_error(distance_ridge(tempdir(), corpus_label = c("a", "b")), "`corpus_label` must be") + testthat::expect_error(distance_ridge(tempdir(), regularization = 0), "`regularization` must be") + testthat::expect_error(fit_ridge(tempdir(), reference_label = " ", output = tempfile()), "`reference_label` must be") + testthat::expect_error(fit_ridge(tempdir(), output = tempfile(), regularization = -1), "`regularization` must be") +}) + +testthat::test_that("distance_ridge reads a flat embeddings dir, names output from metadata and reuses a fit", { + proj <- tempfile("ovc_ridge_flat_") + emb_dir <- write_label_embeddings(file.path(proj, "embeddings"), small_ridge_emb()) + backend_save( + backend_config(provider = "hf", model = "org/flat-model"), + fn = file.path(emb_dir, "embed_model.yaml") + ) + + msgs <- testthat::capture_messages( + out <- distance_ridge(proj, batch_size = 10, verbose = TRUE) + ) + txt <- paste(msgs, collapse = "") + testthat::expect_match(txt, "Using embeddings from") + testthat::expect_match(txt, "Saved reference-area fit to") + testthat::expect_match(txt, "Computing area distances for corpus label 'corpus'") + testthat::expect_match( + out, + "distance_ridge/model_id=org_flat-model/corpus_label=corpus/reference_label=reference$" + ) + meta <- yaml::read_yaml(file.path(out, "embed_model.yaml")) + testthat::expect_identical(meta$ridge_mode, "reference_area") + testthat::expect_identical(meta$reference_label, "reference") + + fit_path <- file.path(proj, "ridge_fit.rds") + testthat::expect_true(file.exists(fit_path)) + first <- dplyr::collect(arrow::open_dataset(out, factory_options = list(exclude_invalid_files = TRUE))) + marker <- file.path(out, "stale.txt") + file.create(marker) + + out2 <- distance_ridge(proj, fit_path = fit_path, verbose = FALSE) + testthat::expect_identical(out2, out) + testthat::expect_false(file.exists(marker)) + second <- dplyr::collect(arrow::open_dataset(out2, factory_options = list(exclude_invalid_files = TRUE))) + testthat::expect_equal( + second$area_distance[order(second$id)], + first$area_distance[order(first$id)] + ) + # C2 is far from the reference cloud compared to C1. + testthat::expect_gt( + second$area_distance[second$id == "C2"], + second$area_distance[second$id == "C1"] + ) +}) + +testthat::test_that("distance_ridge falls back to legacy _tei_info.yaml metadata", { + proj <- tempfile("ovc_ridge_legacy_") + emb_dir <- write_label_embeddings(file.path(proj, "embeddings"), small_ridge_emb()) + yaml::write_yaml( + list( + model = list(requested_id = "legacy/model"), + backend = list(provider = "tei", base_url = "http://localhost:3000") + ), + file.path(emb_dir, "_tei_info.yaml") + ) + + out <- distance_ridge(proj, verbose = FALSE) + testthat::expect_match(out, "model_id=legacy_model/corpus_label=corpus") + meta <- yaml::read_yaml(file.path(out, "embed_model.yaml")) + testthat::expect_identical(meta$ridge_mode, "reference_area") + testthat::expect_identical(meta$model$requested_id, "legacy/model") +}) + +testthat::test_that("distance_ridge rejects missing or invalid fits", { + proj <- tempfile("ovc_ridge_fit_") + write_label_embeddings(file.path(proj, "embeddings", "model_id=m"), small_ridge_emb()) + + testthat::expect_error( + distance_ridge(proj, fit_path = file.path(proj, "nope.rds"), verbose = FALSE), + "`fit_path` does not exist" + ) + bad_fit <- file.path(proj, "bad.rds") + saveRDS(list(mu = 1), bad_fit) + testthat::expect_error( + distance_ridge(proj, fit_path = bad_fit, verbose = FALSE), + "not an `ovc_reference_area_fit`" + ) +}) + +testthat::test_that("distance_ridge errors on bad corpus partitions", { + run_with <- function(emb, ...) { + proj <- tempfile("ovc_ridge_bad_") + write_label_embeddings(file.path(proj, "embeddings", "model_id=m"), emb) + distance_ridge(proj, verbose = FALSE, ...) + } + base <- small_ridge_emb() + + no_v <- base[, c("id", "label")] + testthat::expect_error(run_with(no_v), "No embedding columns") + + dup_in_batch <- base + dup_in_batch$id[6] <- "C1" + testthat::expect_error(run_with(dup_in_batch), "Duplicate ids found in corpus label partition\\.") + + dup_across <- base + dup_across$id[6] <- "C1" + dup_across$batch <- c(1L, 1L, 1L, 1L, 1L, 2L) + testthat::expect_error(run_with(dup_across), "across batches") + + non_finite <- base + non_finite$V1[6] <- NaN + testthat::expect_error(run_with(non_finite), "Non-finite embedding values found in corpus") + + testthat::expect_error( + run_with(base, corpus_label = "missing"), + "No embeddings found for `corpus_label = missing`" + ) +}) + +testthat::test_that("fit_ridge handles degenerate reference sets", { + fit_with <- function(emb, ...) { + dir <- write_label_embeddings(tempfile("ovc_fit_"), emb) + out <- tempfile(fileext = ".rds") + fit_ridge(dir, output = out, verbose = FALSE, ...) + readRDS(out) + } + base <- small_ridge_emb() + + testthat::expect_error(fit_with(base[, c("id", "label")]), "No embedding columns") + testthat::expect_error(fit_with(base, reference_label = "missing"), "No embeddings found for `reference_label") + + nf <- base + nf$V2[1] <- Inf + testthat::expect_error(fit_with(nf), "Non-finite embedding values found in reference") + + testthat::expect_warning( + fit <- fit_with(base[c(1, 5), ]), + "< 2 rows; using diagonal covariance fallback" + ) + testthat::expect_equal(fit$mu, c(1, 0.1)) + testthat::expect_equal(fit$Sigma_inv, diag(1 / (1 + 1e-6), 2)) + + collinear <- data.frame( + id = c("R1", "R2", "R3"), + V1 = c(1, 2, 3), + V2 = c(1, 2, 3), + label = "reference", + stringsAsFactors = FALSE + ) + testthat::expect_error( + fit_with(collinear, regularization = 1e-30), + "Could not invert regularized covariance" + ) +}) + +testthat::test_that("distance_reference_cosine validates inputs and dataset shape", { + testthat::expect_error(distance_reference_cosine(tempdir(), corpus_label = ""), "`corpus_label` must be") + testthat::expect_error(distance_reference_cosine(tempdir(), reference_label = NA), "`reference_label` must be") + testthat::expect_error(distance_reference_cosine(tempdir(), max_cells = -1), "`max_cells` must be") + + proj <- tempfile("ovc_cos_shape_") + mdir <- file.path(proj, "embeddings", "model_id=m") + dir.create(mdir, recursive = TRUE) + arrow::write_parquet(data.frame(id = "A", V1 = 1), file.path(mdir, "x.parquet")) + testthat::expect_error( + distance_reference_cosine(proj, embeddings_dir = "model_id=m", verbose = FALSE), + "has no `label` partition" + ) + + proj2 <- tempfile("ovc_cos_nov_") + write_label_embeddings( + file.path(proj2, "embeddings", "model_id=m"), + data.frame(id = c("A", "B"), x = 1, label = c("corpus", "reference")) + ) + testthat::expect_error( + distance_reference_cosine(proj2, embeddings_dir = "model_id=m", verbose = FALSE), + "No embedding columns" + ) +}) + +testthat::test_that("distance_reference_cosine reports errors for each partition problem", { + run_with <- function(emb) { + proj <- tempfile("ovc_cos_bad_") + write_label_embeddings(file.path(proj, "embeddings", "model_id=m"), emb) + distance_reference_cosine(proj, embeddings_dir = "model_id=m", verbose = FALSE) + } + + testthat::expect_error( + run_with(data.frame(id = "C1", V1 = 1, V2 = 0, label = "corpus")), + "No embeddings found for `reference_label" + ) + testthat::expect_error( + run_with(data.frame(id = c("R1", "C1", "C1"), V1 = 1, V2 = 0, label = c("reference", "corpus", "corpus"))), + "Duplicate ids found in corpus label partition" + ) + testthat::expect_error( + run_with(data.frame(id = c("R1", "C1"), V1 = c(0, 1), V2 = 0, label = c("reference", "corpus"))), + "Reference partition contains zero-norm" + ) + testthat::expect_error( + run_with(data.frame(id = c("R1", "C1", "C2"), V1 = c(1, 1, -1), V2 = 0, label = c("reference", "corpus", "corpus"))), + "Corpus centroid has zero norm" + ) +}) + +testthat::test_that("distance_reference_cosine verbose run replaces previous output", { + proj <- tempfile("ovc_cos_verbose_") + write_label_embeddings( + file.path(proj, "embeddings", "model_id=m"), + data.frame(id = c("R1", "C1"), V1 = c(1, 0), V2 = c(0, 1), label = c("reference", "corpus")) + ) + out <- distance_reference_cosine(proj, embeddings_dir = "model_id=m", verbose = FALSE) + marker <- file.path(out, "stale.txt") + file.create(marker) + + msgs <- testthat::capture_messages( + out2 <- distance_reference_cosine(proj, embeddings_dir = "model_id=m", verbose = TRUE) + ) + txt <- paste(msgs, collapse = "") + testthat::expect_match(txt, "Loading reference and corpus label partitions") + testthat::expect_match(txt, "for 1 corpus x 1 reference vectors") + testthat::expect_match(txt, "Wrote cosine distance matrix \\(2 x 2\\)") + testthat::expect_identical(normalizePath(out2), normalizePath(out)) + testthat::expect_false(file.exists(marker)) + mat <- arrow::read_parquet(file.path(out2, "pairwise-cosine.parquet")) + testthat::expect_equal(mat$R1[mat$id == "C1"], 1) +}) + +testthat::test_that("score_ridge validates input and derives output dir", { + testthat::expect_error(score_ridge(""), "`distance_parquet` must be") + testthat::expect_error(score_ridge(tempdir(), alpha = 0), "`alpha` must be a positive number") + + td <- tempfile("ovc_score_ridge_") + dist_dir <- file.path(td, "dists") + dir.create(dist_dir, recursive = TRUE) + arrow::write_parquet(data.frame(id = c("A", "B"), area_distance = c(0, 2)), file.path(dist_dir, "d.parquet")) + + testthat::expect_message( + out <- score_ridge(dist_dir, alpha = 1, verbose = TRUE), + "Wrote ridge scores for 2 rows" + ) + testthat::expect_identical(out, normalizePath(file.path(td, "score_ridge"), mustWork = FALSE)) + sc <- dplyr::collect(arrow::open_dataset(out)) + sc <- sc[order(sc$id), ] + testthat::expect_equal(sc$relevance_score, c(1, exp(-2))) + + bad_cols <- file.path(td, "badcols") + dir.create(bad_cols) + arrow::write_parquet(data.frame(id = "A", d = 1), file.path(bad_cols, "d.parquet")) + testthat::expect_error(score_ridge(bad_cols, verbose = FALSE), "must contain columns `id` and `area_distance`") + + nf <- file.path(td, "nonfinite") + dir.create(nf) + arrow::write_parquet(data.frame(id = "A", area_distance = NaN), file.path(nf, "d.parquet")) + testthat::expect_error(score_ridge(nf, verbose = FALSE), "non-finite values") + + empty <- file.path(td, "empty") + dir.create(empty) + arrow::write_parquet(data.frame(id = character(), area_distance = numeric()), file.path(empty, "d.parquet")) + testthat::expect_error(score_ridge(empty, verbose = FALSE), "No rows found in distance dataset") +}) + +testthat::test_that("score_reference_cosine derives default output dir and reports", { + td <- tempfile("ovc_score_cos_") + dist_dir <- file.path(td, "dists") + dir.create(dist_dir, recursive = TRUE) + arrow::write_parquet(data.frame(id = c("A", "centroid"), R1 = c(0.25, 0.5)), file.path(dist_dir, "d.parquet")) + + testthat::expect_message( + out <- score_reference_cosine(dist_dir, verbose = TRUE), + "Wrote reference cosine scores" + ) + testthat::expect_identical(out, normalizePath(file.path(td, "score_reference_cosine"), mustWork = FALSE)) + sc <- dplyr::collect(arrow::open_dataset(out)) + testthat::expect_equal(sc$R1[order(sc$id)], c(0.75, 0.5)) + + testthat::expect_error(score_reference_cosine(character()), "`distance_parquet` must be") +}) + +testthat::test_that("calibrate_threshold builds a grid, picks the best F1 and reports progress", { + td <- tempfile("ovc_calib_") + scores_dir <- file.path(td, "scores") + dir.create(scores_dir, recursive = TRUE) + # 12 single-row files -> >= 10 scan batches to trigger the progress message. + ids <- paste0("S", 1:12) + sc <- c(seq(0.95, 0.65, length.out = 6), seq(0.4, 0.1, length.out = 6)) + for (i in seq_along(ids)) { + arrow::write_parquet( + data.frame(id = ids[i], score = sc[i]), + file.path(scores_dir, sprintf("part-%02d.parquet", i)) + ) + } + arrow::write_parquet(data.frame(id = "U1", score = NaN), file.path(scores_dir, "part-unlabeled.parquet")) + arrow::write_parquet(data.frame(id = character(), score = numeric()), file.path(scores_dir, "part-empty.parquet")) + labels_dir <- file.path(td, "labels") + dir.create(labels_dir) + arrow::write_parquet( + data.frame(id = c(ids, "U1"), label = c(rep(1L, 6), rep(0L, 6), NA)), + file.path(labels_dir, "labels.parquet") + ) + + msgs <- testthat::capture_messages( + best <- calibrate_threshold(scores_dir, "score", labels_dir, n_thresholds = 11, batch_size = 1, verbose = TRUE) + ) + txt <- paste(msgs, collapse = "") + testthat::expect_match(txt, "First pass: computing score range") + testthat::expect_match(txt, "Second pass: sweeping 11 thresholds") + testthat::expect_match(txt, "processed 10 batches") + + testthat::expect_length(best$thresholds, 11L) + testthat::expect_equal(range(best$thresholds), c(0.1, 0.95)) + testthat::expect_equal(best$f1, 1) + testthat::expect_gt(best$th, 0.4) + testthat::expect_lte(best$th, 0.65) + + testthat::expect_error( + calibrate_threshold(scores_dir, "score", labels_parquet = ""), + "`labels_parquet` is required" + ) +}) diff --git a/tests/testthat/test-embedding-offline.R b/tests/testthat/test-embedding-offline.R index 6ae3ef0..da1196d 100644 --- a/tests/testthat/test-embedding-offline.R +++ b/tests/testthat/test-embedding-offline.R @@ -518,3 +518,169 @@ testthat::test_that("embed_corpus dry_run preprocesses but does not write embedd testthat::expect_false(dir.exists(emb_root)) } }) + +fake_embed_texts <- function(texts, backend) { + matrix(1, nrow = length(texts), ncol = 2, dimnames = list(NULL, c("V1", "V2"))) +} + +testthat::test_that("embed_corpus validates preprocessor, cleaner_args and model id", { + proj <- make_tmp_corpus_project() + testthat::expect_error( + openalexVectorComp::embed_corpus(project_dir = proj, text_preprocessor = "x", verbose = FALSE), + "`text_preprocessor` must be a function" + ) + testthat::expect_error( + openalexVectorComp::embed_corpus(project_dir = proj, cleaner_args = "x", verbose = FALSE), + "`cleaner_args` must be a list" + ) + testthat::expect_error( + openalexVectorComp::embed_corpus( + project_dir = proj, + backend = list(provider = "hf", base_url = "https://router.huggingface.co/hf-inference", model = NULL), + verbose = FALSE + ), + "Could not determine model id" + ) + + backend <- openalexVectorComp::backend_config(provider = "hf") + run_pp <- function(pp) { + testthat::with_mocked_bindings( + openalexVectorComp::embed_corpus( + project_dir = proj, backend = backend, text_preprocessor = pp, verbose = FALSE + ), + embed_texts = fake_embed_texts, + .package = "openalexVectorComp" + ) + } + testthat::expect_error(run_pp(function(df) "x"), "must return a data frame") + testthat::expect_error( + run_pp(function(df) data.frame(id = rep(df$id[1], 2), text = "t", text_hash = c("a", "b"))), + "duplicated ids" + ) +}) + +testthat::test_that("embed_corpus verbose mode reports directories and progress", { + proj <- make_tmp_corpus_project() + backend <- openalexVectorComp::backend_config(provider = "hf") + run <- function() { + testthat::with_mocked_bindings( + openalexVectorComp::embed_corpus(project_dir = proj, backend = backend, batch_size = 1, verbose = TRUE), + embed_texts = fake_embed_texts, + .package = "openalexVectorComp" + ) + } + + msgs <- testthat::capture_messages(model_dir <- run()) + txt <- paste(msgs, collapse = "") + testthat::expect_match(txt, "Created model output directory") + testthat::expect_match(txt, "Wrote backend metadata") + testthat::expect_match(txt, "Created label output directory") + testthat::expect_match(txt, "Embedding 2 works in up to 2 shards") + testthat::expect_match(txt, "Embedded 2 new/changed works") + + msgs2 <- testthat::capture_messages(run()) + txt2 <- paste(msgs2, collapse = "") + testthat::expect_match(txt2, "Reusing existing model output directory") + testthat::expect_match(txt2, "Reusing existing label output directory") + + meta <- yaml::read_yaml(file.path(model_dir, "embed_model.yaml")) + testthat::expect_identical(meta$text_preprocessor$name, "clean_abstract_for_embedding") + testthat::expect_identical(meta$embedding_label, "corpus") +}) + +testthat::test_that("embed_corpus skips batches where the preprocessor keeps no rows", { + proj <- make_tmp_corpus_project() + backend <- openalexVectorComp::backend_config(provider = "hf") + called <- FALSE + model_dir <- testthat::with_mocked_bindings( + openalexVectorComp::embed_corpus( + project_dir = proj, + backend = backend, + text_preprocessor = function(df) data.frame(id = df$id, text = "", text_hash = "h"), + verbose = FALSE + ), + embed_texts = function(texts, backend) { + called <<- TRUE + fake_embed_texts(texts, backend) + }, + .package = "openalexVectorComp" + ) + testthat::expect_false(called) + testthat::expect_length( + list.files(model_dir, pattern = "embeddings-.*[.]parquet$", recursive = TRUE), + 0L + ) +}) + +testthat::test_that("embed_corpus dry_run parses or reuses cleaned title/abstract", { + proj <- make_tmp_corpus_project() + backend <- openalexVectorComp::backend_config(provider = "hf") + preview_file <- file.path(proj, "corpus_dryrun.parquet") + + parsing_pp <- function(df) { + text <- c("Title: Alpha T\nAbstract: Alpha A", "Plain text without prefix") + data.frame(id = df$id, text = text, text_hash = c("h1", "h2"), stringsAsFactors = FALSE) + } + msgs <- testthat::capture_messages( + openalexVectorComp::embed_corpus( + project_dir = proj, backend = backend, text_preprocessor = parsing_pp, + dry_run = TRUE, verbose = TRUE + ) + ) + testthat::expect_match(paste(msgs, collapse = ""), "Dry run mode") + testthat::expect_match(paste(msgs, collapse = ""), "would embed 2 new/changed works") + prev <- arrow::read_parquet(preview_file) + prev <- prev[order(prev$id), ] + testthat::expect_identical(prev$cleaned_title, c("Alpha T", NA)) + testthat::expect_identical(prev$cleaned_abstract, c("Alpha A", NA)) + + title_only_pp <- function(df) { + data.frame(id = df$id, text = paste("Title:", df$title), text_hash = df$id, stringsAsFactors = FALSE) + } + openalexVectorComp::embed_corpus( + project_dir = proj, backend = backend, text_preprocessor = title_only_pp, + dry_run = TRUE, verbose = FALSE + ) + prev2 <- arrow::read_parquet(preview_file) + prev2 <- prev2[order(prev2$id), ] + testthat::expect_identical(prev2$cleaned_title, c("Alpha", "Beta")) + testthat::expect_true(all(is.na(prev2$cleaned_abstract))) + + own_cols_pp <- function(df) { + data.frame( + id = df$id, text = "x", text_hash = df$id, + cleaned_title = paste0("CT-", df$id), cleaned_abstract = paste0("CA-", df$id), + stringsAsFactors = FALSE + ) + } + # Re-running replaces the previous preview file. + openalexVectorComp::embed_corpus( + project_dir = proj, backend = backend, text_preprocessor = own_cols_pp, + dry_run = TRUE, verbose = FALSE + ) + prev3 <- arrow::read_parquet(preview_file) + prev3 <- prev3[order(prev3$id), ] + testthat::expect_identical(prev3$cleaned_title, c("CT-W1", "CT-W2")) + testthat::expect_identical(prev3$cleaned_abstract, c("CA-W1", "CA-W2")) +}) + +testthat::test_that("embed_corpus does not re-embed unchanged rows when delete_existing = FALSE", { + skip("Known bug: open_dataset(model_dir, 'label=..') passes the label as `schema`, so existing hashes are never loaded (embed_corpus.R:181)") + proj <- make_tmp_corpus_project() + backend <- openalexVectorComp::backend_config(provider = "hf") + n_embedded <- 0L + run <- function() { + testthat::with_mocked_bindings( + openalexVectorComp::embed_corpus(project_dir = proj, backend = backend, verbose = FALSE), + embed_texts = function(texts, backend) { + n_embedded <<- n_embedded + length(texts) + fake_embed_texts(texts, backend) + }, + .package = "openalexVectorComp" + ) + } + run() + testthat::expect_identical(n_embedded, 2L) + run() + testthat::expect_identical(n_embedded, 2L) +}) diff --git a/tests/testthat/test-openai-batch-http.R b/tests/testthat/test-openai-batch-http.R new file mode 100644 index 0000000..bd75165 --- /dev/null +++ b/tests/testthat/test-openai-batch-http.R @@ -0,0 +1,197 @@ +oa_http_backend <- function(base_url = "https://api.openai.test/v1/", timeout = 7) { + list( + provider = "openai", + base_url = base_url, + model = "text-embedding-3-small", + timeout = timeout, + retries = 0L + ) +} + +testthat::test_that(".openai_batch_request validates backend and token", { + req_fun <- ovc_ns(".openai_batch_request") + + testthat::expect_error(req_fun(list(), "/files"), "must include `base_url`") + testthat::expect_error(req_fun("x", "/files"), "must include `base_url`") + + ovc_local_token(NA) + testthat::expect_error( + req_fun(oa_http_backend(), "/files"), + "`OVC_API_TOKEN` is required" + ) +}) + +testthat::test_that(".openai_batch_request builds url, method, auth and timeout", { + req_fun <- ovc_ns(".openai_batch_request") + ovc_local_token(" sk-test ") + + req <- req_fun(oa_http_backend(), "/batches/abc", method = "GET") + testthat::expect_identical(httr2::req_get_url(req), "https://api.openai.test/v1/batches/abc") + testthat::expect_identical(httr2::req_get_method(req), "GET") + testthat::expect_identical( + httr2::req_get_headers(req, "reveal")$Authorization, + "Bearer sk-test" + ) + testthat::expect_equal(req$options$timeout_ms, 7000) + + req_no_timeout <- req_fun(oa_http_backend(timeout = NA), "/files", method = "POST") + testthat::expect_identical(httr2::req_get_method(req_no_timeout), "POST") + testthat::expect_null(req_no_timeout$options$timeout_ms) +}) + +testthat::test_that(".openai_batch_upload_file posts multipart and returns the file id", { + upload <- ovc_ns(".openai_batch_upload_file") + ovc_local_token() + f <- tempfile(fileext = ".jsonl") + writeLines('{"custom_id":"a"}', f) + + seen <- NULL + httr2::local_mocked_responses(function(req) { + seen <<- list( + url = httr2::req_get_url(req), + method = httr2::req_get_method(req), + body_type = httr2::req_get_body_type(req) + ) + httr2::response_json(body = list(id = "file-123", purpose = "batch")) + }) + + testthat::expect_identical(upload(oa_http_backend(), f), "file-123") + testthat::expect_identical(seen$url, "https://api.openai.test/v1/files") + testthat::expect_identical(seen$method, "POST") + testthat::expect_identical(seen$body_type, "multipart") +}) + +testthat::test_that(".openai_batch_upload_file reports HTTP errors with API message or body", { + upload <- ovc_ns(".openai_batch_upload_file") + ovc_local_token() + f <- tempfile(fileext = ".jsonl") + writeLines("{}", f) + + httr2::local_mocked_responses(function(req) { + httr2::response_json( + status_code = 400L, + body = list(error = list(message = "Invalid purpose")) + ) + }) + testthat::expect_error( + upload(oa_http_backend(), f), + "OpenAI file upload failed \\(HTTP 400\\)\\. Invalid purpose" + ) + + httr2::local_mocked_responses(function(req) { + httr2::response( + status_code = 502L, + headers = list(`Content-Type` = "text/plain"), + body = charToRaw("Bad gateway") + ) + }) + testthat::expect_error( + upload(oa_http_backend(), f), + "HTTP 502\\)\\. Bad gateway" + ) + + httr2::local_mocked_responses(function(req) { + httr2::response(status_code = 500L) + }) + testthat::expect_error( + upload(oa_http_backend(), f), + "HTTP 500\\)\\. No error body returned" + ) +}) + +testthat::test_that(".openai_batch_upload_file rejects non-JSON or id-less success responses", { + upload <- ovc_ns(".openai_batch_upload_file") + ovc_local_token() + f <- tempfile(fileext = ".jsonl") + writeLines("{}", f) + + httr2::local_mocked_responses(function(req) { + httr2::response( + status_code = 200L, + headers = list(`Content-Type` = "text/html"), + body = charToRaw("ok") + ) + }) + testthat::expect_error(upload(oa_http_backend(), f), "non-JSON response") + + httr2::local_mocked_responses(function(req) { + httr2::response_json(body = list(object = "file")) + }) + testthat::expect_error(upload(oa_http_backend(), f), "did not return a file id") +}) + +testthat::test_that(".openai_batch_create sends embeddings batch request", { + create <- ovc_ns(".openai_batch_create") + ovc_local_token() + + seen <- NULL + httr2::local_mocked_responses(function(req) { + seen <<- list( + url = httr2::req_get_url(req), + method = httr2::req_get_method(req), + body = httr2::req_get_body(req) + ) + httr2::response_json(body = list(id = "batch_1", status = "validating")) + }) + + res <- create(oa_http_backend(), input_file_id = "file-9") + testthat::expect_identical(res$id, "batch_1") + testthat::expect_identical(res$status, "validating") + testthat::expect_identical(seen$url, "https://api.openai.test/v1/batches") + testthat::expect_identical(seen$method, "POST") + testthat::expect_identical(seen$body$input_file_id, "file-9") + testthat::expect_identical(seen$body$endpoint, "/v1/embeddings") + testthat::expect_identical(seen$body$completion_window, "24h") + + httr2::local_mocked_responses(function(req) { + httr2::response_json(body = list(status = "validating")) + }) + testthat::expect_error( + create(oa_http_backend(), input_file_id = "file-9"), + "did not return a batch id" + ) +}) + +testthat::test_that(".openai_batch_get fetches the batch by id", { + get_batch <- ovc_ns(".openai_batch_get") + ovc_local_token() + + seen_url <- NULL + httr2::local_mocked_responses(function(req) { + seen_url <<- httr2::req_get_url(req) + httr2::response_json(body = list(id = "batch_7", status = "completed", output_file_id = "of_7")) + }) + + res <- get_batch(oa_http_backend(), "batch_7") + testthat::expect_identical(seen_url, "https://api.openai.test/v1/batches/batch_7") + testthat::expect_identical(res$status, "completed") + testthat::expect_identical(res$output_file_id, "of_7") + + httr2::local_mocked_responses(function(req) httr2::response(status_code = 404L)) + testthat::expect_error( + get_batch(oa_http_backend(), "missing"), + "Embedding request failed after retries" + ) +}) + +testthat::test_that(".openai_batch_download_file writes raw content to dest", { + download <- ovc_ns(".openai_batch_download_file") + ovc_local_token() + + payload <- '{"custom_id":"cid_1","embedding":[1,2]}\n' + seen_url <- NULL + httr2::local_mocked_responses(function(req) { + seen_url <<- httr2::req_get_url(req) + httr2::response(status_code = 200L, body = charToRaw(payload)) + }) + + dest <- file.path(tempfile("ovc_dl_"), "nested", "output.jsonl") + out <- download(oa_http_backend(), "of_1", dest) + testthat::expect_identical(out, dest) + testthat::expect_identical(seen_url, "https://api.openai.test/v1/files/of_1/content") + testthat::expect_true(file.exists(dest)) + testthat::expect_identical( + readChar(dest, file.size(dest), useBytes = TRUE), + payload + ) +}) diff --git a/tests/testthat/test-openai-batch.R b/tests/testthat/test-openai-batch.R index 3b15e9c..3e1cf8c 100644 --- a/tests/testthat/test-openai-batch.R +++ b/tests/testthat/test-openai-batch.R @@ -237,3 +237,515 @@ testthat::test_that("collect ingests completed jobs and is idempotent", { files2 <- list.files(model_dir, pattern = "embeddings-.*[.]parquet$", recursive = TRUE, full.names = TRUE) testthat::expect_length(files2, 1L) }) + +# Helpers for state/collect tests ------------------------------------------ + +write_openai_state <- function(project_dir, label = "corpus", jobs = list(), model_id = "text-embedding-3-small") { + state_file <- file.path(project_dir, paste0("openai_batch_state_label=", label, ".json")) + jsonlite::write_json( + list( + version = 1L, + provider = "openai", + model_id = model_id, + label = label, + backend = list(base_url = "https://api.openai.test/v1", timeout = 30, retries = 0), + jobs = jobs + ), + path = state_file, + auto_unbox = TRUE, + null = "null", + pretty = TRUE + ) + state_file +} + +testthat::test_that("batch input validation rejects each invalid argument", { + validate <- ovc_ns(".ovc_validate_openai_batch_inputs") + args <- list( + project_dir = tempdir(), + backend = fake_openai_backend(), + corpus_name = "corpus", + label = "corpus", + batch_size = 10, + text_preprocessor = identity, + cleaner_args = list(), + save_text = TRUE, + max_requests_per_job = 10, + max_job_bytes = 1000, + completion_window = "24h" + ) + call_with <- function(...) { + a <- args + a[names(list(...))] <- list(...) + do.call(validate, a) + } + + testthat::expect_null(call_with()) + testthat::expect_error(call_with(project_dir = ""), "`project_dir` must be a non-empty") + testthat::expect_error( + call_with(backend = backend_config(provider = "hf")), + "must be an OpenAI backend" + ) + testthat::expect_error(call_with(corpus_name = " "), "`corpus_name` must be a non-empty") + testthat::expect_error(call_with(label = ""), "`label` must be a non-empty") + testthat::expect_error(call_with(batch_size = 0), "`batch_size` must be a positive number") + testthat::expect_error(call_with(text_preprocessor = "x"), "`text_preprocessor` must be a function") + testthat::expect_error(call_with(cleaner_args = "x"), "`cleaner_args` must be a list") + testthat::expect_error(call_with(save_text = NA), "`save_text` must be TRUE or FALSE") + testthat::expect_error(call_with(max_requests_per_job = "a"), "`max_requests_per_job` must be numeric scalar") + testthat::expect_error(call_with(max_job_bytes = Inf), "`max_job_bytes` must be numeric scalar") + testthat::expect_error(call_with(completion_window = "1h"), "must currently be '24h'") +}) + +testthat::test_that("state helpers read, default, lock and index consistently", { + state_read <- ovc_ns(".ovc_openai_state_read") + state_file_fun <- ovc_ns(".ovc_openai_state_file") + lock_acquire <- ovc_ns(".ovc_openai_lock_acquire") + next_index <- ovc_ns(".ovc_openai_state_next_batch_index") + active_ids <- ovc_ns(".ovc_openai_state_active_custom_ids") + is_terminal <- ovc_ns(".ovc_openai_is_terminal") + to_df <- ovc_ns(".ovc_openai_state_to_df") + + td <- tempfile("ovc_state_") + dir.create(td) + + testthat::expect_identical( + basename(state_file_fun(td, " a/b ")), + "openai_batch_state_label=a_b.json" + ) + + fresh <- state_read(file.path(td, "nope.json"), model_id = "m", backend = list(base_url = "u")) + testthat::expect_identical(fresh$model_id, "m") + testthat::expect_identical(fresh$backend$base_url, "u") + testthat::expect_equal(fresh$backend$timeout, 60) + testthat::expect_length(fresh$jobs, 0L) + + empty <- file.path(td, "empty.json") + file.create(empty) + testthat::expect_error(state_read(empty), "State file is empty") + + no_jobs <- file.path(td, "nojobs.json") + writeLines('{"version": 1}', no_jobs) + testthat::expect_identical(state_read(no_jobs)$jobs, list()) + + lock <- file.path(td, "x.lock") + testthat::expect_true(lock_acquire(lock)) + testthat::expect_false(lock_acquire(lock)) + + testthat::expect_identical(next_index(list(jobs = list())), 1L) + testthat::expect_identical(next_index(list(jobs = list(list(job_id = "a")))), 1L) + testthat::expect_identical( + next_index(list(jobs = list(list(batch_index = 2L), list(batch_index = 5L)))), + 6L + ) + + mf <- file.path(td, "manifest.parquet") + arrow::write_parquet(data.frame(custom_id = c("c1", "c2", "c1")), mf) + jobs <- list( + list(ingested_at = "2026-01-01", manifest_parquet = mf), + list(ingested_at = "", manifest_parquet = file.path(td, "missing.parquet")), + list(ingested_at = "", manifest_parquet = ""), + list(ingested_at = "", manifest_parquet = mf) + ) + testthat::expect_identical(active_ids(list(jobs = list())), character()) + testthat::expect_identical(active_ids(list(jobs = jobs)), c("c1", "c2")) + + testthat::expect_identical( + is_terminal(c("completed", "FAILED", "expired", "cancelled", "in_progress")), + c(TRUE, TRUE, TRUE, TRUE, FALSE) + ) + + testthat::expect_identical(to_df(list(jobs = list())), data.frame()) + df <- to_df(list(jobs = list( + list(batch_index = 1L, job_id = "j1", status = "completed", row_count_submitted = 3L), + list(job_id = "j2") + ))) + testthat::expect_identical(df$job_id, c("j1", "j2")) + testthat::expect_identical(df$batch_index, c(1L, NA_integer_)) + testthat::expect_identical(df$row_count_submitted, c(3L, 0L)) +}) + +testthat::test_that("job update from remote keeps old ids and records errors", { + update <- ovc_ns(".ovc_openai_job_update_from_remote") + job <- list(status = "validating", output_file_id = "of_old", error_file_id = "") + + same <- update(job, list()) + testthat::expect_identical(same$status, "validating") + testthat::expect_identical(same$output_file_id, "of_old") + testthat::expect_null(same$error_message) + + upd <- update(job, list( + status = "failed", + error_file_id = "ef_1", + errors = list(data = list(list(code = "invalid_request"))) + )) + testthat::expect_identical(upd$status, "failed") + testthat::expect_identical(upd$output_file_id, "of_old") + testthat::expect_identical(upd$error_file_id, "ef_1") + testthat::expect_match(upd$error_message, "invalid_request") +}) + +testthat::test_that("output JSONL parsing handles both shapes and rejects bad files", { + parse <- ovc_ns(".ovc_openai_parse_output_jsonl") + td <- tempfile("ovc_parse_") + dir.create(td) + write_lines <- function(x) { + f <- tempfile(tmpdir = td, fileext = ".jsonl") + writeLines(x, f) + f + } + + testthat::expect_error(parse(write_lines(c("", " "))), "output is empty") + + ok <- parse(write_lines(c( + '{"custom_id":"a","response":{"body":{"data":[{"embedding":[1,2]}]}}}', + '{"custom_id":"","embedding":[9,9]}', + '{"custom_id":"b","embedding":[3,4]}', + '{"custom_id":"c","response":{"status_code":500}}' + ))) + testthat::expect_identical(ok$custom_id, c("a", "b")) + testthat::expect_identical(ok$embeddings, list(c(1, 2), c(3, 4))) + + testthat::expect_error( + parse(write_lines('{"custom_id":"a","error":{"message":"x"}}')), + "No embeddings could be parsed" + ) + testthat::expect_error( + parse(write_lines(c('{"custom_id":"a","embedding":[1]}', '{"custom_id":"a","embedding":[2]}'))), + "Duplicate `custom_id`" + ) +}) + +testthat::test_that("embedding output builder joins manifest and validates it", { + build <- ovc_ns(".ovc_openai_build_embeddings_output") + manifest <- data.frame( + custom_id = c("c1", "c2"), + id = c("W1", "W2"), + text_hash = c("h1", "h2"), + text = c("t1", "t2"), + stringsAsFactors = FALSE + ) + parsed <- list(custom_id = c("c2", "c1"), embeddings = list(c(3, 4), c(1, 2))) + + out <- build(parsed, manifest, provider = "openai", model_id = "m") + testthat::expect_identical(out$id, c("W2", "W1")) + testthat::expect_identical(out$text, c("t2", "t1")) + testthat::expect_identical(out$model_id, c("m", "m")) + testthat::expect_equal(out$V1, c(3, 1)) + testthat::expect_equal(out$V2, c(4, 2)) + + testthat::expect_error( + build(parsed, manifest[, c("custom_id", "id")], "openai", "m"), + "Manifest must include" + ) + testthat::expect_error( + build(list(custom_id = "zz", embeddings = list(1)), manifest, "openai", "m"), + "missing in manifest" + ) +}) + +testthat::test_that("next embed batch index scans batch= directories", { + next_idx <- ovc_ns(".ovc_next_embed_batch_index") + td <- tempfile("ovc_bidx_") + testthat::expect_identical(next_idx(td), 1L) + dir.create(td) + testthat::expect_identical(next_idx(td), 1L) + dir.create(file.path(td, "other")) + testthat::expect_identical(next_idx(td), 1L) + dir.create(file.path(td, "batch=2")) + dir.create(file.path(td, "batch=10")) + testthat::expect_identical(next_idx(td), 11L) +}) + +testthat::test_that("submit validates preprocessor output contract", { + proj <- make_openai_batch_project(2) + backend <- fake_openai_backend() + submit <- function(pp) { + testthat::with_mocked_bindings( + openalexVectorComp::batch_submit_openai( + project_dir = proj, + backend = backend, + text_preprocessor = pp, + verbose = FALSE + ), + .openai_batch_upload_file = function(backend, file_path) stop("no upload expected"), + .openai_batch_create = function(...) stop("no create expected"), + .package = "openalexVectorComp" + ) + } + + testthat::expect_error(submit(function(df) "x"), "must return a data frame") + testthat::expect_error( + submit(function(df) data.frame(id = df$id, text = "t")), + "must contain columns: text_hash" + ) + testthat::expect_error( + submit(function(df) data.frame(id = "ZZ", text = "t", text_hash = "h")), + "ids not present" + ) + testthat::expect_error( + submit(function(df) data.frame(id = rep(df$id[1], 2), text = "t", text_hash = c("a", "b"))), + "duplicated ids" + ) + + # Rows with empty text are dropped; nothing left to submit. + out <- submit(function(df) data.frame(id = df$id, text = "", text_hash = "h")) + testthat::expect_identical(out$submitted_jobs, 0L) + testthat::expect_identical(out$submitted_rows, 0L) +}) + +testthat::test_that("submit skips queued rows, honours delete_existing and reports progress", { + proj <- make_openai_batch_project(3) + backend <- fake_openai_backend() + n_create <- 0L + do_submit <- function(...) { + testthat::with_mocked_bindings( + openalexVectorComp::batch_submit_openai(project_dir = proj, backend = backend, ...), + .openai_batch_upload_file = function(backend, file_path) "file_x", + .openai_batch_create = function(backend, input_file_id, completion_window = "24h") { + n_create <<- n_create + 1L + list(id = paste0("job_", n_create), status = "validating") + }, + .package = "openalexVectorComp" + ) + } + + testthat::expect_message( + first <- do_submit(verbose = TRUE), + "Submitted 1 OpenAI batch job" + ) + testthat::expect_identical(first$submitted_rows, 3L) + + # Same rows are already queued in an un-ingested job: nothing new. + testthat::expect_message( + second <- do_submit(verbose = TRUE), + "No new/changed rows to submit" + ) + testthat::expect_identical(second$submitted_jobs, 0L) + state <- jsonlite::fromJSON(first$state_file, simplifyVector = FALSE) + testthat::expect_length(state$jobs, 1L) + + # delete_existing wipes state and label embeddings and resubmits everything. + stale <- file.path(first$model_dir, "label=corpus", "batch=1", "embeddings-00001.parquet") + dir.create(dirname(stale), recursive = TRUE) + file.create(stale) + third <- do_submit(delete_existing = TRUE, verbose = FALSE) + testthat::expect_false(file.exists(stale)) + testthat::expect_identical(third$submitted_rows, 3L) + state3 <- jsonlite::fromJSON(third$state_file, simplifyVector = FALSE) + testthat::expect_length(state3$jobs, 1L) + testthat::expect_identical(state3$jobs[[1]]$job_id, "job_2") + testthat::expect_identical(state3$jobs[[1]]$batch_index, 1L) + + meta <- yaml::read_yaml(file.path(first$model_dir, "embed_model.yaml")) + testthat::expect_identical(meta$submission_mode, "openai_batch") + testthat::expect_identical(meta$embedding_label, "corpus") +}) + +testthat::test_that("submit warns on byte split, and errors on missing dir, columns or lock", { + proj <- make_openai_batch_project(3) + backend <- fake_openai_backend() + mocks <- function(code) { + testthat::with_mocked_bindings( + code, + .openai_batch_upload_file = function(backend, file_path) "file_x", + .openai_batch_create = function(backend, input_file_id, completion_window = "24h") { + list(id = "job", status = "validating") + }, + .package = "openalexVectorComp" + ) + } + + testthat::expect_message( + mocks(openalexVectorComp::batch_submit_openai( + project_dir = proj, backend = backend, max_job_bytes = 300, verbose = TRUE + )), + "split jobs by byte-size limits" + ) + + testthat::expect_error( + openalexVectorComp::batch_submit_openai( + project_dir = file.path(tempdir(), "does-not-exist-ovc"), + backend = backend, + verbose = FALSE + ), + "`project_dir` does not exist" + ) + + proj2 <- make_openai_batch_project(1) + arrow::write_parquet( + data.frame(id = "A", title = "t"), + file.path(proj2, "corpus", "corpus.parquet") + ) + testthat::expect_error( + openalexVectorComp::batch_submit_openai(project_dir = proj2, backend = backend, verbose = FALSE), + "Dataset must contain columns: abstract" + ) + + proj3 <- make_openai_batch_project(1) + file.create(file.path(proj3, "openai_batch_state_label=corpus.json.lock")) + testthat::expect_error( + mocks(openalexVectorComp::batch_submit_openai(project_dir = proj3, backend = backend, verbose = FALSE)), + "State lock exists" + ) +}) + +testthat::test_that("batch_status_openai validates input and refreshes non-terminal jobs", { + proj <- make_openai_batch_project(1) + + testthat::expect_error(batch_status_openai(proj, label = " "), "`label` must be non-empty") + testthat::expect_error(batch_status_openai(proj, refresh_remote = NA), "TRUE or FALSE") + testthat::expect_identical(batch_status_openai(proj), data.frame()) + + state_file <- write_openai_state(proj, jobs = list( + list(job_id = "j_pending", batch_index = 1L, status = "in_progress", ingested_at = ""), + list(job_id = "j_done", batch_index = 2L, status = "completed", ingested_at = ""), + list(job_id = "j_ingested", batch_index = 3L, status = "in_progress", ingested_at = "2026-01-01") + )) + + asked <- character() + seen_backend <- NULL + df <- testthat::with_mocked_bindings( + batch_status_openai(proj, label = "corpus", refresh_remote = TRUE), + .openai_batch_get = function(backend, job_id) { + asked <<- c(asked, job_id) + seen_backend <<- backend + list(id = job_id, status = "completed", output_file_id = "of_1") + }, + .package = "openalexVectorComp" + ) + testthat::expect_identical(asked, "j_pending") + testthat::expect_identical(seen_backend$base_url, "https://api.openai.test/v1") + testthat::expect_identical(seen_backend$timeout, 30) + testthat::expect_identical(df$status, c("completed", "completed", "in_progress")) + saved <- jsonlite::fromJSON(state_file, simplifyVector = FALSE) + testthat::expect_identical(saved$jobs[[1]]$output_file_id, "of_1") + + df2 <- testthat::with_mocked_bindings( + batch_status_openai(proj, refresh_remote = FALSE), + .openai_batch_get = function(...) stop("should not refresh"), + .package = "openalexVectorComp" + ) + testthat::expect_identical(nrow(df2), 3L) +}) + +testthat::test_that("batch_collect_openai validates inputs, state and lock", { + proj <- make_openai_batch_project(1) + backend <- fake_openai_backend() + + testthat::expect_error( + batch_collect_openai(proj, backend = backend_config(provider = "hf"), verbose = FALSE), + "must be an OpenAI backend" + ) + testthat::expect_error( + batch_collect_openai(proj, backend = backend, label = "", verbose = FALSE), + "`label` must be non-empty" + ) + testthat::expect_error( + batch_collect_openai(proj, backend = backend, verbose = FALSE), + "No OpenAI batch state found" + ) + + state_file <- write_openai_state(proj) + file.create(paste0(state_file, ".lock")) + testthat::expect_error( + batch_collect_openai(proj, backend = backend, verbose = FALSE), + "State lock exists" + ) + unlink(paste0(state_file, ".lock")) + + write_openai_state(proj, model_id = NULL) + no_model <- backend + no_model["model"] <- list(NULL) + testthat::expect_error( + batch_collect_openai(proj, backend = no_model, verbose = FALSE), + "Could not determine model id" + ) + testthat::expect_false(file.exists(paste0(state_file, ".lock"))) +}) + +testthat::test_that("batch_collect_openai counts failed, pending and output-less jobs", { + proj <- make_openai_batch_project(1) + backend <- fake_openai_backend() + state_file <- write_openai_state(proj, jobs = list( + list(job_id = "j_fail", status = "in_progress", ingested_at = ""), + list(job_id = "j_wait", status = "validating", ingested_at = ""), + list(job_id = "j_nofile", status = "in_progress", ingested_at = "") + )) + remote <- list( + j_fail = list(status = "failed", errors = list(message = "boom")), + j_wait = list(status = "in_progress"), + j_nofile = list(status = "completed") + ) + + testthat::expect_message( + out <- testthat::with_mocked_bindings( + batch_collect_openai(proj, backend = backend, verbose = TRUE), + .openai_batch_get = function(backend, job_id) remote[[job_id]], + .openai_batch_download_file = function(...) stop("nothing to download"), + .package = "openalexVectorComp" + ), + "No completed OpenAI batch jobs ready" + ) + testthat::expect_identical(out$checked_jobs, 3L) + testthat::expect_identical(out$failed_jobs, 1L) + testthat::expect_identical(out$pending_jobs, 1L) + testthat::expect_identical(out$completed_jobs, 1L) + testthat::expect_identical(out$downloaded_jobs, 0L) + + saved <- jsonlite::fromJSON(state_file, simplifyVector = FALSE) + testthat::expect_identical(saved$jobs[[1]]$status, "failed") + testthat::expect_match(saved$jobs[[1]]$error_message, "boom") + testthat::expect_identical(saved$jobs[[2]]$status, "in_progress") + testthat::expect_identical(saved$jobs[[3]]$error_message, "Completed job has no output_file_id.") +}) + +testthat::test_that("batch_collect_openai reports collected rows when verbose", { + proj <- make_openai_batch_project(2) + backend <- fake_openai_backend() + submit <- testthat::with_mocked_bindings( + openalexVectorComp::batch_submit_openai(project_dir = proj, backend = backend, verbose = FALSE), + .openai_batch_upload_file = function(backend, file_path) "file_1", + .openai_batch_create = function(...) list(id = "job_1", status = "in_progress"), + .package = "openalexVectorComp" + ) + state <- jsonlite::fromJSON(submit$state_file, simplifyVector = FALSE) + manifest <- arrow::read_parquet(state$jobs[[1]]$manifest_parquet) + lines <- vapply(manifest$custom_id, function(cid) { + jsonlite::toJSON(list(custom_id = cid, embedding = c(1, 0)), auto_unbox = TRUE) + }, character(1)) + + testthat::expect_message( + out <- testthat::with_mocked_bindings( + batch_collect_openai(proj, backend = backend, verbose = TRUE), + .openai_batch_get = function(backend, job_id) list(status = "completed", output_file_id = "of"), + .openai_batch_download_file = function(backend, file_id, dest) { + writeLines(lines, dest) + invisible(dest) + }, + .package = "openalexVectorComp" + ), + "Collected 1 completed job\\(s\\), wrote 2 embedding row\\(s\\)" + ) + testthat::expect_identical(out$written_rows, 2L) +}) + +testthat::test_that("submit skips rows already embedded with the same text hash", { + skip("Known bug: .ovc_load_existing_hash passes the label as `schema` to open_dataset, so existing hashes are never loaded (batch_openai_helpers.R:149)") + proj <- make_openai_batch_project(2) + backend <- fake_openai_backend() + prep <- clean_abstract_for_embedding(arrow::read_parquet(file.path(proj, "corpus", "corpus.parquet"))) + label_dir <- file.path(proj, "embeddings", "model_id=text-embedding-3-small", "label=corpus", "batch=1") + dir.create(label_dir, recursive = TRUE) + arrow::write_parquet( + data.frame(id = prep$id, text_hash = prep$text_hash, V1 = 1), + file.path(label_dir, "embeddings-00001.parquet") + ) + out <- testthat::with_mocked_bindings( + openalexVectorComp::batch_submit_openai(project_dir = proj, backend = backend, verbose = FALSE), + .openai_batch_upload_file = function(...) stop("no upload expected"), + .openai_batch_create = function(...) stop("no create expected"), + .package = "openalexVectorComp" + ) + testthat::expect_identical(out$submitted_rows, 0L) +}) diff --git a/tests/testthat/test-plot-embeddings.R b/tests/testthat/test-plot-embeddings.R index ed3ef1b..e8005ed 100644 --- a/tests/testthat/test-plot-embeddings.R +++ b/tests/testthat/test-plot-embeddings.R @@ -126,3 +126,14 @@ testthat::test_that("plot embedding functions validate id csv schema and embeddi "No embedding columns" ) }) + +testthat::test_that("plot_embeddings_umap errors when no embedding columns exist", { + fx <- make_plot_embeddings_fixture() + no_v <- file.path(dirname(fx$emb_dir), "no_v") + dir.create(no_v) + arrow::write_parquet(data.frame(id = c("W1", "W2"), x = 1), file.path(no_v, "e.parquet")) + testthat::expect_error( + plot_embeddings_umap(embeddings = no_v, labels = fx$labels_csv), + "No embedding columns" + ) +}) From 3a13099569e354d00c0b9dd7f270865e50923d89 Mon Sep 17 00:00:00 2001 From: Rainer M Krug Date: Tue, 27 Oct 2026 19:02:00 +0100 Subject: [PATCH 4/6] fix: skip unchanged rows when delete_existing = FALSE embed_corpus() and .ovc_load_existing_hash() passed the label folder as the `schema` argument of arrow::open_dataset(), which always errored inside try(), so no existing hashes were loaded: every run re-embedded the whole corpus and batch_submit_openai() resubmitted embedded rows. - .ovc_load_existing_hash() opens model_dir/label=