Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Package: openalexVectorComp
Type: Package
Title: Embedding Vectorization and Distance-Based Scoring Workflows
Version: 0.3.4
Version: 0.3.5
Authors@R: c(
person(given = "Rainer M", family = "Krug", role = c("aut", "cre"), email = "Rainer@krugs.de"),
person(given = "ChatGPT", family = "Assistant", role = "ctb")
Expand Down
28 changes: 28 additions & 0 deletions DEVELOPMENT_CONTINUITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,34 @@ Template:
- Impact: Cleaner workspace structure; updated README examples.
- Follow-up tasks: ensure any automation scripts assume new defaults.

- Date: 2026-10-27
- Scope: Skipping unchanged rows with `delete_existing = FALSE`
(`embed_corpus()`, `batch_submit_openai()`, `batch_collect_openai()`)
- Decision: Both read existing hashes through `.ovc_load_existing_hash()`,
which opens `model_dir/label=<label>` directly. `embed_corpus()` appends
new shards after the existing ones (`.ovc_next_embed_batch_index()`), like
`batch_collect_openai()`. After writing, both call
`.ovc_prune_superseded_rows()`, which removes from older `batch=<n>`
shards every id present in a newer shard (deleting emptied shard files and
folders), so each id is stored once per label folder. The prune covers all
shards, so it also removes duplicates left by earlier versions.
`.ovc_load_existing_hash()` still prefers the newest shard's hash as a
safety net for folders not yet pruned.
- Why: The label was passed as the `schema` argument of `open_dataset()`, so
no hashes were ever loaded and everything was re-embedded / resubmitted.
Once skipping works, restarting at `batch=1` would overwrite unchanged
rows, and keeping old rows would give downstream distance/score functions
duplicate ids.
- Alternatives considered: rewriting the whole label partition on each run
(rejected: re-embeds everything); keeping superseded rows and
de-duplicating in every reader (rejected: the user chose removal).
- Impact: Re-runs only embed new/changed rows; each id appears once per
label. Write first, prune after: an interruption leaves at most a
temporary duplicate, never a lost embedding. Pruned shards are replaced
via a temporary file plus rename.
- Follow-up tasks: the prune reads the `id` column of every shard on each
write run; revisit if label folders grow very large.

## 5. Pre-Commit Update Checklist (Required)

Before committing, update this file:
Expand Down
24 changes: 24 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
# openalexVectorComp news

## 0.3.5

### Bug Fixes

- With `delete_existing = FALSE`, `embed_corpus()` and
`batch_submit_openai()` are supposed to skip rows that already have
embeddings with the same text hash. They never did: the existing
embeddings were opened with the label folder passed as the `schema`
argument of `arrow::open_dataset()`, which always failed silently. As a
result every run re-embedded the whole corpus, and `batch_submit_openai()`
resubmitted already-embedded rows as new (paid) OpenAI batch jobs. The
existing `label=<label>` folder is now read correctly and unchanged rows
are skipped.
- When a row's text has changed and it is embedded again, its old row is
now removed, so each id appears exactly once per `label=<label>` folder
and distance and score functions no longer see duplicate ids. This applies
to `embed_corpus()` with `delete_existing = FALSE` and to
`batch_collect_openai()`. New rows are written to a new `batch=<n>` folder
first (`embed_corpus()` no longer restarts at `batch=1`, which would have
overwritten unchanged rows); only then are the old rows removed from older
shards. Shards and `batch=` folders left empty are deleted. Duplicates left
by earlier versions are cleaned up the next time new embeddings are written
to that label.

## 0.3.4

### Bug Fixes
Expand Down
1 change: 1 addition & 0 deletions R/batch_collect_openai.R
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ batch_collect_openai <- function(
}

.ovc_openai_state_write(state_file, state)
if (downloaded_jobs > 0L) .ovc_prune_superseded_rows(label_dir)

if (verbose) {
if (downloaded_jobs == 0L) {
Expand Down
43 changes: 40 additions & 3 deletions R/batch_openai_helpers.R
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,7 @@
existing_hash <- stats::setNames(character(), character())
idx_ds <- try(
arrow::open_dataset(
model_dir,
paste0("label=", label_part),
file.path(model_dir, paste0("label=", label_part)),
factory_options = list(exclude_invalid_files = TRUE)
),
silent = TRUE
Expand All @@ -160,12 +159,18 @@
if (is.null(hash_col) || !"id" %in% idx_cols) return(existing_hash)

idx_df <- idx_ds |>
dplyr::select(id, dplyr::all_of(hash_col)) |>
dplyr::select(id, dplyr::all_of(hash_col), dplyr::any_of("batch")) |>
dplyr::collect()
if (!nrow(idx_df)) return(existing_hash)

names(idx_df)[2] <- "text_hash"
idx_df <- idx_df[!is.na(idx_df$id) & !is.na(idx_df$text_hash), , drop = FALSE]
# Writers prune superseded rows, but folders from older versions or an
# interrupted prune can still hold duplicates: keep the newest shard's hash.
if ("batch" %in% names(idx_df)) {
idx_df <- idx_df[order(idx_df$batch), , drop = FALSE]
idx_df <- idx_df[!duplicated(idx_df$id, fromLast = TRUE), , drop = FALSE]
}
if (!nrow(idx_df)) return(existing_hash)
stats::setNames(as.character(idx_df$text_hash), as.character(idx_df$id))
}
Expand Down Expand Up @@ -407,3 +412,35 @@
if (!length(nums)) return(1L)
as.integer(max(nums) + 1L)
}

# Keep each id once per label folder: drop rows from older batch=<n> shards
# whose id also appears in a newer shard (newest wins), deleting shard files and
# batch= folders that end up empty. Call only after new shards are written, so
# an interruption leaves at most a temporary duplicate, never a lost embedding.
# ponytail: reads the id column of every shard on each write run; index ids if
# label folders grow to many large shards.
.ovc_prune_superseded_rows <- function(label_dir) {
b <- list.dirs(label_dir, full.names = FALSE, recursive = FALSE)
b <- b[grepl("^batch=[0-9]+$", b)]
if (length(b) < 2L) return(invisible(NULL))
b <- b[order(as.integer(sub("^batch=", "", b)), decreasing = TRUE)]
seen <- character()
for (d in file.path(label_dir, b)) {
for (f in list.files(d, pattern = "[.]parquet$", full.names = TRUE)) {
ids <- as.character(arrow::read_parquet(f, col_select = "id")$id)
drop <- ids %in% seen
seen <- union(seen, ids)
if (!any(drop)) next
if (all(drop)) {
unlink(f)
next
}
tmp <- file.path(d, paste0(".", basename(f), ".tmp"))
tbl <- arrow::read_parquet(f, as_data_frame = FALSE)
arrow::write_parquet(tbl[!drop, ], tmp)
if (!file.rename(tmp, f)) stop("Could not replace pruned shard: ", f)
}
if (!length(list.files(d, all.files = TRUE, no.. = TRUE))) unlink(d, recursive = TRUE)
}
invisible(NULL)
}
34 changes: 8 additions & 26 deletions R/embed_corpus.R
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ embed_corpus <- function(

total_rows <- nrow(ds)
no_shards <- ceiling(total_rows / batch_size)
shard_idx <- 0L
shard_idx <- shard_offset <- 0L
embedded_rows <- 0L
skipped_rows <- 0L

Expand All @@ -178,30 +178,9 @@ embed_corpus <- function(

existing_hash <- stats::setNames(character(), character())
if (!delete_existing) {
idx_ds <- try(
arrow::open_dataset(
model_dir,
paste0("label=", label_part),
factory_options = list(exclude_invalid_files = TRUE)
),
silent = TRUE
)
if (!inherits(idx_ds, "try-error")) {
idx_cols <- names(idx_ds)
hash_col <- if ("text_hash" %in% idx_cols) "text_hash" else if ("hash" %in% idx_cols) "hash" else NULL
if (!is.null(hash_col) && "id" %in% idx_cols) {
idx_df <- idx_ds |>
dplyr::select(id, dplyr::all_of(hash_col)) |>
dplyr::collect()
if (nrow(idx_df)) {
names(idx_df)[2] <- "text_hash"
idx_df <- idx_df[!is.na(idx_df$id) & !is.na(idx_df$text_hash), , drop = FALSE]
if (nrow(idx_df)) {
existing_hash <- stats::setNames(as.character(idx_df$text_hash), as.character(idx_df$id))
}
}
}
}
existing_hash <- .ovc_load_existing_hash(model_dir = model_dir, label_part = label_part)
# Append new shards after existing ones instead of overwriting batch=1..n.
shard_idx <- shard_offset <- .ovc_next_embed_batch_index(label_dir) - 1L
}

progress_id <- NULL
Expand Down Expand Up @@ -370,6 +349,9 @@ embed_corpus <- function(
if (!is.null(progress_id)) {
cli::cli_progress_done(id = progress_id)
}
if (!delete_existing && shard_idx > shard_offset) {
.ovc_prune_superseded_rows(label_dir)
}
if (isTRUE(dry_run) && length(dry_run_preview)) {
preview_all <- do.call(rbind, dry_run_preview)
arrow::write_parquet(preview_all, dry_run_file)
Expand All @@ -388,7 +370,7 @@ embed_corpus <- function(
"Done! Embedded %d new/changed works, skipped %d unchanged rows, wrote %d batches in %s.",
embedded_rows,
skipped_rows,
shard_idx,
shard_idx - shard_offset,
format(elapsed, digits = 2)
))
}
Expand Down
44 changes: 21 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,48 +1,46 @@
[![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`).
- Scoring: **prototype cosine-distance** + **reference-area ridge score**
(`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

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

Expand Down
19 changes: 19 additions & 0 deletions tests/testthat/helper-offline.R
Original file line number Diff line number Diff line change
@@ -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")
Loading
Loading