Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
}];
Expand Down
19 changes: 19 additions & 0 deletions crates/registry-breg-client-node/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,13 +194,32 @@ export interface BRegStatisticalDimensionDescriptor {
readonly codes: ReadonlyArray<string>
}

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
readonly periodKind: 'flow' | 'stock'
readonly granularity: 'day' | 'month' | 'quarter' | 'year'
readonly firstPeriod: string
readonly dimensions: ReadonlyArray<BRegStatisticalDimensionDescriptor>
readonly measures?: ReadonlyArray<BRegStatisticalMeasureDescriptor>
readonly display?: BRegStatisticalDisplay
readonly definitionDigest: string
readonly operations: ReadonlyArray<
| 'read-live'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,61 @@ 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
periodKind: Literal["flow", "stock"]
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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
149 changes: 143 additions & 6 deletions crates/registry-breg-client/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
pub description: Option<String>,
}

/// 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<BRegStatisticalDisplay>,
#[serde(flatten)]
pub measure: BRegStatisticalMeasure,
}

#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize)]
pub struct BRegStatisticalDimensionDescriptor {
pub field: String,
pub vocabulary: String,
pub codes: Vec<String>,
}

/// 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<BRegStatisticalDimensionDescriptor>,
pub definition_digest: String,
pub operations: Vec<String>,
pub measures: Option<Vec<BRegStatisticalMeasureDescriptor>>,
pub display: Option<BRegStatisticalDisplay>,
}

/// Validated Base Registry Engine runtime metadata v2 for one caller projection.
#[derive(Clone, PartialEq)]
pub struct BRegMetadata {
Expand All @@ -1250,6 +1317,7 @@ pub struct BRegMetadata {
operations: Vec<BRegMetadataOperation>,
action_metadata: Option<Value>,
statistical_datasets: Option<Value>,
statistical_dataset_descriptors: Option<Vec<BRegStatisticalDatasetDescriptor>>,
proposals: Option<Value>,
proposal_actions: Vec<BRegProposalActionDescriptor>,
actions: Vec<BRegActionDescriptor>,
Expand Down Expand Up @@ -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] {
Expand Down Expand Up @@ -2728,10 +2801,14 @@ fn parse_metadata(value: Value) -> Result<BRegMetadata, BRegMetadataError> {
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()))
Expand All @@ -2752,16 +2829,20 @@ fn parse_metadata(value: Value) -> Result<BRegMetadata, BRegMetadataError> {
operations,
action_metadata,
statistical_datasets,
statistical_dataset_descriptors,
proposals,
proposal_actions,
actions,
source_binding: None,
})
}

fn parse_statistical_datasets(value: Value) -> Result<Value, BRegMetadataError> {
fn parse_statistical_datasets(
value: Value,
) -> Result<(Value, Vec<BRegStatisticalDatasetDescriptor>), 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)?;
Expand Down Expand Up @@ -2829,12 +2910,68 @@ fn parse_statistical_datasets(value: Value) -> Result<Value, BRegMetadataError>
}) {
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 {
Expand Down
41 changes: 41 additions & 0 deletions crates/registry-breg-client/src/metadata_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down
Loading