diff --git a/crates/registry-breg-client-node/__test__/statistics.test.js b/crates/registry-breg-client-node/__test__/statistics.test.js index 82d41ada78..11601b12b3 100644 --- a/crates/registry-breg-client-node/__test__/statistics.test.js +++ b/crates/registry-breg-client-node/__test__/statistics.test.js @@ -26,6 +26,8 @@ test('registry metadata retains statistical datasets without entity authority', id: 'company-counts', unit: 'company', periodKind: 'flow', granularity: 'month', firstPeriod: '2025-01', dimensions: [{ field: 'category', vocabulary: 'company-category', codes: ['Registered', '_U', '_T'] }], + display: { description: "Registered companies" }, + measures: [{ id: "companies", type: "count", display: { label: "Companies" } }], definitionDigest: metadata.revision, operations: ['list-releases', 'read-latest-release', 'read-release-version', 'read-released-series'], }]; diff --git a/crates/registry-breg-client-node/client.d.ts b/crates/registry-breg-client-node/client.d.ts index cb00a57a8d..bd55a33c08 100644 --- a/crates/registry-breg-client-node/client.d.ts +++ b/crates/registry-breg-client-node/client.d.ts @@ -194,6 +194,23 @@ export interface BRegStatisticalDimensionDescriptor { readonly codes: ReadonlyArray } +export interface BRegStatisticalDisplay { + readonly label?: string + readonly description?: string +} + +export type BRegStatisticalMeasureDescriptor = { + readonly id: string + readonly display?: BRegStatisticalDisplay +} & ( + | { readonly type: 'count' } + | { readonly type: 'distinct-count'; readonly field: string } + | { readonly type: 'sum'; readonly field: string; readonly scale: number } + | { readonly type: 'mean'; readonly field: string; readonly scale: number } + | { readonly type: 'ratio'; readonly numerator: string; readonly denominator: string; readonly scale: number } + | { readonly type: 'percentile'; readonly field: string; readonly percentile: number; readonly scale: number } +) + export interface BRegStatisticalDatasetDescriptor { readonly id: string readonly unit: string @@ -201,6 +218,8 @@ export interface BRegStatisticalDatasetDescriptor { readonly granularity: 'day' | 'month' | 'quarter' | 'year' readonly firstPeriod: string readonly dimensions: ReadonlyArray + readonly measures?: ReadonlyArray + readonly display?: BRegStatisticalDisplay readonly definitionDigest: string readonly operations: ReadonlyArray< | 'read-live' diff --git a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi index 19b48f1d69..17063403c5 100644 --- a/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi +++ b/crates/registry-breg-client-py/python/registry_breg_client/__init__.pyi @@ -65,6 +65,52 @@ class BRegStatisticalDimensionDescriptor(TypedDict): vocabulary: str codes: Sequence[str] +class BRegStatisticalDisplay(TypedDict, total=False): + label: str + description: str + +class _BRegStatisticalMeasureBase(TypedDict): + id: str + display: NotRequired[BRegStatisticalDisplay] + +class _BRegStatisticalCount(_BRegStatisticalMeasureBase): + type: Literal["count"] + +class _BRegStatisticalDistinctCount(_BRegStatisticalMeasureBase): + type: Literal["distinct-count"] + field: str + +class _BRegStatisticalSum(_BRegStatisticalMeasureBase): + type: Literal["sum"] + field: str + scale: int + +class _BRegStatisticalMean(_BRegStatisticalMeasureBase): + type: Literal["mean"] + field: str + scale: int + +class _BRegStatisticalRatio(_BRegStatisticalMeasureBase): + type: Literal["ratio"] + numerator: str + denominator: str + scale: int + +class _BRegStatisticalPercentile(_BRegStatisticalMeasureBase): + type: Literal["percentile"] + field: str + percentile: int + scale: int + +BRegStatisticalMeasureDescriptor = ( + _BRegStatisticalCount + | _BRegStatisticalDistinctCount + | _BRegStatisticalSum + | _BRegStatisticalMean + | _BRegStatisticalRatio + | _BRegStatisticalPercentile +) + class BRegStatisticalDatasetDescriptor(TypedDict): id: str unit: str @@ -72,6 +118,8 @@ class BRegStatisticalDatasetDescriptor(TypedDict): granularity: Literal["day", "month", "quarter", "year"] firstPeriod: str dimensions: Sequence[BRegStatisticalDimensionDescriptor] + measures: NotRequired[Sequence[BRegStatisticalMeasureDescriptor]] + display: NotRequired[BRegStatisticalDisplay] definitionDigest: str operations: Sequence[Literal[ "read-live", diff --git a/crates/registry-breg-client-py/tests/python/test_statistics.py b/crates/registry-breg-client-py/tests/python/test_statistics.py index e86f0cd877..5ace390aef 100644 --- a/crates/registry-breg-client-py/tests/python/test_statistics.py +++ b/crates/registry-breg-client-py/tests/python/test_statistics.py @@ -136,6 +136,8 @@ def test_statistical_dataset_metadata(self) -> None: "field": "category", "vocabulary": "company-category", "codes": ["Registered", "_U", "_T"], }], + "display": {"description": "Registered companies"}, + "measures": [{"id": "companies", "type": "count", "display": {"label": "Companies"}}], "definitionDigest": self.metadata_document["revision"], "operations": [ "list-releases", "read-latest-release", "read-release-version", diff --git a/crates/registry-breg-client/src/metadata.rs b/crates/registry-breg-client/src/metadata.rs index 285af64663..5c790177b6 100644 --- a/crates/registry-breg-client/src/metadata.rs +++ b/crates/registry-breg-client/src/metadata.rs @@ -1240,6 +1240,73 @@ impl fmt::Debug for BRegActionDescriptor { } } +/// Presentation supplied by the registry author. +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)] +pub struct BRegStatisticalDisplay { + pub label: Option, + pub description: Option, +} + +/// One authored statistical operation with its compiled arguments. +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)] +#[serde(tag = "type", rename_all = "kebab-case")] +pub enum BRegStatisticalMeasure { + Count, + DistinctCount { + field: String, + }, + Sum { + field: String, + scale: u8, + }, + Mean { + field: String, + scale: u8, + }, + Ratio { + numerator: String, + denominator: String, + scale: u8, + }, + Percentile { + field: String, + percentile: u8, + scale: u8, + }, +} + +/// A measure within caller-filtered dataset metadata. +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)] +pub struct BRegStatisticalMeasureDescriptor { + pub id: String, + pub display: Option, + #[serde(flatten)] + pub measure: BRegStatisticalMeasure, +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)] +pub struct BRegStatisticalDimensionDescriptor { + pub field: String, + pub vocabulary: String, + pub codes: Vec, +} + +/// A caller-visible statistical dataset. Older servers can omit measures and display. +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BRegStatisticalDatasetDescriptor { + pub id: String, + pub unit: String, + pub period_kind: String, + pub granularity: String, + pub first_period: String, + pub dimensions: Vec, + pub definition_digest: String, + pub operations: Vec, + pub measures: Option>, + pub display: Option, +} + /// Validated Base Registry Engine runtime metadata v2 for one caller projection. #[derive(Clone, PartialEq)] pub struct BRegMetadata { @@ -1250,6 +1317,7 @@ pub struct BRegMetadata { operations: Vec, action_metadata: Option, statistical_datasets: Option, + statistical_dataset_descriptors: Option>, proposals: Option, proposal_actions: Vec, actions: Vec, @@ -1422,6 +1490,11 @@ impl BRegMetadata { self.statistical_datasets.as_ref() } + /// Typed descriptions of the same caller-visible statistical datasets. + pub fn statistical_dataset_descriptors(&self) -> Option<&[BRegStatisticalDatasetDescriptor]> { + self.statistical_dataset_descriptors.as_deref() + } + /// Exact caller-visible Action/profile Proposal inventory, without execution authority. #[must_use] pub fn proposal_actions(&self) -> &[BRegProposalActionDescriptor] { @@ -2728,10 +2801,14 @@ fn parse_metadata(value: Value) -> Result { parse_proposal_actions(required(object, "actions")?)? } }; - let statistical_datasets = root - .remove("statisticalDatasets") - .map(parse_statistical_datasets) - .transpose()?; + let (statistical_datasets, statistical_dataset_descriptors) = + match root.remove("statisticalDatasets") { + Some(value) => { + let (wire, typed) = parse_statistical_datasets(value)?; + (Some(wire), Some(typed)) + } + None => (None, None), + }; let actions = action_metadata .as_ref() .map(|value| parse_actions(value.clone())) @@ -2752,6 +2829,7 @@ fn parse_metadata(value: Value) -> Result { operations, action_metadata, statistical_datasets, + statistical_dataset_descriptors, proposals, proposal_actions, actions, @@ -2759,9 +2837,12 @@ fn parse_metadata(value: Value) -> Result { }) } -fn parse_statistical_datasets(value: Value) -> Result { +fn parse_statistical_datasets( + value: Value, +) -> Result<(Value, Vec), BRegMetadataError> { let mut ids = BTreeSet::new(); let mut supported = Vec::new(); + let mut descriptors = Vec::new(); for value in array(value)? { let original = value.clone(); let mut dataset = object(value)?; @@ -2829,12 +2910,68 @@ fn parse_statistical_datasets(value: Value) -> Result }) { vocabulary_is_supported = false; } + if let Some(display) = dataset.remove("display") { + validate_statistical_display(display)?; + } + if let Some(measures) = dataset.remove("measures") { + let mut measures_seen = BTreeSet::new(); + for measure in array(measures)? { + let mut measure = object(measure)?; + let id = identifier(required(&mut measure, "id")?)?; + if !measures_seen.insert(id) { + return Err(metadata_error(BRegMetadataErrorKind::DuplicateIdentifier)); + } + if let Some(display) = measure.remove("display") { + validate_statistical_display(display)?; + } + let kind = string(required(&mut measure, "type")?)?; + match kind.as_str() { + "count" => {} + "distinct-count" | "sum" | "mean" | "percentile" => { + identifier(required(&mut measure, "field")?)?; + } + "ratio" => { + identifier(required(&mut measure, "numerator")?)?; + identifier(required(&mut measure, "denominator")?)?; + } + _ => vocabulary_is_supported = false, + } + if matches!(kind.as_str(), "sum" | "mean" | "ratio" | "percentile") + && required(&mut measure, "scale")? + .as_u64() + .is_none_or(|scale| scale > 38) + { + return Err(metadata_error(BRegMetadataErrorKind::Shape)); + } + if kind == "percentile" + && required(&mut measure, "percentile")? + .as_u64() + .is_none_or(|percentile| !(1..=99).contains(&percentile)) + { + return Err(metadata_error(BRegMetadataErrorKind::Shape)); + } + } + } finish(dataset)?; if vocabulary_is_supported { + descriptors.push( + serde_json::from_value(original.clone()) + .map_err(|_| metadata_error(BRegMetadataErrorKind::Shape))?, + ); supported.push(original); } } - Ok(Value::Array(supported)) + Ok((Value::Array(supported), descriptors)) +} + +fn validate_statistical_display(value: Value) -> Result<(), BRegMetadataError> { + let mut display = object(value)?; + for member in ["label", "description"] { + if let Some(text) = display.remove(member) { + bounded_string(text)?; + } + } + finish(display) } fn valid_statistical_period(period: &str, granularity: &str) -> bool { diff --git a/crates/registry-breg-client/src/metadata_tests.rs b/crates/registry-breg-client/src/metadata_tests.rs index b6dd967961..403edd6cf7 100644 --- a/crates/registry-breg-client/src/metadata_tests.rs +++ b/crates/registry-breg-client/src/metadata_tests.rs @@ -184,6 +184,47 @@ fn runtime_v2_accepts_statistical_datasets_without_adding_entity_authority() { assert_eq!(parse(&empty).statistical_datasets(), Some(&json!([]))); } +#[test] +fn statistical_metadata_exposes_typed_measures_and_optional_display() { + let mut source = fixture(); + source["statisticalDatasets"] = json!([statistical_dataset()]); + let legacy = parse(&source); + let descriptor = &legacy.statistical_dataset_descriptors().unwrap()[0]; + assert!(descriptor.measures.is_none()); + assert!(descriptor.display.is_none()); + + let dataset = &mut source["statisticalDatasets"][0]; + dataset["display"] = json!({"description": "Registered companies"}); + dataset["measures"] = json!([ + {"id":"count","type":"count","display":{"label":"Companies"}}, + {"id":"owners","type":"distinct-count","field":"owner"}, + {"id":"total","type":"sum","field":"amount","scale":2}, + {"id":"mean","type":"mean","field":"amount","scale":3}, + {"id":"ratio","type":"ratio","numerator":"total","denominator":"count","scale":2}, + {"id":"median","type":"percentile","field":"amount","percentile":50,"scale":2} + ]); + let parsed = parse(&source); + let descriptor = &parsed.statistical_dataset_descriptors().unwrap()[0]; + assert_eq!( + descriptor.display.as_ref().unwrap().description.as_deref(), + Some("Registered companies") + ); + let measures = descriptor.measures.as_deref().unwrap(); + assert_eq!(measures.len(), 6); + assert_eq!( + measures[0].display.as_ref().unwrap().label.as_deref(), + Some("Companies") + ); + assert!(matches!( + measures[5].measure, + BRegStatisticalMeasure::Percentile { percentile: 50, .. } + )); + assert_eq!( + parsed.statistical_datasets(), + Some(&source["statisticalDatasets"]) + ); +} + #[test] fn statistical_dataset_metadata_validates_known_domains_and_periods() { type MetadataMutation = fn(&mut Value); diff --git a/crates/registry-breg/src/api/tests/immediate_action_tests.rs b/crates/registry-breg/src/api/tests/immediate_action_tests.rs index e48a5d814a..03711fae31 100644 --- a/crates/registry-breg/src/api/tests/immediate_action_tests.rs +++ b/crates/registry-breg/src/api/tests/immediate_action_tests.rs @@ -2232,7 +2232,7 @@ async fn task_statistics_reads_bind_the_grant_to_the_request_principal_and_purpo "requiredPurposes":["case-management","case-audit"], "taskGrant":{"sourceIssuer":"https://casework.example"}, "permissions":{"datasets":[{"dataset":"counts","operations":["read-releases"]}]}}}, - "statisticalDatasets":{"counts": {"unit":"record","population":"active eq true", + "statisticalDatasets":{"counts": {"recordType":"record","population":"active eq true", "period":{"type":"flow","field":"occurred-on","granularity":"month","firstPeriod":"2025-01"}, "dimensions":["active"],"disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}}}}); let project = diff --git a/crates/registry-breg/src/authoring_integrity.rs b/crates/registry-breg/src/authoring_integrity.rs index 2fab0104ea..cdd11f1331 100644 --- a/crates/registry-breg/src/authoring_integrity.rs +++ b/crates/registry-breg/src/authoring_integrity.rs @@ -688,20 +688,18 @@ pub(crate) fn project_diagnostics( &keyed_ids("/accessProfiles", &project.access_profiles, |item| &item.id), ); for dataset in &project.statistical_datasets { - let values = indexed_ids( - &format!( - "{}/measures", - keyed_pointer("/statisticalDatasets", dataset.id.as_str()) - ), - &dataset.measures, - |item| item.id().as_str(), - ); - add_collisions( - document, - &mut errors, - "breg.statistical-dataset.measure-id-collision", - &values, + let path = format!( + "{}/measures", + keyed_pointer("/statisticalDatasets", dataset.id.as_str()) ); + let code = "breg.statistical-dataset.measure-id-collision"; + if dataset.historical_statistics { + let values = indexed_ids(&path, &dataset.measures, |item| item.id().as_str()); + add_collisions(document, &mut errors, code, &values); + } else { + let values = keyed_ids(&path, &dataset.measures, |item| item.id().as_str()); + add_key_collisions(document, &mut errors, code, &values); + } } add_key_collisions( document, diff --git a/crates/registry-breg/src/compiler.rs b/crates/registry-breg/src/compiler.rs index 973668e52b..4e12c6e48a 100644 --- a/crates/registry-breg/src/compiler.rs +++ b/crates/registry-breg/src/compiler.rs @@ -2136,6 +2136,17 @@ fn validate_authored_display_text( &format!("statisticalDatasets[id={}].display", dataset.id), errors, ); + for measure in &dataset.measures { + validate_presentation_source( + measure.display(), + &format!( + "statisticalDatasets[id={}].measures[id={}].display", + dataset.id, + measure.id() + ), + errors, + ); + } } for entity in &project.entities { validate_entity_display_text(entity, &format!("recordTypes[id={}]", entity.id), errors); diff --git a/crates/registry-breg/src/compiler/statistics.rs b/crates/registry-breg/src/compiler/statistics.rs index dcf83862a5..ccbe49e420 100644 --- a/crates/registry-breg/src/compiler/statistics.rs +++ b/crates/registry-breg/src/compiler/statistics.rs @@ -53,12 +53,12 @@ pub(super) fn compile( )); continue; } - let Some(unit) = entities.get(&source.unit) else { + let Some(unit) = entities.get(&source.record_type) else { errors.push(error( - "breg.statistical-dataset.unit-unknown", - &format!("{root}.unit"), + "breg.statistical-dataset.record-type-unknown", + &format!("{root}.recordType"), &source.id, - &format!("declare the unit entity `{}`", source.unit), + &format!("declare the Record type `{}`", source.record_type), )); continue; }; @@ -85,7 +85,10 @@ pub(super) fn compile( // The fields a live reader must be able to filter on. A measure field is // read, never filtered, so it joins the referenced fields only afterwards. let filtered_fields = referenced_fields.clone(); - let (measures, measure_fields) = compile_measures(source, unit, &root, &mut errors); + let (mut measures, measure_fields) = compile_measures(source, unit, &root, &mut errors); + if !source.historical_statistics { + measures.sort_by(|left, right| left.id().cmp(right.id())); + } referenced_fields.extend(measure_fields.iter().cloned()); validate_referenced_fields(source, unit, &referenced_fields, &root, &mut errors); @@ -323,7 +326,9 @@ pub(super) fn compile( // from that total and recover a cell the other withholds. Every // sum of a field over a unit is released by one dataset. for earlier in &sum_releases { - if earlier.unit == source.unit && !earlier.sum_fields.is_disjoint(&sum_fields) { + if earlier.unit == source.record_type + && !earlier.sum_fields.is_disjoint(&sum_fields) + { errors.push(error( "breg.statistical-dataset.sum-field-released-twice", &root, @@ -337,7 +342,7 @@ pub(super) fn compile( } sum_releases.push(SumRelease { id: source.id.to_string(), - unit: source.unit.clone(), + unit: source.record_type.clone(), sum_fields, }); } @@ -581,7 +586,14 @@ pub(super) fn compile( CompiledStatisticalDataset { id: source.id.to_string(), display: source.display.clone(), - unit_entity_id: source.unit.clone(), + historical_statistics: source.historical_statistics, + measure_display: source + .measures + .iter() + .filter(|measure| !measure.display().is_empty()) + .map(|measure| (measure.id().to_string(), measure.display().clone())) + .collect(), + unit_entity_id: source.record_type.clone(), population: source.population.clone(), period, dimensions, @@ -680,7 +692,7 @@ fn maximum_release_document_bytes( let envelope = canonicalize_json(&json!({ "dataset": { "id": source.id, - "unit": source.unit, + "unit": source.record_type, "measures": measures, "periodKind": period_kind, "granularity": granularity, @@ -1081,8 +1093,8 @@ fn compile_measures( let mut counts = 0_usize; let mut distinct_fields = BTreeSet::new(); let mut measures = Vec::new(); - for (index, measure) in source.measures.iter().enumerate() { - let path = format!("{path}[{index}]"); + for measure in &source.measures { + let path = format!("{path}[id={}]", measure.id()); let id = measure.id(); if !seen.insert(id.as_str()) { errors.push(error( @@ -1686,7 +1698,7 @@ fn definition_digest( require_consent: serde_json::Value, access_requirement_row_boundaries: serde_json::Value, } - let unit = &dependencies.entities[&source.unit]; + let unit = &dependencies.entities[&source.record_type]; let source_columns = dependencies .entities .values() @@ -1788,7 +1800,7 @@ fn definition_digest( } => json!({"kind": "stock", "granularity": granularity, "validity": validity}), }; let mut value = json!({ - "unit": source.unit, + "unit": source.record_type, "population": source.population, "populationFieldBindings": dependencies.population_field_bindings, "referencedFieldDefinitions": referenced_field_definitions, @@ -2312,7 +2324,7 @@ fn compile_sum_disclosure_rules( )), } } - for (index, measure) in source.measures.iter().enumerate() { + for measure in &source.measures { let StatisticalMeasureSource::Sum { field: field_id, .. } = measure @@ -2326,7 +2338,7 @@ fn compile_sum_disclosure_rules( if !non_negative { errors.push(error( "breg.statistical-dataset.sum-release-negative-values", - &format!("{root}.measures[{index}]"), + &format!("{root}.measures[id={}]", measure.id()), &source.id, &format!( "declare a minimum of 0 or more on decimal field `{field_id}`: a released sum of values that may be negative can hide a contributor behind an offsetting one" diff --git a/crates/registry-breg/src/contract.rs b/crates/registry-breg/src/contract.rs index 5a465d998b..4774348431 100644 --- a/crates/registry-breg/src/contract.rs +++ b/crates/registry-breg/src/contract.rs @@ -1284,7 +1284,10 @@ pub struct StatisticalDatasetSource { /// Authored presentation only; labels never establish identity or authority. #[serde(default, skip_serializing_if = "PresentationSource::is_empty")] pub display: PresentationSource, - pub unit: String, + pub record_type: String, + // Set only when replaying sealed sources whose measure lists defined order. + #[serde(skip)] + pub(crate) historical_statistics: bool, pub population: String, pub period: StatisticalPeriodSource, /// Unit Record fields used to group every measure. Each field must be boolean or @@ -1296,14 +1299,16 @@ pub struct StatisticalDatasetSource { /// The values the dataset publishes, one cell per period, dimension /// combination, and measure. Each id is unique, and at most one measure has /// type `count`. Omitting the member publishes one `count` measure named - /// `count`; an empty list is refused. + /// `count`; an empty map is refused. #[serde( default = "default_statistical_measures", + deserialize_with = "registry_platform_yaml::id_keyed_or_list", + serialize_with = "registry_platform_yaml::serialize_id_keyed", skip_serializing_if = "is_default_statistical_measures" )] #[cfg_attr( feature = "schema", - schemars(extend("default" = [{"id": "count", "type": "count"}])) + schemars(schema_with = "statistical_measures_schema") )] pub measures: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -1337,6 +1342,8 @@ pub enum StatisticalMeasureSource { Count { /// Names the measure on every cell that reports it. id: LocalId, + #[serde(default, skip_serializing_if = "PresentationSource::is_empty")] + display: PresentationSource, }, /// The sum of an `int64` or `decimal` unit Record field over the /// population, at the field's scale. Records with no value for the field @@ -1344,6 +1351,8 @@ pub enum StatisticalMeasureSource { Sum { /// Names the measure on every cell that reports it. id: LocalId, + #[serde(default, skip_serializing_if = "PresentationSource::is_empty")] + display: PresentationSource, /// The unit Record field to add up. field: String, }, @@ -1353,6 +1362,8 @@ pub enum StatisticalMeasureSource { Mean { /// Names the measure on every cell that reports it. id: LocalId, + #[serde(default, skip_serializing_if = "PresentationSource::is_empty")] + display: PresentationSource, /// The unit Record field to average. field: String, /// Fractional digits of the reported mean, 0 to 38. @@ -1368,6 +1379,8 @@ pub enum StatisticalMeasureSource { DistinctCount { /// Names the measure on every cell that reports it. id: LocalId, + #[serde(default, skip_serializing_if = "PresentationSource::is_empty")] + display: PresentationSource, /// The unit Record `reference` field whose distinct values are counted. field: String, }, @@ -1377,6 +1390,8 @@ pub enum StatisticalMeasureSource { Ratio { /// Names the measure on every cell that reports it. id: LocalId, + #[serde(default, skip_serializing_if = "PresentationSource::is_empty")] + display: PresentationSource, /// The `count`, `distinct-count` or `sum` measure to divide. numerator: LocalId, /// The `count`, `distinct-count` or `sum` measure to divide by, other @@ -1399,6 +1414,8 @@ pub enum StatisticalMeasureSource { Percentile { /// Names the measure on every cell that reports it. id: LocalId, + #[serde(default, skip_serializing_if = "PresentationSource::is_empty")] + display: PresentationSource, /// The unit Record field to take the percentile of. field: String, /// Which percentile, 1 to 99; the median is 50. @@ -1417,10 +1434,38 @@ pub enum StatisticalMeasureSource { registry_platform_yaml::tagged_union!(StatisticalMeasureSource, tag = "type"); serialize_tagged_union!(StatisticalMeasureSource, tag = "type"); +impl registry_platform_yaml::Identified for StatisticalMeasureSource { + fn id(&self) -> &str { + self.id().as_str() + } +} + +#[cfg(feature = "schema")] +fn statistical_measures_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema { + let mut schema = registry_platform_yaml::id_keyed_schema::(generator); + schema.insert("minProperties".to_owned(), 1.into()); + schema.insert( + "default".to_owned(), + serde_json::json!({"count":{"type":"count"}}), + ); + schema +} + impl StatisticalMeasureSource { + pub fn display(&self) -> &PresentationSource { + match self { + Self::Count { display, .. } + | Self::Sum { display, .. } + | Self::Mean { display, .. } + | Self::DistinctCount { display, .. } + | Self::Ratio { display, .. } + | Self::Percentile { display, .. } => display, + } + } + pub fn id(&self) -> &LocalId { match self { - Self::Count { id } + Self::Count { id, .. } | Self::Sum { id, .. } | Self::Mean { id, .. } | Self::DistinctCount { id, .. } @@ -1433,6 +1478,7 @@ impl StatisticalMeasureSource { fn default_statistical_measures() -> Vec { vec![StatisticalMeasureSource::Count { id: LocalId::new("count").expect("`count` is a local id"), + display: PresentationSource::default(), }] } @@ -6489,7 +6535,7 @@ const PROJECT_REMOVED_KEYS: &[RemovedKey<'static>] = &[ }, RemovedKey { pointer: "/statisticalDatasets/*/id", - replacement: "Write statisticalDatasets as a mapping from each id to the rest of its entry, statisticalDatasets: {DATASET_ID: {unit: ...}}, with no id member.", + replacement: "Write statisticalDatasets as a mapping from each id to the rest of its entry, statisticalDatasets: {DATASET_ID: {recordType: ...}}, with no id member.", }, RemovedKey { pointer: "/evidenceProviders/*/id", @@ -6942,8 +6988,19 @@ fn read_project( } else { &PROJECT_FORMAT }; - let (mut decoded, translated) = - read_with_value_types(file, bytes, format, sealed, predecessor_memberships)?; + let (mut decoded, translated) = read_with_value_types::( + file, + bytes, + format, + sealed, + predecessor_memberships, + )?; + if sealed { + for dataset in &mut decoded.value.statistical_datasets { + let path = format!("/statisticalDatasets/{}/unit", dataset.id); + dataset.historical_statistics = decoded.document.span_of(&path).is_some(); + } + } let errors = crate::authoring_integrity::project_diagnostics(&mut decoded); if errors.is_empty() { Ok((decoded, translated)) @@ -7305,6 +7362,54 @@ fn read_with_value_types( } Err(report) => return Err(report), }; + let mut normalized_statistics = false; + let mut statistical_errors = Vec::new(); + for (pointer, dataset) in entries_mut(&mut value, "statisticalDatasets", "") { + let Some(members) = dataset.as_object_mut() else { + continue; + }; + let old_unit = members.contains_key("unit"); + if sealed && old_unit { + if members.get("measures").is_some_and(Value::is_object) { + return Err(document.report_with([document.diagnostic_at_value( + Severity::Error, + "breg.statistical-dataset.mixed-spelling", + &format!("{pointer}/measures"), + "The sealed source mixes historical and current statistical dataset spellings.", + "Use the original sources sealed by one release.", + )])); + } + normalized_statistics |= + rename_sealed_key(members, "unit", "recordType", &pointer, &document)?; + continue; + } + for (invalid, member, next) in [ + ( + old_unit, + "unit", + "Rename `unit` to `recordType`, keeping the Record type ID.", + ), + ( + members.get("measures").is_some_and(Value::is_array), + "measures", + "Write a map keyed by each measure ID and remove the inline `id` members.", + ), + ] { + if invalid { + statistical_errors.push(document.diagnostic_at_value( + Severity::Error, + "config.removed-key", + &format!("{pointer}/{member}"), + "This statistical dataset member uses a retired authoring spelling.", + next, + )); + } + } + } + if !statistical_errors.is_empty() { + let removed = removed_error.into_iter().flat_map(Report::into_diagnostics); + return Err(document.report_with(removed.chain(statistical_errors))); + } let mut translated = if sealed { let action_plans = normalize_sealed_action_plans(&mut value, &document)?; let proposal_parties = normalize_sealed_proposal_parties(&mut value, &document)?; @@ -7405,7 +7510,12 @@ fn read_with_value_types( if let Some(report) = removed_error { return Err(report); } - if !translated && !has_value_types && !resolved_sets && !has_row_boundary_sets { + if !translated + && !normalized_statistics + && !has_value_types + && !resolved_sets + && !has_row_boundary_sets + { return document .decode() .map(|value| (Decoded { value, document }, false)); @@ -8101,6 +8211,45 @@ mod tests { } } + #[cfg(feature = "runtime")] + #[test] + fn sealed_statistics_preserve_historical_measure_order_and_identity() { + use crate::compiler::{compile_project, CompileProfile}; + + let base = include_str!("../../../products/breg/fixtures/authoring-display/registry.yaml") + .replacen(" - {id: active, type: boolean, required: true, classification: internal}", + " - {id: active, type: boolean, required: true, classification: internal}\n - {id: amount, type: int64, classification: internal}", 1) + .replace("readableFields: [code, active, recorded-on]", "readableFields: [code, active, recorded-on, amount]") + .replace("operations: [publish, read-releases]", "operations: [read-live]"); + let old_order = base.replace(" recordType: entry\n population:", " unit: entry\n measures:\n - {id: z-count, type: count}\n - {id: a-mean, type: mean, field: amount, scale: 2}\n population:"); + let old_sorted = base.replace(" recordType: entry\n population:", " unit: entry\n measures:\n - {id: a-mean, type: mean, field: amount, scale: 2}\n - {id: z-count, type: count}\n population:"); + let current = base.replace(" recordType: entry\n population:", " recordType: entry\n measures:\n z-count: {type: count}\n a-mean: {type: mean, field: amount, scale: 2}\n population:"); + + assert!(parse_project_yaml(old_order.as_bytes()).is_err()); + let compile = |bytes: &str| { + let (project, translated) = parse_sealed_project_yaml(bytes.as_bytes()).unwrap(); + assert!( + !translated, + "the historical source can verify a sealed artifact" + ); + let registry = compile_project(&project, &[], CompileProfile::Authoring).unwrap(); + registry.statistical_datasets()["entry-counts"].clone() + }; + let old = compile(&old_order); + let sorted = compile(&old_sorted); + let current = compile(¤t); + assert_eq!( + old.measures + .iter() + .map(crate::statistics::Measure::id) + .collect::>(), + ["z-count", "a-mean"] + ); + assert_eq!(sorted.measures, current.measures); + assert_eq!(sorted.definition_digest, current.definition_digest); + assert_ne!(old.definition_digest, current.definition_digest); + } + #[cfg(feature = "runtime")] #[test] fn only_a_sealed_project_translates_historical_proposal_ownership() { diff --git a/crates/registry-breg/src/migration.rs b/crates/registry-breg/src/migration.rs index 69d40735f0..0e8e25a420 100644 --- a/crates/registry-breg/src/migration.rs +++ b/crates/registry-breg/src/migration.rs @@ -1082,6 +1082,7 @@ pub async fn plan_verified_package( resumes_activation_id: None, required_backups: Vec::new(), timer_previews: Vec::new(), + statistical_release_impacts: Vec::new(), checks: PlannedActivation::AlreadyActive.checks(), }), Err(error) => Err(error), @@ -1116,10 +1117,62 @@ pub struct ActivationPlan { /// this successor. These are cached predecessor facts, not a projection /// of historical Records or a promise that successor work is runnable. pub timer_previews: Vec, + /// Retained release series whose definition digest changes on activation. + pub statistical_release_impacts: Vec, /// The database checks that passed, in the order they ran. pub checks: &'static [&'static str], } +/// A retained statistical release series hidden by activating a new definition. +#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct StatisticalReleaseImpact { + pub dataset_id: String, + pub old_definition_digest: String, + pub candidate_definition_digest: String, +} + +async fn read_statistical_release_impacts( + client: &tokio_postgres::Client, + predecessor: &CompiledRegistryMigrationBaseline, + candidate: &crate::CompiledRegistry, +) -> Result> { + let mut impacts = Vec::new(); + for (id, before) in &predecessor.statistical_datasets { + let Some(after) = candidate.statistical_datasets().get(id) else { + continue; + }; + if before.definition_digest == after.definition_digest || before.releases.is_none() { + continue; + } + let retained: bool = client + .query_one( + "SELECT EXISTS ( + SELECT 1 + FROM registry_internal.registry_statistical_release_versions AS version + JOIN registry_internal.registry_statistical_release_contents AS content + USING (dataset_id, period_code, release_version) + LEFT JOIN registry_internal.registry_statistical_release_withdrawals AS withdrawal + USING (dataset_id, period_code, release_version) + WHERE version.dataset_id = $1 AND version.definition_digest = $2 + AND withdrawal.dataset_id IS NULL + )", + &[id, &before.definition_digest], + ) + .await + .map_err(|error| named_refusal(error.into()).unwrap_or(MigrationError::ApplyFailed))? + .get(0); + if retained { + impacts.push(StatisticalReleaseImpact { + dataset_id: id.clone(), + old_definition_digest: before.definition_digest.clone(), + candidate_definition_digest: after.definition_digest.clone(), + }); + } + } + Ok(impacts) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PlannedActivation { Initial, @@ -1584,7 +1637,7 @@ async fn activate(request: ApplyVerifiedPackageRequest<'_>, mode: ApplyMode) -> ) .map_err(|_| MigrationError::PackageBinding)?; read_timer_activation_previews( - connection.client_for_proposal_retention_guard(), + connection.client_for_activation_inspection(), definitions, ) .await @@ -1592,6 +1645,17 @@ async fn activate(request: ApplyVerifiedPackageRequest<'_>, mode: ApplyMode) -> } else { Vec::new() }; + let statistical_release_impacts = + if let Some(predecessor) = successor_history.and_then(|(baseline, _)| baseline) { + read_statistical_release_impacts( + connection.client_for_activation_inspection(), + predecessor, + request.package.registry(), + ) + .await? + } else { + Vec::new() + }; let released = connection.release().await; released.map_err(|_| MigrationError::ApplyFailed)?; let activation = match current { @@ -1605,6 +1669,7 @@ async fn activate(request: ApplyVerifiedPackageRequest<'_>, mode: ApplyMode) -> resumes_activation_id, required_backups, timer_previews, + statistical_release_impacts, checks: activation.checks(), })); } @@ -1634,7 +1699,7 @@ async fn activate(request: ApplyVerifiedPackageRequest<'_>, mode: ApplyMode) -> Ok(()) } else { crate::proposal_retention::guard_successor_activation( - connection.client_for_proposal_retention_guard(), + connection.client_for_activation_inspection(), request.package.registry(), ) .await @@ -1998,7 +2063,7 @@ async fn rehearse_begin( // The guard reads current Proposal state before successor maintenance. if !role_change { crate::proposal_retention::guard_successor_activation( - connection.client_for_proposal_retention_guard(), + connection.client_for_activation_inspection(), request.package.registry(), ) .await diff --git a/crates/registry-breg/src/model.rs b/crates/registry-breg/src/model.rs index 17cdefc343..4adfe2ce74 100644 --- a/crates/registry-breg/src/model.rs +++ b/crates/registry-breg/src/model.rs @@ -204,6 +204,10 @@ pub struct CompiledStatisticalDataset { skip_serializing_if = "crate::contract::PresentationSource::is_empty" )] pub display: crate::contract::PresentationSource, + #[serde(skip)] + pub(crate) historical_statistics: bool, + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub(crate) measure_display: BTreeMap, pub unit_entity_id: String, pub population: String, pub period: CompiledStatisticalPeriod, diff --git a/crates/registry-breg/src/package.rs b/crates/registry-breg/src/package.rs index 036b5c9d75..a85efcd1b2 100644 --- a/crates/registry-breg/src/package.rs +++ b/crates/registry-breg/src/package.rs @@ -1258,11 +1258,15 @@ pub(crate) fn statistical_dataset_behavior_eq( ) -> bool { let mut before = before.clone(); before.display = Default::default(); + before.measure_display.clear(); + before.historical_statistics = false; for profile in before.access_profiles.values_mut() { profile.display = Default::default(); } let mut after = after.clone(); after.display = Default::default(); + after.measure_display.clear(); + after.historical_statistics = false; for profile in after.access_profiles.values_mut() { profile.display = Default::default(); } @@ -3302,8 +3306,27 @@ pub fn prepare_package(request: PackageBuildRequest) -> Result /// scripts. The separate argument preserves the existing package build request /// API while keeping script bytes inside the sealed source closure. pub fn prepare_package_with_project_assets( + request: PackageBuildRequest, + project_assets: Vec, +) -> Result { + prepare_package_with_project_reader(request, project_assets, parse_project_yaml) +} + +/// Recreate a previously issued package for statistical migration tests. +#[cfg(feature = "postgres-test")] +#[doc(hidden)] +pub fn prepare_historical_statistics_package_for_test( + request: PackageBuildRequest, +) -> Result { + prepare_package_with_project_reader(request, Vec::new(), |bytes| { + parse_sealed_project_yaml(bytes).map(|(project, _)| project) + }) +} + +fn prepare_package_with_project_reader( mut request: PackageBuildRequest, mut project_assets: Vec, + read_project: fn(&[u8]) -> std::result::Result, ) -> Result { request .modules @@ -3322,8 +3345,7 @@ pub fn prepare_package_with_project_assets( { return Err(PackageError::Closure); } - let project = - parse_project_yaml(&request.project.bytes).map_err(|_| PackageError::Derivation)?; + let project = read_project(&request.project.bytes).map_err(|_| PackageError::Derivation)?; let modules = request .modules .iter() diff --git a/crates/registry-breg/src/postgres/interlock.rs b/crates/registry-breg/src/postgres/interlock.rs index b6ca9b2fc1..1471638514 100644 --- a/crates/registry-breg/src/postgres/interlock.rs +++ b/crates/registry-breg/src/postgres/interlock.rs @@ -319,7 +319,7 @@ impl DedicatedApplyConnection { .await } - pub(crate) fn client_for_proposal_retention_guard(&self) -> &Client { + pub(crate) fn client_for_activation_inspection(&self) -> &Client { &self.client } diff --git a/crates/registry-breg/src/statistical_artifacts.rs b/crates/registry-breg/src/statistical_artifacts.rs index c36ecd452d..d07349f772 100644 --- a/crates/registry-breg/src/statistical_artifacts.rs +++ b/crates/registry-breg/src/statistical_artifacts.rs @@ -9,6 +9,7 @@ use crate::model::{CompiledStatisticalDataset, CompiledStatisticalPeriod}; use crate::problem::ProblemCode; use crate::statistics::{TOTAL_CODE, UNKNOWN_CODE}; +#[cfg(feature = "runtime")] pub(crate) fn statistical_dataset_metadata_entry( dataset: &CompiledStatisticalDataset, profile: &str, @@ -17,8 +18,27 @@ pub(crate) fn statistical_dataset_metadata_entry( if operations.is_empty() { return None; } + let mut entry = dataset_metadata(dataset, true); + entry["operations"] = json!(operations); + Some(entry) +} + +fn dataset_metadata(dataset: &CompiledStatisticalDataset, include_display: bool) -> Value { let (period_kind, granularity, first_period) = period_metadata(&dataset.period); - Some(json!({ + let measures = dataset + .measures + .iter() + .map(|measure| { + let mut descriptor = json!(measure); + if include_display { + if let Some(display) = dataset.measure_display.get(measure.id()) { + descriptor["display"] = json!(display); + } + } + descriptor + }) + .collect::>(); + let mut entry = json!({ "id": dataset.id, "unit": dataset.unit_entity_id, "periodKind": period_kind, @@ -36,10 +56,13 @@ pub(crate) fn statistical_dataset_metadata_entry( "codes": codes, }) }).collect::>(), - "measures": dataset.measures, + "measures": measures, "definitionDigest": dataset.definition_digest, - "operations": operations, - })) + }); + if include_display && !dataset.display.is_empty() { + entry["display"] = json!(dataset.display); + } + entry } pub(crate) fn all_statistical_dataset_metadata( @@ -49,29 +72,18 @@ pub(crate) fn all_statistical_dataset_metadata( datasets .values() .map(|dataset| { - let mut profiles = Map::new(); - for profile in dataset.access_profiles.keys() { - if let Some(entry) = statistical_dataset_metadata_entry(dataset, profile) { - profiles.insert(profile.clone(), entry["operations"].clone()); - } - } - let (period_kind, granularity, first_period) = period_metadata(&dataset.period); - json!({ - "id": dataset.id, - "unit": dataset.unit_entity_id, - "periodKind": period_kind, - "granularity": granularity, - "firstPeriod": first_period, - "dimensions": dataset.dimensions.iter().map(|dimension| { - let mut codes = dimension.codes.clone(); - if dimension.include_unknown { codes.push(UNKNOWN_CODE.to_owned()); } - codes.push(TOTAL_CODE.to_owned()); - json!({"field":dimension.field,"vocabulary":dimension_vocabulary(dimension),"codes":codes}) - }).collect::>(), - "measures": dataset.measures, - "definitionDigest": dataset.definition_digest, - "accessProfiles": profiles, - }) + let profiles: Map = dataset + .access_profiles + .keys() + .filter_map(|profile| { + let operations = statistical_dataset_operations(dataset, profile); + (!operations.is_empty()).then(|| (profile.clone(), json!(operations))) + }) + .collect(); + // Reproduce the generated artifact of already-issued packages. + let mut entry = dataset_metadata(dataset, !dataset.historical_statistics); + entry["accessProfiles"] = json!(profiles); + entry }) .collect(), ) diff --git a/crates/registry-breg/tests/compiler_statistics.rs b/crates/registry-breg/tests/compiler_statistics.rs index 5fa3898b22..9475d008a7 100644 --- a/crates/registry-breg/tests/compiler_statistics.rs +++ b/crates/registry-breg/tests/compiler_statistics.rs @@ -81,7 +81,7 @@ fn source() -> Value { "other-reader": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{}} }, "vocabularies": {"category": {"values":["a","b"]}}, - "statisticalDatasets": {"records-by-category": {"unit":"record", + "statisticalDatasets": {"records-by-category": {"recordType":"record", "population":"active eq true", "period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"}, "dimensions":["category"], @@ -686,9 +686,9 @@ fn statistical_dataset_core_refusals_are_stable_and_actionable() { let cases: Vec = vec![ ( Box::new(|v| { - v["statisticalDatasets"]["records-by-category"]["unit"] = json!("missing") + v["statisticalDatasets"]["records-by-category"]["recordType"] = json!("missing") }), - "breg.statistical-dataset.unit-unknown", + "breg.statistical-dataset.record-type-unknown", ), ( Box::new(|v| { @@ -2260,10 +2260,10 @@ fn omitted_measures_compile_to_one_count_measure_named_count() { } #[test] -fn declared_measures_compile_in_declared_order_with_their_ids() { +fn declared_measures_compile_with_their_ids() { let mut value = source(); value["statisticalDatasets"]["records-by-category"]["measures"] = - json!([{"id":"parcels","type":"count"}]); + json!({"parcels": {"type":"count"}}); let compiled = compile(&value).expect("a declared count measure compiles"); assert_eq!( measures_of(&compiled), @@ -2279,24 +2279,15 @@ fn declared_measures_compile_in_declared_order_with_their_ids() { #[test] fn measure_declarations_are_refused_with_stable_codes() { assert_refused( - |v| v["statisticalDatasets"]["records-by-category"]["measures"] = json!([]), + |v| v["statisticalDatasets"]["records-by-category"]["measures"] = json!({}), "breg.statistical-dataset.measures-empty", ); assert_refused( |v| { - v["statisticalDatasets"]["records-by-category"]["measures"] = json!([ - {"id":"parcels","type":"count"}, - {"id":"parcels","type":"count"} - ]) - }, - "breg.statistical-dataset.measure-duplicate", - ); - assert_refused( - |v| { - v["statisticalDatasets"]["records-by-category"]["measures"] = json!([ - {"id":"parcels","type":"count"}, - {"id":"holdings","type":"count"} - ]) + v["statisticalDatasets"]["records-by-category"]["measures"] = json!({ + "parcels": {"type":"count"}, + "holdings": {"type":"count"} + }) }, "breg.statistical-dataset.measure-count-duplicate", ); @@ -2305,11 +2296,12 @@ fn measure_declarations_are_refused_with_stable_codes() { #[test] fn a_measure_with_an_unknown_type_or_member_or_a_bad_id_does_not_read() { for measures in [ - json!([{"id":"parcels","type":"sum"}]), - json!([{"id":"parcels","type":"count","field":"x"}]), - json!([{"id":"Parcels","type":"count"}]), - json!([{"id":"parcels"}]), - json!([{"type":"count"}]), + json!({"parcels":{"type":"sum"}}), + json!({"parcels":{"type":"count","field":"x"}}), + json!({"Parcels":{"type":"count"}}), + json!({"parcels":{}}), + json!({"parcels":{"type":"unknown"}}), + json!({"parcels":{"type":"count","id":"other"}}), ] { let mut value = source(); value["statisticalDatasets"]["records-by-category"]["measures"] = measures.clone(); @@ -2331,7 +2323,7 @@ fn definition_digest_covers_the_measures_including_the_defaulted_one() { let omitted = digest(&source()); let mut spelled = source(); spelled["statisticalDatasets"]["records-by-category"]["measures"] = - json!([{"id":"count","type":"count"}]); + json!({"count": {"type":"count"}}); assert_eq!( omitted, digest(&spelled), @@ -2340,7 +2332,7 @@ fn definition_digest_covers_the_measures_including_the_defaulted_one() { let mut renamed = source(); renamed["statisticalDatasets"]["records-by-category"]["measures"] = - json!([{"id":"parcels","type":"count"}]); + json!({"parcels": {"type":"count"}}); assert_ne!(omitted, digest(&renamed)); } @@ -2362,7 +2354,8 @@ fn live_measure_source(measures: Value) -> Value { grant(&mut value, ANALYST, &["read-live"]); grant(&mut value, PUBLISHER, &[]); grant(&mut value, READER, &[]); - value["statisticalDatasets"]["records-by-category"]["measures"] = measures; + value["statisticalDatasets"]["records-by-category"]["measures"] = + source_bytes::keyed_measures(measures.clone()); value } @@ -2391,11 +2384,11 @@ fn a_sum_and_a_mean_compile_with_the_scale_their_field_gives() { assert_eq!( measures_of(&compiled), json!([ + {"id":"average-amount","type":"mean","field":"amount","scale":3}, + {"id":"average-units","type":"mean","field":"quantity","scale":0}, {"id":"parcels","type":"count"}, {"id":"total-amount","type":"sum","field":"amount","scale":2}, - {"id":"total-units","type":"sum","field":"quantity","scale":0}, - {"id":"average-amount","type":"mean","field":"amount","scale":3}, - {"id":"average-units","type":"mean","field":"quantity","scale":0} + {"id":"total-units","type":"sum","field":"quantity","scale":0} ]) ); let metadata = artifact_json(&compiled, "generated/metadata/registry.json"); @@ -2616,7 +2609,8 @@ fn public_register_source(measures: Value) -> Value { .unwrap() .extend([json!("amount"), json!("quantity")]); } - value["statisticalDatasets"]["records-by-category"]["measures"] = measures; + value["statisticalDatasets"]["records-by-category"]["measures"] = + source_bytes::keyed_measures(measures.clone()); value["statisticalDatasets"]["records-by-category"]["disclosure"] = json!({"type":"exact-public-values"}); value @@ -3033,7 +3027,7 @@ fn measure_ids_that_differ_only_by_a_separator_are_refused() { assert!( refusals.iter().any(|(code, path, message)| { code == "breg.statistical-dataset.measure-id-collision" - && path == "project.statisticalDatasets.records-by-category.measures[1].id" + && path == "project.statisticalDatasets.records-by-category.measures.mean_amount" && message.contains("`mean-amount`") && message.contains("`mean_amount`") }), @@ -3237,8 +3231,8 @@ fn a_distinct_count_over_a_reference_field_compiles() { assert_eq!( measures_of(&compiled), json!([ - {"id":"parcels","type":"count"}, - {"id":"owners","type":"distinct-count","field":"owner"} + {"id":"owners","type":"distinct-count","field":"owner"}, + {"id":"parcels","type":"count"} ]) ); let metadata = artifact_json(&compiled, "generated/metadata/registry.json"); @@ -3257,7 +3251,7 @@ fn a_distinct_count_field_must_be_a_known_reference_field() { assert_distinct_refused( &distinct_source(json!([{"id":"owners","type":"distinct-count","field":field}])), "breg.statistical-dataset.measure-field-type", - "measures[0].field", + "measures[id=owners].field", ); } let failure = compile(&distinct_source( @@ -3284,7 +3278,7 @@ fn two_distinct_counts_over_one_field_are_refused_and_over_two_fields_are_not() assert_distinct_refused( &value, "breg.statistical-dataset.measure-distinct-count-duplicate", - "measures[1].field", + "measures[id=owners].field", ); value["recordTypes"]["record"]["fields"] .as_array_mut() @@ -3296,10 +3290,10 @@ fn two_distinct_counts_over_one_field_are_refused_and_over_two_fields_are_not() .as_array_mut() .unwrap() .push(json!("agent")); - value["statisticalDatasets"]["records-by-category"]["measures"] = json!([ - {"id":"owners","type":"distinct-count","field":"owner"}, - {"id":"agents","type":"distinct-count","field":"agent"} - ]); + value["statisticalDatasets"]["records-by-category"]["measures"] = json!({ + "owners": {"type":"distinct-count","field":"owner"}, + "agents": {"type":"distinct-count","field":"agent"} + }); compile(&value).expect("distinct counts over different fields compile"); } @@ -3409,11 +3403,11 @@ fn a_distinct_count_is_released_with_rounding_but_a_sum_beside_it_is_not() { .push(json!("owner")); compile(&value).expect("a count and a distinct count release with rounding"); - value["statisticalDatasets"]["records-by-category"]["measures"] = json!([ - {"id":"parcels","type":"count"}, - {"id":"owners","type":"distinct-count","field":"owner"}, - {"id":"total","type":"sum","field":"amount"} - ]); + value["statisticalDatasets"]["records-by-category"]["measures"] = json!({ + "parcels": {"type":"count"}, + "owners": {"type":"distinct-count","field":"owner"}, + "total": {"type":"sum","field":"amount"} + }); let failure = compile(&value).expect_err("a sum cannot be released with rounding"); assert!(failure .diagnostics() @@ -3540,15 +3534,15 @@ fn a_ratio_and_a_percentile_compile_with_the_scale_they_declare() { fn ratio_measures_compiled() -> Value { json!([ - {"id":"parcels","type":"count"}, - {"id":"total-amount","type":"sum","field":"amount","scale":2}, {"id":"amount-per-parcel","type":"ratio","numerator":"total-amount","denominator":"parcels","scale":2}, - {"id":"median-amount","type":"percentile","field":"amount","percentile":50,"scale":2} + {"id":"median-amount","type":"percentile","field":"amount","percentile":50,"scale":2}, + {"id":"parcels","type":"count"}, + {"id":"total-amount","type":"sum","field":"amount","scale":2} ]) } #[test] -fn a_ratio_may_name_an_operand_declared_after_it_and_a_distinct_count_or_sum() { +fn a_ratio_resolves_sibling_count_distinct_count_and_sum_operands() { let compiled = compile(&distinct_source(json!([ {"id":"per-owner","type":"ratio","numerator":"parcels","denominator":"owners","scale":3}, {"id":"parcels","type":"count"}, @@ -3556,7 +3550,7 @@ fn a_ratio_may_name_an_operand_declared_after_it_and_a_distinct_count_or_sum() { {"id":"total","type":"sum","field":"amount"}, {"id":"amount-per-owner","type":"ratio","numerator":"total","denominator":"owners","scale":0} ]))) - .expect("operands declared anywhere in the list are found"); + .expect("operands are resolved by ID"); assert_eq!( measures_of(&compiled) .as_array() @@ -3565,11 +3559,11 @@ fn a_ratio_may_name_an_operand_declared_after_it_and_a_distinct_count_or_sum() { .map(|measure| measure["id"].as_str().unwrap().to_owned()) .collect::>(), [ - "per-owner", - "parcels", + "amount-per-owner", "owners", - "total", - "amount-per-owner" + "parcels", + "per-owner", + "total" ] ); } @@ -3589,8 +3583,16 @@ fn a_ratio_operand_is_a_count_distinct_count_or_sum_of_the_same_dataset() { let code = "breg.statistical-dataset.ratio-operand"; let ratio = |numerator: &str, denominator: &str| json!({"id":"r","type":"ratio","numerator":numerator,"denominator":denominator,"scale":2}); for bad in ["average", "median", "other", "missing", "r"] { - assert_measure_refused_at(base(ratio(bad, "parcels")), code, "measures[5].numerator"); - assert_measure_refused_at(base(ratio("total", bad)), code, "measures[5].denominator"); + assert_measure_refused_at( + base(ratio(bad, "parcels")), + code, + "measures[id=r].numerator", + ); + assert_measure_refused_at( + base(ratio("total", bad)), + code, + "measures[id=r].denominator", + ); } // The same measure on both sides is always 1. let failure = compile(&live_measure_source(base(ratio("total", "total")))) @@ -3600,7 +3602,7 @@ fn a_ratio_operand_is_a_count_distinct_count_or_sum_of_the_same_dataset() { .diagnostics() .iter() .any(|diagnostic| diagnostic.code == code - && diagnostic.path.ends_with("measures[5].denominator") + && diagnostic.path.ends_with("measures[id=r].denominator") && diagnostic.message.contains("total")), "{:?}", failure.diagnostics() @@ -3648,7 +3650,7 @@ fn a_percentile_field_must_be_int64_or_decimal_and_known() { assert_measure_refused_at( json!([{"id":"p","type":"percentile","field":field,"percentile":50,"scale":1}]), "breg.statistical-dataset.measure-field-type", - "measures[0].field", + "measures[id=p].field", ); } assert_measure_refused_at( @@ -3748,10 +3750,10 @@ fn a_ratio_is_additive_and_a_percentile_is_not() { assert_eq!( additive, [ - ("parcels", true), - ("total-amount", true), ("amount-per-parcel", true), - ("median-amount", false) + ("median-amount", false), + ("parcels", true), + ("total-amount", true) ] ); } @@ -3981,7 +3983,7 @@ fn a_contributor_or_dominance_without_a_sum_or_a_publisher_is_refused() { let counts = || { let mut value = sum_release_source(); value["statisticalDatasets"]["records-by-category"]["measures"] = - json!([{"id":"parcels","type":"count"}]); + json!({"parcels": {"type":"count"}}); value }; let unpublished = || { @@ -4115,11 +4117,11 @@ fn a_summed_decimal_field_must_declare_a_non_negative_minimum() { let refusal = diagnostic_for(&amount_minimum(None), "sum-release-negative-values"); assert!(refusal .path - .ends_with("statisticalDatasets[id=records-by-category].measures[1]")); + .ends_with("statisticalDatasets[id=records-by-category].measures[id=total-amount]")); // the int64 sum declares no bounds and is not refused let mut int_only = amount_minimum(None); int_only["statisticalDatasets"]["records-by-category"]["measures"] = - json!([{"id":"total-units","type":"sum","field":"quantity"}]); + json!({"total-units": {"type":"sum","field":"quantity"}}); assert!(!codes_of(&int_only).contains(&code("sum-release-negative-values"))); } @@ -4263,17 +4265,17 @@ fn a_summed_field_released_by_two_datasets_over_one_unit_is_refused_at_the_secon assert_eq!(released_twice_refusals(&different_granularity).len(), 1); // a different summed field let different_field = two_sum_releases(|second| { - second["measures"] = json!([{"id":"total-amount","type":"sum","field":"amount"}]); + second["measures"] = json!({"total-amount": {"type":"sum","field":"amount"}}); }); let mut only_amount = different_field; only_amount["statisticalDatasets"]["records-by-category"]["measures"] = - json!([{"id":"total-units","type":"sum","field":"quantity"}]); + json!({"total-units": {"type":"sum","field":"quantity"}}); assert!(released_twice_refusals(&only_amount).is_empty()); } #[test] fn a_summed_field_released_over_two_units_is_not_refused() { - let mut value = two_sum_releases(|second| second["unit"] = json!("record-two")); + let mut value = two_sum_releases(|second| second["recordType"] = json!("record-two")); let mut second_type = value["recordTypes"]["record"].clone(); second_type["route"] = json!("records-two"); value["recordTypes"]["record-two"] = second_type; @@ -4296,11 +4298,12 @@ fn means_ratios_and_percentiles_are_still_refused_for_release_and_name_what_is_c json!({"id":"m","type":"percentile","field":"amount","percentile":50,"scale":2}), ] { let mut value = sum_release_source(); - value["statisticalDatasets"]["records-by-category"]["measures"] = json!([ - {"id":"parcels","type":"count"}, - {"id":"owners","type":"distinct-count","field":"owner"}, - measure - ]); + value["statisticalDatasets"]["records-by-category"]["measures"] = + source_bytes::keyed_measures(json!([ + {"id":"parcels","type":"count"}, + {"id":"owners","type":"distinct-count","field":"owner"}, + measure + ])); value["statisticalDatasets"]["records-by-category"]["disclosure"] = json!({"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}); let refusal = diagnostic_for(&value, "measure-release-unsupported"); @@ -4335,3 +4338,84 @@ fn a_dominance_percent_outside_one_to_one_hundred_is_refused_when_the_project_is assert_eq!(codes_of(&value), vec![HELD.to_owned()]); } } + +#[test] +fn keyed_measures_sort_by_id_and_display_only_changes_metadata() { + let mut value = source(); + let dataset = &mut value["statisticalDatasets"]["records-by-category"]; + dataset["measures"] = json!({ + "z-count": {"type":"count", "display":{"label":"Records"}} + }); + let compiled = compile(&value).unwrap(); + let definition = &compiled.statistical_datasets()["records-by-category"]; + assert_eq!(definition.measures[0].id(), "z-count"); + let metadata = artifact_json(&compiled, "generated/metadata/registry.json"); + assert_eq!( + metadata["statisticalDatasets"][0]["measures"][0]["display"]["label"], + "Records" + ); + value["statisticalDatasets"]["records-by-category"]["measures"]["z-count"] + .as_object_mut() + .unwrap() + .remove("display"); + assert_eq!( + compile(&value).unwrap().statistical_datasets()["records-by-category"].definition_digest, + definition.definition_digest, + ); +} + +#[test] +fn raw_statistical_measure_duplicates_are_refused_at_the_key() { + let source = source(); + let mut json = serde_json::to_string(&source).unwrap(); + json = json.replace( + "\"records-by-category\":{", + "\"records-by-category\":{\"measures\":{\"count\":{\"type\":\"count\"},\"count\":{\"type\":\"count\"}},", + ); + let yaml = r#" +apiVersion: id.registrystack.org/formats/breg/project/v1alpha1 +kind: BRegProject +statisticalDatasets: + records-by-category: + recordType: record + measures: + count: {type: count} + count: {type: count} +"#; + for (name, bytes) in [("registry.json", json.as_str()), ("registry.yaml", yaml)] { + let report = registry_breg::contract::read_project_yaml(name, bytes.as_bytes()) + .expect_err("duplicate measure key"); + assert!( + report.diagnostics().iter().any(|d| { + d.code == "yaml.duplicate-key" + && d.path == "/statisticalDatasets/records-by-category/measures/count" + }), + "{report:?}" + ); + } +} + +#[test] +fn legacy_statistical_spellings_point_to_their_replacements() { + let mut value = source(); + let dataset = value["statisticalDatasets"]["records-by-category"] + .as_object_mut() + .unwrap(); + let record_type = dataset.remove("recordType").unwrap(); + dataset.insert("unit".to_owned(), record_type); + dataset.insert( + "measures".to_owned(), + json!([{"id":"count","type":"count"}]), + ); + let errors = read_refusals(&value); + for (member, replacement) in [("unit", "recordType"), ("measures", "map keyed")] { + assert!( + errors + .iter() + .any(|(code, path, message)| code == "config.removed-key" + && path.ends_with(&format!(".records-by-category.{member}")) + && message.contains(replacement)), + "{errors:?}" + ); + } +} diff --git a/crates/registry-breg/tests/disclosure_compile.rs b/crates/registry-breg/tests/disclosure_compile.rs index 66ac5d40b3..933164c915 100644 --- a/crates/registry-breg/tests/disclosure_compile.rs +++ b/crates/registry-breg/tests/disclosure_compile.rs @@ -618,7 +618,7 @@ fn statistics_source() -> Value { }, "vocabularies": {"category": {"values":["a","b"]}}, "statisticalDatasets": {"records-by-category": { - "unit":"record","population":"active eq true", + "recordType":"record","population":"active eq true", "period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"}, "dimensions":["category"], "disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}}} diff --git a/crates/registry-breg/tests/http_auth.rs b/crates/registry-breg/tests/http_auth.rs index 76f5cbe083..67b22f31e3 100644 --- a/crates/registry-breg/tests/http_auth.rs +++ b/crates/registry-breg/tests/http_auth.rs @@ -3422,7 +3422,7 @@ fn dataset_only_claim_source() -> Value { "reader": { "principalClaim":"registry_principal", "requiredScopes":["statistics:read"], "requiredPurposes":[PURPOSE], "permissions":{"datasets":[{"dataset":"counts", "operations":["read-releases"]}]}} }, - "statisticalDatasets":{"counts": {"unit":"record", "population":"active eq true", + "statisticalDatasets":{"counts": {"recordType":"record", "population":"active eq true", "period":{"type":"flow", "field":"occurred-on", "granularity":"month", "firstPeriod":"2025-01"}, "dimensions":["active"], "disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}}} }) diff --git a/crates/registry-breg/tests/native_inspection_inventory.rs b/crates/registry-breg/tests/native_inspection_inventory.rs index 98202d6bda..74a02ba11c 100644 --- a/crates/registry-breg/tests/native_inspection_inventory.rs +++ b/crates/registry-breg/tests/native_inspection_inventory.rs @@ -265,7 +265,7 @@ fn omitted_and_empty_profile_display_have_identical_compiled_meaning() { #[test] fn profile_dataset_and_hook_displays_refuse_record_title_selection() { let mut source = source(); - source["statisticalDatasets"] = json!({"counts": {"unit":"facility", "population":"active eq true", + source["statisticalDatasets"] = json!({"counts": {"recordType":"facility", "population":"active eq true", "period":{"type":"flow", "field":"date", "granularity":"month", "firstPeriod":"2025-01"}, "dimensions":["active"] }}); @@ -486,7 +486,7 @@ fn dataset_inventory_includes_dataset_only_profile_authentication() { json!({"id":"event-date", "type":"date", "required":true, "classification":"internal"}), ]); source["project"]["timezone"] = json!("UTC"); - source["statisticalDatasets"] = json!({"directory-counts": {"display":{"label":"Directory counts"}, "unit":"directory-entry", "population":"active eq true", + source["statisticalDatasets"] = json!({"directory-counts": {"display":{"label":"Directory counts"}, "recordType":"directory-entry", "population":"active eq true", "period":{"type":"flow", "field":"event-date", "granularity":"month", "firstPeriod":"2025-01"}, "dimensions":["active"], "disclosure":{"type":"minimum-count-and-rounding","minimumCount":5, "roundingBase":5}}}); source["accessProfiles"].as_object_mut().unwrap().extend([ diff --git a/crates/registry-breg/tests/postgres_statistics_byte_limits.rs b/crates/registry-breg/tests/postgres_statistics_byte_limits.rs index 85f692238c..268f4a81b5 100644 --- a/crates/registry-breg/tests/postgres_statistics_byte_limits.rs +++ b/crates/registry-breg/tests/postgres_statistics_byte_limits.rs @@ -56,7 +56,7 @@ async fn authored_multi_period_response_obeys_the_shared_document_byte_limit() { "recordTypes":{"unit": {"route":"units","primaryDataset":"load","mutationMode":"mutable","fields":fields}}, "vocabularies":vocabularies, "accessProfiles":{"publisher": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{"recordType":"unit","operations":["list"],"allowCount":true,"rowBoundaries":"unrestricted","readableFields":accessible,"filterableFields":accessible}],"datasets":[{"dataset":"units-by-category","operations":["read-live"]}]}}}, - "statisticalDatasets":{"units-by-category": {"unit":"unit","population":"eventDate ne null","period":{"type":"flow","field":"event-date","granularity":"day","firstPeriod":"2025-01-01"},"dimensions":dimension_ids,"disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}}} + "statisticalDatasets":{"units-by-category": {"recordType":"unit","population":"eventDate ne null","period":{"type":"flow","field":"event-date","granularity":"day","firstPeriod":"2025-01-01"},"dimensions":dimension_ids,"disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}}} }); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); let compiled = Arc::new(compile_project(&project, &[], CompileProfile::Authoring).unwrap()); diff --git a/crates/registry-breg/tests/postgres_statistics_exact.rs b/crates/registry-breg/tests/postgres_statistics_exact.rs index 9362131a43..25277f2037 100644 --- a/crates/registry-breg/tests/postgres_statistics_exact.rs +++ b/crates/registry-breg/tests/postgres_statistics_exact.rs @@ -98,14 +98,14 @@ fn registry_source(dimension: &str) -> Value { }]}} }, "vocabularies":{"category": {"values":["a","b","c"]}}, - "statisticalDatasets":{"records-by-category": {"unit":"record","population":"active eq true", + "statisticalDatasets":{"records-by-category": {"recordType":"record","population":"active eq true", "period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"}, "dimensions":[dimension], - "measures":[ - {"id":"records","type":"count"}, - {"id":"amount-sum","type":"sum","field":"amount"}, - {"id":"amount-mean","type":"mean","field":"amount","scale":2} - ], + "measures":{ + "records": {"type":"count"}, + "amount-sum": {"type":"sum","field":"amount"}, + "amount-mean": {"type":"mean","field":"amount","scale":2} + }, "exactReads":{"accessProfile":"analyst"}, "disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5} }} diff --git a/crates/registry-breg/tests/postgres_statistics_first_period.rs b/crates/registry-breg/tests/postgres_statistics_first_period.rs index 2e7c16ccbb..f5739db865 100644 --- a/crates/registry-breg/tests/postgres_statistics_first_period.rs +++ b/crates/registry-breg/tests/postgres_statistics_first_period.rs @@ -37,7 +37,7 @@ async fn moving_first_period_forward_hides_old_releases_without_changing_the_def "project":{"id":"statistics-load","version":"1","defaultLanguage":"en","canonicalBaseIri":"https://load.example.test","timezone":"UTC"}, "recordTypes":{"unit": {"route":"units","primaryDataset":"load","mutationMode":"mutable","fields":[{"id":"active","type":"boolean","required":true,"classification":"internal"},{"id":"event-date","type":"date","required":true,"classification":"internal"}]}}, "accessProfiles":{"publisher": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"records":[{"recordType":"unit","operations":["list"],"allowCount":true,"rowBoundaries":"unrestricted","readableFields":["active","event-date"],"filterableFields":["active","event-date"]}],"datasets":[{"dataset":"units-by-category","operations":["read-live","publish","read-releases"]}]}},"reader": {"principalClaim":"principal","requiredScopes":"unrestricted","permissions":{"datasets":[{"dataset":"units-by-category","operations":["read-releases"]}]}}}, - "statisticalDatasets":{"units-by-category": {"unit":"unit","population":"active ne null","period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"},"dimensions":["active"],"disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}}} + "statisticalDatasets":{"units-by-category": {"recordType":"unit","population":"active ne null","period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"},"dimensions":["active"],"disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}}} }); let project = parse_project_json(&serde_json::to_vec(&source).unwrap()).unwrap(); let compiled = Arc::new(compile_project(&project, &[], CompileProfile::Authoring).unwrap()); diff --git a/crates/registry-breg/tests/postgres_statistics_http.rs b/crates/registry-breg/tests/postgres_statistics_http.rs index 4729616378..29a1e3e9d9 100644 --- a/crates/registry-breg/tests/postgres_statistics_http.rs +++ b/crates/registry-breg/tests/postgres_statistics_http.rs @@ -4427,35 +4427,90 @@ async fn insert_other_definition_release( #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn changing_population_through_package_apply_starts_a_new_release_series() { + statistical_successor_release_impact(StatisticalSuccessor::PopulationChange).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn sorting_legacy_measures_is_previewed_before_it_hides_the_release_series() { + statistical_successor_release_impact(StatisticalSuccessor::LegacyUnsorted).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn id_sorted_legacy_measures_keep_the_release_readable_after_activation() { + statistical_successor_release_impact(StatisticalSuccessor::LegacySorted).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn withdrawn_versions_do_not_count_as_retained_release_impact() { + statistical_successor_release_impact(StatisticalSuccessor::Withdrawn).await; +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum StatisticalSuccessor { + PopulationChange, + LegacyUnsorted, + LegacySorted, + Withdrawn, +} + +async fn statistical_successor_release_impact(scenario: StatisticalSuccessor) { use registry_breg::migration::{ - apply_verified_package, ActivationDeployment, ApplyPrecondition, ApplyRoles, ApplyTimeouts, - ApplyVerifiedPackageRequest, + apply_verified_package, plan_verified_package, ActivationDeployment, ApplyPrecondition, + ApplyRoles, ApplyTimeouts, ApplyVerifiedPackageRequest, }; use registry_breg::package::{ - load_package, prepare_package, PackageBuildRequest, PackageLoadContext, - PackageMigrationPlanInput, PackageSourceFile, + load_package, load_predecessor_package, prepare_historical_statistics_package_for_test, + prepare_package, PackageBuildRequest, PackageLoadContext, PackageMigrationPlanInput, + PackageSourceFile, }; use registry_breg::postgres::managed_schema_fingerprint; + let legacy_order = scenario != StatisticalSuccessor::PopulationChange; let database = TestDatabase::create(4).await; let mut source = statistics_registry_source(); source["package"] = json!({"sourceRevision":"statistics-definition-test"}); - let prior = compile_statistics_registry(source.clone()); + if legacy_order { + source["recordTypes"]["record"]["fields"] + .as_array_mut() + .unwrap() + .push(json!({ + "id": "owner", "type": "reference", "target": "record", "classification": "internal" + })); + for profile in ["analyst", "analyst-wide", "publisher"] { + source["accessProfiles"][profile]["permissions"]["records"][0]["readableFields"] + .as_array_mut() + .unwrap() + .push(json!("owner")); + } + source["statisticalDatasets"]["records-by-category"]["measures"] = json!({ + "parcels": {"type":"count"}, + "owners": {"type":"distinct-count", "field":"owner"} + }); + } + let schema = compile_statistics_registry(source.clone()); let (mut migration, task) = database.connect_migration().await; let transaction = migration.transaction().await.unwrap(); - install_compiled_schema(&transaction, &prior, &database.runtime_role) + install_compiled_schema(&transaction, &schema, &database.runtime_role) .await .unwrap(); let fingerprint = managed_schema_fingerprint( &transaction, &database.runtime_role, - &ExpectedManagedCatalog::compiled(&prior), + &ExpectedManagedCatalog::compiled(&schema), ) .await .unwrap(); transaction.rollback().await.unwrap(); task.abort(); let make_package = |source: &Value, from: Option<&str>, plan| { - let prepared = prepare_package(PackageBuildRequest { + let legacy = source["statisticalDatasets"]["records-by-category"] + .get("unit") + .is_some(); + let prepare = if legacy { + prepare_historical_statistics_package_for_test + } else { + prepare_package + }; + let prepared = prepare(PackageBuildRequest { from_package_digest: from.map(str::to_owned), compiler_source_revision: "statistics-definition-test".to_owned(), schema_fingerprint: fingerprint.clone(), @@ -4486,30 +4541,60 @@ journeys: let root = tempfile::tempdir().unwrap(); let path = root.path().canonicalize().unwrap().join("package"); prepared.publish_to_directory(&path).unwrap(); - load_package( - &path, - &PackageLoadContext { - posture: registry_platform_config::Posture::Development, - }, - ) - .unwrap() + let context = PackageLoadContext { + posture: registry_platform_config::Posture::Development, + }; + let verified = load_package(&path, &context).unwrap(); + if legacy { + let predecessor = load_predecessor_package(&path, &context).unwrap(); + assert_eq!( + predecessor.migration_baseline().statistical_datasets["records-by-category"] + .definition_digest, + verified.registry().statistical_datasets()["records-by-category"].definition_digest, + ); + } + verified }; - let initial = make_package(&source, None, PackageMigrationPlanInput::InitialCompiledDdl); - let audit = database.activation_audit(); - let request = |package, precondition| { - ApplyVerifiedPackageRequest::new( + let mut initial_source = source.clone(); + if legacy_order { + let dataset = initial_source["statisticalDatasets"]["records-by-category"] + .as_object_mut() + .unwrap(); + let unit = dataset.remove("recordType").unwrap(); + dataset.insert("unit".to_owned(), unit); + let mut measures = vec![ + json!({"id":"owners", "type":"distinct-count", "field":"owner"}), + json!({"id":"parcels", "type":"count"}), + ]; + if scenario != StatisticalSuccessor::LegacySorted { + measures.reverse(); + } + dataset.insert("measures".to_owned(), json!(measures)); + } + let initial = make_package( + &initial_source, + None, + PackageMigrationPlanInput::InitialCompiledDdl, + ); + let prior = initial.registry().clone(); + async fn apply( + database: &TestDatabase, + package: ®istry_breg::package::VerifiedPackage, + precondition: ApplyPrecondition<'_>, + ) -> registry_breg::postgres::ExpectedRegistryIdentity { + apply_verified_package(ApplyVerifiedPackageRequest::new( &database.migration_config, package, ActivationDeployment::new("local", "statistics-definition-test", DATABASE_ID), precondition, ApplyRoles::new(&database.migration_role, &database.runtime_role), ApplyTimeouts::new(Duration::from_secs(5), Duration::from_secs(5)).unwrap(), - audit.clone(), - ) - }; - let active = apply_verified_package(request(&initial, ApplyPrecondition::InitialActivation)) + database.activation_audit(), + )) .await - .expect("initial statistical package applies"); + .expect("statistics package applies") + } + let active = apply(&database, &initial, ApplyPrecondition::InitialActivation).await; let pool = database.runtime_config.build_pool().unwrap(); let lock_key = RegistryLockKey::derive(PACKAGE_ID) .unwrap() @@ -4534,6 +4619,48 @@ journeys: None, ) }; + async fn plan_for( + database: &TestDatabase, + package: ®istry_breg::package::VerifiedPackage, + current: ®istry_breg::postgres::ExpectedRegistryIdentity, + ) -> registry_breg::migration::ActivationPlan { + plan_verified_package(ApplyVerifiedPackageRequest::plan( + &database.migration_config, + package, + ActivationDeployment::new("local", "statistics-definition-test", DATABASE_ID), + ApplyPrecondition::Successor { current }, + ApplyRoles::new(&database.migration_role, &database.runtime_role), + ApplyTimeouts::new(Duration::from_secs(5), Duration::from_secs(5)).unwrap(), + )) + .await + .expect("statistics successor plans") + } + let successor_for = + |source: &Value, current: ®istry_breg::postgres::ExpectedRegistryIdentity, prior| { + make_package( + source, + Some(¤t.package_digest), + PackageMigrationPlanInput::Successor { + prior_registry: Box::new(prior), + }, + ) + }; + let mut changed_source = source.clone(); + if !legacy_order { + changed_source["statisticalDatasets"]["records-by-category"]["population"] = + json!("active eq false"); + } + if scenario == StatisticalSuccessor::LegacySorted { + // Make the successor an observable metadata change while keeping its definition. + changed_source["statisticalDatasets"]["records-by-category"]["display"] = + json!({"label":"Records by category"}); + } + let empty_series = successor_for(&changed_source, &active, prior.clone()); + assert!(plan_for(&database, &empty_series, &active) + .await + .statistical_release_impacts + .is_empty()); + let app = make_app(Arc::new(prior.clone()), active.clone()); let old = publish( &app, @@ -4554,25 +4681,135 @@ journeys: .await .unwrap() .get(0); - source["statisticalDatasets"]["records-by-category"]["population"] = json!("active eq false"); - let candidate = compile_statistics_registry(source.clone()); - assert_ne!( - prior.statistical_datasets()["records-by-category"].definition_digest, + let (active, app, presentation) = if legacy_order { + assert_eq!( + prior.statistical_datasets()["records-by-category"].measures[0].id(), + if scenario == StatisticalSuccessor::LegacySorted { + "owners" + } else { + "parcels" + } + ); + (active, app, prior.clone()) + } else { + source["statisticalDatasets"]["records-by-category"]["measures"] = + json!({"count": {"type":"count", "display":{"label":"Records"}}}); + source["statisticalDatasets"]["records-by-category"]["display"] = + json!({"label":"Records by category"}); + let presentation = compile_statistics_registry(source.clone()); + let display_successor = successor_for(&source, &active, prior.clone()); + assert!(plan_for(&database, &display_successor, &active) + .await + .statistical_release_impacts + .is_empty()); + let active = apply( + &database, + &display_successor, + ApplyPrecondition::Successor { current: &active }, + ) + .await; + let app = make_app(Arc::new(presentation.clone()), active.clone()); + let metadata = send( + &app, + Method::GET, + "/v1/registry?accessProfile=reader", + Some(claims("reader", false)), + &[], + Vec::new(), + ) + .await; + assert_eq!(metadata.status(), StatusCode::OK); + let metadata = body_json(metadata).await; + let dataset = &metadata["statisticalDatasets"][0]; + assert_eq!(dataset["display"]["label"], "Records by category"); + assert_eq!(dataset["measures"][0]["display"]["label"], "Records"); + assert!(metadata["recordTypes"].as_array().unwrap().is_empty()); + let denied = send( + &app, + Method::GET, + "/v1/registry?accessProfile=seed", + Some(claims("seed", false)), + &[], + Vec::new(), + ) + .await; + assert_eq!(denied.status(), StatusCode::NOT_FOUND); + changed_source["statisticalDatasets"]["records-by-category"]["display"] = + source["statisticalDatasets"]["records-by-category"]["display"].clone(); + changed_source["statisticalDatasets"]["records-by-category"]["measures"] = + source["statisticalDatasets"]["records-by-category"]["measures"].clone(); + (active, app, presentation) + }; + let candidate = compile_statistics_registry(changed_source.clone()); + let candidate_digest = + &candidate.statistical_datasets()["records-by-category"].definition_digest; + let successor = successor_for(&changed_source, &active, presentation); + if scenario == StatisticalSuccessor::Withdrawn { + assert_ne!(old["definitionDigest"], *candidate_digest); + let withdrawal = withdraw( + &app, + &period, + 1, + "withdraw-before-plan", + claims("publisher", false), + ) + .await; + assert_eq!(withdrawal.status(), StatusCode::OK); + let withdrawn = send( + &app, + Method::GET, + &format!("/v1/statistics/records-by-category/releases/{period}/versions/1?accessProfile=reader"), + Some(claims("reader", false)), + &[], + Vec::new(), + ).await; + assert_eq!(withdrawn.status(), StatusCode::GONE); + assert!(plan_for(&database, &successor, &active) + .await + .statistical_release_impacts + .is_empty()); + drop(app); + drop(pool); + database.cleanup().await; + return; + } + let plan = plan_for(&database, &successor, &active).await; + if scenario == StatisticalSuccessor::LegacySorted { + assert_eq!(old["definitionDigest"], *candidate_digest); + assert!(plan.statistical_release_impacts.is_empty()); + let next = apply( + &database, + &successor, + ApplyPrecondition::Successor { current: &active }, + ) + .await; + assert_ne!(next.activation_id, active.activation_id); + let successor_app = make_app(Arc::new(candidate), next); + assert_release_bytes(&successor_app, &period, &old_bytes).await; + drop(successor_app); + drop(app); + drop(pool); + database.cleanup().await; + return; + } + assert_ne!(old["definitionDigest"], *candidate_digest); + let [impact] = plan.statistical_release_impacts.as_slice() else { + panic!("one retained series should be affected: {plan:?}"); + }; + assert_eq!(impact.dataset_id, "records-by-category"); + assert_eq!(impact.old_definition_digest, old["definitionDigest"]); + assert_eq!( + impact.candidate_definition_digest, candidate.statistical_datasets()["records-by-category"].definition_digest ); - let successor = make_package( - &source, - Some(&active.package_digest), - PackageMigrationPlanInput::Successor { - prior_registry: Box::new(prior), - }, - ); - let next = apply_verified_package(request( + + assert_release_bytes(&app, &period, &old_bytes).await; + let next = apply( + &database, &successor, ApplyPrecondition::Successor { current: &active }, - )) - .await - .expect("definition-only successor applies through the maintained coordinator"); + ) + .await; assert_ne!(next.activation_id, active.activation_id); let app = make_app(Arc::new(candidate), next); let hidden = send( @@ -4631,6 +4868,24 @@ journeys: database.cleanup().await; } +async fn assert_release_bytes(app: &axum::Router, period: &str, old_bytes: &[u8]) { + for suffix in ["/versions/1", ""] { + let response = send( + app, + Method::GET, + &format!( + "/v1/statistics/records-by-category/releases/{period}{suffix}?accessProfile=reader" + ), + Some(claims("reader", false)), + &[], + Vec::new(), + ) + .await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(body_bytes(response).await, old_bytes); + } +} + /// A fixture of the default dataset for the dry run: the database, the router and /// the prior (ended) period with seven records, six in `a` and one in `b`. async fn dry_run_fixture(source: Value, label: &str) -> (TestDatabase, axum::Router, String) { @@ -4881,7 +5136,7 @@ fn statistics_registry_source() -> Value { }} }, "vocabularies":{"category": {"values":["a","b"]}, "jurisdiction": {"values":["north","south"]}}, - "statisticalDatasets":{"records-by-category": {"unit":"record","population":"active eq true", + "statisticalDatasets":{"records-by-category": {"recordType":"record","population":"active eq true", "period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"}, "dimensions":["category"],"disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5} }} @@ -4925,7 +5180,7 @@ fn cap_registry() -> registry_breg::CompiledRegistry { }} }, "vocabularies":{"category": {"values":codes}}, - "statisticalDatasets":{"daily-by-category": {"unit":"record","population":"active eq true", + "statisticalDatasets":{"daily-by-category": {"recordType":"record","population":"active eq true", "period":{"type":"flow","field":"event-date","granularity":"day","firstPeriod":"2025-01-01"}, "dimensions":["category"],"disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5} }} diff --git a/crates/registry-breg/tests/postgres_statistics_load.rs b/crates/registry-breg/tests/postgres_statistics_load.rs index 4c80465932..2bf3f9ee6a 100644 --- a/crates/registry-breg/tests/postgres_statistics_load.rs +++ b/crates/registry-breg/tests/postgres_statistics_load.rs @@ -61,7 +61,7 @@ async fn million_unit_three_dimension_statistics_measurement() { {"dataset":"units-by-category","operations":["read-releases"]} ] }}}, - "statisticalDatasets":{"units-by-category": {"unit":"unit","population":"active ne null", + "statisticalDatasets":{"units-by-category": {"recordType":"unit","population":"active ne null", "period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"}, "dimensions":["active","category","region"], "disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5}}} diff --git a/crates/registry-breg/tests/postgres_statistics_measures.rs b/crates/registry-breg/tests/postgres_statistics_measures.rs index ccd01f3284..e9be454922 100644 --- a/crates/registry-breg/tests/postgres_statistics_measures.rs +++ b/crates/registry-breg/tests/postgres_statistics_measures.rs @@ -7,6 +7,10 @@ #[allow(dead_code)] mod postgres_harness; +#[path = "support/source_bytes.rs"] +#[allow(dead_code)] +mod source_bytes; + use std::sync::Arc; use std::time::Duration; @@ -159,9 +163,9 @@ async fn a_sum_and_mean_are_served_as_decimal_strings_in_json_and_csv() { assert_eq!( document["dataset"]["measures"], json!([ - {"id":"records","type":"count"}, {"id":"amount-sum","type":"sum","field":"amount","scale":2}, - {"id":"quantity-mean","type":"mean","field":"quantity","scale":1} + {"id":"quantity-mean","type":"mean","field":"quantity","scale":1}, + {"id":"records","type":"count"} ]) ); let a_count = &document["cells"] @@ -658,9 +662,9 @@ fn registry_source(dimensions: &[&str], measures: Value) -> Value { }]}} }, "vocabularies":{"category": {"values":["a","b","c"]}}, - "statisticalDatasets":{"records-by-category": {"unit":"record","population":"active eq true", + "statisticalDatasets":{"records-by-category": {"recordType":"record","population":"active eq true", "period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"}, - "dimensions":dimensions,"measures":measures, + "dimensions":dimensions,"measures":source_bytes::keyed_measures(measures), "disclosure":{"type":"minimum-count-and-rounding","minimumCount":5,"roundingBase":5} }} }) diff --git a/crates/registry-breg/tests/postgres_statistics_protected_sums.rs b/crates/registry-breg/tests/postgres_statistics_protected_sums.rs index 5cab2a8bdd..74916557be 100644 --- a/crates/registry-breg/tests/postgres_statistics_protected_sums.rs +++ b/crates/registry-breg/tests/postgres_statistics_protected_sums.rs @@ -598,14 +598,14 @@ fn source() -> Value { "datasets":[{"dataset":DATASET,"operations":["read-releases"]}]}} }, "vocabularies":{"district": {"values":["d1","d2"]}, "category": {"values":["a","b","c"]}}, - "statisticalDatasets":{(DATASET): {"unit":"record","population":"active eq true", + "statisticalDatasets":{(DATASET): {"recordType":"record","population":"active eq true", "period":{"type":"flow","field":"event-date","granularity":"month","firstPeriod":"2025-01"}, "dimensions":["district","category"], - "measures":[ - {"id":"parcels","type":"count"}, - {"id":"area-sum","type":"sum","field":"area"}, - {"id":"units-sum","type":"sum","field":"units"} - ], + "measures":{ + "parcels": {"type":"count"}, + "area-sum": {"type":"sum","field":"area"}, + "units-sum": {"type":"sum","field":"units"} + }, "disclosure":{"type":"exact-public-values"} }} }) diff --git a/crates/registry-breg/tests/postgres_statistics_stock.rs b/crates/registry-breg/tests/postgres_statistics_stock.rs index 1a630d92c9..c87ecdb4ee 100644 --- a/crates/registry-breg/tests/postgres_statistics_stock.rs +++ b/crates/registry-breg/tests/postgres_statistics_stock.rs @@ -618,11 +618,11 @@ fn last_day_registry() -> registry_breg::CompiledRegistry { ]} }}, "vocabularies":{"administrative-boundary": {"values":["north-district","south-district"]}}, - "statisticalDatasets":{"permits-in-force-temporal": {"unit":"permit","population":"validFrom ne null", + "statisticalDatasets":{"permits-in-force-temporal": {"recordType":"permit","population":"validFrom ne null", "period":{"type":"stock","granularity":"month","firstPeriod":"2025-01","validity":"temporal"}, "dimensions":["administrative-boundary"], "disclosure":{"type":"minimum-count-and-rounding","minimumCount":2,"roundingBase":2} - }, "permits-in-force-fields": {"unit":"permit","population":"validFrom ne null", + }, "permits-in-force-fields": {"recordType":"permit","population":"validFrom ne null", "period":{"type":"stock","granularity":"month","firstPeriod":"2025-01", "validity":{"from":"valid-from","until":"valid-through"}}, "dimensions":["administrative-boundary"], @@ -670,7 +670,7 @@ fn twelve_dimension_registry() -> registry_breg::CompiledRegistry { }],"datasets":[{"dataset":"permits-by-twelve-dimensions","operations":["read-live"]}]} }}, "vocabularies":vocabularies, - "statisticalDatasets":{"permits-by-twelve-dimensions": {"unit":"permit","population":"validFrom ne null", + "statisticalDatasets":{"permits-by-twelve-dimensions": {"recordType":"permit","population":"validFrom ne null", "period":{"type":"flow","field":"valid-from","granularity":"month","firstPeriod":"2025-01"}, "dimensions":dimension_ids, "disclosure":{"type":"minimum-count-and-rounding","minimumCount":2,"roundingBase":2} @@ -706,7 +706,7 @@ fn cube_registry() -> registry_breg::CompiledRegistry { }],"datasets":[{"dataset":"permits-by-type-and-region","operations":["read-live"]}]} }}, "vocabularies":{"permit-type": {"values":["air","water"]}, "region": {"values":["north","south"]}}, - "statisticalDatasets":{"permits-by-type-and-region": {"unit":"permit","population":"validFrom ne null", + "statisticalDatasets":{"permits-by-type-and-region": {"recordType":"permit","population":"validFrom ne null", "period":{"type":"flow","field":"valid-from","granularity":"month","firstPeriod":"2025-01"}, "dimensions":["permit-type","region"], "disclosure":{"type":"minimum-count-and-rounding","minimumCount":2,"roundingBase":2} @@ -742,7 +742,7 @@ fn partial_text_registry() -> registry_breg::CompiledRegistry { }],"datasets":[{"dataset":"monthly-air-permits","operations":["read-live"]}]} }}, "vocabularies":{"permit-type": {"values":["air-emissions","water-discharge"]}, "administrative-boundary": {"values":["north-district","south-district"]}}, - "statisticalDatasets":{"monthly-air-permits": {"unit":"permit","population":"startswith(permitType,'a')", + "statisticalDatasets":{"monthly-air-permits": {"recordType":"permit","population":"startswith(permitType,'a')", "period":{"type":"flow","field":"valid-from","granularity":"month","firstPeriod":"2025-01"}, "dimensions":["administrative-boundary"], "disclosure":{"type":"minimum-count-and-rounding","minimumCount":2,"roundingBase":2} diff --git a/crates/registry-breg/tests/project_collections_map.rs b/crates/registry-breg/tests/project_collections_map.rs index 232fff585c..fa74eedc18 100644 --- a/crates/registry-breg/tests/project_collections_map.rs +++ b/crates/registry-breg/tests/project_collections_map.rs @@ -25,7 +25,7 @@ const COLLECTIONS: [(&str, &str); 8] = [ ("reviewAuthorities", "{protocol: id.registrystack.org/protocols/review/v1}"), ( "statisticalDatasets", - "{unit: entry, population: active eq true, period: {type: flow, field: recorded-on, granularity: month, firstPeriod: 2025-01}, dimensions: [active]}", + "{recordType: entry, population: active eq true, period: {type: flow, field: recorded-on, granularity: month, firstPeriod: 2025-01}, dimensions: [active]}", ), ( "evidenceProviders", diff --git a/crates/registry-breg/tests/standing_agent_ceiling.rs b/crates/registry-breg/tests/standing_agent_ceiling.rs index 1cd0ca8b19..199eb2866b 100644 --- a/crates/registry-breg/tests/standing_agent_ceiling.rs +++ b/crates/registry-breg/tests/standing_agent_ceiling.rs @@ -450,7 +450,7 @@ fn with_dataset(clerk: &[&str], assistant: &[&str]) -> Value { json!({"id": "filed", "type": "date", "required": true, "classification": "internal"}), ]); value["project"]["timezone"] = json!("UTC"); - value["statisticalDatasets"] = json!({"notes-by-status": {"unit": "note", "population": "open eq true", + value["statisticalDatasets"] = json!({"notes-by-status": {"recordType": "note", "population": "open eq true", "period": {"type": "flow", "field": "filed", "granularity": "month", "firstPeriod": "2025-01"}, "dimensions": ["open"], "disclosure": {"type":"minimum-count-and-rounding","minimumCount": 5, "roundingBase": 5} diff --git a/crates/registry-breg/tests/support/source_bytes.rs b/crates/registry-breg/tests/support/source_bytes.rs index eb54b02b78..19dbaaacf9 100644 --- a/crates/registry-breg/tests/support/source_bytes.rs +++ b/crates/registry-breg/tests/support/source_bytes.rs @@ -25,3 +25,20 @@ fn drop_null_members(value: &mut Value) { _ => {} } } + +/// Convert a list of test measure variants into the authored keyed collection. +#[allow(dead_code)] +pub fn keyed_measures(measures: serde_json::Value) -> serde_json::Value { + use serde_json::Value; + let Value::Array(items) = measures else { + return measures; + }; + let mut keyed = serde_json::Map::new(); + for mut item in items { + let id = item.as_object_mut().unwrap().remove("id").unwrap(); + assert!(keyed + .insert(id.as_str().unwrap().to_owned(), item) + .is_none()); + } + Value::Object(keyed) +} diff --git a/crates/registry-bregctl/src/apply_lifecycle.rs b/crates/registry-bregctl/src/apply_lifecycle.rs index 3f4b12cecc..5b30934cf9 100644 --- a/crates/registry-bregctl/src/apply_lifecycle.rs +++ b/crates/registry-bregctl/src/apply_lifecycle.rs @@ -125,7 +125,7 @@ pub(crate) fn plan( }, LifecycleMode::Plan, )? { - Executed::Planned(outcome) => Ok(outcome), + Executed::Planned(outcome) => Ok(*outcome), Executed::Applied(_) => Err(ApplyLifecycleError::Apply(MigrationError::ApplyFailed)), } } @@ -154,7 +154,7 @@ pub(crate) fn status( enum Executed { Applied(ApplyLifecycleOutcome), - Planned(PlanLifecycleOutcome), + Planned(Box), } struct DatabaseAccess { @@ -477,14 +477,14 @@ fn execute( let migration = target .migration_summary() .map_err(ApplyLifecycleError::TargetPackage)?; - return Ok(Executed::Planned(PlanLifecycleOutcome { + return Ok(Executed::Planned(Box::new(PlanLifecycleOutcome { diagnostics, package_digest: target.package_digest().to_owned(), registry_revision: target.registry().revision().to_owned(), active_package_digest: current_identity.map(|current| current.package_digest), plan, migration, - })); + }))); } let activated = runtime .block_on(apply_verified_package(apply)) diff --git a/crates/registry-bregctl/src/lib.rs b/crates/registry-bregctl/src/lib.rs index f062552c12..2c3b1ed270 100644 --- a/crates/registry-bregctl/src/lib.rs +++ b/crates/registry-bregctl/src/lib.rs @@ -2576,6 +2576,7 @@ struct PlanSuccessReport { checks: &'static [&'static str], migration: MigrationInspectionSummary, timer_previews: Vec, + statistical_release_impacts: Vec, } /// The activation `bregctl apply` would report, or `none` when the package is @@ -7296,6 +7297,7 @@ fn plan(posture: DeclaredPosture, args: &PlanArgs) -> Result