From 8b92ce33a58f8482e405bee1ae765dff2205514b Mon Sep 17 00:00:00 2001 From: Jared Knowles Date: Thu, 12 Nov 2026 21:23:58 -0500 Subject: [PATCH] feat(corpus): cache the metadata tables by sha256 between sessions (#64) R/cache.R was a stub, so a remote session read the ten metadata tables (about 3 MB) over HTTP every time. cog_open() now keeps them in USCOGDATA_CACHE_DIR/corpus/ and points the metadata views there. A cached file is used only while its sha256 matches the session's manifest; a download is checked before it replaces anything. Any failure (an HTTP error such as Hugging Face's 429, a mismatch, an unwritable directory) falls back to remote reads with a message. A local corpus is read in place and never cached. The yearly partitions stay remote; cog_mirror() is still the tool for repeat work on them. Against the public corpus, 2026-11-12, one run each, fresh cache: session open 1.76 s cold -> 0.38 s warm first query 1.16 s cold -> 0.68 s warm cog_spending() for Madison (552025209777), 2012 and 2020, returns the same 46 rows and the same digest as main. Live-corpus tests pass. Closes #64 Co-Authored-By: Claude Opus 5.5 --- NEWS.md | 17 ++++ R/cache.R | 85 ++++++++++++++++- R/session.R | 3 +- R/views.R | 10 +- README.md | 2 +- tests/testthat/test-metadata-cache.R | 132 +++++++++++++++++++++++++++ 6 files changed, 238 insertions(+), 11 deletions(-) create mode 100644 tests/testthat/test-metadata-cache.R diff --git a/NEWS.md b/NEWS.md index 8e9b4f8..aa685f0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,22 @@ # uscogdata (development version) +## Faster sessions on the remote corpus + +Opening a session against the public corpus took about 5.6 seconds. It now takes +about 1.8 seconds the first time and about 0.4 seconds after that (measured +2026-11-12, one run each). Two changes do it: + +- A session keeps the HTTP file details it has already requested instead of asking + again for every view and query. A repeated query in the same session drops from + about 0.55 seconds to 0.02. +- The ten metadata tables, about 3 MB, are kept in `USCOGDATA_CACHE_DIR` and used + only while their SHA-256 matches the manifest. A republished corpus is picked up + when the manifest is, and if a download fails or does not match, the session reads + the tables remotely as before. + +The yearly data files are still read remotely. For repeat work on them, +`cog_mirror()` remains the fastest option. Results are unchanged. + ## Fiscal-year periods for each row `year` is the Census survey year, and a survey year covers different months for diff --git a/R/cache.R b/R/cache.R index cd3a3e8..2ff9bc6 100644 --- a/R/cache.R +++ b/R/cache.R @@ -1,6 +1,81 @@ # R/cache.R -# Local partition cache; SHA-based invalidation. -# Phase N v0.1 implementation: DuckDB httpfs handles actual reads directly -# from Nextcloud; cache_dir holds only manifest.json. Richer partition -# caching (pre-fetch hot partitions) is a v0.2 feature. -# Stub here for cog_mirror to compose against. +# +# Metadata-table cache for a remote corpus (#64). +# +# Every view over a metadata table (summary_categories, canonical_fips_xwalk, +# code_set and the rest: about 3 MB in all) used to read it over HTTP in +# every session. Keeping those tables in the cache directory, checked against +# the manifest's sha256, cut session open from 1.7 s to 0.4 s against the +# public corpus (2026-11-12, one run per arm). The long partitions stay +# remote; for repeat work on them, cog_mirror() is the tool. +# +# A cached file is used only when its sha256 matches the session's manifest, +# so a republished corpus is picked up as soon as the manifest is. Anything +# that goes wrong falls back to reading every table remotely, as before. + +#' Keep the corpus's metadata tables in `cache_dir`, verified by sha256. +#' +#' @param url Corpus root (ends in "/"). +#' @param manifest Parsed manifest for `url`. +#' @param cache_dir The session's cache directory. +#' @param fetch `function(src, dest)` that writes the file at URL `src` to +#' path `dest`. Injectable so the remote path can be tested offline. +#' @return The base the metadata views should read from: a local directory +#' ending in "/" when every table is cached and verified, otherwise `url`. +#' @noRd +.cache_metadata_tables <- function(url, manifest, cache_dir, + fetch = .fetch_to_file) { + if (.is_local_path(url)) return(url) + entries <- manifest$files$metadata + if (length(entries) == 0L) return(url) + shas <- vapply(entries, function(e) e$sha256 %||% NA_character_, character(1)) + if (anyNA(shas)) return(url) + + base <- file.path(cache_dir, "corpus") + for (e in entries) { + problem <- .cache_one_table(paste0(url, e$path), file.path(base, e$path), + e$sha256, fetch) + if (!is.null(problem)) { + cli::cli_inform(c( + "!" = "Reading metadata tables remotely this session: {problem}" + )) + return(url) + } + } + paste0(normalizePath(base, winslash = "/"), "/") +} + +#' Make `dest` a verified copy of `src`. Returns NULL on success, or a +#' one-line description of what went wrong. A download is written beside +#' `dest` and moved into place only once its sha256 matches, so an +#' unverified file is never left where a later session would read it. +#' @noRd +.cache_one_table <- function(src, dest, sha, fetch) { + if (file.exists(dest) && + digest::digest(dest, algo = "sha256", file = TRUE) == sha) { + return(NULL) + } + dir.create(dirname(dest), recursive = TRUE, showWarnings = FALSE) + tmp <- paste0(dest, ".tmp.", Sys.getpid()) + on.exit(unlink(tmp), add = TRUE) + err <- tryCatch({ fetch(src, tmp); NULL }, + error = function(e) conditionMessage(e)) + if (!is.null(err)) return(sprintf("%s: %s", basename(dest), err)) + if (!file.exists(tmp) || + digest::digest(tmp, algo = "sha256", file = TRUE) != sha) { + return(sprintf("%s did not match its sha256 in the manifest", + basename(dest))) + } + if (!file.rename(tmp, dest)) { + return(sprintf("could not write %s", dest)) + } + NULL +} + +#' @noRd +.fetch_to_file <- function(src, dest) { + httr2::request(src) |> + httr2::req_error(is_error = function(r) httr2::resp_status(r) >= 400) |> + httr2::req_perform(path = dest) + invisible(dest) +} diff --git a/R/session.R b/R/session.R index ff7f53a..e1a1049 100644 --- a/R/session.R +++ b/R/session.R @@ -32,7 +32,8 @@ cog_open <- function(url = .resolve_url(), .validate_schema(manifest, supported = c(4L, 5L, 6L, 7L)) .validate_scope(manifest) - .register_views(con, url, manifest) + meta_url <- .cache_metadata_tables(url, manifest, cache_dir) + .register_views(con, url, manifest, meta_url = meta_url) .uscogdata_env$con <- con .uscogdata_env$manifest <- manifest diff --git a/R/views.R b/R/views.R index 0433ebc..f2050b9 100644 --- a/R/views.R +++ b/R/views.R @@ -138,14 +138,16 @@ #' lived in the original `{url}` substitution, unnoticed because nothing ever #' ran on Windows until the mirror's check matrix existed. #' @noRd -.render_view_sql <- function(sql, url, manifest = list()) { +.render_view_sql <- function(sql, url, manifest = list(), meta_url = url) { sql <- gsub("{long_files}", .long_files_sql(url, manifest), sql, fixed = TRUE) - gsub("{url}", url, sql, fixed = TRUE) + # {url} appears only in the metadata-table views, so `meta_url` can point + # them at the local cache (#64) while {long_files} stays on the corpus. + gsub("{url}", meta_url, sql, fixed = TRUE) } #' Register DuckDB views from inst/sql/ SQL files #' @noRd -.register_views <- function(con, url, manifest) { +.register_views <- function(con, url, manifest, meta_url = url) { sql_dir <- system.file("sql", package = "uscogdata") files <- sort(list.files(sql_dir, pattern = "\\.sql$", full.names = TRUE)) schema_version <- suppressWarnings(as.integer(manifest$schema_version %||% 0L)) @@ -156,7 +158,7 @@ !.corpus_has_table(manifest, .representation_view_files[[base]])) next if (base %in% .balance_view_files && !.corpus_has_balance_subtype(con)) next sql <- paste(readLines(f, warn = FALSE), collapse = "\n") - sql <- .render_view_sql(sql, url, manifest) + sql <- .render_view_sql(sql, url, manifest, meta_url = meta_url) DBI::dbExecute(con, sql) } } diff --git a/README.md b/README.md index 9b19cb6..a2da36c 100644 --- a/README.md +++ b/README.md @@ -133,7 +133,7 @@ After that, nothing in your analysis touches an external service. ### Configuration - `USCOGDATA_URL` — corpus root: an HTTPS URL or a local path, **trailing slash required** -- `USCOGDATA_CACHE_DIR` — where the manifest is cached (default: user cache dir) +- `USCOGDATA_CACHE_DIR` — where the manifest and the corpus's metadata tables (about 3 MB) are cached (default: user cache dir) - `USCOGDATA_MANIFEST_TTL_SECS` — manifest re-fetch interval (default 3600) - `USCOGDATA_DUCKDB_THREADS` — cap DuckDB's thread count (default: every visible core) - `USCOGDATA_DUCKDB_MEMORY_LIMIT` — cap DuckDB's memory, e.g. `"4GB"` (default: DuckDB's own) diff --git a/tests/testthat/test-metadata-cache.R b/tests/testthat/test-metadata-cache.R new file mode 100644 index 0000000..5a0afea --- /dev/null +++ b/tests/testthat/test-metadata-cache.R @@ -0,0 +1,132 @@ +# tests/testthat/test-metadata-cache.R +# +# uscogdata#64. On the remote path the ten metadata tables (about 3 MB) were +# read over HTTP every session. Kept in the cache directory and checked +# against the manifest's sha256, they cut session open from 1.7 s to 0.4 s +# against the public corpus (2026-11-12, one run per arm). +# +# The fixture is local, and a local corpus is never cached. These tests treat +# the fixture as if it were remote by handing .cache_metadata_tables() a +# fetch function that copies from it, so they run offline. + +fake_remote <- "https://example.invalid/corpus/" + +# A fetch that serves the fixture's bytes for the fake remote URL, and counts +# its calls. +counting_fetch <- function() { + env <- new.env(); env$n <- 0L + env$fetch <- function(src, dest) { + env$n <- env$n + 1L + rel <- sub(fake_remote, "", src, fixed = TRUE) + stopifnot(file.copy(file.path(fixture_corpus_path(), rel), dest, + overwrite = TRUE)) + } + env +} + +fixture_manifest <- function() { + jsonlite::fromJSON(file.path(fixture_corpus_path(), "manifest.json"), + simplifyVector = FALSE) +} + +test_that("a local corpus is read in place, never cached (#64)", { + skip_if_no_corpus() + cd <- withr::local_tempdir() + url <- paste0(fixture_corpus_path(), "/") + expect_identical(.cache_metadata_tables(url, fixture_manifest(), cd), url) + expect_false(dir.exists(file.path(cd, "corpus"))) +}) + +test_that("remote metadata tables are cached and verified (#64)", { + skip_if_no_corpus() + cd <- withr::local_tempdir() + m <- fixture_manifest() + f <- counting_fetch() + base <- .cache_metadata_tables(fake_remote, m, cd, fetch = f$fetch) + expect_false(identical(base, fake_remote)) + expect_match(base, "/$") + expect_equal(f$n, length(m$files$metadata)) + for (e in m$files$metadata) { + p <- file.path(cd, "corpus", e$path) + expect_true(file.exists(p), info = e$path) + expect_equal(digest::digest(p, algo = "sha256", file = TRUE), e$sha256) + } + + # Second session: nothing fetched. + expect_identical(.cache_metadata_tables(fake_remote, m, cd, fetch = f$fetch), + base) + expect_equal(f$n, length(m$files$metadata)) +}) + +test_that("a cached file that no longer matches the manifest is fetched again (#64)", { + skip_if_no_corpus() + cd <- withr::local_tempdir() + m <- fixture_manifest() + f <- counting_fetch() + .cache_metadata_tables(fake_remote, m, cd, fetch = f$fetch) + writeLines("stale", file.path(cd, "corpus", m$files$metadata[[1]]$path)) + .cache_metadata_tables(fake_remote, m, cd, fetch = f$fetch) + expect_equal(f$n, length(m$files$metadata) + 1L) + p <- file.path(cd, "corpus", m$files$metadata[[1]]$path) + expect_equal(digest::digest(p, algo = "sha256", file = TRUE), + m$files$metadata[[1]]$sha256) +}) + +test_that("a download that fails its sha256 check falls back to remote (#64)", { + skip_if_no_corpus() + cd <- withr::local_tempdir() + m <- fixture_manifest() + bad_fetch <- function(src, dest) writeLines("not parquet", dest) + expect_message( + base <- .cache_metadata_tables(fake_remote, m, cd, fetch = bad_fetch), + "sha256" + ) + expect_identical(base, fake_remote) + # Nothing unverified is left where a later session would find it. + left <- list.files(file.path(cd, "corpus"), recursive = TRUE) + expect_length(left, 0L) +}) + +test_that("a failed download falls back to remote (#64)", { + skip_if_no_corpus() + cd <- withr::local_tempdir() + err_fetch <- function(src, dest) stop("HTTP 429 Too Many Requests") + expect_message( + base <- .cache_metadata_tables(fake_remote, fixture_manifest(), cd, + fetch = err_fetch), + "429" + ) + expect_identical(base, fake_remote) +}) + +test_that("a manifest entry without a sha256 disables the cache (#64)", { + skip_if_no_corpus() + cd <- withr::local_tempdir() + m <- fixture_manifest() + m$files$metadata[[1]]$sha256 <- NULL + f <- counting_fetch() + expect_identical(.cache_metadata_tables(fake_remote, m, cd, fetch = f$fetch), + fake_remote) + expect_equal(f$n, 0L) +}) + +test_that("views read metadata from the cache and partitions from the corpus (#64)", { + skip_if_no_corpus() + cd <- withr::local_tempdir() + m <- fixture_manifest() + meta <- .cache_metadata_tables(fake_remote, m, cd, + fetch = counting_fetch()$fetch) + url <- paste0(fixture_corpus_path(), "/") + con <- DBI::dbConnect(duckdb::duckdb()) + on.exit(DBI::dbDisconnect(con, shutdown = TRUE), add = TRUE) + .register_views(con, url, m, meta_url = meta) + + sql_of <- function(view) DBI::dbGetQuery(con, sprintf( + "SELECT sql FROM duckdb_views() WHERE view_name = '%s'", view))$sql + expect_match(sql_of("summary_categories"), + file.path(normalizePath(cd, winslash = "/"), "corpus"), + fixed = TRUE) + expect_match(sql_of("long"), fixture_corpus_path(), fixed = TRUE) + n <- DBI::dbGetQuery(con, "SELECT COUNT(*) AS n FROM spending_long")$n + expect_gt(n, 0) +})