From 6d3330d0f030306c387ab3ed93a5dfc8a3d4a426 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Thu, 12 Nov 2026 06:44:53 -0500
Subject: [PATCH 1/6] feat(reporting): read a flattened value-object member in
@of, never mixing its units (FR-044 R12)
A dimension's or aggregate measure's @of may name Entity.field.member, a member
of a value object stored with @storage: flattened. The report reads the member's
own column (amount_amount, amount_currency). A report that sums, averages or
takes the min or max of a numeric member must group by every non-numeric member
of the same value object, so amounts in different currencies are never combined.
jsonb members, unknown members and deeper paths are refused at load. The Cube
exporter refuses member references.
Loader rules and report-shape derivation in TypeScript, C#, Java and Python,
with shared conformance fixtures for the positive case and each refusal.
---
.../expected-errors.json | 15 ++
.../input/meta.billing.json | 79 ++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 ++
.../input/meta.billing.json | 80 ++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 ++
.../input/meta.billing.json | 80 ++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 ++
.../input/meta.billing.json | 80 ++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 ++
.../input/meta.billing.json | 80 ++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 ++
.../input/meta.billing.json | 98 ++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 ++
.../input/meta.billing.json | 112 +++++++++++
.../providers.json | 1 +
.../expected.json | 185 ++++++++++++++++++
.../input/meta.billing.json | 177 +++++++++++++++++
.../providers.json | 1 +
.../expected-registry.json | 6 +-
.../ReportShapeTests.cs | 16 ++
.../MetaObjects/Core/Reporting/ReportShape.cs | 26 ++-
.../Loader/ValidationPasses.Reporting.cs | 129 ++++++++++--
.../loader/ReportingValidation.java | 129 ++++++++++--
.../metaobjects/reporting/ReportShape.java | 47 ++++-
.../reporting/ReportShapeTest.java | 18 ++
.../metaobjects/loader/validate_reporting.py | 134 +++++++++++--
.../meta/core/reporting/report_shape.py | 35 +++-
server/python/tests/test_report_shape.py | 22 +++
.../codegen-ts/src/cube/build-cube-model.ts | 17 +-
.../codegen-ts/src/cube/cube-errors.ts | 3 +
.../codegen-ts/src/cube/cube-members.ts | 21 +-
.../src/projection/extract-report-spec.ts | 16 +-
.../src/projection/report-resolve.ts | 42 +++-
.../report-value-object-members.test.ts | 48 +++++
.../src/core/reporting/report-shape.ts | 60 +++++-
.../reporting-definition.embedded.ts | 6 +-
.../typescript/packages/metadata/src/index.ts | 3 +
.../src/loader/reporting-validation.ts | 142 ++++++++++++--
spec/metamodel/reporting.json | 6 +-
45 files changed, 1886 insertions(+), 124 deletions(-)
create mode 100644 fixtures/conformance/error-dimension-of-jsonb-member/expected-errors.json
create mode 100644 fixtures/conformance/error-dimension-of-jsonb-member/input/meta.billing.json
create mode 100644 fixtures/conformance/error-dimension-of-jsonb-member/providers.json
create mode 100644 fixtures/conformance/error-measure-of-jsonb-member/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-of-jsonb-member/input/meta.billing.json
create mode 100644 fixtures/conformance/error-measure-of-jsonb-member/providers.json
create mode 100644 fixtures/conformance/error-measure-of-member-of-scalar/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-of-member-of-scalar/input/meta.billing.json
create mode 100644 fixtures/conformance/error-measure-of-member-of-scalar/providers.json
create mode 100644 fixtures/conformance/error-measure-of-path-too-deep/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-of-path-too-deep/input/meta.billing.json
create mode 100644 fixtures/conformance/error-measure-of-path-too-deep/providers.json
create mode 100644 fixtures/conformance/error-measure-of-unknown-member/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-of-unknown-member/input/meta.billing.json
create mode 100644 fixtures/conformance/error-measure-of-unknown-member/providers.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-not-grouped/expected-errors.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-not-grouped/input/meta.billing.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-ratio-operand/expected-errors.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-ratio-operand/input/meta.billing.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json
create mode 100644 fixtures/conformance/reporting-value-object-members/expected.json
create mode 100644 fixtures/conformance/reporting-value-object-members/input/meta.billing.json
create mode 100644 fixtures/conformance/reporting-value-object-members/providers.json
create mode 100644 server/typescript/packages/codegen-ts/test/projection/report-value-object-members.test.ts
diff --git a/fixtures/conformance/error-dimension-of-jsonb-member/expected-errors.json b/fixtures/conformance/error-dimension-of-jsonb-member/expected-errors.json
new file mode 100644
index 0000000000..b49cf6b836
--- /dev/null
+++ b/fixtures/conformance/error-dimension-of-jsonb-member/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_DIMENSION",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.billing.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[6]['dimension.attribute']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-dimension-of-jsonb-member/input/meta.billing.json b/fixtures/conformance/error-dimension-of-jsonb-member/input/meta.billing.json
new file mode 100644
index 0000000000..8433818f46
--- /dev/null
+++ b/fixtures/conformance/error-dimension-of-jsonb-member/input/meta.billing.json
@@ -0,0 +1,79 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "jsonb",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "currency",
+ "@of": "Payment.amount.currency"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-dimension-of-jsonb-member/providers.json b/fixtures/conformance/error-dimension-of-jsonb-member/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-dimension-of-jsonb-member/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-of-jsonb-member/expected-errors.json b/fixtures/conformance/error-measure-of-jsonb-member/expected-errors.json
new file mode 100644
index 0000000000..498d304bd3
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-jsonb-member/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.billing.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[6]['measure.aggregate']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-of-jsonb-member/input/meta.billing.json b/fixtures/conformance/error-measure-of-jsonb-member/input/meta.billing.json
new file mode 100644
index 0000000000..3d6de959f8
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-jsonb-member/input/meta.billing.json
@@ -0,0 +1,80 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "jsonb",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "revenue",
+ "@agg": "sum",
+ "@of": "Payment.amount.amount"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-of-jsonb-member/providers.json b/fixtures/conformance/error-measure-of-jsonb-member/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-jsonb-member/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-of-member-of-scalar/expected-errors.json b/fixtures/conformance/error-measure-of-member-of-scalar/expected-errors.json
new file mode 100644
index 0000000000..498d304bd3
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-member-of-scalar/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.billing.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[6]['measure.aggregate']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-of-member-of-scalar/input/meta.billing.json b/fixtures/conformance/error-measure-of-member-of-scalar/input/meta.billing.json
new file mode 100644
index 0000000000..83608fb0a3
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-member-of-scalar/input/meta.billing.json
@@ -0,0 +1,80 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "flattened",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "kinds",
+ "@agg": "count",
+ "@of": "Payment.kind.length"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-of-member-of-scalar/providers.json b/fixtures/conformance/error-measure-of-member-of-scalar/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-member-of-scalar/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-of-path-too-deep/expected-errors.json b/fixtures/conformance/error-measure-of-path-too-deep/expected-errors.json
new file mode 100644
index 0000000000..498d304bd3
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-path-too-deep/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.billing.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[6]['measure.aggregate']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-of-path-too-deep/input/meta.billing.json b/fixtures/conformance/error-measure-of-path-too-deep/input/meta.billing.json
new file mode 100644
index 0000000000..76d777edfb
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-path-too-deep/input/meta.billing.json
@@ -0,0 +1,80 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "flattened",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "revenue",
+ "@agg": "sum",
+ "@of": "Payment.amount.amount.value"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-of-path-too-deep/providers.json b/fixtures/conformance/error-measure-of-path-too-deep/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-path-too-deep/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-of-unknown-member/expected-errors.json b/fixtures/conformance/error-measure-of-unknown-member/expected-errors.json
new file mode 100644
index 0000000000..498d304bd3
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-unknown-member/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.billing.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[1]['object.entity'].children[6]['measure.aggregate']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-of-unknown-member/input/meta.billing.json b/fixtures/conformance/error-measure-of-unknown-member/input/meta.billing.json
new file mode 100644
index 0000000000..f7b05b143e
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-unknown-member/input/meta.billing.json
@@ -0,0 +1,80 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "flattened",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "revenue",
+ "@agg": "sum",
+ "@of": "Payment.amount.total"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-of-unknown-member/providers.json b/fixtures/conformance/error-measure-of-unknown-member/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-of-unknown-member/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-report-value-object-unit-not-grouped/expected-errors.json b/fixtures/conformance/error-report-value-object-unit-not-grouped/expected-errors.json
new file mode 100644
index 0000000000..83482e8c01
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-not-grouped/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_REPORT",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.billing.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.report']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-report-value-object-unit-not-grouped/input/meta.billing.json b/fixtures/conformance/error-report-value-object-unit-not-grouped/input/meta.billing.json
new file mode 100644
index 0000000000..5c6646939c
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-not-grouped/input/meta.billing.json
@@ -0,0 +1,98 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "flattened",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "revenue",
+ "@agg": "sum",
+ "@of": "Payment.amount.amount"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "Revenue",
+ "@from": "Payment",
+ "@dimensions": [],
+ "@measures": [
+ "revenue"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_revenue"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json b/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-not-grouped/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-report-value-object-unit-ratio-operand/expected-errors.json b/fixtures/conformance/error-report-value-object-unit-ratio-operand/expected-errors.json
new file mode 100644
index 0000000000..83482e8c01
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-ratio-operand/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_REPORT",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.billing.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.report']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-report-value-object-unit-ratio-operand/input/meta.billing.json b/fixtures/conformance/error-report-value-object-unit-ratio-operand/input/meta.billing.json
new file mode 100644
index 0000000000..3d757e6f8f
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-ratio-operand/input/meta.billing.json
@@ -0,0 +1,112 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "flattened",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "revenue",
+ "@agg": "sum",
+ "@of": "Payment.amount.amount"
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "payments",
+ "@agg": "count",
+ "@of": "Payment.id"
+ }
+ },
+ {
+ "measure.ratio": {
+ "name": "averagePayment",
+ "@numerator": "revenue",
+ "@denominator": "payments"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "AveragePayment",
+ "@from": "Payment",
+ "@dimensions": [],
+ "@measures": [
+ "averagePayment"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_averagepayment"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json b/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-ratio-operand/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/reporting-value-object-members/expected.json b/fixtures/conformance/reporting-value-object-members/expected.json
new file mode 100644
index 0000000000..43e492f392
--- /dev/null
+++ b/fixtures/conformance/reporting-value-object-members/expected.json
@@ -0,0 +1,185 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@precision": 12,
+ "@required": true,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@maxLength": 3,
+ "@required": true
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "acme::billing::Money",
+ "@required": true,
+ "@storage": "flattened"
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "currency",
+ "@of": "acme::billing::Payment.amount.currency"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "kind",
+ "@of": "acme::billing::Payment.kind"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "receivedOn",
+ "@grains": [
+ "month"
+ ],
+ "@of": "acme::billing::Payment.receivedOn"
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "revenue",
+ "@agg": "sum",
+ "@of": [
+ "acme::billing::Payment.amount.amount"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "largest",
+ "@agg": "max",
+ "@default": 0,
+ "@of": [
+ "acme::billing::Payment.amount.amount"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "currencies",
+ "@agg": "count",
+ "@distinct": true,
+ "@of": [
+ "acme::billing::Payment.amount.currency"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "payments",
+ "@agg": "count",
+ "@of": [
+ "acme::billing::Payment.id"
+ ]
+ }
+ },
+ {
+ "measure.ratio": {
+ "name": "averagePayment",
+ "@denominator": "payments",
+ "@numerator": "revenue"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "RevenueByMonth",
+ "@dimensions": [
+ "currency",
+ "kind",
+ "receivedOn:month"
+ ],
+ "@from": "acme::billing::Payment",
+ "@measures": [
+ "revenue",
+ "largest",
+ "averagePayment",
+ "payments"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_revenuebymonth"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "CurrencyMix",
+ "@dimensions": [
+ "kind"
+ ],
+ "@from": "acme::billing::Payment",
+ "@measures": [
+ "currencies",
+ "payments"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_currencymix"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/reporting-value-object-members/input/meta.billing.json b/fixtures/conformance/reporting-value-object-members/input/meta.billing.json
new file mode 100644
index 0000000000..fd1aa34d40
--- /dev/null
+++ b/fixtures/conformance/reporting-value-object-members/input/meta.billing.json
@@ -0,0 +1,177 @@
+{
+ "metadata.root": {
+ "package": "acme::billing",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Payment",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "payments"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "kind"
+ }
+ },
+ {
+ "field.date": {
+ "name": "receivedOn",
+ "@required": true
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "flattened",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "currency",
+ "@of": "Payment.amount.currency"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "kind",
+ "@of": "Payment.kind"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "receivedOn",
+ "@of": "Payment.receivedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "revenue",
+ "@agg": "sum",
+ "@of": "Payment.amount.amount"
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "largest",
+ "@agg": "max",
+ "@of": "Payment.amount.amount",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "currencies",
+ "@agg": "count",
+ "@distinct": true,
+ "@of": "Payment.amount.currency"
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "payments",
+ "@agg": "count",
+ "@of": "Payment.id"
+ }
+ },
+ {
+ "measure.ratio": {
+ "name": "averagePayment",
+ "@numerator": "revenue",
+ "@denominator": "payments"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "RevenueByMonth",
+ "@from": "Payment",
+ "@dimensions": [
+ "currency",
+ "kind",
+ "receivedOn:month"
+ ],
+ "@measures": [
+ "revenue",
+ "largest",
+ "averagePayment",
+ "payments"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_revenuebymonth"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "CurrencyMix",
+ "@from": "Payment",
+ "@dimensions": [
+ "kind"
+ ],
+ "@measures": [
+ "currencies",
+ "payments"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_currencymix"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/reporting-value-object-members/providers.json b/fixtures/conformance/reporting-value-object-members/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/reporting-value-object-members/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json
index 2b39ff1a37..39e633105c 100644
--- a/fixtures/registry-conformance/expected-registry.json
+++ b/fixtures/registry-conformance/expected-registry.json
@@ -89,7 +89,7 @@
"valueType": "string",
"isArray": false,
"required": true,
- "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via)."
+ "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own."
},
{
"name": "via",
@@ -127,7 +127,7 @@
"valueType": "string",
"isArray": false,
"required": true,
- "description": "Dotted Entity.field reference naming the date or timestamp column."
+ "description": "Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object."
},
{
"name": "via",
@@ -3350,7 +3350,7 @@
"valueType": "string",
"isArray": true,
"required": false,
- "description": "Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows."
+ "description": "Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows."
},
{
"name": "segment",
diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReportShapeTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReportShapeTests.cs
index 758faeaff1..6fc0b1799f 100644
--- a/server/csharp/MetaObjects.Conformance.Tests/ReportShapeTests.cs
+++ b/server/csharp/MetaObjects.Conformance.Tests/ReportShapeTests.cs
@@ -138,6 +138,22 @@ public void An_hour_grain_is_a_timestamp_and_a_coarser_grain_is_a_date()
Assert.Null(fields["asOfDateWeek"].TypeSource);
}
+ [Fact]
+ public void A_value_object_member_derives_the_members_type()
+ {
+ // FR-044 R12: `Payment.amount.currency` and `Payment.amount.amount` read Money's members,
+ // so the derived fields take the member's subtype, nullability and type source. The
+ // same rows as the TypeScript report-shape derivation of this fixture.
+ var root = LoadFixture("reporting-value-object-members");
+ var rows = Shape(root, "RevenueByMonth").Fields.Select(f =>
+ $"{f.Name} {f.SubType} {f.Required} {(f.TypeSource is null ? "-" : $"{f.TypeSource.Parent!.Name}.{f.TypeSource.Name}")}");
+ Assert.Equal(
+ ["currency string True Money.currency", "kind string False Payment.kind", "receivedOnMonth date True -",
+ "revenue decimal False -", "largest decimal True Money.amount", "averagePayment decimal False -",
+ "payments long True -"],
+ rows.ToList());
+ }
+
[Fact]
public void A_sourceless_report_has_a_shape_and_no_view()
{
diff --git a/server/csharp/MetaObjects/Core/Reporting/ReportShape.cs b/server/csharp/MetaObjects/Core/Reporting/ReportShape.cs
index 338edda66f..60e3c8512a 100644
--- a/server/csharp/MetaObjects/Core/Reporting/ReportShape.cs
+++ b/server/csharp/MetaObjects/Core/Reporting/ReportShape.cs
@@ -96,17 +96,35 @@ public static class ReportShapes
private static (MetaObject Named, MetaField Field)? ResolveReportingFieldRefNamed(
string reference, MetaData declaring, MetaRoot root, MetaObject? host)
{
- // `Entity.field`; a package qualifier uses `::`, so the member separator is the LAST dot.
- int dot = reference.LastIndexOf(CHILD_REF_SEPARATOR, StringComparison.Ordinal);
+ // `Entity.field` or `Entity.field.member`; a package qualifier uses `::` and holds no `.`,
+ // so the owner ends at the first `.` after the last `::`.
+ int lastSep = reference.LastIndexOf(PACKAGE_SEPARATOR, StringComparison.Ordinal);
+ int dot = reference.IndexOf(CHILD_REF_SEPARATOR, lastSep == -1 ? 0 : lastSep + PACKAGE_SEPARATOR.Length, StringComparison.Ordinal);
if (dot <= 0) return null;
+ string[] path = reference[(dot + CHILD_REF_SEPARATOR.Length)..].Split(CHILD_REF_SEPARATOR);
+ if (path.Length > 2) return null;
if (NamingRefs.ResolveObjectRef(root, reference[..dot], NamingRefs.EffectivePackage(declaring))
is not MetaObject named) return null;
if (host is not null && !ValidationPasses.IsSelfOrAncestor(named, host)) return null;
// ADR-0039: resolving, so a field inherited through extends is found.
- var field = (host ?? named).FindField(reference[(dot + CHILD_REF_SEPARATOR.Length)..]);
- return field is null ? null : (named, field);
+ var field = (host ?? named).FindField(path[0]);
+ if (field is null) return null;
+ if (path.Length == 1) return (named, field);
+ var member = FlattenedMemberOf(field, path[1]);
+ return member is null ? null : (named, member);
}
+ ///
+ /// FR-044 R12: member of the value object a flattened
+ /// field.object embeds (resolving, so an inherited member counts). Null when the field
+ /// is not flattened, names no value object, or the value object has no such member.
+ ///
+ public static MetaField? FlattenedMemberOf(MetaField embedding, string name) =>
+ ValidationPasses.IsFlattenedField(embedding) &&
+ NamingRefs.RefTarget(embedding, FIELD_ATTR_OBJECT_REF) is MetaObject valueObject
+ ? valueObject.FindField(name)
+ : null;
+
///
/// A dimension's @of field, read as the loader's rule D1 reads it. Without
/// @via it is with as
diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs
index 71350ffe87..6c90958984 100644
--- a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs
+++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs
@@ -175,6 +175,52 @@ internal static bool IsSelfOrAncestor(MetaData? candidate, MetaData entity)
private static MetaData? ReportingFieldOf(MetaData obj, string name) =>
ReportingChildOfType(obj, TYPE_FIELD, name);
+ ///
+ /// R12 — the column an @of path names on : field , or
+ /// field.member for a member of a value object stored flattened (one column per member).
+ /// Reports the first failure through and returns null.
+ ///
+ private static MetaData? OfColumn(
+ MetaData entity, string[] path, string item, Action err, Func fieldMissing)
+ {
+ var field = ReportingFieldOf(entity, path[0]);
+ if (field is null)
+ {
+ err(fieldMissing());
+ return null;
+ }
+ if (path.Length == 1) return field;
+ string memberName = path[1];
+ var valueObject = field.SubType == FIELD_SUBTYPE_OBJECT ? ReportingRefTargetOf(field) : null;
+ if (valueObject is null)
+ {
+ err($"@of '{item}' names member '{memberName}' of '{path[0]}', a field.{field.SubType} with no value object.");
+ return null;
+ }
+ if (!IsFlattenedField(field))
+ {
+ string storage = field.Attr(FIELD_ATTR_STORAGE) as string ?? "jsonb (the default)";
+ err($"@of '{item}' names a member of '{path[0]}', whose value object is stored as {storage}. " +
+ "A report reads a member only under @storage: flattened, where the member has a column of its own.");
+ return null;
+ }
+ var member = ReportingFieldOf(valueObject, memberName);
+ if (member is null)
+ {
+ err($"@of '{item}' names no member '{memberName}' on value object '{valueObject.ResolutionKey()}'.");
+ return null;
+ }
+ return member;
+ }
+
+ /// The object a field's @objectRef resolves to (ADR-0059 R3), when it is one.
+ private static MetaData? ReportingRefTargetOf(MetaData field) =>
+ NamingRefs.RefTarget(field, FIELD_ATTR_OBJECT_REF) is { Type: TYPE_OBJECT } target ? target : null;
+
+ /// True for a field.object whose @storage is flattened (ADR-0039: resolving).
+ internal static bool IsFlattenedField(MetaData field) =>
+ field.SubType == FIELD_SUBTYPE_OBJECT && field.Attr(FIELD_ATTR_STORAGE) as string == STORAGE_FLATTENED;
+
private static IReadOnlyDictionary? AsPlainObject(object? v) =>
v as IReadOnlyDictionary;
@@ -329,9 +375,9 @@ void Err(string message) =>
string? of = dim.Of();
if (of is null) return; // missing @of is ERR_MISSING_REQUIRED_ATTR (attr schema pass)
var parts = ReportingSplitDotted(of);
- if (parts is null || parts.Value.Path.Length != 1)
+ if (parts is null || parts.Value.Path.Length > 2)
{
- Err($"@of '{of}' must be Entity.field.");
+ Err($"@of '{of}' must be Entity.field or Entity.field.member.");
return;
}
// D1 — after @via, a bare Owner resolves in the package of the entity @via reaches:
@@ -357,16 +403,12 @@ void Err(string message) =>
// @via terminal: a base the terminal extends must itself carry the field, or the dimension
// names a column the base table lacks. Without @via the host IS the checked entity.
var lookup = via is null ? ofEntity : named!;
- var field = ReportingFieldOf(lookup, fieldName);
- if (field is null)
- {
- bool declaredOnTerminal = !ReferenceEquals(lookup, ofEntity) && ReportingFieldOf(ofEntity, fieldName) is not null;
- Err(declaredOnTerminal
+ var field = OfColumn(lookup, parts.Value.Path, of, Err, () =>
+ !ReferenceEquals(lookup, ofEntity) && ReportingFieldOf(ofEntity, fieldName) is not null
? $"@of '{of}' names no field '{fieldName}' on '{Shown(ctx, lookup)}': only '{Shown(ctx, ofEntity)}', " +
$"the entity @via reaches, declares it. Name it '{ofEntity.Name}.{fieldName}'."
: $"@of '{of}' names no field '{fieldName}' on '{Shown(ctx, lookup)}'.");
- return;
- }
+ if (field is null) return;
// D5 — a dimension groups by a scalar. A field.object (or a field carrying @objectRef) is a JSON
// document: no port serves a report over one, and a document is not a value to group rows by.
@@ -597,9 +639,9 @@ private static bool CheckAggregateColumns(MemberCtx ctx, MetaMeasure measure, Ac
foreach (string item in columns)
{
var parts = ReportingSplitDotted(item);
- if (parts is null || parts.Value.Path.Length != 1)
+ if (parts is null || parts.Value.Path.Length > 2)
{
- err($"@of '{item}' must be Entity.field.");
+ err($"@of '{item}' must be Entity.field or Entity.field.member.");
return false;
}
var named = NamingRefs.ResolveObjectRef(ctx.Root, parts.Value.Owner, NamingRefs.EffectivePackage(ctx.Declaring));
@@ -609,12 +651,9 @@ private static bool CheckAggregateColumns(MemberCtx ctx, MetaMeasure measure, Ac
"A measure aggregates its own entity's rows; declare it on the entity that owns the column.");
return false;
}
- var ofField = ReportingFieldOf(ctx.Host, parts.Value.Path[0]);
- if (ofField is null)
- {
- err($"@of '{item}' names no field '{parts.Value.Path[0]}' on '{ctx.Declaring.ResolutionKey()}'.");
- return false;
- }
+ var ofField = OfColumn(ctx.Host, parts.Value.Path, item, err,
+ () => $"@of '{item}' names no field '{parts.Value.Path[0]}' on '{ctx.Declaring.ResolutionKey()}'.");
+ if (ofField is null) return false;
// M10 — a measure aggregates scalars. A field.object (or a field carrying @objectRef) is a JSON
// document, which no port aggregates in a report.
if (ofField.SubType == FIELD_SUBTYPE_OBJECT || ReportingObjectRefOf(ofField) is not null)
@@ -935,6 +974,9 @@ void Claim(string fieldName, string what)
if (measureName is not null) Claim(measureName, $"measure '{measureName}'");
}
+ // R12 — amounts in different units are never combined.
+ CheckValueObjectUnits(report, from, m => Err(m));
+
// R7 — @segment names a segment of @from.
// ADR-0039: resolving — a report may inherit @segment via extends.
if (report.Attr(OBJECT_REPORT_ATTR_SEGMENT) is string segment &&
@@ -1000,6 +1042,59 @@ void Claim(string fieldName, string what)
/// ERR_REPORT_FOREIGN_MEASURE (it is another entity's measure) or ERR_INVALID_REPORT
/// (it is nobody's) and returns null.
///
+ ///
+ /// R12 — a measure that sums, averages or takes the min or max of a numeric member of a
+ /// flattened value object (Money's amount) combines rows only when the report groups by each
+ /// non-numeric member of that value object (Money's currency). Checked for every listed
+ /// measure.aggregate and every operand of a listed ratio; the grouping is an attribute
+ /// dimension of @from, with no @via, whose @of names the same field.member . A measure
+ /// whose @of fails M1 is skipped (M1 reports it).
+ ///
+ private static void CheckValueObjectUnits(MetaData report, MetaData from, Action err)
+ {
+ var grouped = new HashSet(StringComparer.Ordinal);
+ foreach (var item in ReportAccessors.ReportDimensionItems(report))
+ {
+ if (ReportingChildOfType(from, TYPE_DIMENSION, item.Name) is not MetaDimension dim ||
+ dim.IsTime() || dim.Via() is not null) continue;
+ var path = ReportingSplitDotted(dim.Of() ?? "")?.Path;
+ if (path is { Length: 2 }) grouped.Add(string.Join(CHILD_REF_SEPARATOR, path));
+ }
+ var checkedMeasures = new HashSet(ReferenceEqualityComparer.Instance);
+ foreach (string item in ReportAccessors.ReportMeasureNames(report))
+ {
+ string name = item[(item.LastIndexOf(CHILD_REF_SEPARATOR, StringComparison.Ordinal) + 1)..];
+ if (ReportingChildOfType(from, TYPE_MEASURE, name) is not MetaMeasure listed) continue;
+ IEnumerable aggregates = listed.IsRatio()
+ ? new[] { listed.Numerator(), listed.Denominator() }
+ .Select(n => n is null ? null : ReportingChildOfType(from, TYPE_MEASURE, n))
+ : [listed];
+ foreach (var candidate in aggregates)
+ {
+ if (candidate is not MetaMeasure m || m.SubType != MEASURE_SUBTYPE_AGGREGATE || !checkedMeasures.Add(m)) continue;
+ string? agg = m.Agg();
+ if (agg != AGG_SUM && agg != AGG_AVG && agg != AGG_MIN && agg != AGG_MAX) continue;
+ string of = m.OfColumns().FirstOrDefault() ?? "";
+ var parts = ReportingSplitDotted(of);
+ if (parts is not { Path.Length: 2 }) continue;
+ string fieldName = parts.Value.Path[0];
+ var field = ReportingFieldOf(from, fieldName);
+ var valueObject = field is not null && IsFlattenedField(field) ? ReportingRefTargetOf(field) : null;
+ var member = valueObject is null ? null : ReportingFieldOf(valueObject, parts.Value.Path[1]);
+ if (valueObject is null || member is null || !ReportingNumericFieldSubtypes.Contains(member.SubType)) continue;
+ // ADR-0039: resolving — a unit member the value object inherits qualifies its amounts too.
+ foreach (var unit in valueObject.Children().Where(c => c.Type == TYPE_FIELD))
+ {
+ if (ReportingNumericFieldSubtypes.Contains(unit.SubType) || grouped.Contains($"{fieldName}.{unit.Name}")) continue;
+ err($": measure '{m.Name}' takes @agg '{agg}' of '{of}', a member of value object " +
+ $"'{valueObject.ResolutionKey()}', but the report does not group by its member '{unit.Name}', so " +
+ $"amounts with different '{unit.Name}' values would be combined. List an attribute dimension of " +
+ $"@from whose @of is '{parts.Value.Owner}.{fieldName}.{unit.Name}'.");
+ }
+ }
+ }
+ }
+
private static string? CheckReportMeasure(
MetaData root, MetaData report, MetaData from, string item, string label, ReportingErrorSink sink)
{
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java
index 88789141f7..968fefefa3 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java
@@ -253,6 +253,43 @@ private static MetaData fieldOf(MetaData obj, String name) {
return childOfType(obj, MetaField.TYPE_FIELD, name);
}
+ /**
+ * R12 — the column an {@code @of} path names on {@code entity}: {@code field}, or
+ * {@code field.member} for a member of a value object stored flattened (one column per
+ * member). Reports the first failure through {@code err} and returns {@code null}.
+ */
+ private static MetaData ofColumn(MetaData entity, List path, String item, Consumer err,
+ java.util.function.Supplier fieldMissing) {
+ MetaData field = fieldOf(entity, path.get(0));
+ if (field == null) {
+ err.accept(fieldMissing.get());
+ return null;
+ }
+ if (path.size() == 1) return field;
+ String memberName = path.get(1);
+ MetaObject valueObject = ObjectField.SUBTYPE_OBJECT.equals(field.getSubType())
+ ? References.refTarget(field, MetaObject.ATTR_OBJECT_REF) : null;
+ if (valueObject == null) {
+ err.accept("@of '" + item + "' names member '" + memberName + "' of '" + path.get(0) + "', a field."
+ + field.getSubType() + " with no value object.");
+ return null;
+ }
+ if (!ReportShape.isFlattenedField(field)) {
+ String storage = stringAttr(field, ObjectField.ATTR_STORAGE);
+ err.accept("@of '" + item + "' names a member of '" + path.get(0) + "', whose value object is stored as "
+ + (storage == null ? "jsonb (the default)" : storage) + ". A report reads a member only under "
+ + "@storage: flattened, where the member has a column of its own.");
+ return null;
+ }
+ MetaData member = fieldOf(valueObject, memberName);
+ if (member == null) {
+ err.accept("@of '" + item + "' names no member '" + memberName + "' on value object '"
+ + valueObject.getName() + "'.");
+ return null;
+ }
+ return member;
+ }
+
/** An object operand carrying a {@code now} key — a relative-date value, well-formed
* ({@code { now }} plus an optional {@code startOf}) or not. A malformed one is refused, never read as data. */
private static boolean isRelativeValue(Object v) {
@@ -434,8 +471,8 @@ private static void checkDimension(MemberCtx ctx, MetaDimension dim) {
String of = dim.getOf();
if (of == null) return; // missing @of is ERR_MISSING_REQUIRED_ATTR (attr schema pass)
Dotted parts = splitDotted(of);
- if (parts == null || parts.path().size() != 1) {
- err.accept("@of '" + of + "' must be Entity.field.");
+ if (parts == null || parts.path().size() > 2) {
+ err.accept("@of '" + of + "' must be Entity.field or Entity.field.member.");
return;
}
// D1 — after @via, a bare Owner resolves in the package of the entity @via reaches: the
@@ -459,16 +496,14 @@ private static void checkDimension(MemberCtx ctx, MetaDimension dim) {
// field, or the dimension names a column the base table lacks. Without @via the host IS
// the checked entity.
MetaData lookup = via == null ? ofEntity : named;
- MetaData field = fieldOf(lookup, fieldName);
- if (field == null) {
- boolean declaredOnTerminal = lookup != ofEntity && fieldOf(ofEntity, fieldName) != null;
- err.accept(declaredOnTerminal
+ final MetaData terminalEntity = ofEntity;
+ MetaData field = ofColumn(lookup, parts.path(), of, err, () ->
+ lookup != terminalEntity && fieldOf(terminalEntity, fieldName) != null
? "@of '" + of + "' names no field '" + fieldName + "' on '" + shown(ctx, lookup) + "': only '"
- + shown(ctx, ofEntity) + "', the entity @via reaches, declares it. Name it '"
- + ofEntity.getShortName() + "." + fieldName + "'."
+ + shown(ctx, terminalEntity) + "', the entity @via reaches, declares it. Name it '"
+ + terminalEntity.getShortName() + "." + fieldName + "'."
: "@of '" + of + "' names no field '" + fieldName + "' on '" + shown(ctx, lookup) + "'.");
- return;
- }
+ if (field == null) return;
// D5 — a dimension groups by a scalar. A field.object (or a field carrying @objectRef) is
// a JSON document: no port serves a report over one, and a document is not a value to
@@ -720,8 +755,8 @@ private static AggregateColumns checkAggregateColumns(MemberCtx ctx, MetaMeasure
List fields = new ArrayList<>();
for (String item : columns) {
Dotted parts = splitDotted(item);
- if (parts == null || parts.path().size() != 1) {
- err.accept("@of '" + item + "' must be Entity.field.");
+ if (parts == null || parts.path().size() > 2) {
+ err.accept("@of '" + item + "' must be Entity.field or Entity.field.member.");
return null;
}
MetaData named = ValidationPhase.resolveRootObject(ctx.root(), parts.owner(), pkgOf(ctx.declaring()));
@@ -730,12 +765,9 @@ private static AggregateColumns checkAggregateColumns(MemberCtx ctx, MetaMeasure
+ "'. A measure aggregates its own entity's rows; declare it on the entity that owns the column.");
return null;
}
- MetaData field = fieldOf(ctx.host(), parts.path().get(0));
- if (field == null) {
- err.accept("@of '" + item + "' names no field '" + parts.path().get(0) + "' on '"
- + ctx.declaring().getName() + "'.");
- return null;
- }
+ MetaData field = ofColumn(ctx.host(), parts.path(), item, err, () -> "@of '" + item
+ + "' names no field '" + parts.path().get(0) + "' on '" + ctx.declaring().getName() + "'.");
+ if (field == null) return null;
// M10 — a measure aggregates scalars. A field.object (or a field carrying @objectRef)
// is a JSON document, which no port aggregates in a report.
if (isDocumentField(field)) {
@@ -1032,6 +1064,9 @@ private static void checkReport(MetaRoot root, MetaObject report, ErrorSink sink
if (measureName != null) claim.accept(measureName, "measure '" + measureName + "'");
}
+ // R12 — amounts in different units are never combined.
+ checkValueObjectUnits(report, from, message -> sink.push(report, ErrorCode.ERR_INVALID_REPORT, label, message));
+
// R7 — @segment names a segment of @from.
String segment = stringAttr(report, MetaObject.ATTR_REPORT_SEGMENT);
if (segment != null && childOfType(from, ReportingConstants.TYPE_SEGMENT, segment) == null) {
@@ -1103,6 +1138,64 @@ private static void checkSpine(MetaRoot root, MetaObject report, MetaObject from
* ERR_REPORT_FOREIGN_MEASURE (it is another entity's measure) or ERR_INVALID_REPORT (it
* is nobody's) and returns {@code null}.
*/
+ /**
+ * R12 — a measure that sums, averages or takes the min or max of a numeric member of a
+ * flattened value object (Money's amount) combines rows only when the report groups by each
+ * non-numeric member of that value object (Money's currency). Checked for every listed
+ * measure.aggregate and every operand of a listed ratio; the grouping is an attribute
+ * dimension of @from, with no @via, whose @of names the same {@code field.member}. A measure
+ * whose @of fails M1 is skipped (M1 reports it).
+ */
+ private static void checkValueObjectUnits(MetaObject report, MetaObject from, Consumer err) {
+ Set grouped = new HashSet<>();
+ for (ReportDimensionItem item : ReportAccessors.reportDimensionItems(report)) {
+ if (!(childOfType(from, ReportingConstants.TYPE_DIMENSION, item.name()) instanceof MetaDimension dim)
+ || dim.isTime() || dim.getVia() != null || dim.getOf() == null) continue;
+ Dotted parts = splitDotted(dim.getOf());
+ if (parts != null && parts.path().size() == 2) grouped.add(String.join(SEP, parts.path()));
+ }
+ Set checked = java.util.Collections.newSetFromMap(new IdentityHashMap<>());
+ for (String item : ReportAccessors.reportMeasureNames(report)) {
+ String name = item.substring(item.lastIndexOf(SEP) + 1);
+ if (!(childOfType(from, ReportingConstants.TYPE_MEASURE, name) instanceof MetaMeasure listed)) continue;
+ List aggregates = new ArrayList<>();
+ if (listed.isRatio()) {
+ for (String operand : new String[] {listed.getNumerator(), listed.getDenominator()}) {
+ if (operand != null) aggregates.add(childOfType(from, ReportingConstants.TYPE_MEASURE, operand));
+ }
+ } else {
+ aggregates.add(listed);
+ }
+ for (MetaData candidate : aggregates) {
+ if (!(candidate instanceof MetaMeasure m)
+ || !ReportingConstants.MEASURE_SUBTYPE_AGGREGATE.equals(m.getSubType()) || !checked.add(m)) continue;
+ String agg = m.getAgg();
+ if (!List.of(ReportingConstants.AGG_SUM, ReportingConstants.AGG_AVG, ReportingConstants.AGG_MIN,
+ ReportingConstants.AGG_MAX).contains(agg)) continue;
+ String of = m.getOfColumns().isEmpty() ? "" : m.getOfColumns().get(0);
+ Dotted parts = splitDotted(of);
+ if (parts == null || parts.path().size() != 2) continue;
+ String fieldName = parts.path().get(0);
+ MetaData field = fieldOf(from, fieldName);
+ MetaObject valueObject = field != null && ReportShape.isFlattenedField(field)
+ ? References.refTarget(field, MetaObject.ATTR_OBJECT_REF) : null;
+ MetaData member = valueObject == null ? null : fieldOf(valueObject, parts.path().get(1));
+ if (member == null || !NUMERIC_FIELD_SUBTYPES.contains(member.getSubType())) continue;
+ // ADR-0039: resolving — a unit member the value object inherits qualifies its amounts too.
+ for (MetaData unit : valueObject.getChildren(MetaData.class, true)) {
+ if (!MetaField.TYPE_FIELD.equals(unit.getType())
+ || NUMERIC_FIELD_SUBTYPES.contains(unit.getSubType())
+ || grouped.contains(fieldName + SEP + unit.getShortName())) continue;
+ err.accept(": measure '" + m.getShortName() + "' takes @agg '" + agg + "' of '" + of
+ + "', a member of value object '" + valueObject.getName() + "', but the report does not "
+ + "group by its member '" + unit.getShortName() + "', so amounts with different '"
+ + unit.getShortName() + "' values would be combined. List an attribute dimension of @from "
+ + "whose @of is '" + parts.owner() + SEP + fieldName + SEP + unit.getShortName() + "'.");
+ }
+ }
+ }
+ }
+
private static String checkReportMeasure(MetaRoot root, MetaObject report, MetaObject from, String item,
String label, ErrorSink sink) {
String fromKey = from.getName();
diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportShape.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportShape.java
index dfa6337b5f..424a21637b 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportShape.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportShape.java
@@ -259,7 +259,10 @@ public static MetaData memberOwner(MetaData member, MetaObject from) {
* and as the TypeScript {@code resolveReportingFieldRef}:
*
*
- * A package qualifier uses {@code ::}, so the member separator is the LAST dot.
+ * The reference is {@code Entity.field} or, for a member of a value object stored
+ * flattened, {@code Entity.field.member} (FR-044 R12). A package qualifier uses
+ * {@code ::} and holds no dot, so the entity half ends at the first dot after the
+ * last {@code ::}.
* The entity half resolves relative to the package of {@code declaring}, the
* entity that declares the member ({@link #memberOwner}; ADR-0042).
* With {@code host} (a measure, or a dimension without {@code @via}: the reference
@@ -274,14 +277,46 @@ public static MetaField> resolveFieldRef(String ref, MetaData declaring, MetaR
MetaObject named = resolveFieldRefEntity(ref, declaring, root);
if (named == null) return null;
if (host != null && !isSelfOrAncestor(named, host)) return null;
- String fieldName = ref.substring(ref.lastIndexOf(SEP) + SEP.length());
- // ADR-0039: resolving, so a field inherited through extends is found.
- for (MetaField> f : (host != null ? host : named).getMetaFields()) {
- if (fieldName.equals(f.getName())) return f;
+ String[] path = ref.substring(ownerEnd(ref) + SEP.length()).split(java.util.regex.Pattern.quote(SEP), -1);
+ if (path.length > 2) return null;
+ MetaField> field = fieldNamed(host != null ? host : named, path[0]);
+ if (field == null || path.length == 1) return field;
+ return flattenedMemberOf(field, path[1]);
+ }
+
+ /** A field of {@code obj} by name (ADR-0039: resolving, so a field inherited through extends is found). */
+ private static MetaField> fieldNamed(MetaObject obj, String name) {
+ for (MetaField> f : obj.getMetaFields()) {
+ if (name.equals(f.getName())) return f;
}
return null;
}
+ /**
+ * FR-044 R12: member {@code name} of the value object a flattened {@code field.object}
+ * embeds (resolving, so an inherited member counts). {@code null} when the field is not
+ * flattened, names no value object, or the value object has no such member.
+ */
+ public static MetaField> flattenedMemberOf(MetaField> embedding, String name) {
+ if (!isFlattenedField(embedding)) return null;
+ MetaObject valueObject = References.refTarget(embedding, MetaObject.ATTR_OBJECT_REF);
+ return valueObject == null ? null : fieldNamed(valueObject, name);
+ }
+
+ /** True for a {@code field.object} whose {@code @storage} is {@code flattened} (ADR-0039: resolving). */
+ public static boolean isFlattenedField(MetaData field) {
+ if (!com.metaobjects.field.ObjectField.SUBTYPE_OBJECT.equals(field.getSubType())
+ || !field.hasMetaAttr(com.metaobjects.field.ObjectField.ATTR_STORAGE)) return false;
+ return com.metaobjects.field.ObjectField.STORAGE_FLATTENED.equals(
+ field.getMetaAttr(com.metaobjects.field.ObjectField.ATTR_STORAGE).getValue());
+ }
+
+ /** Index of the dot that ends a reference's entity half: the first dot after the last {@code ::}. */
+ private static int ownerEnd(String ref) {
+ int lastSep = ref.lastIndexOf(PKG_SEP);
+ return ref.indexOf(SEP, lastSep == -1 ? 0 : lastSep + PKG_SEP.length());
+ }
+
/**
* The entity an {@code Entity.field} reference NAMES, or {@code null}: the entity half
* of {@link #resolveFieldRef}, resolved relative to the package of {@code declaring}
@@ -291,7 +326,7 @@ public static MetaField> resolveFieldRef(String ref, MetaData declaring, MetaR
*/
public static MetaObject resolveFieldRefEntity(String ref, MetaData declaring, MetaRoot root) {
if (ref == null) return null;
- int dot = ref.lastIndexOf(SEP);
+ int dot = ownerEnd(ref);
if (dot <= 0) return null;
return ValidationPhase.resolveRootObject(root, ref.substring(0, dot), packageOf(declaring));
}
diff --git a/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportShapeTest.java b/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportShapeTest.java
index 9d623a602f..d563cd235e 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportShapeTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportShapeTest.java
@@ -228,6 +228,24 @@ public void timeDimensionIsNamedByGrainAndTypedByGrain() {
assertEquals("date", field(activity, "asOfDateWeek").subType());
}
+ @Test
+ public void aValueObjectMemberDerivesTheMembersType() throws IOException {
+ // FR-044 R12: `Payment.amount.currency` and `Payment.amount.amount` read Money's members,
+ // so the derived fields take the member's subtype, nullability and type source. The same
+ // rows as the TypeScript report-shape derivation of this fixture.
+ Path input = corpusDir().resolveSibling("conformance")
+ .resolve("reporting-value-object-members/input/meta.billing.json");
+ MetaRoot root = loadJson(new String(Files.readAllBytes(input), StandardCharsets.UTF_8));
+ List rows = ReportShape.of(object(root, "RevenueByMonth"), root).fields().stream()
+ .map(f -> f.name() + " " + f.subType() + " " + f.required() + " "
+ + (f.typeSourceKey() == null ? "-" : f.typeSourceKey()))
+ .collect(Collectors.toList());
+ assertEquals(List.of("currency string true acme::billing::Money.currency",
+ "kind string false acme::billing::Payment.kind", "receivedOnMonth date true -",
+ "revenue decimal false -", "largest decimal true acme::billing::Money.amount",
+ "averagePayment decimal false -", "payments long true -"), rows);
+ }
+
@Test
public void aReportWithNoDimensionsHasOnlyMeasures() {
ReportShape shape = ReportShape.of(object(canonical, "FitnessTotals"), canonical);
diff --git a/server/python/src/metaobjects/loader/validate_reporting.py b/server/python/src/metaobjects/loader/validate_reporting.py
index 6038697431..ad19eb9429 100644
--- a/server/python/src/metaobjects/loader/validate_reporting.py
+++ b/server/python/src/metaobjects/loader/validate_reporting.py
@@ -47,6 +47,7 @@
from ..meta.core.attr.attr_constants import ATTR_SUBTYPE_FILTER
from ..meta.core.field.field_constants import (
FIELD_ATTR_OBJECT_REF,
+ FIELD_ATTR_STORAGE,
FIELD_SUBTYPE_BOOLEAN,
FIELD_SUBTYPE_CURRENCY,
FIELD_SUBTYPE_DATE,
@@ -88,7 +89,7 @@
report_measure_names,
report_spine,
)
-from ..meta.core.reporting.report_shape import measure_result_sub_type
+from ..meta.core.reporting.report_shape import is_flattened_field, measure_result_sub_type
from ..meta.core.reporting.reporting_constants import (
AGG_AVG,
AGG_COUNT,
@@ -313,6 +314,44 @@ def _is_document_field(field: MetaData) -> bool:
return field.sub_type == FIELD_SUBTYPE_OBJECT or _object_ref_of(field) is not None
+def _of_column(
+ entity: MetaData, path: list[str], item: str, err: Callable[[str], None], field_missing: Callable[[], str]
+) -> MetaData | None:
+ """R12 -- the column an ``@of`` path names on *entity*: ``field``, or ``field.member`` for a
+ member of a value object stored flattened (one column per member). Reports the first
+ failure through *err* and returns ``None``."""
+ field = _field_of(entity, path[0])
+ if field is None:
+ err(field_missing())
+ return None
+ if len(path) == 1:
+ return field
+ member_name = path[1]
+ value_object = _ref_target_object(field) if field.sub_type == FIELD_SUBTYPE_OBJECT else None
+ if value_object is None:
+ err(f"@of '{item}' names member '{member_name}' of '{path[0]}', a field.{field.sub_type} with no value object.")
+ return None
+ if not is_flattened_field(field):
+ storage = field.get_meta_attr(FIELD_ATTR_STORAGE)
+ shown = storage if isinstance(storage, str) else "jsonb (the default)"
+ err(
+ f"@of '{item}' names a member of '{path[0]}', whose value object is stored as {shown}. "
+ f"A report reads a member only under @storage: flattened, where the member has a column of its own."
+ )
+ return None
+ member = _field_of(value_object, member_name)
+ if member is None:
+ err(f"@of '{item}' names no member '{member_name}' on value object '{value_object.resolution_key()}'.")
+ return None
+ return member
+
+
+def _ref_target_object(field: MetaData) -> MetaData | None:
+ """The object a field's ``@objectRef`` resolves to (ADR-0059 R7), when it is one."""
+ target = ref_target(field, FIELD_ATTR_OBJECT_REF)
+ return target if target is not None and target.type == TYPE_OBJECT else None
+
+
def _is_relative_value(v: object) -> TypeGuard[dict[str, object]]:
"""An object operand carrying a ``now`` key — a relative-date value, well-formed
(``{ now }`` plus an optional ``startOf``) or not. A malformed one is refused, never read as data."""
@@ -467,8 +506,8 @@ def err(message: str) -> None:
if of is None:
return # missing @of is ERR_MISSING_REQUIRED_ATTR (attr schema pass)
parts = _split_dotted(of)
- if parts is None or len(parts.path) != 1:
- err(f"@of '{of}' must be Entity.field.")
+ if parts is None or len(parts.path) > 2:
+ err(f"@of '{of}' must be Entity.field or Entity.field.member.")
return
# D1 — after @via, a bare Owner resolves in the package of the entity @via reaches: the path
# already fixes the entity, so `Realm.name` after a hop onto `world::Realm` names it. Without
@@ -489,17 +528,20 @@ def err(message: str) -> None:
# @via terminal: a base the terminal extends must itself carry the field, or the dimension
# names a column the base table lacks. Without @via the host IS the checked entity.
lookup = of_entity if via is None else named
- field = _field_of(lookup, field_name) if lookup is not None else None
- if field is None:
- assert lookup is not None
- if lookup is not of_entity and _field_of(of_entity, field_name) is not None:
- err(
+ assert lookup is not None
+ terminal = of_entity
+
+ def field_missing() -> str:
+ if lookup is not terminal and _field_of(terminal, field_name) is not None:
+ return (
f"@of '{of}' names no field '{field_name}' on '{_shown(ctx, lookup)}': only "
- f"'{_shown(ctx, of_entity)}', the entity @via reaches, declares it. "
- f"Name it '{of_entity.name}.{field_name}'."
+ f"'{_shown(ctx, terminal)}', the entity @via reaches, declares it. "
+ f"Name it '{terminal.name}.{field_name}'."
)
- else:
- err(f"@of '{of}' names no field '{field_name}' on '{_shown(ctx, lookup)}'.")
+ return f"@of '{of}' names no field '{field_name}' on '{_shown(ctx, lookup)}'."
+
+ field = _of_column(lookup, parts.path, of, err, field_missing)
+ if field is None:
return
# D5 -- a dimension groups by a scalar.
@@ -735,8 +777,8 @@ def _check_aggregate_columns(
fields: list[MetaData] = []
for item in columns:
parts = _split_dotted(item)
- if parts is None or len(parts.path) != 1:
- err(f"@of '{item}' must be Entity.field.")
+ if parts is None or len(parts.path) > 2:
+ err(f"@of '{item}' must be Entity.field or Entity.field.member.")
return None
named = resolve_object_ref(ctx.root, parts.owner, _pkg_of(ctx.declaring))
if not _is_self_or_ancestor(named, ctx.host):
@@ -745,9 +787,9 @@ def _check_aggregate_columns(
f"A measure aggregates its own entity's rows; declare it on the entity that owns the column."
)
return None
- field = _field_of(ctx.host, parts.path[0])
+ missing = f"@of '{item}' names no field '{parts.path[0]}' on '{ctx.declaring.resolution_key()}'."
+ field = _of_column(ctx.host, parts.path, item, err, lambda: missing)
if field is None:
- err(f"@of '{item}' names no field '{parts.path[0]}' on '{ctx.declaring.resolution_key()}'.")
return None
# M10 -- a measure aggregates scalars.
if _is_document_field(field):
@@ -1019,6 +1061,9 @@ def claim(field_name: str, what: str) -> None:
if measure_name is not None:
claim(measure_name, f"measure '{measure_name}'")
+ # R12 — amounts in different units are never combined.
+ _check_value_object_units(report, from_, err)
+
# R7 — @segment names a segment of @from.
# ADR-0039: resolving (get_meta_attr — Python attr() is own-only).
segment = report.get_meta_attr(OBJECT_REPORT_ATTR_SEGMENT)
@@ -1095,6 +1140,63 @@ def _check_spine_dimensions(
)
+def _check_value_object_units(report: MetaData, from_: MetaData, err: Callable[[str], None]) -> None:
+ """R12 -- a measure that sums, averages or takes the min or max of a numeric member of a
+ flattened value object (Money's amount) combines rows only when the report groups by each
+ non-numeric member of that value object (Money's currency). Checked for every listed
+ measure.aggregate and every operand of a listed ratio; the grouping is an attribute
+ dimension of @from, with no @via, whose @of names the same ``field.member``. A measure
+ whose @of fails M1 is skipped (M1 reports it)."""
+ grouped: set[str] = set()
+ for item in report_dimension_items(report):
+ dim = _child_of_type(from_, TYPE_DIMENSION, item.name)
+ if not isinstance(dim, MetaDimension) or dim.is_time() or dim.via() is not None:
+ continue
+ parts = _split_dotted(dim.of() or "")
+ if parts is not None and len(parts.path) == 2:
+ grouped.add(CHILD_REF_SEP.join(parts.path))
+ checked: set[int] = set()
+ for measure_item in report_measure_names(report):
+ listed = _child_of_type(from_, TYPE_MEASURE, measure_item.rsplit(CHILD_REF_SEP, 1)[-1])
+ if not isinstance(listed, MetaMeasure):
+ continue
+ operands = [listed.numerator(), listed.denominator()] if listed.is_ratio() else None
+ candidates = (
+ [listed]
+ if operands is None
+ else [_child_of_type(from_, TYPE_MEASURE, n) for n in operands if n is not None]
+ )
+ for m in candidates:
+ if not isinstance(m, MetaMeasure) or m.sub_type != MEASURE_SUBTYPE_AGGREGATE or id(m) in checked:
+ continue
+ checked.add(id(m))
+ agg = m.agg()
+ if agg not in (AGG_SUM, AGG_AVG, AGG_MIN, AGG_MAX):
+ continue
+ of = (m.of_columns() or [""])[0]
+ parts = _split_dotted(of)
+ if parts is None or len(parts.path) != 2:
+ continue
+ field_name = parts.path[0]
+ field = _field_of(from_, field_name)
+ value_object = _ref_target_object(field) if field is not None and is_flattened_field(field) else None
+ member = _field_of(value_object, parts.path[1]) if value_object is not None else None
+ if value_object is None or member is None or member.sub_type not in _NUMERIC_FIELD_SUBTYPES:
+ continue
+ # ADR-0039: resolving — a unit member the value object inherits qualifies its amounts too.
+ for unit in value_object.children():
+ if unit.type != TYPE_FIELD or unit.sub_type in _NUMERIC_FIELD_SUBTYPES:
+ continue
+ if f"{field_name}{CHILD_REF_SEP}{unit.name}" in grouped:
+ continue
+ err(
+ f": measure '{m.name}' takes @agg '{agg}' of '{of}', a member of value object "
+ f"'{value_object.resolution_key()}', but the report does not group by its member '{unit.name}', so "
+ f"amounts with different '{unit.name}' values would be combined. List an attribute dimension of "
+ f"@from whose @of is '{parts.owner}.{field_name}.{unit.name}'."
+ )
+
+
def _check_report_measure(
root: MetaData,
report: MetaData,
diff --git a/server/python/src/metaobjects/meta/core/reporting/report_shape.py b/server/python/src/metaobjects/meta/core/reporting/report_shape.py
index c56efafad2..613ad7f2f4 100644
--- a/server/python/src/metaobjects/meta/core/reporting/report_shape.py
+++ b/server/python/src/metaobjects/meta/core/reporting/report_shape.py
@@ -19,7 +19,11 @@
from ...meta_data import MetaData
from ...meta_root import MetaRoot
from ..field.field_constants import (
+ FIELD_ATTR_OBJECT_REF,
FIELD_ATTR_REQUIRED,
+ FIELD_ATTR_STORAGE,
+ FIELD_SUBTYPE_OBJECT,
+ STORAGE_FLATTENED,
FIELD_SUBTYPE_BOOLEAN,
FIELD_SUBTYPE_CURRENCY,
FIELD_SUBTYPE_DATE,
@@ -154,21 +158,44 @@ def _resolve_reporting_field_ref_named(
""":func:`resolve_reporting_field_ref`, also returning the entity the reference's
entity half NAMES (which, with ``host``, may be an ancestor of the entity the field is
read from). Table C reads that entity's primary identity."""
- # ``Entity.field``; a package qualifier uses ``::``, so the member separator is the LAST dot.
- dot = ref.rfind(CHILD_REF_SEP)
+ # ``Entity.field`` or ``Entity.field.member`` (FR-044 R12); a package qualifier uses ``::``
+ # and holds no dot, so the entity half ends at the first dot after the last ``::``.
+ last_sep = ref.rfind(PACKAGE_SEP)
+ dot = ref.find(CHILD_REF_SEP, 0 if last_sep == -1 else last_sep + len(PACKAGE_SEP))
if dot <= 0:
return None
+ path = ref[dot + len(CHILD_REF_SEP):].split(CHILD_REF_SEP)
+ if len(path) > 2:
+ return None
named = resolve_object_ref(root, ref[:dot], _package_of_key(declaring.resolution_key()))
if not isinstance(named, MetaObject):
return None
if host is not None and not _is_self_or_ancestor(named, host):
return None
# ADR-0039: resolving fields(), so a field inherited through extends is found.
- member = ref[dot + len(CHILD_REF_SEP):]
- field = next((f for f in (host if host is not None else named).fields() if f.name == member), None)
+ field = next((f for f in (host if host is not None else named).fields() if f.name == path[0]), None)
+ if field is not None and len(path) == 2:
+ field = flattened_member_of(field, path[1])
return None if field is None else (named, field)
+def is_flattened_field(field: MetaData) -> bool:
+ """True for a ``field.object`` whose ``@storage`` is ``flattened`` (ADR-0039: resolving)."""
+ return field.sub_type == FIELD_SUBTYPE_OBJECT and field.get_meta_attr(FIELD_ATTR_STORAGE) == STORAGE_FLATTENED
+
+
+def flattened_member_of(embedding: MetaField, name: str) -> MetaField | None:
+ """FR-044 R12: member *name* of the value object a flattened ``field.object`` embeds
+ (resolving, so an inherited member counts). ``None`` when the field is not flattened,
+ names no value object, or the value object has no such member."""
+ if not is_flattened_field(embedding):
+ return None
+ value_object = ref_target(embedding, FIELD_ATTR_OBJECT_REF)
+ if not isinstance(value_object, MetaObject):
+ return None
+ return next((f for f in value_object.fields() if f.name == name), None)
+
+
def resolve_dimension_of(
dim: MetaDimension, from_: MetaObject, root: MetaRoot
) -> tuple[MetaObject, MetaField] | None:
diff --git a/server/python/tests/test_report_shape.py b/server/python/tests/test_report_shape.py
index b1db6e3be5..ee756311ce 100644
--- a/server/python/tests/test_report_shape.py
+++ b/server/python/tests/test_report_shape.py
@@ -877,3 +877,25 @@ def test_agg_any_all_without_of_derive_nullable_boolean_rows_unless_defaulted()
("allSlow", "boolean", True),
("anySlowFailure", "boolean", False),
]
+
+
+def test_a_value_object_member_derives_the_members_type() -> None:
+ """FR-044 R12: ``Payment.amount.currency`` and ``Payment.amount.amount`` read Money's
+ members, so the derived fields take the member's subtype, nullability and type source.
+ The same rows as the TypeScript report-shape derivation of this fixture."""
+ path = CORPUS.parent / "conformance" / "reporting-value-object-members" / "input" / "meta.billing.json"
+ root = _load(InMemoryStringSource(path.read_text(encoding="utf-8"), "meta.billing.json"))
+ rows = [
+ f"{f.name} {f.sub_type} {f.required} "
+ + ("-" if f.type_source is None else f"{f.type_source.parent.name}.{f.type_source.name}")
+ for f in report_shape(_object(root, "RevenueByMonth"), root).fields
+ ]
+ assert rows == [
+ "currency string True Money.currency",
+ "kind string False Payment.kind",
+ "receivedOnMonth date True -",
+ "revenue decimal False -",
+ "largest decimal True Money.amount",
+ "averagePayment decimal False -",
+ "payments long True -",
+ ]
diff --git a/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts b/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts
index cd7b4a1b7a..4d2b62c1bd 100644
--- a/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts
+++ b/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts
@@ -42,6 +42,8 @@ import {
stripPackage,
type MetaData,
REPORTING_ATTR_VIA,
+ REPORTING_ATTR_OF,
+ resolveDimensionOf,
OBJECT_REPORT_ATTR_SPINE,
type MetaDimension,
type MetaField,
@@ -87,6 +89,7 @@ import {
measureMembers,
memberKey,
segmentSpec,
+ valueObjectMemberError,
type MemberContext,
} from "./cube-members.js";
import {
@@ -510,11 +513,18 @@ class CubeModelBuilder {
return true;
}
+ /** A dimension's `@of` field; refused when it names a value-object member (FR-044 R12). */
+ private memberFreeDimensionField(draft: CubeDraft, dim: MetaDimension, where: string): MetaField {
+ const ref = resolveDimensionOf(dim, draft.entity, this.root);
+ if (ref === undefined) throw new Error(`${where} @of '${dim.of() ?? ""}' does not resolve.`);
+ if (ref.embedding !== undefined) throw valueObjectMemberError(where, authoredText(dim, REPORTING_ATTR_OF) ?? dim.of() ?? "");
+ return ref.field;
+ }
+
/** A dimension over the owning cube's own column (no `@via`). */
private ownDimension(draft: CubeDraft, dim: MetaDimension, where: string): CubeDimensionSpec {
// A dimension without @via is about `from`'s own rows: the field is read from `from`.
- const of = dimensionOfField(dim, draft.entity, this.root);
- if (of === undefined) throw new Error(`${where} @of '${dim.of() ?? ""}' does not resolve.`);
+ const of = this.memberFreeDimensionField(draft, dim, where);
const { sql, type } = this.columnOf(of, where);
// An attribute and a time dimension over one field have the same Table C SQL, so either
// serves a @via that reaches the field.
@@ -680,8 +690,7 @@ class CubeModelBuilder {
}
}
// With @via, the field is read from the entity its @of names.
- const of = dimensionOfField(dim, draft.entity, this.root);
- if (of === undefined) throw new Error(`${where} @of '${dim.of() ?? ""}' does not resolve.`);
+ const of = this.memberFreeDimensionField(draft, dim, where);
const { type } = this.columnOf(of, where);
const member = this.reachedMember(joined, of, label);
draft.viaMembers.set(dim, member);
diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-errors.ts b/server/typescript/packages/codegen-ts/src/cube/cube-errors.ts
index b5813be0c9..12468b9a29 100644
--- a/server/typescript/packages/codegen-ts/src/cube/cube-errors.ts
+++ b/server/typescript/packages/codegen-ts/src/cube/cube-errors.ts
@@ -11,6 +11,8 @@ export const ERR_CUBE_INVALID_NAME = "ERR_CUBE_INVALID_NAME";
export const ERR_CUBE_MEMBER_COLLISION = "ERR_CUBE_MEMBER_COLLISION";
export const ERR_CUBE_NAME_COLLISION = "ERR_CUBE_NAME_COLLISION";
export const ERR_CUBE_UNESCAPABLE_LITERAL = "ERR_CUBE_UNESCAPABLE_LITERAL";
+/** FR-044 R12: an `@of` names a value-object member, which the exporter does not map. */
+export const ERR_CUBE_VALUE_OBJECT_MEMBER = "ERR_CUBE_VALUE_OBJECT_MEMBER";
/** The generator's dialect is not one it writes Cube SQL for (postgres, mysql). */
export const ERR_CUBE_UNSUPPORTED_DIALECT = "ERR_CUBE_UNSUPPORTED_DIALECT";
@@ -25,6 +27,7 @@ export const CUBE_ERROR_CODES = [
ERR_CUBE_NAME_COLLISION,
ERR_CUBE_UNESCAPABLE_LITERAL,
ERR_CUBE_UNSUPPORTED_DIALECT,
+ ERR_CUBE_VALUE_OBJECT_MEMBER,
] as const;
export type CubeErrorCode = (typeof CUBE_ERROR_CODES)[number];
diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
index 5971c61a25..6ad42d59f7 100644
--- a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
+++ b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
@@ -40,7 +40,21 @@ import { intValueMapOf } from "../enum-meta.js";
import { sourceColumnNameFor, type ExtractContext } from "../projection/extract-view-spec.js";
import { ratioOperand, resolveAggregate } from "../projection/report-resolve.js";
import { cond, mysqlTupleCount, resolveReportFilter, type SqlRenderer } from "../projection/report-sql.js";
-import { CubeModelError, ERR_CUBE_UNMAPPABLE_DIMENSION } from "./cube-errors.js";
+import { CubeModelError, ERR_CUBE_UNMAPPABLE_DIMENSION, ERR_CUBE_VALUE_OBJECT_MEMBER } from "./cube-errors.js";
+
+/**
+ * FR-044 R12: a report reads a member of a flattened value object only beside a grouping by the
+ * value object's other members (its currency), and Cube cannot hold a query to that, so the
+ * exporter refuses every `@of` that names a member rather than let Cube add amounts across units.
+ */
+export function valueObjectMemberError(where: string, of: string): CubeModelError {
+ return new CubeModelError(
+ ERR_CUBE_VALUE_OBJECT_MEMBER,
+ `${where} @of '${of}' names a member of a value object, which the Cube exporter does not map: a Cube ` +
+ `query could sum it without grouping by the value object's unit member (a currency). Read it through a ` +
+ `report with a view source, or remove the member from the exported entity.`,
+ );
+}
import type {
CubeDialect,
CubeDimensionSpec,
@@ -223,8 +237,9 @@ function aggregateSpec(
const d = mc.dialect;
const renderer = cubeSqlRenderer(where);
// The view's own resolution: @of read from the cube's entity, then its condition.
- const { agg, distinct, fields, condition } = resolveAggregate(m, entity, mc.root, CUBE_SELF, mc.extract, where);
- const cols = fields.map((f) => cubeColumn(sourceColumnNameFor(f, mc.extract), d, renderer));
+ const { agg, distinct, columns, condition, readsMember } = resolveAggregate(m, entity, mc.root, CUBE_SELF, mc.extract, where);
+ if (readsMember) throw valueObjectMemberError(where, m.ofColumns().join(", "));
+ const cols = columns.map((c) => cubeColumn(c, d, renderer));
const c = condition === undefined ? undefined : cond(condition, d, renderer);
// Only @agg any / all may omit @of (rule M0); they are handled below.
if (cols.length === 0 && agg !== AGG_ANY && agg !== AGG_ALL) throw new Error(`${where}: has no @of.`);
diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-report-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-report-spec.ts
index 17139e2d52..7373abca93 100644
--- a/server/typescript/packages/codegen-ts/src/projection/extract-report-spec.ts
+++ b/server/typescript/packages/codegen-ts/src/projection/extract-report-spec.ts
@@ -13,6 +13,7 @@ import {
FIELD_SUBTYPE_INT,
FIELD_SUBTYPE_LONG,
measureDerivedSubType,
+ resolveDimensionOf,
reportShape,
reportSpine,
reportSpineHops,
@@ -32,14 +33,13 @@ import {
pathsToJoins,
projectionViewName,
shortAliasFor,
- sourceColumnNameFor,
walkViaPath,
type ExtractContext,
type Path,
} from "./extract-view-spec.js";
import {
authoredText,
- dimensionOfField,
+ reportColumnName,
ratioOperand,
resolveAggregate,
resolveDimensionViaPath,
@@ -74,7 +74,7 @@ function aggregateOf(
ctx: ExtractContext,
): ReportAggregate {
const where = `report '${report.name}' measure '${measure.name}'`;
- const { agg, distinct, fields, condition } = resolveAggregate(measure, from, root, baseAlias, ctx, where);
+ const { agg, distinct, fields, columns, condition } = resolveAggregate(measure, from, root, baseAlias, ctx, where);
const cast = castFor(agg, fields[0]);
// Table D: `@default` is read through the measure itself, so a ratio operand that the report
// does not list still carries its own.
@@ -89,7 +89,7 @@ function aggregateOf(
return {
agg,
distinct,
- refs: fields.map((f) => `${baseAlias}.${sourceColumnNameFor(f, ctx)}`),
+ refs: columns.map((c) => `${baseAlias}.${c}`),
...(condition !== undefined ? { filter: condition } : {}),
...(cast !== undefined ? { cast } : {}),
...(defaultValue !== undefined ? { defaultValue } : {}),
@@ -239,14 +239,14 @@ export function extractReportSpec(report: MetaObject, root: MetaRoot, ctx: Extra
const dbColAlias = columnNameFromField(f.name, ctx.columnNamingStrategy);
if (f.role === "dimension") {
const dim = f.dimension;
- // A time dimension below the hour grain carries no typeSource; resolve by reportShape's rule.
- const of = f.typeSource ?? (dim === undefined ? undefined : dimensionOfField(dim, from, root));
+ // Resolved by reportShape's rule; a member of a flattened value object reads its own column.
+ const of = dim === undefined ? undefined : resolveDimensionOf(dim, from, root);
if (of === undefined) throw new Error(`report '${report.name}': dimension '${f.name}' @of does not resolve.`);
const path = pathOf.get(f);
const alias = path === undefined ? baseAlias : aliasAtEndOf(path, joins);
- const ref = `${alias}.${sourceColumnNameFor(of, ctx)}`;
+ const ref = `${alias}.${reportColumnName(of, ctx)}`;
if (f.grain !== undefined) {
- return { kind: "timeDimension", fieldName: f.name, dbColAlias, ref, grain: f.grain, temporal: temporalOf(of) };
+ return { kind: "timeDimension", fieldName: f.name, dbColAlias, ref, grain: f.grain, temporal: temporalOf(of.field) };
}
return { kind: "dimension", fieldName: f.name, dbColAlias, ref };
}
diff --git a/server/typescript/packages/codegen-ts/src/projection/report-resolve.ts b/server/typescript/packages/codegen-ts/src/projection/report-resolve.ts
index 2d64e87244..f0a688a7eb 100644
--- a/server/typescript/packages/codegen-ts/src/projection/report-resolve.ts
+++ b/server/typescript/packages/codegen-ts/src/projection/report-resolve.ts
@@ -15,8 +15,10 @@ import {
reportingViaHops,
resolveDimensionOf,
refTarget,
- resolveReportingFieldRef,
+ resolveReportingColumnRef,
+ resolveFlattenedColumnName,
type MeasureAgg,
+ type ReportingColumnRef,
type MetaData,
REPORTING_ATTR_VIA,
type MetaDimension,
@@ -25,7 +27,7 @@ import {
type MetaObject,
type MetaRoot,
} from "@metaobjectsdev/metadata";
-import { packageOf, walkViaPath, type ExtractContext, type Path } from "./extract-view-spec.js";
+import { packageOf, sourceColumnNameFor, walkViaPath, type ExtractContext, type Path } from "./extract-view-spec.js";
import { andOf, declared, resolveReportFilter, segmentClause } from "./report-sql.js";
import type { ViewFilterClause } from "./view-spec.js";
@@ -46,6 +48,16 @@ export function dimensionOfField(dim: MetaDimension, from: MetaObject, root: Met
return resolveDimensionOf(dim, from, root)?.field;
}
+/**
+ * The column an `@of` reference reads: the field's own, or for `Entity.field.member` (FR-044
+ * R12) the member's flattened column, spelled by core naming as `meta migrate` creates it.
+ */
+export function reportColumnName(ref: Pick, ctx: ExtractContext): string {
+ return ref.embedding === undefined
+ ? sourceColumnNameFor(ref.field, ctx)
+ : resolveFlattenedColumnName(ref.embedding, ref.field, ctx.columnNamingStrategy);
+}
+
/**
* Why a dimension's `@via` (or a report's `@spine`, `attr`) walk stopped at `hop`: the error
* names the hop, the entity it was looked up on, and what the model is missing. The loader
@@ -124,8 +136,12 @@ export function resolveDimensionViaPath(
export interface ResolvedAggregate {
readonly agg: MeasureAgg;
readonly distinct: boolean;
- /** The `@of` fields, read from `from`: one, or a tuple. */
+ /** The `@of` fields, read from `from`: one, or a tuple. A value-object member is the member field. */
readonly fields: readonly MetaField[];
+ /** The column each of `fields` reads (a member's is its flattened column). */
+ readonly columns: readonly string[];
+ /** True when an `@of` names a value-object member (FR-044 R12). */
+ readonly readsMember: boolean;
/** Its `@segment` filter, then its `@filter`, ANDed, over `alias`. Absent when neither. */
readonly condition?: ViewFilterClause;
}
@@ -143,16 +159,26 @@ export function resolveAggregate(
// The same rule as reportShape: the entity half resolves in the DECLARING entity's package,
// and the column is read from `from` (a measure aggregates `from`'s own rows).
const declaring = reportingMemberOwner(measure, from);
- const fields = measure.ofColumns().map((ref) => {
- const f = resolveReportingFieldRef(ref, declaring, root, from);
- if (f === undefined) throw new Error(`${where}: @of '${ref}' does not resolve.`);
- return f;
+ const refs = measure.ofColumns().map((ref) => {
+ const r = resolveReportingColumnRef(ref, declaring, root, from);
+ if (r === undefined) throw new Error(`${where}: @of '${ref}' does not resolve.`);
+ return r;
});
+ const fields = refs.map((r) => r.field);
+ const columns = refs.map((r) => reportColumnName(r, ctx));
+ const readsMember = refs.some((r) => r.embedding !== undefined);
const condition = andOf([
segmentClause(measure.segmentName(), from, alias, ctx, where),
resolveReportFilter(measure.filter(), from, alias, ctx, `${where} @filter`),
]);
- return { agg, distinct: measure.distinct(), fields, ...(condition !== undefined ? { condition } : {}) };
+ return {
+ agg,
+ distinct: measure.distinct(),
+ fields,
+ columns,
+ readsMember,
+ ...(condition !== undefined ? { condition } : {}),
+ };
}
/** A ratio operand: a `measure.aggregate` declared on (or inherited by) `from`. */
diff --git a/server/typescript/packages/codegen-ts/test/projection/report-value-object-members.test.ts b/server/typescript/packages/codegen-ts/test/projection/report-value-object-members.test.ts
new file mode 100644
index 0000000000..131b012cb9
--- /dev/null
+++ b/server/typescript/packages/codegen-ts/test/projection/report-value-object-members.test.ts
@@ -0,0 +1,48 @@
+// FR-044 R12 — a report over a member of a flattened value object reads the member's own
+// column, the one `meta migrate` creates (`amount_amount`, `amount_currency`), in every dialect.
+// The model is the shared conformance fixture, so the loader rules and the lowering see one model.
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { InMemoryStringSource, MetaDataLoader } from "@metaobjectsdev/metadata";
+import { buildReportViews } from "../../src/projection/build-projection-views.js";
+import { buildCubeModel } from "../../src/cube/build-cube-model.js";
+
+const FIXTURE = join(
+ import.meta.dir,
+ "../../../../../../fixtures/conformance/reporting-value-object-members/input/meta.billing.json",
+);
+
+async function load() {
+ const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(readFileSync(FIXTURE, "utf8"))]);
+ expect(errors).toEqual([]);
+ return root;
+}
+
+async function views(dialect: "postgres" | "sqlite"): Promise> {
+ const out: Record = {};
+ for (const v of buildReportViews(await load(), { dialect })) out[v.name] = v.sql;
+ return out;
+}
+
+describe("FR-044 R12: value-object members in a report view", () => {
+ for (const dialect of ["postgres", "sqlite"] as const) {
+ test(`${dialect}: sums the amount column and groups by the currency column`, async () => {
+ const sql = (await views(dialect))["v_revenuebymonth"] ?? "";
+ expect(sql).toContain(`"amount_currency" AS "currency"`);
+ expect(sql).toContain(`SUM(p."amount_amount")`);
+ expect(sql).toContain(`MAX(p."amount_amount")`);
+ expect(sql).toMatch(/GROUP BY[^;]*"amount_currency"/);
+ });
+ }
+
+ test("a distinct count over a member reads its column", async () => {
+ const sql = (await views("postgres"))["v_currencymix"] ?? "";
+ expect(sql).toContain(`COUNT(DISTINCT p."amount_currency")`);
+ });
+
+ test("the Cube exporter refuses a member rather than let a query add amounts across currencies", async () => {
+ const root = await load();
+ expect(() => buildCubeModel(root, { dialect: "postgres" })).toThrow(/ERR_CUBE_VALUE_OBJECT_MEMBER/);
+ });
+});
diff --git a/server/typescript/packages/metadata/src/core/reporting/report-shape.ts b/server/typescript/packages/metadata/src/core/reporting/report-shape.ts
index e6231bf63f..2b39d44097 100644
--- a/server/typescript/packages/metadata/src/core/reporting/report-shape.ts
+++ b/server/typescript/packages/metadata/src/core/reporting/report-shape.ts
@@ -12,6 +12,10 @@ import { CHILD_REF_SEPARATOR, PACKAGE_SEPARATOR } from "../../shared/structural.
import type { MetaObject } from "../object/meta-object.js";
import type { MetaField } from "../field/meta-field.js";
import {
+ FIELD_ATTR_OBJECT_REF,
+ FIELD_ATTR_STORAGE,
+ FIELD_SUBTYPE_OBJECT,
+ STORAGE_FLATTENED,
FIELD_SUBTYPE_BOOLEAN,
FIELD_SUBTYPE_CURRENCY,
FIELD_SUBTYPE_DATE,
@@ -138,7 +142,7 @@ export function resolveDimensionOf(
dim: MetaDimension,
from: MetaObject,
root: MetaRoot,
-): { readonly named: MetaObject; readonly field: MetaField } | undefined {
+): ReportingColumnRef | undefined {
const of = dim.of() ?? "";
const via = dim.via();
if (via === undefined) return resolveReportingFieldRefNamed(of, reportingMemberOwner(dim, from), root, from);
@@ -179,16 +183,60 @@ function resolveReportingFieldRefNamed(
declaring: MetaData,
root: MetaRoot,
host?: MetaObject,
-): { readonly named: MetaObject; readonly field: MetaField } | undefined {
- // `Entity.field`; a package qualifier uses `::`, so the member separator is the LAST dot.
- const dot = ref.lastIndexOf(CHILD_REF_SEPARATOR);
+): ReportingColumnRef | undefined {
+ // `Entity.field` or `Entity.field.member`; a package qualifier uses `::` and holds no `.`, so
+ // the owner ends at the first `.` after the last `::`.
+ const lastSep = ref.lastIndexOf(PACKAGE_SEPARATOR);
+ const dot = ref.indexOf(CHILD_REF_SEPARATOR, lastSep === -1 ? 0 : lastSep + PACKAGE_SEPARATOR.length);
if (dot <= 0) return undefined;
+ const path = ref.slice(dot + 1).split(CHILD_REF_SEPARATOR);
+ if (path.length > 2) return undefined;
const named = resolveObjectRef(root, ref.slice(0, dot), packageOfKey(declaring.resolutionKey())).node;
if (!isMetaObject(named)) return undefined;
if (host !== undefined && !isSelfOrAncestor(named, host)) return undefined;
// ADR-0039: resolving, so a field inherited through extends is found.
- const field = (host ?? named).fields().find((f) => f.name === ref.slice(dot + 1));
- return field === undefined ? undefined : { named, field };
+ const field = (host ?? named).fields().find((f) => f.name === path[0]);
+ if (field === undefined) return undefined;
+ if (path[1] === undefined) return { named, field };
+ const member = flattenedMemberOf(field, path[1]);
+ return member === undefined ? undefined : { named, field: member, embedding: field };
+}
+
+/** A resolved `@of` column: the field read, and for `Entity.field.member` the flattened
+ * `field.object` that embeds it (its column is the member's flattened column). */
+export interface ReportingColumnRef {
+ readonly named: MetaObject;
+ readonly field: MetaField;
+ readonly embedding?: MetaField;
+}
+
+/** True for a `field.object` whose `@storage` is `flattened` (ADR-0039: resolving read). */
+export function isFlattenedField(field: MetaData): boolean {
+ return field.subType === FIELD_SUBTYPE_OBJECT && field.attr(FIELD_ATTR_STORAGE) === STORAGE_FLATTENED;
+}
+
+/**
+ * FR-044 R12: member `name` of the value object a flattened `field.object` embeds, read with the
+ * resolving accessor so a member the value object inherits counts. Undefined when `embedding`
+ * is not flattened, names no value object, or the value object has no such member.
+ */
+export function flattenedMemberOf(embedding: MetaField, name: string): MetaField | undefined {
+ if (!isFlattenedField(embedding)) return undefined;
+ const valueObject = refTarget(embedding, FIELD_ATTR_OBJECT_REF);
+ return isMetaObject(valueObject) ? valueObject.fields().find((f) => f.name === name) : undefined;
+}
+
+/**
+ * {@link resolveReportingFieldRef}, keeping the embedding field of an `Entity.field.member`
+ * reference, which a lowering needs to name the member's column.
+ */
+export function resolveReportingColumnRef(
+ ref: string,
+ declaring: MetaData,
+ root: MetaRoot,
+ host?: MetaObject,
+): ReportingColumnRef | undefined {
+ return resolveReportingFieldRefNamed(ref, declaring, root, host);
}
/**
diff --git a/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts b/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts
index f8c9c5b39f..6ed16e8cdf 100644
--- a/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts
+++ b/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts
@@ -21,7 +21,7 @@ export const REPORTING_DEFINITION: ProviderDefinition = {
"name": "of",
"min": 1,
"max": 1,
- "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via)."
+ "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own."
},
{
"type": "attr",
@@ -45,7 +45,7 @@ export const REPORTING_DEFINITION: ProviderDefinition = {
"name": "of",
"min": 1,
"max": 1,
- "description": "Dotted Entity.field reference naming the date or timestamp column."
+ "description": "Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object."
},
{
"type": "attr",
@@ -104,7 +104,7 @@ export const REPORTING_DEFINITION: ProviderDefinition = {
"isArray": true,
"min": 0,
"max": 1,
- "description": "Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows."
+ "description": "Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows."
},
{
"type": "attr",
diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts
index b2880f7827..ad4284c58c 100644
--- a/server/typescript/packages/metadata/src/index.ts
+++ b/server/typescript/packages/metadata/src/index.ts
@@ -65,6 +65,9 @@ export {
reportingMemberOwner,
reportingViaHops,
resolveReportingFieldRef,
+ resolveReportingColumnRef,
+ flattenedMemberOf,
+ type ReportingColumnRef,
resolveDimensionOf,
type ReportField,
type ReportFieldRole,
diff --git a/server/typescript/packages/metadata/src/loader/reporting-validation.ts b/server/typescript/packages/metadata/src/loader/reporting-validation.ts
index 0fa6a949c5..6828096844 100644
--- a/server/typescript/packages/metadata/src/loader/reporting-validation.ts
+++ b/server/typescript/packages/metadata/src/loader/reporting-validation.ts
@@ -59,6 +59,7 @@ import {
FIELD_SUBTYPE_DATE,
FIELD_SUBTYPE_TIMESTAMP,
FIELD_ATTR_OBJECT_REF,
+ FIELD_ATTR_STORAGE,
} from "../core/field/field-constants.js";
import {
IDENTITY_SUBTYPE_REFERENCE,
@@ -103,7 +104,7 @@ import {
import { MetaDimension } from "../core/reporting/meta-dimension.js";
import { MetaMeasure } from "../core/reporting/meta-measure.js";
import { MetaSegment } from "../core/reporting/meta-segment.js";
-import { measureResultSubType } from "../core/reporting/report-shape.js";
+import { isFlattenedField, measureResultSubType } from "../core/reporting/report-shape.js";
import {
reportDerivedFieldName,
reportDimensionItems,
@@ -246,6 +247,53 @@ function fieldOf(obj: MetaData, name: string): MetaData | undefined {
return childOfType(obj, TYPE_FIELD, name);
}
+/**
+ * R12 — the column an `@of` path names on `entity`: `field`, or `field.member` for a member of a
+ * value object stored flattened (one column per member). Reports the first failure through
+ * `err` and returns undefined. `fieldMissing` words the message for an absent `field`.
+ */
+function ofColumn(
+ entity: MetaData,
+ path: readonly string[],
+ item: string,
+ err: (message: string) => void,
+ fieldMissing: () => string,
+): MetaData | undefined {
+ const field = fieldOf(entity, path[0]!);
+ if (field === undefined) {
+ err(fieldMissing());
+ return undefined;
+ }
+ const memberName = path[1];
+ if (memberName === undefined) return field;
+ const valueObject = field.subType === FIELD_SUBTYPE_OBJECT ? refTargetOf(field) : undefined;
+ if (valueObject === undefined) {
+ err(`@of '${item}' names member '${memberName}' of '${path[0]!}', a field.${field.subType} with no value object.`);
+ return undefined;
+ }
+ if (!isFlattenedField(field)) {
+ const storage = field.attr(FIELD_ATTR_STORAGE);
+ err(
+ `@of '${item}' names a member of '${path[0]!}', whose value object is stored as ` +
+ `${typeof storage === "string" ? storage : "jsonb (the default)"}. A report reads a member only under ` +
+ `@storage: flattened, where the member has a column of its own.`,
+ );
+ return undefined;
+ }
+ const member = fieldOf(valueObject, memberName);
+ if (member === undefined) {
+ err(`@of '${item}' names no member '${memberName}' on value object '${valueObject.resolutionKey()}'.`);
+ return undefined;
+ }
+ return member;
+}
+
+/** The object a field's `@objectRef` resolves to (ADR-0059 R3 package rule), when it is one. */
+function refTargetOf(field: MetaData): MetaData | undefined {
+ const target = refTarget(field, FIELD_ATTR_OBJECT_REF);
+ return target !== undefined && target.type === TYPE_OBJECT ? target : undefined;
+}
+
function isPlainObject(v: unknown): v is Record {
return typeof v === "object" && v !== null && !Array.isArray(v);
}
@@ -382,8 +430,8 @@ function checkDimension(ctx: MemberCtx, dim: MetaDimension): void {
const of = dim.of();
if (of === undefined) return; // missing @of is ERR_MISSING_REQUIRED_ATTR (attr schema pass)
const parts = splitDotted(of);
- if (parts === undefined || parts.path.length !== 1) {
- err(`@of '${of}' must be Entity.field.`);
+ if (parts === undefined || parts.path.length > 2) {
+ err(`@of '${of}' must be Entity.field or Entity.field.member.`);
return;
}
// D1 — after @via, a bare Owner resolves in the package of the entity @via reaches: the path
@@ -409,17 +457,13 @@ function checkDimension(ctx: MemberCtx, dim: MetaDimension): void {
// the host IS the checked entity: a dimension inherited from a base is checked against the
// inheritor's own (possibly overriding) field.
const lookup = via === undefined ? ofEntity : named!;
- const field = fieldOf(lookup, fieldName);
- if (field === undefined) {
- const declaredOnTerminal = lookup !== ofEntity && fieldOf(ofEntity, fieldName) !== undefined;
- err(
- declaredOnTerminal
- ? `@of '${of}' names no field '${fieldName}' on '${shown(ctx, lookup)}': only '${shown(ctx, ofEntity)}', ` +
- `the entity @via reaches, declares it. Name it '${ofEntity.name}.${fieldName}'.`
- : `@of '${of}' names no field '${fieldName}' on '${shown(ctx, lookup)}'.`,
- );
- return;
- }
+ const field = ofColumn(lookup, parts.path, of, err, () =>
+ lookup !== ofEntity && fieldOf(ofEntity, fieldName) !== undefined
+ ? `@of '${of}' names no field '${fieldName}' on '${shown(ctx, lookup)}': only '${shown(ctx, ofEntity)}', ` +
+ `the entity @via reaches, declares it. Name it '${ofEntity.name}.${fieldName}'.`
+ : `@of '${of}' names no field '${fieldName}' on '${shown(ctx, lookup)}'.`,
+ );
+ if (field === undefined) return;
// D5 — a dimension groups by a scalar. A field.object (or a field carrying @objectRef) is a JSON
// document: no port serves a report over one, and a document is not a value to group rows by.
@@ -668,8 +712,8 @@ function checkAggregateColumns(
const fields: MetaData[] = [];
for (const item of columns) {
const parts = splitDotted(item);
- if (parts === undefined || parts.path.length !== 1) {
- err(`@of '${item}' must be Entity.field.`);
+ if (parts === undefined || parts.path.length > 2) {
+ err(`@of '${item}' must be Entity.field or Entity.field.member.`);
return undefined;
}
const named = resolveObjectRef(ctx.root, parts.owner, pkgOf(ctx.declaring)).node;
@@ -680,11 +724,14 @@ function checkAggregateColumns(
);
return undefined;
}
- const field = fieldOf(ctx.host, parts.path[0]!);
- if (field === undefined) {
- err(`@of '${item}' names no field '${parts.path[0]!}' on '${ctx.declaring.resolutionKey()}'.`);
- return undefined;
- }
+ const field = ofColumn(
+ ctx.host,
+ parts.path,
+ item,
+ err,
+ () => `@of '${item}' names no field '${parts.path[0]!}' on '${ctx.declaring.resolutionKey()}'.`,
+ );
+ if (field === undefined) return undefined;
// M10 — a measure aggregates scalars. A field.object (or a field carrying @objectRef) is a JSON
// document, which no port aggregates in a report.
if (field.subType === FIELD_SUBTYPE_OBJECT || objectRefOf(field) !== undefined) {
@@ -998,6 +1045,9 @@ function checkReport(root: MetaData, report: MetaData, sink: ErrorSink): void {
if (measureName !== undefined) claim(measureName, `measure '${measureName}'`);
}
+ // R12 — amounts in different units are never combined.
+ checkValueObjectUnits(report, from, err);
+
// R7 — @segment names a segment of @from.
const segment = report.attr(OBJECT_REPORT_ATTR_SEGMENT);
if (typeof segment === "string" && childOfType(from, TYPE_SEGMENT, segment) === undefined) {
@@ -1055,6 +1105,56 @@ function checkReport(root: MetaData, report: MetaData, sink: ErrorSink): void {
if (isPlainObject(filter)) checkFilter(filter, from, fromKey, label, report, "", sink);
}
+/**
+ * R12 — a measure that sums, averages or takes the min or max of a numeric member of a flattened
+ * value object (Money's amount) combines rows only when the report groups by each non-numeric
+ * member of that value object (Money's currency): otherwise amounts in different currencies are
+ * added. Checked for every listed measure.aggregate and every operand of a listed ratio; the
+ * grouping is an attribute dimension of @from, with no @via, whose @of names the same
+ * `field.member`. A measure whose @of fails M1 is skipped (M1 reports it).
+ */
+function checkValueObjectUnits(report: MetaData, from: MetaData, err: (message: string) => void): void {
+ const grouped = new Set();
+ for (const item of reportDimensionItems(report)) {
+ const dim = childOfType(from, TYPE_DIMENSION, item.name);
+ if (!(dim instanceof MetaDimension) || dim.isTime() || dim.via() !== undefined) continue;
+ const path = splitDotted(dim.of() ?? "")?.path;
+ if (path?.length === 2) grouped.add(path.join(CHILD_REF_SEPARATOR));
+ }
+ const checked = new Set();
+ for (const item of reportMeasureNames(report)) {
+ const listed = childOfType(from, TYPE_MEASURE, item.slice(item.lastIndexOf(CHILD_REF_SEPARATOR) + 1));
+ if (!(listed instanceof MetaMeasure)) continue;
+ const aggregates = listed.isRatio()
+ ? [listed.numerator(), listed.denominator()].map((n) => (n === undefined ? undefined : childOfType(from, TYPE_MEASURE, n)))
+ : [listed];
+ for (const m of aggregates) {
+ if (!(m instanceof MetaMeasure) || m.subType !== MEASURE_SUBTYPE_AGGREGATE || checked.has(m)) continue;
+ checked.add(m);
+ const agg = m.agg();
+ if (agg !== AGG_SUM && agg !== AGG_AVG && agg !== AGG_MIN && agg !== AGG_MAX) continue;
+ const of = m.ofColumns()[0] ?? "";
+ const parts = splitDotted(of);
+ if (parts?.path.length !== 2) continue;
+ const [fieldName, memberName] = parts.path as [string, string];
+ const field = fieldOf(from, fieldName);
+ const valueObject = field !== undefined && isFlattenedField(field) ? refTargetOf(field) : undefined;
+ const member = valueObject === undefined ? undefined : fieldOf(valueObject, memberName);
+ if (valueObject === undefined || member === undefined || !NUMERIC_FIELD_SUBTYPES.includes(member.subType)) continue;
+ // ADR-0039: resolving — a unit member the value object inherits qualifies its amounts too.
+ for (const unit of valueObject.children().filter((c) => c.type === TYPE_FIELD)) {
+ if (NUMERIC_FIELD_SUBTYPES.includes(unit.subType) || grouped.has(`${fieldName}.${unit.name}`)) continue;
+ err(
+ `: measure '${m.name}' takes @agg '${agg}' of '${of}', a member of value object ` +
+ `'${valueObject.resolutionKey()}', but the report does not group by its member '${unit.name}', so ` +
+ `amounts with different '${unit.name}' values would be combined. List an attribute dimension of ` +
+ `@from whose @of is '${parts.owner}.${fieldName}.${unit.name}'.`,
+ );
+ }
+ }
+ }
+}
+
/**
* R3 for one `@measures` item (bare `name` or dotted `Entity.name`). Returns
* the measure's name when it is a measure of @from (for R6), else reports
diff --git a/spec/metamodel/reporting.json b/spec/metamodel/reporting.json
index 98c0bd24f0..5eedaf0721 100644
--- a/spec/metamodel/reporting.json
+++ b/spec/metamodel/reporting.json
@@ -5,14 +5,14 @@
"description": "A named group-by attribute of the entity that declares it (FR-044). Groups report rows by a column value as-is. @of names Entity.field: the owning entity, or the @via terminal. @via may follow only to-one hops, so grouping by a related row's column can never multiply the measured rows.",
"whenToUse": "A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports.",
"children": [
- { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via)." },
+ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own." },
{ "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference." }
] },
{ "type": "dimension", "subType": "time",
"description": "A named time dimension (FR-044): groups report rows by a date or timestamp column truncated to a grain. @of names a field.date or field.timestamp. Weeks start on Monday (ISO-8601) in every lowering. A report names it as 'dimension:grain' and the derived report field is (e.g. purchasedAtDay).",
"whenToUse": "Per-day, per-week or per-month series on a dashboard.",
"children": [
- { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column." },
+ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object." },
{ "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path, as on dimension.attribute." },
{ "type": "attr", "subType": "string", "name": "grains", "isArray": true, "min": 1, "max": 1, "allowedValues": ["hour", "day", "week", "month", "quarter", "year"], "description": "The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date." }
] },
@@ -21,7 +21,7 @@
"whenToUse": "A number a dashboard shows: revenue, purchases, distinct buyers, last activity.",
"children": [
{ "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all"], "description": "The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment." },
- { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." },
+ { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." },
{ "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Count distinct values. Legal only with @agg: count." },
{ "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: \"-P7D\" }). Combines with @segment by AND." },
{ "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment declared on the same entity. Combines with @filter by AND." },
From 2778e104f3c2a1deb95fef966b8c3bd4c6cd9f99 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Thu, 12 Nov 2026 06:55:08 -0500
Subject: [PATCH 2/6] feat(reporting): add measure.derived arithmetic over
measures and grouped dimensions (FR-044 R13, TypeScript)
---
.../expected-errors.json | 15 +
.../input/meta.studio.json | 279 ++++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 267 +++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 266 +++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 266 +++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 273 +++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 282 ++++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 266 +++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 266 +++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 294 ++++++++++++
.../providers.json | 1 +
.../expected-errors.json | 15 +
.../input/meta.studio.json | 103 +++++
.../providers.json | 1 +
.../reporting-derived-measures/expected.json | 427 ++++++++++++++++++
.../input/meta.studio.json | 419 +++++++++++++++++
.../reporting-derived-measures/providers.json | 1 +
fixtures/metamodel-docs/expected/INDEX.md | 1 +
.../expected/types/dimension.md | 4 +-
.../metamodel-docs/expected/types/measure.md | 18 +-
.../expected-registry.json | 16 +
.../codegen-ts/src/cube/build-cube-model.ts | 7 +-
.../codegen-ts/src/cube/cube-errors.ts | 3 +
.../codegen-ts/src/cube/cube-members.ts | 63 ++-
.../codegen-ts/src/cube/cube-reports.ts | 7 +-
.../src/projection/extract-report-spec.ts | 49 +-
.../src/projection/report-ddl-emit.ts | 78 +++-
.../src/projection/report-resolve.ts | 3 +-
.../codegen-ts/src/projection/report-spec.ts | 19 +-
.../report-derived-measures.test.ts | 98 ++++
.../src/core/reporting/derived-expr.ts | 45 ++
.../src/core/reporting/meta-measure.ts | 17 +-
.../src/core/reporting/report-describe.ts | 29 +-
.../src/core/reporting/report-shape.ts | 3 +-
.../src/core/reporting/reporting-constants.ts | 19 +-
.../reporting-definition.embedded.ts | 16 +
.../typescript/packages/metadata/src/index.ts | 1 +
.../src/loader/reporting-validation.ts | 106 ++++-
.../metadata/test/reporting-registry.test.ts | 12 +-
spec/metamodel/reporting.json | 6 +
56 files changed, 4139 insertions(+), 50 deletions(-)
create mode 100644 fixtures/conformance/error-measure-derived-ambiguous-operand/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-derived-ambiguous-operand/input/meta.studio.json
create mode 100644 fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json
create mode 100644 fixtures/conformance/error-measure-derived-default/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-derived-default/input/meta.studio.json
create mode 100644 fixtures/conformance/error-measure-derived-default/providers.json
create mode 100644 fixtures/conformance/error-measure-derived-malformed-expr/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-derived-malformed-expr/input/meta.studio.json
create mode 100644 fixtures/conformance/error-measure-derived-malformed-expr/providers.json
create mode 100644 fixtures/conformance/error-measure-derived-non-numeric-dimension/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-derived-non-numeric-dimension/input/meta.studio.json
create mode 100644 fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json
create mode 100644 fixtures/conformance/error-measure-derived-non-numeric-measure/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-derived-non-numeric-measure/input/meta.studio.json
create mode 100644 fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json
create mode 100644 fixtures/conformance/error-measure-derived-of-derived/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-derived-of-derived/input/meta.studio.json
create mode 100644 fixtures/conformance/error-measure-derived-of-derived/providers.json
create mode 100644 fixtures/conformance/error-measure-derived-time-dimension/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-derived-time-dimension/input/meta.studio.json
create mode 100644 fixtures/conformance/error-measure-derived-time-dimension/providers.json
create mode 100644 fixtures/conformance/error-measure-derived-unknown-operand/expected-errors.json
create mode 100644 fixtures/conformance/error-measure-derived-unknown-operand/input/meta.studio.json
create mode 100644 fixtures/conformance/error-measure-derived-unknown-operand/providers.json
create mode 100644 fixtures/conformance/error-report-derived-dimension-not-listed/expected-errors.json
create mode 100644 fixtures/conformance/error-report-derived-dimension-not-listed/input/meta.studio.json
create mode 100644 fixtures/conformance/error-report-derived-dimension-not-listed/providers.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-derived-operand/expected-errors.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-derived-operand/input/meta.studio.json
create mode 100644 fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json
create mode 100644 fixtures/conformance/reporting-derived-measures/expected.json
create mode 100644 fixtures/conformance/reporting-derived-measures/input/meta.studio.json
create mode 100644 fixtures/conformance/reporting-derived-measures/providers.json
create mode 100644 server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
create mode 100644 server/typescript/packages/metadata/src/core/reporting/derived-expr.ts
diff --git a/fixtures/conformance/error-measure-derived-ambiguous-operand/expected-errors.json b/fixtures/conformance/error-measure-derived-ambiguous-operand/expected-errors.json
new file mode 100644
index 0000000000..f070582c63
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-ambiguous-operand/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.entity'].children[24]['measure.derived']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-derived-ambiguous-operand/input/meta.studio.json b/fixtures/conformance/error-measure-derived-ambiguous-operand/input/meta.studio.json
new file mode 100644
index 0000000000..064be1016f
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-ambiguous-operand/input/meta.studio.json
@@ -0,0 +1,279 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "hours",
+ "@of": "TimeEntry.hours"
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "hours",
+ "@agg": "max",
+ "@of": "TimeEntry.hours"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "doubled",
+ "@expr": {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "hours"
+ },
+ {
+ "value": 2
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json b/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-ambiguous-operand/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-derived-default/expected-errors.json b/fixtures/conformance/error-measure-derived-default/expected-errors.json
new file mode 100644
index 0000000000..c475706039
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-default/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_UNKNOWN_ATTR",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.entity'].children[22]['measure.derived']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-derived-default/input/meta.studio.json b/fixtures/conformance/error-measure-derived-default/input/meta.studio.json
new file mode 100644
index 0000000000..fcbf488176
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-default/input/meta.studio.json
@@ -0,0 +1,267 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "overtime",
+ "@expr": {
+ "fn": "subtract",
+ "args": [
+ {
+ "field": "totalHours"
+ },
+ {
+ "value": 40
+ }
+ ]
+ },
+ "@default": 0
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-derived-default/providers.json b/fixtures/conformance/error-measure-derived-default/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-default/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-derived-malformed-expr/expected-errors.json b/fixtures/conformance/error-measure-derived-malformed-expr/expected-errors.json
new file mode 100644
index 0000000000..13c2bea516
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-malformed-expr/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.entity'].children[22]['measure.derived']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-derived-malformed-expr/input/meta.studio.json b/fixtures/conformance/error-measure-derived-malformed-expr/input/meta.studio.json
new file mode 100644
index 0000000000..e878118932
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-malformed-expr/input/meta.studio.json
@@ -0,0 +1,266 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "squared",
+ "@expr": {
+ "fn": "power",
+ "args": [
+ {
+ "field": "totalHours"
+ },
+ {
+ "value": 2
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-derived-malformed-expr/providers.json b/fixtures/conformance/error-measure-derived-malformed-expr/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-malformed-expr/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-derived-non-numeric-dimension/expected-errors.json b/fixtures/conformance/error-measure-derived-non-numeric-dimension/expected-errors.json
new file mode 100644
index 0000000000..13c2bea516
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-non-numeric-dimension/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.entity'].children[22]['measure.derived']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-derived-non-numeric-dimension/input/meta.studio.json b/fixtures/conformance/error-measure-derived-non-numeric-dimension/input/meta.studio.json
new file mode 100644
index 0000000000..7808ad5f51
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-non-numeric-dimension/input/meta.studio.json
@@ -0,0 +1,266 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "hoursPerName",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "field": "totalHours"
+ },
+ {
+ "field": "memberName"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json b/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-non-numeric-dimension/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-derived-non-numeric-measure/expected-errors.json b/fixtures/conformance/error-measure-derived-non-numeric-measure/expected-errors.json
new file mode 100644
index 0000000000..24f9e4f326
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-non-numeric-measure/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.entity'].children[23]['measure.derived']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-derived-non-numeric-measure/input/meta.studio.json b/fixtures/conformance/error-measure-derived-non-numeric-measure/input/meta.studio.json
new file mode 100644
index 0000000000..870b3bf0ec
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-non-numeric-measure/input/meta.studio.json
@@ -0,0 +1,273 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "lastWorked",
+ "@agg": "max",
+ "@of": "TimeEntry.workedOn"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "lastWorkedPlusOne",
+ "@expr": {
+ "fn": "add",
+ "args": [
+ {
+ "field": "lastWorked"
+ },
+ {
+ "value": 1
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json b/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-non-numeric-measure/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-derived-of-derived/expected-errors.json b/fixtures/conformance/error-measure-derived-of-derived/expected-errors.json
new file mode 100644
index 0000000000..24f9e4f326
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-of-derived/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.entity'].children[23]['measure.derived']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-derived-of-derived/input/meta.studio.json b/fixtures/conformance/error-measure-derived-of-derived/input/meta.studio.json
new file mode 100644
index 0000000000..42d983e26d
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-of-derived/input/meta.studio.json
@@ -0,0 +1,282 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "nonBillableHours",
+ "@expr": {
+ "fn": "subtract",
+ "args": [
+ {
+ "field": "totalHours"
+ },
+ {
+ "field": "billableHours"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "nonBillableDays",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "field": "nonBillableHours"
+ },
+ {
+ "value": 8
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-derived-of-derived/providers.json b/fixtures/conformance/error-measure-derived-of-derived/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-of-derived/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-derived-time-dimension/expected-errors.json b/fixtures/conformance/error-measure-derived-time-dimension/expected-errors.json
new file mode 100644
index 0000000000..13c2bea516
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-time-dimension/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.entity'].children[22]['measure.derived']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-derived-time-dimension/input/meta.studio.json b/fixtures/conformance/error-measure-derived-time-dimension/input/meta.studio.json
new file mode 100644
index 0000000000..bde4848a0f
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-time-dimension/input/meta.studio.json
@@ -0,0 +1,266 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "hoursPerMonth",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "field": "totalHours"
+ },
+ {
+ "field": "workedOn"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-derived-time-dimension/providers.json b/fixtures/conformance/error-measure-derived-time-dimension/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-time-dimension/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-measure-derived-unknown-operand/expected-errors.json b/fixtures/conformance/error-measure-derived-unknown-operand/expected-errors.json
new file mode 100644
index 0000000000..13c2bea516
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-unknown-operand/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_MEASURE",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.entity'].children[22]['measure.derived']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-measure-derived-unknown-operand/input/meta.studio.json b/fixtures/conformance/error-measure-derived-unknown-operand/input/meta.studio.json
new file mode 100644
index 0000000000..9e3c796e3f
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-unknown-operand/input/meta.studio.json
@@ -0,0 +1,266 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "overtime",
+ "@expr": {
+ "fn": "subtract",
+ "args": [
+ {
+ "field": "totalHours"
+ },
+ {
+ "field": "contractHours"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-measure-derived-unknown-operand/providers.json b/fixtures/conformance/error-measure-derived-unknown-operand/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-measure-derived-unknown-operand/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-report-derived-dimension-not-listed/expected-errors.json b/fixtures/conformance/error-report-derived-dimension-not-listed/expected-errors.json
new file mode 100644
index 0000000000..fd91a4e8e1
--- /dev/null
+++ b/fixtures/conformance/error-report-derived-dimension-not-listed/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_REPORT",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[3]['object.report']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-report-derived-dimension-not-listed/input/meta.studio.json b/fixtures/conformance/error-report-derived-dimension-not-listed/input/meta.studio.json
new file mode 100644
index 0000000000..e412f9334d
--- /dev/null
+++ b/fixtures/conformance/error-report-derived-dimension-not-listed/input/meta.studio.json
@@ -0,0 +1,294 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "capacityHours",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "weeklyCapacityHours"
+ },
+ {
+ "value": 52
+ }
+ ]
+ },
+ {
+ "value": 12
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "Capacity",
+ "@from": "TimeEntry",
+ "@dimensions": [
+ "memberId"
+ ],
+ "@measures": [
+ "capacityHours"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_capacity"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json b/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-report-derived-dimension-not-listed/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/error-report-value-object-unit-derived-operand/expected-errors.json b/fixtures/conformance/error-report-value-object-unit-derived-operand/expected-errors.json
new file mode 100644
index 0000000000..0f97a4c285
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-derived-operand/expected-errors.json
@@ -0,0 +1,15 @@
+{
+ "errors": [
+ {
+ "code": "ERR_INVALID_REPORT",
+ "source": {
+ "format": "json",
+ "files": [
+ "meta.studio.json"
+ ],
+ "jsonPath": "$['metadata.root'].children[2]['object.report']"
+ }
+ }
+ ],
+ "warnings": []
+}
diff --git a/fixtures/conformance/error-report-value-object-unit-derived-operand/input/meta.studio.json b/fixtures/conformance/error-report-value-object-unit-derived-operand/input/meta.studio.json
new file mode 100644
index 0000000000..96914bb5da
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-derived-operand/input/meta.studio.json
@@ -0,0 +1,103 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.value": {
+ "name": "Money",
+ "children": [
+ {
+ "field.decimal": {
+ "name": "amount",
+ "@required": true,
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.string": {
+ "name": "currency",
+ "@required": true,
+ "@maxLength": 3
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.object": {
+ "name": "amount",
+ "@objectRef": "Money",
+ "@storage": "flattened",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "revenue",
+ "@agg": "sum",
+ "@of": "TimeEntry.amount.amount"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "revenueWithTax",
+ "@expr": {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "revenue"
+ },
+ {
+ "value": 1.2
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "RevenueWithTax",
+ "@from": "TimeEntry",
+ "@dimensions": [],
+ "@measures": [
+ "revenueWithTax"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_revenuewithtax"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json b/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/error-report-value-object-unit-derived-operand/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/conformance/reporting-derived-measures/expected.json b/fixtures/conformance/reporting-derived-measures/expected.json
new file mode 100644
index 0000000000..ab4d637aee
--- /dev/null
+++ b/fixtures/conformance/reporting-derived-measures/expected.json
@@ -0,0 +1,427 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@precision": 6,
+ "@required": true,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@precision": 6,
+ "@required": true,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@fields": [
+ "memberId"
+ ],
+ "@references": "acme::studio::Member"
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@fields": [
+ "projectId"
+ ],
+ "@references": "acme::studio::Project"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@cardinality": "one",
+ "@objectRef": "acme::studio::Member"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@cardinality": "one",
+ "@objectRef": "acme::studio::Project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "acme::studio::Member.id",
+ "@via": "acme::studio::TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "acme::studio::Member.firstName",
+ "@via": "acme::studio::TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "acme::studio::Member.weeklyCapacityHours",
+ "@via": "acme::studio::TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "acme::studio::Project.id",
+ "@via": "acme::studio::TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "acme::studio::Project.budget",
+ "@via": "acme::studio::TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@grains": [
+ "month"
+ ],
+ "@of": "acme::studio::TimeEntry.workedOn"
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@default": 0,
+ "@of": [
+ "acme::studio::TimeEntry.hours"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@default": 0,
+ "@filter": {
+ "billable": {
+ "eq": true
+ }
+ },
+ "@of": [
+ "acme::studio::TimeEntry.hours"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": [
+ "acme::studio::TimeEntry.cost"
+ ]
+ }
+ },
+ {
+ "measure.ratio": {
+ "name": "billableShare",
+ "@denominator": "totalHours",
+ "@numerator": "billableHours"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "capacityHours",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "weeklyCapacityHours"
+ },
+ {
+ "value": 52
+ }
+ ]
+ },
+ {
+ "value": 12
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "utilization",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "billableHours"
+ },
+ {
+ "value": 100
+ }
+ ]
+ },
+ {
+ "fn": "divide",
+ "args": [
+ {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "weeklyCapacityHours"
+ },
+ {
+ "value": 52
+ }
+ ]
+ },
+ {
+ "value": 12
+ }
+ ]
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "nonBillableHours",
+ "@expr": {
+ "fn": "subtract",
+ "args": [
+ {
+ "field": "totalHours"
+ },
+ {
+ "field": "billableHours"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "billableSharePct",
+ "@expr": {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "billableShare"
+ },
+ {
+ "value": 100
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "budgetBurn",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "field": "cost"
+ },
+ {
+ "field": "projectBudget"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "MemberUtilization",
+ "@dimensions": [
+ "memberId",
+ "memberName",
+ "weeklyCapacityHours",
+ "workedOn:month"
+ ],
+ "@from": "acme::studio::TimeEntry",
+ "@measures": [
+ "totalHours",
+ "billableHours",
+ "capacityHours",
+ "utilization",
+ "nonBillableHours",
+ "billableSharePct"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_memberutilization"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "ProjectBurn",
+ "@dimensions": [
+ "projectId",
+ "projectBudget"
+ ],
+ "@from": "acme::studio::TimeEntry",
+ "@measures": [
+ "cost",
+ "budgetBurn"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_projectburn"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/reporting-derived-measures/input/meta.studio.json b/fixtures/conformance/reporting-derived-measures/input/meta.studio.json
new file mode 100644
index 0000000000..b23a68cf1e
--- /dev/null
+++ b/fixtures/conformance/reporting-derived-measures/input/meta.studio.json
@@ -0,0 +1,419 @@
+{
+ "metadata.root": {
+ "package": "acme::studio",
+ "children": [
+ {
+ "object.entity": {
+ "name": "Member",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "members"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "firstName",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "weeklyCapacityHours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "Project",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "projects"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.string": {
+ "name": "name",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "budget",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.entity": {
+ "name": "TimeEntry",
+ "children": [
+ {
+ "source.rdb": {
+ "@table": "time_entries"
+ }
+ },
+ {
+ "field.long": {
+ "name": "id"
+ }
+ },
+ {
+ "field.long": {
+ "name": "memberId",
+ "@required": true
+ }
+ },
+ {
+ "field.long": {
+ "name": "projectId",
+ "@required": true
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "hours",
+ "@required": true,
+ "@precision": 6,
+ "@scale": 2
+ }
+ },
+ {
+ "field.decimal": {
+ "name": "cost",
+ "@precision": 12,
+ "@scale": 2
+ }
+ },
+ {
+ "field.boolean": {
+ "name": "billable",
+ "@required": true
+ }
+ },
+ {
+ "field.date": {
+ "name": "workedOn",
+ "@required": true
+ }
+ },
+ {
+ "identity.primary": {
+ "name": "id",
+ "@fields": [
+ "id"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkMember",
+ "@references": "Member",
+ "@fields": [
+ "memberId"
+ ]
+ }
+ },
+ {
+ "identity.reference": {
+ "name": "fkProject",
+ "@references": "Project",
+ "@fields": [
+ "projectId"
+ ]
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "member",
+ "@objectRef": "Member",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "relationship.association": {
+ "name": "project",
+ "@objectRef": "Project",
+ "@cardinality": "one"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberId",
+ "@of": "Member.id",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "memberName",
+ "@of": "Member.firstName",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours",
+ "@via": "TimeEntry.member"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectId",
+ "@of": "Project.id",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.attribute": {
+ "name": "projectBudget",
+ "@of": "Project.budget",
+ "@via": "TimeEntry.project"
+ }
+ },
+ {
+ "dimension.time": {
+ "name": "workedOn",
+ "@of": "TimeEntry.workedOn",
+ "@grains": [
+ "month"
+ ]
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "totalHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "billableHours",
+ "@agg": "sum",
+ "@of": "TimeEntry.hours",
+ "@filter": {
+ "billable": true
+ },
+ "@default": 0
+ }
+ },
+ {
+ "measure.aggregate": {
+ "name": "cost",
+ "@agg": "sum",
+ "@of": "TimeEntry.cost"
+ }
+ },
+ {
+ "measure.ratio": {
+ "name": "billableShare",
+ "@numerator": "billableHours",
+ "@denominator": "totalHours"
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "capacityHours",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "weeklyCapacityHours"
+ },
+ {
+ "value": 52
+ }
+ ]
+ },
+ {
+ "value": 12
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "utilization",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "billableHours"
+ },
+ {
+ "value": 100
+ }
+ ]
+ },
+ {
+ "fn": "divide",
+ "args": [
+ {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "weeklyCapacityHours"
+ },
+ {
+ "value": 52
+ }
+ ]
+ },
+ {
+ "value": 12
+ }
+ ]
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "nonBillableHours",
+ "@expr": {
+ "fn": "subtract",
+ "args": [
+ {
+ "field": "totalHours"
+ },
+ {
+ "field": "billableHours"
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "billableSharePct",
+ "@expr": {
+ "fn": "multiply",
+ "args": [
+ {
+ "field": "billableShare"
+ },
+ {
+ "value": 100
+ }
+ ]
+ }
+ }
+ },
+ {
+ "measure.derived": {
+ "name": "budgetBurn",
+ "@expr": {
+ "fn": "divide",
+ "args": [
+ {
+ "field": "cost"
+ },
+ {
+ "field": "projectBudget"
+ }
+ ]
+ }
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "MemberUtilization",
+ "@from": "TimeEntry",
+ "@dimensions": [
+ "memberId",
+ "memberName",
+ "weeklyCapacityHours",
+ "workedOn:month"
+ ],
+ "@measures": [
+ "totalHours",
+ "billableHours",
+ "capacityHours",
+ "utilization",
+ "nonBillableHours",
+ "billableSharePct"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_memberutilization"
+ }
+ }
+ ]
+ }
+ },
+ {
+ "object.report": {
+ "name": "ProjectBurn",
+ "@from": "TimeEntry",
+ "@dimensions": [
+ "projectId",
+ "projectBudget"
+ ],
+ "@measures": [
+ "cost",
+ "budgetBurn"
+ ],
+ "children": [
+ {
+ "source.rdb": {
+ "@kind": "view",
+ "@view": "v_projectburn"
+ }
+ }
+ ]
+ }
+ }
+ ]
+ }
+}
diff --git a/fixtures/conformance/reporting-derived-measures/providers.json b/fixtures/conformance/reporting-derived-measures/providers.json
new file mode 100644
index 0000000000..f9bb435a37
--- /dev/null
+++ b/fixtures/conformance/reporting-derived-measures/providers.json
@@ -0,0 +1 @@
+["metaobjects-core-types","metaobjects-db"]
diff --git a/fixtures/metamodel-docs/expected/INDEX.md b/fixtures/metamodel-docs/expected/INDEX.md
index d0ba64ebf9..f66e1327f1 100644
--- a/fixtures/metamodel-docs/expected/INDEX.md
+++ b/fixtures/metamodel-docs/expected/INDEX.md
@@ -54,6 +54,7 @@ children and the cardinality of that subtype. Documentation attributes
| `layout.base` | Abstract base layout — the shared root subtype for object-level UI surfaces. A layout attaches a presentation concern (grids, forms, tabs, cards) to an object. The base carries no attrs of its own; concrete subtypes add their presentation attrs. Not authored directly: a `layout.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED) — this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/layout.md#layoutbase](types/layout.md#layoutbase) |
| `layout.dataGrid` | A metadata-driven data grid attached to an object: declares the displayed columns, page size, default sort, and an optional preset filter the generated grid renders. | [types/layout.md#layoutdatagrid](types/layout.md#layoutdatagrid) |
| `measure.aggregate` | A named aggregate over the declaring entity's own rows (FR-044). @agg count without @distinct counts rows; with @distinct it counts distinct values of @of (a list in @of is a distinct count of the tuple). Unlike origin.aggregate, count is NOT distinct by default: a measure aggregates its own rows and dimensions reach only to-one paths, so no join inflates it. | [types/measure.md#measureaggregate](types/measure.md#measureaggregate) |
+| `measure.derived` | A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension. | [types/measure.md#measurederived](types/measure.md#measurederived) |
| `measure.ratio` | A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null. | [types/measure.md#measureratio](types/measure.md#measureratio) |
| `metadata.root` | Root metadata document | [types/metadata.md#metadataroot](types/metadata.md#metadataroot) |
| `object.base` | Abstract object base — the shared root subtype that concrete object subtypes (entity/value/projection) specialize. Declares the structural children common to EVERY object subtype (the intersection: field/identity/validator/layout/source); subtype-specific children (relationship, template) and attrs (discriminator) ride their own subtypes. Has no runtime semantics of its own; not authored directly. A `object.base` node fails to load (ERR_ABSTRACT_SUBTYPE_AUTHORED): this subtype is a registry anchor concrete subtypes inherit from, never a node in a document. | [types/object.md#objectbase](types/object.md#objectbase) |
diff --git a/fixtures/metamodel-docs/expected/types/dimension.md b/fixtures/metamodel-docs/expected/types/dimension.md
index 7d20448ff5..9ccb48ae62 100644
--- a/fixtures/metamodel-docs/expected/types/dimension.md
+++ b/fixtures/metamodel-docs/expected/types/dimension.md
@@ -20,7 +20,7 @@ A named group-by attribute of the entity that declares it (FR-044). Groups repor
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
-| `@of` | string | yes | | | — | Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). |
+| `@of` | string | yes | | | — | Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own. |
| `@via` | string | no | | | — | Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference. |
**Allowed children**
@@ -38,7 +38,7 @@ A named time dimension (FR-044): groups report rows by a date or timestamp colum
| Attribute | Type | Required | Default | Allowed values | Provider | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `@grains` | string[] | yes | | `hour`, `day`, `week`, `month`, `quarter`, `year` | — | The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date. |
-| `@of` | string | yes | | | — | Dotted Entity.field reference naming the date or timestamp column. |
+| `@of` | string | yes | | | — | Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object. |
| `@via` | string | no | | | — | Optional dotted to-one relationship path, as on dimension.attribute. |
**Allowed children**
diff --git a/fixtures/metamodel-docs/expected/types/measure.md b/fixtures/metamodel-docs/expected/types/measure.md
index 885b81d281..a4a0f90669 100644
--- a/fixtures/metamodel-docs/expected/types/measure.md
+++ b/fixtures/metamodel-docs/expected/types/measure.md
@@ -24,13 +24,29 @@ A named aggregate over the declaring entity's own rows (FR-044). @agg count with
| `@default` | int | no | | | — | Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null), on min/max over a field that is not numeric, and on @agg any/all unless it is 0 (false) or 1 (true). A ratio's operand carries its own @default into the ratio. |
| `@distinct` | boolean | no | | | — | Count distinct values. Legal only with @agg: count. |
| `@filter` | filter | no | | | — | Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: "-P7D" }). Combines with @segment by AND. |
-| `@of` | string[] | no | | | — | Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows. |
+| `@of` | string[] | no | | | — | Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows. |
| `@segment` | string | no | | | — | Optional name of a segment declared on the same entity. Combines with @filter by AND. |
**Allowed children**
_No structural children._
+### measure.derived
+
+A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.
+
+**When to use:** A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).
+
+**Attributes**
+
+| Attribute | Type | Required | Default | Allowed values | Provider | Description |
+| --- | --- | --- | --- | --- | --- | --- |
+| `@expr` | expression | yes | | | — | The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add \| subtract \| multiply \| divide, args: [a, b] } combines two operands. |
+
+**Allowed children**
+
+_No structural children._
+
### measure.ratio
A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null.
diff --git a/fixtures/registry-conformance/expected-registry.json b/fixtures/registry-conformance/expected-registry.json
index 39e633105c..4f1d8dd42c 100644
--- a/fixtures/registry-conformance/expected-registry.json
+++ b/fixtures/registry-conformance/expected-registry.json
@@ -3362,6 +3362,22 @@
],
"children": []
},
+ {
+ "type": "measure",
+ "subType": "derived",
+ "description": "A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.",
+ "whenToUse": "A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).",
+ "attrs": [
+ {
+ "name": "expr",
+ "valueType": "expression",
+ "isArray": false,
+ "required": true,
+ "description": "The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands."
+ }
+ ],
+ "children": []
+ },
{
"type": "measure",
"subType": "ratio",
diff --git a/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts b/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts
index 4d2b62c1bd..b39e3b6b09 100644
--- a/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts
+++ b/server/typescript/packages/codegen-ts/src/cube/build-cube-model.ts
@@ -87,6 +87,7 @@ import {
docOf,
grainsOf,
measureMembers,
+ measuresRead,
memberKey,
segmentSpec,
valueObjectMemberError,
@@ -896,10 +897,8 @@ class CubeModelBuilder {
if (f.role !== "measure" || m === undefined) continue;
listed.add(m.name);
need(m);
- if (m.isRatio()) {
- need(ratioOperand(from.entity, m, m.numerator(), where));
- need(ratioOperand(from.entity, m, m.denominator(), where));
- }
+ // A ratio's operands, and a derived measure's operands and theirs, are members its SQL reads.
+ for (const o of measuresRead(from.entity, m, where)) need(o);
}
return from.measures
.filter((m) => needed.has(m.name))
diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-errors.ts b/server/typescript/packages/codegen-ts/src/cube/cube-errors.ts
index 12468b9a29..ffd6c001ea 100644
--- a/server/typescript/packages/codegen-ts/src/cube/cube-errors.ts
+++ b/server/typescript/packages/codegen-ts/src/cube/cube-errors.ts
@@ -13,6 +13,8 @@ export const ERR_CUBE_NAME_COLLISION = "ERR_CUBE_NAME_COLLISION";
export const ERR_CUBE_UNESCAPABLE_LITERAL = "ERR_CUBE_UNESCAPABLE_LITERAL";
/** FR-044 R12: an `@of` names a value-object member, which the exporter does not map. */
export const ERR_CUBE_VALUE_OBJECT_MEMBER = "ERR_CUBE_VALUE_OBJECT_MEMBER";
+/** FR-044 R13: a `measure.derived` reads a dimension, which a Cube measure cannot. */
+export const ERR_CUBE_DERIVED_DIMENSION = "ERR_CUBE_DERIVED_DIMENSION";
/** The generator's dialect is not one it writes Cube SQL for (postgres, mysql). */
export const ERR_CUBE_UNSUPPORTED_DIALECT = "ERR_CUBE_UNSUPPORTED_DIALECT";
@@ -28,6 +30,7 @@ export const CUBE_ERROR_CODES = [
ERR_CUBE_UNESCAPABLE_LITERAL,
ERR_CUBE_UNSUPPORTED_DIALECT,
ERR_CUBE_VALUE_OBJECT_MEMBER,
+ ERR_CUBE_DERIVED_DIMENSION,
] as const;
export type CubeErrorCode = (typeof CUBE_ERROR_CODES)[number];
diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
index 6ad42d59f7..bbcdaa2801 100644
--- a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
+++ b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
@@ -9,6 +9,9 @@ import {
AGG_ANY,
AGG_COUNT,
CHILD_REF_SEPARATOR,
+ DERIVED_FN_ADD,
+ DERIVED_FN_DIVIDE,
+ DERIVED_FN_SUBTRACT,
DOC_ATTR_DESCRIPTION,
DOC_ATTR_TITLE,
FIELD_SUBTYPE_BOOLEAN,
@@ -35,12 +38,20 @@ import {
type MetaObject,
type MetaRoot,
type MetaSegment,
+ type DerivedExprNode,
+ TYPE_MEASURE,
+ derivedExprFields,
} from "@metaobjectsdev/metadata";
import { intValueMapOf } from "../enum-meta.js";
import { sourceColumnNameFor, type ExtractContext } from "../projection/extract-view-spec.js";
import { ratioOperand, resolveAggregate } from "../projection/report-resolve.js";
-import { cond, mysqlTupleCount, resolveReportFilter, type SqlRenderer } from "../projection/report-sql.js";
-import { CubeModelError, ERR_CUBE_UNMAPPABLE_DIMENSION, ERR_CUBE_VALUE_OBJECT_MEMBER } from "./cube-errors.js";
+import { cond, declared, mysqlTupleCount, resolveReportFilter, type SqlRenderer } from "../projection/report-sql.js";
+import {
+ CubeModelError,
+ ERR_CUBE_DERIVED_DIMENSION,
+ ERR_CUBE_UNMAPPABLE_DIMENSION,
+ ERR_CUBE_VALUE_OBJECT_MEMBER,
+} from "./cube-errors.js";
/**
* FR-044 R12: a report reads a member of a flattened value object only beside a grouping by the
@@ -199,10 +210,58 @@ function withDefault(sql: string, n: number, boolean: boolean, d: ReportDialect)
return `COALESCE(${sql}, ${String(n)})`;
}
+/**
+ * FR-044 R13: the measures a `measure.derived`'s `@expr` names, resolved on `entity`. A Cube measure
+ * reads other measures, never a group's dimension value, so a name that is not a measure is refused.
+ */
+function derivedOperands(entity: MetaObject, m: MetaMeasure, where: string): MetaMeasure[] {
+ const expr = m.expr();
+ if (expr === undefined) throw new Error(`${where}: measure '${m.name}' @expr is not an arithmetic expression.`);
+ return derivedExprFields(expr).map((name) => {
+ const operand = declared(entity, TYPE_MEASURE, name) as MetaMeasure | undefined;
+ if (operand === undefined) {
+ throw new CubeModelError(
+ ERR_CUBE_DERIVED_DIMENSION,
+ `${where}: measure '${m.name}' reads dimension '${name}'. A Cube measure reads other measures, not a ` +
+ `group's dimension value, so the exporter cannot write it; read the dimension in the report view instead.`,
+ );
+ }
+ return operand;
+ });
+}
+
+/** Every measure `m`'s Cube SQL references, transitively: a ratio's operands, a derived measure's
+ * operands and theirs. Not `m` itself. */
+export function measuresRead(entity: MetaObject, m: MetaMeasure, where: string): MetaMeasure[] {
+ const direct = m.isRatio()
+ ? [ratioOperand(entity, m, m.numerator(), where), ratioOperand(entity, m, m.denominator(), where)]
+ : m.isDerived()
+ ? derivedOperands(entity, m, where)
+ : [];
+ return direct.flatMap((o) => [o, ...measuresRead(entity, o, where)]);
+}
+
+/** R13: a derived measure's Cube SQL over its operand members; `divide` divides as a ratio does. */
+function derivedSql(node: DerivedExprNode, d: ReportDialect, top = true): string {
+ if ("field" in node) return memberRef(node.field);
+ if ("value" in node) return node.value < 0 ? `(${String(node.value)})` : String(node.value);
+ const l = derivedSql(node.args[0], d, false);
+ const r = derivedSql(node.args[1], d, false);
+ const sql =
+ node.fn === DERIVED_FN_DIVIDE
+ ? `${d === "postgres" ? `CAST(${l} AS NUMERIC)` : l} / NULLIF(${r}, 0)`
+ : `${l} ${node.fn === DERIVED_FN_ADD ? "+" : node.fn === DERIVED_FN_SUBTRACT ? "-" : "*"} ${r}`;
+ return top ? sql : `(${sql})`;
+}
+
/** Table D, and the zero-rows / measure-defaults plan's Table D: one measure over `entity`'s own rows. */
export function measureMembers(entity: MetaObject, m: MetaMeasure, where: string, mc: MemberContext): MeasureMembers {
// ADR-0039: defaultValue() resolves, so a measure inherited through extends keeps its default.
const n = m.defaultValue();
+ if (m.isDerived()) {
+ derivedOperands(entity, m, where); // refuses a dimension operand
+ return { measure: { name: m.name, sql: derivedSql(m.expr()!, mc.dialect), type: "number", ...docOf(m) } };
+ }
if (m.isRatio()) {
// Member references: each operand is its full Cube expression, condition included, and an
// operand with its own @default is its COALESCE member, so that default reaches the ratio
diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-reports.ts b/server/typescript/packages/codegen-ts/src/cube/cube-reports.ts
index 1e5ece24da..a98fb4d9e3 100644
--- a/server/typescript/packages/codegen-ts/src/cube/cube-reports.ts
+++ b/server/typescript/packages/codegen-ts/src/cube/cube-reports.ts
@@ -9,6 +9,7 @@
// reading the authored JSON.
import {
+ MEASURE_SUBTYPE_AGGREGATE,
TIME_GRAINS,
type MetaMeasure,
type ReportShape,
@@ -18,7 +19,7 @@ import { ratioOperand, resolveAggregate } from "../projection/report-resolve.js"
import { isRelativeNow } from "../projection/report-spec.js";
import { cond, reportScope } from "../projection/report-sql.js";
import type { ViewFilterClause } from "../projection/view-spec.js";
-import type { MemberContext } from "./cube-members.js";
+import { measuresRead, type MemberContext } from "./cube-members.js";
import type { CubeRollupSpec, CubeRollupTimeDimension, CubeSegmentSpec } from "./cube-model-spec.js";
import { CUBE_SELF, cubeSqlRenderer } from "./cube-sql.js";
@@ -146,9 +147,7 @@ export function reportContribution(shape: ReportShape, cube: string, mc: MemberC
if (m === undefined) throw new Error(`${where}: report field '${f.name}' names no measure.`);
measures.push(m.name);
// A ratio's condition is its operands' conditions: each is the full aggregate it divides.
- const aggregates: MetaMeasure[] = m.isRatio()
- ? [ratioOperand(from, m, m.numerator(), where), ratioOperand(from, m, m.denominator(), where)]
- : [m];
+ const aggregates: MetaMeasure[] = [m, ...measuresRead(from, m, where)].filter((a) => a.subType === MEASURE_SUBTYPE_AGGREGATE);
for (const a of aggregates) {
conditions.push(resolveAggregate(a, from, mc.root, CUBE_SELF, ctx, `${where} measure '${a.name}'`).condition);
}
diff --git a/server/typescript/packages/codegen-ts/src/projection/extract-report-spec.ts b/server/typescript/packages/codegen-ts/src/projection/extract-report-spec.ts
index 7373abca93..6721d68484 100644
--- a/server/typescript/packages/codegen-ts/src/projection/extract-report-spec.ts
+++ b/server/typescript/packages/codegen-ts/src/projection/extract-report-spec.ts
@@ -12,6 +12,9 @@ import {
FIELD_SUBTYPE_FLOAT,
FIELD_SUBTYPE_INT,
FIELD_SUBTYPE_LONG,
+ MEASURE_SUBTYPE_AGGREGATE,
+ TYPE_MEASURE,
+ type DerivedExprNode,
measureDerivedSubType,
resolveDimensionOf,
reportShape,
@@ -45,8 +48,8 @@ import {
resolveDimensionViaPath,
viaHopError,
} from "./report-resolve.js";
-import type { ReportAggregate, ReportColumn, ReportViewSpec } from "./report-spec.js";
-import { reportScope, temporalOf } from "./report-sql.js";
+import type { ReportAggregate, ReportColumn, ReportDerivedTerm, ReportViewSpec } from "./report-spec.js";
+import { declared, reportScope, temporalOf } from "./report-sql.js";
import type { JoinNode } from "./view-spec.js";
// `temporalOf` lives with the other report SQL helpers; this module keeps exporting it.
@@ -235,6 +238,8 @@ export function extractReportSpec(report: MetaObject, root: MetaRoot, ctx: Extra
const tree = pathsToJoins(spinePath === undefined ? dimensionPaths : [spinePath, ...dimensionPaths], used);
const joins = spinePath === undefined ? tree : allLeft(tree);
+ // R13: a derived measure reads a listed attribute dimension through the column the view groups by.
+ const dimensionRefs = new Map();
const columns = shape.fields.map((f): ReportColumn => {
const dbColAlias = columnNameFromField(f.name, ctx.columnNamingStrategy);
if (f.role === "dimension") {
@@ -248,21 +253,47 @@ export function extractReportSpec(report: MetaObject, root: MetaRoot, ctx: Extra
if (f.grain !== undefined) {
return { kind: "timeDimension", fieldName: f.name, dbColAlias, ref, grain: f.grain, temporal: temporalOf(of.field) };
}
+ if (dim !== undefined) dimensionRefs.set(dim.name, ref);
return { kind: "dimension", fieldName: f.name, dbColAlias, ref };
}
const measure = f.measure!;
- if (measure.isRatio()) {
+ const ratioTerm = (ratio: MetaMeasure): Extract => {
const operand = (name: string | undefined): ReportAggregate =>
- aggregateOf(ratioOperand(from, measure, name, `report '${report.name}'`), report, from, baseAlias, root, ctx);
- const defaultValue = measure.defaultValue();
+ aggregateOf(ratioOperand(from, ratio, name, `report '${report.name}'`), report, from, baseAlias, root, ctx);
+ const defaultValue = ratio.defaultValue();
return {
kind: "ratio",
- fieldName: f.name,
- dbColAlias,
- numerator: operand(measure.numerator()),
- denominator: operand(measure.denominator()),
+ numerator: operand(ratio.numerator()),
+ denominator: operand(ratio.denominator()),
...(defaultValue !== undefined ? { defaultValue } : {}),
};
+ };
+ if (measure.isRatio()) {
+ const { kind: _kind, ...ratio } = ratioTerm(measure);
+ return { kind: "ratio", fieldName: f.name, dbColAlias, ...ratio };
+ }
+ if (measure.isDerived()) {
+ const where = `report '${report.name}': measure '${f.name}'`;
+ const expr = measure.expr();
+ if (expr === undefined) throw new Error(`${where}: @expr is not an arithmetic expression.`);
+ const term = (node: DerivedExprNode): ReportDerivedTerm => {
+ if ("value" in node) return { kind: "value", value: node.value };
+ if ("fn" in node) return { kind: "op", fn: node.fn, left: term(node.args[0]), right: term(node.args[1]) };
+ const operand = declared(from, TYPE_MEASURE, node.field) as MetaMeasure | undefined;
+ if (operand !== undefined) {
+ if (operand.isRatio()) return ratioTerm(operand);
+ if (operand.subType === MEASURE_SUBTYPE_AGGREGATE) {
+ return { kind: "aggregate", aggregate: aggregateOf(operand, report, from, baseAlias, root, ctx) };
+ }
+ throw new Error(`${where}: @expr names '${node.field}', a measure.${operand.subType}.`);
+ }
+ const ref = dimensionRefs.get(node.field);
+ if (ref === undefined) {
+ throw new Error(`${where}: @expr names '${node.field}', which is no measure of '${from.name}' and no dimension the report lists.`);
+ }
+ return { kind: "ref", ref };
+ };
+ return { kind: "derived", fieldName: f.name, dbColAlias, term: term(expr) };
}
return { kind: "aggregate", fieldName: f.name, dbColAlias, aggregate: aggregateOf(measure, report, from, baseAlias, root, ctx) };
});
diff --git a/server/typescript/packages/codegen-ts/src/projection/report-ddl-emit.ts b/server/typescript/packages/codegen-ts/src/projection/report-ddl-emit.ts
index c85ec24c4b..003e3cea9c 100644
--- a/server/typescript/packages/codegen-ts/src/projection/report-ddl-emit.ts
+++ b/server/typescript/packages/codegen-ts/src/projection/report-ddl-emit.ts
@@ -3,8 +3,8 @@
// emitter quotes conditionally (`quoteIfNeeded`) and is Postgres/SQLite only; a report
// quotes every identifier unconditionally, so a measure named `order` is valid DDL.
import type { JoinNode } from "./view-spec.js";
-import type { ReportAggregate, ReportColumn, ReportViewSpec } from "./report-spec.js";
-import { AGG_ALL, AGG_ANY } from "@metaobjectsdev/metadata";
+import type { ReportAggregate, ReportColumn, ReportDerivedTerm, ReportViewSpec } from "./report-spec.js";
+import { AGG_ALL, AGG_ANY, DERIVED_FN_ADD, DERIVED_FN_DIVIDE, DERIVED_FN_SUBTRACT } from "@metaobjectsdev/metadata";
import { cond, mysqlTupleCount, q, ref } from "./report-sql.js";
import { truncateToGrain, type ReportDialect } from "./time-sql.js";
@@ -92,6 +92,64 @@ function aggregate(a: ReportAggregate, d: ReportDialect, factRef?: string): stri
return withDefault(type === undefined ? sql : `CAST(${sql} AS ${type})`, a.defaultValue, d);
}
+/** A ratio (Table C/D): each operand its full aggregate, the quotient real, its own default around it. */
+function ratio(
+ numerator: ReportAggregate,
+ denominator: ReportAggregate,
+ defaultValue: number | undefined,
+ d: ReportDialect,
+ factRef: string | undefined,
+): string {
+ // Each operand is its FULL Table C expression (condition and cast included), and its own
+ // Table D default; the ratio's default wraps the whole quotient, which is always real.
+ const num = aggregate(numerator, d, factRef);
+ const den = aggregate(denominator, d, factRef);
+ const quotient = `${realOf(num, d)} / NULLIF(${den}, 0)`;
+ const dv = defaultValue === undefined ? undefined : { value: defaultValue, real: true };
+ return withDefault(quotient, dv, d);
+}
+
+/** `CAST(x AS )` where the dialect would otherwise divide integers as integers. */
+function realOf(sql: string, d: ReportDialect): string {
+ const top = d === "postgres" ? "NUMERIC" : d === "sqlite" ? "REAL" : undefined;
+ return top === undefined ? sql : `CAST(${sql} AS ${top})`;
+}
+
+/** FR-044 R13: a derived measure's expression. An operation or ratio under another operator is
+ * parenthesised; `divide` divides as a ratio does (real, a zero divisor reads null), and a
+ * nonzero literal divisor needs no NULLIF. */
+function derived(t: ReportDerivedTerm, d: ReportDialect, factRef: string | undefined, top = true): string {
+ switch (t.kind) {
+ case "aggregate":
+ return aggregate(t.aggregate, d, factRef);
+ case "ratio": {
+ const sql = ratio(t.numerator, t.denominator, t.defaultValue, d, factRef);
+ return top || t.defaultValue !== undefined ? sql : `(${sql})`;
+ }
+ case "ref":
+ return ref(t.ref, d);
+ case "value":
+ return t.value < 0 ? `(${String(t.value)})` : String(t.value);
+ case "op": {
+ let sql: string;
+ if (t.fn === DERIVED_FN_DIVIDE) {
+ // Inside CAST(...) the dividend needs no parentheses of its own; MySQL has no cast.
+ const real = realOf(derived(t.left, d, factRef), d);
+ const dividend = real.startsWith("CAST(") ? real : derived(t.left, d, factRef, false);
+ const divisor =
+ t.right.kind === "value" && t.right.value !== 0
+ ? derived(t.right, d, factRef, false)
+ : `NULLIF(${derived(t.right, d, factRef)}, 0)`;
+ sql = `${dividend} / ${divisor}`;
+ } else {
+ const sign = t.fn === DERIVED_FN_ADD ? "+" : t.fn === DERIVED_FN_SUBTRACT ? "-" : "*";
+ sql = `${derived(t.left, d, factRef, false)} ${sign} ${derived(t.right, d, factRef, false)}`;
+ }
+ return top ? sql : `(${sql})`;
+ }
+ }
+}
+
interface RenderedColumn {
readonly expr: string;
readonly alias: string;
@@ -108,15 +166,13 @@ function column(c: ReportColumn, d: ReportDialect, factRef: string | undefined):
return { expr: truncateToGrain(ref(c.ref, d), c.grain, c.temporal, d), alias, grouped: true };
case "aggregate":
return { expr: aggregate(c.aggregate, d, factRef), alias, grouped: false };
- case "ratio": {
- // Each operand is its FULL Table C expression (condition and cast included), and its own
- // Table D default; the ratio's default wraps the whole quotient, which is always real.
- const num = aggregate(c.numerator, d, factRef);
- const den = aggregate(c.denominator, d, factRef);
- const top = d === "postgres" ? "NUMERIC" : d === "sqlite" ? "REAL" : undefined;
- const quotient = `${top === undefined ? num : `CAST(${num} AS ${top})`} / NULLIF(${den}, 0)`;
- const dv = c.defaultValue === undefined ? undefined : { value: c.defaultValue, real: true };
- return { expr: withDefault(quotient, dv, d), alias, grouped: false };
+ case "ratio":
+ return { expr: ratio(c.numerator, c.denominator, c.defaultValue, d, factRef), alias, grouped: false };
+ case "derived": {
+ // Typed decimal (Table B) whatever its operands: the whole expression is real.
+ const top = c.term.kind === "op" && c.term.fn === DERIVED_FN_DIVIDE;
+ const sql = derived(c.term, d, factRef);
+ return { expr: top ? sql : realOf(sql, d), alias, grouped: false };
}
}
}
diff --git a/server/typescript/packages/codegen-ts/src/projection/report-resolve.ts b/server/typescript/packages/codegen-ts/src/projection/report-resolve.ts
index f0a688a7eb..320db653a1 100644
--- a/server/typescript/packages/codegen-ts/src/projection/report-resolve.ts
+++ b/server/typescript/packages/codegen-ts/src/projection/report-resolve.ts
@@ -5,6 +5,7 @@
// the same messages. Rendering the result as SQL is report-sql.ts's concern.
import {
+ MEASURE_SUBTYPE_AGGREGATE,
IDENTITY_REFERENCE_ATTR_REFERENCES,
IDENTITY_SUBTYPE_REFERENCE,
RELATIONSHIP_ATTR_OBJECT_REF,
@@ -184,7 +185,7 @@ export function resolveAggregate(
/** A ratio operand: a `measure.aggregate` declared on (or inherited by) `from`. */
export function ratioOperand(from: MetaObject, ratio: MetaMeasure, name: string | undefined, where: string): MetaMeasure {
const m = name === undefined ? undefined : (declared(from, TYPE_MEASURE, name) as MetaMeasure | undefined);
- if (m === undefined || m.isRatio()) {
+ if (m === undefined || m.subType !== MEASURE_SUBTYPE_AGGREGATE) {
throw new Error(
`${where}: ratio '${ratio.name}' operand '${name ?? ""}' is not a measure.aggregate on '${from.name}'.`,
);
diff --git a/server/typescript/packages/codegen-ts/src/projection/report-spec.ts b/server/typescript/packages/codegen-ts/src/projection/report-spec.ts
index eebd5fe505..100f3f86cf 100644
--- a/server/typescript/packages/codegen-ts/src/projection/report-spec.ts
+++ b/server/typescript/packages/codegen-ts/src/projection/report-spec.ts
@@ -2,7 +2,7 @@
// `extractReportSpec` produces it; the report DDL emitter renders it per dialect. Column
// references are already resolved to unquoted `alias.column`, as in `ViewSpec`.
-import type { MeasureAgg, RelativeStartOf, TimeGrain } from "@metaobjectsdev/metadata";
+import type { DerivedFn, MeasureAgg, RelativeStartOf, TimeGrain } from "@metaobjectsdev/metadata";
import type { JoinTree, ViewFilterClause } from "./view-spec.js";
import type { ReportTemporal } from "./time-sql.js";
@@ -36,6 +36,20 @@ export interface ReportAggregate {
readonly defaultValue?: { readonly value: number; readonly real: boolean; readonly boolean?: true };
}
+/** FR-044 R13: one node of a `measure.derived` expression, its operands resolved. A measure operand
+ * is its full Table C/D expression; a dimension operand is the grouped column of a listed dimension. */
+export type ReportDerivedTerm =
+ | { readonly kind: "aggregate"; readonly aggregate: ReportAggregate }
+ | {
+ readonly kind: "ratio";
+ readonly numerator: ReportAggregate;
+ readonly denominator: ReportAggregate;
+ readonly defaultValue?: number;
+ }
+ | { readonly kind: "ref"; readonly ref: string }
+ | { readonly kind: "value"; readonly value: number }
+ | { readonly kind: "op"; readonly fn: DerivedFn; readonly left: ReportDerivedTerm; readonly right: ReportDerivedTerm };
+
export type ReportColumn =
| { readonly kind: "dimension"; readonly fieldName: string; readonly dbColAlias: string; readonly ref: string }
| {
@@ -60,7 +74,8 @@ export type ReportColumn =
readonly denominator: ReportAggregate;
/** FR-044 Table D: the ratio's own `@default` (a ratio is always real). */
readonly defaultValue?: number;
- };
+ }
+ | { readonly kind: "derived"; readonly fieldName: string; readonly dbColAlias: string; readonly term: ReportDerivedTerm };
export interface ReportViewSpec {
readonly viewName: string;
diff --git a/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts b/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
new file mode 100644
index 0000000000..59a67d7f98
--- /dev/null
+++ b/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
@@ -0,0 +1,98 @@
+// FR-044 R13 — a measure.derived lowers to arithmetic over its operands' full expressions: a
+// measure reads its aggregate (condition and default included), a dimension reads the column the
+// view groups by, and `divide` divides as a ratio does. The model is the shared conformance
+// fixture, so the loader rules and the lowering see one model.
+import { describe, expect, test } from "bun:test";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { InMemoryStringSource, MetaDataLoader } from "@metaobjectsdev/metadata";
+import { buildReportViews } from "../../src/projection/build-projection-views.js";
+import { buildCubeModel } from "../../src/cube/build-cube-model.js";
+
+const FIXTURE = join(
+ import.meta.dir,
+ "../../../../../../fixtures/conformance/reporting-derived-measures/input/meta.studio.json",
+);
+
+type Json = Record;
+const DIMENSION_READERS = new Set(["capacityHours", "utilization", "budgetBurn"]);
+
+/** The fixture, or (for Cube) the fixture without the derived measures that read a dimension. */
+async function load(measuresOnly = false) {
+ const doc = JSON.parse(readFileSync(FIXTURE, "utf8")) as Json;
+ if (measuresOnly) {
+ const children = (doc["metadata.root"] as { children: Json[] }).children;
+ const entity = children.find((c) => (c["object.entity"] as Json | undefined)?.name === "TimeEntry")!;
+ const ec = entity["object.entity"] as { children: Json[] };
+ ec.children = ec.children.filter((c) => !DIMENSION_READERS.has(String((c["measure.derived"] as Json | undefined)?.name)));
+ (doc["metadata.root"] as { children: Json[] }).children = children
+ .filter((c) => (c["object.report"] as Json | undefined)?.name !== "ProjectBurn")
+ .map((c) => {
+ const r = c["object.report"] as { "@measures": string[] } | undefined;
+ if (r !== undefined) r["@measures"] = r["@measures"].filter((m) => !DIMENSION_READERS.has(m));
+ return c;
+ });
+ }
+ const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]);
+ expect(errors).toEqual([]);
+ return root;
+}
+
+async function views(dialect: "postgres" | "sqlite" | "mysql"): Promise> {
+ const out: Record = {};
+ for (const v of buildReportViews(await load(), { dialect })) out[v.name] = v.sql;
+ return out;
+}
+
+const BILLABLE = {
+ postgres: `COALESCE(SUM(t."hours") FILTER (WHERE t."billable" = TRUE), 0)`,
+ sqlite: `COALESCE(SUM(CASE WHEN t."billable" = 1 THEN t."hours" END), 0.0)`,
+};
+
+describe("FR-044 R13: derived measures in a report view", () => {
+ for (const [dialect, real] of [["postgres", "NUMERIC"], ["sqlite", "REAL"]] as const) {
+ test(`${dialect}: utilization divides billable hours by the grouped capacity`, async () => {
+ const sql = (await views(dialect))["v_memberutilization"] ?? "";
+ const capacity = `CAST(m."weekly_capacity_hours" * 52 AS ${real}) / 12`;
+ expect(sql).toContain(`${capacity} AS "capacity_hours"`);
+ expect(sql).toContain(`CAST(${BILLABLE[dialect]} * 100 AS ${real}) / NULLIF(${capacity}, 0) AS "utilization"`);
+ expect(sql).toMatch(/GROUP BY[^;]*m\."weekly_capacity_hours"/);
+ });
+
+ test(`${dialect}: a subtraction of two measures is cast to the decimal it is typed as`, async () => {
+ const sql = (await views(dialect))["v_memberutilization"] ?? "";
+ expect(sql).toContain(`AS "non_billable_hours"`);
+ expect(sql).toMatch(new RegExp(`CAST\\(COALESCE\\(SUM\\(t\\."hours"\\), 0(\\.0)?\\) - .* AS ${real}\\) AS "non_billable_hours"`));
+ });
+
+ test(`${dialect}: a ratio operand is parenthesised under the multiplication`, async () => {
+ const sql = (await views(dialect))["v_memberutilization"] ?? "";
+ expect(sql).toMatch(new RegExp(`CAST\\(\\(CAST\\(.* / NULLIF\\(.*\\)\\) \\* 100 AS ${real}\\) AS "billable_share_pct"`));
+ });
+
+ test(`${dialect}: budget burn divides cost by the project's budget, null when it is 0`, async () => {
+ const sql = (await views(dialect))["v_projectburn"] ?? "";
+ expect(sql).toContain(`CAST(SUM(t."cost") AS ${real}) / NULLIF(p."budget", 0) AS "budget_burn"`);
+ });
+ }
+
+ test("mysql divides without a cast and keeps the operator precedence", async () => {
+ const sql = (await views("mysql"))["v_memberutilization"] ?? "";
+ expect(sql).toContain("(m.`weekly_capacity_hours` * 52) / 12 AS `capacity_hours`");
+ });
+
+ test("Cube: a derived measure over measures is a number member reading them", async () => {
+ const model = buildCubeModel(await load(true), { dialect: "postgres" });
+ const cube = model.cubes.find((c) => c.name.toLowerCase().includes("timeentr"))!;
+ const derived = cube.measures.find((m) => m.name === "nonBillableHours")!;
+ expect(derived.type).toBe("number");
+ expect(derived.sql).toBe("{totalHours} - {billableHours}");
+ const pct = cube.measures.find((m) => m.name === "billableSharePct")!;
+ expect(pct.sql).toBe("{billableShare} * 100");
+ });
+
+ test("Cube: a derived measure that reads a dimension is refused", async () => {
+ const root = await load();
+ expect(() => buildCubeModel(root, { dialect: "postgres" })).toThrow(/ERR_CUBE_DERIVED_DIMENSION/);
+ });
+});
diff --git a/server/typescript/packages/metadata/src/core/reporting/derived-expr.ts b/server/typescript/packages/metadata/src/core/reporting/derived-expr.ts
new file mode 100644
index 0000000000..b53f83d3bf
--- /dev/null
+++ b/server/typescript/packages/metadata/src/core/reporting/derived-expr.ts
@@ -0,0 +1,45 @@
+// FR-044 R13 — the `@expr` grammar of a `measure.derived`: FR-037 R5's first arithmetic wave.
+//
+// A closed subset of the attr.expression node grammar. An operand is `{ field: name }` (a sibling
+// measure.aggregate or measure.ratio, or a numeric attribute dimension the report lists) or
+// `{ value: number }`; an operation is `{ fn: add | subtract | multiply | divide, args: [a, b] }`.
+// The arithmetic members are admitted here first: origin.computed's grammar does not take them
+// yet, so its lowerings and every port's evaluator stay as they are.
+
+import { DERIVED_FNS, type DerivedFn } from "./reporting-constants.js";
+
+export type DerivedExprNode =
+ | { readonly field: string }
+ | { readonly value: number }
+ | { readonly fn: DerivedFn; readonly args: readonly [DerivedExprNode, DerivedExprNode] };
+
+function isObj(v: unknown): v is Record {
+ return typeof v === "object" && v !== null && !Array.isArray(v);
+}
+
+/** True for a node of the grammar, its whole subtree included. */
+export function isDerivedExpr(node: unknown): node is DerivedExprNode {
+ if (!isObj(node)) return false;
+ const keys = Object.keys(node);
+ if (keys.length === 1 && keys[0] === "field") return typeof node.field === "string" && node.field.length > 0;
+ if (keys.length === 1 && keys[0] === "value") return typeof node.value === "number" && Number.isFinite(node.value);
+ if (keys.length === 2 && "fn" in node && "args" in node) {
+ return (
+ (DERIVED_FNS as readonly unknown[]).includes(node.fn) &&
+ Array.isArray(node.args) &&
+ node.args.length === 2 &&
+ node.args.every(isDerivedExpr)
+ );
+ }
+ return false;
+}
+
+/** The names a well-formed expression's `{ field }` operands read, each once, in first-read order. */
+export function derivedExprFields(node: DerivedExprNode, out: string[] = []): string[] {
+ if ("field" in node) {
+ if (!out.includes(node.field)) out.push(node.field);
+ } else if ("fn" in node) {
+ for (const a of node.args) derivedExprFields(a, out);
+ }
+ return out;
+}
diff --git a/server/typescript/packages/metadata/src/core/reporting/meta-measure.ts b/server/typescript/packages/metadata/src/core/reporting/meta-measure.ts
index 3e914f2865..ada2cfaf3c 100644
--- a/server/typescript/packages/metadata/src/core/reporting/meta-measure.ts
+++ b/server/typescript/packages/metadata/src/core/reporting/meta-measure.ts
@@ -5,28 +5,43 @@
import { MetaData } from "../../shared/meta-data.js";
import {
MEASURE_AGGS,
+ MEASURE_SUBTYPE_DERIVED,
MEASURE_SUBTYPE_RATIO,
REPORTING_ATTR_AGG,
REPORTING_ATTR_DEFAULT,
REPORTING_ATTR_DENOMINATOR,
REPORTING_ATTR_DISTINCT,
+ REPORTING_ATTR_EXPR,
REPORTING_ATTR_FILTER,
REPORTING_ATTR_NUMERATOR,
REPORTING_ATTR_OF,
REPORTING_ATTR_SEGMENT,
type MeasureAgg,
} from "./reporting-constants.js";
+import { isDerivedExpr, type DerivedExprNode } from "./derived-expr.js";
function optionalString(v: unknown): string | undefined {
return typeof v === "string" ? v : undefined;
}
export class MetaMeasure extends MetaData {
- /** True for `measure.ratio`; false for `measure.aggregate`. */
+ /** True for `measure.ratio`. */
isRatio(): boolean {
return this.subType === MEASURE_SUBTYPE_RATIO;
}
+ /** True for `measure.derived`. */
+ isDerived(): boolean {
+ return this.subType === MEASURE_SUBTYPE_DERIVED;
+ }
+
+ /** `measure.derived`'s `@expr`, when it is a well-formed arithmetic expression (rule M11
+ * refuses any other). ADR-0039: resolving. */
+ expr(): DerivedExprNode | undefined {
+ const v = this.attr(REPORTING_ATTR_EXPR);
+ return isDerivedExpr(v) ? v : undefined;
+ }
+
/** The aggregate function (`measure.aggregate` only). */
agg(): MeasureAgg | undefined {
const v = this.attr(REPORTING_ATTR_AGG);
diff --git a/server/typescript/packages/metadata/src/core/reporting/report-describe.ts b/server/typescript/packages/metadata/src/core/reporting/report-describe.ts
index d6db439474..0758c096bd 100644
--- a/server/typescript/packages/metadata/src/core/reporting/report-describe.ts
+++ b/server/typescript/packages/metadata/src/core/reporting/report-describe.ts
@@ -20,7 +20,13 @@ import type { MetaObject } from "../object/meta-object.js";
import { OBJECT_REPORT_ATTR_FILTER, OBJECT_REPORT_ATTR_SEGMENT, OBJECT_REPORT_ATTR_SPINE } from "../object/object-constants.js";
import {
DIMENSION_SUBTYPE_TIME,
+ MEASURE_SUBTYPE_DERIVED,
MEASURE_SUBTYPE_RATIO,
+ REPORTING_ATTR_EXPR,
+ DERIVED_FN_ADD,
+ DERIVED_FN_SUBTRACT,
+ DERIVED_FN_MULTIPLY,
+ DERIVED_FN_DIVIDE,
REPORTING_ATTR_AGG,
REPORTING_ATTR_DEFAULT,
REPORTING_ATTR_DENOMINATOR,
@@ -33,6 +39,7 @@ import {
REPORTING_ATTR_VIA,
} from "./reporting-constants.js";
import { reportSpine } from "./report-accessors.js";
+import { isDerivedExpr, type DerivedExprNode } from "./derived-expr.js";
import { reportReadSource } from "./report-read-model.js";
import { reportSpineEntity, type ReportField, type ReportShape } from "./report-shape.js";
@@ -107,7 +114,23 @@ function defaultClause(measure: MetaData): string {
* `@default` ends either with the value it reads when there is nothing to aggregate; a
* defaulted ratio is never null, so its null rule gives way to that clause.
*/
+/** R13: an arithmetic expression in words, fully parenthesised below the top so the reading is exact. */
+function describeExpr(node: DerivedExprNode, top = true): string {
+ if ("field" in node) return tick(node.field);
+ if ("value" in node) return tick(String(node.value));
+ const op =
+ node.fn === DERIVED_FN_ADD ? "+" : node.fn === DERIVED_FN_SUBTRACT ? "-" : node.fn === DERIVED_FN_MULTIPLY ? "×" : "÷";
+ const text = `${describeExpr(node.args[0], false)} ${op} ${describeExpr(node.args[1], false)}`;
+ return top ? text : `(${text})`;
+}
+
export function describeMeasure(measure: MetaData): string {
+ if (measure.subType === MEASURE_SUBTYPE_DERIVED) {
+ const expr = measure.attr(REPORTING_ATTR_EXPR);
+ if (!isDerivedExpr(expr)) return "";
+ const divides = (n: DerivedExprNode): boolean => "fn" in n && (n.fn === DERIVED_FN_DIVIDE || n.args.some(divides));
+ return divides(expr) ? `${describeExpr(expr)}, null when a divisor is 0` : describeExpr(expr);
+ }
const fallback = defaultClause(measure);
if (measure.subType === MEASURE_SUBTYPE_RATIO) {
const numerator = measure.attr(REPORTING_ATTR_NUMERATOR);
@@ -191,6 +214,7 @@ const AGGREGATE_ATTRS = [
REPORTING_ATTR_DEFAULT,
] as const;
const RATIO_ATTRS = [REPORTING_ATTR_NUMERATOR, REPORTING_ATTR_DENOMINATOR, REPORTING_ATTR_DEFAULT] as const;
+const DERIVED_ATTRS = [REPORTING_ATTR_EXPR] as const;
const SEGMENT_ATTRS = [REPORTING_ATTR_FILTER] as const;
/**
@@ -200,7 +224,10 @@ const SEGMENT_ATTRS = [REPORTING_ATTR_FILTER] as const;
*/
export function reportingDescribedAttrs(node: MetaData): readonly string[] {
if (node.type === TYPE_DIMENSION) return node.subType === DIMENSION_SUBTYPE_TIME ? TIME_DIMENSION_ATTRS : DIMENSION_ATTRS;
- if (node.type === TYPE_MEASURE) return node.subType === MEASURE_SUBTYPE_RATIO ? RATIO_ATTRS : AGGREGATE_ATTRS;
+ if (node.type === TYPE_MEASURE) {
+ if (node.subType === MEASURE_SUBTYPE_DERIVED) return DERIVED_ATTRS;
+ return node.subType === MEASURE_SUBTYPE_RATIO ? RATIO_ATTRS : AGGREGATE_ATTRS;
+ }
if (node.type === TYPE_SEGMENT) return SEGMENT_ATTRS;
return [];
}
diff --git a/server/typescript/packages/metadata/src/core/reporting/report-shape.ts b/server/typescript/packages/metadata/src/core/reporting/report-shape.ts
index 2b39d44097..1378b87365 100644
--- a/server/typescript/packages/metadata/src/core/reporting/report-shape.ts
+++ b/server/typescript/packages/metadata/src/core/reporting/report-shape.ts
@@ -486,7 +486,8 @@ interface MeasureDerivation {
/** Table B for one measure. Undefined when its `@of` does not resolve. */
function deriveMeasure(m: MetaMeasure, from: MetaObject, root: MetaRoot): MeasureDerivation | undefined {
- if (m.isRatio()) return { subType: FIELD_SUBTYPE_DECIMAL };
+ // A quotient, and (R13) an arithmetic expression, are decimal whatever their operands.
+ if (m.isRatio() || m.isDerived()) return { subType: FIELD_SUBTYPE_DECIMAL };
const agg = m.agg();
if (agg === AGG_COUNT) return { subType: FIELD_SUBTYPE_LONG };
// any / all are boolean whatever the source (the loader's M4 refuses a non-boolean @of).
diff --git a/server/typescript/packages/metadata/src/core/reporting/reporting-constants.ts b/server/typescript/packages/metadata/src/core/reporting/reporting-constants.ts
index 24af7e3909..7c63216613 100644
--- a/server/typescript/packages/metadata/src/core/reporting/reporting-constants.ts
+++ b/server/typescript/packages/metadata/src/core/reporting/reporting-constants.ts
@@ -25,10 +25,12 @@ export type DimensionSubType = (typeof DIMENSION_SUBTYPES)[number];
/** One aggregate over the declaring entity's own rows. */
export const MEASURE_SUBTYPE_AGGREGATE = "aggregate";
-/** A quotient of two `measure.aggregate` siblings, `numerator / NULLIF(denominator, 0)`.
- * `measure.derived` is deliberately NOT registered: it waits for FR-037 R5. */
+/** A quotient of two `measure.aggregate` siblings, `numerator / NULLIF(denominator, 0)`. */
export const MEASURE_SUBTYPE_RATIO = "ratio";
-export const MEASURE_SUBTYPES = [MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO] as const;
+/** FR-044 R13: arithmetic (`@expr`) over sibling measures and the report's numeric attribute
+ * dimensions, typed decimal. Uses FR-037 R5's first arithmetic wave. */
+export const MEASURE_SUBTYPE_DERIVED = "derived";
+export const MEASURE_SUBTYPES = [MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO, MEASURE_SUBTYPE_DERIVED] as const;
export type MeasureSubType = (typeof MEASURE_SUBTYPES)[number];
/** A named, reusable row filter. The only concrete segment subtype: every `*.base`
@@ -58,6 +60,17 @@ export const REPORTING_ATTR_SEGMENT = "segment";
/** `measure.ratio` operand names. */
export const REPORTING_ATTR_NUMERATOR = "numerator";
export const REPORTING_ATTR_DENOMINATOR = "denominator";
+/** `measure.derived`'s arithmetic expression (an attr.expression). */
+export const REPORTING_ATTR_EXPR = "expr";
+
+/** The arithmetic `fn` members a `measure.derived` `@expr` may use, each with exactly two args.
+ * `divide` lowers as a ratio does: a zero divisor yields null. */
+export const DERIVED_FN_ADD = "add";
+export const DERIVED_FN_SUBTRACT = "subtract";
+export const DERIVED_FN_MULTIPLY = "multiply";
+export const DERIVED_FN_DIVIDE = "divide";
+export const DERIVED_FNS = [DERIVED_FN_ADD, DERIVED_FN_SUBTRACT, DERIVED_FN_MULTIPLY, DERIVED_FN_DIVIDE] as const;
+export type DerivedFn = (typeof DERIVED_FNS)[number];
/** Integer a measure reads when it would otherwise be null (`measure.aggregate` / `measure.ratio`). */
export const REPORTING_ATTR_DEFAULT = "default";
diff --git a/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts b/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts
index 6ed16e8cdf..354707a4fe 100644
--- a/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts
+++ b/server/typescript/packages/metadata/src/core/reporting/reporting-definition.embedded.ts
@@ -172,6 +172,22 @@ export const REPORTING_DEFINITION: ProviderDefinition = {
}
]
},
+ {
+ "type": "measure",
+ "subType": "derived",
+ "description": "A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.",
+ "whenToUse": "A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).",
+ "children": [
+ {
+ "type": "attr",
+ "subType": "expression",
+ "name": "expr",
+ "min": 1,
+ "max": 1,
+ "description": "The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands."
+ }
+ ]
+ },
{
"type": "segment",
"subType": "filter",
diff --git a/server/typescript/packages/metadata/src/index.ts b/server/typescript/packages/metadata/src/index.ts
index ad4284c58c..9d15ac675c 100644
--- a/server/typescript/packages/metadata/src/index.ts
+++ b/server/typescript/packages/metadata/src/index.ts
@@ -47,6 +47,7 @@ export * from "./core/reporting/reporting-constants.js";
export { MetaDimension } from "./core/reporting/meta-dimension.js";
export { MetaMeasure } from "./core/reporting/meta-measure.js";
export { MetaSegment } from "./core/reporting/meta-segment.js";
+export { isDerivedExpr, derivedExprFields, type DerivedExprNode } from "./core/reporting/derived-expr.js";
export {
reportFrom,
reportSpine,
diff --git a/server/typescript/packages/metadata/src/loader/reporting-validation.ts b/server/typescript/packages/metadata/src/loader/reporting-validation.ts
index 6828096844..a1be960941 100644
--- a/server/typescript/packages/metadata/src/loader/reporting-validation.ts
+++ b/server/typescript/packages/metadata/src/loader/reporting-validation.ts
@@ -100,11 +100,15 @@ import {
REPORTING_ATTR_DEFAULT,
REPORTING_ATTR_VIA,
MEASURE_SUBTYPE_AGGREGATE,
+ MEASURE_SUBTYPE_DERIVED,
+ REPORTING_ATTR_EXPR,
+ DERIVED_FNS,
} from "../core/reporting/reporting-constants.js";
import { MetaDimension } from "../core/reporting/meta-dimension.js";
import { MetaMeasure } from "../core/reporting/meta-measure.js";
import { MetaSegment } from "../core/reporting/meta-segment.js";
-import { isFlattenedField, measureResultSubType } from "../core/reporting/report-shape.js";
+import { isFlattenedField, measureResultSubType, resolveDimensionOf } from "../core/reporting/report-shape.js";
+import { derivedExprFields } from "../core/reporting/derived-expr.js";
import {
reportDerivedFieldName,
reportDimensionItems,
@@ -624,6 +628,10 @@ function checkMeasure(ctx: MemberCtx, measure: MetaMeasure): void {
checkRatioOperands(ctx, measure, err);
return;
}
+ if (measure.isDerived()) {
+ checkDerivedExpr(ctx, measure, err);
+ return;
+ }
if (measure.subType !== MEASURE_SUBTYPE_AGGREGATE) return;
const checked = checkAggregateColumns(ctx, measure, err);
@@ -809,6 +817,54 @@ function checkRatioOperands(ctx: MemberCtx, ratio: MetaMeasure, err: (message: s
}
}
+/**
+ * M11 — a measure.derived's @expr is FR-037 R5's arithmetic over operands a report can read:
+ * each `{ field }` names a numeric measure.aggregate or measure.ratio of the same entity, or a
+ * numeric attribute dimension of it (R13 then requires the report to list that dimension). A
+ * derived measure never reads another derived measure, and a name both a measure and a
+ * dimension carry is refused rather than guessed. One error per offending operand.
+ */
+function checkDerivedExpr(ctx: MemberCtx, measure: MetaMeasure, err: (message: string) => void): void {
+ const raw = measure.attr(REPORTING_ATTR_EXPR);
+ if (raw === undefined) return; // missing @expr is ERR_MISSING_REQUIRED_ATTR
+ const expr = measure.expr();
+ if (expr === undefined) {
+ err(
+ `@expr is not an arithmetic expression. Each node is { field: }, { value: } or { fn: ${DERIVED_FNS.join(" | ")}, args: [, ] }.`,
+ );
+ return;
+ }
+ const entityKey = ctx.declaring.resolutionKey();
+ for (const name of derivedExprFields(expr)) {
+ const target = childOfType(ctx.host, TYPE_MEASURE, name);
+ const dim = childOfType(ctx.host, TYPE_DIMENSION, name);
+ if (target !== undefined && dim !== undefined) {
+ err(`@expr names '${name}', which is both a measure and a dimension of '${entityKey}'. Rename one.`);
+ } else if (target !== undefined) {
+ if (target.subType === MEASURE_SUBTYPE_DERIVED) {
+ err(`@expr names '${name}', a measure.derived. A derived measure reads aggregates, ratios and dimensions, not another derived measure.`);
+ } else if (target instanceof MetaMeasure && isMetaObject(ctx.host) && isMetaRoot(ctx.root)) {
+ const result = measureResultSubType(target, ctx.host, ctx.root);
+ if (result !== undefined && !NUMERIC_FIELD_SUBTYPES.includes(result)) {
+ err(`@expr names measure '${name}', whose result is a ${result}, not a number.`);
+ }
+ }
+ } else if (dim instanceof MetaDimension) {
+ if (dim.isTime()) {
+ err(`@expr names '${name}', a dimension.time. Arithmetic reads a numeric attribute dimension.`);
+ } else if (isMetaObject(ctx.host) && isMetaRoot(ctx.root)) {
+ const of = resolveDimensionOf(dim, ctx.host, ctx.root);
+ if (of !== undefined && !NUMERIC_FIELD_SUBTYPES.includes(of.field.subType)) {
+ err(`@expr names dimension '${name}', whose @of is a field.${of.field.subType}, not a number.`);
+ }
+ }
+ } else {
+ err(`@expr names '${name}', which is no measure or dimension of '${entityKey}'.`);
+ }
+ }
+}
+
// ---------------------------------------------------------------------------
// S1 / F2 — a reporting-host @filter over its entity
// ---------------------------------------------------------------------------
@@ -1047,6 +1103,8 @@ function checkReport(root: MetaData, report: MetaData, sink: ErrorSink): void {
// R12 — amounts in different units are never combined.
checkValueObjectUnits(report, from, err);
+ // R13 — a derived measure reads only dimensions the report groups by.
+ checkDerivedDimensions(report, from, err);
// R7 — @segment names a segment of @from.
const segment = report.attr(OBJECT_REPORT_ATTR_SEGMENT);
@@ -1125,10 +1183,7 @@ function checkValueObjectUnits(report: MetaData, from: MetaData, err: (message:
for (const item of reportMeasureNames(report)) {
const listed = childOfType(from, TYPE_MEASURE, item.slice(item.lastIndexOf(CHILD_REF_SEPARATOR) + 1));
if (!(listed instanceof MetaMeasure)) continue;
- const aggregates = listed.isRatio()
- ? [listed.numerator(), listed.denominator()].map((n) => (n === undefined ? undefined : childOfType(from, TYPE_MEASURE, n)))
- : [listed];
- for (const m of aggregates) {
+ for (const m of aggregatesRead(listed, from)) {
if (!(m instanceof MetaMeasure) || m.subType !== MEASURE_SUBTYPE_AGGREGATE || checked.has(m)) continue;
checked.add(m);
const agg = m.agg();
@@ -1155,6 +1210,47 @@ function checkValueObjectUnits(report: MetaData, from: MetaData, err: (message:
}
}
+/**
+ * The measures `listed` aggregates through: itself for a measure.aggregate, its two operands for a
+ * ratio, and for a measure.derived each measure its @expr names (a ratio there read through its
+ * operands). Unresolved names are left out; the member rules report them.
+ */
+function aggregatesRead(listed: MetaMeasure, from: MetaData): MetaData[] {
+ const measure = (n: string | undefined): MetaData | undefined =>
+ n === undefined ? undefined : childOfType(from, TYPE_MEASURE, n);
+ const operandsOf = (m: MetaData | undefined): (MetaData | undefined)[] =>
+ m instanceof MetaMeasure && m.isRatio() ? [measure(m.numerator()), measure(m.denominator())] : [m];
+ if (listed.isDerived()) {
+ const expr = listed.expr();
+ return (expr === undefined ? [] : derivedExprFields(expr))
+ .flatMap((n) => operandsOf(measure(n)))
+ .filter((m): m is MetaData => m !== undefined);
+ }
+ return operandsOf(listed).filter((m): m is MetaData => m !== undefined);
+}
+
+/**
+ * R13 — a measure.derived that reads an attribute dimension reads that dimension's value for each
+ * group, so the report must list the dimension in @dimensions. A name that is also a measure is
+ * M11's to report.
+ */
+function checkDerivedDimensions(report: MetaData, from: MetaData, err: (message: string) => void): void {
+ const listedDims = new Set(reportDimensionItems(report).map((i) => i.name));
+ for (const item of reportMeasureNames(report)) {
+ const m = childOfType(from, TYPE_MEASURE, item.slice(item.lastIndexOf(CHILD_REF_SEPARATOR) + 1));
+ const expr = m instanceof MetaMeasure && m.isDerived() ? m.expr() : undefined;
+ if (expr === undefined) continue;
+ for (const name of derivedExprFields(expr)) {
+ if (listedDims.has(name) || childOfType(from, TYPE_MEASURE, name) !== undefined) continue;
+ if (childOfType(from, TYPE_DIMENSION, name) === undefined) continue;
+ err(
+ `: measure '${m!.name}' reads dimension '${name}', which @dimensions does not list. A derived measure ` +
+ `reads a dimension's value for each group, so the report must group by it.`,
+ );
+ }
+ }
+}
+
/**
* R3 for one `@measures` item (bare `name` or dotted `Entity.name`). Returns
* the measure's name when it is a measure of @from (for R6), else reports
diff --git a/server/typescript/packages/metadata/test/reporting-registry.test.ts b/server/typescript/packages/metadata/test/reporting-registry.test.ts
index 5deaeca98a..b4d6667751 100644
--- a/server/typescript/packages/metadata/test/reporting-registry.test.ts
+++ b/server/typescript/packages/metadata/test/reporting-registry.test.ts
@@ -3,7 +3,8 @@ import { composeRegistry, coreProviders } from "../src/index.js";
import {
TYPE_DIMENSION, TYPE_MEASURE, TYPE_SEGMENT,
DIMENSION_SUBTYPE_ATTRIBUTE, DIMENSION_SUBTYPE_TIME,
- MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO, SEGMENT_SUBTYPE_FILTER,
+ MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO, MEASURE_SUBTYPE_DERIVED, SEGMENT_SUBTYPE_FILTER,
+ REPORTING_ATTR_EXPR,
TIME_GRAINS, MEASURE_AGGS,
} from "../src/core/reporting/reporting-constants.js";
import { TYPE_OBJECT } from "../src/shared/base-types.js";
@@ -22,8 +23,13 @@ describe("FR-044 reporting vocabulary registration", () => {
}
});
- test("does not register measure.derived (waits for FR-037 R5)", () => {
- expect(registry.find(TYPE_MEASURE, "derived")).toBeUndefined();
+ test("registers measure.derived with a required expression @expr and no @default (R13)", () => {
+ const derived = registry.find(TYPE_MEASURE, MEASURE_SUBTYPE_DERIVED)!;
+ expect(derived).toBeDefined();
+ const expr = derived.attributes.find((a) => a.name === REPORTING_ATTR_EXPR);
+ expect(expr?.valueType).toBe("expression");
+ expect(expr?.required).toBe(true);
+ expect(derived.attributes.find((a) => a.name === "default")).toBeUndefined();
});
test("object.report registers an optional string @spine (R8)", () => {
diff --git a/spec/metamodel/reporting.json b/spec/metamodel/reporting.json
index 5eedaf0721..adbe87f9ed 100644
--- a/spec/metamodel/reporting.json
+++ b/spec/metamodel/reporting.json
@@ -35,6 +35,12 @@
{ "type": "attr", "subType": "string", "name": "denominator", "min": 1, "max": 1, "description": "Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field." },
{ "type": "attr", "subType": "int", "name": "default", "min": 0, "max": 1, "description": "Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio." }
] },
+ { "type": "measure", "subType": "derived",
+ "description": "A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.",
+ "whenToUse": "A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).",
+ "children": [
+ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands." }
+ ] },
{ "type": "segment", "subType": "filter",
"description": "A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment.",
"whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.",
From 6333671a1384ac249b7cfbee95b549dbf8dfbfde Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Thu, 12 Nov 2026 07:47:35 -0500
Subject: [PATCH 3/6] feat(reporting): measure.derived in C#, Java and Python;
docs and gates (FR-044 R13)
Ports measure.derived (M11 @expr validation, R13 dimension operands, the
nullable-decimal column type) to the C#, Java and Python loaders, so all four
loader ports pass the shared derived and value-object fixtures.
Also:
- docs: reporting.md, the authoring skill references, the FR-044 spec (R11
amendment) and an FR-037 R5 note; CHANGELOG under Unreleased.
- a measureDerived requirement, with the requirement harness regenerated.
- fixture counts (490) in AGENTS.md and CONFORMANCE.md, the site payload and
the site reference regenerated.
- cube-members.ts: imports moved above valueObjectMemberError, so the eject
scanner sees every import and the ejected cube template compiles.
- Java: a measure whose @agg is outside the closed set no longer throws an NPE
in the value-object unit check.
- test typecheck fixes for the derived and value-object Cube tests.
---
AGENTS.md | 2 +-
CHANGELOG.md | 39 +++++-
.../references/declaring-reports.md | 13 +-
.../references/reporting.md | 2 +
docs/CONFORMANCE.md | 6 +-
docs/features/reporting.md | 99 +++++++++++++-
...on-expressiveness-and-write-once-design.md | 4 +
...2026-10-02-fr-044-core-reporting-design.md | 51 +++++++-
examples/showcase/site-payload.json | 2 +-
.../references/declaring-reports.md | 13 +-
.../references/reporting.md | 2 +
.../references/declaring-reports.md | 13 +-
.../references/reporting.md | 2 +
.../references/declaring-reports.md | 13 +-
.../references/reporting.md | 2 +
.../references/declaring-reports.md | 13 +-
.../references/reporting.md | 2 +
.../references/declaring-reports.md | 13 +-
.../references/reporting.md | 2 +
.../csharp/RequirementHarnessTests.cs | 6 +-
.../java/RequirementHarnessTest.java | 7 +-
.../kotlin/RequirementHarnessTest.kt | 7 +-
.../python/test_requirement_harness.py | 7 +-
.../typescript/requirement-harness.test.ts | 7 +-
metaobjects/meta.requirements.yaml | 13 ++
.../ReportShapeTests.cs | 20 +++
.../MetaObjects/Core/Reporting/DerivedExpr.cs | 60 +++++++++
.../MetaObjects/Core/Reporting/ReportShape.cs | 2 +-
.../Core/Reporting/ReportingConstants.cs | 22 +++-
.../Core/Reporting/ReportingSchema.cs | 7 +
server/csharp/MetaObjects/CoreTypes.cs | 4 +-
.../Loader/ValidationPasses.Reporting.cs | 114 +++++++++++++++-
server/csharp/MetaObjects/Meta/MetaMeasure.cs | 9 +-
.../MetaObjects/SpecMetamodel/reporting.json | 12 +-
.../loader/ReportingValidation.java | 123 ++++++++++++++++--
.../metaobjects/reporting/DerivedExpr.java | 72 ++++++++++
.../metaobjects/reporting/DerivedMeasure.java | 44 +++++++
.../metaobjects/reporting/MetaMeasure.java | 17 ++-
.../metaobjects/reporting/ReportShape.java | 19 ++-
.../reporting/ReportingConstants.java | 15 ++-
.../ReportingTypesMetaDataProvider.java | 5 +-
.../loader/ReportingValidationTest.java | 2 +-
.../reporting/ReportShapeTest.java | 24 ++++
server/python/src/metaobjects/core_types.py | 14 ++
.../metaobjects/loader/validate_reporting.py | 107 +++++++++++++--
.../meta/core/reporting/derived_expr.py | 62 +++++++++
.../meta/core/reporting/meta_measure.py | 15 ++-
.../meta/core/reporting/report_shape.py | 3 +-
.../core/reporting/reporting_constants.py | 16 ++-
.../metaobjects/spec_metamodel/reporting.json | 12 +-
server/python/tests/test_report_shape.py | 33 +++++
.../codegen-ts/src/cube/cube-members.ts | 20 +--
.../projection/extract-report-spec.test.ts | 26 +++-
.../report-derived-measures.test.ts | 4 +-
.../report-value-object-members.test.ts | 2 +-
.../metadata/test/report-describe.test.ts | 25 ++++
.../metadata/test/report-shape.test.ts | 22 ++++
site-reference/index.html | 5 +
site-reference/types/dimension.html | 4 +-
site-reference/types/measure.html | 30 ++++-
60 files changed, 1204 insertions(+), 107 deletions(-)
create mode 100644 server/csharp/MetaObjects/Core/Reporting/DerivedExpr.cs
create mode 100644 server/java/metadata/src/main/java/com/metaobjects/reporting/DerivedExpr.java
create mode 100644 server/java/metadata/src/main/java/com/metaobjects/reporting/DerivedMeasure.java
create mode 100644 server/python/src/metaobjects/meta/core/reporting/derived_expr.py
diff --git a/AGENTS.md b/AGENTS.md
index 72567644f8..b4e59695a8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -71,7 +71,7 @@ PyPI has had no product change since `0.25.0` — nothing is broken.
- **Kotlin** — `codegen-kotlin` (KotlinPoet on JVM): entity + Exposed table + Spring controller + payload + relations + filter allowlist + validator + stored-proc + output-parser generators. `integration-tests-kotlin` runs the persistence-conformance corpus through Exposed against Testcontainers Postgres.
**Cross-port conformance corpora** (every port runs the shared corpus):
-- Metamodel: `fixtures/conformance/` (471 fixtures; 38 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
+- Metamodel: `fixtures/conformance/` (490 fixtures; 38 shared corpora in total — per-corpus counts + the corpus x port matrix live in `docs/CONFORMANCE.md`). TS / C# / Java / Python all green.
- Render: `fixtures/render-conformance/`. TS / C# / Java / Kotlin / Python byte-identical.
- Persistence: `fixtures/persistence-conformance/`. **Query** scenarios run on every port (TS / C# / Java / Kotlin / Python), each provisioning its test DB by executing the committed, TS-produced `canonical/schema.postgres.sql` (Postgres only — Derby dropped for the cross-port query corpus, ADR-0015; the FR-044 `report-*` scenarios also run on SQLite, MySQL and D1 where a port has the engine, see [docs/CONFORMANCE.md](docs/CONFORMANCE.md)). The **migration** scenarios are exercised by **TS only** (TS owns schema migrations). **The corpus now gates WRITES, not just reads (SP-H):** an `op: roundtrip` scenario type INSERTs through each port's runtime/ORM write codec (NOT raw SQL), reads the row back, and asserts the wire-normalized value. The `AllTypes` entity (`roundtrip-all-types.yaml`) carries one field of **every** persistable `field.*` subtype — string/int/long/double/float/decimal/boolean/date/time/timestamp(+tz)/currency/enum/uuid/object — plus an **array-of-VO** `field.object @isArray @storage:jsonb` column (`labels`, written as 2-element / empty-`[]` / single-element arrays across the three rows) — so every subtype write+read (incl. the array-of-value-object jsonb codec) round-trips through every port against Testcontainers PG. (`field.byte`/`field.short`/`field.class` were cut as non-functional registration-only stubs — the matrix tracks only genuinely-supported subtypes; see `fixtures/registry-conformance/README.md` → "Per-subtype write-round-trip matrix".)
- API-contract: `fixtures/api-contract-conformance/`. TS / C# / Java / Kotlin / Python all green — each port runs **two lanes**: a hand-rolled reference server AND its **generated** API artifact booted over HTTP (the deployed controller/routes; TS+C# full-stack vs Testcontainers PG, Java/Kotlin/Python generated controller + in-memory repo behind the consumer seam). The generated fan-out found 10 real deployment bugs golden snapshots missed. Three sub-corpora run the **generated lane only, on all five ports** — `write-through/`, `projection/` (F22: a view-only `object.projection` serves GET list + GET by id and answers every write verb with `405 {"error": "method_not_allowed"}`) and `report/` (FR-044: a view-backed `object.report` serves GET list, answers `POST` with that same `405`, and mounts no `/{id}` route). That is deliberate, not a gap: what is under test is whether a port's GENERATOR emits those routes, and a hand-rolled reference server would answer every scenario by construction. The `m2m/` sub-corpus also gates **TPH x M:N together** (base-declared, subtype-declared, abstract-mid-declared, a non-subtype source onto a subtype TARGET, and the cross-subtype source id answering `200 []`) — the two corpora were originally built disjoint (`tph/` had no relationships, `m2m/` no discriminators), which is precisely how that defect class survived.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2e818d8bb9..c8249dd704 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,38 @@ here.**
## [Unreleased]
+**New metamodel vocabulary: `measure.derived` and its `@expr`.** It is additive: nothing that
+loaded before stops loading. If this ships after 1.3.0, the release moves `metamodelVersion`.
+
+### Added
+
+- **Report measures over Money and other value-object members (FR-044 R12).** A dimension's or
+ measure's `@of` may name `Entity.field.member`, a member of a value object stored with
+ `@storage: flattened` (`Payment.amount.amount`, `Payment.amount.currency`); the report reads
+ the member's own column. A `sum`, `avg`, `min` or `max` of a numeric member loads only when the
+ report lists a dimension over each non-numeric member of the same value object (its
+ currency), so amounts in different currencies are never combined; the rule follows the
+ measure into ratio and derived-measure operands. A member of a jsonb value object, an unknown
+ member and a deeper path are refused at load, and the Cube exporter refuses member paths.
+ Loader rules and report-shape derivation in TypeScript, C#, Java and Python.
+- **`measure.derived`: arithmetic between measures (FR-044 R13).** `@expr` is FR-037 R5's
+ first arithmetic wave: `add`, `subtract`, `multiply` and `divide` over two operands, where an
+ operand is `{ "field": }` (a numeric `measure.aggregate` or `measure.ratio` of the
+ entity, or a numeric attribute dimension the report lists) or `{ "value": }`. It
+ expresses a ratio scaled to a percent and a measure over a grouped quantity (utilization =
+ billable hours × 100 ÷ (weekly capacity × 52 ÷ 12); budget burn = cost ÷ budget). The result
+ is a nullable `decimal`; `divide` reads null on a zero divisor. `meta migrate` lowers it on
+ Postgres, SQLite, MySQL and D1, every port reads and serves it, and the Cube exporter writes
+ one over measures as a `number` member (one reading a dimension is refused). Loader rule M11,
+ report rule R13 and a conformance fixture per refusal, in every loader port.
+
+### Changed
+
+- **Agent context routes report work to the reporting vocabulary.** The `meta init` agent guide
+ and the `metaobjects-authoring` skill now send grouped totals, dashboard numbers and read-only
+ report views to `object.report` (`references/declaring-reports.md`) before the `@sql` escape,
+ which they describe as the last resort for bodies the vocabulary cannot express.
+
### Fixed
- **A projection view keeps the columns a reverse `@via` hop feeds.** An origin `@via` that walks
@@ -24,13 +56,6 @@ here.**
rather than summing the flattened amount column, keeps a sum from adding amounts in different
currencies. `count` is unaffected.
-### Changed
-
-- **Agent context routes report work to the reporting vocabulary.** The `meta init` agent guide
- and the `metaobjects-authoring` skill now send grouped totals, dashboard numbers and read-only
- report views to `object.report` (`references/declaring-reports.md`) before the `@sql` escape,
- which they describe as the last resort for bodies the vocabulary cannot express.
-
## [1.3.0] — 2026-11-11
_npm `1.3.0` (full lockstep across all 14 `@metaobjectsdev/*` publish candidates)._
diff --git a/agent-context/skills/metaobjects-authoring/references/declaring-reports.md b/agent-context/skills/metaobjects-authoring/references/declaring-reports.md
index 544a7fbe69..ecaaa30cc1 100644
--- a/agent-context/skills/metaobjects-authoring/references/declaring-reports.md
+++ b/agent-context/skills/metaobjects-authoring/references/declaring-reports.md
@@ -18,6 +18,10 @@ and an `object.report` combines them by name. Four node kinds:
`field.boolean` `@of`, or no `@of` and a `@filter` or `@segment`: `{ "name": "hasError",
"@agg": "any", "@filter": { "success": false } }` is "some row has `success` false" (a row
whose condition is null does not pass);
+- `measure.derived` — `@expr` arithmetic (`add`, `subtract`, `multiply`, `divide`, two operands
+ each) over `{ "field": }` and `{ "value": }`:
+ utilization is `billableHours × 100 ÷ (weeklyCapacityHours × 52 ÷ 12)`. A dimension it reads
+ must be in the report's `@dimensions`; it never reads another derived measure;
- `segment.filter` — a named, reusable `@filter` ("active purchase");
- `object.report` — a top-level object: `@from` an entity, `@dimensions` (`name` or
`name:grain`), `@measures`.
@@ -72,6 +76,11 @@ Three rules an author trips on:
measure (a time dimension at a grain is ``, so `purchasedAt:day` is
`purchasedAtDay`). A `field.*` or `identity.*` child on a report is an error.
+**Money.** `@of` may name a member of a `@storage: flattened` value object,
+`Payment.amount.amount`. A `sum`, `avg`, `min` or `max` of it loads only when the report also
+lists a dimension over each non-numeric member (`Payment.amount.currency`), so currencies are
+never added together. A jsonb value object's members are refused.
+
Two questions to answer for every report:
- **Do I want the rows that have no facts?** A report's rows come from the facts, so a
@@ -99,8 +108,8 @@ A report `@from` a TPH subtype is refused when its view is derived (the subtype
base's table): declare it `@from` the base with an `@filter` on the discriminator field.
What does not exist: no grid or form for a report (TypeScript generates a list hook; no other port has a client tier), no way to narrow which
-derived fields are filterable, no `measure.derived`
-(arithmetic between measures beyond `measure.ratio`), no query-time choice of dimensions or
+derived fields are filterable, no product measure
+(`sum(hours × rate)`), no member of a jsonb value object, no query-time choice of dimensions or
measures (a report is a fixed, compiled combination), and no time-zone vocabulary (grains and
relative dates are UTC). Column types, the null rules, Monday weeks and per-engine differences
are in `references/reporting.md`.
diff --git a/agent-context/skills/metaobjects-authoring/references/reporting.md b/agent-context/skills/metaobjects-authoring/references/reporting.md
index 33c60ec19b..eaa55e3356 100644
--- a/agent-context/skills/metaobjects-authoring/references/reporting.md
+++ b/agent-context/skills/metaobjects-authoring/references/reporting.md
@@ -49,6 +49,7 @@ A report declares no fields. Its columns are one per `@dimensions` item in liste
| `min` / `max` | the measure's name | the `@of` field's type | no |
| `any` / `all` (boolean OR / AND, `bool_or` / `bool_and`; over a `field.boolean` `@of`, or with no `@of` over the measure's `@filter` / `@segment`) | the measure's name | `boolean` | no |
| `measure.ratio` | the measure's name | `decimal` | no |
+| `measure.derived` | the measure's name | `decimal` | no |
| any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads the default instead of null |
| in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the field is `@required` or in that entity's `identity.primary`; no for a dimension beyond the spine entity |
@@ -72,6 +73,7 @@ Add `"startOf": "day"`, `"week"` or `"month"` to cut the window to a calendar bo
- A `sum` of nothing is **null**, not zero: no matching rows, or a filtered measure that matched none of a group's rows. So are `avg`, `min` and `max`.
- An `any` or `all` over no rows, or only null values, is **null**, not `false`. `"@default": 0` reads `false` and `"@default": 1` reads `true` (any other number is refused).
- A ratio is `numerator / NULLIF(denominator, 0)`: a zero denominator is **null**. Each operand must be a numeric measure: a `count`, a `sum`, an `avg`, or a `min` or `max` of a numeric field. An `any` or `all` (a boolean), or a `min` or `max` of a date, timestamp, string, uuid or enum, is refused as `@numerator` or `@denominator`. For a share, use an `@agg: count` with a `@filter`.
+- A derived measure's `divide` divides as a ratio does (null on a zero divisor); a null operand makes it null, so default the operand measure when `0` is meant.
- A report with no dimensions is one row for the whole table, and still one row over an empty table (counts `0`, sums and ratios null).
**Ask: is zero true here, or is null?** If "nothing to aggregate" means zero (revenue of a program nobody bought is `0`), declare `"@default": 0` on the measure (`revenue` in the example under "Rows with no facts"). If it means unknown (the average rating of a product with no ratings is not `0`), leave it null. Do not default in the client what the model can state once.
diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md
index 565a911200..5bfc57f808 100644
--- a/docs/CONFORMANCE.md
+++ b/docs/CONFORMANCE.md
@@ -26,7 +26,7 @@ regenerate with `ls -d fixtures//*/ | wc -l` for directory-shaped corpor
| Corpus | Fixtures | TS | Java | Kotlin | C# | Python |
|---|---|---|---|---|---|---|
-| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 471 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ |
+| [`fixtures/conformance/`](../fixtures/conformance/) (metamodel) | 490 | ✓ | ✓ | inherits via `metadata-ktx` | ✓ | ✓ |
| [`fixtures/yaml-conformance/`](../fixtures/yaml-conformance/) | 16 | 16 / 16 | 15 / 16 (1 ledgered: `yaml-quoted-leading-zero` — Java pipeline strips quotes off `"007"`) | inherits via Java | 15 / 16 (1 ledgered: `error-yaml-coerced-hex-in-string` — YamlDotNet doesn't coerce `0xFF`) | 16 / 16 |
| [`fixtures/verify-conformance/`](../fixtures/verify-conformance/) | 45 | ✓ | ✓ | inherits via Java | ✓ | ✓ |
| [`fixtures/verify-strict-conformance/`](../fixtures/verify-strict-conformance/) | 1 | ✓ | — | — | — | ✓ |
@@ -354,7 +354,7 @@ unit-test runners (`bun test`, `dotnet test`, `pytest`, `mvn test`) pull Docker.
## Fixture-to-doc mapping
-### `fixtures/conformance/` — metamodel loader + canonical serializer (471)
+### `fixtures/conformance/` — metamodel loader + canonical serializer (490)
| Fixture prefix | Feature doc |
|---|---|
@@ -716,7 +716,7 @@ JSON and verify payload feeds it unchanged.
## Orphaned fixtures (tested but not yet documented)
-The fixtures in the nine corpora mapped above (metamodel 471 + yaml 16 + verify 45
+The fixtures in the nine corpora mapped above (metamodel 490 + yaml 16 + verify 45
+ render 18 + persistence 62 + api-contract 123 + source-resolution 25 + scope 10 +
dependency 47) each map to a feature doc, and so do the two requirement corpora, `shared-model-conformance`, the
`cube-model` corpus and `explorer-conformance`, whose case lists live in their own READMEs. None are orphaned today. The remaining
diff --git a/docs/features/reporting.md b/docs/features/reporting.md
index 00e2dc5579..2fea4c10a3 100644
--- a/docs/features/reporting.md
+++ b/docs/features/reporting.md
@@ -24,8 +24,9 @@ with `@spine`. See [Exporting to Cube](#exporting-to-cube) and [cube-export.md](
**What does not exist yet.** No grid, form or other UI-tier output is generated for a report
in any port; TypeScript's list hook is the one client piece (the 1.2 `reporting` library
-adds the rest). There is no dbt MetricFlow exporter (it is built when an adopter asks), no `measure.derived`,
-no query-time choice of dimensions or measures (a report is a fixed combination, compiled
+adds the rest). There is no dbt MetricFlow exporter (it is built when an adopter asks), no product
+measure (`sum(hours × rate)`, an aggregate over a per-row expression), no member read out of a
+jsonb value object, no query-time choice of dimensions or measures (a report is a fixed combination, compiled
once), and no time-zone vocabulary: time grains and relative dates are UTC.
**Entirely opt-in.** Nothing here applies to a model that declares none of it. The change
@@ -47,8 +48,7 @@ mean what they appear to mean: a measure of one table in a report over another,
## What is registered
-Exactly these names, and nothing else (`measure.derived` is **not** registered; it waits for
-FR-037 R5's arithmetic wave and will need its own agreement):
+Exactly these names, and nothing else:
| Node | Lives on | Attributes |
|---|---|---|
@@ -56,6 +56,7 @@ FR-037 R5's arithmetic wave and will need its own agreement):
| `dimension.time` | `object.entity` | `@of` (required), `@via`, `@grains` (required, array) |
| `measure.aggregate` | `object.entity` | `@agg` (required), `@of` (required, array, except `any` / `all`), `@distinct`, `@filter`, `@segment`, `@default` |
| `measure.ratio` | `object.entity` | `@numerator` (required), `@denominator` (required), `@default` |
+| `measure.derived` | `object.entity` | `@expr` (required, an arithmetic expression) |
| `segment.filter` | `object.entity` | `@filter` (required) |
| `object.report` | root | `@from` (required), `@dimensions` (array), `@measures` (required, array), `@segment`, `@filter`, `@spine` |
@@ -65,6 +66,8 @@ Closed sets:
in every lowering.
- `@agg`: `count, sum, avg, min, max, any, all`. `any` and `all` are boolean OR and AND
(Postgres `bool_or` / `bool_and`) and are the names `origin.aggregate` already uses.
+- `@expr` operations: `add, subtract, multiply, divide`, each of exactly two operands (see
+ [Arithmetic over measures](#arithmetic-over-measures-measurederived)).
`@spine` is a path written like a dimension's `@via`. A measure's `@default` is an integer.
@@ -279,6 +282,8 @@ physical column name is your naming strategy applied to the **derived field name
| `min` / `max` | the measure's name | the `@of` field's type | no |
| `any` / `all` | the measure's name | `boolean` | no |
| `measure.ratio` | the measure's name | `decimal` | no |
+| `measure.derived` | the measure's name | `decimal` | no |
+| a dimension or `min` / `max` over `Entity.field.member` | as for a field | the member's type | the dimension rule, read on the member (a required member of a required value object is required) |
| any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads its `@default` instead of null |
| in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the `@of` field is required (`@required` or a `validator.required` child) or one of the spine entity's `identity.primary` `@fields`; no for a dimension reached beyond the spine entity |
@@ -327,6 +332,82 @@ applied. The aggregates:
A report with no dimensions is one row over the whole table. Over an **empty** table that row
still exists: counts are `0`, sums and ratios are null, or their `@default`.
+### Money and other value-object members
+
+A `field.object` stored with `@storage: flattened` has a column per member (`amount_amount`,
+`amount_currency` for a `Money` named `amount`). A dimension's or measure's `@of` may name one
+of them as `Entity.field.member`:
+
+```jsonc
+{ "dimension.attribute": { "name": "currency", "@of": "Payment.amount.currency" } },
+{ "measure.aggregate": { "name": "revenue", "@agg": "sum", "@of": "Payment.amount.amount" } },
+{ "object.report": { "name": "RevenueByMonth", "@from": "Payment",
+ "@dimensions": ["currency", "receivedOn:month"], "@measures": ["revenue"] } }
+```
+
+**Amounts in different currencies are never added together.** A report that takes `sum`,
+`avg`, `min` or `max` of a numeric member must list, in `@dimensions`, an attribute dimension
+(with no `@via`) over **every non-numeric member of the same value object**: for `Money`, its
+currency. Otherwise the load fails (R12) and names the dimension to add. The rule follows a
+measure into a ratio's operands and a derived measure's, so `revenue / payments` is held to it
+too. A `count` of a member is not constrained, since it adds nothing up.
+
+A member of a value object stored as jsonb (`@storage: jsonb`, or no `@storage`) is refused at
+load: it has no column of its own to group or aggregate. So is a path deeper than one member,
+a member the value object does not declare, and a member path on a field that is not a value
+object. The Cube exporter refuses a member path (`ERR_CUBE_VALUE_OBJECT_MEMBER`).
+
+### Arithmetic over measures (`measure.derived`)
+
+A `measure.derived` computes a number from other measures of the same entity and from numeric
+attribute dimensions the report groups by. Its `@expr` is the first arithmetic wave of FR-037
+R5, a closed subset of the attr.expression grammar:
+
+- `{ "field": "" }` names a `measure.aggregate` or `measure.ratio` of the entity whose
+ result is numeric, or one of its numeric `dimension.attribute`s. It never names another
+ `measure.derived`.
+- `{ "value": }` is a literal.
+- `{ "fn": "add" | "subtract" | "multiply" | "divide", "args": [, ] }` combines two
+ operands.
+
+```jsonc
+// On TimeEntry: utilization is billable hours as a percent of the member's monthly capacity
+// (weekly capacity x 52 / 12); budget burn is cost over the project's budget.
+{ "dimension.attribute": { "name": "weeklyCapacityHours",
+ "@of": "Member.weeklyCapacityHours", "@via": "TimeEntry.member" } },
+{ "dimension.attribute": { "name": "projectBudget", "@of": "Project.budget", "@via": "TimeEntry.project" } },
+{ "measure.aggregate": { "name": "billableHours", "@agg": "sum", "@of": "TimeEntry.hours",
+ "@filter": { "billable": true }, "@default": 0 } },
+{ "measure.aggregate": { "name": "cost", "@agg": "sum", "@of": "TimeEntry.cost" } },
+{ "measure.derived": { "name": "utilization", "@expr":
+ { "fn": "divide", "args": [
+ { "fn": "multiply", "args": [{ "field": "billableHours" }, { "value": 100 }] },
+ { "fn": "divide", "args": [
+ { "fn": "multiply", "args": [{ "field": "weeklyCapacityHours" }, { "value": 52 }] },
+ { "value": 12 } ] } ] } } },
+{ "measure.derived": { "name": "budgetBurn", "@expr":
+ { "fn": "divide", "args": [{ "field": "cost" }, { "field": "projectBudget" }] } } }
+```
+
+A report listing `utilization` must list `weeklyCapacityHours` (and, for a monthly figure,
+`workedOn:month`); one listing `budgetBurn` must list `projectBudget`. A derived measure may not
+read another derived measure, so a shared sub-expression is written out where it is used. Each
+measure operand is inlined as its full aggregate (its own `@filter`, `@segment` and `@default`),
+so an operand need not be listed in `@measures`. A dimension operand reads the grouped column,
+which is why **the report must list that dimension** (R13): otherwise its value could differ
+from row to row inside one group. The conformance fixture `reporting-derived-measures` carries
+both reports.
+
+The result is always `decimal` and nullable. `divide` divides as a ratio does: the dividend is
+cast to the engine's exact or real type (Postgres `NUMERIC`, SQLite `REAL`), and a divisor that
+is not a nonzero literal is wrapped in `NULLIF(…, 0)`, so dividing by zero reads null. A null
+operand makes the whole expression null; give the operand measure a `@default` when an empty
+group should read `0`. A derived measure takes no `@default`.
+
+The Cube exporter writes a derived measure over measures as a `number` member reading them
+(`{totalHours} - {billableHours}`), and refuses one that reads a dimension
+(`ERR_CUBE_DERIVED_DIMENSION`), since a Cube measure cannot read a grouped column.
+
### Dimensions, time grains and joins
- **`@via`** reaches a column of a to-one related entity, through a join. Every hop is joined
@@ -834,6 +915,7 @@ no file.
| `dimension.time` | a `time` dimension, with `@grains` carried as `meta.grains` |
| `measure.aggregate` | a measure, its `@segment` and `@filter` as one `filters` entry |
| `measure.ratio` | a `number` measure over its two operand measures |
+| `measure.derived` over measures and literals | a `number` measure over them (one that reads a dimension is refused) |
| a measure's `@default` | `COALESCE` over the measure (a `measure.aggregate` keeps its aggregate as a `public: false` `Raw` member) |
| `segment.filter` | a segment |
| a served `object.report` | a `rollup` pre-aggregation on its `@from` cube, and a segment for its `@filter` |
@@ -858,7 +940,7 @@ a rule differently fails the corpus.
| Rule | Refused |
|---|---|
-| **D1** | An `@of` that is not `Entity.field`, that names the wrong entity, or whose field does not exist. Without `@via`, `Entity` is the owning entity; with `@via`, it is the `@via` terminal, and a bare `Entity` resolves in the terminal's package. With `@via`, the field must be declared on, or inherited by, the entity `@of` names: naming a base for a field only the reached subtype declares is refused, and the message names the subtype to write. When the reached subtype redeclares a field the base has, the subtype's declaration (its column and type) is what the view selects. |
+| **D1** | An `@of` that is not `Entity.field` or `Entity.field.member` (a member of a flattened value object, below), that names the wrong entity, or whose field does not exist. Without `@via`, `Entity` is the owning entity; with `@via`, it is the `@via` terminal, and a bare `Entity` resolves in the terminal's package. With `@via`, the field must be declared on, or inherited by, the entity `@of` names: naming a base for a field only the reached subtype declares is refused, and the message names the subtype to write. When the reached subtype redeclares a field the base has, the subtype's declaration (its column and type) is what the view selects. |
| **D2** | An `@via` that is not `Owner.hop[.hop...]` starting at the owning entity, or that crosses a hop which is not a `relationship.*` with `@cardinality: one` or an `identity.reference`, or a hop whose target resolves to no object. |
| **D3** | A `dimension.time` whose `@of` is not a `field.date` or `field.timestamp`. |
| **D4** | A `dimension.time` over a `field.date` that declares `hour` (a date has no hour). |
@@ -878,7 +960,7 @@ row, and a `SUM` over the result would double-count. A to-one hop cannot fan out
| Rule | Refused |
|---|---|
| **M0** | A `measure.aggregate` with no `@of` whose `@agg` is not `any` or `all`, or an `any` or `all` with no `@of` that declares neither `@filter` nor `@segment`. |
-| **M1** | An `@of` item that is not `Entity.field`, names an entity other than the owning one (or one it extends), or names a field that does not exist. A measure aggregates its own entity's rows. |
+| **M1** | An `@of` item that is not `Entity.field` or `Entity.field.member`, names an entity other than the owning one (or one it extends), or names a field that does not exist. A measure aggregates its own entity's rows. For a member path (also under D1): the field is not a value object, the value object is not stored `@storage: flattened`, the member does not exist, or the path is deeper than one member. |
| **M2** | More than one `@of` item without both `@agg: count` and `@distinct: true`. |
| **M3** | `@distinct: true` with any `@agg` other than `count`. |
| **M4** | `sum` or `avg` over a non-numeric field (numeric is `int, long, double, float, decimal, currency`); `min` or `max` over a `boolean`, `object` or `map` field; `any` or `all` over a field that is not a `boolean`. |
@@ -887,7 +969,8 @@ row, and a `SUM` over the result would double-count. A to-one hop cannot fan out
| **M7** | A `@default` on an `@agg: count`. A count is never null, so the default could never apply. |
| **M8** | A `@default` on an `@agg: min` or `max` over a field that is not numeric (not one of `int, long, double, float, decimal, currency`). |
| **M9** | A `@default` on an `@agg: any` or `all` other than `0` (false) or `1` (true). |
-| **M10** | An `@of` naming a `field.object`, or any field carrying `@objectRef`, for any `@agg`. A measure aggregates scalars: aggregate a scalar field of the value instead. |
+| **M10** | An `@of` naming a `field.object`, or any field carrying `@objectRef`, for any `@agg`. A measure aggregates scalars: aggregate a scalar member of the value instead (`Entity.field.member`). |
+| **M11** | A `measure.derived` whose `@expr` is not the arithmetic grammar (a node other than `field`, `value` or a two-operand `add`/`subtract`/`multiply`/`divide`), or names an operand that is no measure or dimension of the entity, is another `measure.derived`, is a measure with a non-numeric result, is a `dimension.time`, is a dimension whose `@of` is not numeric, or is both a measure and a dimension. One error per offending operand. A `@default` on a derived measure is `ERR_UNKNOWN_ATTR`. |
A measure that breaks several of M1 to M4 reports only the first, in that order, so one
mistake gives one error. M7, M8 and M9 run only when none of M1 to M4 fired.
@@ -918,6 +1001,8 @@ port. A ratio's `@default` is checked for this only.
| **R9** | `ERR_INVALID_REPORT` | A `@spine` report with no dimension, or a listed dimension whose `@via` does not begin with the spine's hops (no `@via` at all included). Hop names are compared as written; the owner segment is not. |
| **R10** | `ERR_INVALID_REPORT` | A read-only report source whose effective `@kind` is not `view` (`materializedView`, `storedProc`, `tableFunction`), on the `source.rdb`. A report is read through a view; for a view or materialized view you create yourself, declare `@kind: view` with `@unmanaged: true`. |
| **R11** | `ERR_INVALID_REPORT` | A report declared `abstract: true`. Its fields are derived from its own `@dimensions` and `@measures`, so there is nothing for a subtype to add, and no port reads or serves an abstract report. |
+| **R12** | `ERR_INVALID_REPORT` | A listed `sum`, `avg`, `min` or `max` of a numeric value-object member (directly, or as a ratio's or derived measure's operand) when `@dimensions` lacks an attribute dimension, with no `@via`, over each non-numeric member of that value object (its currency). |
+| **R13** | `ERR_INVALID_REPORT` | A listed `measure.derived` that reads a dimension `@dimensions` does not list. |
`purchasedAt:day` and `purchasedAt:week` together are legal, since they derive different
fields (`purchasedAtDay`, `purchasedAtWeek`).
diff --git a/docs/superpowers/specs/2026-08-10-fr-037-projection-expressiveness-and-write-once-design.md b/docs/superpowers/specs/2026-08-10-fr-037-projection-expressiveness-and-write-once-design.md
index de568da5c2..55f3b192f6 100644
--- a/docs/superpowers/specs/2026-08-10-fr-037-projection-expressiveness-and-write-once-design.md
+++ b/docs/superpowers/specs/2026-08-10-fr-037-projection-expressiveness-and-write-once-design.md
@@ -877,6 +877,10 @@ a second arrives.
declared subtype VERIFIED; registered cross-port; a `registry-conformance` fixture;
and a lowering in the existing `view-ddl-emit` switch. No member is added without at
least one non-RDB lowering demonstrated or specified.
+ *(2026-11-12: arithmetic shipped first for report measures only. `measure.derived`'s
+ `@expr` takes `add`/`subtract`/`multiply`/`divide` with two operands and a decimal result
+ (FR-044 R11). `origin.computed`'s grammar does not take them yet; when it does, it takes the
+ same members with the same semantics, `divide`'s null-on-zero included.)*
2. **Regex extraction is capability-gated, not core** — SQLite has no regex without an
extension and Search scripting is commonly disabled. If admitted, it errors on a
lowering that cannot support it.
diff --git a/docs/superpowers/specs/2026-10-02-fr-044-core-reporting-design.md b/docs/superpowers/specs/2026-10-02-fr-044-core-reporting-design.md
index e85d10916f..45143bfa7b 100644
--- a/docs/superpowers/specs/2026-10-02-fr-044-core-reporting-design.md
+++ b/docs/superpowers/specs/2026-10-02-fr-044-core-reporting-design.md
@@ -13,6 +13,9 @@ from a dimension's entity (`@spine`, R8), and a measure can declare its value wh
(`@default`, R9). The register entries are in §3.2. Both are additive and `metamodelVersion`
stays `1.1`. Plan:
`docs/superpowers/plans/2026-10-09-fr-044-zero-rows-and-measure-defaults.md`.
+**Amended 2026-11-12:** `measure.derived` is registered, and a measure's `@of` may name a
+flattened value-object member (R11, below). Both came from a large-application smoke test whose
+dashboard reports fell back to `@sql`. Both are additive.
**Target:** metamodel `1.1` (additive vocabulary is a MINOR — `docs/compatibility-policy.md`,
`scripts/check-metamodel-version.mjs`). Nothing here is a PATCH.
**Relates to:** [ADR-0037](../../../spec/decisions/ADR-0037-metamodel-vocabulary-expansion-decision-framework.md)
@@ -114,7 +117,7 @@ These bind every requirement below. They restate FR-037's shared obligations for
The maintainer agreed to this list on 2026-10-03. Each entry carries its can't-be-computed
justification. Nothing outside this list may be registered under FR-044 without a new
agreement. `measure.derived` is deliberately absent: it waits for FR-037 R5's arithmetic wave
-and gets its own agreement then.
+and gets its own agreement then. *(2026-11-12: that agreement is R11 below.)*
| New name | Kind | Why it cannot be computed from existing metadata |
|---|---|---|
@@ -531,6 +534,45 @@ no `any` / `all` aggregation (`sum_boolean` counts the trues); the dbt exporter,
must refuse it by name or map it to `max` / `min` over a 0/1 expression. It is not part of this
change.
+### R11 — value-object members in `@of`, and `measure.derived` (added 2026-11-12)
+
+**Why.** A large-application smoke test wrote its dashboard reports in this vocabulary, and two
+of the five gaps that sent reports back to `@sql` are closed here. (1) Revenue by client by month
+sums `Payment.amount`, a required Money value object stored flattened (`amount_amount`,
+`amount_currency`); `@of` could not name a member. (2) Utilization is billable hours divided by
+capacity hours, and capacity is the member's weekly capacity x 52 / 12; budget burn is cost
+divided by budget. These need arithmetic between measures. The other three gaps (a calendar-month
+spine with no facts, product measures such as hours x rate, a member read out of a jsonb value
+object) stay `@sql`.
+
+**Members.** An `@of` path may step into a flattened `field.object` and name its member
+(`Payment.amount.amount`). A `sum`/`avg`/`min`/`max` over a numeric member requires the report
+to group, by an attribute dimension with no `@via`, on every non-numeric member of the same value
+object (its currency): units are never mixed silently, and a report that would mix them does not
+load (rule R12 in `docs/features/reporting.md`). The check follows ratio and derived operands. A
+member of a jsonb value object is a load error naming the storage. No new attribute: the path
+syntax already existed.
+
+**`measure.derived`.** A new subtype with one required attribute, `@expr` (type `expression`),
+over a closed subset of `attr.expression`: `{field: }`, `{value: }`
+and `{fn: add | subtract | multiply | divide, args: [a, b]}`. The result is a nullable decimal.
+`divide` lowers as a ratio does: the dividend is cast to a decimal (Postgres `NUMERIC`, SQLite
+`REAL`) and a divisor that is not a nonzero literal is wrapped in `NULLIF(…, 0)`. A derived measure
+that reads a dimension requires the report to group by it (R13). `@default` is not registered on
+it; wrap the operand measures instead. This is FR-037 R5 wave 1 scoped to report measures:
+`origin.computed`'s grammar does not take these members yet, and when it does the two must agree.
+
+| New name | Kind | Why it cannot be computed from existing metadata |
+|---|---|---|
+| `measure.derived` | subtype of `measure` | an author's formula over measures; nothing in the model states it |
+| `@expr` on `measure.derived` | attribute (`expression`) | the formula itself |
+
+**Lowering and ports.** Loader validation (M11, R12, R13) and the report's column type in all
+four loader ports; view lowering in TypeScript (Postgres and SQLite), as for every report. Cube
+writes a derived measure over measures as a `number` member and refuses a member path
+(`ERR_CUBE_VALUE_OBJECT_MEMBER`) and a derived measure over a dimension
+(`ERR_CUBE_DERIVED_DIMENSION`).
+
## 5. Mapping contract (core → Cube → MetricFlow)
| MetaObjects | Cube | dbt MetricFlow |
@@ -545,7 +587,7 @@ change.
| `measure.aggregate` sum/avg/min/max | `sum`/`avg`/`min`/`max` | `sum`/`average`/`min`/`max` |
| `measure.aggregate` any/all | `boolean` measure holding `bool_or(x)` / `bool_and(x)` (MySQL `MAX(x)` / `MIN(x)`) | none yet: `sum_boolean` counts the trues; the dbt exporter refuses it or maps `max` / `min` over a 0/1 expression |
| `measure.ratio` | `number` measure `{a} / NULLIF({b}, 0)`; on Postgres `CAST({a} AS NUMERIC) / NULLIF({b}, 0)`, with no cast on MySQL | `ratio` metric |
-| `measure.derived` | `number` measure | `derived` metric |
+| `measure.derived` | `number` measure over the measures it reads; one that reads a dimension is refused (`ERR_CUBE_DERIVED_DIMENSION`) | `derived` metric |
| `segment` | segment | metric `filter` / saved query filter |
| relative filter `{ now: "-P7D" }` | the view's SQL in a segment or measure filter (no rollup for such a report) | `{{ TimeDimension(...) }} >= dateadd(...)` |
| `object.report` | a rollup on the `@from` cube (coarsest first) | a saved query |
@@ -554,7 +596,7 @@ change.
FR-044 Plan 4 ([plan](../plans/2026-10-09-fr-044-plan-4-cube-exporter.md)) built the Cube
column as written above, the `@spine` and `@default` rows included once the zero-rows /
-measure-defaults build registered them, except `measure.derived`, which is not registered. The MetricFlow column waits for the first adopter who asks (D5).
+measure-defaults build registered them. `measure.derived` followed in R11 (2026-11-12). The MetricFlow column waits for the first adopter who asks (D5).
## 6. Dependencies and order
@@ -566,7 +608,8 @@ measure-defaults build registered them, except `measure.derived`, which is not r
MySQL, persistence-conformance (read each report view in every port), api-contract
`report/` sub-corpus (list, filter, sort, paging, 405 on writes) in every port. **R8 and
R9** (added 2026-10-09) join this change set and are gated the same way.
-3. **R2 `measure.derived`** — once FR-037 R5's arithmetic lands.
+3. **R2 `measure.derived`** — shipped 2026-11-12 (R11), with a report-only arithmetic subset
+ in place of the full FR-037 R5 wave.
4. **R6** — Cube exporter. MetricFlow on first adopter demand (D5).
5. **R7** — the library.
diff --git a/examples/showcase/site-payload.json b/examples/showcase/site-payload.json
index cf58472f9d..c0da6ed6d5 100644
--- a/examples/showcase/site-payload.json
+++ b/examples/showcase/site-payload.json
@@ -7,7 +7,7 @@
"metamodel": "1.3"
},
"counts": {
- "fixtures": 471,
+ "fixtures": 490,
"corpora": 38,
"baseTypes": 17
},
diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
index 544a7fbe69..ecaaa30cc1 100644
--- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
+++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
@@ -18,6 +18,10 @@ and an `object.report` combines them by name. Four node kinds:
`field.boolean` `@of`, or no `@of` and a `@filter` or `@segment`: `{ "name": "hasError",
"@agg": "any", "@filter": { "success": false } }` is "some row has `success` false" (a row
whose condition is null does not pass);
+- `measure.derived` — `@expr` arithmetic (`add`, `subtract`, `multiply`, `divide`, two operands
+ each) over `{ "field": }` and `{ "value": }`:
+ utilization is `billableHours × 100 ÷ (weeklyCapacityHours × 52 ÷ 12)`. A dimension it reads
+ must be in the report's `@dimensions`; it never reads another derived measure;
- `segment.filter` — a named, reusable `@filter` ("active purchase");
- `object.report` — a top-level object: `@from` an entity, `@dimensions` (`name` or
`name:grain`), `@measures`.
@@ -72,6 +76,11 @@ Three rules an author trips on:
measure (a time dimension at a grain is ``, so `purchasedAt:day` is
`purchasedAtDay`). A `field.*` or `identity.*` child on a report is an error.
+**Money.** `@of` may name a member of a `@storage: flattened` value object,
+`Payment.amount.amount`. A `sum`, `avg`, `min` or `max` of it loads only when the report also
+lists a dimension over each non-numeric member (`Payment.amount.currency`), so currencies are
+never added together. A jsonb value object's members are refused.
+
Two questions to answer for every report:
- **Do I want the rows that have no facts?** A report's rows come from the facts, so a
@@ -99,8 +108,8 @@ A report `@from` a TPH subtype is refused when its view is derived (the subtype
base's table): declare it `@from` the base with an `@filter` on the discriminator field.
What does not exist: no grid or form for a report (TypeScript generates a list hook; no other port has a client tier), no way to narrow which
-derived fields are filterable, no `measure.derived`
-(arithmetic between measures beyond `measure.ratio`), no query-time choice of dimensions or
+derived fields are filterable, no product measure
+(`sum(hours × rate)`), no member of a jsonb value object, no query-time choice of dimensions or
measures (a report is a fixed, compiled combination), and no time-zone vocabulary (grains and
relative dates are UTC). Column types, the null rules, Monday weeks and per-engine differences
are in `references/reporting.md`.
diff --git a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/reporting.md b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/reporting.md
index 33c60ec19b..eaa55e3356 100644
--- a/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/reporting.md
+++ b/fixtures/agent-context-conformance/csharp/expected/.claude/skills/metaobjects-authoring/references/reporting.md
@@ -49,6 +49,7 @@ A report declares no fields. Its columns are one per `@dimensions` item in liste
| `min` / `max` | the measure's name | the `@of` field's type | no |
| `any` / `all` (boolean OR / AND, `bool_or` / `bool_and`; over a `field.boolean` `@of`, or with no `@of` over the measure's `@filter` / `@segment`) | the measure's name | `boolean` | no |
| `measure.ratio` | the measure's name | `decimal` | no |
+| `measure.derived` | the measure's name | `decimal` | no |
| any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads the default instead of null |
| in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the field is `@required` or in that entity's `identity.primary`; no for a dimension beyond the spine entity |
@@ -72,6 +73,7 @@ Add `"startOf": "day"`, `"week"` or `"month"` to cut the window to a calendar bo
- A `sum` of nothing is **null**, not zero: no matching rows, or a filtered measure that matched none of a group's rows. So are `avg`, `min` and `max`.
- An `any` or `all` over no rows, or only null values, is **null**, not `false`. `"@default": 0` reads `false` and `"@default": 1` reads `true` (any other number is refused).
- A ratio is `numerator / NULLIF(denominator, 0)`: a zero denominator is **null**. Each operand must be a numeric measure: a `count`, a `sum`, an `avg`, or a `min` or `max` of a numeric field. An `any` or `all` (a boolean), or a `min` or `max` of a date, timestamp, string, uuid or enum, is refused as `@numerator` or `@denominator`. For a share, use an `@agg: count` with a `@filter`.
+- A derived measure's `divide` divides as a ratio does (null on a zero divisor); a null operand makes it null, so default the operand measure when `0` is meant.
- A report with no dimensions is one row for the whole table, and still one row over an empty table (counts `0`, sums and ratios null).
**Ask: is zero true here, or is null?** If "nothing to aggregate" means zero (revenue of a program nobody bought is `0`), declare `"@default": 0` on the measure (`revenue` in the example under "Rows with no facts"). If it means unknown (the average rating of a product with no ratings is not `0`), leave it null. Do not default in the client what the model can state once.
diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
index 544a7fbe69..ecaaa30cc1 100644
--- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
+++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
@@ -18,6 +18,10 @@ and an `object.report` combines them by name. Four node kinds:
`field.boolean` `@of`, or no `@of` and a `@filter` or `@segment`: `{ "name": "hasError",
"@agg": "any", "@filter": { "success": false } }` is "some row has `success` false" (a row
whose condition is null does not pass);
+- `measure.derived` — `@expr` arithmetic (`add`, `subtract`, `multiply`, `divide`, two operands
+ each) over `{ "field": }` and `{ "value": }`:
+ utilization is `billableHours × 100 ÷ (weeklyCapacityHours × 52 ÷ 12)`. A dimension it reads
+ must be in the report's `@dimensions`; it never reads another derived measure;
- `segment.filter` — a named, reusable `@filter` ("active purchase");
- `object.report` — a top-level object: `@from` an entity, `@dimensions` (`name` or
`name:grain`), `@measures`.
@@ -72,6 +76,11 @@ Three rules an author trips on:
measure (a time dimension at a grain is ``, so `purchasedAt:day` is
`purchasedAtDay`). A `field.*` or `identity.*` child on a report is an error.
+**Money.** `@of` may name a member of a `@storage: flattened` value object,
+`Payment.amount.amount`. A `sum`, `avg`, `min` or `max` of it loads only when the report also
+lists a dimension over each non-numeric member (`Payment.amount.currency`), so currencies are
+never added together. A jsonb value object's members are refused.
+
Two questions to answer for every report:
- **Do I want the rows that have no facts?** A report's rows come from the facts, so a
@@ -99,8 +108,8 @@ A report `@from` a TPH subtype is refused when its view is derived (the subtype
base's table): declare it `@from` the base with an `@filter` on the discriminator field.
What does not exist: no grid or form for a report (TypeScript generates a list hook; no other port has a client tier), no way to narrow which
-derived fields are filterable, no `measure.derived`
-(arithmetic between measures beyond `measure.ratio`), no query-time choice of dimensions or
+derived fields are filterable, no product measure
+(`sum(hours × rate)`), no member of a jsonb value object, no query-time choice of dimensions or
measures (a report is a fixed, compiled combination), and no time-zone vocabulary (grains and
relative dates are UTC). Column types, the null rules, Monday weeks and per-engine differences
are in `references/reporting.md`.
diff --git a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/reporting.md b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/reporting.md
index 33c60ec19b..eaa55e3356 100644
--- a/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/reporting.md
+++ b/fixtures/agent-context-conformance/java-kotlin-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/reporting.md
@@ -49,6 +49,7 @@ A report declares no fields. Its columns are one per `@dimensions` item in liste
| `min` / `max` | the measure's name | the `@of` field's type | no |
| `any` / `all` (boolean OR / AND, `bool_or` / `bool_and`; over a `field.boolean` `@of`, or with no `@of` over the measure's `@filter` / `@segment`) | the measure's name | `boolean` | no |
| `measure.ratio` | the measure's name | `decimal` | no |
+| `measure.derived` | the measure's name | `decimal` | no |
| any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads the default instead of null |
| in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the field is `@required` or in that entity's `identity.primary`; no for a dimension beyond the spine entity |
@@ -72,6 +73,7 @@ Add `"startOf": "day"`, `"week"` or `"month"` to cut the window to a calendar bo
- A `sum` of nothing is **null**, not zero: no matching rows, or a filtered measure that matched none of a group's rows. So are `avg`, `min` and `max`.
- An `any` or `all` over no rows, or only null values, is **null**, not `false`. `"@default": 0` reads `false` and `"@default": 1` reads `true` (any other number is refused).
- A ratio is `numerator / NULLIF(denominator, 0)`: a zero denominator is **null**. Each operand must be a numeric measure: a `count`, a `sum`, an `avg`, or a `min` or `max` of a numeric field. An `any` or `all` (a boolean), or a `min` or `max` of a date, timestamp, string, uuid or enum, is refused as `@numerator` or `@denominator`. For a share, use an `@agg: count` with a `@filter`.
+- A derived measure's `divide` divides as a ratio does (null on a zero divisor); a null operand makes it null, so default the operand measure when `0` is meant.
- A report with no dimensions is one row for the whole table, and still one row over an empty table (counts `0`, sums and ratios null).
**Ask: is zero true here, or is null?** If "nothing to aggregate" means zero (revenue of a program nobody bought is `0`), declare `"@default": 0` on the measure (`revenue` in the example under "Rows with no facts"). If it means unknown (the average rating of a product with no ratings is not `0`), leave it null. Do not default in the client what the model can state once.
diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
index 544a7fbe69..ecaaa30cc1 100644
--- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
+++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
@@ -18,6 +18,10 @@ and an `object.report` combines them by name. Four node kinds:
`field.boolean` `@of`, or no `@of` and a `@filter` or `@segment`: `{ "name": "hasError",
"@agg": "any", "@filter": { "success": false } }` is "some row has `success` false" (a row
whose condition is null does not pass);
+- `measure.derived` — `@expr` arithmetic (`add`, `subtract`, `multiply`, `divide`, two operands
+ each) over `{ "field": }` and `{ "value": }`:
+ utilization is `billableHours × 100 ÷ (weeklyCapacityHours × 52 ÷ 12)`. A dimension it reads
+ must be in the report's `@dimensions`; it never reads another derived measure;
- `segment.filter` — a named, reusable `@filter` ("active purchase");
- `object.report` — a top-level object: `@from` an entity, `@dimensions` (`name` or
`name:grain`), `@measures`.
@@ -72,6 +76,11 @@ Three rules an author trips on:
measure (a time dimension at a grain is ``, so `purchasedAt:day` is
`purchasedAtDay`). A `field.*` or `identity.*` child on a report is an error.
+**Money.** `@of` may name a member of a `@storage: flattened` value object,
+`Payment.amount.amount`. A `sum`, `avg`, `min` or `max` of it loads only when the report also
+lists a dimension over each non-numeric member (`Payment.amount.currency`), so currencies are
+never added together. A jsonb value object's members are refused.
+
Two questions to answer for every report:
- **Do I want the rows that have no facts?** A report's rows come from the facts, so a
@@ -99,8 +108,8 @@ A report `@from` a TPH subtype is refused when its view is derived (the subtype
base's table): declare it `@from` the base with an `@filter` on the discriminator field.
What does not exist: no grid or form for a report (TypeScript generates a list hook; no other port has a client tier), no way to narrow which
-derived fields are filterable, no `measure.derived`
-(arithmetic between measures beyond `measure.ratio`), no query-time choice of dimensions or
+derived fields are filterable, no product measure
+(`sum(hours × rate)`), no member of a jsonb value object, no query-time choice of dimensions or
measures (a report is a fixed, compiled combination), and no time-zone vocabulary (grains and
relative dates are UTC). Column types, the null rules, Monday weeks and per-engine differences
are in `references/reporting.md`.
diff --git a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/reporting.md b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/reporting.md
index 33c60ec19b..eaa55e3356 100644
--- a/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/reporting.md
+++ b/fixtures/agent-context-conformance/java-react/expected/.claude/skills/metaobjects-authoring/references/reporting.md
@@ -49,6 +49,7 @@ A report declares no fields. Its columns are one per `@dimensions` item in liste
| `min` / `max` | the measure's name | the `@of` field's type | no |
| `any` / `all` (boolean OR / AND, `bool_or` / `bool_and`; over a `field.boolean` `@of`, or with no `@of` over the measure's `@filter` / `@segment`) | the measure's name | `boolean` | no |
| `measure.ratio` | the measure's name | `decimal` | no |
+| `measure.derived` | the measure's name | `decimal` | no |
| any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads the default instead of null |
| in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the field is `@required` or in that entity's `identity.primary`; no for a dimension beyond the spine entity |
@@ -72,6 +73,7 @@ Add `"startOf": "day"`, `"week"` or `"month"` to cut the window to a calendar bo
- A `sum` of nothing is **null**, not zero: no matching rows, or a filtered measure that matched none of a group's rows. So are `avg`, `min` and `max`.
- An `any` or `all` over no rows, or only null values, is **null**, not `false`. `"@default": 0` reads `false` and `"@default": 1` reads `true` (any other number is refused).
- A ratio is `numerator / NULLIF(denominator, 0)`: a zero denominator is **null**. Each operand must be a numeric measure: a `count`, a `sum`, an `avg`, or a `min` or `max` of a numeric field. An `any` or `all` (a boolean), or a `min` or `max` of a date, timestamp, string, uuid or enum, is refused as `@numerator` or `@denominator`. For a share, use an `@agg: count` with a `@filter`.
+- A derived measure's `divide` divides as a ratio does (null on a zero divisor); a null operand makes it null, so default the operand measure when `0` is meant.
- A report with no dimensions is one row for the whole table, and still one row over an empty table (counts `0`, sums and ratios null).
**Ask: is zero true here, or is null?** If "nothing to aggregate" means zero (revenue of a program nobody bought is `0`), declare `"@default": 0` on the measure (`revenue` in the example under "Rows with no facts"). If it means unknown (the average rating of a product with no ratings is not `0`), leave it null. Do not default in the client what the model can state once.
diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
index 544a7fbe69..ecaaa30cc1 100644
--- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
+++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
@@ -18,6 +18,10 @@ and an `object.report` combines them by name. Four node kinds:
`field.boolean` `@of`, or no `@of` and a `@filter` or `@segment`: `{ "name": "hasError",
"@agg": "any", "@filter": { "success": false } }` is "some row has `success` false" (a row
whose condition is null does not pass);
+- `measure.derived` — `@expr` arithmetic (`add`, `subtract`, `multiply`, `divide`, two operands
+ each) over `{ "field": }` and `{ "value": }`:
+ utilization is `billableHours × 100 ÷ (weeklyCapacityHours × 52 ÷ 12)`. A dimension it reads
+ must be in the report's `@dimensions`; it never reads another derived measure;
- `segment.filter` — a named, reusable `@filter` ("active purchase");
- `object.report` — a top-level object: `@from` an entity, `@dimensions` (`name` or
`name:grain`), `@measures`.
@@ -72,6 +76,11 @@ Three rules an author trips on:
measure (a time dimension at a grain is ``, so `purchasedAt:day` is
`purchasedAtDay`). A `field.*` or `identity.*` child on a report is an error.
+**Money.** `@of` may name a member of a `@storage: flattened` value object,
+`Payment.amount.amount`. A `sum`, `avg`, `min` or `max` of it loads only when the report also
+lists a dimension over each non-numeric member (`Payment.amount.currency`), so currencies are
+never added together. A jsonb value object's members are refused.
+
Two questions to answer for every report:
- **Do I want the rows that have no facts?** A report's rows come from the facts, so a
@@ -99,8 +108,8 @@ A report `@from` a TPH subtype is refused when its view is derived (the subtype
base's table): declare it `@from` the base with an `@filter` on the discriminator field.
What does not exist: no grid or form for a report (TypeScript generates a list hook; no other port has a client tier), no way to narrow which
-derived fields are filterable, no `measure.derived`
-(arithmetic between measures beyond `measure.ratio`), no query-time choice of dimensions or
+derived fields are filterable, no product measure
+(`sum(hours × rate)`), no member of a jsonb value object, no query-time choice of dimensions or
measures (a report is a fixed, compiled combination), and no time-zone vocabulary (grains and
relative dates are UTC). Column types, the null rules, Monday weeks and per-engine differences
are in `references/reporting.md`.
diff --git a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/reporting.md b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/reporting.md
index 33c60ec19b..eaa55e3356 100644
--- a/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/reporting.md
+++ b/fixtures/agent-context-conformance/python/expected/.claude/skills/metaobjects-authoring/references/reporting.md
@@ -49,6 +49,7 @@ A report declares no fields. Its columns are one per `@dimensions` item in liste
| `min` / `max` | the measure's name | the `@of` field's type | no |
| `any` / `all` (boolean OR / AND, `bool_or` / `bool_and`; over a `field.boolean` `@of`, or with no `@of` over the measure's `@filter` / `@segment`) | the measure's name | `boolean` | no |
| `measure.ratio` | the measure's name | `decimal` | no |
+| `measure.derived` | the measure's name | `decimal` | no |
| any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads the default instead of null |
| in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the field is `@required` or in that entity's `identity.primary`; no for a dimension beyond the spine entity |
@@ -72,6 +73,7 @@ Add `"startOf": "day"`, `"week"` or `"month"` to cut the window to a calendar bo
- A `sum` of nothing is **null**, not zero: no matching rows, or a filtered measure that matched none of a group's rows. So are `avg`, `min` and `max`.
- An `any` or `all` over no rows, or only null values, is **null**, not `false`. `"@default": 0` reads `false` and `"@default": 1` reads `true` (any other number is refused).
- A ratio is `numerator / NULLIF(denominator, 0)`: a zero denominator is **null**. Each operand must be a numeric measure: a `count`, a `sum`, an `avg`, or a `min` or `max` of a numeric field. An `any` or `all` (a boolean), or a `min` or `max` of a date, timestamp, string, uuid or enum, is refused as `@numerator` or `@denominator`. For a share, use an `@agg: count` with a `@filter`.
+- A derived measure's `divide` divides as a ratio does (null on a zero divisor); a null operand makes it null, so default the operand measure when `0` is meant.
- A report with no dimensions is one row for the whole table, and still one row over an empty table (counts `0`, sums and ratios null).
**Ask: is zero true here, or is null?** If "nothing to aggregate" means zero (revenue of a program nobody bought is `0`), declare `"@default": 0` on the measure (`revenue` in the example under "Rows with no facts"). If it means unknown (the average rating of a product with no ratings is not `0`), leave it null. Do not default in the client what the model can state once.
diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
index 544a7fbe69..ecaaa30cc1 100644
--- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
+++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/declaring-reports.md
@@ -18,6 +18,10 @@ and an `object.report` combines them by name. Four node kinds:
`field.boolean` `@of`, or no `@of` and a `@filter` or `@segment`: `{ "name": "hasError",
"@agg": "any", "@filter": { "success": false } }` is "some row has `success` false" (a row
whose condition is null does not pass);
+- `measure.derived` — `@expr` arithmetic (`add`, `subtract`, `multiply`, `divide`, two operands
+ each) over `{ "field": }` and `{ "value": }`:
+ utilization is `billableHours × 100 ÷ (weeklyCapacityHours × 52 ÷ 12)`. A dimension it reads
+ must be in the report's `@dimensions`; it never reads another derived measure;
- `segment.filter` — a named, reusable `@filter` ("active purchase");
- `object.report` — a top-level object: `@from` an entity, `@dimensions` (`name` or
`name:grain`), `@measures`.
@@ -72,6 +76,11 @@ Three rules an author trips on:
measure (a time dimension at a grain is ``, so `purchasedAt:day` is
`purchasedAtDay`). A `field.*` or `identity.*` child on a report is an error.
+**Money.** `@of` may name a member of a `@storage: flattened` value object,
+`Payment.amount.amount`. A `sum`, `avg`, `min` or `max` of it loads only when the report also
+lists a dimension over each non-numeric member (`Payment.amount.currency`), so currencies are
+never added together. A jsonb value object's members are refused.
+
Two questions to answer for every report:
- **Do I want the rows that have no facts?** A report's rows come from the facts, so a
@@ -99,8 +108,8 @@ A report `@from` a TPH subtype is refused when its view is derived (the subtype
base's table): declare it `@from` the base with an `@filter` on the discriminator field.
What does not exist: no grid or form for a report (TypeScript generates a list hook; no other port has a client tier), no way to narrow which
-derived fields are filterable, no `measure.derived`
-(arithmetic between measures beyond `measure.ratio`), no query-time choice of dimensions or
+derived fields are filterable, no product measure
+(`sum(hours × rate)`), no member of a jsonb value object, no query-time choice of dimensions or
measures (a report is a fixed, compiled combination), and no time-zone vocabulary (grains and
relative dates are UTC). Column types, the null rules, Monday weeks and per-engine differences
are in `references/reporting.md`.
diff --git a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/reporting.md b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/reporting.md
index 33c60ec19b..eaa55e3356 100644
--- a/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/reporting.md
+++ b/fixtures/agent-context-conformance/ts-react-tanstack/expected/.claude/skills/metaobjects-authoring/references/reporting.md
@@ -49,6 +49,7 @@ A report declares no fields. Its columns are one per `@dimensions` item in liste
| `min` / `max` | the measure's name | the `@of` field's type | no |
| `any` / `all` (boolean OR / AND, `bool_or` / `bool_and`; over a `field.boolean` `@of`, or with no `@of` over the measure's `@filter` / `@segment`) | the measure's name | `boolean` | no |
| `measure.ratio` | the measure's name | `decimal` | no |
+| `measure.derived` | the measure's name | `decimal` | no |
| any measure above except `count`, declaring `@default` | the measure's name | as above | yes: it reads the default instead of null |
| in a `@spine` report, a dimension over a column of the spine entity | the dimension's name | the `@of` field's type | yes when the field is `@required` or in that entity's `identity.primary`; no for a dimension beyond the spine entity |
@@ -72,6 +73,7 @@ Add `"startOf": "day"`, `"week"` or `"month"` to cut the window to a calendar bo
- A `sum` of nothing is **null**, not zero: no matching rows, or a filtered measure that matched none of a group's rows. So are `avg`, `min` and `max`.
- An `any` or `all` over no rows, or only null values, is **null**, not `false`. `"@default": 0` reads `false` and `"@default": 1` reads `true` (any other number is refused).
- A ratio is `numerator / NULLIF(denominator, 0)`: a zero denominator is **null**. Each operand must be a numeric measure: a `count`, a `sum`, an `avg`, or a `min` or `max` of a numeric field. An `any` or `all` (a boolean), or a `min` or `max` of a date, timestamp, string, uuid or enum, is refused as `@numerator` or `@denominator`. For a share, use an `@agg: count` with a `@filter`.
+- A derived measure's `divide` divides as a ratio does (null on a zero divisor); a null operand makes it null, so default the operand measure when `0` is meant.
- A report with no dimensions is one row for the whole table, and still one row over an empty table (counts `0`, sums and ratios null).
**Ask: is zero true here, or is null?** If "nothing to aggregate" means zero (revenue of a program nobody bought is `0`), declare `"@default": 0` on the measure (`revenue` in the example under "Rows with no facts"). If it means unknown (the average rating of a product with no ratings is not `0`), leave it null. Do not default in the client what the model can state once.
diff --git a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
index f152f72dea..64d2858d5c 100644
--- a/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
+++ b/fixtures/requirement-harness/csharp/RequirementHarnessTests.cs
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (117 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into C#'s own suite and write the assertion the
@@ -352,6 +352,10 @@ public void declare_reporting_dimensionTime() { /* metaobjects.declare.reporting
[Fact(Skip = "planned — not built yet")]
public void declare_reporting_measureAggregate() { /* metaobjects.declare.reporting.measureAggregate */ }
+ // Derived measure — A derived measure is arithmetic over the entity's other measures and the report's dimensions, and a division by zero is empty, not an error.
+ [Fact(Skip = "planned — not built yet")]
+ public void declare_reporting_measureDerived() { /* metaobjects.declare.reporting.measureDerived */ }
+
// Ratio measure — A ratio measure is the quotient of two aggregate measures and is empty, not an error, when the denominator is zero.
[Fact(Skip = "planned — not built yet")]
public void declare_reporting_measureRatio() { /* metaobjects.declare.reporting.measureRatio */ }
diff --git a/fixtures/requirement-harness/java/RequirementHarnessTest.java b/fixtures/requirement-harness/java/RequirementHarnessTest.java
index 90a7342772..bdcd3edcf6 100644
--- a/fixtures/requirement-harness/java/RequirementHarnessTest.java
+++ b/fixtures/requirement-harness/java/RequirementHarnessTest.java
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (117 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into Java's own suite and write the assertion the
@@ -437,6 +437,11 @@ void declare_reporting_dimensionTime() { /* metaobjects.declare.reporting.dimens
@Disabled("planned — not built yet")
void declare_reporting_measureAggregate() { /* metaobjects.declare.reporting.measureAggregate */ }
+ // Derived measure — A derived measure is arithmetic over the entity's other measures and the report's dimensions, and a division by zero is empty, not an error.
+ @Test
+ @Disabled("planned — not built yet")
+ void declare_reporting_measureDerived() { /* metaobjects.declare.reporting.measureDerived */ }
+
// Ratio measure — A ratio measure is the quotient of two aggregate measures and is empty, not an error, when the denominator is zero.
@Test
@Disabled("planned — not built yet")
diff --git a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
index 6ed84f006c..797f485c56 100644
--- a/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
+++ b/fixtures/requirement-harness/kotlin/RequirementHarnessTest.kt
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (117 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into Kotlin's own suite and write the assertion the
@@ -437,6 +437,11 @@ class RequirementHarnessTest {
@Disabled("planned — not built yet")
fun declare_reporting_measureAggregate() { /* metaobjects.declare.reporting.measureAggregate */ }
+ // Derived measure — A derived measure is arithmetic over the entity's other measures and the report's dimensions, and a division by zero is empty, not an error.
+ @Test
+ @Disabled("planned — not built yet")
+ fun declare_reporting_measureDerived() { /* metaobjects.declare.reporting.measureDerived */ }
+
// Ratio measure — A ratio measure is the quotient of two aggregate measures and is empty, not an error, when the denominator is zero.
@Test
@Disabled("planned — not built yet")
diff --git a/fixtures/requirement-harness/python/test_requirement_harness.py b/fixtures/requirement-harness/python/test_requirement_harness.py
index bc494c15ce..69a1ede453 100644
--- a/fixtures/requirement-harness/python/test_requirement_harness.py
+++ b/fixtures/requirement-harness/python/test_requirement_harness.py
@@ -1,6 +1,6 @@
# @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
#
-# One slot per authored promise in metaobjects/meta.requirements.yaml (117 of them).
+# One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them).
# Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
# claim that nothing is verified — the conformance corpora already check many of
# these. To FILL one, move it into Python's own suite and write the assertion the
@@ -432,6 +432,11 @@ def test_declare_reporting_dimensionTime():
def test_declare_reporting_measureAggregate():
"""metaobjects.declare.reporting.measureAggregate"""
+# Derived measure — A derived measure is arithmetic over the entity's other measures and the report's dimensions, and a division by zero is empty, not an error.
+@pytest.mark.skip(reason="planned — not built yet")
+def test_declare_reporting_measureDerived():
+ """metaobjects.declare.reporting.measureDerived"""
+
# Ratio measure — A ratio measure is the quotient of two aggregate measures and is empty, not an error, when the denominator is zero.
@pytest.mark.skip(reason="planned — not built yet")
def test_declare_reporting_measureRatio():
diff --git a/fixtures/requirement-harness/typescript/requirement-harness.test.ts b/fixtures/requirement-harness/typescript/requirement-harness.test.ts
index 1e7d21f463..8720e5c83a 100644
--- a/fixtures/requirement-harness/typescript/requirement-harness.test.ts
+++ b/fixtures/requirement-harness/typescript/requirement-harness.test.ts
@@ -1,6 +1,6 @@
// @generated by scripts/generate-requirement-harness.ts — DO NOT EDIT IN PLACE.
//
-// One slot per authored promise in metaobjects/meta.requirements.yaml (117 of them).
+// One slot per authored promise in metaobjects/meta.requirements.yaml (118 of them).
// Every slot is SKIPPED: this is a to-do list with a drift gate behind it, not a
// claim that nothing is verified — the conformance corpora already check many of
// these. To FILL one, move it into TypeScript's own suite and write the assertion the
@@ -432,6 +432,11 @@ test.skip("metaobjects.declare.reporting.measureAggregate", () => {
// planned — not built yet
});
+// Derived measure — A derived measure is arithmetic over the entity's other measures and the report's dimensions, and a division by zero is empty, not an error.
+test.skip("metaobjects.declare.reporting.measureDerived", () => {
+ // planned — not built yet
+});
+
// Ratio measure — A ratio measure is the quotient of two aggregate measures and is empty, not an error, when the denominator is zero.
test.skip("metaobjects.declare.reporting.measureRatio", () => {
// planned — not built yet
diff --git a/metaobjects/meta.requirements.yaml b/metaobjects/meta.requirements.yaml
index fedf9a3b70..93fe3b2627 100644
--- a/metaobjects/meta.requirements.yaml
+++ b/metaobjects/meta.requirements.yaml
@@ -1228,6 +1228,19 @@ metadata.root:
counterexample: >-
A dashboard average that fails the whole report for
the one day nothing was started.
+ - requirement.functional:
+ name: measureDerived
+ title: Derived measure
+ level: 4
+ status: planned
+ statement: >-
+ A derived measure is arithmetic over the entity's
+ other measures and the report's dimensions, and a
+ division by zero is empty, not an error.
+ counterexample: >-
+ A utilization percentage hand-written in SQL beside
+ the report, so a renamed hours measure breaks it
+ only at run time.
- requirement.functional:
name: segmentFilter
title: Named filter
diff --git a/server/csharp/MetaObjects.Conformance.Tests/ReportShapeTests.cs b/server/csharp/MetaObjects.Conformance.Tests/ReportShapeTests.cs
index 6fc0b1799f..c4d9cc4529 100644
--- a/server/csharp/MetaObjects.Conformance.Tests/ReportShapeTests.cs
+++ b/server/csharp/MetaObjects.Conformance.Tests/ReportShapeTests.cs
@@ -154,6 +154,26 @@ public void A_value_object_member_derives_the_members_type()
rows.ToList());
}
+ [Fact]
+ public void A_derived_measure_is_a_nullable_decimal()
+ {
+ // FR-044 R13: a measure.derived is typed decimal, not required, with no type source,
+ // whatever its operands. The same rows as the TypeScript derivation of this fixture.
+ var root = LoadFixture("reporting-derived-measures");
+ string Rows(string report) => string.Join(", ", Shape(root, report).Fields.Select(f =>
+ $"{f.Name} {f.SubType} {f.Required} {(f.TypeSource is null ? "-" : $"{f.TypeSource.Parent!.Name}.{f.TypeSource.Name}")}"));
+ Assert.Equal(
+ "memberId long False Member.id, memberName string True Member.firstName, " +
+ "weeklyCapacityHours decimal True Member.weeklyCapacityHours, workedOnMonth date True -, " +
+ "totalHours decimal True -, billableHours decimal True -, capacityHours decimal False -, " +
+ "utilization decimal False -, nonBillableHours decimal False -, billableSharePct decimal False -",
+ Rows("MemberUtilization"));
+ Assert.Equal(
+ "projectId long False Project.id, projectBudget decimal False Project.budget, cost decimal False -, " +
+ "budgetBurn decimal False -",
+ Rows("ProjectBurn"));
+ }
+
[Fact]
public void A_sourceless_report_has_a_shape_and_no_view()
{
diff --git a/server/csharp/MetaObjects/Core/Reporting/DerivedExpr.cs b/server/csharp/MetaObjects/Core/Reporting/DerivedExpr.cs
new file mode 100644
index 0000000000..cf8aca82d5
--- /dev/null
+++ b/server/csharp/MetaObjects/Core/Reporting/DerivedExpr.cs
@@ -0,0 +1,60 @@
+// FR-044 R13 — the @expr grammar of a measure.derived: FR-037 R5's first arithmetic wave.
+//
+// Ported from server/typescript/packages/metadata/src/core/reporting/derived-expr.ts. A closed
+// subset of the attr.expression node grammar: an operand is { field: name } or { value: number };
+// an operation is { fn: add | subtract | multiply | divide, args: [a, b] }. origin.computed's
+// grammar (ExpressionGrammar) does not take the arithmetic members yet.
+
+namespace MetaObjects.Core.Reporting;
+
+/// The measure.derived @expr grammar.
+public static class DerivedExpr
+{
+ private const string KEY_FIELD = "field";
+ private const string KEY_VALUE = "value";
+ private const string KEY_FN = "fn";
+ private const string KEY_ARGS = "args";
+
+ /// True for a node of the grammar, its whole subtree included.
+ public static bool IsDerivedExpr(object? node)
+ {
+ if (node is not IReadOnlyDictionary n) return false;
+ if (n.Count == 1 && n.TryGetValue(KEY_FIELD, out var field)) return field is string { Length: > 0 };
+ if (n.Count == 1 && n.TryGetValue(KEY_VALUE, out var value)) return IsFiniteNumber(value);
+ if (n.Count == 2 && n.TryGetValue(KEY_FN, out var fn) && n.TryGetValue(KEY_ARGS, out var args))
+ {
+ return fn is string f && ReportingConstants.DERIVED_FNS.Contains(f) &&
+ args is IEnumerable list && list.Count() == 2 && list.All(IsDerivedExpr);
+ }
+ return false;
+ }
+
+ /// The names a well-formed expression's { field } operands read, each once, in first-read order.
+ public static IReadOnlyList Fields(object? node)
+ {
+ var out_ = new List();
+ Collect(node, out_);
+ return out_;
+ }
+
+ private static void Collect(object? node, List out_)
+ {
+ if (node is not IReadOnlyDictionary n) return;
+ if (n.TryGetValue(KEY_FIELD, out var f) && f is string name)
+ {
+ if (!out_.Contains(name)) out_.Add(name);
+ }
+ else if (n.TryGetValue(KEY_ARGS, out var args) && args is IEnumerable list)
+ {
+ foreach (var a in list) Collect(a, out_);
+ }
+ }
+
+ private static bool IsFiniteNumber(object? v) => v switch
+ {
+ int or long or short or decimal => true,
+ double d => double.IsFinite(d),
+ float f => float.IsFinite(f),
+ _ => false,
+ };
+}
diff --git a/server/csharp/MetaObjects/Core/Reporting/ReportShape.cs b/server/csharp/MetaObjects/Core/Reporting/ReportShape.cs
index 60e3c8512a..3b48bc8a1a 100644
--- a/server/csharp/MetaObjects/Core/Reporting/ReportShape.cs
+++ b/server/csharp/MetaObjects/Core/Reporting/ReportShape.cs
@@ -361,7 +361,7 @@ private static ReportField MeasureField(string item, MetaObject report, MetaObje
///
private static (string SubType, MetaField? TypeSource)? DeriveMeasure(MetaMeasure m, MetaObject from, MetaRoot root)
{
- if (m.IsRatio()) return (FIELD_SUBTYPE_DECIMAL, null);
+ if (m.IsRatio() || m.IsDerived()) return (FIELD_SUBTYPE_DECIMAL, null);
string? agg = m.Agg();
if (agg == AGG_COUNT) return (FIELD_SUBTYPE_LONG, null);
// any / all are boolean whatever the source (the loader's M4 refuses a non-boolean @of).
diff --git a/server/csharp/MetaObjects/Core/Reporting/ReportingConstants.cs b/server/csharp/MetaObjects/Core/Reporting/ReportingConstants.cs
index c469f117b6..29df51f551 100644
--- a/server/csharp/MetaObjects/Core/Reporting/ReportingConstants.cs
+++ b/server/csharp/MetaObjects/Core/Reporting/ReportingConstants.cs
@@ -33,13 +33,16 @@ public static class ReportingConstants
/// One aggregate over the declaring entity's own rows.
public const string MEASURE_SUBTYPE_AGGREGATE = "aggregate";
+ /// A quotient of two measure.aggregate siblings, numerator / NULLIF(denominator, 0) .
+ public const string MEASURE_SUBTYPE_RATIO = "ratio";
+
///
- /// A quotient of two measure.aggregate siblings, numerator / NULLIF(denominator, 0) .
- /// measure.derived is deliberately NOT registered: it waits for FR-037 R5.
+ /// FR-044 R13: arithmetic (@expr ) over the entity's measures and its numeric attribute
+ /// dimensions — FR-037 R5's first arithmetic wave.
///
- public const string MEASURE_SUBTYPE_RATIO = "ratio";
+ public const string MEASURE_SUBTYPE_DERIVED = "derived";
- public static readonly string[] MEASURE_SUBTYPES = [MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO];
+ public static readonly string[] MEASURE_SUBTYPES = [MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO, MEASURE_SUBTYPE_DERIVED];
///
/// A named, reusable row filter. The only concrete segment subtype: every *.base
@@ -82,6 +85,17 @@ public static class ReportingConstants
/// Integer a measure reads when it would otherwise be null (measure.aggregate / measure.ratio ).
public const string REPORTING_ATTR_DEFAULT = "default";
+ /// The arithmetic of a measure.derived (an attr.expression, R13).
+ public const string REPORTING_ATTR_EXPR = "expr";
+
+ public const string DERIVED_FN_ADD = "add";
+ public const string DERIVED_FN_SUBTRACT = "subtract";
+ public const string DERIVED_FN_MULTIPLY = "multiply";
+ public const string DERIVED_FN_DIVIDE = "divide";
+
+ /// The operations a measure.derived @expr takes, each of two operands.
+ public static readonly string[] DERIVED_FNS = [DERIVED_FN_ADD, DERIVED_FN_SUBTRACT, DERIVED_FN_MULTIPLY, DERIVED_FN_DIVIDE];
+
// -----------------------------------------------------------------------
// Closed sets — mirrored by `allowedValues` in spec/metamodel/reporting.json.
// Order is part of the contract (it is the order the registry manifest records).
diff --git a/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs b/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs
index 635f3746f8..101fbc6dc5 100644
--- a/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs
+++ b/server/csharp/MetaObjects/Core/Reporting/ReportingSchema.cs
@@ -67,6 +67,12 @@ private static AttrSchema MeasureDefault() =>
MeasureDefault(),
];
+ /// measure.derived — the required @expr (R13); no @default.
+ private static readonly IReadOnlyList MeasureDerivedAttrs =
+ [
+ new(Name: ReportingConstants.REPORTING_ATTR_EXPR, ValueType: AttrConstants.ATTR_SUBTYPE_EXPRESSION, Required: true),
+ ];
+
/// segment.filter — the required @filter.
private static readonly IReadOnlyList SegmentFilterAttrs =
[
@@ -87,6 +93,7 @@ private static AttrSchema MeasureDefault() =>
{
[ReportingConstants.MEASURE_SUBTYPE_AGGREGATE] = MeasureAggregateAttrs,
[ReportingConstants.MEASURE_SUBTYPE_RATIO] = MeasureRatioAttrs,
+ [ReportingConstants.MEASURE_SUBTYPE_DERIVED] = MeasureDerivedAttrs,
};
/// Attrs per segment subtype.
diff --git a/server/csharp/MetaObjects/CoreTypes.cs b/server/csharp/MetaObjects/CoreTypes.cs
index 44bb64208b..37615de07a 100644
--- a/server/csharp/MetaObjects/CoreTypes.cs
+++ b/server/csharp/MetaObjects/CoreTypes.cs
@@ -647,8 +647,8 @@ private static void RegisterCoreTypeDefs(TypeRegistry registry)
// of `object.entity` (spec/metamodel/object.json), never root-level, so no root
// wildcard is added above. Three types in one provider file (reporting.json)
// because they are one vocabulary: a report names dimensions and measures, and
- // both may reference a segment. `measure.derived` is NOT registered (waits for
- // FR-037 R5). Descriptions + whenToUse come from the embedded reporting.json via
+ // both may reference a segment. `measure.derived` is FR-037 R5's first arithmetic
+ // wave (R13). Descriptions + whenToUse come from the embedded reporting.json via
// ApplySpecDescriptions; the placeholder descriptions below are overwritten there.
foreach (string subType in DIMENSION_SUBTYPES)
{
diff --git a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs
index 6c90958984..e56ea5db11 100644
--- a/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs
+++ b/server/csharp/MetaObjects/Loader/ValidationPasses.Reporting.cs
@@ -558,6 +558,11 @@ void Err(string message) =>
CheckRatioOperands(ctx, measure, Err);
return;
}
+ if (measure.IsDerived())
+ {
+ CheckDerivedExpr(ctx, measure, Err);
+ return;
+ }
if (measure.SubType != MEASURE_SUBTYPE_AGGREGATE) return;
bool clean = CheckAggregateColumns(ctx, measure, Err, out var ofField);
@@ -735,6 +740,66 @@ private static void CheckRatioOperands(MemberCtx ctx, MetaMeasure ratio, Action<
}
}
+ ///
+ /// M11 — a measure.derived's @expr is FR-037 R5's arithmetic over operands a report can read:
+ /// each { field } names a numeric measure.aggregate or measure.ratio of the same entity,
+ /// or a numeric attribute dimension of it (R13 then requires the report to list that
+ /// dimension). A derived measure never reads another derived measure, and a name both a
+ /// measure and a dimension carry is refused rather than guessed. One error per offending operand.
+ ///
+ private static void CheckDerivedExpr(MemberCtx ctx, MetaMeasure measure, Action err)
+ {
+ if (measure.Attr(REPORTING_ATTR_EXPR) is null) return; // missing @expr is ERR_MISSING_REQUIRED_ATTR
+ var expr = measure.Expr();
+ if (expr is null)
+ {
+ err("@expr is not an arithmetic expression. Each node is { field: }, " +
+ $"{{ value: }} or {{ fn: {string.Join(" | ", DERIVED_FNS)}, args: [, ] }}.");
+ return;
+ }
+ string entityKey = ctx.Declaring.ResolutionKey();
+ foreach (string name in DerivedExpr.Fields(expr))
+ {
+ var target = ReportingChildOfType(ctx.Host, TYPE_MEASURE, name);
+ var dim = ReportingChildOfType(ctx.Host, TYPE_DIMENSION, name);
+ if (target is not null && dim is not null)
+ {
+ err($"@expr names '{name}', which is both a measure and a dimension of '{entityKey}'. Rename one.");
+ }
+ else if (target is not null)
+ {
+ if (target.SubType == MEASURE_SUBTYPE_DERIVED)
+ {
+ err($"@expr names '{name}', a measure.derived. A derived measure reads aggregates, ratios and " +
+ "dimensions, not another derived measure.");
+ }
+ else if (target is MetaMeasure operand && ctx.Host is MetaObject from && ctx.Root is MetaRoot root &&
+ ReportShapes.MeasureResultSubType(operand, from, root) is { } result &&
+ !ReportingNumericFieldSubtypes.Contains(result))
+ {
+ err($"@expr names measure '{name}', whose result is a {result}, not a number.");
+ }
+ }
+ else if (dim is MetaDimension d)
+ {
+ if (d.IsTime())
+ {
+ err($"@expr names '{name}', a dimension.time. Arithmetic reads a numeric attribute dimension.");
+ }
+ else if (ctx.Host is MetaObject from && ctx.Root is MetaRoot root &&
+ ReportShapes.ResolveDimensionOf(d, from, root) is { } of &&
+ !ReportingNumericFieldSubtypes.Contains(of.Field.SubType))
+ {
+ err($"@expr names dimension '{name}', whose @of is a field.{of.Field.SubType}, not a number.");
+ }
+ }
+ else
+ {
+ err($"@expr names '{name}', which is no measure or dimension of '{entityKey}'.");
+ }
+ }
+ }
+
// -------------------------------------------------------------------------
// S1 / F2 — a reporting-host @filter over its entity
// -------------------------------------------------------------------------
@@ -977,6 +1042,9 @@ void Claim(string fieldName, string what)
// R12 — amounts in different units are never combined.
CheckValueObjectUnits(report, from, m => Err(m));
+ // R13 — a derived measure reads only dimensions the report groups by.
+ CheckDerivedDimensions(report, from, m => Err(m));
+
// R7 — @segment names a segment of @from.
// ADR-0039: resolving — a report may inherit @segment via extends.
if (report.Attr(OBJECT_REPORT_ATTR_SEGMENT) is string segment &&
@@ -1065,11 +1133,7 @@ private static void CheckValueObjectUnits(MetaData report, MetaData from, Action
{
string name = item[(item.LastIndexOf(CHILD_REF_SEPARATOR, StringComparison.Ordinal) + 1)..];
if (ReportingChildOfType(from, TYPE_MEASURE, name) is not MetaMeasure listed) continue;
- IEnumerable aggregates = listed.IsRatio()
- ? new[] { listed.Numerator(), listed.Denominator() }
- .Select(n => n is null ? null : ReportingChildOfType(from, TYPE_MEASURE, n))
- : [listed];
- foreach (var candidate in aggregates)
+ foreach (var candidate in AggregatesRead(listed, from))
{
if (candidate is not MetaMeasure m || m.SubType != MEASURE_SUBTYPE_AGGREGATE || !checkedMeasures.Add(m)) continue;
string? agg = m.Agg();
@@ -1095,6 +1159,46 @@ private static void CheckValueObjectUnits(MetaData report, MetaData from, Action
}
}
+ ///
+ /// The measures aggregates through: itself for a measure.aggregate,
+ /// its two operands for a ratio, and for a measure.derived each measure its @expr names (a
+ /// ratio there read through its operands). Unresolved names are left out; the member rules
+ /// report them.
+ ///
+ private static IEnumerable AggregatesRead(MetaMeasure listed, MetaData from)
+ {
+ MetaData? Measure(string? n) => n is null ? null : ReportingChildOfType(from, TYPE_MEASURE, n);
+ IEnumerable OperandsOf(MetaData? m) =>
+ m is MetaMeasure r && r.IsRatio() ? [Measure(r.Numerator()), Measure(r.Denominator())] : [m];
+ var read = listed.IsDerived()
+ ? (listed.Expr() is { } expr ? DerivedExpr.Fields(expr) : []).SelectMany(n => OperandsOf(Measure(n)))
+ : OperandsOf(listed);
+ return read.Where(m => m is not null).Select(m => m!);
+ }
+
+ ///
+ /// R13 — a measure.derived that reads an attribute dimension reads that dimension's value for
+ /// each group, so the report must list the dimension in @dimensions. A name that is also a
+ /// measure is M11's to report.
+ ///
+ private static void CheckDerivedDimensions(MetaData report, MetaData from, Action err)
+ {
+ var listedDims = ReportAccessors.ReportDimensionItems(report).Select(i => i.Name).ToHashSet(StringComparer.Ordinal);
+ foreach (string item in ReportAccessors.ReportMeasureNames(report))
+ {
+ string name = item[(item.LastIndexOf(CHILD_REF_SEPARATOR, StringComparison.Ordinal) + 1)..];
+ if (ReportingChildOfType(from, TYPE_MEASURE, name) is not MetaMeasure m || !m.IsDerived() ||
+ m.Expr() is not { } expr) continue;
+ foreach (string read in DerivedExpr.Fields(expr))
+ {
+ if (listedDims.Contains(read) || ReportingChildOfType(from, TYPE_MEASURE, read) is not null) continue;
+ if (ReportingChildOfType(from, TYPE_DIMENSION, read) is null) continue;
+ err($": measure '{m.Name}' reads dimension '{read}', which @dimensions does not list. A derived " +
+ "measure reads a dimension's value for each group, so the report must group by it.");
+ }
+ }
+ }
+
private static string? CheckReportMeasure(
MetaData root, MetaData report, MetaData from, string item, string label, ReportingErrorSink sink)
{
diff --git a/server/csharp/MetaObjects/Meta/MetaMeasure.cs b/server/csharp/MetaObjects/Meta/MetaMeasure.cs
index e750cf6ec2..41d8680ecc 100644
--- a/server/csharp/MetaObjects/Meta/MetaMeasure.cs
+++ b/server/csharp/MetaObjects/Meta/MetaMeasure.cs
@@ -13,9 +13,16 @@ namespace MetaObjects.Meta;
// ADR-0039: every getter below uses the RESOLVING Attr() accessor.
public class MetaMeasure(TypeId typeId, string name) : MetaData(typeId, name)
{
- /// True for measure.ratio ; false for measure.aggregate .
+ /// True for measure.ratio .
public bool IsRatio() => SubType == MEASURE_SUBTYPE_RATIO;
+ /// True for measure.derived (R13).
+ public bool IsDerived() => SubType == MEASURE_SUBTYPE_DERIVED;
+
+ /// A measure.derived 's @expr , when it is a well-formed arithmetic expression.
+ public IReadOnlyDictionary? Expr() =>
+ Attr(REPORTING_ATTR_EXPR) is IReadOnlyDictionary e && DerivedExpr.IsDerivedExpr(e) ? e : null;
+
/// The aggregate function (measure.aggregate only); null outside the closed set.
public string? Agg() =>
Attr(REPORTING_ATTR_AGG) is string s && MEASURE_AGGS.Contains(s) ? s : null;
diff --git a/server/csharp/MetaObjects/SpecMetamodel/reporting.json b/server/csharp/MetaObjects/SpecMetamodel/reporting.json
index 98c0bd24f0..adbe87f9ed 100644
--- a/server/csharp/MetaObjects/SpecMetamodel/reporting.json
+++ b/server/csharp/MetaObjects/SpecMetamodel/reporting.json
@@ -5,14 +5,14 @@
"description": "A named group-by attribute of the entity that declares it (FR-044). Groups report rows by a column value as-is. @of names Entity.field: the owning entity, or the @via terminal. @via may follow only to-one hops, so grouping by a related row's column can never multiply the measured rows.",
"whenToUse": "A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports.",
"children": [
- { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via)." },
+ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own." },
{ "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference." }
] },
{ "type": "dimension", "subType": "time",
"description": "A named time dimension (FR-044): groups report rows by a date or timestamp column truncated to a grain. @of names a field.date or field.timestamp. Weeks start on Monday (ISO-8601) in every lowering. A report names it as 'dimension:grain' and the derived report field is (e.g. purchasedAtDay).",
"whenToUse": "Per-day, per-week or per-month series on a dashboard.",
"children": [
- { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column." },
+ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object." },
{ "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path, as on dimension.attribute." },
{ "type": "attr", "subType": "string", "name": "grains", "isArray": true, "min": 1, "max": 1, "allowedValues": ["hour", "day", "week", "month", "quarter", "year"], "description": "The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date." }
] },
@@ -21,7 +21,7 @@
"whenToUse": "A number a dashboard shows: revenue, purchases, distinct buyers, last activity.",
"children": [
{ "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all"], "description": "The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment." },
- { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." },
+ { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." },
{ "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Count distinct values. Legal only with @agg: count." },
{ "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: \"-P7D\" }). Combines with @segment by AND." },
{ "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment declared on the same entity. Combines with @filter by AND." },
@@ -35,6 +35,12 @@
{ "type": "attr", "subType": "string", "name": "denominator", "min": 1, "max": 1, "description": "Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field." },
{ "type": "attr", "subType": "int", "name": "default", "min": 0, "max": 1, "description": "Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio." }
] },
+ { "type": "measure", "subType": "derived",
+ "description": "A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.",
+ "whenToUse": "A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).",
+ "children": [
+ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands." }
+ ] },
{ "type": "segment", "subType": "filter",
"description": "A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment.",
"whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.",
diff --git a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java
index 968fefefa3..eedad7b05f 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/loader/ReportingValidation.java
@@ -40,6 +40,7 @@
import com.metaobjects.object.MetaObject;
import com.metaobjects.query.FilterOps;
import com.metaobjects.relationship.MetaRelationship;
+import com.metaobjects.reporting.DerivedExpr;
import com.metaobjects.reporting.MetaDimension;
import com.metaobjects.reporting.MetaMeasure;
import com.metaobjects.reporting.MetaSegment;
@@ -681,6 +682,10 @@ private static void checkMeasure(MemberCtx ctx, MetaMeasure measure) {
checkRatioOperands(ctx, measure, err);
return;
}
+ if (measure.isDerived()) {
+ checkDerivedExpr(ctx, measure, err);
+ return;
+ }
if (!ReportingConstants.MEASURE_SUBTYPE_AGGREGATE.equals(measure.getSubType())) return;
AggregateColumns checked = checkAggregateColumns(ctx, measure, err);
@@ -843,6 +848,55 @@ private static void checkRatioOperands(MemberCtx ctx, MetaMeasure ratio, Consume
}
}
+ /**
+ * M11 — a measure.derived's @expr is FR-037 R5's arithmetic over operands a report can read:
+ * each {@code { field }} names a numeric measure.aggregate or measure.ratio of the same entity,
+ * or a numeric attribute dimension of it (R13 then requires the report to list that
+ * dimension). A derived measure never reads another derived measure, and a name both a
+ * measure and a dimension carry is refused rather than guessed. One error per offending operand.
+ */
+ private static void checkDerivedExpr(MemberCtx ctx, MetaMeasure measure, Consumer err) {
+ if (!measure.hasMetaAttr(ReportingConstants.ATTR_EXPR)) return; // ERR_MISSING_REQUIRED_ATTR
+ Map expr = measure.getExpr();
+ if (expr == null) {
+ err.accept("@expr is not an arithmetic expression. Each node is { field: }, "
+ + "{ value: } or { fn: " + String.join(" | ", ReportingConstants.DERIVED_FNS)
+ + ", args: [, ] }.");
+ return;
+ }
+ String entityKey = ctx.declaring().getName();
+ for (String name : DerivedExpr.fields(expr)) {
+ MetaData target = childOfType(ctx.host(), ReportingConstants.TYPE_MEASURE, name);
+ MetaData dim = childOfType(ctx.host(), ReportingConstants.TYPE_DIMENSION, name);
+ if (target != null && dim != null) {
+ err.accept("@expr names '" + name + "', which is both a measure and a dimension of '" + entityKey
+ + "'. Rename one.");
+ } else if (target != null) {
+ if (ReportingConstants.MEASURE_SUBTYPE_DERIVED.equals(target.getSubType())) {
+ err.accept("@expr names '" + name + "', a measure.derived. A derived measure reads aggregates, "
+ + "ratios and dimensions, not another derived measure.");
+ } else if (target instanceof MetaMeasure operand) {
+ String result = ReportShape.measureResultSubType(operand, ctx.host(), ctx.root());
+ if (result != null && !NUMERIC_FIELD_SUBTYPES.contains(result)) {
+ err.accept("@expr names measure '" + name + "', whose result is a " + result + ", not a number.");
+ }
+ }
+ } else if (dim instanceof MetaDimension d) {
+ if (d.isTime()) {
+ err.accept("@expr names '" + name + "', a dimension.time. Arithmetic reads a numeric attribute dimension.");
+ } else {
+ MetaField> of = ReportShape.resolveDimensionOf(d, ctx.host(), ctx.root());
+ if (of != null && !NUMERIC_FIELD_SUBTYPES.contains(of.getSubType())) {
+ err.accept("@expr names dimension '" + name + "', whose @of is a field." + of.getSubType()
+ + ", not a number.");
+ }
+ }
+ } else {
+ err.accept("@expr names '" + name + "', which is no measure or dimension of '" + entityKey + "'.");
+ }
+ }
+ }
+
// ---------------------------------------------------------------------------
// S1 / F2 — a reporting-host @filter over its entity
// ---------------------------------------------------------------------------
@@ -1067,6 +1121,9 @@ private static void checkReport(MetaRoot root, MetaObject report, ErrorSink sink
// R12 — amounts in different units are never combined.
checkValueObjectUnits(report, from, message -> sink.push(report, ErrorCode.ERR_INVALID_REPORT, label, message));
+ // R13 — a derived measure reads only dimensions the report groups by.
+ checkDerivedDimensions(report, from, message -> sink.push(report, ErrorCode.ERR_INVALID_REPORT, label, message));
+
// R7 — @segment names a segment of @from.
String segment = stringAttr(report, MetaObject.ATTR_REPORT_SEGMENT);
if (segment != null && childOfType(from, ReportingConstants.TYPE_SEGMENT, segment) == null) {
@@ -1158,20 +1215,12 @@ private static void checkValueObjectUnits(MetaObject report, MetaObject from, Co
for (String item : ReportAccessors.reportMeasureNames(report)) {
String name = item.substring(item.lastIndexOf(SEP) + 1);
if (!(childOfType(from, ReportingConstants.TYPE_MEASURE, name) instanceof MetaMeasure listed)) continue;
- List aggregates = new ArrayList<>();
- if (listed.isRatio()) {
- for (String operand : new String[] {listed.getNumerator(), listed.getDenominator()}) {
- if (operand != null) aggregates.add(childOfType(from, ReportingConstants.TYPE_MEASURE, operand));
- }
- } else {
- aggregates.add(listed);
- }
- for (MetaData candidate : aggregates) {
+ for (MetaData candidate : aggregatesRead(listed, from)) {
if (!(candidate instanceof MetaMeasure m)
|| !ReportingConstants.MEASURE_SUBTYPE_AGGREGATE.equals(m.getSubType()) || !checked.add(m)) continue;
String agg = m.getAgg();
- if (!List.of(ReportingConstants.AGG_SUM, ReportingConstants.AGG_AVG, ReportingConstants.AGG_MIN,
- ReportingConstants.AGG_MAX).contains(agg)) continue;
+ if (agg == null || !List.of(ReportingConstants.AGG_SUM, ReportingConstants.AGG_AVG,
+ ReportingConstants.AGG_MIN, ReportingConstants.AGG_MAX).contains(agg)) continue;
String of = m.getOfColumns().isEmpty() ? "" : m.getOfColumns().get(0);
Dotted parts = splitDotted(of);
if (parts == null || parts.path().size() != 2) continue;
@@ -1196,6 +1245,58 @@ private static void checkValueObjectUnits(MetaObject report, MetaObject from, Co
}
}
+ /**
+ * The measures {@code listed} aggregates through: itself for a measure.aggregate, its two
+ * operands for a ratio, and for a measure.derived each measure its @expr names (a ratio there
+ * read through its operands). Unresolved names are left out; the member rules report them.
+ */
+ private static List aggregatesRead(MetaMeasure listed, MetaObject from) {
+ List direct = new ArrayList<>();
+ if (listed.isDerived()) {
+ Map expr = listed.getExpr();
+ if (expr != null) {
+ for (String n : DerivedExpr.fields(expr)) direct.add(childOfType(from, ReportingConstants.TYPE_MEASURE, n));
+ }
+ } else {
+ direct.add(listed);
+ }
+ List out = new ArrayList<>();
+ for (MetaData m : direct) {
+ if (m instanceof MetaMeasure r && r.isRatio()) {
+ for (String operand : new String[] {r.getNumerator(), r.getDenominator()}) {
+ MetaData o = operand == null ? null : childOfType(from, ReportingConstants.TYPE_MEASURE, operand);
+ if (o != null) out.add(o);
+ }
+ } else if (m != null) {
+ out.add(m);
+ }
+ }
+ return out;
+ }
+
+ /**
+ * R13 — a measure.derived that reads an attribute dimension reads that dimension's value for
+ * each group, so the report must list the dimension in @dimensions. A name that is also a
+ * measure is M11's to report.
+ */
+ private static void checkDerivedDimensions(MetaObject report, MetaObject from, Consumer err) {
+ Set listedDims = new HashSet<>();
+ for (ReportDimensionItem item : ReportAccessors.reportDimensionItems(report)) listedDims.add(item.name());
+ for (String item : ReportAccessors.reportMeasureNames(report)) {
+ String name = item.substring(item.lastIndexOf(SEP) + 1);
+ if (!(childOfType(from, ReportingConstants.TYPE_MEASURE, name) instanceof MetaMeasure m) || !m.isDerived()) continue;
+ Map expr = m.getExpr();
+ if (expr == null) continue;
+ for (String read : DerivedExpr.fields(expr)) {
+ if (listedDims.contains(read) || childOfType(from, ReportingConstants.TYPE_MEASURE, read) != null) continue;
+ if (childOfType(from, ReportingConstants.TYPE_DIMENSION, read) == null) continue;
+ err.accept(": measure '" + m.getShortName() + "' reads dimension '" + read + "', which @dimensions "
+ + "does not list. A derived measure reads a dimension's value for each group, so the report "
+ + "must group by it.");
+ }
+ }
+ }
+
private static String checkReportMeasure(MetaRoot root, MetaObject report, MetaObject from, String item,
String label, ErrorSink sink) {
String fromKey = from.getName();
diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/DerivedExpr.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/DerivedExpr.java
new file mode 100644
index 0000000000..3de4915922
--- /dev/null
+++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/DerivedExpr.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2026 Doug Mealing LLC dba Meta Objects
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.metaobjects.reporting;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * FR-044 R13 — the {@code @expr} grammar of a {@code measure.derived}: FR-037 R5's first
+ * arithmetic wave. Ported from {@code server/typescript/packages/metadata/src/core/reporting/derived-expr.ts}.
+ * A closed subset of the attr.expression node grammar: an operand is {@code { field: name }} or
+ * {@code { value: number }}; an operation is {@code { fn: add | subtract | multiply | divide, args: [a, b] }}.
+ * origin.computed's grammar does not take the arithmetic members yet.
+ */
+public final class DerivedExpr {
+
+ private static final String KEY_FIELD = "field";
+ private static final String KEY_VALUE = "value";
+ private static final String KEY_FN = "fn";
+ private static final String KEY_ARGS = "args";
+
+ private DerivedExpr() {}
+
+ /** True for a node of the grammar, its whole subtree included. */
+ public static boolean isDerivedExpr(Object node) {
+ if (!(node instanceof Map, ?> n)) return false;
+ if (n.size() == 1 && n.containsKey(KEY_FIELD)) return n.get(KEY_FIELD) instanceof String s && !s.isEmpty();
+ if (n.size() == 1 && n.containsKey(KEY_VALUE)) return isFiniteNumber(n.get(KEY_VALUE));
+ if (n.size() == 2 && n.containsKey(KEY_FN) && n.containsKey(KEY_ARGS)) {
+ return n.get(KEY_FN) instanceof String fn && ReportingConstants.DERIVED_FNS.contains(fn)
+ && n.get(KEY_ARGS) instanceof List> args && args.size() == 2
+ && args.stream().allMatch(DerivedExpr::isDerivedExpr);
+ }
+ return false;
+ }
+
+ /** The names a well-formed expression's {@code { field }} operands read, each once, in first-read order. */
+ public static List fields(Object node) {
+ List out = new ArrayList<>();
+ collect(node, out);
+ return out;
+ }
+
+ private static void collect(Object node, List out) {
+ if (!(node instanceof Map, ?> n)) return;
+ if (n.get(KEY_FIELD) instanceof String name) {
+ if (!out.contains(name)) out.add(name);
+ } else if (n.get(KEY_ARGS) instanceof List> args) {
+ for (Object a : args) collect(a, out);
+ }
+ }
+
+ private static boolean isFiniteNumber(Object v) {
+ if (v instanceof Double d) return Double.isFinite(d);
+ if (v instanceof Float f) return Float.isFinite(f);
+ return v instanceof Number;
+ }
+}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/DerivedMeasure.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/DerivedMeasure.java
new file mode 100644
index 0000000000..de8cd64e84
--- /dev/null
+++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/DerivedMeasure.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright 2026 Doug Mealing LLC dba Meta Objects
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.metaobjects.reporting;
+
+import com.metaobjects.MetaData;
+import com.metaobjects.attr.ExpressionAttribute;
+import com.metaobjects.registry.MetaDataRegistry;
+
+/**
+ * {@code measure.derived} (FR-044 R13): arithmetic ({@code @expr}) over the entity's measures
+ * and its numeric attribute dimensions — FR-037 R5's first arithmetic wave. It takes no
+ * {@code @default}.
+ */
+@SuppressWarnings("serial")
+public class DerivedMeasure extends MetaMeasure {
+
+ public DerivedMeasure(String name) {
+ super(ReportingConstants.MEASURE_SUBTYPE_DERIVED, name);
+ }
+
+ /** Register {@code measure.derived}; descriptions come from {@code spec/metamodel/reporting.json}. */
+ public static void registerTypes(MetaDataRegistry registry) {
+ registry.registerType(DerivedMeasure.class, def -> {
+ def.type(ReportingConstants.TYPE_MEASURE).subType(ReportingConstants.MEASURE_SUBTYPE_DERIVED)
+ .description("A named arithmetic expression over measures and grouped dimensions.")
+ .inheritsFrom(MetaData.TYPE_METADATA, MetaData.SUBTYPE_BASE);
+ def.requiredAttributeWithConstraints(ReportingConstants.ATTR_EXPR)
+ .ofType(ExpressionAttribute.SUBTYPE_EXPRESSION).asSingle();
+ });
+ }
+}
diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/MetaMeasure.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/MetaMeasure.java
index 9714dc2627..230e2700ec 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/reporting/MetaMeasure.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/MetaMeasure.java
@@ -32,11 +32,26 @@ protected MetaMeasure(String subType, String name) {
super(ReportingConstants.TYPE_MEASURE, subType, name);
}
- /** True for {@code measure.ratio}; false for {@code measure.aggregate}. */
+ /** True for {@code measure.ratio}. */
public boolean isRatio() {
return ReportingConstants.MEASURE_SUBTYPE_RATIO.equals(getSubType());
}
+ /** True for {@code measure.derived} (R13). */
+ public boolean isDerived() {
+ return ReportingConstants.MEASURE_SUBTYPE_DERIVED.equals(getSubType());
+ }
+
+ /** A {@code measure.derived}'s {@code @expr} when it is a well-formed arithmetic expression, else {@code null}. */
+ public Map getExpr() {
+ if (!hasMetaAttr(ReportingConstants.ATTR_EXPR)) return null;
+ Object v = getMetaAttr(ReportingConstants.ATTR_EXPR).getValue();
+ if (!DerivedExpr.isDerivedExpr(v)) return null;
+ @SuppressWarnings("unchecked")
+ Map expr = (Map) v;
+ return expr;
+ }
+
/** The aggregate function ({@code measure.aggregate} only), or {@code null} when absent
* or outside the closed set. */
public String getAgg() {
diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportShape.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportShape.java
index 424a21637b..4ce25e6437 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportShape.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportShape.java
@@ -507,6 +507,23 @@ private static boolean isSelfOrAncestor(MetaData candidate, MetaData entity) {
return false;
}
+ /**
+ * The field a dimension's {@code @of} names, read after its {@code @via} (rule D1), or
+ * {@code null} when either does not resolve. R13 reads it to check a dimension operand is numeric.
+ */
+ public static MetaField> resolveDimensionOf(MetaDimension dim, MetaObject from, MetaRoot root) {
+ if (dim.getOf() == null) return null;
+ MetaData ofDeclaring = memberOwner(dim, from);
+ MetaObject ofHost = from;
+ if (dim.getVia() != null) {
+ MetaObject terminal = reportingViaTerminal(dim.getVia(), ofDeclaring, from, root);
+ if (terminal == null) return null;
+ ofDeclaring = terminal;
+ ofHost = terminal;
+ }
+ return resolveFieldRef(dim.getOf(), ofDeclaring, root, ofHost);
+ }
+
private static Field dimensionField(ReportDimensionItem item, MetaObject from, MetaRoot root, MetaObject report,
List spine) {
MetaDimension dim = declaredMember(from, MetaDimension.class, item.name());
@@ -579,7 +596,7 @@ private record MeasureDerivation(String subType, MetaField> typeSource) {}
/** Table B for one measure. {@code null} when its {@code @of} does not resolve. */
private static MeasureDerivation deriveMeasure(MetaMeasure m, MetaObject from, MetaRoot root) {
- if (m.isRatio()) return new MeasureDerivation(DecimalField.SUBTYPE_DECIMAL, null);
+ if (m.isRatio() || m.isDerived()) return new MeasureDerivation(DecimalField.SUBTYPE_DECIMAL, null);
String agg = m.getAgg();
if (ReportingConstants.AGG_COUNT.equals(agg)) return new MeasureDerivation(LongField.SUBTYPE_LONG, null);
// any / all are boolean whatever the source (the loader's M4 refuses a non-boolean @of).
diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingConstants.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingConstants.java
index 69f77f965f..e688468b2b 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingConstants.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingConstants.java
@@ -51,9 +51,10 @@ private ReportingConstants() {
/** One aggregate over the declaring entity's own rows. */
public static final String MEASURE_SUBTYPE_AGGREGATE = "aggregate";
- /** A quotient of two {@code measure.aggregate} siblings. {@code measure.derived} is
- * deliberately NOT registered: it waits for FR-037 R5. */
+ /** A quotient of two {@code measure.aggregate} siblings. */
public static final String MEASURE_SUBTYPE_RATIO = "ratio";
+ /** FR-044 R13: arithmetic ({@code @expr}) over measures and numeric attribute dimensions. */
+ public static final String MEASURE_SUBTYPE_DERIVED = "derived";
/** A named, reusable row filter — the only concrete segment subtype. */
public static final String SEGMENT_SUBTYPE_FILTER = "filter";
@@ -85,6 +86,16 @@ private ReportingConstants() {
* registration: a field's is an untyped string re-read by the field's subtype.
*/
public static final String ATTR_DEFAULT = "default";
+ /** The arithmetic of a {@code measure.derived} (an attr.expression, R13). */
+ public static final String ATTR_EXPR = "expr";
+
+ public static final String DERIVED_FN_ADD = "add";
+ public static final String DERIVED_FN_SUBTRACT = "subtract";
+ public static final String DERIVED_FN_MULTIPLY = "multiply";
+ public static final String DERIVED_FN_DIVIDE = "divide";
+ /** The operations a {@code measure.derived} {@code @expr} takes, each of two operands. */
+ public static final List DERIVED_FNS =
+ List.of(DERIVED_FN_ADD, DERIVED_FN_SUBTRACT, DERIVED_FN_MULTIPLY, DERIVED_FN_DIVIDE);
// ------------------------------------------------------------------
// Closed sets — mirrored by allowedValues in spec/metamodel/reporting.json.
diff --git a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java
index 9b2ad1f47b..395ccbbe72 100644
--- a/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java
+++ b/server/java/metadata/src/main/java/com/metaobjects/reporting/ReportingTypesMetaDataProvider.java
@@ -24,8 +24,8 @@
* Registers the entity-member reporting vocabulary: {@code dimension.attribute},
* {@code dimension.time}, {@code measure.aggregate}, {@code measure.ratio} and
* {@code segment.filter}. {@code object.report} is an object subtype and is registered by
- * the object-types provider beside {@code object.projection}. {@code measure.derived} is
- * deliberately absent (it waits for FR-037 R5).
+ * the object-types provider beside {@code object.projection}. {@code measure.derived} (R13) is
+ * FR-037 R5's first arithmetic wave.
*
* Depends on {@code core-types} for {@code metadata.base} inheritance.
*/
@@ -37,6 +37,7 @@ public void registerTypes(MetaDataRegistry registry) {
TimeDimension.registerTypes(registry);
AggregateMeasure.registerTypes(registry);
RatioMeasure.registerTypes(registry);
+ DerivedMeasure.registerTypes(registry);
FilterSegment.registerTypes(registry);
}
diff --git a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java
index c5bf63f1ff..333081e3ba 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/loader/ReportingValidationTest.java
@@ -476,7 +476,7 @@ public void aBareStringOfWithACommaIsOneInvalidItem() throws IOException {
List got = ValidationPhase.validateReporting(loadJson(doc));
assertEquals(List.of("ERR_INVALID_MEASURE"), codes(got));
assertEquals("measure 'revenue' on entity 'acme::shop::Purchase': @of 'Purchase.amountCents,Purchase.id' "
- + "must be Entity.field.", got.get(0).getMessage());
+ + "names no field 'amountCents,Purchase' on 'acme::shop::Purchase'.", got.get(0).getMessage());
}
// ---------------------------------------------------------------------------
diff --git a/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportShapeTest.java b/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportShapeTest.java
index d563cd235e..34eefb9b05 100644
--- a/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportShapeTest.java
+++ b/server/java/metadata/src/test/java/com/metaobjects/reporting/ReportShapeTest.java
@@ -246,6 +246,30 @@ public void aValueObjectMemberDerivesTheMembersType() throws IOException {
"averagePayment decimal false -", "payments long true -"), rows);
}
+ @Test
+ public void aDerivedMeasureIsANullableDecimal() throws IOException {
+ // FR-044 R13: a measure.derived is typed decimal, not required, with no type source,
+ // whatever its operands. The same rows as the TypeScript derivation of this fixture.
+ Path input = corpusDir().resolveSibling("conformance")
+ .resolve("reporting-derived-measures/input/meta.studio.json");
+ MetaRoot root = loadJson(new String(Files.readAllBytes(input), StandardCharsets.UTF_8));
+ java.util.function.Function> rows = name ->
+ ReportShape.of(object(root, name), root).fields().stream()
+ .map(f -> f.name() + " " + f.subType() + " " + f.required() + " "
+ + (f.typeSourceKey() == null ? "-" : f.typeSourceKey()))
+ .collect(Collectors.toList());
+ assertEquals(List.of("memberId long false acme::studio::Member.id",
+ "memberName string true acme::studio::Member.firstName",
+ "weeklyCapacityHours decimal true acme::studio::Member.weeklyCapacityHours",
+ "workedOnMonth date true -", "totalHours decimal true -", "billableHours decimal true -",
+ "capacityHours decimal false -", "utilization decimal false -",
+ "nonBillableHours decimal false -", "billableSharePct decimal false -"),
+ rows.apply("MemberUtilization"));
+ assertEquals(List.of("projectId long false acme::studio::Project.id",
+ "projectBudget decimal false acme::studio::Project.budget", "cost decimal false -",
+ "budgetBurn decimal false -"), rows.apply("ProjectBurn"));
+ }
+
@Test
public void aReportWithNoDimensionsHasOnlyMeasures() {
ReportShape shape = ReportShape.of(object(canonical, "FitnessTotals"), canonical);
diff --git a/server/python/src/metaobjects/core_types.py b/server/python/src/metaobjects/core_types.py
index 5030e34220..f93f4c7f01 100644
--- a/server/python/src/metaobjects/core_types.py
+++ b/server/python/src/metaobjects/core_types.py
@@ -83,10 +83,12 @@
DIMENSION_SUBTYPE_TIME,
MEASURE_AGGS,
MEASURE_SUBTYPE_AGGREGATE,
+ MEASURE_SUBTYPE_DERIVED,
MEASURE_SUBTYPE_RATIO,
REPORTING_ATTR_AGG,
REPORTING_ATTR_DEFAULT,
REPORTING_ATTR_DENOMINATOR,
+ REPORTING_ATTR_EXPR,
REPORTING_ATTR_DISTINCT,
REPORTING_ATTR_FILTER,
REPORTING_ATTR_GRAINS,
@@ -463,6 +465,18 @@ def _register_subtypes(
child_rules=[ChildRule(TYPE_ATTR, "*")],
)
)
+# FR-044 R13: measure.derived — FR-037 R5's first arithmetic wave; no @default.
+core_provider.add(
+ TypeDefinition(
+ type=TYPE_MEASURE,
+ sub_type=MEASURE_SUBTYPE_DERIVED,
+ factory=MetaMeasure,
+ attrs=[
+ AttrSchema(name=REPORTING_ATTR_EXPR, value_type=ATTR_SUBTYPE_EXPRESSION, required=True),
+ ],
+ child_rules=[ChildRule(TYPE_ATTR, "*")],
+ )
+)
core_provider.add(
TypeDefinition(
type=TYPE_SEGMENT,
diff --git a/server/python/src/metaobjects/loader/validate_reporting.py b/server/python/src/metaobjects/loader/validate_reporting.py
index ad19eb9429..a70dcca5d4 100644
--- a/server/python/src/metaobjects/loader/validate_reporting.py
+++ b/server/python/src/metaobjects/loader/validate_reporting.py
@@ -89,7 +89,8 @@
report_measure_names,
report_spine,
)
-from ..meta.core.reporting.report_shape import is_flattened_field, measure_result_sub_type
+from ..meta.core.reporting.derived_expr import derived_expr_fields
+from ..meta.core.reporting.report_shape import is_flattened_field, measure_result_sub_type, resolve_dimension_of
from ..meta.core.reporting.reporting_constants import (
AGG_AVG,
AGG_COUNT,
@@ -103,10 +104,13 @@
RELATIVE_START_OF_UNITS,
GRAIN_HOUR,
ISO_DURATION_RE,
+ DERIVED_FNS,
MEASURE_SUBTYPE_AGGREGATE,
+ MEASURE_SUBTYPE_DERIVED,
REPORT_DIMENSION_GRAIN_SEPARATOR,
REPORTING_ATTR_DEFAULT,
REPORTING_ATTR_DENOMINATOR,
+ REPORTING_ATTR_EXPR,
REPORTING_ATTR_NUMERATOR,
REPORTING_ATTR_VIA,
)
@@ -697,6 +701,9 @@ def err(message: str) -> None:
if measure.is_ratio():
_check_ratio_operands(ctx, measure, err)
return
+ if measure.is_derived():
+ _check_derived_expr(ctx, measure, err)
+ return
if measure.sub_type != MEASURE_SUBTYPE_AGGREGATE:
return
@@ -857,6 +864,52 @@ def _check_ratio_operands(ctx: _MemberCtx, ratio: MetaMeasure, err: Callable[[st
)
+def _check_derived_expr(ctx: _MemberCtx, measure: MetaMeasure, err: Callable[[str], None]) -> None:
+ """M11 — a measure.derived's @expr is FR-037 R5's arithmetic over operands a report can read:
+ each ``{ field }`` names a numeric measure.aggregate or measure.ratio of the same entity, or a
+ numeric attribute dimension of it (R13 then requires the report to list that dimension). A
+ derived measure never reads another derived measure, and a name both a measure and a
+ dimension carry is refused rather than guessed. One error per offending operand."""
+ # ADR-0039: resolving (get_meta_attr — Python attr() is own-only).
+ if measure.get_meta_attr(REPORTING_ATTR_EXPR) is None:
+ return # missing @expr is ERR_MISSING_REQUIRED_ATTR
+ expr = measure.expr()
+ if expr is None:
+ err(
+ "@expr is not an arithmetic expression. Each node is { field: }, "
+ f"{{ value: }} or {{ fn: {' | '.join(DERIVED_FNS)}, args: [, ] }}."
+ )
+ return
+ entity_key = ctx.declaring.resolution_key()
+ host_ok = isinstance(ctx.host, MetaObject) and isinstance(ctx.root, MetaRoot)
+ for name in derived_expr_fields(expr):
+ target = _child_of_type(ctx.host, TYPE_MEASURE, name)
+ dim = _child_of_type(ctx.host, TYPE_DIMENSION, name)
+ if target is not None and dim is not None:
+ err(f"@expr names '{name}', which is both a measure and a dimension of '{entity_key}'. Rename one.")
+ elif target is not None:
+ if target.sub_type == MEASURE_SUBTYPE_DERIVED:
+ err(
+ f"@expr names '{name}', a measure.derived. A derived measure reads aggregates, ratios and "
+ "dimensions, not another derived measure."
+ )
+ elif isinstance(target, MetaMeasure) and host_ok:
+ result = measure_result_sub_type(target, ctx.host, ctx.root) # type: ignore[arg-type]
+ if result is not None and result not in _NUMERIC_FIELD_SUBTYPES:
+ err(f"@expr names measure '{name}', whose result is a {result}, not a number.")
+ elif isinstance(dim, MetaDimension):
+ if dim.is_time():
+ err(f"@expr names '{name}', a dimension.time. Arithmetic reads a numeric attribute dimension.")
+ elif host_ok:
+ resolved = resolve_dimension_of(dim, ctx.host, ctx.root) # type: ignore[arg-type]
+ if resolved is not None and resolved[1].sub_type not in _NUMERIC_FIELD_SUBTYPES:
+ err(
+ f"@expr names dimension '{name}', whose @of is a field.{resolved[1].sub_type}, not a number."
+ )
+ else:
+ err(f"@expr names '{name}', which is no measure or dimension of '{entity_key}'.")
+
+
# ---------------------------------------------------------------------------
# S1 / F2 — a reporting-host @filter over its entity
# ---------------------------------------------------------------------------
@@ -1063,6 +1116,8 @@ def claim(field_name: str, what: str) -> None:
# R12 — amounts in different units are never combined.
_check_value_object_units(report, from_, err)
+ # R13 — a derived measure reads only dimensions the report groups by.
+ _check_derived_dimensions(report, from_, err)
# R7 — @segment names a segment of @from.
# ADR-0039: resolving (get_meta_attr — Python attr() is own-only).
@@ -1160,13 +1215,7 @@ def _check_value_object_units(report: MetaData, from_: MetaData, err: Callable[[
listed = _child_of_type(from_, TYPE_MEASURE, measure_item.rsplit(CHILD_REF_SEP, 1)[-1])
if not isinstance(listed, MetaMeasure):
continue
- operands = [listed.numerator(), listed.denominator()] if listed.is_ratio() else None
- candidates = (
- [listed]
- if operands is None
- else [_child_of_type(from_, TYPE_MEASURE, n) for n in operands if n is not None]
- )
- for m in candidates:
+ for m in _aggregates_read(listed, from_):
if not isinstance(m, MetaMeasure) or m.sub_type != MEASURE_SUBTYPE_AGGREGATE or id(m) in checked:
continue
checked.add(id(m))
@@ -1197,6 +1246,48 @@ def _check_value_object_units(report: MetaData, from_: MetaData, err: Callable[[
)
+def _aggregates_read(listed: MetaMeasure, from_: MetaData) -> list[MetaData]:
+ """The measures ``listed`` aggregates through: itself for a measure.aggregate, its two
+ operands for a ratio, and for a measure.derived each measure its @expr names (a ratio there
+ read through its operands). Unresolved names are left out; the member rules report them."""
+
+ def measure(n: str | None) -> MetaData | None:
+ return None if n is None else _child_of_type(from_, TYPE_MEASURE, n)
+
+ def operands_of(m: MetaData | None) -> list[MetaData | None]:
+ if isinstance(m, MetaMeasure) and m.is_ratio():
+ return [measure(m.numerator()), measure(m.denominator())]
+ return [m]
+
+ if listed.is_derived():
+ expr = listed.expr()
+ read = [o for n in (derived_expr_fields(expr) if expr is not None else []) for o in operands_of(measure(n))]
+ else:
+ read = operands_of(listed)
+ return [m for m in read if m is not None]
+
+
+def _check_derived_dimensions(report: MetaData, from_: MetaData, err: Callable[[str], None]) -> None:
+ """R13 — a measure.derived that reads an attribute dimension reads that dimension's value for
+ each group, so the report must list the dimension in @dimensions. A name that is also a
+ measure is M11's to report."""
+ listed_dims = {item.name for item in report_dimension_items(report)}
+ for measure_item in report_measure_names(report):
+ m = _child_of_type(from_, TYPE_MEASURE, measure_item.rsplit(CHILD_REF_SEP, 1)[-1])
+ expr = m.expr() if isinstance(m, MetaMeasure) and m.is_derived() else None
+ if m is None or expr is None:
+ continue
+ for name in derived_expr_fields(expr):
+ if name in listed_dims or _child_of_type(from_, TYPE_MEASURE, name) is not None:
+ continue
+ if _child_of_type(from_, TYPE_DIMENSION, name) is None:
+ continue
+ err(
+ f": measure '{m.name}' reads dimension '{name}', which @dimensions does not list. A derived "
+ "measure reads a dimension's value for each group, so the report must group by it."
+ )
+
+
def _check_report_measure(
root: MetaData,
report: MetaData,
diff --git a/server/python/src/metaobjects/meta/core/reporting/derived_expr.py b/server/python/src/metaobjects/meta/core/reporting/derived_expr.py
new file mode 100644
index 0000000000..bbd3b572a2
--- /dev/null
+++ b/server/python/src/metaobjects/meta/core/reporting/derived_expr.py
@@ -0,0 +1,62 @@
+"""FR-044 R13 — the ``@expr`` grammar of a ``measure.derived``: FR-037 R5's first arithmetic wave.
+
+Ported from ``server/typescript/packages/metadata/src/core/reporting/derived-expr.ts``. A closed
+subset of the attr.expression node grammar: an operand is ``{ field: name }`` (a sibling
+measure.aggregate or measure.ratio, or a numeric attribute dimension the report lists) or
+``{ value: number }``; an operation is ``{ fn: add | subtract | multiply | divide, args: [a, b] }``.
+origin.computed's grammar does not take the arithmetic members yet.
+"""
+from __future__ import annotations
+
+import math
+
+from .reporting_constants import DERIVED_FNS
+
+_KEY_FIELD = "field"
+_KEY_VALUE = "value"
+_KEY_FN = "fn"
+_KEY_ARGS = "args"
+
+
+def _is_finite_number(v: object) -> bool:
+ # bool is an int subclass in Python, and True is not a number here.
+ if isinstance(v, bool):
+ return False
+ if isinstance(v, int):
+ return True
+ return isinstance(v, float) and math.isfinite(v)
+
+
+def is_derived_expr(node: object) -> bool:
+ """True for a node of the grammar, its whole subtree included."""
+ if not isinstance(node, dict):
+ return False
+ keys = set(node)
+ if keys == {_KEY_FIELD}:
+ return isinstance(node[_KEY_FIELD], str) and len(node[_KEY_FIELD]) > 0
+ if keys == {_KEY_VALUE}:
+ return _is_finite_number(node[_KEY_VALUE])
+ if keys == {_KEY_FN, _KEY_ARGS}:
+ args = node[_KEY_ARGS]
+ return (
+ node[_KEY_FN] in DERIVED_FNS
+ and isinstance(args, list)
+ and len(args) == 2
+ and all(is_derived_expr(a) for a in args)
+ )
+ return False
+
+
+def derived_expr_fields(node: object, out: list[str] | None = None) -> list[str]:
+ """The names a well-formed expression's ``{ field }`` operands read, each once, in first-read order."""
+ if out is None:
+ out = []
+ if isinstance(node, dict):
+ name = node.get(_KEY_FIELD)
+ if isinstance(name, str):
+ if name not in out:
+ out.append(name)
+ elif isinstance(node.get(_KEY_ARGS), list):
+ for a in node[_KEY_ARGS]:
+ derived_expr_fields(a, out)
+ return out
diff --git a/server/python/src/metaobjects/meta/core/reporting/meta_measure.py b/server/python/src/metaobjects/meta/core/reporting/meta_measure.py
index f58c7017a7..fa1dc3e70a 100644
--- a/server/python/src/metaobjects/meta/core/reporting/meta_measure.py
+++ b/server/python/src/metaobjects/meta/core/reporting/meta_measure.py
@@ -9,16 +9,19 @@
from ...meta_data import MetaData
from .reporting_constants import (
MEASURE_AGGS,
+ MEASURE_SUBTYPE_DERIVED,
MEASURE_SUBTYPE_RATIO,
REPORTING_ATTR_AGG,
REPORTING_ATTR_DEFAULT,
REPORTING_ATTR_DENOMINATOR,
REPORTING_ATTR_DISTINCT,
+ REPORTING_ATTR_EXPR,
REPORTING_ATTR_FILTER,
REPORTING_ATTR_NUMERATOR,
REPORTING_ATTR_OF,
REPORTING_ATTR_SEGMENT,
)
+from .derived_expr import is_derived_expr
def _optional_string(v: object) -> str | None:
@@ -27,9 +30,19 @@ def _optional_string(v: object) -> str | None:
class MetaMeasure(MetaData):
def is_ratio(self) -> bool:
- """True for ``measure.ratio``; False for ``measure.aggregate``."""
+ """True for ``measure.ratio``."""
return self.sub_type == MEASURE_SUBTYPE_RATIO
+ def is_derived(self) -> bool:
+ """True for ``measure.derived`` (R13)."""
+ return self.sub_type == MEASURE_SUBTYPE_DERIVED
+
+ def expr(self) -> dict[str, object] | None:
+ """ADR-0039: resolving. A ``measure.derived``'s ``@expr`` when it is a well-formed
+ arithmetic expression (rule M11 refuses any other)."""
+ v = self.get_meta_attr(REPORTING_ATTR_EXPR)
+ return v if is_derived_expr(v) else None
+
def agg(self) -> str | None:
"""ADR-0039: resolving. The aggregate function (``measure.aggregate`` only)."""
v = self.get_meta_attr(REPORTING_ATTR_AGG)
diff --git a/server/python/src/metaobjects/meta/core/reporting/report_shape.py b/server/python/src/metaobjects/meta/core/reporting/report_shape.py
index 613ad7f2f4..ae5371eab1 100644
--- a/server/python/src/metaobjects/meta/core/reporting/report_shape.py
+++ b/server/python/src/metaobjects/meta/core/reporting/report_shape.py
@@ -479,7 +479,8 @@ def _measure_field(item: str, report: MetaObject, from_: MetaObject, root: MetaR
def _derive_measure(m: MetaMeasure, from_: MetaObject, root: MetaRoot) -> tuple[str, MetaField | None] | None:
"""Table B for one measure: its subtype, and the ``@of`` field it carries type attrs from
(if any). None when its ``@of`` does not resolve."""
- if m.is_ratio():
+ # A quotient, and (R13) an arithmetic expression, are decimal whatever their operands.
+ if m.is_ratio() or m.is_derived():
return FIELD_SUBTYPE_DECIMAL, None
agg = m.agg()
if agg == AGG_COUNT:
diff --git a/server/python/src/metaobjects/meta/core/reporting/reporting_constants.py b/server/python/src/metaobjects/meta/core/reporting/reporting_constants.py
index cd31ac5f98..b77fc68ede 100644
--- a/server/python/src/metaobjects/meta/core/reporting/reporting_constants.py
+++ b/server/python/src/metaobjects/meta/core/reporting/reporting_constants.py
@@ -32,9 +32,11 @@
#: One aggregate over the declaring entity's own rows.
MEASURE_SUBTYPE_AGGREGATE = "aggregate"
#: A quotient of two ``measure.aggregate`` siblings, ``numerator / NULLIF(denominator, 0)``.
-#: ``measure.derived`` is deliberately NOT registered: it waits for FR-037 R5.
MEASURE_SUBTYPE_RATIO = "ratio"
-MEASURE_SUBTYPES: tuple[str, ...] = (MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO)
+#: FR-044 R13: arithmetic (``@expr``) over sibling measures and the report's numeric attribute
+#: dimensions, typed decimal. Uses FR-037 R5's first arithmetic wave.
+MEASURE_SUBTYPE_DERIVED = "derived"
+MEASURE_SUBTYPES: tuple[str, ...] = (MEASURE_SUBTYPE_AGGREGATE, MEASURE_SUBTYPE_RATIO, MEASURE_SUBTYPE_DERIVED)
#: A named, reusable row filter. The only concrete segment subtype.
SEGMENT_SUBTYPE_FILTER = "filter"
@@ -63,6 +65,16 @@
REPORTING_ATTR_DENOMINATOR = "denominator"
#: Integer a measure reads when it would otherwise be null (``measure.aggregate`` / ``measure.ratio``).
REPORTING_ATTR_DEFAULT = "default"
+#: ``measure.derived``'s arithmetic expression (an attr.expression).
+REPORTING_ATTR_EXPR = "expr"
+
+#: The arithmetic ``fn`` members a ``measure.derived`` ``@expr`` may use, each with exactly two
+#: args. ``divide`` lowers as a ratio does: a zero divisor yields null.
+DERIVED_FN_ADD = "add"
+DERIVED_FN_SUBTRACT = "subtract"
+DERIVED_FN_MULTIPLY = "multiply"
+DERIVED_FN_DIVIDE = "divide"
+DERIVED_FNS: tuple[str, ...] = (DERIVED_FN_ADD, DERIVED_FN_SUBTRACT, DERIVED_FN_MULTIPLY, DERIVED_FN_DIVIDE)
# ---------------------------------------------------------------------------
# Closed sets — mirrored by ``allowedValues`` in spec/metamodel/reporting.json.
diff --git a/server/python/src/metaobjects/spec_metamodel/reporting.json b/server/python/src/metaobjects/spec_metamodel/reporting.json
index 98c0bd24f0..adbe87f9ed 100644
--- a/server/python/src/metaobjects/spec_metamodel/reporting.json
+++ b/server/python/src/metaobjects/spec_metamodel/reporting.json
@@ -5,14 +5,14 @@
"description": "A named group-by attribute of the entity that declares it (FR-044). Groups report rows by a column value as-is. @of names Entity.field: the owning entity, or the @via terminal. @via may follow only to-one hops, so grouping by a related row's column can never multiply the measured rows.",
"whenToUse": "A column a dashboard groups by: product, status, region. Declare it once on the fact entity and reference it by name from reports.",
"children": [
- { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via)." },
+ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own." },
{ "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path from the owning entity to the entity @of names (e.g. 'Purchase.program'). Every hop must be @cardinality: one or an identity.reference." }
] },
{ "type": "dimension", "subType": "time",
"description": "A named time dimension (FR-044): groups report rows by a date or timestamp column truncated to a grain. @of names a field.date or field.timestamp. Weeks start on Monday (ISO-8601) in every lowering. A report names it as 'dimension:grain' and the derived report field is (e.g. purchasedAtDay).",
"whenToUse": "Per-day, per-week or per-month series on a dashboard.",
"children": [
- { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column." },
+ { "type": "attr", "subType": "string", "name": "of", "min": 1, "max": 1, "description": "Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object." },
{ "type": "attr", "subType": "string", "name": "via", "min": 0, "max": 1, "description": "Optional dotted to-one relationship path, as on dimension.attribute." },
{ "type": "attr", "subType": "string", "name": "grains", "isArray": true, "min": 1, "max": 1, "allowedValues": ["hour", "day", "week", "month", "quarter", "year"], "description": "The grains this dimension supports. Weeks start Monday (ISO-8601). 'hour' is refused on a field.date." }
] },
@@ -21,7 +21,7 @@
"whenToUse": "A number a dashboard shows: revenue, purchases, distinct buyers, last activity.",
"children": [
{ "type": "attr", "subType": "string", "name": "agg", "min": 1, "max": 1, "allowedValues": ["count", "sum", "avg", "min", "max", "any", "all"], "description": "The aggregate function. sum/avg need a numeric field; min/max refuse boolean, object and map fields; any/all (boolean OR / AND, Postgres bool_or / bool_and) type the measure boolean and take either a field.boolean in @of or no @of, when they ask whether some row (any) or every row (all) passes the measure's @filter / @segment." },
- { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." },
+ { "type": "attr", "subType": "string", "name": "of", "isArray": true, "min": 0, "max": 1, "description": "Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows." },
{ "type": "attr", "subType": "boolean", "name": "distinct", "min": 0, "max": 1, "description": "Count distinct values. Legal only with @agg: count." },
{ "type": "attr", "subType": "filter", "name": "filter", "min": 0, "max": 1, "description": "Optional row scope (a portable attr.filter over the declaring entity's fields). May use relative-date values ({ now: \"-P7D\" }). Combines with @segment by AND." },
{ "type": "attr", "subType": "string", "name": "segment", "min": 0, "max": 1, "description": "Optional name of a segment declared on the same entity. Combines with @filter by AND." },
@@ -35,6 +35,12 @@
{ "type": "attr", "subType": "string", "name": "denominator", "min": 1, "max": 1, "description": "Name of a measure.aggregate on the same entity whose result is numeric: a count, a sum, an avg, or a min or max of a numeric field." },
{ "type": "attr", "subType": "int", "name": "default", "min": 0, "max": 1, "description": "Optional integer the measure reads when it would otherwise be null: nothing matched, every matched value is null, or (a ratio) the denominator is zero or null. The derived report field is then never null. Refused on @agg: count (a count is never null) and on min/max over a field that is not numeric. A ratio's operand carries its own @default into the ratio." }
] },
+ { "type": "measure", "subType": "derived",
+ "description": "A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.",
+ "whenToUse": "A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).",
+ "children": [
+ { "type": "attr", "subType": "expression", "name": "expr", "min": 1, "max": 1, "description": "The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands." }
+ ] },
{ "type": "segment", "subType": "filter",
"description": "A named, reusable row filter on the declaring entity (FR-044). Measures and reports reference it by name; exporters emit it as a named segment.",
"whenToUse": "The same filter (e.g. 'active purchase') would otherwise be repeated in several measures or reports.",
diff --git a/server/python/tests/test_report_shape.py b/server/python/tests/test_report_shape.py
index ee756311ce..d2e5bd2f43 100644
--- a/server/python/tests/test_report_shape.py
+++ b/server/python/tests/test_report_shape.py
@@ -899,3 +899,36 @@ def test_a_value_object_member_derives_the_members_type() -> None:
"averagePayment decimal False -",
"payments long True -",
]
+
+
+def test_a_derived_measure_is_a_nullable_decimal() -> None:
+ """FR-044 R13: a measure.derived is typed decimal, not required, with no type source,
+ whatever its operands. The same rows as the TypeScript derivation of this fixture."""
+ path = CORPUS.parent / "conformance" / "reporting-derived-measures" / "input" / "meta.studio.json"
+ root = _load(InMemoryStringSource(path.read_text(encoding="utf-8"), "meta.studio.json"))
+
+ def rows(name: str) -> list[str]:
+ return [
+ f"{f.name} {f.sub_type} {f.required} "
+ + ("-" if f.type_source is None else f"{f.type_source.parent.name}.{f.type_source.name}")
+ for f in report_shape(_object(root, name), root).fields
+ ]
+
+ assert rows("MemberUtilization") == [
+ "memberId long False Member.id",
+ "memberName string True Member.firstName",
+ "weeklyCapacityHours decimal True Member.weeklyCapacityHours",
+ "workedOnMonth date True -",
+ "totalHours decimal True -",
+ "billableHours decimal True -",
+ "capacityHours decimal False -",
+ "utilization decimal False -",
+ "nonBillableHours decimal False -",
+ "billableSharePct decimal False -",
+ ]
+ assert rows("ProjectBurn") == [
+ "projectId long False Project.id",
+ "projectBudget decimal False Project.budget",
+ "cost decimal False -",
+ "budgetBurn decimal False -",
+ ]
diff --git a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
index bbcdaa2801..3273777ead 100644
--- a/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
+++ b/server/typescript/packages/codegen-ts/src/cube/cube-members.ts
@@ -52,6 +52,16 @@ import {
ERR_CUBE_UNMAPPABLE_DIMENSION,
ERR_CUBE_VALUE_OBJECT_MEMBER,
} from "./cube-errors.js";
+import type {
+ CubeDialect,
+ CubeDimensionSpec,
+ CubeDimensionType,
+ CubeMeasureSpec,
+ CubeMeasureType,
+ CubeSegmentSpec,
+} from "./cube-model-spec.js";
+import { CUBE_SELF, cubeColumn, cubeSqlRenderer, memberRef } from "./cube-sql.js";
+import type { ReportDialect } from "../projection/time-sql.js";
/**
* FR-044 R12: a report reads a member of a flattened value object only beside a grouping by the
@@ -66,16 +76,6 @@ export function valueObjectMemberError(where: string, of: string): CubeModelErro
`report with a view source, or remove the member from the exported entity.`,
);
}
-import type {
- CubeDialect,
- CubeDimensionSpec,
- CubeDimensionType,
- CubeMeasureSpec,
- CubeMeasureType,
- CubeSegmentSpec,
-} from "./cube-model-spec.js";
-import { CUBE_SELF, cubeColumn, cubeSqlRenderer, memberRef } from "./cube-sql.js";
-import type { ReportDialect } from "../projection/time-sql.js";
/** What every member mapping reads: the model, the dialect, the column naming strategy. */
export interface MemberContext {
diff --git a/server/typescript/packages/codegen-ts/test/projection/extract-report-spec.test.ts b/server/typescript/packages/codegen-ts/test/projection/extract-report-spec.test.ts
index de399d6593..97bc18bc31 100644
--- a/server/typescript/packages/codegen-ts/test/projection/extract-report-spec.test.ts
+++ b/server/typescript/packages/codegen-ts/test/projection/extract-report-spec.test.ts
@@ -16,7 +16,7 @@ import {
} from "@metaobjectsdev/metadata";
import { extractReportSpec, temporalOf } from "../../src/projection/extract-report-spec.js";
import { isRelativeNow } from "../../src/projection/report-spec.js";
-import type { ReportViewSpec } from "../../src/projection/report-spec.js";
+import type { ReportDerivedTerm, ReportViewSpec } from "../../src/projection/report-spec.js";
type Json = Record;
@@ -691,10 +691,32 @@ function joinTypes(nodes: Joins): string[] {
return nodes.flatMap((n) => [n.joinType, ...joinTypes(n.children)]);
}
+/** Every column reference a derived measure's term reads. */
+function derivedRefs(t: ReportDerivedTerm): unknown[] {
+ switch (t.kind) {
+ case "aggregate":
+ return [t.aggregate.refs];
+ case "ratio":
+ return [t.numerator.refs, t.denominator.refs];
+ case "ref":
+ return [t.ref];
+ case "value":
+ return [];
+ case "op":
+ return [...derivedRefs(t.left), ...derivedRefs(t.right)];
+ }
+}
+
/** Every alias the spec names: the base, each join with its hop, and every column reference. */
function aliasesOf(s: ReportViewSpec): unknown[] {
const refs = s.columns.map((c) =>
- c.kind === "aggregate" ? c.aggregate.refs : c.kind === "ratio" ? [c.numerator.refs, c.denominator.refs] : c.ref,
+ c.kind === "aggregate"
+ ? c.aggregate.refs
+ : c.kind === "ratio"
+ ? [c.numerator.refs, c.denominator.refs]
+ : c.kind === "derived"
+ ? derivedRefs(c.term)
+ : c.ref,
);
return [s.joinTree.baseAlias, joinsOfTree(s.joinTree.joins), refs];
}
diff --git a/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts b/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
index 59a67d7f98..fb31c1afe1 100644
--- a/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
+++ b/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
@@ -82,7 +82,7 @@ describe("FR-044 R13: derived measures in a report view", () => {
});
test("Cube: a derived measure over measures is a number member reading them", async () => {
- const model = buildCubeModel(await load(true), { dialect: "postgres" });
+ const model = buildCubeModel(await load(true), { dialect: "postgres", columnNamingStrategy: "snake_case" });
const cube = model.cubes.find((c) => c.name.toLowerCase().includes("timeentr"))!;
const derived = cube.measures.find((m) => m.name === "nonBillableHours")!;
expect(derived.type).toBe("number");
@@ -93,6 +93,6 @@ describe("FR-044 R13: derived measures in a report view", () => {
test("Cube: a derived measure that reads a dimension is refused", async () => {
const root = await load();
- expect(() => buildCubeModel(root, { dialect: "postgres" })).toThrow(/ERR_CUBE_DERIVED_DIMENSION/);
+ expect(() => buildCubeModel(root, { dialect: "postgres", columnNamingStrategy: "snake_case" })).toThrow(/ERR_CUBE_DERIVED_DIMENSION/);
});
});
diff --git a/server/typescript/packages/codegen-ts/test/projection/report-value-object-members.test.ts b/server/typescript/packages/codegen-ts/test/projection/report-value-object-members.test.ts
index 131b012cb9..b0c864db69 100644
--- a/server/typescript/packages/codegen-ts/test/projection/report-value-object-members.test.ts
+++ b/server/typescript/packages/codegen-ts/test/projection/report-value-object-members.test.ts
@@ -43,6 +43,6 @@ describe("FR-044 R12: value-object members in a report view", () => {
test("the Cube exporter refuses a member rather than let a query add amounts across currencies", async () => {
const root = await load();
- expect(() => buildCubeModel(root, { dialect: "postgres" })).toThrow(/ERR_CUBE_VALUE_OBJECT_MEMBER/);
+ expect(() => buildCubeModel(root, { dialect: "postgres", columnNamingStrategy: "snake_case" })).toThrow(/ERR_CUBE_VALUE_OBJECT_MEMBER/);
});
});
diff --git a/server/typescript/packages/metadata/test/report-describe.test.ts b/server/typescript/packages/metadata/test/report-describe.test.ts
index 6244e59a2f..e259e2c2d9 100644
--- a/server/typescript/packages/metadata/test/report-describe.test.ts
+++ b/server/typescript/packages/metadata/test/report-describe.test.ts
@@ -248,3 +248,28 @@ describe("the attrs a describer reads", () => {
}
});
});
+
+describe("describing a measure.derived (FR-044 R13)", () => {
+ test("the arithmetic in words, parenthesised below the top, and null on a zero divisor", async () => {
+ const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify({
+ "metadata.root": { package: "acme::time", children: [
+ { "object.entity": { name: "Entry", children: [
+ { "source.rdb": { "@table": "entries" } },
+ { "field.long": { name: "id" } },
+ { "field.decimal": { name: "hours" } },
+ { "identity.primary": { name: "id", "@fields": ["id"] } },
+ { "measure.aggregate": { name: "total", "@agg": "sum", "@of": "Entry.hours" } },
+ { "measure.aggregate": { name: "entries", "@agg": "count", "@of": "Entry.id" } },
+ { "measure.derived": { name: "perEntry", "@expr": { fn: "divide", args: [{ field: "total" }, { fn: "add", args: [{ field: "entries" }, { value: 1 }] }] } } },
+ { "measure.derived": { name: "doubled", "@expr": { fn: "multiply", args: [{ field: "total" }, { value: 2 }] } } },
+ ] } },
+ ] },
+ }))]);
+ expect(errors).toEqual([]);
+ const entity = root.objects().find((o) => o.name === "Entry")!;
+ const m = (name: string) => entity.children().find((c) => c.type === "measure" && c.name === name)!;
+ expect(describeMeasure(m("perEntry"))).toBe("`total` ÷ (`entries` + `1`), null when a divisor is 0");
+ expect(describeMeasure(m("doubled"))).toBe("`total` × `2`");
+ expect(reportingDescribedAttrs(m("doubled"))).toEqual(["expr"]);
+ });
+});
diff --git a/server/typescript/packages/metadata/test/report-shape.test.ts b/server/typescript/packages/metadata/test/report-shape.test.ts
index c46c2e772b..52ac3b5d3b 100644
--- a/server/typescript/packages/metadata/test/report-shape.test.ts
+++ b/server/typescript/packages/metadata/test/report-shape.test.ts
@@ -719,3 +719,25 @@ describe("reportShape: @agg any / all without @of (R6)", () => {
]);
});
});
+
+describe("reportShape: measure.derived (FR-044 R13)", () => {
+ test("a derived measure is a nullable decimal with no type source, whatever its operands", async () => {
+ const fixture = join(REPO_ROOT, "fixtures", "conformance", "reporting-derived-measures", "input", "meta.studio.json");
+ const result = await loadUris([pathToFileURL(fixture).href]);
+ expect(result.errors).toEqual([]);
+ const rows = (name: string) =>
+ reportShape(report(result.root, name), result.root).fields.map(
+ (f) => `${f.name} ${f.subType} ${f.required} ${f.typeSource ? `${f.typeSource.parent!.name}.${f.typeSource.name}` : "-"}`,
+ );
+ expect(rows("MemberUtilization")).toEqual([
+ "memberId long false Member.id", "memberName string true Member.firstName",
+ "weeklyCapacityHours decimal true Member.weeklyCapacityHours", "workedOnMonth date true -",
+ "totalHours decimal true -", "billableHours decimal true -", "capacityHours decimal false -",
+ "utilization decimal false -", "nonBillableHours decimal false -", "billableSharePct decimal false -",
+ ]);
+ expect(rows("ProjectBurn")).toEqual([
+ "projectId long false Project.id", "projectBudget decimal false Project.budget", "cost decimal false -",
+ "budgetBurn decimal false -",
+ ]);
+ });
+});
diff --git a/site-reference/index.html b/site-reference/index.html
index 9ef6fbf714..79a602afa7 100644
--- a/site-reference/index.html
+++ b/site-reference/index.html
@@ -256,6 +256,11 @@
types/measure.md#measureaggregate
+measure.derived
+A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.
+types/measure.md#measurederived
+
+
measure.ratio
A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null.
types/measure.md#measureratio
diff --git a/site-reference/types/dimension.html b/site-reference/types/dimension.html
index 3bb94fc6f8..e033e0e119 100644
--- a/site-reference/types/dimension.html
+++ b/site-reference/types/dimension.html
@@ -73,7 +73,7 @@ dimension.attribute
—
-Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via).
+Dotted Entity.field reference naming the grouped column (e.g. 'Purchase.programId', or 'Program.title' with @via). Entity.field.member names a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.currency'), which has a column of its own.
@via
@@ -119,7 +119,7 @@ dimension.time
—
-Dotted Entity.field reference naming the date or timestamp column.
+Dotted Entity.field reference naming the date or timestamp column, or Entity.field.member for a member of a flattened value object.
@via
diff --git a/site-reference/types/measure.html b/site-reference/types/measure.html
index 70e4064c48..08479ad7ad 100644
--- a/site-reference/types/measure.html
+++ b/site-reference/types/measure.html
@@ -109,7 +109,7 @@ measure.aggregate
—
-Dotted Entity.field reference(s) on the declaring entity. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows.
+Dotted Entity.field reference(s) on the declaring entity, or Entity.field.member for a member of a value object stored with @storage: flattened (e.g. 'Payment.amount.amount'). A report that takes sum, avg, min or max of a numeric member must group by every non-numeric member of the same value object (its currency), so amounts in different units are never combined. A bare string is one column; more than one requires @agg: count and @distinct: true. Required for every @agg except any/all, which may omit it to quantify their @filter / @segment over the rows.
@segment
@@ -123,6 +123,34 @@ measure.aggregate
Allowed children
No structural children.
+measure.derived
+A named arithmetic expression (FR-044 R13) over measures of the same entity and the report's numeric attribute dimensions, typed decimal. @expr is FR-037 R5's first arithmetic wave: add, subtract, multiply and divide, each of two operands. divide lowers as a ratio does, so a zero divisor yields null. A report listing a derived measure that reads a dimension must list that dimension.
+When to use: A number computed from other measures or from a grouped value: utilization percent (billable hours x 100 / capacity), budget burn (cost / budget), net revenue (revenue - refunds).
+Attributes
+
+
+
+Attribute
+Type
+Required
+Default
+Allowed values
+Provider
+Description
+
+
+
+@expr
+expression
+yes
+
+
+—
+The arithmetic: { field: name } names a numeric measure.aggregate or measure.ratio of the same entity, or one of its numeric attribute dimensions (never another measure.derived); { value: n } is a number; { fn: add | subtract | multiply | divide, args: [a, b] } combines two operands.
+
+
+Allowed children
+No structural children.
measure.ratio
A named quotient of two numeric measure.aggregate siblings (FR-044), lowered as numerator / NULLIF(denominator, 0) and typed decimal. A zero denominator yields null.
When to use: Averages per unit that are not a plain avg: average days engaged per starter.
From 36f7f2f10b5707e6628c920dd3dfbf60986bd884 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Thu, 12 Nov 2026 18:40:45 -0500
Subject: [PATCH 4/6] no-mistakes(review): apply reviewer inline fixes
---
.../metadata/src/core/reporting/report-describe.ts | 11 ++++++-----
1 file changed, 6 insertions(+), 5 deletions(-)
diff --git a/server/typescript/packages/metadata/src/core/reporting/report-describe.ts b/server/typescript/packages/metadata/src/core/reporting/report-describe.ts
index 0758c096bd..7c95cb3549 100644
--- a/server/typescript/packages/metadata/src/core/reporting/report-describe.ts
+++ b/server/typescript/packages/metadata/src/core/reporting/report-describe.ts
@@ -109,11 +109,6 @@ function defaultClause(measure: MetaData): string {
return typeof declared === "number" ? `; ${tick(String(declared))} when there is nothing to aggregate` : "";
}
-/**
- * A measure in words: the aggregate and its row scope, or the ratio and its null rule. A
- * `@default` ends either with the value it reads when there is nothing to aggregate; a
- * defaulted ratio is never null, so its null rule gives way to that clause.
- */
/** R13: an arithmetic expression in words, fully parenthesised below the top so the reading is exact. */
function describeExpr(node: DerivedExprNode, top = true): string {
if ("field" in node) return tick(node.field);
@@ -124,6 +119,12 @@ function describeExpr(node: DerivedExprNode, top = true): string {
return top ? text : `(${text})`;
}
+/**
+ * A measure in words: the aggregate and its row scope, the ratio and its null rule, or (R13) the
+ * derived measure's arithmetic. A `@default` ends an aggregate or ratio with the value it reads
+ * when there is nothing to aggregate; a defaulted ratio is never null, so its null rule gives way
+ * to that clause.
+ */
export function describeMeasure(measure: MetaData): string {
if (measure.subType === MEASURE_SUBTYPE_DERIVED) {
const expr = measure.attr(REPORTING_ATTR_EXPR);
From c7c74d4e7e815560c72376047ba52f8022ccca84 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Thu, 12 Nov 2026 18:43:19 -0500
Subject: [PATCH 5/6] no-mistakes(review): Fix MySQL derived divide
parentheses; reword CHANGELOG
---
CHANGELOG.md | 2 +-
.../src/projection/report-ddl-emit.ts | 3 +-
.../report-derived-measures.test.ts | 35 +++++++++++++++++++
3 files changed, 37 insertions(+), 3 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c8249dd704..3aa9f96685 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,7 +11,7 @@ here.**
## [Unreleased]
**New metamodel vocabulary: `measure.derived` and its `@expr`.** It is additive: nothing that
-loaded before stops loading. If this ships after 1.3.0, the release moves `metamodelVersion`.
+loaded before stops loading. This vocabulary ships in 1.3.0 with `metamodelVersion` 1.3 if it merges before the 1.3.0 publish; if it lands after, the next release moves `metamodelVersion`.
### Added
diff --git a/server/typescript/packages/codegen-ts/src/projection/report-ddl-emit.ts b/server/typescript/packages/codegen-ts/src/projection/report-ddl-emit.ts
index 003e3cea9c..e3ae61ccd7 100644
--- a/server/typescript/packages/codegen-ts/src/projection/report-ddl-emit.ts
+++ b/server/typescript/packages/codegen-ts/src/projection/report-ddl-emit.ts
@@ -134,8 +134,7 @@ function derived(t: ReportDerivedTerm, d: ReportDialect, factRef: string | undef
let sql: string;
if (t.fn === DERIVED_FN_DIVIDE) {
// Inside CAST(...) the dividend needs no parentheses of its own; MySQL has no cast.
- const real = realOf(derived(t.left, d, factRef), d);
- const dividend = real.startsWith("CAST(") ? real : derived(t.left, d, factRef, false);
+ const dividend = d === "mysql" ? derived(t.left, d, factRef, false) : realOf(derived(t.left, d, factRef), d);
const divisor =
t.right.kind === "value" && t.right.value !== 0
? derived(t.right, d, factRef, false)
diff --git a/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts b/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
index fb31c1afe1..72abc2f533 100644
--- a/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
+++ b/server/typescript/packages/codegen-ts/test/projection/report-derived-measures.test.ts
@@ -81,6 +81,41 @@ describe("FR-044 R13: derived measures in a report view", () => {
expect(sql).toContain("(m.`weekly_capacity_hours` * 52) / 12 AS `capacity_hours`");
});
+ test("mysql keeps the parentheses around a dividend that is a difference of integral sums", async () => {
+ const doc = JSON.parse(readFileSync(FIXTURE, "utf8")) as Json;
+ const children = (doc["metadata.root"] as { children: Json[] }).children;
+ const entity = children.find((c) => (c["object.entity"] as Json | undefined)?.name === "TimeEntry")!;
+ const ec = (entity["object.entity"] as { children: Json[] }).children;
+ const hours = ec.findIndex((c) => (c["field.decimal"] as Json | undefined)?.name === "hours");
+ ec[hours] = { "field.long": { name: "hours", "@required": true } };
+ ec.push(
+ { "measure.aggregate": { name: "allHours", "@agg": "sum", "@of": "TimeEntry.hours" } },
+ { "measure.aggregate": { name: "billedHours", "@agg": "sum", "@of": "TimeEntry.hours", "@filter": { billable: true } } },
+ );
+ ec.push({
+ "measure.derived": {
+ name: "hoursGapPerBudget",
+ "@expr": {
+ fn: "divide",
+ args: [{ fn: "subtract", args: [{ field: "allHours" }, { field: "billedHours" }] }, { field: "projectBudget" }],
+ },
+ },
+ });
+ children.push({
+ "object.report": {
+ name: "HoursGap",
+ "@from": "TimeEntry",
+ "@dimensions": ["projectId", "projectBudget"],
+ "@measures": ["allHours", "billedHours", "hoursGapPerBudget"],
+ children: [{ "source.rdb": { "@kind": "view", "@view": "v_hoursgap" } }],
+ },
+ });
+ const { root, errors } = await new MetaDataLoader().load([new InMemoryStringSource(JSON.stringify(doc))]);
+ expect(errors).toEqual([]);
+ const sql = buildReportViews(root, { dialect: "mysql" }).find((v) => v.name === "v_hoursgap")?.sql ?? "";
+ expect(sql).toMatch(/\(CAST\(.* AS SIGNED\) - CAST\(.* AS SIGNED\)\) \/ NULLIF\(p\.`budget`, 0\) AS `hours_gap_per_budget`/);
+ });
+
test("Cube: a derived measure over measures is a number member reading them", async () => {
const model = buildCubeModel(await load(true), { dialect: "postgres", columnNamingStrategy: "snake_case" });
const cube = model.cubes.find((c) => c.name.toLowerCase().includes("timeentr"))!;
From 56653ca0657532c8ac6037b56166a021af847c27 Mon Sep 17 00:00:00 2001
From: Doug Mealing
Date: Thu, 12 Nov 2026 19:26:45 -0500
Subject: [PATCH 6/6] no-mistakes(document): Cube docs: derived measure,
value-object refusal
---
docs/features/cube-export.md | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/docs/features/cube-export.md b/docs/features/cube-export.md
index 8c4d9cbfd6..21847a4aea 100644
--- a/docs/features/cube-export.md
+++ b/docs/features/cube-export.md
@@ -327,6 +327,7 @@ somewhere to go: an `identity.reference` onto an entity that is not a cube makes
| `measure.ratio` | `type: number`. Postgres: `CAST({num} AS NUMERIC) / NULLIF({den}, 0)`. MySQL: `{num} / NULLIF({den}, 0)`. |
| a `measure.aggregate` with `@default: n` | two members. `Raw` is the aggregate as the rows above write it (its `type`, `sql` and `filters`), with `public: false`. `` is `type: number` (`type: boolean` for an `any` or `all`, where `n` is written `TRUE` / `FALSE` on Postgres and `1` / `0` on MySQL), `sql: 'COALESCE({Raw}, n)'`, and carries the measure's `title` and `description`. |
| a `measure.ratio` with `@default: n` | `type: number`, the quotient above inside `COALESCE(…, n)` |
+| `measure.derived` | `type: number`, `sql` the `@expr` over the operand measures' members (each operand is its full Cube expression, as in a ratio). `divide` is `CAST(x AS NUMERIC) / NULLIF(y, 0)` on Postgres and `x / NULLIF(y, 0)` on MySQL. A `@expr` that reads a dimension (not a measure) is `ERR_CUBE_DERIVED_DIMENSION`. |
In a ratio, `{num}` and `{den}` are references to the two operand measures, so each operand is
its full Cube expression, condition included, and an operand need not be listed in any report.
@@ -491,6 +492,8 @@ are printed in its messages and are not loader codes.
| `ERR_CUBE_NAME_COLLISION` | two cubes, or a cube and a view, would have one name |
| `ERR_CUBE_UNESCAPABLE_LITERAL` | a literal, an identifier or free text that is raw-wrapped (it holds a Jinja opener) holds `endraw` |
| `ERR_CUBE_UNSUPPORTED_DIALECT` | the dialect is neither `postgres` nor `mysql` and the run would write a cube |
+| `ERR_CUBE_VALUE_OBJECT_MEMBER` | an `@of` names a value-object member (`Entity.field.member`); the exporter does not map it |
+| `ERR_CUBE_DERIVED_DIMENSION` | a `measure.derived` `@expr` reads a dimension rather than a measure |
## Which files a run writes
@@ -676,7 +679,8 @@ jobs API) before a query can use them.
- **No `sqlite` or `d1`.** See [Dialects](#wiring-it).
- **No `extends`, no `refresh_key`, no partitions, no `format`.** The exporter writes cubes, and
a Cube view only for a served `@spine` report.
-- **No derived measure.** `measure.derived` is not registered, so there is nothing to map.
+- **No member of a value object.** An `@of` naming `Entity.field.member` is `ERR_CUBE_VALUE_OBJECT_MEMBER`
+ (see [What the exporter refuses](#what-the-exporter-refuses)). Read it through a report view instead.
## Compatibility