//! `hazine comet`: import the COMET enrichments of DataCite records into the
//! lake, and point a stable `comet` schema at the newest import.
//!
//! COMET (Collaborative Metadata, <https://cometadata.org>) publishes its
//! enrichments on Hugging Face (CC0) as three JSON Lines files in DataCite's
//! enrichment ingest format, one line per change to one field of a DataCite
//! record: author affiliations, preprint matching and resource types. The
//! dataset has no releases, so a version is the dataset's latest commit that
//! changed a data file (`2026_02_06_6f4066e`): the README's edits don't make
//! one.
//!
//! `import` uses the files in commonmeta's cache (`~/.cache/commonmeta/comet`,
//! root's and the sudo user's) when they are that version's (by size), or
//! downloads them there. It converts each to Parquet, one row per line, and
//! stores the original files and the Parquet parts in the lake's bucket under
//! `sources/comet/<version>/`. It then creates a schema named after the
//! version (`comet_2026_02_06_6f4066e`) with the tables `enrichments` and
//! `release`. `setup` creates views in the `comet` schema on the tables of
//! the newest (or a chosen) version.
use std::collections::BTreeMap;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;
use arrow_schema::{DataType, Field, Fields, Schema};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_json::value::RawValue;
use crate::Error;
use crate::cache;
use crate::lake::{CSV, Limits, Runner, last_count, pairs};
use crate::parts::{Layout, Part, Parts};
use crate::s3::Bucket;
use crate::setup;
use crate::tempdir::TempDir;
/// The Hugging Face dataset.
pub const DATASET: &str = "cometadata/comet-datacite-enrichment-layer-ingest-format";
/// Its data files, by kind.
pub const FILES: [(&str, &str); 3] = [
(
"author_affiliations",
"author_affiliations_enrichments_datacite_format.jsonl",
),
(
"preprint_matching",
"preprint_matching_enrichments_datacite_format.jsonl",
),
(
"resource_type",
"resource_type_enrichments_datacite_format.jsonl",
),
];
/// The schema with views on the tables of the version in use.
pub const VIEW_SCHEMA: &str = "comet";
/// The prefix of the schemas holding one version each.
const RELEASE_PREFIX: &str = "comet_";
/// Where in the lake's bucket the original files and the Parquet parts go.
const SOURCES: &str = "sources/comet";
/// commonmeta's cache namespace for the files.
const CACHE: &str = "comet";
/// The tables of a version.
const ENRICHMENTS: &str = "enrichments";
const RELEASE: &str = "release";
/// Lines parsed at once, and per Parquet row group.
const BATCH: usize = 20_000;
/// Rows per Parquet part: a few hundred MB.
const PART_ROWS: u64 = 2_000_000;
/// Seconds a downloaded file stays in commonmeta's cache.
const CACHE_TTL: u64 = 400 * 24 * 60 * 60;
const LINUX_ONLY: &str = "hazine comet needs Linux (use --output to convert elsewhere)";
/// A version of the dataset: the date and the short id of the latest commit
/// that changed a data file.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Version {
/// `2026_02_06`
date: String,
/// `6f4066e`
commit: String,
}
impl Version {
/// From a commit's id and its ISO date.
fn new(commit: &str, date: &str) -> Result<Self, Error> {
let invalid = || Error::InvalidSetting {
name: "COMET version",
reason: format!("unexpected commit {commit:?} of {date:?}"),
};
let day = date.get(..10).ok_or_else(invalid)?;
let bytes = day.as_bytes();
let is_day = bytes.iter().enumerate().all(|(i, b)| match i {
4 | 7 => *b == b'-',
_ => b.is_ascii_digit(),
});
let short = commit.get(..7).ok_or_else(invalid)?;
if !is_day
|| !short
.bytes()
.all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase())
{
return Err(invalid());
}
Ok(Version {
date: day.replace('-', "_"),
commit: short.to_string(),
})
}
/// `2026_02_06_6f4066e`, as [`Version`] displays.
pub fn parse(value: &str) -> Result<Self, Error> {
let invalid = || Error::InvalidSetting {
name: "COMET version",
reason: format!("{value:?} is not like 2026_02_06_6f4066e"),
};
let (date, commit) = value.rsplit_once('_').ok_or_else(invalid)?;
Version::new(commit, &date.replace('_', "-")).map_err(|_| invalid())
}
fn from_schema(schema: &str) -> Option<Self> {
Version::parse(schema.strip_prefix(RELEASE_PREFIX)?).ok()
}
/// `comet_2026_02_06_6f4066e`.
pub fn schema(&self) -> String {
format!("{RELEASE_PREFIX}{self}")
}
}
impl std::fmt::Display for Version {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}_{}", self.date, self.commit)
}
}
/// A data file as the dataset has it now.
#[derive(Debug, Clone)]
struct RemoteFile {
kind: &'static str,
name: &'static str,
size: u64,
/// The latest commit that changed it.
commit: String,
date: String,
}
/// The dataset's current data files and its version.
#[derive(Debug, Clone)]
struct Revision {
version: Version,
/// The full id of the version's commit.
commit: String,
files: Vec<RemoteFile>,
}
#[derive(Deserialize)]
struct PathInfo {
path: String,
size: u64,
#[serde(rename = "lastCommit")]
last_commit: Option<LastCommit>,
}
#[derive(Deserialize)]
struct LastCommit {
id: String,
date: String,
}
/// The revision from Hugging Face's `paths-info` answer for [`FILES`].
fn parse_revision(json: &str) -> Result<Revision, Error> {
let invalid = |reason: String| Error::Import(format!("Hugging Face's file list: {reason}"));
let infos: Vec<PathInfo> = serde_json::from_str(json).map_err(|e| invalid(e.to_string()))?;
let mut files = Vec::new();
for (kind, name) in FILES {
let info = infos
.iter()
.find(|info| info.path == name)
.ok_or_else(|| invalid(format!("{name} is missing")))?;
let commit = info
.last_commit
.as_ref()
.ok_or_else(|| invalid(format!("{name} has no last commit")))?;
files.push(RemoteFile {
kind,
name,
size: info.size,
commit: commit.id.clone(),
date: commit.date.clone(),
});
}
let latest = files
.iter()
.max_by(|a, b| a.date.cmp(&b.date).then(a.commit.cmp(&b.commit)))
.expect("there are files");
Ok(Revision {
version: Version::new(&latest.commit, &latest.date)?,
commit: latest.commit.clone(),
files,
})
}
/// The dataset's current revision, from Hugging Face.
fn current_revision() -> Result<Revision, Error> {
let failed = |e: &dyn std::fmt::Display| {
Error::Import(format!("asking Hugging Face for {DATASET}: {e}"))
};
crate::tls::init();
let client = commonmeta::blocking_client_builder()
.user_agent(concat!("hazine/", env!("CARGO_PKG_VERSION")))
.build()
.map_err(|e| failed(&e))?;
let body = FILES
.iter()
.map(|(_, name)| format!("paths={name}"))
.chain(["expand=true".to_string()])
.collect::<Vec<_>>()
.join("&");
let json = client
.post(format!(
"https://huggingface.co/api/datasets/{DATASET}/paths-info/main"
))
.header("content-type", "application/x-www-form-urlencoded")
.body(body)
.send()
.and_then(|response| response.error_for_status())
.and_then(|response| response.text())
.map_err(|e| failed(&e))?;
parse_revision(&json)
}
/// A data file on this host.
#[derive(Debug, Clone)]
struct Local {
remote: RemoteFile,
path: PathBuf,
}
/// The revision's files: in `dir`, or in a cache, or (with `download`)
/// downloaded into commonmeta's cache. A file whose size isn't the
/// revision's is from another revision (or incomplete), and an error.
fn find_files(
revision: &Revision,
dir: Option<&Path>,
download: bool,
) -> Result<Option<Vec<Local>>, Error> {
let dirs = match dir {
Some(dir) => vec![dir.to_path_buf()],
None => cache::dirs(CACHE),
};
let mut found = Vec::new();
for remote in &revision.files {
let path = dirs
.iter()
.map(|dir| dir.join(remote.name))
.find(|path| path.is_file());
let path = match path {
Some(path) => path,
None if dir.is_some() => {
return Err(Error::InvalidSetting {
name: "--dir",
reason: format!("{} has no {}", dirs[0].display(), remote.name),
});
}
None if download => {
tracing::info!(
file = remote.name,
gb = format!("{:.1}", remote.size as f64 / 1e9),
"downloading from Hugging Face"
);
let url = format!(
"https://huggingface.co/datasets/{DATASET}/resolve/{}/{}",
remote.commit, remote.name
);
commonmeta::io_utils::ensure_cached_path(
&url,
CACHE,
remote.name,
std::time::Duration::from_secs(CACHE_TTL),
)
.map_err(|e| Error::Import(format!("downloading {}: {e}", remote.name)))?
.0
}
None => return Ok(None),
};
let size = std::fs::metadata(&path)?.len();
if size != remote.size {
return Err(Error::Import(format!(
"{} has {size} bytes, version {} has {}: from another version, or \
incomplete? Remove it to download it again",
path.display(),
revision.version,
remote.size
)));
}
found.push(Local {
remote: remote.clone(),
path,
});
}
Ok(Some(found))
}
/// A line of an ingest-format file. A key not listed here is an error, so
/// that a change of the format is noticed rather than lost.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Line<'a> {
doi: String,
#[serde(default)]
contributors: Option<Value>,
#[serde(default)]
resources: Option<Value>,
action: String,
field: String,
#[serde(default, borrow, rename = "originalValue")]
original: Option<&'a RawValue>,
#[serde(default, borrow, rename = "enrichedValue")]
enriched: Option<&'a RawValue>,
}
/// One Parquet row: a line, with the values it changes as JSON text,
/// unchanged.
#[derive(Debug, Serialize)]
struct Row<'a> {
kind: &'static str,
line: u64,
doi: String,
field: String,
action: String,
original_value: Option<&'a str>,
enriched_value: Option<&'a str>,
/// The DOI of the COMET project that made it (`IsDocumentedBy`).
project: Option<String>,
contributors: Option<Value>,
resources: Option<Value>,
}
fn row<'a>(kind: &'static str, line: u64, text: &'a str) -> Result<Row<'a>, String> {
let parsed: Line<'a> = serde_json::from_str(text).map_err(|e| format!("line {line}: {e}"))?;
let project = parsed
.resources
.as_ref()
.and_then(Value::as_array)
.and_then(|resources| {
resources
.iter()
.find(|r| r.get("relationType").and_then(Value::as_str) == Some("IsDocumentedBy"))
})
.and_then(|r| r.get("relatedIdentifier").and_then(Value::as_str))
.map(str::to_string);
Ok(Row {
kind,
line,
doi: parsed.doi,
field: parsed.field,
action: parsed.action,
original_value: parsed.original.map(RawValue::get),
enriched_value: parsed.enriched.map(RawValue::get),
project,
contributors: parsed.contributors,
resources: parsed.resources,
})
}
/// The Arrow schema of a row.
pub fn schema() -> Schema {
let utf8 = |name: &str| Field::new(name, DataType::Utf8, true);
let required = |name: &str| Field::new(name, DataType::Utf8, false);
let list_of = |name: &str, fields: Vec<Field>| {
Field::new(
name,
DataType::List(Arc::new(Field::new(
"item",
DataType::Struct(Fields::from(fields)),
true,
))),
true,
)
};
Schema::new(vec![
required("kind"),
Field::new("line", DataType::UInt64, false),
required("doi"),
required("field"),
required("action"),
utf8("original_value"),
utf8("enriched_value"),
utf8("project"),
list_of(
"contributors",
vec![utf8("name"), utf8("contributorType"), utf8("nameType")],
),
list_of(
"resources",
vec![
utf8("relatedIdentifier"),
utf8("relatedIdentifierType"),
utf8("relationType"),
utf8("resourceTypeGeneral"),
],
),
])
}
fn convert_error(error: impl std::fmt::Display) -> Error {
Error::Import(format!("converting the COMET enrichments: {error}"))
}
/// Convert the JSON Lines file at `path` (of `kind`) to Parquet parts in
/// `dir`, parsing on `threads` threads, and hand each finished part to
/// `on_part`; returns the number of rows. Empty lines are skipped; any other
/// line that isn't an enrichment is an error, as is a truncated last line.
pub fn convert(
path: &Path,
kind: &'static str,
dir: &Path,
version: &Version,
threads: usize,
on_part: impl FnMut(Part) -> Result<(), Error>,
) -> Result<u64, Error> {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(threads.max(1))
.build()
.map_err(convert_error)?;
let mut parts = Parts::new(
dir,
schema(),
Layout {
batch: BATCH,
part_rows: PART_ROWS,
metadata: vec![
("comet_version".into(), version.to_string()),
("comet_kind".into(), kind.to_string()),
],
},
"converting the COMET enrichments",
on_part,
)?;
let reader = BufReader::with_capacity(1 << 20, std::fs::File::open(path)?);
let mut chunk: Vec<(u64, String)> = Vec::with_capacity(BATCH);
let mut rows = 0u64;
let started = Instant::now();
let mut flush = |chunk: &mut Vec<(u64, String)>,
parts: &mut Parts<'_, _>|
-> Result<(), Error> {
let converted: Result<Vec<Row<'_>>, String> = pool.install(|| {
chunk
.par_iter()
.map(|(line, text)| row(kind, *line, text))
.collect()
});
let converted = converted.map_err(|e| convert_error(format!("{}: {e}", path.display())))?;
parts.write(&converted)?;
rows += converted.len() as u64;
chunk.clear();
if rows % (100 * BATCH as u64) == 0 {
tracing::info!(
kind,
rows,
per_s = format!("{:.0}", rows as f64 / started.elapsed().as_secs_f64()),
"converting"
);
}
Ok(())
};
for (index, text) in reader.lines().enumerate() {
let text = text.map_err(convert_error)?;
if text.trim().is_empty() {
continue;
}
chunk.push((index as u64 + 1, text));
if chunk.len() == BATCH {
flush(&mut chunk, &mut parts)?;
}
}
if !chunk.is_empty() {
flush(&mut chunk, &mut parts)?;
}
parts.finish()?;
Ok(rows)
}
fn sql_str(value: &str) -> String {
value.replace('\'', "''")
}
fn sql_list(urls: &[String]) -> String {
urls.iter()
.map(|url| format!("'{}'", sql_str(url)))
.collect::<Vec<_>>()
.join(",\n ")
}
/// What an import stored, for the `release` table.
struct Imported {
revision: Revision,
/// Rows by kind, in [`FILES`] order.
rows: Vec<(&'static str, u64)>,
source_files: Vec<String>,
part_files: Vec<String>,
}
/// SQL that (re)creates the version's tables from the uploaded parts in one
/// transaction, and prints the row count of `enrichments`.
fn import_sql(limits: &Limits, secret: &str, imported: &Imported) -> String {
let version = &imported.revision.version;
let schema = version.schema();
let parts = sql_list(&imported.part_files);
let counts = imported
.rows
.iter()
.map(|(kind, rows)| format!("{rows}::BIGINT AS {kind}"))
.collect::<Vec<_>>()
.join(",\n ");
let total: u64 = imported.rows.iter().map(|(_, rows)| rows).sum();
let date = version.date.replace('_', "-");
format!(
"{CSV}SET threads = {threads};\n\
SET memory_limit = '{memory}';\n\
SET preserve_insertion_order = false;\n\
SET temp_directory = '{home}/tmp';\n\
LOAD httpfs;\n\
{secret}\n\
CREATE SCHEMA IF NOT EXISTS {schema};\n\
BEGIN;\n\
DROP TABLE IF EXISTS {schema}.{ENRICHMENTS};\n\
DROP TABLE IF EXISTS {schema}.{RELEASE};\n\
CREATE TABLE {schema}.{ENRICHMENTS} AS\n \
SELECT * REPLACE (original_value::JSON AS original_value, enriched_value::JSON AS enriched_value)\n \
FROM read_parquet([\n {parts}\n ]);\n\
CREATE TABLE {schema}.{RELEASE} AS SELECT\n \
'{version}' AS version,\n \
'{commit}' AS commit,\n \
DATE '{date}' AS commit_date,\n \
'https://huggingface.co/datasets/{DATASET}' AS dataset,\n \
{total}::BIGINT AS records,\n \
{counts},\n \
[\n {sources}\n ] AS source_files,\n \
[\n {parts}\n ] AS parquet_files,\n \
now() AS imported_at;\n\
COMMIT;\n\
SELECT count(*) FROM {schema}.{ENRICHMENTS};\n",
threads = limits.threads,
memory = sql_str(&limits.memory_limit),
home = setup::HOME,
commit = sql_str(&imported.revision.commit),
sources = sql_list(&imported.source_files),
)
}
/// SQL that prints `schema,table` for every table in a version schema.
fn catalog_sql() -> String {
format!(
"{CSV}SELECT table_schema, table_name FROM information_schema.tables\n\
WHERE table_schema LIKE '{RELEASE_PREFIX}%' AND table_type = 'BASE TABLE';\n"
)
}
/// The complete versions in the catalog, newest first: those with their
/// `release` table, which the import creates with the data.
fn parse_catalog(output: &str) -> Vec<Version> {
let mut tables: BTreeMap<Version, Vec<String>> = BTreeMap::new();
for (schema, table) in pairs(output) {
if let Some(version) = Version::from_schema(&schema)
&& version.schema() == schema
{
tables.entry(version).or_default().push(table);
}
}
tables
.into_iter()
.rev()
.filter(|(_, tables)| tables.iter().any(|t| t == RELEASE))
.map(|(version, _)| version)
.collect()
}
/// SQL that points the views in [`VIEW_SCHEMA`] at `version`'s tables.
fn views_sql(version: &Version) -> String {
let schema = version.schema();
let mut sql = format!("BEGIN;\nCREATE SCHEMA IF NOT EXISTS {VIEW_SCHEMA};\n");
for table in [ENRICHMENTS, RELEASE] {
sql.push_str(&format!(
"CREATE OR REPLACE VIEW {VIEW_SCHEMA}.{table} AS FROM {schema}.{table};\n"
));
}
sql.push_str("COMMIT;\n");
sql
}
/// What `hazine comet import` was asked to do.
#[derive(Debug, Clone, Default)]
pub struct ImportOptions {
/// A directory with the three files; without, commonmeta's cache.
pub dir: Option<PathBuf>,
/// Import again, though this version is imported.
pub force: bool,
pub threads: Option<usize>,
pub memory_limit: Option<String>,
/// Only write the Parquet parts here; no lake.
pub output: Option<PathBuf>,
pub dry_run: bool,
}
/// `name.jsonl` without `.jsonl`: the directory of a file's parts.
fn stem(name: &str) -> &str {
name.strip_suffix(".jsonl").unwrap_or(name)
}
/// Import the current COMET enrichments into the lake. Blocking: call it in
/// `spawn_blocking` (the S3 client needs the Tokio runtime around it).
pub fn import(options: ImportOptions) -> Result<(), Error> {
let revision = current_revision()?;
let version = revision.version.clone();
let schema = version.schema();
tracing::info!(%version, commit = %revision.commit, %schema, "COMET enrichments");
if let Some(output) = &options.output {
let threads = Limits::threads(options.threads)?;
let files = find_files(&revision, options.dir.as_deref(), true)?
.expect("find_files downloads when asked to");
for local in &files {
let dir = output.join(stem(local.remote.name));
std::fs::create_dir_all(&dir)?;
let begun = Instant::now();
let rows = convert(
&local.path,
local.remote.kind,
&dir,
&version,
threads,
|part| {
tracing::info!(part = %part.path.display(), rows = part.rows, "wrote");
Ok(())
},
)?;
tracing::info!(
kind = local.remote.kind,
rows,
seconds = format!("{:.0}", begun.elapsed().as_secs_f64()),
"converted"
);
}
return Ok(());
}
if options.dry_run {
match find_files(&revision, options.dir.as_deref(), false)? {
Some(files) => {
for local in files {
println!(
"{:<20} {} ({:.2} GB)",
local.remote.kind,
local.path.display(),
local.remote.size as f64 / 1e9
);
}
}
None => println!("files: not all on this host; would download them from {DATASET}"),
}
println!(
"would store them and their Parquet parts in <bucket>/{SOURCES}/{version}/, \
and create {schema}.{ENRICHMENTS} and {schema}.{RELEASE}"
);
println!("then: hazine comet setup (views in the {VIEW_SCHEMA} schema)");
return Ok(());
}
let runner = Runner::service(LINUX_ONLY)?;
let limits = Limits::new(options.threads, options.memory_limit.clone())?;
if parse_catalog(&runner.run(true, &catalog_sql())?).contains(&version) && !options.force {
tracing::info!(%schema, "this version is imported already (--force imports it again)");
return Ok(());
}
let files = find_files(&revision, options.dir.as_deref(), true)?
.expect("find_files downloads when asked to");
let secret = crate::lake::installed_data_secret()?;
let bucket = Bucket::from_env(
|name| runner.env(name).map(str::to_string),
crate::lake::installed_use_ssl()?,
)?;
let prefix = format!("{SOURCES}/{version}");
let dir = TempDir::new_in(&Path::new(setup::HOME).join("tmp"))?;
let mut imported = Imported {
revision: revision.clone(),
rows: Vec::new(),
source_files: Vec::new(),
part_files: Vec::new(),
};
for local in &files {
let name = local.remote.name;
let kind = local.remote.kind;
tracing::info!(kind, file = %local.path.display(), threads = limits.threads, "converting");
let begun = Instant::now();
let part_files = &mut imported.part_files;
let rows = convert(
&local.path,
kind,
dir.path(),
&version,
limits.threads,
|part| {
let key = format!(
"{prefix}/{}/{}",
stem(name),
part.path
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default()
);
let size = bucket.upload(&part.path, &key)?;
verify_size(&bucket, &key, size)?;
std::fs::remove_file(&part.path)?;
tracing::info!(kind, part = part.index, rows = part.rows, to = %bucket.url(&key), "uploaded");
part_files.push(bucket.url(&key));
Ok(())
},
)?;
tracing::info!(
kind,
rows,
minutes = format!("{:.1}", begun.elapsed().as_secs_f64() / 60.0),
"converted"
);
imported.rows.push((kind, rows));
// The original, once the conversion has read all of it; unless it is
// stored already.
let key = format!("{prefix}/{name}");
if bucket.size(&key)? == Some(local.remote.size) {
tracing::info!(file = %bucket.url(&key), "the original is stored already");
} else {
tracing::info!(file = %local.path.display(), to = %bucket.url(&key), "uploading the original");
bucket.upload(&local.path, &key)?;
verify_size(&bucket, &key, local.remote.size)?;
}
imported.source_files.push(bucket.url(&key));
}
tracing::info!(%schema, parts = imported.part_files.len(), "creating the tables");
let expected: u64 = imported.rows.iter().map(|(_, rows)| rows).sum();
let output = runner.run(true, &import_sql(&limits, &secret, &imported))?;
let rows = last_count(&output);
if rows != Some(expected) {
return Err(Error::Import(format!(
"{schema}.{ENRICHMENTS} has {} rows, the files {expected}; rerun with --force",
rows.map_or("no".into(), |r| r.to_string()),
)));
}
tracing::info!(
%schema,
rows = expected,
"COMET enrichments imported; point the {VIEW_SCHEMA} views at them with: hazine comet setup"
);
Ok(())
}
/// The object at `key` has `size` bytes.
fn verify_size(bucket: &Bucket, key: &str, size: u64) -> Result<(), Error> {
match bucket.size(key)? {
Some(stored) if stored == size => Ok(()),
stored => Err(Error::Import(format!(
"{} has {} bytes after the upload, the file {size}",
bucket.url(key),
stored.map_or("no".into(), |s| s.to_string())
))),
}
}
/// What `hazine comet setup` was asked to do.
#[derive(Debug, Clone, Default)]
pub struct SetupOptions {
/// The version to use, e.g. `2026_02_06_6f4066e`; the newest imported
/// without.
pub release: Option<String>,
pub dry_run: bool,
}
/// Point the views in the `comet` schema at an imported version.
pub fn setup(options: SetupOptions) -> Result<(), Error> {
let runner = Runner::service(LINUX_ONLY)?;
let versions = parse_catalog(&runner.run(true, &catalog_sql())?);
let Some(newest) = versions.first() else {
return Err(Error::InvalidSetting {
name: "COMET",
reason: "no version is imported; run hazine comet import first".into(),
});
};
let version = match &options.release {
Some(wanted) => {
let wanted = Version::parse(wanted)?;
if !versions.contains(&wanted) {
return Err(Error::InvalidSetting {
name: "--release",
reason: format!(
"{wanted} is not imported; imported: {}",
versions
.iter()
.map(Version::to_string)
.collect::<Vec<_>>()
.join(", ")
),
});
}
wanted
}
None => newest.clone(),
};
let sql = views_sql(&version);
if options.dry_run {
print!("{sql}");
return Ok(());
}
runner.run(true, &sql)?;
tracing::info!(
%version,
schema = %version.schema(),
"the {VIEW_SCHEMA} schema now shows this version, e.g. FROM {VIEW_SCHEMA}.{ENRICHMENTS}"
);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn versions_are_data_commits() {
let v = Version::new(
"6f4066e9d22b2aa6a0c4d59805f8772d0d4b43a1",
"2026-02-06T06:04:46.000Z",
)
.unwrap();
assert_eq!(v.to_string(), "2026_02_06_6f4066e");
assert_eq!(v.schema(), "comet_2026_02_06_6f4066e");
assert_eq!(Version::parse("2026_02_06_6f4066e").unwrap(), v);
assert_eq!(
Version::from_schema("comet_2026_02_06_6f4066e"),
Some(v.clone())
);
assert!(Version::parse("2026_03_01_0000000").unwrap() > v);
for bad in [
"2026_02_06",
"2026_02_06_XYZ1234",
"6f4066e",
"2026_02_06_6f40",
] {
assert!(Version::parse(bad).is_err(), "{bad}");
}
assert_eq!(Version::from_schema("comet_scratch"), None);
}
const PATHS_INFO: &str = r#"[
{"type": "file", "size": 9406722616, "path": "author_affiliations_enrichments_datacite_format.jsonl",
"lastCommit": {"id": "6f4066e9d22b2aa6a0c4d59805f8772d0d4b43a1", "title": "Add", "date": "2026-02-06T06:04:46.000Z"}},
{"type": "file", "size": 551182843, "path": "preprint_matching_enrichments_datacite_format.jsonl",
"lastCommit": {"id": "912ca54b495ccf8b916c94d12a9410cd47c55884", "title": "Add", "date": "2026-02-06T05:58:13.000Z"}},
{"type": "file", "size": 2222148408, "path": "resource_type_enrichments_datacite_format.jsonl",
"lastCommit": {"id": "0a1b2c3d4e5f60718293a4b5c6d7e8f901234567", "title": "Add", "date": "2026-02-06T05:50:00.000Z"}}
]"#;
#[test]
fn the_version_is_the_latest_data_commit() {
let revision = parse_revision(PATHS_INFO).unwrap();
assert_eq!(revision.version.to_string(), "2026_02_06_6f4066e");
assert_eq!(revision.commit, "6f4066e9d22b2aa6a0c4d59805f8772d0d4b43a1");
assert_eq!(revision.files[1].kind, "preprint_matching");
assert_eq!(revision.files[1].size, 551182843);
assert!(parse_revision("[]").is_err(), "files missing");
}
#[test]
fn cached_files_must_be_the_versions() {
let dir = tempfile::tempdir().unwrap();
let mut revision = parse_revision(PATHS_INFO).unwrap();
for (file, size) in revision.files.iter_mut().zip([3u64, 4, 5]) {
file.size = size;
std::fs::write(dir.path().join(file.name), "x".repeat(size as usize)).unwrap();
}
let found = find_files(&revision, Some(dir.path()), false)
.unwrap()
.unwrap();
assert_eq!(found.len(), 3);
revision.files[2].size = 6;
assert!(
find_files(&revision, Some(dir.path()), false).is_err(),
"wrong size"
);
std::fs::remove_file(dir.path().join(FILES[0].1)).unwrap();
assert!(
find_files(&revision, Some(dir.path()), false).is_err(),
"missing in --dir"
);
}
const AFFILIATION: &str = r#"{"doi": "10.48550/arxiv.1109.3791", "contributors": [{"name": "COMET", "contributorType": "Producer", "nameType": "Organizational"}], "resources": [{"relatedIdentifier": "http://doi.org/10.82461/160e-8q92", "relatedIdentifierType": "DOI", "relationType": "IsDocumentedBy", "resourceTypeGeneral": "Project"}, {"relatedIdentifier": "https://huggingface.co/datasets/cometadata/arxiv-author-affiliations-matched-ror-ids", "relatedIdentifierType": "URL", "relationType": "IsDerivedFrom", "resourceTypeGeneral": "Dataset"}], "action": "updateChild", "field": "creators", "originalValue": {"nameType": "Personal", "givenName": "Fangfei", "familyName": "Zhou", "name": "Zhou, Fangfei"}, "enrichedValue": {"nameType": "Personal", "givenName": "Fangfei", "familyName": "Zhou", "name": "Zhou, Fangfei", "affiliation": [{"name": "Northeastern University"}]}}"#;
#[test]
fn lines_keep_their_values_as_json() {
let row = row("author_affiliations", 1, AFFILIATION).unwrap();
assert_eq!(row.doi, "10.48550/arxiv.1109.3791");
assert_eq!(
(row.field.as_str(), row.action.as_str()),
("creators", "updateChild")
);
assert_eq!(
row.project.as_deref(),
Some("http://doi.org/10.82461/160e-8q92")
);
assert_eq!(
row.original_value,
Some(
r#"{"nameType": "Personal", "givenName": "Fangfei", "familyName": "Zhou", "name": "Zhou, Fangfei"}"#
)
);
assert!(
row.enriched_value
.unwrap()
.contains("Northeastern University")
);
let insert = r#"{"doi": "10.1/x", "action": "insert", "field": "relatedIdentifiers", "enrichedValue": {"relatedIdentifier": "10.2/y"}}"#;
let row = super::row("preprint_matching", 2, insert).unwrap();
assert_eq!((row.original_value, row.project), (None, None));
let unknown = r#"{"doi": "10.1/x", "action": "insert", "field": "f", "newKey": 1}"#;
assert!(
super::row("x", 3, unknown)
.unwrap_err()
.starts_with("line 3:")
);
assert!(
super::row("x", 4, r#"{"doi": "10.1/x", "act"#).is_err(),
"truncated"
);
}
#[test]
fn files_become_parquet_parts() {
use parquet::file::reader::{FileReader, SerializedFileReader};
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join(FILES[0].1);
std::fs::write(&file, format!("{AFFILIATION}\n\n{AFFILIATION}\n")).unwrap();
let version = Version::parse("2026_02_06_6f4066e").unwrap();
let mut parts = Vec::new();
let rows = convert(
&file,
"author_affiliations",
dir.path(),
&version,
2,
|part| {
parts.push((part.index, part.rows));
Ok(())
},
)
.unwrap();
assert_eq!(rows, 2);
assert_eq!(parts, [(0, 2)]);
let reader = SerializedFileReader::new(
std::fs::File::open(dir.path().join("part-00000.parquet")).unwrap(),
)
.unwrap();
assert_eq!(reader.metadata().file_metadata().num_rows(), 2);
std::fs::write(&file, format!("{AFFILIATION}\n{}", &AFFILIATION[..80])).unwrap();
assert!(
convert(
&file,
"author_affiliations",
dir.path(),
&version,
1,
|_| Ok(())
)
.is_err()
);
}
#[test]
fn the_import_creates_enrichments_and_release_from_the_parts() {
let limits = Limits {
threads: 8,
memory_limit: "30GB".into(),
};
let imported = Imported {
revision: parse_revision(PATHS_INFO).unwrap(),
rows: vec![
("author_affiliations", 10),
("preprint_matching", 2),
("resource_type", 3),
],
source_files: vec!["s3://lake/sources/comet/2026_02_06_6f4066e/a.jsonl".into()],
part_files: vec![
"s3://lake/sources/comet/2026_02_06_6f4066e/a/part-00000.parquet".into(),
],
};
let sql = import_sql(&limits, "CREATE SECRET hazine_data (TYPE s3);", &imported);
for part in [
"BEGIN;\nDROP TABLE IF EXISTS comet_2026_02_06_6f4066e.enrichments;",
"SELECT * REPLACE (original_value::JSON AS original_value, enriched_value::JSON AS enriched_value)",
"'s3://lake/sources/comet/2026_02_06_6f4066e/a/part-00000.parquet'",
"'2026_02_06_6f4066e' AS version,",
"DATE '2026-02-06' AS commit_date,",
"15::BIGINT AS records,",
"2::BIGINT AS preprint_matching,",
"COMMIT;\nSELECT count(*) FROM comet_2026_02_06_6f4066e.enrichments;",
] {
assert!(sql.contains(part), "{part} missing from\n{sql}");
}
}
#[test]
fn complete_versions_are_found_newest_first() {
let versions = parse_catalog(
"comet_2026_02_06_6f4066e,enrichments\ncomet_2026_02_06_6f4066e,release\n\
comet_2026_05_01_abcdef0,enrichments\ncomet,enrichments\ncomet_scratch,x\n",
);
let names: Vec<String> = versions.iter().map(Version::to_string).collect();
assert_eq!(
names,
["2026_02_06_6f4066e"],
"2026_05_01 lacks its release table"
);
let sql = views_sql(&versions[0]);
assert!(sql.contains(
"CREATE OR REPLACE VIEW comet.enrichments AS FROM comet_2026_02_06_6f4066e.enrichments;"
));
}
}