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 <noreply@anthropic.com>
This commit is contained in:
6 files changed
+238
-11
No files matched your search
@@ -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)
|
||||
}
|
||||
+2
-1
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user