use super::{
ArtifactLocation, CatalogArtifact, CatalogArtifactFile, CatalogExperiment,
CatalogExperimentSample, CatalogId, CatalogKineticMethodOutput, CatalogObjectKind,
CatalogPublication, CatalogPublicationSnapshot, CatalogSample, CatalogSeries, CatalogStudy,
CatalogStudyManifest, CatalogStudySeriesManifest, CatalogSubstance, CatalogThermalMode,
CatalogTypedDocumentSummary, CatalogValidationError, PublishedSeriesMember,
};
use crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultCatalog;
use crate::Kinetics::experimental_kinetics::column_provenance::{
ColumnProvenance, ColumnTransformKind,
};
use crate::Kinetics::experimental_kinetics::data_lineage::{DataLineage, DataSource};
use rusqlite::{Connection, OptionalExtension, Transaction, params};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
const SCHEMA_VERSION: i64 = 4;
const DATABASE_FILE: &str = "catalog.sqlite3";
#[derive(Debug, thiserror::Error)]
pub enum CatalogStoreError {
#[error("catalog database error: {0}")]
Database(#[from] rusqlite::Error),
#[error("catalog filesystem error: {0}")]
Filesystem(#[from] std::io::Error),
#[error("no local catalog database exists under '{0}'")]
LibraryDoesNotExist(PathBuf),
#[error("catalog serialization error: {0}")]
Serialization(#[from] serde_json::Error),
#[error("catalog validation failed: {0}")]
Validation(#[from] CatalogValidationError),
#[error("catalog object '{0}' already exists")]
AlreadyExists(String),
#[error("catalog object '{0}' does not exist")]
NotFound(String),
#[error("catalog library identity changed: expected '{expected}', found '{actual}'")]
LibraryIdentityMismatch { expected: String, actual: String },
#[error(
"series '{series_id}' is already assigned to substance '{existing_substance_id}', not '{requested_substance_id}'"
)]
SeriesSubstanceConflict {
series_id: CatalogId,
existing_substance_id: CatalogId,
requested_substance_id: CatalogId,
},
#[error("sample '{sample_id}' belongs to a different substance than series '{series_id}'")]
SeriesSampleSubstanceMismatch {
series_id: CatalogId,
sample_id: CatalogId,
},
#[error("unsupported catalog schema version {0}")]
UnsupportedSchema(i64),
#[error("catalog entry '{0}' is not a series")]
NotASeries(String),
#[error("artifact size {0} exceeds the local catalog integer range")]
ArtifactSizeOutOfRange(u64),
#[error("artifact path '{0}' is not a regular file")]
ArtifactNotAFile(PathBuf),
#[error("artifact root '{0}' is not a directory")]
ArtifactRootNotDirectory(PathBuf),
#[error("artifact root '{0}' is already registered under another ID")]
ArtifactRootAlreadyRegistered(PathBuf),
#[error("artifact source '{0}' was selected more than once")]
DuplicateArtifactSource(PathBuf),
#[error("file '{path}' does not match artifact purpose {purpose}")]
ArtifactPurposeFormatMismatch { path: PathBuf, purpose: String },
#[error("series contains {0} experiments; catalog order cannot represent more than u32::MAX")]
SeriesTooManyExperiments(usize),
#[error("publication target does not match the catalog snapshot being registered")]
PublicationTargetMismatch,
#[error("publication membership does not match the registered catalog snapshot")]
PublicationMembershipMismatch,
#[error(
"series membership changed after confirmation was requested; review the update and try again"
)]
MembershipConfirmationStale,
#[error("parent publication belongs to a different experiment or series")]
ParentPublicationTargetMismatch,
#[error("catalog experiment id does not match its KiThe source identity")]
ExperimentIdentityMismatch,
#[error("artifact file '{0}' changed while its checksum was being calculated")]
ArtifactChangedDuringHash(PathBuf),
#[error("catalog publication was cancelled while hashing external files")]
PublicationCancelled,
#[error("artifact root '{0}' is not registered in this catalog")]
ArtifactRootNotFound(String),
#[error("artifact path '{0}' resolves outside its registered root")]
ArtifactPathOutsideRoot(PathBuf),
#[error(
"cannot rebind artifact root; artifact '{artifact_id}' at '{path}' is missing or has changed"
)]
ArtifactRootRelinkMismatch { artifact_id: String, path: PathBuf },
#[error("invalid typed KiThe document '{path}': {reason}")]
InvalidTypedDocument { path: PathBuf, reason: String },
#[error("typed document '{path}' does not match the selected catalog target: {reason}")]
TypedDocumentTargetMismatch { path: PathBuf, reason: String },
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ArtifactHashProgress {
pub file_index: usize,
pub file_count: usize,
pub file_name: String,
pub bytes_in_file: u64,
pub bytes_total: u64,
pub total_bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LocalArtifactResolution {
Available(PathBuf),
Missing(PathBuf),
NoLocalCopy,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LocalArtifactIntegrity {
Verified,
Modified {
path: PathBuf,
expected_sha256: String,
actual_sha256: String,
},
Missing(PathBuf),
NoLocalCopy,
}
pub struct CatalogStore {
root: PathBuf,
connection: Connection,
library_id: String,
}
impl CatalogStore {
pub fn open(root: impl AsRef<Path>) -> Result<Self, CatalogStoreError> {
let root = root.as_ref();
std::fs::create_dir_all(root)?;
let root = std::fs::canonicalize(root)?;
let database_path = root.join(DATABASE_FILE);
let mut connection = Connection::open(database_path)?;
connection.pragma_update(None, "foreign_keys", "ON")?;
connection.busy_timeout(std::time::Duration::from_secs(5))?;
initialize_schema(&mut connection)?;
let library_id = read_library_id(&connection)?;
Ok(Self {
root,
connection,
library_id,
})
}
pub fn open_existing(root: impl AsRef<Path>) -> Result<Self, CatalogStoreError> {
let root = root.as_ref();
let root = match std::fs::canonicalize(root) {
Ok(path) => path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Err(CatalogStoreError::LibraryDoesNotExist(
root.join(DATABASE_FILE),
));
}
Err(error) => return Err(error.into()),
};
let database_path = root.join(DATABASE_FILE);
if !database_path.is_file() {
return Err(CatalogStoreError::LibraryDoesNotExist(database_path));
}
let mut connection = Connection::open(database_path)?;
connection.pragma_update(None, "foreign_keys", "ON")?;
connection.busy_timeout(std::time::Duration::from_secs(5))?;
initialize_schema(&mut connection)?;
let library_id = read_library_id(&connection)?;
Ok(Self {
root,
connection,
library_id,
})
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn library_id(&self) -> &str {
&self.library_id
}
pub fn ensure_library_identity(&self, expected: &str) -> Result<(), CatalogStoreError> {
if self.library_id == expected {
Ok(())
} else {
Err(CatalogStoreError::LibraryIdentityMismatch {
expected: expected.to_owned(),
actual: self.library_id.clone(),
})
}
}
pub fn insert_experiment(
&mut self,
experiment: &CatalogExperiment,
) -> Result<(), CatalogStoreError> {
experiment.validate()?;
let payload = serde_json::to_string(experiment)?;
let inserted = self.connection.execute(
"INSERT OR IGNORE INTO experiments(id, source_identity, display_name, payload_json) VALUES (?1, ?2, ?3, ?4)",
params![experiment.id.as_str(), experiment.source_identity, experiment.display_name, payload],
)?;
if inserted == 0 {
return Err(CatalogStoreError::AlreadyExists(
experiment.source_identity.clone(),
));
}
Ok(())
}
pub fn insert_series(&mut self, series: &CatalogSeries) -> Result<(), CatalogStoreError> {
if series.display_name.trim().is_empty() {
return Err(CatalogValidationError::EmptyDisplayName.into());
}
let payload = serde_json::to_string(series)?;
let inserted = self.connection.execute(
"INSERT OR IGNORE INTO series(id, display_name, payload_json) VALUES (?1, ?2, ?3)",
params![series.id.as_str(), series.display_name, payload],
)?;
if inserted == 0 {
return Err(CatalogStoreError::AlreadyExists(
series.id.as_str().to_owned(),
));
}
Ok(())
}
pub fn insert_study(&mut self, study: &CatalogStudy) -> Result<(), CatalogStoreError> {
study.validate()?;
let payload = serde_json::to_string(study)?;
let inserted = self.connection.execute(
"INSERT OR IGNORE INTO studies(id, display_name, payload_json) VALUES (?1, ?2, ?3)",
params![study.id.as_str(), study.display_name, payload],
)?;
if inserted == 0 {
return Err(CatalogStoreError::AlreadyExists(
study.id.as_str().to_owned(),
));
}
Ok(())
}
pub fn insert_substance(
&mut self,
substance: &CatalogSubstance,
) -> Result<(), CatalogStoreError> {
substance.validate()?;
let payload = serde_json::to_string(substance)?;
let inserted = self.connection.execute(
"INSERT OR IGNORE INTO substances(id, display_name, payload_json) VALUES (?1, ?2, ?3)",
params![substance.id.as_str(), substance.display_name, payload],
)?;
if inserted == 0 {
return Err(CatalogStoreError::AlreadyExists(
substance.id.as_str().to_owned(),
));
}
Ok(())
}
pub fn insert_substance_in_study(
&mut self,
substance: &CatalogSubstance,
study_id: &CatalogId,
) -> Result<(), CatalogStoreError> {
substance.validate()?;
let payload = serde_json::to_string(substance)?;
let tx = self.connection.transaction()?;
require_study(&tx, study_id)?;
let inserted = tx.execute(
"INSERT OR IGNORE INTO substances(id, display_name, payload_json) VALUES (?1, ?2, ?3)",
params![substance.id.as_str(), substance.display_name, payload],
)?;
if inserted == 0 {
return Err(CatalogStoreError::AlreadyExists(
substance.id.as_str().to_owned(),
));
}
tx.execute(
"INSERT INTO study_substances(study_id, substance_id) VALUES (?1, ?2)",
params![study_id.as_str(), substance.id.as_str()],
)?;
tx.commit()?;
Ok(())
}
pub fn insert_sample(&mut self, sample: &CatalogSample) -> Result<(), CatalogStoreError> {
sample.validate()?;
let payload = serde_json::to_string(sample)?;
let tx = self.connection.transaction()?;
require_substance(&tx, &sample.substance_id)?;
let inserted = tx.execute(
"INSERT OR IGNORE INTO samples(id, substance_id, display_name, payload_json) VALUES (?1, ?2, ?3, ?4)",
params![sample.id.as_str(), sample.substance_id.as_str(), sample.display_name, payload],
)?;
if inserted == 0 {
return Err(CatalogStoreError::AlreadyExists(
sample.id.as_str().to_owned(),
));
}
tx.commit()?;
Ok(())
}
pub fn insert_sample_for_experiment(
&mut self,
sample: &CatalogSample,
experiment_id: &CatalogId,
) -> Result<(), CatalogStoreError> {
sample.validate()?;
let payload = serde_json::to_string(sample)?;
let tx = self.connection.transaction()?;
require_experiment(&tx, experiment_id)?;
require_substance(&tx, &sample.substance_id)?;
let conflicting_series = tx
.query_row(
"SELECT ss.series_id
FROM series_members sm
JOIN series_substances ss ON ss.series_id = sm.series_id
WHERE sm.experiment_id = ?1 AND ss.substance_id <> ?2
LIMIT 1",
params![experiment_id.as_str(), sample.substance_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?;
if let Some(series_id) = conflicting_series {
return Err(CatalogStoreError::SeriesSampleSubstanceMismatch {
series_id: CatalogId::parse(series_id)?,
sample_id: sample.id.clone(),
});
}
let inserted = tx.execute(
"INSERT OR IGNORE INTO samples(id, substance_id, display_name, payload_json) VALUES (?1, ?2, ?3, ?4)",
params![sample.id.as_str(), sample.substance_id.as_str(), sample.display_name, payload],
)?;
if inserted == 0 {
return Err(CatalogStoreError::AlreadyExists(
sample.id.as_str().to_owned(),
));
}
tx.execute(
"INSERT INTO experiment_samples(experiment_id, sample_id) VALUES (?1, ?2)
ON CONFLICT(experiment_id) DO UPDATE SET sample_id = excluded.sample_id",
params![experiment_id.as_str(), sample.id.as_str()],
)?;
tx.commit()?;
Ok(())
}
pub fn assign_substance_to_series(
&mut self,
series_id: &CatalogId,
substance_id: &CatalogId,
) -> Result<(), CatalogStoreError> {
let tx = self.connection.transaction()?;
require_series(&tx, series_id)?;
require_substance(&tx, substance_id)?;
let existing = tx
.query_row(
"SELECT substance_id FROM series_substances WHERE series_id = ?1",
[series_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?
.map(CatalogId::parse)
.transpose()?;
if let Some(existing) = existing {
if existing != *substance_id {
return Err(CatalogStoreError::SeriesSubstanceConflict {
series_id: series_id.clone(),
existing_substance_id: existing,
requested_substance_id: substance_id.clone(),
});
}
tx.commit()?;
return Ok(());
}
let mismatch = tx
.query_row(
"SELECT es.sample_id
FROM series_members sm
JOIN experiment_samples es ON es.experiment_id = sm.experiment_id
JOIN samples sa ON sa.id = es.sample_id
WHERE sm.series_id = ?1 AND sa.substance_id <> ?2
LIMIT 1",
params![series_id.as_str(), substance_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?;
if let Some(sample_id) = mismatch {
return Err(CatalogStoreError::SeriesSampleSubstanceMismatch {
series_id: series_id.clone(),
sample_id: CatalogId::parse(sample_id)?,
});
}
tx.execute(
"INSERT INTO series_substances(series_id, substance_id) VALUES (?1, ?2)",
params![series_id.as_str(), substance_id.as_str()],
)?;
tx.execute(
"INSERT OR IGNORE INTO study_substances(study_id, substance_id)
SELECT study_id, ?2 FROM study_series WHERE series_id = ?1",
params![series_id.as_str(), substance_id.as_str()],
)?;
tx.commit()?;
Ok(())
}
pub fn add_substance_to_study(
&mut self,
study_id: &CatalogId,
substance_id: &CatalogId,
) -> Result<(), CatalogStoreError> {
let tx = self.connection.transaction()?;
require_study(&tx, study_id)?;
require_substance(&tx, substance_id)?;
tx.execute(
"INSERT OR IGNORE INTO study_substances(study_id, substance_id) VALUES (?1, ?2)",
params![study_id.as_str(), substance_id.as_str()],
)?;
tx.commit()?;
Ok(())
}
pub fn add_series_to_study(
&mut self,
study_id: &CatalogId,
series_id: &CatalogId,
) -> Result<(), CatalogStoreError> {
let tx = self.connection.transaction()?;
require_study(&tx, study_id)?;
require_series(&tx, series_id)?;
let substance_id = tx
.query_row(
"SELECT substance_id FROM series_substances WHERE series_id = ?1",
[series_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?;
if let Some(substance_id) = substance_id {
tx.execute(
"INSERT OR IGNORE INTO study_substances(study_id, substance_id) VALUES (?1, ?2)",
params![study_id.as_str(), substance_id],
)?;
}
tx.execute(
"INSERT OR IGNORE INTO study_series(study_id, series_id) VALUES (?1, ?2)",
params![study_id.as_str(), series_id.as_str()],
)?;
tx.commit()?;
Ok(())
}
pub fn assign_sample_to_experiment(
&mut self,
experiment_id: &CatalogId,
sample_id: &CatalogId,
) -> Result<(), CatalogStoreError> {
let tx = self.connection.transaction()?;
require_experiment(&tx, experiment_id)?;
let sample_substance = tx
.query_row(
"SELECT substance_id FROM samples WHERE id = ?1",
[sample_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?
.ok_or_else(|| CatalogStoreError::NotFound(sample_id.as_str().to_owned()))?;
let conflicting_series = tx
.query_row(
"SELECT ss.series_id
FROM series_members sm
JOIN series_substances ss ON ss.series_id = sm.series_id
WHERE sm.experiment_id = ?1 AND ss.substance_id <> ?2
LIMIT 1",
params![experiment_id.as_str(), sample_substance],
|row| row.get::<_, String>(0),
)
.optional()?;
if let Some(series_id) = conflicting_series {
return Err(CatalogStoreError::SeriesSampleSubstanceMismatch {
series_id: CatalogId::parse(series_id)?,
sample_id: sample_id.clone(),
});
}
tx.execute(
"INSERT INTO experiment_samples(experiment_id, sample_id) VALUES (?1, ?2)
ON CONFLICT(experiment_id) DO UPDATE SET sample_id = excluded.sample_id",
params![experiment_id.as_str(), sample_id.as_str()],
)?;
tx.commit()?;
Ok(())
}
pub fn list_studies(&self) -> Result<Vec<CatalogStudy>, CatalogStoreError> {
list_payloads(&self.connection, "studies", "display_name")
}
pub fn get_study(
&self,
study_id: &CatalogId,
) -> Result<Option<CatalogStudy>, CatalogStoreError> {
get_payload(&self.connection, "studies", study_id)
}
pub fn list_substances(&self) -> Result<Vec<CatalogSubstance>, CatalogStoreError> {
list_payloads(&self.connection, "substances", "display_name")
}
pub fn get_substance(
&self,
substance_id: &CatalogId,
) -> Result<Option<CatalogSubstance>, CatalogStoreError> {
get_payload(&self.connection, "substances", substance_id)
}
pub fn list_samples(&self) -> Result<Vec<CatalogSample>, CatalogStoreError> {
list_payloads(&self.connection, "samples", "display_name")
}
pub fn get_sample(
&self,
sample_id: &CatalogId,
) -> Result<Option<CatalogSample>, CatalogStoreError> {
get_payload(&self.connection, "samples", sample_id)
}
pub fn list_study_substances(
&self,
study_id: &CatalogId,
) -> Result<Vec<CatalogSubstance>, CatalogStoreError> {
let mut statement = self.connection.prepare(
"SELECT s.payload_json FROM substances s
JOIN study_substances ss ON ss.substance_id = s.id
WHERE ss.study_id = ?1 ORDER BY s.display_name COLLATE NOCASE, s.id",
)?;
let rows = statement.query_map([study_id.as_str()], |row| row.get::<_, String>(0))?;
rows.map(|row| serde_json::from_str(&row?).map_err(CatalogStoreError::from))
.collect()
}
pub fn list_study_series(
&self,
study_id: &CatalogId,
) -> Result<Vec<CatalogSeries>, CatalogStoreError> {
let mut statement = self.connection.prepare(
"SELECT s.payload_json FROM series s
JOIN study_series ss ON ss.series_id = s.id
WHERE ss.study_id = ?1 ORDER BY s.display_name COLLATE NOCASE, s.id",
)?;
let rows = statement.query_map([study_id.as_str()], |row| row.get::<_, String>(0))?;
rows.map(|row| serde_json::from_str(&row?).map_err(CatalogStoreError::from))
.collect()
}
pub fn list_series_members(
&self,
series_id: &CatalogId,
) -> Result<Vec<PublishedSeriesMember>, CatalogStoreError> {
let mut statement = self.connection.prepare(
"SELECT experiment_id, ordinal FROM series_members
WHERE series_id = ?1 ORDER BY ordinal",
)?;
let rows = statement.query_map([series_id.as_str()], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, u32>(1)?))
})?;
rows.map(|row| {
let (experiment_id, ordinal) = row?;
Ok(PublishedSeriesMember {
experiment_id: CatalogId::parse(experiment_id)?,
ordinal,
})
})
.collect()
}
pub fn list_experiment_sample_substances(
&self,
) -> Result<Vec<(CatalogId, CatalogId)>, CatalogStoreError> {
let mut statement = self.connection.prepare(
"SELECT es.experiment_id, s.substance_id
FROM experiment_samples es
JOIN samples s ON s.id = es.sample_id
ORDER BY es.experiment_id",
)?;
let rows = statement.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
rows.map(|row| {
let (experiment_id, substance_id) = row?;
Ok((
CatalogId::parse(experiment_id)?,
CatalogId::parse(substance_id)?,
))
})
.collect()
}
pub fn list_experiment_samples(
&self,
) -> Result<Vec<(CatalogId, CatalogId)>, CatalogStoreError> {
let mut statement = self.connection.prepare(
"SELECT experiment_id, sample_id FROM experiment_samples ORDER BY experiment_id",
)?;
let rows = statement.query_map([], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
rows.map(|row| {
let (experiment_id, sample_id) = row?;
Ok((
CatalogId::parse(experiment_id)?,
CatalogId::parse(sample_id)?,
))
})
.collect()
}
pub fn study_manifest(
&self,
study_id: &CatalogId,
) -> Result<CatalogStudyManifest, CatalogStoreError> {
let study = self
.get_study(study_id)?
.ok_or_else(|| CatalogStoreError::NotFound(study_id.as_str().to_owned()))?;
let substances = self.list_study_substances(study_id)?;
let mut samples = Vec::new();
let publications = self.list_publications()?;
let mut series_manifest = Vec::new();
for series in self.list_study_series(study_id)? {
let mut statement = self.connection.prepare(
"SELECT experiment_id, ordinal FROM series_members
WHERE series_id = ?1 ORDER BY ordinal",
)?;
let rows = statement.query_map([series.id.as_str()], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, u32>(1)?))
})?;
let current_members = rows
.map(|row| {
let (experiment_id, ordinal) = row?;
Ok(PublishedSeriesMember {
experiment_id: CatalogId::parse(experiment_id)?,
ordinal,
})
})
.collect::<Result<Vec<_>, CatalogStoreError>>()?;
let mut statement = self.connection.prepare(
"SELECT es.experiment_id, s.payload_json
FROM series_members sm
JOIN experiment_samples es ON es.experiment_id = sm.experiment_id
JOIN samples s ON s.id = es.sample_id
WHERE sm.series_id = ?1 ORDER BY sm.ordinal",
)?;
let rows = statement.query_map([series.id.as_str()], |row| {
Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
})?;
let mut experiment_samples = Vec::new();
for row in rows {
let (experiment_id, sample_json) = row?;
let sample: CatalogSample = serde_json::from_str(&sample_json)?;
let link = CatalogExperimentSample {
experiment_id: CatalogId::parse(experiment_id)?,
sample_id: sample.id.clone(),
};
if !samples
.iter()
.any(|existing: &CatalogSample| existing.id == sample.id)
{
samples.push(sample);
}
experiment_samples.push(link);
}
let series_publications = publications
.iter()
.filter(|publication| {
publication.object_kind == CatalogObjectKind::Series
&& publication.object_id == series.id
})
.cloned()
.collect();
series_manifest.push(CatalogStudySeriesManifest {
substance_id: self.substance_for_series(&series.id)?,
current_members,
experiment_samples,
publications: series_publications,
series,
});
}
let manifest = CatalogStudyManifest {
schema_version: 1,
study,
substances,
samples,
series: series_manifest,
};
manifest.validate()?;
Ok(manifest)
}
pub fn substance_for_series(
&self,
series_id: &CatalogId,
) -> Result<Option<CatalogId>, CatalogStoreError> {
self.connection
.query_row(
"SELECT substance_id FROM series_substances WHERE series_id = ?1",
[series_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?
.map(CatalogId::parse)
.transpose()
.map_err(Into::into)
}
pub fn sample_for_experiment(
&self,
experiment_id: &CatalogId,
) -> Result<Option<CatalogId>, CatalogStoreError> {
self.connection
.query_row(
"SELECT sample_id FROM experiment_samples WHERE experiment_id = ?1",
[experiment_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?
.map(CatalogId::parse)
.transpose()
.map_err(Into::into)
}
pub fn register_series_snapshot(
&mut self,
series: &CatalogSeries,
experiments: &[CatalogExperiment],
) -> Result<(), CatalogStoreError> {
let tx = self.connection.transaction()?;
upsert_series_snapshot(&tx, series, experiments)?;
tx.commit()?;
Ok(())
}
pub fn register_experiment_snapshot(
&mut self,
experiment: &CatalogExperiment,
) -> Result<(), CatalogStoreError> {
validate_experiment_identity(experiment)?;
let tx = self.connection.transaction()?;
upsert_experiment_snapshot(&tx, experiment)?;
tx.commit()?;
Ok(())
}
pub fn list_series(&self) -> Result<Vec<CatalogSeries>, CatalogStoreError> {
let mut statement = self
.connection
.prepare("SELECT payload_json FROM series ORDER BY display_name COLLATE NOCASE, id")?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
rows.map(|row| {
let payload = row?;
serde_json::from_str(&payload).map_err(CatalogStoreError::from)
})
.collect()
}
pub fn list_experiments(&self) -> Result<Vec<CatalogExperiment>, CatalogStoreError> {
let mut statement = self.connection.prepare(
"SELECT payload_json FROM experiments ORDER BY display_name COLLATE NOCASE, id",
)?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
rows.map(|row| {
let payload = row?;
serde_json::from_str(&payload).map_err(CatalogStoreError::from)
})
.collect()
}
pub fn set_series_members(
&mut self,
series_id: &CatalogId,
members: &[PublishedSeriesMember],
) -> Result<(), CatalogStoreError> {
validate_members(members)?;
let tx = self.connection.transaction()?;
require_series(&tx, series_id)?;
for member in members {
require_experiment(&tx, &member.experiment_id)?;
}
validate_series_sample_materials(
&tx,
series_id,
&members
.iter()
.map(|member| member.experiment_id.clone())
.collect::<Vec<_>>(),
)?;
tx.execute(
"DELETE FROM series_members WHERE series_id = ?1",
[series_id.as_str()],
)?;
for member in members {
tx.execute(
"INSERT INTO series_members(series_id, experiment_id, ordinal) VALUES (?1, ?2, ?3)",
params![
series_id.as_str(),
member.experiment_id.as_str(),
member.ordinal
],
)?;
}
tx.commit()?;
Ok(())
}
pub fn insert_artifact(&mut self, artifact: &CatalogArtifact) -> Result<(), CatalogStoreError> {
artifact.validate()?;
let size_bytes = i64::try_from(artifact.size_bytes)
.map_err(|_| CatalogStoreError::ArtifactSizeOutOfRange(artifact.size_bytes))?;
let payload = serde_json::to_string(artifact)?;
let inserted = self.connection.execute(
"INSERT OR IGNORE INTO artifacts(id, sha256, size_bytes, payload_json) VALUES (?1, ?2, ?3, ?4)",
params![artifact.id.as_str(), artifact.sha256.to_ascii_lowercase(), size_bytes, payload],
)?;
if inserted == 0 {
return Err(CatalogStoreError::AlreadyExists(
artifact.id.as_str().to_owned(),
));
}
Ok(())
}
pub fn publish(&mut self, publication: &CatalogPublication) -> Result<(), CatalogStoreError> {
publication.validate()?;
let tx = self.connection.transaction()?;
insert_publication(&tx, publication)?;
tx.commit()?;
Ok(())
}
pub fn publish_with_local_files(
&mut self,
publication: &CatalogPublication,
files: &[CatalogArtifactFile],
) -> Result<CatalogPublication, CatalogStoreError> {
self.publish_with_local_files_with_progress(publication, files, |_| true)
}
pub fn publish_with_local_files_with_progress<F>(
&mut self,
publication: &CatalogPublication,
files: &[CatalogArtifactFile],
mut progress: F,
) -> Result<CatalogPublication, CatalogStoreError>
where
F: FnMut(ArtifactHashProgress) -> bool,
{
let inspected = inspect_artifact_files_with_progress(files, &mut progress)?;
let typed_documents = validate_inspected_typed_document_targets(publication, &inspected)?;
check_publication_commit_boundary(&inspected, files.len(), &mut progress)?;
let mut published = publication.clone();
published.typed_documents = typed_documents;
let tx = self.connection.transaction()?;
for item in inspected {
let artifact = insert_inspected_artifact(&tx, item)?;
published.artifact_ids.push(artifact.id);
}
published.validate()?;
insert_publication(&tx, &published)?;
tx.commit()?;
Ok(published)
}
pub fn register_and_publish_series_snapshot(
&mut self,
series: &CatalogSeries,
experiments: &[CatalogExperiment],
publication: &CatalogPublication,
files: &[CatalogArtifactFile],
) -> Result<CatalogPublication, CatalogStoreError> {
self.register_and_publish_series_snapshot_with_progress(
series,
experiments,
publication,
files,
|_| true,
)
}
pub fn register_and_publish_series_snapshot_with_progress<F>(
&mut self,
series: &CatalogSeries,
experiments: &[CatalogExperiment],
publication: &CatalogPublication,
files: &[CatalogArtifactFile],
mut progress: F,
) -> Result<CatalogPublication, CatalogStoreError>
where
F: FnMut(ArtifactHashProgress) -> bool,
{
if publication.object_kind != CatalogObjectKind::Series
|| publication.object_id != series.id
{
return Err(CatalogStoreError::PublicationTargetMismatch);
}
let expected_members = experiments
.iter()
.enumerate()
.map(|(index, experiment)| {
let source_id = CatalogId::parse(experiment.source_identity.clone())?;
if source_id != experiment.id {
return Err(CatalogStoreError::ExperimentIdentityMismatch);
}
Ok(PublishedSeriesMember {
experiment_id: experiment.id.clone(),
ordinal: u32::try_from(index)
.map_err(|_| CatalogStoreError::SeriesTooManyExperiments(index))?,
})
})
.collect::<Result<Vec<_>, CatalogStoreError>>()?;
if publication.series_members != expected_members {
return Err(CatalogStoreError::PublicationMembershipMismatch);
}
let inspected = inspect_artifact_files_with_progress(files, &mut progress)?;
let typed_documents = validate_inspected_typed_document_targets(publication, &inspected)?;
check_publication_commit_boundary(&inspected, files.len(), &mut progress)?;
let mut published = publication.clone();
published.typed_documents = typed_documents;
let tx = self.connection.transaction()?;
upsert_series_snapshot(&tx, series, experiments)?;
for item in inspected {
let artifact = insert_inspected_artifact(&tx, item)?;
published.artifact_ids.push(artifact.id);
}
insert_publication(&tx, &published)?;
tx.commit()?;
Ok(published)
}
pub fn register_and_publish_experiment_snapshot(
&mut self,
experiment: &CatalogExperiment,
publication: &CatalogPublication,
files: &[CatalogArtifactFile],
) -> Result<CatalogPublication, CatalogStoreError> {
self.register_and_publish_experiment_snapshot_with_progress(
experiment,
publication,
files,
|_| true,
)
}
pub fn register_and_publish_experiment_snapshot_with_progress<F>(
&mut self,
experiment: &CatalogExperiment,
publication: &CatalogPublication,
files: &[CatalogArtifactFile],
mut progress: F,
) -> Result<CatalogPublication, CatalogStoreError>
where
F: FnMut(ArtifactHashProgress) -> bool,
{
if publication.object_kind != CatalogObjectKind::Experiment
|| publication.object_id != experiment.id
{
return Err(CatalogStoreError::PublicationTargetMismatch);
}
if !publication.series_members.is_empty() {
return Err(CatalogStoreError::PublicationMembershipMismatch);
}
validate_experiment_identity(experiment)?;
let inspected = inspect_artifact_files_with_progress(files, &mut progress)?;
let typed_documents = validate_inspected_typed_document_targets(publication, &inspected)?;
check_publication_commit_boundary(&inspected, files.len(), &mut progress)?;
let mut published = publication.clone();
published.typed_documents = typed_documents;
let tx = self.connection.transaction()?;
upsert_experiment_snapshot(&tx, experiment)?;
for item in inspected {
let artifact = insert_inspected_artifact(&tx, item)?;
published.artifact_ids.push(artifact.id);
}
insert_publication(&tx, &published)?;
tx.commit()?;
Ok(published)
}
pub fn get_experiment(
&self,
id: &CatalogId,
) -> Result<Option<CatalogExperiment>, CatalogStoreError> {
let payload = self
.connection
.query_row(
"SELECT payload_json FROM experiments WHERE id = ?1",
[id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?;
payload
.map(|json| serde_json::from_str(&json).map_err(CatalogStoreError::from))
.transpose()
}
pub fn get_publication(
&self,
id: &CatalogId,
) -> Result<Option<CatalogPublication>, CatalogStoreError> {
let payload = self
.connection
.query_row(
"SELECT payload_json FROM publications WHERE id = ?1",
[id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?;
payload
.map(|json| serde_json::from_str(&json).map_err(CatalogStoreError::from))
.transpose()
}
pub fn list_publications(&self) -> Result<Vec<CatalogPublication>, CatalogStoreError> {
let mut statement = self
.connection
.prepare("SELECT payload_json FROM publications ORDER BY created_at DESC, id DESC")?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
rows.map(|row| {
let payload = row?;
serde_json::from_str(&payload).map_err(CatalogStoreError::from)
})
.collect()
}
pub fn get_artifact(
&self,
id: &CatalogId,
) -> Result<Option<CatalogArtifact>, CatalogStoreError> {
let payload = self
.connection
.query_row(
"SELECT payload_json FROM artifacts WHERE id = ?1",
[id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?;
payload
.map(|json| serde_json::from_str(&json).map_err(CatalogStoreError::from))
.transpose()
}
pub fn resolve_local_artifact(
&self,
id: &CatalogId,
) -> Result<LocalArtifactResolution, CatalogStoreError> {
let artifact = self
.get_artifact(id)?
.ok_or_else(|| CatalogStoreError::NotFound(id.as_str().to_owned()))?;
artifact.validate()?;
let Some((root_id, relative_path)) = artifact.locations.iter().find_map(|location| {
if let ArtifactLocation::Local {
root_id,
relative_path,
} = location
{
Some((root_id, relative_path))
} else {
None
}
}) else {
return Ok(LocalArtifactResolution::NoLocalCopy);
};
let root_path = self
.connection
.query_row(
"SELECT canonical_path FROM artifact_roots WHERE id = ?1",
[root_id],
|row| row.get::<_, String>(0),
)
.optional()?
.map(PathBuf::from)
.ok_or_else(|| CatalogStoreError::ArtifactRootNotFound(root_id.clone()))?;
let expected_path = root_path.join(relative_path);
let canonical_root = match std::fs::canonicalize(&root_path) {
Ok(path) => path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(LocalArtifactResolution::Missing(expected_path));
}
Err(error) => return Err(error.into()),
};
let canonical_path = match std::fs::canonicalize(&expected_path) {
Ok(path) => path,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(LocalArtifactResolution::Missing(expected_path));
}
Err(error) => return Err(error.into()),
};
if !canonical_path.starts_with(&canonical_root) {
return Err(CatalogStoreError::ArtifactPathOutsideRoot(canonical_path));
}
if !canonical_path.is_file() {
return Ok(LocalArtifactResolution::Missing(canonical_path));
}
Ok(LocalArtifactResolution::Available(canonical_path))
}
pub fn verify_local_artifact(
&self,
id: &CatalogId,
) -> Result<LocalArtifactIntegrity, CatalogStoreError> {
let artifact = self
.get_artifact(id)?
.ok_or_else(|| CatalogStoreError::NotFound(id.as_str().to_owned()))?;
artifact.validate()?;
let path = match self.resolve_local_artifact(id)? {
LocalArtifactResolution::Available(path) => path,
LocalArtifactResolution::Missing(path) => {
return Ok(LocalArtifactIntegrity::Missing(path));
}
LocalArtifactResolution::NoLocalCopy => return Ok(LocalArtifactIntegrity::NoLocalCopy),
};
let (_, actual_sha256) = hash_stable_file(&path)?;
if actual_sha256.eq_ignore_ascii_case(&artifact.sha256) {
Ok(LocalArtifactIntegrity::Verified)
} else {
Ok(LocalArtifactIntegrity::Modified {
path,
expected_sha256: artifact.sha256,
actual_sha256,
})
}
}
pub fn relink_local_root(
&mut self,
root_id: &str,
new_root: impl AsRef<Path>,
) -> Result<usize, CatalogStoreError> {
let new_root = std::fs::canonicalize(new_root)?;
if !new_root.is_dir() {
return Err(CatalogStoreError::ArtifactRootNotDirectory(new_root));
}
self.connection
.query_row(
"SELECT 1 FROM artifact_roots WHERE id = ?1",
[root_id],
|_| Ok(()),
)
.optional()?
.ok_or_else(|| CatalogStoreError::ArtifactRootNotFound(root_id.to_owned()))?;
let mut matching = Vec::new();
{
let mut statement = self
.connection
.prepare("SELECT payload_json FROM artifacts")?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
for row in rows {
let artifact: CatalogArtifact = serde_json::from_str(&row?)?;
if let Some(relative_path) =
artifact
.locations
.iter()
.find_map(|location| match location {
ArtifactLocation::Local {
root_id: artifact_root_id,
relative_path,
} if artifact_root_id == root_id => Some(relative_path.clone()),
_ => None,
})
{
matching.push((artifact, relative_path));
}
}
}
if matching.is_empty() {
return Err(CatalogStoreError::ArtifactRootNotFound(root_id.to_owned()));
}
for (artifact, relative_path) in &matching {
let candidate = new_root.join(relative_path);
let canonical = std::fs::canonicalize(&candidate).map_err(|_| {
CatalogStoreError::ArtifactRootRelinkMismatch {
artifact_id: artifact.id.as_str().to_owned(),
path: candidate.clone(),
}
})?;
if !canonical.starts_with(&new_root) || !canonical.is_file() {
return Err(CatalogStoreError::ArtifactPathOutsideRoot(canonical));
}
let (size, checksum) = hash_stable_file(&canonical)?;
if size != artifact.size_bytes || !checksum.eq_ignore_ascii_case(&artifact.sha256) {
return Err(CatalogStoreError::ArtifactRootRelinkMismatch {
artifact_id: artifact.id.as_str().to_owned(),
path: canonical,
});
}
}
let canonical_new_root = new_root.to_string_lossy().into_owned();
if self
.connection
.query_row(
"SELECT 1 FROM artifact_roots WHERE canonical_path = ?1 AND id <> ?2",
params![canonical_new_root, root_id],
|_| Ok(()),
)
.optional()?
.is_some()
{
return Err(CatalogStoreError::ArtifactRootAlreadyRegistered(new_root));
}
let tx = self.connection.transaction()?;
let changed = tx.execute(
"UPDATE artifact_roots SET canonical_path = ?1 WHERE id = ?2",
params![canonical_new_root, root_id],
)?;
if changed != 1 {
return Err(CatalogStoreError::ArtifactRootNotFound(root_id.to_owned()));
}
tx.commit()?;
Ok(matching.len())
}
}
struct InspectedArtifactFile {
canonical_path: PathBuf,
root_path: PathBuf,
file_name: String,
size_bytes: u64,
sha256: String,
purpose: super::CatalogArtifactPurpose,
typed_header: Option<TypedDocumentHeader>,
}
fn hash_stable_file(path: &Path) -> Result<(u64, String), CatalogStoreError> {
hash_stable_file_with_progress(path, |_| true)
}
fn hash_stable_file_with_progress(
path: &Path,
mut progress: impl FnMut(u64) -> bool,
) -> Result<(u64, String), CatalogStoreError> {
let mut file = std::fs::File::open(path)?;
let before = file.metadata()?;
let path_before = std::fs::metadata(path)?;
hash_open_file_with_progress(path, &mut file, before, path_before, &mut progress)
}
fn hash_open_file_with_progress(
path: &Path,
file: &mut std::fs::File,
before: std::fs::Metadata,
path_before: std::fs::Metadata,
progress: &mut dyn FnMut(u64) -> bool,
) -> Result<(u64, String), CatalogStoreError> {
if !before.is_file() {
return Err(CatalogStoreError::ArtifactNotAFile(path.to_path_buf()));
}
file.seek(SeekFrom::Start(0))?;
let mut hasher = Sha256::new();
let mut buffer = [0_u8; 64 * 1024];
let mut bytes_hashed = 0_u64;
if !progress(0) {
return Err(CatalogStoreError::PublicationCancelled);
}
loop {
let count = file.read(&mut buffer)?;
if count == 0 {
break;
}
bytes_hashed = bytes_hashed.saturating_add(count as u64);
hasher.update(&buffer[..count]);
if !progress(bytes_hashed) {
return Err(CatalogStoreError::PublicationCancelled);
}
}
let after = file.metadata()?;
let path_after = std::fs::metadata(path)?;
if before.len() != after.len()
|| bytes_hashed != before.len()
|| before.modified().ok() != after.modified().ok()
|| path_before.len() != before.len()
|| path_after.len() != after.len()
|| path_before.modified().ok() != before.modified().ok()
|| path_after.modified().ok() != after.modified().ok()
{
return Err(CatalogStoreError::ArtifactChangedDuringHash(
path.to_path_buf(),
));
}
let digest = hasher
.finalize()
.iter()
.map(|byte| format!("{byte:02x}"))
.collect();
Ok((bytes_hashed, digest))
}
enum TypedDocumentHeader {
Dataset {
experiment_identity: Option<String>,
},
Series {
series_identity: String,
experiment_identities: Vec<String>,
analysis_results:
Vec<crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultRecord>,
kinetic_method_outputs: Vec<CatalogKineticMethodOutput>,
},
}
fn validate_typed_document_targets(
publication: &CatalogPublication,
files: &[CatalogArtifactFile],
) -> Result<Vec<CatalogTypedDocumentSummary>, CatalogStoreError> {
let inspected = inspect_artifact_files_with_progress(files, &mut |_| true)?;
validate_inspected_typed_document_targets(publication, &inspected)
}
fn validate_inspected_typed_document_targets(
publication: &CatalogPublication,
files: &[InspectedArtifactFile],
) -> Result<Vec<CatalogTypedDocumentSummary>, CatalogStoreError> {
let mut summaries = Vec::new();
for selected in files.iter().filter(|file| {
file.purpose == super::CatalogArtifactPurpose::TypedKiTheDocument
|| file.typed_header.is_some()
}) {
let header = selected.typed_header.as_ref().ok_or_else(|| {
CatalogStoreError::InvalidTypedDocument {
path: selected.canonical_path.clone(),
reason: "typed document header was not inspected".into(),
}
})?;
match header {
TypedDocumentHeader::Dataset { .. }
if publication.object_kind != CatalogObjectKind::Experiment =>
{
return Err(CatalogStoreError::TypedDocumentTargetMismatch {
path: selected.canonical_path.clone(),
reason: "a single-dataset document must be published under an experiment, not a series".into(),
});
}
TypedDocumentHeader::Dataset {
experiment_identity,
} => {
let expected = experiment_identity.clone().ok_or_else(|| {
CatalogStoreError::TypedDocumentTargetMismatch {
path: selected.canonical_path.clone(),
reason: "single-experiment typed CSV has no stable experiment identity; re-export it from the experiment".into(),
}
})?;
if expected != publication.object_id.as_str() {
return Err(CatalogStoreError::TypedDocumentTargetMismatch {
path: selected.canonical_path.clone(),
reason: format!(
"document experiment identity {expected} differs from publication target {}",
publication.object_id.as_str()
),
});
}
}
TypedDocumentHeader::Series {
series_identity,
experiment_identities,
analysis_results,
kinetic_method_outputs,
} => {
if publication.object_kind != CatalogObjectKind::Series {
return Err(CatalogStoreError::TypedDocumentTargetMismatch {
path: selected.canonical_path.clone(),
reason:
"a typed-series document cannot be attached as an experiment document"
.into(),
});
}
if series_identity != publication.object_id.as_str() {
return Err(CatalogStoreError::TypedDocumentTargetMismatch {
path: selected.canonical_path.clone(),
reason: format!(
"document series identity {series_identity} differs from publication target {}",
publication.object_id.as_str()
),
});
}
let expected = publication
.series_members
.iter()
.map(|member| member.experiment_id.as_str())
.collect::<Vec<_>>();
let actual = experiment_identities
.iter()
.map(String::as_str)
.collect::<Vec<_>>();
if expected != actual {
return Err(CatalogStoreError::TypedDocumentTargetMismatch {
path: selected.canonical_path.clone(),
reason: "document experiment identities or their order differ from the published series membership".into(),
});
}
validate_typed_series_metadata(&selected.canonical_path, publication)?;
summaries.push(CatalogTypedDocumentSummary {
file_name: selected
.canonical_path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("typed-series.csv")
.to_string(),
analysis_results: analysis_results.clone(),
kinetic_method_outputs: kinetic_method_outputs.clone(),
});
}
}
}
Ok(summaries)
}
fn validate_typed_series_metadata(
path: &Path,
publication: &CatalogPublication,
) -> Result<(), CatalogStoreError> {
let expected_experiments = match publication.snapshot.as_ref() {
Some(CatalogPublicationSnapshot::Series { experiments, .. }) => experiments,
_ => return Ok(()),
};
let file = std::fs::File::open(path)?;
let mut parsed: HashMap<String, TypedExperimentCatalogMetadata> = HashMap::new();
for line in BufReader::new(file).lines() {
let line = line?;
let Some(payload) = line.strip_prefix("#META\t") else {
if line.starts_with('#') {
continue;
}
break;
};
let mut fields = payload.split('\t');
match fields.next() {
Some("EXP") => {
let display_id = fields.next().ok_or_else(|| {
typed_metadata_error(path, "experiment metadata has no display ID")
})?;
let identity = fields.next().ok_or_else(|| {
typed_metadata_error(path, "experiment metadata has no stable identity")
})?;
let heating_rate = parse_typed_optional_f64(fields.next(), path)?;
let temperature_k = parse_typed_optional_f64(fields.next(), path)?;
let thermal_mode = match fields.next() {
Some("isothermal") => Some(CatalogThermalMode::Isothermal),
Some("non_isothermal") => Some(CatalogThermalMode::NonIsothermal),
Some("unspecified" | "unknown") => Some(CatalogThermalMode::Unspecified),
_ => return Err(typed_metadata_error(path, "invalid thermal mode metadata")),
};
let _comment = decode_typed_optional_string(fields.next(), path)?;
if fields.next().is_some() {
return Err(typed_metadata_error(path, "malformed experiment metadata"));
}
let identity = unescape_metadata_field(identity, path)?;
let display_id = unescape_metadata_field(display_id, path)?;
let metadata = TypedExperimentCatalogMetadata {
display_id,
thermal_mode,
temperature_k,
heating_rate_k_per_min: heating_rate,
..Default::default()
};
if parsed.insert(identity, metadata).is_some() {
return Err(typed_metadata_error(path, "duplicate experiment metadata"));
}
}
Some("ACQ") => {
let display_id = fields.next().ok_or_else(|| {
typed_metadata_error(path, "acquisition metadata has no experiment ID")
})?;
let date = decode_typed_optional_string(fields.next(), path)?;
let _time = decode_typed_optional_string(fields.next(), path)?;
let sample = decode_typed_optional_string(fields.next(), path)?;
let _mass = parse_typed_optional_f64(fields.next(), path)?;
let _mass_unit = fields.next().ok_or_else(|| {
typed_metadata_error(path, "acquisition metadata has no mass unit field")
})?;
let instrument = decode_typed_optional_string(fields.next(), path)?;
let operator = decode_typed_optional_string(fields.next(), path)?;
if fields.next().is_some() {
return Err(typed_metadata_error(path, "malformed acquisition metadata"));
}
let display_id = unescape_metadata_field(display_id, path)?;
let metadata = parsed
.values_mut()
.find(|metadata| metadata.display_id == display_id)
.ok_or_else(|| {
typed_metadata_error(
path,
"acquisition metadata precedes or lacks experiment metadata",
)
})?;
if metadata.acquisition.is_some() {
return Err(typed_metadata_error(path, "duplicate acquisition metadata"));
}
metadata.acquisition = Some(TypedAcquisitionCatalogMetadata {
date,
sample,
instrument,
operator,
});
}
_ => {}
}
}
for expected in expected_experiments {
let Some(actual) = parsed.get(&expected.source_identity) else {
return Err(typed_metadata_error(
path,
&format!(
"typed CSV has no metadata for experiment '{}'",
expected.display_name
),
));
};
check_typed_metadata_field(
path,
&expected.display_name,
"display name",
&actual.display_id,
&expected.display_name,
)?;
let actual_mode = actual
.thermal_mode
.unwrap_or(CatalogThermalMode::Unspecified);
let expected_mode = expected
.thermal_mode
.unwrap_or(CatalogThermalMode::Unspecified);
check_typed_metadata_field(
path,
&expected.display_name,
"thermal mode",
&actual_mode,
&expected_mode,
)?;
check_typed_metadata_field(
path,
&expected.display_name,
"isothermal temperature",
&actual.temperature_k,
&expected.temperature_k,
)?;
check_typed_metadata_field(
path,
&expected.display_name,
"heating rate",
&actual.heating_rate_k_per_min,
&expected.heating_rate_k_per_min,
)?;
let expected_has_acquisition = expected.date.is_some()
|| expected.sample.is_some()
|| expected.instrument.is_some()
|| expected.operator.is_some();
let acquisition = match (&actual.acquisition, expected_has_acquisition) {
(None, true) => {
return Err(typed_metadata_error(
path,
&format!(
"typed CSV is missing acquisition metadata for experiment '{}'",
expected.display_name
),
));
}
(Some(actual), _) => Some(actual),
(None, false) => None,
};
if let Some(acquisition) = acquisition {
check_typed_metadata_field(
path,
&expected.display_name,
"measurement date",
&acquisition.date,
&expected.date,
)?;
check_typed_metadata_field(
path,
&expected.display_name,
"sample description",
&acquisition.sample,
&expected.sample,
)?;
check_typed_metadata_field(
path,
&expected.display_name,
"instrument",
&acquisition.instrument,
&expected.instrument,
)?;
check_typed_metadata_field(
path,
&expected.display_name,
"operator",
&acquisition.operator,
&expected.operator,
)?;
}
}
Ok(())
}
#[derive(Default)]
struct TypedExperimentCatalogMetadata {
display_id: String,
thermal_mode: Option<CatalogThermalMode>,
temperature_k: Option<f64>,
heating_rate_k_per_min: Option<f64>,
acquisition: Option<TypedAcquisitionCatalogMetadata>,
}
#[derive(Default)]
struct TypedAcquisitionCatalogMetadata {
date: Option<String>,
sample: Option<String>,
instrument: Option<String>,
operator: Option<String>,
}
fn parse_typed_optional_f64(
value: Option<&str>,
path: &Path,
) -> Result<Option<f64>, CatalogStoreError> {
let value =
value.ok_or_else(|| typed_metadata_error(path, "missing numeric metadata field"))?;
if value == "0" || value == "-" {
return Ok(None);
}
let value = value
.strip_prefix("1:")
.ok_or_else(|| typed_metadata_error(path, "malformed optional numeric metadata"))?;
value
.parse::<f64>()
.map(Some)
.map_err(|_| typed_metadata_error(path, "invalid numeric metadata value"))
}
fn decode_typed_optional_string(
value: Option<&str>,
path: &Path,
) -> Result<Option<String>, CatalogStoreError> {
let value = value.ok_or_else(|| typed_metadata_error(path, "missing text metadata field"))?;
if value == "0" || value == "-" {
return Ok(None);
}
let value = value
.strip_prefix("1:")
.ok_or_else(|| typed_metadata_error(path, "malformed optional text metadata"))?;
unescape_metadata_field(value, path).map(Some)
}
fn typed_metadata_error(path: &Path, reason: &str) -> CatalogStoreError {
CatalogStoreError::TypedDocumentTargetMismatch {
path: path.to_path_buf(),
reason: reason.to_string(),
}
}
fn check_typed_metadata_field<T: PartialEq + std::fmt::Debug>(
path: &Path,
experiment: &str,
field: &str,
actual: &T,
expected: &T,
) -> Result<(), CatalogStoreError> {
if actual == expected {
Ok(())
} else {
Err(typed_metadata_error(
path,
&format!(
"{field} for experiment '{experiment}' differs between typed CSV ({actual:?}) and catalog snapshot ({expected:?})"
),
))
}
}
fn unescape_metadata_field(value: &str, path: &Path) -> Result<String, CatalogStoreError> {
let mut decoded = String::with_capacity(value.len());
let mut chars = value.chars();
while let Some(character) = chars.next() {
if character != '\\' {
decoded.push(character);
continue;
}
match chars.next() {
Some('\\') => decoded.push('\\'),
Some('t') => decoded.push('\t'),
Some('n') => decoded.push('\n'),
Some('r') => decoded.push('\r'),
Some(other) => {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: format!("unsupported metadata escape sequence \\{other}"),
});
}
None => {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "trailing escape character in metadata".into(),
});
}
}
}
Ok(decoded)
}
fn read_typed_document_header(path: &Path) -> Result<TypedDocumentHeader, CatalogStoreError> {
let file = std::fs::File::open(path)?;
read_typed_document_header_from_reader(path, file)
}
fn read_typed_document_header_from_reader(
path: &Path,
reader: impl Read,
) -> Result<TypedDocumentHeader, CatalogStoreError> {
let mut lines = BufReader::new(reader).lines();
let first =
lines
.next()
.transpose()?
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "file is empty".into(),
})?;
if first.starts_with("# KiThe TGA Dataset") {
let mut experiment_identity = None;
for line in lines {
let line = line?;
if let Some(value) = line.strip_prefix("# Experiment identity: ") {
if experiment_identity.is_some() || CatalogId::parse(value.to_string()).is_err() {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "duplicate or invalid experiment identity".into(),
});
}
experiment_identity = Some(value.to_string());
} else if !line.starts_with('#') {
break;
}
}
return Ok(TypedDocumentHeader::Dataset {
experiment_identity,
});
}
let version_line = if first == "# KiThe TGA Series" {
lines
.next()
.transpose()?
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "typed-series document is missing its format version".into(),
})?
} else {
first
};
let Some(version) = version_line.strip_prefix("# format_version=") else {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "expected a typed dataset or typed-series CSV header".into(),
});
};
if version.parse::<u32>().is_err() {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: format!("invalid typed-series format version '{version}'"),
});
}
let mut series_identity = None;
let mut experiment_identities = Vec::new();
let mut analysis_catalog = None;
let mut experiment_display_ids = HashMap::new();
let mut kinetic_method_outputs = Vec::new();
for line in lines {
let line = line?;
let Some(payload) = line.strip_prefix("#META\t") else {
if line.starts_with('#') {
continue;
}
break;
};
let mut fields = payload.split('\t');
match fields.next() {
Some("SERIES") => {
let identity = fields
.next()
.filter(|_| fields.next().is_none())
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "malformed SERIES metadata".into(),
})?;
if series_identity.replace(identity.to_string()).is_some() {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "duplicate SERIES metadata".into(),
});
}
}
Some("EXP") => {
let display_id =
fields
.next()
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "experiment metadata has no display ID".into(),
})?;
let identity =
fields
.next()
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "experiment metadata has no stable identity".into(),
})?;
CatalogId::parse(identity.to_string()).map_err(|error| {
CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: format!("invalid experiment identity: {error}"),
}
})?;
if experiment_identities
.iter()
.any(|existing| existing == identity)
{
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: format!("duplicate experiment identity {identity}"),
});
}
experiment_identities.push(identity.to_string());
experiment_display_ids.insert(display_id.to_string(), identity.to_string());
}
Some("ANALYSIS") => {
let payload = fields.next().filter(|_| fields.next().is_none());
let parsed = payload
.and_then(|json| serde_json::from_str::<AnalysisResultCatalog>(json).ok());
if analysis_catalog.is_some() || parsed.is_none() {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "malformed or duplicate ANALYSIS metadata".into(),
});
}
analysis_catalog = parsed;
}
Some("PROV") => {
let display_id =
fields
.next()
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "provenance metadata has no experiment ID".into(),
})?;
let output_column =
fields
.next()
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "provenance metadata has no column name".into(),
})?;
let provenance_json = fields.next().filter(|_| fields.next().is_none());
let Some(provenance_json) = provenance_json else {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "malformed PROV metadata".into(),
});
};
let provenance: ColumnProvenance = serde_json::from_str(provenance_json)?;
let Some(ColumnTransformKind::KineticMethod {
method,
model,
solver,
output_unit,
parameters,
sources,
value_range,
diagnostics,
}) = provenance.steps.last().map(|step| &step.kind)
else {
continue;
};
let experiment_identity = experiment_display_ids
.get(display_id)
.cloned()
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: format!(
"provenance for column '{output_column}' precedes or lacks its EXP metadata"
),
})?;
kinetic_method_outputs.push(CatalogKineticMethodOutput {
experiment_identity,
experiment_id_snapshot: unescape_metadata_field(display_id, path)?,
output_column: unescape_metadata_field(output_column, path)?,
method: method.clone(),
model: model.clone(),
solver: solver.clone(),
output_unit: output_unit.clone(),
parameters: parameters.clone(),
sources: sources.clone(),
value_range: value_range.clone(),
diagnostics: diagnostics.clone(),
});
}
_ => {}
}
}
let series_identity =
series_identity.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "typed-series document has no stable SERIES identity".into(),
})?;
CatalogId::parse(series_identity.clone()).map_err(|error| {
CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: format!("invalid series identity: {error}"),
}
})?;
if experiment_identities.is_empty() {
return Err(CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "typed series contains no experiments".into(),
});
}
let analysis_results = analysis_catalog
.ok_or_else(|| CatalogStoreError::InvalidTypedDocument {
path: path.to_path_buf(),
reason: "typed series is missing its analysis-result metadata".into(),
})?
.records()
.to_vec();
Ok(TypedDocumentHeader::Series {
series_identity,
experiment_identities,
analysis_results,
kinetic_method_outputs,
})
}
pub fn source_kind_from_lineage(lineage: &DataLineage) -> super::SourceKind {
let mut measured = false;
let mut synthetic = false;
let mut reconstructed = false;
for contribution in &lineage.contributions {
match &contribution.source {
DataSource::Measured { .. } => measured = true,
DataSource::Synthetic { .. } | DataSource::Simulated { .. } => synthetic = true,
DataSource::Reconstructed { .. } => reconstructed = true,
DataSource::Imported { .. } => {}
}
}
let kinds = [measured, synthetic, reconstructed]
.into_iter()
.filter(|present| *present)
.count();
if kinds > 1 {
super::SourceKind::Mixed
} else if measured {
super::SourceKind::Measured
} else if synthetic {
super::SourceKind::Synthetic
} else if reconstructed {
super::SourceKind::Reconstructed
} else {
super::SourceKind::Unknown
}
}
fn upsert_series_snapshot(
tx: &Transaction<'_>,
series: &CatalogSeries,
experiments: &[CatalogExperiment],
) -> Result<(), CatalogStoreError> {
if series.display_name.trim().is_empty() {
return Err(CatalogValidationError::EmptyDisplayName.into());
}
let mut seen = std::collections::HashSet::with_capacity(experiments.len());
for experiment in experiments {
experiment.validate()?;
if !seen.insert(experiment.id.as_str()) {
return Err(
CatalogValidationError::DuplicateSeriesMember(experiment.id.clone()).into(),
);
}
}
validate_series_sample_materials(
tx,
&series.id,
&experiments
.iter()
.map(|experiment| experiment.id.clone())
.collect::<Vec<_>>(),
)?;
tx.execute(
"INSERT INTO series(id, display_name, payload_json) VALUES (?1, ?2, ?3)
ON CONFLICT(id) DO UPDATE SET display_name = excluded.display_name,
payload_json = excluded.payload_json",
params![
series.id.as_str(),
series.display_name,
serde_json::to_string(series)?
],
)?;
for experiment in experiments {
upsert_experiment_snapshot(tx, experiment)?;
}
tx.execute(
"DELETE FROM series_members WHERE series_id = ?1",
[series.id.as_str()],
)?;
for (ordinal, experiment) in experiments.iter().enumerate() {
let ordinal = i64::try_from(ordinal)
.map_err(|_| CatalogStoreError::SeriesTooManyExperiments(ordinal))?;
tx.execute(
"INSERT INTO series_members(series_id, experiment_id, ordinal)
VALUES (?1, ?2, ?3)",
params![series.id.as_str(), experiment.id.as_str(), ordinal],
)?;
}
Ok(())
}
fn validate_series_sample_materials(
tx: &Transaction<'_>,
series_id: &CatalogId,
experiment_ids: &[CatalogId],
) -> Result<(), CatalogStoreError> {
let Some(substance_id) = tx
.query_row(
"SELECT substance_id FROM series_substances WHERE series_id = ?1",
[series_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?
else {
return Ok(());
};
for experiment_id in experiment_ids {
let sample_id = tx
.query_row(
"SELECT es.sample_id FROM experiment_samples es
JOIN samples sa ON sa.id = es.sample_id
WHERE es.experiment_id = ?1 AND sa.substance_id <> ?2",
params![experiment_id.as_str(), substance_id],
|row| row.get::<_, String>(0),
)
.optional()?;
if let Some(sample_id) = sample_id {
return Err(CatalogStoreError::SeriesSampleSubstanceMismatch {
series_id: series_id.clone(),
sample_id: CatalogId::parse(sample_id)?,
});
}
}
Ok(())
}
fn upsert_experiment_snapshot(
tx: &Transaction<'_>,
experiment: &CatalogExperiment,
) -> Result<(), CatalogStoreError> {
experiment.validate()?;
tx.execute(
"INSERT INTO experiments(id, source_identity, display_name, payload_json)
VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(id) DO UPDATE SET source_identity = excluded.source_identity,
display_name = excluded.display_name,
payload_json = excluded.payload_json",
params![
experiment.id.as_str(),
experiment.source_identity,
experiment.display_name,
serde_json::to_string(experiment)?
],
)?;
Ok(())
}
fn validate_experiment_identity(experiment: &CatalogExperiment) -> Result<(), CatalogStoreError> {
let source_id = CatalogId::parse(experiment.source_identity.clone())?;
if source_id != experiment.id {
return Err(CatalogStoreError::ExperimentIdentityMismatch);
}
experiment.validate()?;
Ok(())
}
fn insert_inspected_artifact(
tx: &Transaction<'_>,
item: InspectedArtifactFile,
) -> Result<CatalogArtifact, CatalogStoreError> {
let root_path = item.root_path.to_string_lossy().into_owned();
let root_id = match tx
.query_row(
"SELECT id FROM artifact_roots WHERE canonical_path = ?1",
[&root_path],
|row| row.get::<_, String>(0),
)
.optional()?
{
Some(id) => id,
None => {
let id = uuid::Uuid::new_v4().to_string();
tx.execute(
"INSERT INTO artifact_roots(id, canonical_path) VALUES (?1, ?2)",
params![id, root_path],
)?;
id
}
};
let artifact = CatalogArtifact {
id: CatalogId::new(),
purpose: item.purpose,
format: item
.canonical_path
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("unknown")
.to_ascii_lowercase(),
file_name: item.file_name.clone(),
size_bytes: item.size_bytes,
sha256: item.sha256,
locations: vec![ArtifactLocation::Local {
root_id,
relative_path: item.file_name,
}],
};
artifact.validate()?;
let size_bytes = i64::try_from(artifact.size_bytes)
.map_err(|_| CatalogStoreError::ArtifactSizeOutOfRange(artifact.size_bytes))?;
tx.execute(
"INSERT INTO artifacts(id, sha256, size_bytes, payload_json) VALUES (?1, ?2, ?3, ?4)",
params![
artifact.id.as_str(),
artifact.sha256,
size_bytes,
serde_json::to_string(&artifact)?
],
)?;
Ok(artifact)
}
#[cfg(test)]
fn inspect_artifact_files(
files: &[CatalogArtifactFile],
) -> Result<Vec<InspectedArtifactFile>, CatalogStoreError> {
inspect_artifact_files_with_progress(files, &mut |_| true)
}
fn inspect_artifact_files_with_progress(
files: &[CatalogArtifactFile],
progress: &mut dyn FnMut(ArtifactHashProgress) -> bool,
) -> Result<Vec<InspectedArtifactFile>, CatalogStoreError> {
let mut prepared = Vec::with_capacity(files.len());
let mut seen = std::collections::HashSet::with_capacity(files.len());
for selected in files {
let canonical_path = std::fs::canonicalize(&selected.path)?;
validate_artifact_purpose_format(&canonical_path, &selected.purpose)?;
let file = std::fs::File::open(&canonical_path)?;
let metadata = file.metadata()?;
let path_metadata = std::fs::metadata(&canonical_path)?;
if !metadata.is_file() {
return Err(CatalogStoreError::ArtifactNotAFile(canonical_path));
}
if metadata.len() != path_metadata.len()
|| metadata.modified().ok() != path_metadata.modified().ok()
{
return Err(CatalogStoreError::ArtifactChangedDuringHash(canonical_path));
}
if !seen.insert(canonical_path.clone()) {
return Err(CatalogStoreError::DuplicateArtifactSource(canonical_path));
}
let root_path = canonical_path
.parent()
.ok_or_else(|| CatalogStoreError::ArtifactNotAFile(canonical_path.clone()))?
.to_path_buf();
let file_name = canonical_path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.ok_or_else(|| CatalogStoreError::ArtifactNotAFile(canonical_path.clone()))?;
prepared.push((
canonical_path,
root_path,
file_name,
metadata,
path_metadata,
file,
selected.purpose.clone(),
));
}
let total_bytes = prepared
.iter()
.fold(0_u64, |total, item| total.saturating_add(item.3.len()));
if !progress(ArtifactHashProgress {
file_count: prepared.len(),
total_bytes,
..ArtifactHashProgress::default()
}) {
return Err(CatalogStoreError::PublicationCancelled);
}
let mut inspected = Vec::with_capacity(prepared.len());
let mut bytes_before_file = 0_u64;
for (index, (canonical_path, root_path, file_name, before, path_before, mut file, purpose)) in
prepared.into_iter().enumerate()
{
let progress_file_name = file_name.clone();
let mut reader = BufReader::new(&mut file);
let mut first_line = String::new();
reader.read_line(&mut first_line)?;
drop(reader);
let typed_signature = first_line.starts_with("# KiThe TGA Dataset")
|| first_line.starts_with("# KiThe TGA Series")
|| first_line.starts_with("# format_version=");
let typed_header =
if purpose == super::CatalogArtifactPurpose::TypedKiTheDocument || typed_signature {
file.seek(SeekFrom::Start(0))?;
Some(read_typed_document_header_from_reader(
&canonical_path,
&mut file,
)?)
} else {
None
};
let (size_bytes, sha256) = hash_open_file_with_progress(
&canonical_path,
&mut file,
before,
path_before,
&mut |bytes_in_file| {
progress(ArtifactHashProgress {
file_index: index + 1,
file_count: files.len(),
file_name: progress_file_name.clone(),
bytes_in_file,
bytes_total: bytes_before_file.saturating_add(bytes_in_file),
total_bytes,
})
},
)?;
inspected.push(InspectedArtifactFile {
canonical_path,
root_path,
file_name,
size_bytes,
sha256,
purpose,
typed_header,
});
bytes_before_file = bytes_before_file.saturating_add(size_bytes);
}
Ok(inspected)
}
fn check_publication_commit_boundary(
inspected: &[InspectedArtifactFile],
file_count: usize,
progress: &mut dyn FnMut(ArtifactHashProgress) -> bool,
) -> Result<(), CatalogStoreError> {
let total_bytes = inspected
.iter()
.fold(0_u64, |total, file| total.saturating_add(file.size_bytes));
if progress(ArtifactHashProgress {
file_index: file_count,
file_count,
file_name: "Committing catalog metadata".into(),
bytes_total: total_bytes,
total_bytes,
..ArtifactHashProgress::default()
}) {
Ok(())
} else {
Err(CatalogStoreError::PublicationCancelled)
}
}
fn validate_artifact_purpose_format(
path: &Path,
purpose: &super::CatalogArtifactPurpose,
) -> Result<(), CatalogStoreError> {
let extension = path
.extension()
.and_then(|value| value.to_str())
.unwrap_or_default()
.to_ascii_lowercase();
let matches = match purpose {
super::CatalogArtifactPurpose::TypedKiTheDocument => extension == "csv",
super::CatalogArtifactPurpose::ProcessedResults => {
matches!(extension.as_str(), "csv" | "txt" | "tsv" | "xlsx")
}
super::CatalogArtifactPurpose::PlotImage => {
matches!(extension.as_str(), "png" | "jpg" | "jpeg")
}
super::CatalogArtifactPurpose::EditableKiThePlot => extension == "kplot",
super::CatalogArtifactPurpose::RawInstrumentData | super::CatalogArtifactPurpose::Other => {
true
}
};
if matches {
Ok(())
} else {
Err(CatalogStoreError::ArtifactPurposeFormatMismatch {
path: path.to_path_buf(),
purpose: format!("{:?}", purpose),
})
}
}
fn insert_publication(
tx: &Transaction<'_>,
publication: &CatalogPublication,
) -> Result<(), CatalogStoreError> {
publication.validate()?;
match publication.object_kind {
CatalogObjectKind::Experiment => {
require_experiment(tx, &publication.object_id)?;
if !publication.series_members.is_empty() {
return Err(CatalogValidationError::DuplicateSeriesMember(
publication.object_id.clone(),
)
.into());
}
}
CatalogObjectKind::Series => require_series(tx, &publication.object_id)?,
}
for member in &publication.series_members {
require_experiment(tx, &member.experiment_id)?;
}
for artifact_id in &publication.artifact_ids {
let exists = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM artifacts WHERE id = ?1)",
[artifact_id.as_str()],
|row| row.get::<_, bool>(0),
)?;
if !exists {
return Err(CatalogStoreError::NotFound(artifact_id.as_str().to_owned()));
}
}
if let Some(parent_id) = &publication.parent_publication_id {
let parent = tx
.query_row(
"SELECT payload_json FROM publications WHERE id = ?1",
[parent_id.as_str()],
|row| row.get::<_, String>(0),
)
.optional()?;
let Some(parent_json) = parent else {
return Err(CatalogStoreError::NotFound(parent_id.as_str().to_owned()));
};
let parent: CatalogPublication = serde_json::from_str(&parent_json)?;
if parent.object_kind != publication.object_kind
|| parent.object_id != publication.object_id
{
return Err(CatalogStoreError::ParentPublicationTargetMismatch);
}
}
tx.execute(
"INSERT INTO publications(id, object_id, parent_id, created_at, payload_json) VALUES (?1, ?2, ?3, ?4, ?5)",
params![
publication.id.as_str(),
publication.object_id.as_str(),
publication.parent_publication_id.as_ref().map(CatalogId::as_str),
publication.created_at_rfc3339,
serde_json::to_string(publication)?,
],
)?;
for member in &publication.series_members {
tx.execute(
"INSERT INTO publication_members(publication_id, experiment_id, ordinal) VALUES (?1, ?2, ?3)",
params![publication.id.as_str(), member.experiment_id.as_str(), member.ordinal],
)?;
}
for artifact_id in &publication.artifact_ids {
tx.execute(
"INSERT INTO publication_artifacts(publication_id, artifact_id) VALUES (?1, ?2)",
params![publication.id.as_str(), artifact_id.as_str()],
)?;
}
Ok(())
}
fn initialize_schema(connection: &mut Connection) -> Result<(), CatalogStoreError> {
let version: i64 = connection.pragma_query_value(None, "user_version", |row| row.get(0))?;
if version > SCHEMA_VERSION {
return Err(CatalogStoreError::UnsupportedSchema(version));
}
if version == SCHEMA_VERSION {
return Ok(());
}
let tx = connection.transaction()?;
if version == 0 {
tx.execute_batch(
"CREATE TABLE IF NOT EXISTS experiments (
id TEXT PRIMARY KEY NOT NULL,
source_identity TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL,
payload_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS series (
id TEXT PRIMARY KEY NOT NULL,
display_name TEXT NOT NULL,
payload_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS series_members (
series_id TEXT NOT NULL REFERENCES series(id) ON DELETE CASCADE,
experiment_id TEXT NOT NULL REFERENCES experiments(id),
ordinal INTEGER NOT NULL,
PRIMARY KEY(series_id, experiment_id),
UNIQUE(series_id, ordinal)
);
CREATE TABLE IF NOT EXISTS artifacts (
id TEXT PRIMARY KEY NOT NULL,
sha256 TEXT NOT NULL,
size_bytes INTEGER NOT NULL CHECK(size_bytes >= 0),
payload_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS publications (
id TEXT PRIMARY KEY NOT NULL,
object_id TEXT NOT NULL,
parent_id TEXT REFERENCES publications(id),
created_at TEXT NOT NULL,
payload_json TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS publications_object_idx ON publications(object_id, created_at);
CREATE TABLE IF NOT EXISTS publication_members (
publication_id TEXT NOT NULL REFERENCES publications(id) ON DELETE CASCADE,
experiment_id TEXT NOT NULL REFERENCES experiments(id),
ordinal INTEGER NOT NULL,
PRIMARY KEY(publication_id, experiment_id),
UNIQUE(publication_id, ordinal)
);
CREATE TABLE IF NOT EXISTS publication_artifacts (
publication_id TEXT NOT NULL REFERENCES publications(id) ON DELETE CASCADE,
artifact_id TEXT NOT NULL REFERENCES artifacts(id),
PRIMARY KEY(publication_id, artifact_id)
);",
)?;
}
if version <= 1 {
tx.execute_batch(
"CREATE TABLE IF NOT EXISTS catalog_meta (
key TEXT PRIMARY KEY NOT NULL,
value TEXT NOT NULL
);",
)?;
tx.execute(
"INSERT OR IGNORE INTO catalog_meta(key, value) VALUES ('library_id', ?1)",
[uuid::Uuid::new_v4().to_string()],
)?;
}
if version <= 2 {
tx.execute_batch(
"CREATE TABLE IF NOT EXISTS artifact_roots (
id TEXT PRIMARY KEY NOT NULL,
canonical_path TEXT NOT NULL UNIQUE
);",
)?;
}
if version <= 3 {
tx.execute_batch(
"CREATE TABLE IF NOT EXISTS studies (
id TEXT PRIMARY KEY NOT NULL,
display_name TEXT NOT NULL,
payload_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS substances (
id TEXT PRIMARY KEY NOT NULL,
display_name TEXT NOT NULL,
payload_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS samples (
id TEXT PRIMARY KEY NOT NULL,
substance_id TEXT NOT NULL REFERENCES substances(id),
display_name TEXT NOT NULL,
payload_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS study_substances (
study_id TEXT NOT NULL REFERENCES studies(id) ON DELETE CASCADE,
substance_id TEXT NOT NULL REFERENCES substances(id),
PRIMARY KEY(study_id, substance_id)
);
CREATE TABLE IF NOT EXISTS series_substances (
series_id TEXT PRIMARY KEY NOT NULL REFERENCES series(id) ON DELETE CASCADE,
substance_id TEXT NOT NULL REFERENCES substances(id)
);
CREATE TABLE IF NOT EXISTS study_series (
study_id TEXT NOT NULL REFERENCES studies(id) ON DELETE CASCADE,
series_id TEXT NOT NULL REFERENCES series(id),
PRIMARY KEY(study_id, series_id)
);
CREATE TABLE IF NOT EXISTS experiment_samples (
experiment_id TEXT PRIMARY KEY NOT NULL REFERENCES experiments(id) ON DELETE CASCADE,
sample_id TEXT NOT NULL REFERENCES samples(id)
);
CREATE INDEX IF NOT EXISTS studies_name_idx ON studies(display_name COLLATE NOCASE);
CREATE INDEX IF NOT EXISTS substances_name_idx ON substances(display_name COLLATE NOCASE);
CREATE INDEX IF NOT EXISTS samples_substance_idx ON samples(substance_id);",
)?;
}
tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;
tx.commit()?;
Ok(())
}
fn read_library_id(connection: &Connection) -> Result<String, CatalogStoreError> {
Ok(connection.query_row(
"SELECT value FROM catalog_meta WHERE key = 'library_id'",
[],
|row| row.get(0),
)?)
}
fn list_payloads<T: serde::de::DeserializeOwned>(
connection: &Connection,
table: &str,
name_column: &str,
) -> Result<Vec<T>, CatalogStoreError> {
let sql = format!("SELECT payload_json FROM {table} ORDER BY {name_column} COLLATE NOCASE, id");
let mut statement = connection.prepare(&sql)?;
let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
rows.map(|row| serde_json::from_str(&row?).map_err(CatalogStoreError::from))
.collect()
}
fn get_payload<T: serde::de::DeserializeOwned>(
connection: &Connection,
table: &str,
id: &CatalogId,
) -> Result<Option<T>, CatalogStoreError> {
let sql = format!("SELECT payload_json FROM {table} WHERE id = ?1");
let payload = connection
.query_row(&sql, [id.as_str()], |row| row.get::<_, String>(0))
.optional()?;
payload
.map(|json| serde_json::from_str(&json).map_err(CatalogStoreError::from))
.transpose()
}
fn require_study(tx: &Transaction<'_>, id: &CatalogId) -> Result<(), CatalogStoreError> {
let exists = tx.query_row("SELECT 1 FROM studies WHERE id = ?1", [id.as_str()], |_| {
Ok(())
});
exists.map_err(|error| match error {
rusqlite::Error::QueryReturnedNoRows => CatalogStoreError::NotFound(id.as_str().to_owned()),
other => CatalogStoreError::Database(other),
})
}
fn require_substance(tx: &Transaction<'_>, id: &CatalogId) -> Result<(), CatalogStoreError> {
let exists = tx.query_row(
"SELECT 1 FROM substances WHERE id = ?1",
[id.as_str()],
|_| Ok(()),
);
exists.map_err(|error| match error {
rusqlite::Error::QueryReturnedNoRows => CatalogStoreError::NotFound(id.as_str().to_owned()),
other => CatalogStoreError::Database(other),
})
}
fn validate_members(members: &[PublishedSeriesMember]) -> Result<(), CatalogStoreError> {
let mut ids = std::collections::HashSet::new();
let mut ordinals = std::collections::HashSet::new();
for member in members {
if !ids.insert(&member.experiment_id) {
return Err(CatalogValidationError::DuplicateSeriesMember(
member.experiment_id.clone(),
)
.into());
}
if !ordinals.insert(member.ordinal) {
return Err(CatalogValidationError::DuplicateMemberOrder(member.ordinal).into());
}
}
Ok(())
}
fn require_series(tx: &Transaction<'_>, id: &CatalogId) -> Result<(), CatalogStoreError> {
let exists = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM series WHERE id = ?1)",
[id.as_str()],
|row| row.get::<_, bool>(0),
)?;
if exists {
Ok(())
} else {
Err(CatalogStoreError::NotASeries(id.as_str().to_owned()))
}
}
fn require_experiment(tx: &Transaction<'_>, id: &CatalogId) -> Result<(), CatalogStoreError> {
let exists = tx.query_row(
"SELECT EXISTS(SELECT 1 FROM experiments WHERE id = ?1)",
[id.as_str()],
|row| row.get::<_, bool>(0),
)?;
if exists {
Ok(())
} else {
Err(CatalogStoreError::NotFound(id.as_str().to_owned()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Kinetics::experimental_kinetics::catalog::{
CatalogArtifactPurpose, CatalogObjectKind, CatalogPublicationSnapshot, CatalogSeries,
SourceKind,
};
fn experiment() -> CatalogExperiment {
CatalogExperiment {
id: CatalogId::new(),
source_identity: "kithe-identity-1".into(),
display_name: "run A".into(),
source_kind: SourceKind::Measured,
date: None,
sample: Some("sample-1".into()),
instrument: None,
operator: None,
thermal_mode: Some(super::super::CatalogThermalMode::Isothermal),
temperature_k: Some(500.0),
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
}
}
fn artifact() -> CatalogArtifact {
CatalogArtifact {
id: CatalogId::new(),
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
format: "csv".into(),
file_name: "run.csv".into(),
size_bytes: 12,
sha256: "b".repeat(64),
locations: vec![],
}
}
#[test]
fn lineage_source_kind_reports_mixed_contributions_without_guessing_imports() {
use crate::Kinetics::experimental_kinetics::data_lineage::{DataContribution, DataSource};
let lineage = DataLineage {
row_namespace: "rows-1".into(),
next_row_id: 3,
contributions: vec![
DataContribution {
source: DataSource::Measured { artifact_id: None },
columns: vec!["mass".into()],
row_ranges: vec![
crate::Kinetics::experimental_kinetics::data_lineage::RowIdRange {
namespace: "rows-1".into(),
first: 0,
last: 2,
},
],
input_refs: vec![],
operation_id: None,
},
DataContribution {
source: DataSource::Reconstructed {
method: "fit".into(),
parameters: vec![],
},
columns: vec!["mass".into()],
row_ranges: vec![
crate::Kinetics::experimental_kinetics::data_lineage::RowIdRange {
namespace: "rows-1".into(),
first: 0,
last: 2,
},
],
input_refs: vec![],
operation_id: None,
},
],
};
assert_eq!(source_kind_from_lineage(&lineage), SourceKind::Mixed);
assert_eq!(
source_kind_from_lineage(&DataLineage::default()),
SourceKind::Unknown
);
}
#[test]
fn study_groups_substances_and_series_without_combining_kinetic_series() {
use super::super::{CatalogStudy, CatalogSubstance};
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path().join("catalog")).unwrap();
let study = CatalogStudy {
id: CatalogId::new(),
display_name: "related materials comparison".into(),
description: Some("Shared heating program, separate kinetic series".into()),
};
let substance_a = CatalogSubstance {
id: CatalogId::new(),
display_name: "Material A".into(),
formula: Some("C2H4".into()),
cas_number: None,
inchi_key: None,
description: None,
};
let substance_b = CatalogSubstance {
id: CatalogId::new(),
display_name: "Material B".into(),
formula: Some("C2H6".into()),
cas_number: None,
inchi_key: None,
description: None,
};
let series_a = CatalogSeries {
id: CatalogId::new(),
display_name: "Material A at 5 K/min".into(),
description: None,
};
let series_b = CatalogSeries {
id: CatalogId::new(),
display_name: "Material B at 5 K/min".into(),
description: None,
};
store.insert_study(&study).unwrap();
store.insert_substance(&substance_a).unwrap();
store.insert_substance(&substance_b).unwrap();
store.insert_series(&series_a).unwrap();
store.insert_series(&series_b).unwrap();
store
.assign_substance_to_series(&series_a.id, &substance_a.id)
.unwrap();
store
.assign_substance_to_series(&series_b.id, &substance_b.id)
.unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series_a.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: Some("researcher".into()),
description: Some("first processed version".into()),
series_members: Vec::new(),
artifact_ids: Vec::new(),
snapshot: Some(CatalogPublicationSnapshot::Series {
series: series_a.clone(),
experiments: Vec::new(),
}),
typed_documents: Vec::new(),
};
store.publish(&publication).unwrap();
store.add_series_to_study(&study.id, &series_a.id).unwrap();
store.add_series_to_study(&study.id, &series_b.id).unwrap();
assert_eq!(store.get_study(&study.id).unwrap(), Some(study.clone()));
assert_eq!(
store.list_study_substances(&study.id).unwrap(),
vec![substance_a.clone(), substance_b.clone()]
);
assert_eq!(
store.list_study_series(&study.id).unwrap(),
vec![series_a.clone(), series_b]
);
assert!(matches!(
store.assign_substance_to_series(&series_a.id, &substance_b.id),
Err(CatalogStoreError::SeriesSubstanceConflict {
series_id,
existing_substance_id,
requested_substance_id,
}) if series_id == series_a.id
&& existing_substance_id == substance_a.id
&& requested_substance_id == substance_b.id
));
assert_eq!(
store.substance_for_series(&series_a.id).unwrap(),
Some(substance_a.id)
);
let manifest = store.study_manifest(&study.id).unwrap();
let encoded = manifest.to_json().unwrap();
let restored = super::super::CatalogStudyManifest::from_json(&encoded).unwrap();
assert_eq!(restored, manifest);
assert_eq!(restored.series.len(), 2);
assert_eq!(restored.series[0].publications.len(), 1);
assert!(restored.series[0].publications[0].artifact_ids.is_empty());
}
#[test]
fn study_and_sample_creation_are_atomic_with_their_relationships() {
use super::super::{CatalogSample, CatalogStudy, CatalogSubstance};
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path().join("catalog")).unwrap();
let study = CatalogStudy {
id: CatalogId::new(),
display_name: "Campaign".into(),
description: None,
};
store.insert_study(&study).unwrap();
let substance = CatalogSubstance {
id: CatalogId::new(),
display_name: "Material A".into(),
formula: None,
cas_number: None,
inchi_key: None,
description: None,
};
store
.insert_substance_in_study(&substance, &study.id)
.unwrap();
let other_substance = CatalogSubstance {
id: CatalogId::new(),
display_name: "Material B".into(),
formula: None,
cas_number: None,
inchi_key: None,
description: None,
};
store.insert_substance(&other_substance).unwrap();
let mut measured = experiment();
measured.id = CatalogId::new();
measured.source_identity = measured.id.as_str().to_owned();
let mut measured_again = experiment();
measured_again.id = CatalogId::new();
measured_again.source_identity = measured_again.id.as_str().to_owned();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "Series A".into(),
description: None,
};
store
.register_series_snapshot(&series, &[measured.clone(), measured_again.clone()])
.unwrap();
store
.assign_substance_to_series(&series.id, &substance.id)
.unwrap();
let wrong_sample = CatalogSample {
id: CatalogId::new(),
substance_id: other_substance.id,
display_name: "invalid sample".into(),
batch_label: None,
preparation_note: None,
};
assert!(
store
.insert_sample_for_experiment(&wrong_sample, &measured.id)
.is_err()
);
assert!(store.list_samples().unwrap().is_empty());
let sample = CatalogSample {
id: CatalogId::new(),
substance_id: substance.id.clone(),
display_name: "prepared batch".into(),
batch_label: Some("B-17".into()),
preparation_note: None,
};
store
.insert_sample_for_experiment(&sample, &measured.id)
.unwrap();
store
.assign_sample_to_experiment(&measured_again.id, &sample.id)
.unwrap();
let mut expected_samples = vec![
(measured.id.clone(), sample.id.clone()),
(measured_again.id.clone(), sample.id.clone()),
];
expected_samples.sort_by(|left, right| left.0.as_str().cmp(right.0.as_str()));
assert_eq!(store.list_experiment_samples().unwrap(), expected_samples);
assert_eq!(
store.list_study_substances(&study.id).unwrap(),
vec![substance]
);
assert_eq!(
store.sample_for_experiment(&measured.id).unwrap(),
Some(sample.id.clone())
);
assert_eq!(
store.sample_for_experiment(&measured_again.id).unwrap(),
Some(sample.id)
);
}
#[test]
fn sample_and_series_substance_invariants_are_checked_atomically() {
use super::super::CatalogSample;
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path().join("catalog")).unwrap();
let substance_a = CatalogSubstance {
id: CatalogId::new(),
display_name: "Material A".into(),
formula: None,
cas_number: None,
inchi_key: None,
description: None,
};
let substance_b = CatalogSubstance {
id: CatalogId::new(),
display_name: "Material B".into(),
formula: None,
cas_number: None,
inchi_key: None,
description: None,
};
store.insert_substance(&substance_a).unwrap();
store.insert_substance(&substance_b).unwrap();
let sample_a = CatalogSample {
id: CatalogId::new(),
substance_id: substance_a.id.clone(),
display_name: "aliquot A".into(),
batch_label: Some("batch-1".into()),
preparation_note: None,
};
let sample_b = CatalogSample {
id: CatalogId::new(),
substance_id: substance_b.id.clone(),
display_name: "aliquot B".into(),
batch_label: None,
preparation_note: None,
};
store.insert_sample(&sample_a).unwrap();
store.insert_sample(&sample_b).unwrap();
let mut experiment = experiment();
experiment.id = CatalogId::new();
experiment.source_identity = experiment.id.as_str().to_owned();
store.register_experiment_snapshot(&experiment).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "A temperature series".into(),
description: None,
};
store.insert_series(&series).unwrap();
store
.assign_substance_to_series(&series.id, &substance_a.id)
.unwrap();
store
.assign_sample_to_experiment(&experiment.id, &sample_b.id)
.unwrap();
let member = PublishedSeriesMember {
experiment_id: experiment.id.clone(),
ordinal: 0,
};
assert!(matches!(
store.set_series_members(&series.id, std::slice::from_ref(&member)),
Err(CatalogStoreError::SeriesSampleSubstanceMismatch { .. })
));
assert!(
store
.connection
.query_row(
"SELECT COUNT(*) FROM series_members WHERE series_id = ?1",
[series.id.as_str()],
|row| row.get::<_, i64>(0)
)
.unwrap()
== 0
);
store
.assign_sample_to_experiment(&experiment.id, &sample_a.id)
.unwrap();
store.set_series_members(&series.id, &[member]).unwrap();
assert_eq!(
store.sample_for_experiment(&experiment.id).unwrap(),
Some(sample_a.id.clone())
);
assert!(matches!(
store.assign_sample_to_experiment(&experiment.id, &sample_b.id),
Err(CatalogStoreError::SeriesSampleSubstanceMismatch { .. })
));
assert_eq!(
store.sample_for_experiment(&experiment.id).unwrap(),
Some(sample_a.id)
);
}
#[test]
fn typed_series_header_is_bound_to_matching_series_and_ordered_members() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("series.csv");
let series_id = CatalogId::new();
let first = CatalogId::new();
let second = CatalogId::new();
std::fs::write(
&path,
format!(
"# format_version=10\n#META\tSERIES\t{}\n#META\tANALYSIS\t{{\"records\":[],\"next_id\":0}}\n#META\tEXP\trun-a\t{}\t-\t-\tunknown\t-\n#META\tEXP\trun-b\t{}\t-\t-\tunknown\t-\nrun-a_time,run-b_time\n0,0\n",
series_id.as_str(), first.as_str(), second.as_str()
),
)
.unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series_id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![
PublishedSeriesMember {
experiment_id: first.clone(),
ordinal: 0,
},
PublishedSeriesMember {
experiment_id: second,
ordinal: 1,
},
],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
validate_typed_document_targets(
&publication,
&[CatalogArtifactFile {
path,
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}],
)
.unwrap();
}
#[test]
fn typed_series_publication_rejects_metadata_that_conflicts_with_catalog_snapshot() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("series.csv");
let series_id = CatalogId::new();
let experiment_id = CatalogId::new();
std::fs::write(
&path,
format!(
"# KiThe TGA Series\n# format_version=10\n#META\tSERIES\t{}\n#META\tANALYSIS\t{{\"records\":[],\"next_id\":0}}\n#META\tEXP\trun-a\t{}\t0\t1:500\tisothermal\t0\n#META\tACQ\trun-a\t1:2026-12-01\t0\t1:sample-A\t0\t-\t1:instrument-A\t1:operator-A\nrun-a_time\n0\n",
series_id.as_str(),
experiment_id.as_str(),
),
)
.unwrap();
let mut experiment = experiment();
experiment.id = experiment_id.clone();
experiment.source_identity = experiment_id.as_str().to_string();
experiment.display_name = "run-a".into();
experiment.date = Some("2026-12-01".into());
experiment.sample = Some("sample-A".into());
experiment.instrument = Some("instrument-A".into());
experiment.operator = Some("operator-A".into());
experiment.thermal_mode = Some(CatalogThermalMode::Isothermal);
experiment.temperature_k = Some(500.0);
experiment.heating_rate_k_per_min = None;
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series_id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![PublishedSeriesMember {
experiment_id,
ordinal: 0,
}],
artifact_ids: vec![],
snapshot: Some(CatalogPublicationSnapshot::Series {
series: CatalogSeries {
id: series_id,
display_name: "series".into(),
description: None,
},
experiments: vec![experiment.clone()],
}),
typed_documents: vec![],
};
let file = CatalogArtifactFile {
path: path.clone(),
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
};
validate_typed_document_targets(&publication, std::slice::from_ref(&file)).unwrap();
let typed_contents = std::fs::read_to_string(&path).unwrap();
let without_acquisition = typed_contents
.lines()
.filter(|line| !line.starts_with("#META\tACQ\t"))
.collect::<Vec<_>>()
.join("\n");
std::fs::write(&path, without_acquisition).unwrap();
assert!(matches!(
validate_typed_document_targets(&publication, std::slice::from_ref(&file)),
Err(CatalogStoreError::TypedDocumentTargetMismatch { reason, .. })
if reason.contains("missing acquisition metadata")
));
std::fs::write(&path, typed_contents).unwrap();
let mut conflicting = publication;
if let Some(CatalogPublicationSnapshot::Series { experiments, .. }) =
conflicting.snapshot.as_mut()
{
experiments[0].instrument = Some("different-instrument".into());
}
assert!(matches!(
validate_typed_document_targets(&conflicting, std::slice::from_ref(&file)),
Err(CatalogStoreError::TypedDocumentTargetMismatch { .. })
));
}
#[test]
fn typed_series_cannot_be_published_under_an_experiment_or_different_series() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("series.csv");
let series_id = CatalogId::new();
let member_id = CatalogId::new();
std::fs::write(
&path,
format!(
"# format_version=10\n#META\tSERIES\t{}\n#META\tANALYSIS\t{{\"records\":[],\"next_id\":0}}\n#META\tEXP\trun\t{}\t-\t-\tunknown\t-\nrun_time\n0\n",
series_id.as_str(), member_id.as_str()
),
)
.unwrap();
let file = CatalogArtifactFile {
path,
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
};
let mut publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: member_id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
assert!(matches!(
validate_typed_document_targets(&publication, std::slice::from_ref(&file)),
Err(CatalogStoreError::TypedDocumentTargetMismatch { .. })
));
publication.object_kind = CatalogObjectKind::Series;
publication.object_id = CatalogId::new();
publication.series_members = vec![PublishedSeriesMember {
experiment_id: member_id,
ordinal: 0,
}];
assert!(matches!(
validate_typed_document_targets(&publication, &[file]),
Err(CatalogStoreError::TypedDocumentTargetMismatch { .. })
));
}
#[test]
fn typed_single_dataset_cannot_be_published_under_a_series() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("dataset.csv");
std::fs::write(
&path,
"# KiThe TGA Dataset\n# time [s], mass [mg]\ntime,mass\n0,10\n",
)
.unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: CatalogId::new(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let error = validate_typed_document_targets(
&publication,
&[CatalogArtifactFile {
path: path.clone(),
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}],
)
.unwrap_err();
let canonical_path = std::fs::canonicalize(&path).unwrap();
assert!(matches!(
error,
CatalogStoreError::TypedDocumentTargetMismatch { path: error_path, .. }
if error_path == canonical_path
));
}
#[test]
fn typed_single_dataset_requires_matching_experiment_identity() {
let temp = tempfile::tempdir().unwrap();
let identity = CatalogId::new();
let path = temp.path().join("dataset.csv");
std::fs::write(
&path,
format!(
"# KiThe TGA Dataset\n# time [s], mass [mg]\n# Experiment identity: {}\ntime,mass\n0,10\n",
identity.as_str()
),
)
.unwrap();
let file = CatalogArtifactFile {
path: path.clone(),
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
};
let mut publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: identity.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
assert!(validate_typed_document_targets(&publication, std::slice::from_ref(&file)).is_ok());
publication.object_id = CatalogId::new();
assert!(matches!(
validate_typed_document_targets(&publication, std::slice::from_ref(&file)),
Err(CatalogStoreError::TypedDocumentTargetMismatch { .. })
));
let mislabeled_file = CatalogArtifactFile {
path: path.clone(),
purpose: CatalogArtifactPurpose::Other,
};
assert!(matches!(
validate_typed_document_targets(&publication, std::slice::from_ref(&mislabeled_file)),
Err(CatalogStoreError::TypedDocumentTargetMismatch { .. })
));
std::fs::write(
&path,
"# KiThe TGA Dataset\n# time [s], mass [mg]\n# Experiment identity: not-a-uuid\ntime,mass\n0,10\n",
)
.unwrap();
assert!(matches!(
read_typed_document_header(&path),
Err(CatalogStoreError::InvalidTypedDocument { .. })
));
std::fs::write(
&path,
format!(
"# KiThe TGA Dataset\n# time [s], mass [mg]\n# Experiment identity: {}\n# Experiment identity: {}\ntime,mass\n0,10\n",
identity.as_str(), identity.as_str()
),
)
.unwrap();
assert!(matches!(
read_typed_document_header(&path),
Err(CatalogStoreError::InvalidTypedDocument { .. })
));
std::fs::write(
&path,
"# KiThe TGA Dataset\n# time [s], mass [mg]\ntime,mass\n0,10\n",
)
.unwrap();
assert!(matches!(
validate_typed_document_targets(&publication, &[file]),
Err(CatalogStoreError::TypedDocumentTargetMismatch { .. })
));
}
#[test]
fn typed_series_rejects_malformed_analysis_metadata_before_publication() {
let temp = tempfile::tempdir().unwrap();
let path = temp.path().join("series.csv");
let series_id = CatalogId::new();
let member_id = CatalogId::new();
std::fs::write(
&path,
format!(
"# KiThe TGA Series\n# format_version=10\n#META\tSERIES\t{}\n#META\tANALYSIS\t{{broken}}\n#META\tEXP\trun\t{}\t-\t-\tunknown\t-\nrun_time\n0\n",
series_id.as_str(), member_id.as_str()
),
)
.unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series_id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![PublishedSeriesMember {
experiment_id: member_id,
ordinal: 0,
}],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
assert!(matches!(
validate_typed_document_targets(
&publication,
&[CatalogArtifactFile {
path,
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}]
),
Err(CatalogStoreError::InvalidTypedDocument { .. })
));
}
#[test]
fn typed_series_with_series_level_ea_eta_result_round_trips_and_publishes_as_series() {
use crate::Kinetics::experimental_kinetics::experiment_series_main::{
TGAExperiment, TGASeries,
};
use crate::Kinetics::experimental_kinetics::kinetic_methods::integral_isoconversion::{
IsoLayerResult, IsoconversionalResult,
};
use crate::Kinetics::experimental_kinetics::kinetic_methods::kinetic_regression::LinearRegressionResult;
use crate::Kinetics::experimental_kinetics::one_experiment_dataset::TGADataset;
let temp = tempfile::tempdir().unwrap();
let input_path = temp.path().join("source.csv");
std::fs::write(
&input_path,
"time,temperature,mass\n0,500,10\n1,500,9.5\n2,500,9\n",
)
.unwrap();
let source =
TGADataset::from_csv(input_path.to_str().unwrap(), "time", "temperature", "mass")
.unwrap();
let second_input_path = temp.path().join("source-2.csv");
std::fs::write(
&second_input_path,
"time,temperature,mass\n0,600,10\n1,600,9.5\n2,600,9\n",
)
.unwrap();
let second_source = TGADataset::from_csv(
second_input_path.to_str().unwrap(),
"time",
"temperature",
"mass",
)
.unwrap();
let isoconversional = IsoconversionalResult {
method: "KAS",
layers: vec![
IsoLayerResult {
eta: 0.1,
ea: 81_000.0,
k: None,
regression: LinearRegressionResult {
r2: 0.99,
..LinearRegressionResult::default()
},
},
IsoLayerResult {
eta: 0.5,
ea: 83_000.0,
k: None,
regression: LinearRegressionResult {
r2: 0.98,
..LinearRegressionResult::default()
},
},
IsoLayerResult {
eta: 0.9,
ea: 85_000.0,
k: None,
regression: LinearRegressionResult {
r2: 0.97,
..LinearRegressionResult::default()
},
},
],
warnings: Vec::new(),
};
let mut series = TGASeries::new();
series
.push(TGAExperiment::new(source).with_id("run-500K"))
.unwrap();
series
.push(TGAExperiment::new(second_source).with_id("run-600K"))
.unwrap();
let source_refs = ["run-500K", "run-600K"]
.into_iter()
.map(|id| {
let source_experiment = series.get_experiment_by_id(id).unwrap();
crate::Kinetics::experimental_kinetics::column_provenance::KineticSourceRef {
experiment_identity: source_experiment.meta.identity().to_string(),
experiment_id_snapshot: source_experiment.meta.id.clone(),
columns: vec!["time".into(), "temperature".into(), "mass".into()],
column_units: vec![
("time".into(), "Second".into()),
("temperature".into(), "Kelvin".into()),
("mass".into(), "Milligram".into()),
],
conditions: vec![("heating_rate_K_per_min".into(), 5.0)],
}
})
.collect::<Vec<_>>();
let ea_eta = isoconversional
.to_tga_dataset_with_sources(&source_refs)
.unwrap();
series
.push(TGAExperiment::new(ea_eta).with_id("series-Ea-eta"))
.unwrap();
series
.add_analysis_result(
crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultRecord {
id: String::new(),
kind: crate::Kinetics::experimental_kinetics::analysis_results::AnalysisResultKind::ParameterSet(
crate::Kinetics::experimental_kinetics::analysis_results::ParameterSetRecord {
method: "Fit Model".into(),
model: "Linear".into(),
formula: Some("a*x+b".into()),
solver: Some("LM".into()),
x_column: Some("time".into()),
y_column: Some("mass".into()),
x_unit: Some("Second".into()),
y_unit: Some("Milligram".into()),
range: Some(crate::Kinetics::experimental_kinetics::analysis_results::AnalysisRange {
axis: "time".into(),
start: 0.0,
end: 2.0,
}),
excluded_range: None,
conditions: vec![],
settings: vec![("robust".into(), "false".into())],
diagnostics: vec![("R2".into(), 0.99, "1".into())],
coefficients: vec![crate::Kinetics::experimental_kinetics::analysis_results::CoefficientValue {
name: "slope".into(),
role: None,
stage: None,
value: -0.5,
unit: "mg/s".into(),
}],
},
),
source_experiment_id: Some("run-500K".into()),
source_experiment_ids: vec!["run-500K".into()],
source_experiments: vec![crate::Kinetics::experimental_kinetics::analysis_results::AnalysisSourceRef {
experiment_identity: source_refs[0].experiment_identity.clone(),
experiment_id_snapshot: "run-500K".into(),
}],
parent_result_ids: vec![],
},
)
.unwrap();
let document_path = temp.path().join("series.csv");
series.to_csv_series(&document_path).unwrap();
let restored = TGASeries::from_csv_series(&document_path).unwrap();
assert_eq!(restored.identity(), series.identity());
let restored_result = restored.get_experiment_by_id("series-Ea-eta").unwrap();
let ea_provenance = restored_result
.dataset
.schema
.columns
.get("Ea")
.unwrap()
.provenance
.steps
.last()
.unwrap();
let crate::Kinetics::experimental_kinetics::column_provenance::ColumnTransformKind::KineticMethod {
method,
solver,
output_unit,
sources,
value_range,
..
} = &ea_provenance.kind else {
panic!("expected kinetic-method provenance on Ea(eta)");
};
assert_eq!(method, "KAS");
assert!(solver.as_deref().unwrap().contains("regression"));
assert_eq!(output_unit, "J/mol");
assert_eq!(sources, source_refs.as_slice());
assert_eq!(value_range.as_ref().unwrap().0, "eta");
assert_eq!(value_range.as_ref().unwrap().1, 0.1);
assert_eq!(value_range.as_ref().unwrap().2, 0.9);
let result_frame = restored_result.dataset.frame().collect().unwrap();
assert_eq!(
result_frame
.column("eta")
.unwrap()
.f64()
.unwrap()
.into_no_null_iter()
.collect::<Vec<_>>(),
vec![0.1, 0.5, 0.9]
);
assert_eq!(
result_frame
.column("Ea")
.unwrap()
.f64()
.unwrap()
.into_no_null_iter()
.collect::<Vec<_>>(),
vec![81_000.0, 83_000.0, 85_000.0]
);
assert_eq!(
result_frame
.column("R2")
.unwrap()
.f64()
.unwrap()
.into_no_null_iter()
.collect::<Vec<_>>(),
vec![0.99, 0.98, 0.97]
);
let catalog_series_id = CatalogId::parse(restored.identity().to_string()).unwrap();
let catalog_series = CatalogSeries {
id: catalog_series_id.clone(),
display_name: "isothermal series".into(),
description: Some("Two runs and series-level Ea(eta) result".into()),
};
let catalog_experiments = restored
.experiments()
.iter()
.map(|experiment| {
let id = CatalogId::parse(experiment.meta.identity().to_string()).unwrap();
CatalogExperiment {
id: id.clone(),
source_identity: id.as_str().to_owned(),
display_name: experiment.meta.id.clone(),
source_kind: source_kind_from_lineage(experiment.dataset.data_lineage()),
date: None,
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: None,
heating_rate_k_per_min: None,
comment: None,
tags: Vec::new(),
}
})
.collect::<Vec<_>>();
let members = catalog_experiments
.iter()
.enumerate()
.map(|(ordinal, experiment)| PublishedSeriesMember {
experiment_id: experiment.id.clone(),
ordinal: ordinal as u32,
})
.collect::<Vec<_>>();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: catalog_series_id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: members,
artifact_ids: Vec::new(),
snapshot: Some(CatalogPublicationSnapshot::Series {
series: catalog_series.clone(),
experiments: catalog_experiments.clone(),
}),
typed_documents: vec![],
};
let mut store = CatalogStore::open(temp.path().join("library")).unwrap();
let published = store
.register_and_publish_series_snapshot(
&catalog_series,
&catalog_experiments,
&publication,
&[CatalogArtifactFile {
path: document_path.clone(),
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}],
)
.unwrap();
assert_eq!(published.object_kind, CatalogObjectKind::Series);
assert_eq!(published.series_members.len(), 3);
assert_eq!(published.typed_documents.len(), 1);
let typed_summary = &published.typed_documents[0];
assert_eq!(typed_summary.file_name, "series.csv");
assert_eq!(
typed_summary.analysis_results,
restored.analysis_results().records()
);
assert_eq!(typed_summary.kinetic_method_outputs.len(), 3);
let ea_output = typed_summary
.kinetic_method_outputs
.iter()
.find(|output| output.output_column == "Ea")
.unwrap();
assert_eq!(ea_output.method, "KAS");
assert_eq!(ea_output.experiment_id_snapshot, "series-Ea-eta");
assert_eq!(
ea_output.experiment_identity,
restored_result.meta.identity()
);
assert_eq!(ea_output.sources.len(), 2);
assert_eq!(
ea_output.sources[0].columns,
["time", "temperature", "mass"]
);
assert_eq!(ea_output.value_range.as_ref().unwrap().0, "eta");
let attached = store
.get_artifact(&published.artifact_ids[0])
.unwrap()
.unwrap();
assert_eq!(attached.purpose, CatalogArtifactPurpose::TypedKiTheDocument);
assert_eq!(
store.get_publication(&published.id).unwrap(),
Some(published)
);
}
#[test]
fn publication_snapshot_stays_unchanged_when_search_card_is_refreshed() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let experiment_id = CatalogId::new();
let card = CatalogExperiment {
id: experiment_id.clone(),
source_identity: experiment_id.as_str().to_owned(),
display_name: "Run before rename".into(),
source_kind: SourceKind::Measured,
date: Some("2026-12-01".into()),
sample: None,
instrument: None,
operator: None,
thermal_mode: None,
temperature_k: None,
heating_rate_k_per_min: None,
comment: None,
tags: vec![],
};
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "series v1".into(),
description: None,
};
store
.register_series_snapshot(&series, std::slice::from_ref(&card))
.unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![PublishedSeriesMember {
experiment_id: experiment_id.clone(),
ordinal: 0,
}],
artifact_ids: vec![],
snapshot: Some(CatalogPublicationSnapshot::Series {
series: series.clone(),
experiments: vec![card.clone()],
}),
typed_documents: vec![],
};
store.publish(&publication).unwrap();
let mut renamed_series = series.clone();
renamed_series.display_name = "series v2".into();
let mut renamed_card = card;
renamed_card.display_name = "Run after rename".into();
store
.register_series_snapshot(&renamed_series, &[renamed_card])
.unwrap();
let historical = store.get_publication(&publication.id).unwrap().unwrap();
let Some(CatalogPublicationSnapshot::Series {
series,
experiments,
}) = historical.snapshot
else {
panic!("expected publication snapshot");
};
assert_eq!(series.display_name, "series v1");
assert_eq!(experiments[0].display_name, "Run before rename");
assert_eq!(
store
.list_series()
.unwrap()
.into_iter()
.find(|entry| entry.id == series.id)
.unwrap()
.display_name,
"series v2"
);
}
#[test]
fn registering_same_series_refreshes_one_card_and_preserves_member_order() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let first = experiment();
let mut second = experiment();
second.id = CatalogId::new();
second.source_identity = "kithe-identity-2".into();
second.display_name = "run B".into();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "isothermal series".into(),
description: None,
};
store
.register_series_snapshot(&series, &[first.clone(), second.clone()])
.unwrap();
let mut refreshed = series.clone();
refreshed.display_name = "updated series name".into();
store
.register_series_snapshot(&refreshed, &[second.clone(), first.clone()])
.unwrap();
let listed = store.list_series().unwrap();
assert_eq!(listed, vec![refreshed]);
let members = store
.connection
.query_row(
"SELECT experiment_id FROM series_members WHERE series_id = ?1 ORDER BY ordinal",
[series.id.as_str()],
|row| row.get::<_, String>(0),
)
.unwrap();
assert_eq!(members, second.id.as_str());
let experiment_count: i64 = store
.connection
.query_row("SELECT COUNT(*) FROM experiments", [], |row| row.get(0))
.unwrap();
assert_eq!(experiment_count, 2);
}
#[test]
fn failed_series_registration_rolls_back_series_and_members() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let existing = experiment();
store.insert_experiment(&existing).unwrap();
let mut conflicting = experiment();
conflicting.id = CatalogId::new();
conflicting.display_name = "conflicting identity".into();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "must roll back".into(),
description: None,
};
assert!(
store
.register_series_snapshot(&series, &[conflicting])
.is_err()
);
assert!(store.list_series().unwrap().is_empty());
let count: i64 = store
.connection
.query_row("SELECT COUNT(*) FROM experiments", [], |row| row.get(0))
.unwrap();
assert_eq!(count, 1);
}
#[test]
fn browsing_missing_library_does_not_create_it() {
let temp = tempfile::tempdir().unwrap();
let missing = temp.path().join("not-created");
assert!(matches!(
CatalogStore::open_existing(&missing),
Err(CatalogStoreError::LibraryDoesNotExist(_))
));
assert!(!missing.exists());
std::fs::create_dir(&missing).unwrap();
assert!(matches!(
CatalogStore::open_existing(&missing),
Err(CatalogStoreError::LibraryDoesNotExist(_))
));
assert!(!missing.join(DATABASE_FILE).exists());
}
#[test]
fn library_identity_is_stored_in_database_and_distinguishes_roots() {
let temp = tempfile::tempdir().unwrap();
let first_root = temp.path().join("first");
let second_root = temp.path().join("second");
let first_id = CatalogStore::open(&first_root)
.unwrap()
.library_id()
.to_string();
let reopened_id = CatalogStore::open_existing(&first_root)
.unwrap()
.library_id()
.to_string();
let second_id = CatalogStore::open(&second_root)
.unwrap()
.library_id()
.to_string();
assert_eq!(first_id, reopened_id);
assert_ne!(first_id, second_id);
CatalogStore::open_existing(&first_root)
.unwrap()
.ensure_library_identity(&first_id)
.unwrap();
assert!(matches!(
CatalogStore::open_existing(&second_root)
.unwrap()
.ensure_library_identity(&first_id),
Err(CatalogStoreError::LibraryIdentityMismatch { .. })
));
}
#[test]
fn version_one_library_migrates_without_losing_existing_cards() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "pre-migration".into(),
description: None,
};
store.register_series_snapshot(&series, &[]).unwrap();
store
.connection
.execute_batch("DROP TABLE catalog_meta; PRAGMA user_version = 1;")
.unwrap();
drop(store);
let migrated = CatalogStore::open_existing(temp.path()).unwrap();
assert_eq!(migrated.list_series().unwrap(), vec![series]);
assert!(!migrated.library_id().is_empty());
}
#[test]
fn version_three_library_adds_study_model_without_losing_catalog_cards() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "existing series".into(),
description: None,
};
store.insert_series(&series).unwrap();
store
.connection
.execute_batch(
"DROP TABLE experiment_samples;
DROP TABLE study_series;
DROP TABLE series_substances;
DROP TABLE study_substances;
DROP TABLE samples;
DROP TABLE substances;
DROP TABLE studies;
PRAGMA user_version = 3;",
)
.unwrap();
drop(store);
let migrated = CatalogStore::open_existing(temp.path()).unwrap();
assert_eq!(migrated.list_series().unwrap(), vec![series]);
let tables: i64 = migrated.connection.query_row(
"SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN
('studies', 'substances', 'samples', 'study_substances', 'series_substances', 'study_series', 'experiment_samples')",
[],
|row| row.get(0),
).unwrap();
assert_eq!(tables, 7);
}
#[test]
fn local_publication_references_external_file_and_records_its_checksum() {
use std::io::Write;
let temp = tempfile::tempdir().unwrap();
let library = temp.path().join("catalog");
let external = temp.path().join("measurements");
std::fs::create_dir(&external).unwrap();
let file_path = external.join("raw run.txt");
let mut file = std::fs::File::create(&file_path).unwrap();
file.write_all(b"time\tmass\n0\t10\n1\t9\n").unwrap();
drop(file);
let experiment = experiment();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "series".into(),
description: None,
};
let mut store = CatalogStore::open(&library).unwrap();
store
.register_series_snapshot(&series, std::slice::from_ref(&experiment))
.unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: Some("first local publication".into()),
series_members: vec![PublishedSeriesMember {
experiment_id: experiment.id,
ordinal: 0,
}],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let result = store
.publish_with_local_files(
&publication,
&[CatalogArtifactFile {
path: file_path.clone(),
purpose: CatalogArtifactPurpose::RawInstrumentData,
}],
)
.unwrap();
assert_eq!(result.artifact_ids.len(), 1);
assert_eq!(
store.get_publication(&result.id).unwrap(),
Some(result.clone())
);
let artifact = store
.get_artifact(&result.artifact_ids[0])
.unwrap()
.unwrap();
assert_eq!(artifact.file_name, "raw run.txt");
assert_eq!(
artifact.size_bytes,
b"time\tmass\n0\t10\n1\t9\n".len() as u64
);
assert_eq!(artifact.purpose, CatalogArtifactPurpose::RawInstrumentData);
let expected_sha256 = Sha256::digest(b"time\tmass\n0\t10\n1\t9\n")
.iter()
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
assert_eq!(artifact.sha256, expected_sha256);
assert_eq!(
std::fs::read(&file_path).unwrap(),
b"time\tmass\n0\t10\n1\t9\n"
);
assert!(!library.join("artifacts").exists());
assert_eq!(
store
.connection
.query_row("SELECT COUNT(*) FROM artifact_roots", [], |row| row
.get::<_, i64>(0))
.unwrap(),
1
);
assert_eq!(
store
.resolve_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactResolution::Available(std::fs::canonicalize(&file_path).unwrap())
);
assert_eq!(
store
.verify_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactIntegrity::Verified
);
drop(store);
let store = CatalogStore::open_existing(&library).unwrap();
assert_eq!(
store.get_publication(&result.id).unwrap(),
Some(result.clone())
);
assert_eq!(
store
.resolve_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactResolution::Available(std::fs::canonicalize(&file_path).unwrap())
);
assert_eq!(
store
.verify_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactIntegrity::Verified
);
let unavailable_root = temp.path().join("measurements-unavailable");
std::fs::rename(&external, &unavailable_root).unwrap();
assert!(matches!(
store
.resolve_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactResolution::Missing(_)
));
std::fs::rename(&unavailable_root, &external).unwrap();
std::fs::write(&file_path, b"changed after publication").unwrap();
assert!(matches!(
store
.verify_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactIntegrity::Modified { path, .. }
if path == std::fs::canonicalize(&file_path).unwrap()
));
std::fs::remove_file(&file_path).unwrap();
assert!(matches!(
store
.resolve_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactResolution::Missing(path)
if path.file_name() == file_path.file_name()
));
assert!(matches!(
store
.verify_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactIntegrity::Missing(path)
if path.file_name() == file_path.file_name()
));
}
#[test]
fn moved_artifact_root_relinks_only_after_all_files_match_saved_checksums() {
let temp = tempfile::tempdir().unwrap();
let library = temp.path().join("catalog");
let old_root = temp.path().join("external-old");
let new_root = temp.path().join("external-new");
std::fs::create_dir(&old_root).unwrap();
let raw_file = old_root.join("measurement.txt");
let bytes = b"time\tmass\n0\t10\n1\t9\n";
std::fs::write(&raw_file, bytes).unwrap();
let mut store = CatalogStore::open(&library).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "moved root".into(),
description: None,
};
store.register_series_snapshot(&series, &[]).unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let result = store
.publish_with_local_files(
&publication,
&[CatalogArtifactFile {
path: raw_file.clone(),
purpose: CatalogArtifactPurpose::RawInstrumentData,
}],
)
.unwrap();
let artifact = store
.get_artifact(&result.artifact_ids[0])
.unwrap()
.unwrap();
let root_id = match &artifact.locations[0] {
ArtifactLocation::Local { root_id, .. } => root_id.clone(),
ArtifactLocation::Server { .. } => unreachable!(),
};
std::fs::rename(&old_root, &new_root).unwrap();
std::fs::write(new_root.join("measurement.txt"), b"wrong version").unwrap();
assert!(matches!(
store.relink_local_root(&root_id, &new_root),
Err(CatalogStoreError::ArtifactRootRelinkMismatch { .. })
));
assert!(matches!(
store
.resolve_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactResolution::Missing(_)
));
std::fs::write(new_root.join("measurement.txt"), bytes).unwrap();
assert_eq!(store.relink_local_root(&root_id, &new_root).unwrap(), 1);
assert_eq!(
store
.resolve_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactResolution::Available(
std::fs::canonicalize(new_root.join("measurement.txt")).unwrap()
)
);
assert_eq!(
store
.verify_local_artifact(&result.artifact_ids[0])
.unwrap(),
LocalArtifactIntegrity::Verified
);
}
#[cfg(unix)]
#[test]
fn relink_rejects_artifact_symlinks_that_escape_the_selected_root() {
use std::os::unix::fs::symlink;
let temp = tempfile::tempdir().unwrap();
let library = temp.path().join("catalog");
let old_root = temp.path().join("old-root");
let selected_root = temp.path().join("selected-root");
let outside = temp.path().join("outside.txt");
std::fs::create_dir(&old_root).unwrap();
std::fs::write(old_root.join("raw.txt"), b"raw source").unwrap();
std::fs::write(&outside, b"raw source").unwrap();
let mut store = CatalogStore::open(&library).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "symlink containment".into(),
description: None,
};
store.register_series_snapshot(&series, &[]).unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let result = store
.publish_with_local_files(
&publication,
&[CatalogArtifactFile {
path: old_root.join("raw.txt"),
purpose: CatalogArtifactPurpose::RawInstrumentData,
}],
)
.unwrap();
let artifact = store
.get_artifact(&result.artifact_ids[0])
.unwrap()
.unwrap();
let root_id = match &artifact.locations[0] {
ArtifactLocation::Local { root_id, .. } => root_id.clone(),
ArtifactLocation::Server { .. } => panic!("expected a local artifact"),
};
std::fs::rename(&old_root, temp.path().join("old-root-moved")).unwrap();
std::fs::create_dir(&selected_root).unwrap();
symlink(&outside, selected_root.join("raw.txt")).unwrap();
assert!(matches!(
store.relink_local_root(&root_id, &selected_root),
Err(CatalogStoreError::ArtifactPathOutsideRoot(_))
));
assert!(matches!(
store.resolve_local_artifact(&artifact.id).unwrap(),
LocalArtifactResolution::Missing(_)
));
}
#[test]
fn catalog_rejects_artifact_extension_that_conflicts_with_its_purpose() {
let temp = tempfile::tempdir().unwrap();
let image = temp.path().join("plot.csv");
std::fs::write(&image, b"not an image").unwrap();
assert!(matches!(
inspect_artifact_files(&[CatalogArtifactFile {
path: image.clone(),
purpose: CatalogArtifactPurpose::PlotImage,
}]),
Err(CatalogStoreError::ArtifactPurposeFormatMismatch { path, .. })
if path == std::fs::canonicalize(&image).unwrap()
));
let project = temp.path().join("plot.kplot");
std::fs::write(&project, b"project").unwrap();
assert!(
inspect_artifact_files(&[CatalogArtifactFile {
path: project,
purpose: CatalogArtifactPurpose::EditableKiThePlot,
}])
.is_ok()
);
}
#[test]
fn same_file_name_in_different_roots_resolves_to_each_original_file() {
let temp = tempfile::tempdir().unwrap();
let first_root = temp.path().join("instrument-a");
let second_root = temp.path().join("instrument-b");
std::fs::create_dir(&first_root).unwrap();
std::fs::create_dir(&second_root).unwrap();
let first_file = first_root.join("raw.csv");
let second_file = second_root.join("raw.csv");
std::fs::write(&first_file, b"source=A\n").unwrap();
std::fs::write(&second_file, b"source=B\n").unwrap();
let library = temp.path().join("catalog");
let mut store = CatalogStore::open(&library).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "same names, different roots".into(),
description: None,
};
store.register_series_snapshot(&series, &[]).unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let published = store
.publish_with_local_files(
&publication,
&[
CatalogArtifactFile {
path: first_file.clone(),
purpose: CatalogArtifactPurpose::RawInstrumentData,
},
CatalogArtifactFile {
path: second_file.clone(),
purpose: CatalogArtifactPurpose::RawInstrumentData,
},
],
)
.unwrap();
assert_eq!(published.artifact_ids.len(), 2);
assert_eq!(
store
.resolve_local_artifact(&published.artifact_ids[0])
.unwrap(),
LocalArtifactResolution::Available(std::fs::canonicalize(first_file).unwrap())
);
assert_eq!(
store
.resolve_local_artifact(&published.artifact_ids[1])
.unwrap(),
LocalArtifactResolution::Available(std::fs::canonicalize(second_file).unwrap())
);
assert_ne!(
store
.get_artifact(&published.artifact_ids[0])
.unwrap()
.unwrap()
.locations,
store
.get_artifact(&published.artifact_ids[1])
.unwrap()
.unwrap()
.locations
);
}
#[test]
fn publication_reports_streaming_hash_progress_and_cancels_before_commit() {
let temp = tempfile::tempdir().unwrap();
let library = temp.path().join("catalog");
let file_path = temp.path().join("large-source.bin");
let contents = vec![0x5a_u8; 1024 * 1024];
std::fs::write(&file_path, &contents).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "hash progress series".into(),
description: None,
};
let mut store = CatalogStore::open(&library).unwrap();
store.register_series_snapshot(&series, &[]).unwrap();
let make_publication = || CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let files = [CatalogArtifactFile {
path: file_path.clone(),
purpose: CatalogArtifactPurpose::Other,
}];
let mut observed = Vec::new();
let cancelled =
store.publish_with_local_files_with_progress(&make_publication(), &files, |progress| {
observed.push(progress.clone());
progress.bytes_in_file < 64 * 1024
});
assert!(matches!(
cancelled,
Err(CatalogStoreError::PublicationCancelled)
));
assert!(
observed
.iter()
.any(|progress| progress.total_bytes == contents.len() as u64)
);
assert!(
observed
.iter()
.any(|progress| progress.bytes_in_file >= 64 * 1024)
);
for table in ["artifact_roots", "artifacts", "publications"] {
let count: i64 = store
.connection
.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
row.get(0)
})
.unwrap();
assert_eq!(count, 0, "cancellation left records in {table}");
}
let mut successful_progress = Vec::new();
let publication = store
.publish_with_local_files_with_progress(&make_publication(), &files, |progress| {
successful_progress.push(progress);
true
})
.unwrap();
assert_eq!(publication.artifact_ids.len(), 1);
assert_eq!(
successful_progress.last().unwrap().bytes_total,
contents.len() as u64
);
assert!(
successful_progress
.windows(2)
.all(|pair| pair[0].bytes_total <= pair[1].bytes_total)
);
}
#[test]
fn failed_local_publication_rolls_back_root_and_artifact_records() {
let temp = tempfile::tempdir().unwrap();
let outside = temp.path().join("file.csv");
std::fs::write(&outside, b"dataset").unwrap();
let mut store = CatalogStore::open(temp.path().join("catalog")).unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: CatalogId::new(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
assert!(
store
.publish_with_local_files(
&publication,
&[CatalogArtifactFile {
path: outside,
purpose: CatalogArtifactPurpose::TypedKiTheDocument,
}],
)
.is_err()
);
for table in ["artifact_roots", "artifacts", "publications"] {
let count: i64 = store
.connection
.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
row.get(0)
})
.unwrap();
assert_eq!(count, 0, "unexpected partial rows in {table}");
}
}
#[test]
fn failure_to_inspect_any_attachment_leaves_no_catalog_rows() {
let temp = tempfile::tempdir().unwrap();
let library = temp.path().join("catalog");
let external = temp.path().join("external");
std::fs::create_dir(&external).unwrap();
let valid = external.join("first.txt");
let missing = external.join("second.txt");
std::fs::write(&valid, b"valid source").unwrap();
let mut store = CatalogStore::open(&library).unwrap();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "atomic attachment inspection".into(),
description: None,
};
store.register_series_snapshot(&series, &[]).unwrap();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id,
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
assert!(
store
.publish_with_local_files(
&publication,
&[
CatalogArtifactFile {
path: valid,
purpose: CatalogArtifactPurpose::RawInstrumentData,
},
CatalogArtifactFile {
path: missing,
purpose: CatalogArtifactPurpose::RawInstrumentData,
},
],
)
.is_err()
);
for table in ["artifact_roots", "artifacts", "publications"] {
let count: i64 = store
.connection
.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
row.get(0)
})
.unwrap();
assert_eq!(count, 0, "partial catalog data in {table}");
}
}
#[test]
fn corrupt_or_unsupported_catalog_database_is_reported_without_reinitializing_it() {
let temp = tempfile::tempdir().unwrap();
let corrupt_root = temp.path().join("corrupt");
std::fs::create_dir(&corrupt_root).unwrap();
let corrupt_db = corrupt_root.join(DATABASE_FILE);
std::fs::write(&corrupt_db, b"not a SQLite database").unwrap();
assert!(matches!(
CatalogStore::open_existing(&corrupt_root),
Err(CatalogStoreError::Database(_))
));
assert_eq!(
std::fs::read(&corrupt_db).unwrap(),
b"not a SQLite database"
);
let unsupported_root = temp.path().join("unsupported");
let store = CatalogStore::open(&unsupported_root).unwrap();
store
.connection
.pragma_update(None, "user_version", SCHEMA_VERSION + 1)
.unwrap();
drop(store);
assert!(matches!(
CatalogStore::open_existing(&unsupported_root),
Err(CatalogStoreError::UnsupportedSchema(version)) if version == SCHEMA_VERSION + 1
));
}
#[test]
fn failed_series_publication_rolls_back_snapshot_and_external_artifacts() {
let temp = tempfile::tempdir().unwrap();
let library = temp.path().join("catalog");
let external = temp.path().join("measurements");
std::fs::create_dir(&external).unwrap();
let file_path = external.join("raw.txt");
std::fs::write(&file_path, b"t\tm\n0\t1\n").unwrap();
let mut experiment = experiment();
experiment.source_identity = experiment.id.as_str().to_owned();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "must roll back".into(),
description: None,
};
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id.clone(),
parent_publication_id: Some(CatalogId::new()),
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![PublishedSeriesMember {
experiment_id: experiment.id.clone(),
ordinal: 0,
}],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let mut store = CatalogStore::open(&library).unwrap();
assert!(matches!(
store.register_and_publish_series_snapshot(
&series,
&[experiment],
&publication,
&[CatalogArtifactFile {
path: file_path,
purpose: CatalogArtifactPurpose::RawInstrumentData,
}],
),
Err(CatalogStoreError::NotFound(_))
));
assert!(store.list_series().unwrap().is_empty());
assert!(store.list_publications().unwrap().is_empty());
for table in [
"experiments",
"series_members",
"artifact_roots",
"artifacts",
] {
let count: i64 = store
.connection
.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
row.get(0)
})
.unwrap();
assert_eq!(count, 0, "unexpected partial rows in {table}");
}
}
#[test]
fn series_publication_rejects_mismatched_experiment_identity_before_writing() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let mut experiment = experiment();
experiment.source_identity = CatalogId::new().as_str().to_owned();
let series = CatalogSeries {
id: CatalogId::new(),
display_name: "identity check".into(),
description: None,
};
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Series,
object_id: series.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![PublishedSeriesMember {
experiment_id: experiment.id.clone(),
ordinal: 0,
}],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
assert!(matches!(
store.register_and_publish_series_snapshot(&series, &[experiment], &publication, &[],),
Err(CatalogStoreError::ExperimentIdentityMismatch)
));
assert!(store.list_series().unwrap().is_empty());
assert!(store.list_publications().unwrap().is_empty());
}
#[test]
fn raw_instrument_files_publish_without_data_lineage() {
let temp = tempfile::tempdir().unwrap();
let library = temp.path().join("catalog");
let file_path = temp.path().join("run.csv");
let continuation_path = temp.path().join("run-continuation.csv");
std::fs::write(&file_path, "time,mass\n0,10\n1,9\n").unwrap();
std::fs::write(&continuation_path, "time,mass\n2,8\n3,7\n").unwrap();
let mut experiment = experiment();
experiment.source_identity = experiment.id.as_str().to_owned();
experiment.source_kind = SourceKind::Unknown;
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: experiment.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: Some("operator".into()),
description: Some("individual experiment snapshot".into()),
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let mut store = CatalogStore::open(&library).unwrap();
let published = store
.register_and_publish_experiment_snapshot(
&experiment,
&publication,
&[
CatalogArtifactFile {
path: file_path.clone(),
purpose: CatalogArtifactPurpose::RawInstrumentData,
},
CatalogArtifactFile {
path: continuation_path.clone(),
purpose: CatalogArtifactPurpose::RawInstrumentData,
},
],
)
.unwrap();
assert_eq!(store.list_experiments().unwrap(), vec![experiment.clone()]);
assert_eq!(
store
.get_experiment(&experiment.id)
.unwrap()
.unwrap()
.source_kind,
SourceKind::Unknown
);
assert!(store.list_series().unwrap().is_empty());
assert_eq!(
store.get_publication(&published.id).unwrap(),
Some(published.clone())
);
assert_eq!(published.series_members, vec![]);
assert_eq!(published.artifact_ids.len(), 2);
let artifact = store
.get_artifact(&published.artifact_ids[0])
.unwrap()
.unwrap();
assert_eq!(artifact.purpose, CatalogArtifactPurpose::RawInstrumentData);
assert_eq!(
store.resolve_local_artifact(&artifact.id).unwrap(),
LocalArtifactResolution::Available(std::fs::canonicalize(file_path).unwrap())
);
let second_artifact = store
.get_artifact(&published.artifact_ids[1])
.unwrap()
.unwrap();
assert_eq!(
second_artifact.purpose,
CatalogArtifactPurpose::RawInstrumentData
);
assert_eq!(
store.resolve_local_artifact(&second_artifact.id).unwrap(),
LocalArtifactResolution::Available(std::fs::canonicalize(continuation_path).unwrap())
);
}
#[test]
fn experiment_registration_refreshes_same_identity_without_duplicates() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let mut experiment = experiment();
experiment.source_identity = experiment.id.as_str().to_owned();
store.register_experiment_snapshot(&experiment).unwrap();
experiment.display_name = "renamed run".into();
store.register_experiment_snapshot(&experiment).unwrap();
let listed = store.list_experiments().unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].id, experiment.id);
assert_eq!(listed[0].display_name, "renamed run");
}
#[test]
fn experiment_registration_rejects_identity_mismatch_without_writing() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let experiment = experiment();
assert!(matches!(
store.register_experiment_snapshot(&experiment),
Err(CatalogStoreError::Validation(
CatalogValidationError::InvalidId(_)
))
));
assert!(store.list_experiments().unwrap().is_empty());
}
#[test]
fn failed_experiment_publication_rolls_back_card_and_artifact_rows() {
let temp = tempfile::tempdir().unwrap();
let file_path = temp.path().join("run.csv");
std::fs::write(&file_path, "time,mass\n0,10\n").unwrap();
let mut experiment = experiment();
experiment.source_identity = experiment.id.as_str().to_owned();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: experiment.id.clone(),
parent_publication_id: Some(CatalogId::new()),
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
let mut store = CatalogStore::open(temp.path().join("catalog")).unwrap();
assert!(matches!(
store.register_and_publish_experiment_snapshot(
&experiment,
&publication,
&[CatalogArtifactFile {
path: file_path,
purpose: CatalogArtifactPurpose::RawInstrumentData,
}]
),
Err(CatalogStoreError::NotFound(_))
));
assert!(store.list_experiments().unwrap().is_empty());
assert!(store.list_publications().unwrap().is_empty());
for table in ["artifact_roots", "artifacts"] {
let count: i64 = store
.connection
.query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |row| {
row.get(0)
})
.unwrap();
assert_eq!(count, 0, "unexpected partial rows in {table}");
}
}
#[test]
fn local_store_round_trips_records_and_keeps_db_inside_selected_library() {
let temp = tempfile::tempdir().unwrap();
let library = temp.path().join("chosen-library");
let experiment = experiment();
let artifact = artifact();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: experiment.id.clone(),
parent_publication_id: None,
created_at_rfc3339: "2026-12-01T10:00:00Z".into(),
author: Some("operator".into()),
description: None,
series_members: vec![],
artifact_ids: vec![artifact.id.clone()],
snapshot: None,
typed_documents: vec![],
};
{
let mut store = CatalogStore::open(&library).unwrap();
assert_eq!(store.root(), std::fs::canonicalize(&library).unwrap());
store.insert_experiment(&experiment).unwrap();
store.insert_artifact(&artifact).unwrap();
store.publish(&publication).unwrap();
}
let store = CatalogStore::open(&library).unwrap();
assert_eq!(
store.resolve_local_artifact(&artifact.id).unwrap(),
LocalArtifactResolution::NoLocalCopy
);
assert_eq!(
store.get_experiment(&experiment.id).unwrap(),
Some(experiment)
);
assert_eq!(
store.get_publication(&publication.id).unwrap(),
Some(publication)
);
assert!(library.join(DATABASE_FILE).is_file());
}
#[test]
fn failed_publication_does_not_leave_partial_rows() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let experiment = experiment();
store.insert_experiment(&experiment).unwrap();
let missing_artifact_id = CatalogId::new();
let publication = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: experiment.id,
parent_publication_id: None,
created_at_rfc3339: "2026-12-01T10:00:00Z".into(),
author: None,
description: None,
series_members: vec![],
artifact_ids: vec![missing_artifact_id],
snapshot: None,
typed_documents: vec![],
};
assert!(store.publish(&publication).is_err());
assert!(store.get_publication(&publication.id).unwrap().is_none());
}
#[test]
fn child_publication_must_belong_to_the_same_catalog_target() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let mut first = experiment();
first.source_identity = first.id.as_str().into();
let mut second = experiment();
second.source_identity = second.id.as_str().into();
store.insert_experiment(&first).unwrap();
store.insert_experiment(&second).unwrap();
let parent = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: first.id.clone(),
parent_publication_id: None,
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: Some("first experiment processing".into()),
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
store.publish(&parent).unwrap();
let child = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: second.id.clone(),
parent_publication_id: Some(parent.id.clone()),
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: Some("unrelated plot".into()),
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
assert!(matches!(
store.publish(&child),
Err(CatalogStoreError::ParentPublicationTargetMismatch)
));
assert!(store.get_publication(&child.id).unwrap().is_none());
let related_plot = CatalogPublication {
id: CatalogId::new(),
object_kind: CatalogObjectKind::Experiment,
object_id: first.id,
parent_publication_id: Some(parent.id),
created_at_rfc3339: chrono::Utc::now().to_rfc3339(),
author: None,
description: Some("plot for the same experiment".into()),
series_members: vec![],
artifact_ids: vec![],
snapshot: None,
typed_documents: vec![],
};
store.publish(&related_plot).unwrap();
assert!(store.get_publication(&related_plot.id).unwrap().is_some());
}
#[test]
fn artifact_size_outside_sqlite_integer_range_is_rejected() {
let temp = tempfile::tempdir().unwrap();
let mut store = CatalogStore::open(temp.path()).unwrap();
let mut artifact = artifact();
artifact.size_bytes = u64::MAX;
assert!(matches!(
store.insert_artifact(&artifact),
Err(CatalogStoreError::ArtifactSizeOutOfRange(u64::MAX))
));
}
}