Compare commits

..
5 Commits
Author SHA1 Message Date
jaredandClaude Opus 5.5 903c896ffc docs: record session (#84) [review-followup]
Mirror to GitHub / mirror (push) Successful in 21s
R-CMD-check / check (push) Successful in 4m6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 10:42:05 -05:00
jaredandClaude Opus 5.5 441bfb2b70 docs: record session (#64) [review-followup]
Mirror to GitHub / mirror (push) Successful in 9s
R-CMD-check / check (push) Successful in 4m0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 08:09:49 -05:00
jared dfb5b4c711 Merge pull request 'perf(corpus): faster remote sessions, with metadata tables cached by sha256 (#64)' (#82) from perf/remote-metadata-cache-64 into main
Mirror to GitHub / mirror (push) Failing after 5s
R-CMD-check / check (push) Successful in 3m46s
2026-11-12 21:49:44 -05:00
jaredandClaude Opus 5.5 8b92ce33a5 feat(corpus): cache the metadata tables by sha256 between sessions (#64)
R-CMD-check / check (push) Successful in 5m9s
R-CMD-check / check (pull_request) Successful in 4m53s
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>
2026-11-12 21:23:58 -05:00
jaredandClaude Opus 5.5 455ae2f177 perf(corpus): cache HTTP file metadata for the life of a session (#64)
On the remote path every CREATE VIEW and every query re-requested the same
file metadata over HTTP. Against the public Hugging Face corpus on 2026-11-12
(one run per arm, from this Mac), turning on DuckDB's
enable_http_metadata_cache moved:

  session open             5.6 s -> 1.6 s
  first one-year query     1.2 s -> 0.8 s
  same query again         0.55 s -> 0.02 s

parquet_metadata_cache alone changed nothing measurable, so it stays off.
The cache is per connection, so nothing persists between sessions; that half
of #64 is still open. Live-corpus tests pass with the setting on.

Refs #64

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:54:37 -05:00
9 changed files with 289 additions and 26 deletions

No files matched your search

+17
View File
@@ -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
+80 -5
View File
@@ -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)
}
+9 -1
View File
@@ -20,12 +20,20 @@ cog_open <- function(url = .resolve_url(),
# a remote read should already be bound by whatever budget the operator set.
.apply_duckdb_limits(con, threads, memory_limit)
DBI::dbExecute(con, "INSTALL httpfs; LOAD httpfs;")
# Remote path: without this, every CREATE VIEW in .register_views() and
# every query re-requests the same file metadata over HTTP -- about 4 s of
# a 5.6 s session open against the public corpus (#64). The cache lives as
# long as the connection; cog_close() discards it. A corpus republished
# mid-session is not picked up until then, which matches the manifest,
# already fixed for the session.
DBI::dbExecute(con, "SET enable_http_metadata_cache = true")
manifest <- .fetch_or_cache_manifest(url, cache_dir)
.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
+6 -4
View File
@@ -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)
}
}
+1 -1
View File
@@ -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)
+12
View File
@@ -13,6 +13,18 @@ file carries the reasoning and the pointers.
---
## 2026-11-12 · corpus · remote sessions open in 0.4 s; fixture docs tracked; 8 names recovered upstream
**Why:** Every remote session re-requested the same file metadata and re-read the same 3 MB of metadata tables. Caching both, with the tables checked against the manifest's sha256, cut session open from 5.6 s to 0.4 s after the first session. The missing names are Census's own placeholder, so the fix, and the record of the 58 that can't be fixed, live in the pipeline.
**Obligates:** #83, #76 (waits on the next corpus publish)
**Refs:** #73, #64, 1ff6fe8, 455ae2f, 8b92ce3, census_of_governments_finance_pipeline#156 and its decision 0008
## 2026-11-04 · api · fiscal-year periods on the verbs; coverage suggestions exported (recorded 2026-11-12)
**Why:** A survey year runs up to 18 months ahead of the calendar for some governments, so `nss_time` couldn't place events against a series without knowing which months each row covers. FY1993 has no fiscal-year end for 99% of governments, and that gap is already in the Census file.
**Obligates:** #77 (the cog-api half), census_of_governments_finance_pipeline#129
**Refs:** #72, #75, #77, #78, #79, #80, b6b3e46, dc93eec, GitHub PRs 1–6
## 2026-09-30 · repo · moved out of Nextcloud; code syncs only through Gitea
**Why:** Nextcloud was syncing this repo's `.git`, which risks conflict copies inside
+9 -15
View File
@@ -7,20 +7,14 @@
## Where this stands
uscogdata's code now lives only in Gitea; the old Nextcloud folder keeps just build
output and working files. The move changed no test result: 1,101 pass and the two
opt-in live-corpus tests skip, before and after. It turned up one defect, #73: the
fixture's reference docs have never been in git, because a `.gitignore` rule matches
too broadly. Next in line are #73 and #72 (a vignette for the coverage counters), with
#52 (data-correction intake) and #74 (the stale state section in `CLAUDE.md`) waiting
on a decision.
uscogdata reads the public Census of Governments finance corpus from R. A remote session now opens in under half a second after the first, because the package keeps the small metadata tables on disk and checks them against the manifest. Heavy work is still fastest through `cog_mirror()`, which doesn't yet check what it downloads (#83). Rows can carry the months each survey year covers; the cog-api half of that (#77) is still open. The corpus published on Nov 13 gives six formerly unnamed governments their names, and 60 keep Census's "NOT AVAILABLE".
## Ready to work on next
- **#73** The fixture corpus's docs/ never reaches git: .gitignore's docs/ rule is unanchored · `ws/corpus` — nothing is blocking it; something is currently wrong
- **#72** docs: add a vignette explaining provenance$coverage counters · `ws/docs` — nothing is blocking it; owed work from an earlier change
- **#83** cog_mirror() records a file as downloaded without checking its sha256 · `ws/corpus` — nothing is blocking it; something is currently wrong
- **#84** Low findings from the Nov 4 reviews: version-pinned messages, unstated vintages, cog_suggestions() edges · `ws/api` — nothing is blocking it; owed work from an earlier change
- **#2** Extend population data to be households as an alternate spending denominator · `ws/corpus` — nothing is blocking it
- **#64** Partition-level caching: R/cache.R is still a stub, and the remote path pays for it every session · `ws/corpus` — nothing is blocking it
- **#77** Expose fiscal-year timing: what months each survey year covers, per government · `ws/api` — nothing is blocking it
- **#74** CLAUDE.md's Current State section is frozen at 2026-08-03 · `ws/docs` — waiting on a person, not on other work
- **#52** Release 11/11: design the data-correction intake (deferred; gates the API announcement) · `ws/corpus` — waiting on a person, not on other work
@@ -28,9 +22,9 @@ on a decision.
| Stream | Commits since | Open | Debt | Owes docs |
|---|---|---|---|---|
| Query verbs and results | 0 | 0 | 0 | no |
| Corpus, mirror, provenance | 0 | 4 | 0 | no |
| Vignettes and guides | 0 | 2 | 2 | no |
| Query verbs and results | 0 | 2 | 1 | no |
| Corpus, mirror, provenance | 0 | 3 | 0 | no |
| Vignettes and guides | 0 | 1 | 1 | no |
## CI
@@ -42,8 +36,8 @@ on a decision.
_Nothing blocks anything else, so there is no graph to draw._
- Marker: `9adb9211` (2026-09-09)
- Commits since: 3
- Marker: `441bfb2b` (2026-11-13)
- Commits since: 0
- Open issues: 6
</details>
+23
View File
@@ -0,0 +1,23 @@
# tests/testthat/test-http-metadata-cache.R
#
# uscogdata#64. On the remote path every CREATE VIEW re-requested the same
# file metadata over HTTP: 23 views at about 0.35 s each made session open
# take about 6 s against the public corpus. DuckDB's HTTP metadata cache keeps
# those responses for the life of the connection. Measured on 2026-11-12
# against the Hugging Face corpus, one run per arm: session open 5.6 s ->
# 1.6 s, first one-year query 1.2 s -> 0.8 s, the same query again
# 0.55 s -> 0.02 s.
#
# The fixture is local, so these tests can only check that the setting is on,
# not that it saves anything.
test_that("cog_open() turns on DuckDB's HTTP metadata cache (#64)", {
skip_if_no_corpus()
uscogdata:::cog_close()
on.exit(uscogdata:::cog_close(), add = TRUE)
con <- uscogdata:::cog_open()
v <- DBI::dbGetQuery(
con, "SELECT current_setting('enable_http_metadata_cache') AS v"
)$v[[1]]
expect_true(isTRUE(as.logical(v)))
})
+132
View File
@@ -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)
})