From 5997249fb0b0baeb07b83ab964cc25c018451b58 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Sat, 7 Nov 2026 18:14:57 +0000 Subject: [PATCH 1/6] =?UTF-8?q?feat(analytic-registry):=20mirror=20the=20l?= =?UTF-8?q?ibrary's=20=C2=A75=20field=20vocabulary=20in=20the=20declaratio?= =?UTF-8?q?n=20model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RS-W2-1a step 1 (decision D2: trellis-analytics authors the vocabulary, pyegeria mirrors it). - MeasureDeclaration: completeness_field replaces capped_field (still read, with a DeprecationWarning, as the library did in 0.3); population (viewer | repository); a basis on a share is refused, as in the library. - FieldDeclaration / FieldCompanion (name, label, kind data|cell|representation|dataset, type, unit, companions, ...), AnalyticDeclaration.out, plus the categories and listing blocks the library requires for distribution/graph and list results. - ROW_SHAPES: the row shapes built-in declarations name from a dataset field. - asset_composition: categories (rows overlap), population and completeness on its measures, and an out field list. - test_declarations_match_library.py: every built-in declaration loads as a library Declaration, its out as a library Shape; skipped when trellis_analytics is absent. Passes against egeria-trellis-analytics 0.3.1. Signed-off-by: Dan Wolfson --- pyegeria/view/analytic_registry.py | 268 +++++++++++++++++- .../test_declarations_match_library.py | 71 +++++ .../test_rs_w2_1a_routine_declarations.py | 74 +++++ 3 files changed, 407 insertions(+), 6 deletions(-) create mode 100644 tests/micro-tests/test_declarations_match_library.py create mode 100644 tests/micro-tests/test_rs_w2_1a_routine_declarations.py diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 3d0c2c0e..8ea733a8 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -38,6 +38,8 @@ from __future__ import annotations import os +import re +import warnings from importlib.metadata import entry_points from pathlib import Path from typing import Any, Dict, List, Literal, Optional, Tuple, Union @@ -53,7 +55,17 @@ 'MeasureDeclaration', 'BasisDeclaration', 'AbsenceSentences', + 'FieldDeclaration', + 'FieldCompanion', + 'CategoriesDeclaration', + 'ListDeclaration', + 'ROW_SHAPES', 'RESULT_KINDS', + 'POPULATIONS', + 'COMPLETENESS', + 'FIELD_KINDS', + 'FIELD_TYPES', + 'CELL_COMPANIONS', 'ABSENCE_STATES', 'canonical_absence_state', 'KNOWN_ANALYTIC_SOURCES', @@ -156,14 +168,66 @@ def _filled(self) -> "BasisDeclaration": return self +#: The two populations a count can be taken over (trellis `POPULATIONS`, RS-W1-1 §5). `viewer`: what +#: the caller may see (Egeria pushDown=false, or any find); `repository`: the whole repository, fast, +#: with no per-element visibility check (pushDown=true). +POPULATIONS = ("viewer", "repository") + +#: §5 completeness (trellis `COMPLETENESS`), replacing the boolean `capped_field`. A boolean result +#: field still reads: true is `lower_bound`, false is `complete`. +COMPLETENESS = ("complete", "lower_bound", "unknown") + + +def _is_fraction(unit: str) -> bool: + """Does this unit say a share rather than a count (trellis `is_fraction`)? Its whole is in its words.""" + u = " ".join(str(unit or "").lower().split()) + return u.startswith(("fraction", "ratio", "percent", "share", "proportion")) or "(0-1)" in u or "%" in u + + class MeasureDeclaration(BaseModel): - """One number a function reports. A number never travels without its unit and its as-of.""" + """One number a function reports. A number never travels without its unit and its as-of. + + `as_of` names the result field saying when the value is of; `run.as_of` names the call's own + `as_of` argument (None = when it ran), for a routine whose result carries no time of its own. + `completeness_field` names the result field that says the value may be incomplete (one of + COMPLETENESS, or a boolean: true = only a lower bound). `capped_field` is its old name, read + with a DeprecationWarning. `population` is set when the value is always counted in one + population; empty when the caller chooses it or the server default applies.""" name: str unit: str # in words, plural where it counts things: "tables", "fraction of rows (0-1)" - as_of: str # the result field saying when this was measured, e.g. "asOf" + as_of: str # the result field saying when this was measured, e.g. "asOf"; or run.as_of value_field: str # the result field holding the value; dotted for nested, trailing [] counts a list basis: Optional[BasisDeclaration] = None - capped_field: str = "" # the result field that is true when the value is only a lower bound + completeness_field: str = "" + population: str = "" + + @model_validator(mode="before") + @classmethod + def _legacy_capped_field(cls, data: Any) -> Any: + if isinstance(data, dict) and "capped_field" in data: + data = dict(data) + capped = data.pop("capped_field") + if _words(data.get("completeness_field")) and _words(capped) != _words(data["completeness_field"]): + raise ValueError(f"measure '{data.get('name', '')}' declares capped_field and completeness_field: " + "capped_field is the old word for completeness_field, so declare that only") + data["completeness_field"] = capped + warnings.warn(f"measure '{data.get('name', '')}': capped_field is deprecated; use completeness_field", + DeprecationWarning, stacklevel=2) + return data + + @property + def capped_field(self) -> str: + """The old name for `completeness_field`. Read-only; warns.""" + warnings.warn("MeasureDeclaration.capped_field is deprecated; use completeness_field", + DeprecationWarning, stacklevel=2) + return self.completeness_field + + @field_validator("population") + @classmethod + def _population(cls, value: str) -> str: + if value and value not in POPULATIONS: + raise ValueError(f"population '{value}' is not one of {', '.join(POPULATIONS)}") + return value @model_validator(mode="after") def _filled(self) -> "MeasureDeclaration": @@ -171,6 +235,110 @@ def _filled(self) -> "MeasureDeclaration": if empty: raise ValueError(f"measure '{self.name}' declares no {', '.join(empty)}: " "a number never travels without its unit and its as-of") + if self.basis is not None and _is_fraction(self.unit): + raise ValueError(f"measure '{self.name}' declares a basis on a share ('{self.unit}'): " + "its whole is in its unit, so a basis belongs on a count only") + return self + + +# ── Result fields (§5 of the report-spec pipeline model), mirrored from trellis-analytics ── +# The library (egeria-trellis-analytics) authors this vocabulary; pyegeria keeps the same names and +# meanings without importing it. tests/micro-tests/test_declarations_match_library.py checks every +# built-in declaration loads in the library when it is installed. + +#: What a field is: plain data; a value cell with companions; a pre-built representation; nested +#: rows of a registered shape. +FIELD_KINDS = ("data", "cell", "representation", "dataset") + +#: The plain field types; `list` and `map` take one of them as T. +FIELD_TYPES = ("string", "int", "float", "fraction", "bool", "datetime", "guid") + +#: The companions a value cell may carry. +CELL_COMPANIONS = ("state", "completeness", "uncertainty", "unit", "as_of", "basis", "provenance", "score", + "population") + +_FIELD_NAME = r"[A-Za-z_][A-Za-z0-9_]*" +_SCALAR = "|".join(FIELD_TYPES) +_FIELD_TYPE = re.compile(rf"(?:{_SCALAR})|list<(?:{_SCALAR})>|map<\s*string\s*,\s*(?:{_SCALAR})\s*>|" + rf"representation/[A-Za-z0-9_.+-]+") + + +class FieldCompanion(BaseModel): + """A companion a cell carries, optionally narrowed to a named state set or a list of values.""" + name: str + valid_values: Optional[Union[str, List[str]]] = None + + +class FieldDeclaration(BaseModel): + """One field of a result (trellis `Field`). `name` is the result key (an identifier; a dot is a + path, never part of a name), `label` the column name a person reads. A `cell` is a value with + companions; a `dataset` is nested rows of the registered shape it names (ROW_SHAPES).""" + name: str + label: str = "" + kind: Literal["data", "cell", "representation", "dataset"] = "data" + type: str = "" + unit: str = "" + detail_spec: str = "" + valid_values: Optional[Union[str, List[str]]] = None + shape: str = "" + companions: Optional[List[Union[str, FieldCompanion]]] = None + format: str = "" + measure: str = "" + + @model_validator(mode="after") + def _shape(self) -> "FieldDeclaration": + label = f"field '{self.name}'" + if not re.fullmatch(_FIELD_NAME, self.name or ""): + raise ValueError(f"{label} is not an identifier: a dot is a path, never part of a name") + if not _words(self.label) and self.kind != "representation": + raise ValueError(f"{label} declares no label: say the column name a person reads") + if self.kind == "dataset": + if not _words(self.shape) or _words(self.type): + raise ValueError(f"{label} is a dataset: it names a shape and no type") + else: + if _words(self.shape): + raise ValueError(f"{label} names a shape and is a '{self.kind}' field: a shape belongs to a dataset") + if not _FIELD_TYPE.fullmatch(self.type or ""): + raise ValueError(f"{label} type '{self.type}' is not a field type ({', '.join(FIELD_TYPES)}, " + "list, map, representation/)") + if self.type.startswith("representation/") != (self.kind == "representation"): + raise ValueError(f"{label}: a representation field, and only one, has type representation/") + if self.companions is not None: + if self.kind != "cell": + raise ValueError(f"{label} declares companions and is a '{self.kind}' field: companions belong to a cell") + names = [c if isinstance(c, str) else c.name for c in self.companions] + unknown = [n for n in names if n not in CELL_COMPANIONS] + if unknown or len(set(names)) != len(names): + raise ValueError(f"{label} companions {names} must be distinct cell companions " + f"({', '.join(CELL_COMPANIONS)})") + return self + + +class CategoriesDeclaration(BaseModel): + """How a distribution's or graph's categories relate (trellis `CategoriesDeclaration`): exclusive + when one item falls in exactly one category; `sums_to` names the field holding the stated total.""" + exclusive: bool + sums_to: str = "" + + @model_validator(mode="after") + def _sums(self) -> "CategoriesDeclaration": + if _words(self.sums_to) and not self.exclusive: + raise ValueError("categories that overlap cannot sum to a total: leave sums_to out or declare exclusive") + return self + + +class ListDeclaration(BaseModel): + """A list result's items (trellis `ListDeclaration`): the fields a row shows, the order in words, + and the field that makes an item one item.""" + item_fields: List[str] + order: str + key_field: str + item_label: str = "" + + @model_validator(mode="after") + def _filled(self) -> "ListDeclaration": + if not [f for f in self.item_fields if _words(f)] or not _words(self.order) or not _words(self.key_field): + raise ValueError("a list declares its item_fields, its order in words and its key_field") return self @@ -205,10 +373,17 @@ def sentence(self, state: str) -> str: class AnalyticDeclaration(BaseModel): """What an analytic function declares about its results: the minimum is `result_kind`, - `measures` (required for measure/series/distribution/graph) and `absence`.""" + `measures` (required for measure/series/distribution/graph) and `absence`. + + `out` lists the result's fields (for a list or series, the fields of one row). `categories` + belongs to a distribution or graph and `listing` to a list, as in trellis-analytics; this model + accepts a declaration without them, and the built-ins all carry them.""" result_kind: str measures: List[MeasureDeclaration] = Field(default_factory=list) absence: AbsenceSentences + categories: Optional[CategoriesDeclaration] = None + listing: Optional[ListDeclaration] = None + out: List[FieldDeclaration] = Field(default_factory=list) @field_validator("result_kind") @classmethod @@ -295,6 +470,73 @@ def _strict() -> AnalyticParam: "(query failed, or the fallback hit the page-size cap). ISSUE-123.") +def _population() -> AnalyticParam: + return AnalyticParam(name="population", type="str", + description="viewer (what the caller may see) or repository (whole repository, " + "fast; native count only). Omit for the server default.") + + +# ── Declaration literals (RS-W2-1a). Short builders so each entry below reads as its declaration. ── +# `as_of="run.as_of"` names the call's own as_of argument (None = when it ran): these routines' +# results carry no time of their own. + +RUN_AS_OF = "run.as_of" + + +def _measure(name: str, unit: str, value_field: str, as_of: str = RUN_AS_OF, **kw: Any) -> MeasureDeclaration: + return MeasureDeclaration(name=name, unit=unit, as_of=as_of, value_field=value_field, **kw) + + +def _basis(denominator_field: str, denominator_label: str) -> BasisDeclaration: + return BasisDeclaration(denominator_field=denominator_field, denominator_label=denominator_label) + + +def _field(name: str, label: str, type: str = "", kind: str = "data", **kw: Any) -> FieldDeclaration: + return FieldDeclaration(name=name, label=label, type=type, kind=kind, **kw) + + +def _absence(not_measured: str, not_permitted: str, not_applicable: str, nothing_found: str) -> AbsenceSentences: + return AbsenceSentences(not_measured=not_measured, not_permitted=not_permitted, + not_applicable=not_applicable, nothing_found=nothing_found) + + +def _always_applies(what: str) -> str: + """The not_applicable sentence for a routine with no input that could make it not apply.""" + return (f"{what} applies to every catalog, so this routine never reports it as not applicable; " + "seeing this means the result was labelled wrongly.") + + +#: Row shapes the built-in declarations name from a `dataset` field (trellis registered shapes). +ROW_SHAPES: Dict[str, List[FieldDeclaration]] = { + "TypeCount": [ + _field("label", "Label", "string"), + _field("type", "Type", "string"), + _field("count", "Count", "int", unit="elements"), + ], + "ZoneCount": [ + _field("zone", "Zone", "string"), + _field("count", "Elements", "int", unit="elements"), + ], + "ExpiringCertification": [ + _field("name", "Certification", "string"), + _field("days", "Days left", "int", unit="days"), + ], + "CompositionRow": [ + _field("type_name", "Type", "string"), + _field("parent", "Parent", "string"), + _field("level", "Level", "int"), + _field("exact_type", "Exactly the parent type", "bool"), + _field("subtypes_error", "Subtypes not read", "string"), + _field("viewer", "Viewer count", "int", kind="cell", unit="elements", + companions=["state", "completeness", "as_of", "population"], measure="viewer_count"), + _field("repository", "Repository count", "int", kind="cell", unit="elements", + companions=["state", "completeness", "as_of", "population"], measure="repository_count"), + _field("not_visible", "Not visible to you", "int", kind="cell", unit="elements", + companions=["state"], measure="not_visible"), + ], +} + + # ── Built-ins -- every analytic function already proven live via the Overview # dashboard's /api/overview/* endpoints (overview_handler.py), just not yet # reachable from a Dr.Egeria report spec. ────────────────────────────────── @@ -661,12 +903,16 @@ def _strict() -> AnalyticParam: result_kind="distribution", measures=[ MeasureDeclaration(name="repository_count", unit="elements", as_of="as_of", - value_field="rows.repository.value"), + value_field="rows.repository.value", + completeness_field="rows.repository.completeness", population="repository"), MeasureDeclaration(name="viewer_count", unit="elements", as_of="as_of", - value_field="rows.viewer.value"), + value_field="rows.viewer.value", + completeness_field="rows.viewer.completeness", population="viewer"), MeasureDeclaration(name="not_visible", unit="elements", as_of="as_of", value_field="rows.not_visible.value"), ], + # A parent row counts its subtypes too, so the rows overlap and never sum. + categories=CategoriesDeclaration(exclusive=False), absence=AbsenceSentences( not_measured="The subtype counts could not be measured: the count queries failed or " "the server could not answer them.", @@ -674,6 +920,16 @@ def _strict() -> AnalyticParam: not_applicable="A subtype composition does not apply to this type.", nothing_found="Counted: there are no elements of this type or its subtypes.", ), + out=[ + _field("state", "State", "string"), + _field("state_reason", "Why", "string"), + _field("root", "Root type", "string"), + _field("depth", "Depth", "int"), + _field("as_of", "As of", "datetime"), + _field("concurrency", "Counts in flight", "int"), + _field("rows", "Types", kind="dataset", shape="CompositionRow"), + _field("not_measured", "Not measured", "list"), + ], ), ), "control_implementation_summary": AnalyticFunctionSpec( diff --git a/tests/micro-tests/test_declarations_match_library.py b/tests/micro-tests/test_declarations_match_library.py new file mode 100644 index 00000000..f496aa97 --- /dev/null +++ b/tests/micro-tests/test_declarations_match_library.py @@ -0,0 +1,71 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +"""RS-W2-1a: pyegeria's declaration model mirrors trellis-analytics' (decision D2: the library +authors the vocabulary, pyegeria mirrors it). Every built-in declaration must load as a library +`Declaration`, its `out` fields as a library `Shape`, and every row shape it names as a library +shape. This is the only coupling: pyegeria never imports the library at run time, and this test is +skipped when the library is not installed. + +Run it against a release with, for example: + uv run -p 3.13 --with egeria-trellis-analytics==0.3.1 pytest tests/micro-tests/test_declarations_match_library.py +""" +import warnings + +import pytest + +library = pytest.importorskip("trellis_analytics.declaration") + +from pyegeria.view.analytic_registry import ROW_SHAPES, get_analytic_registry # noqa: E402 + +#: Keys pyegeria declares that a library release may not know yet, by where they sit. Each is +#: dropped before validation only when the installed library's model has no such field, so a newer +#: library that adds them checks them too. +PYEGERIA_AHEAD = {"measure": {"population"}, "declaration": {"out"}} + + +def _known(model, data: dict, where: str) -> dict: + ahead = {k for k in PYEGERIA_AHEAD[where] if k not in model.model_fields} + return {k: v for k, v in data.items() if k not in ahead} + + +def _for_library(decl) -> dict: + data = decl.model_dump(exclude_defaults=True) + data["absence"] = decl.absence.model_dump() + data["measures"] = [_known(library.MeasureDeclaration, m, "measure") for m in data.get("measures", [])] + return _known(library.Declaration, data, "declaration") + + +def _fields(fields) -> list: + return [f.model_dump(exclude_defaults=True) for f in fields] + + +DECLARED = sorted((name, spec.declaration) for name, spec in get_analytic_registry().items() + if spec.declaration is not None) + + +@pytest.fixture(scope="module", autouse=True) +def _row_shapes_registered(): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + for name, fields in ROW_SHAPES.items(): + library.register_shape(name, {"fields": _fields(fields)}) + + +@pytest.mark.parametrize("name, decl", DECLARED, ids=[n for n, _ in DECLARED]) +def test_declaration_loads_in_the_library(name, decl): + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) # no legacy word reaches the library + library.Declaration.model_validate(_for_library(decl)) + + +@pytest.mark.parametrize("name, decl", DECLARED, ids=[n for n, _ in DECLARED]) +def test_out_loads_as_a_library_shape(name, decl): + shape = library.Shape.model_validate({"fields": _fields(decl.out)}) + for f in shape.declared(): + if f.kind == "dataset": + assert f.shape in library.SHAPES, f"{name}.{f.name} names shape {f.shape}, not registered" + + +@pytest.mark.parametrize("shape", sorted(ROW_SHAPES)) +def test_row_shapes_load_in_the_library(shape): + library.Shape.model_validate({"fields": _fields(ROW_SHAPES[shape])}) diff --git a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py new file mode 100644 index 00000000..918136b4 --- /dev/null +++ b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py @@ -0,0 +1,74 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +"""RS-W2-1a: every registered routine declares its results -- measures with unit and as-of, the four +nothing_found-vocabulary absence sentences and an `out` field list -- and the model mirrors the +trellis-analytics §5 vocabulary (population, completeness, fields).""" +import warnings + +import pytest +from pydantic import ValidationError + +from pyegeria.view.analytic_registry import ( + AnalyticDeclaration, + FieldDeclaration, + MeasureDeclaration, +) + +ABSENCE = {"not_measured": "a", "not_permitted": "b", "not_applicable": "c", "nothing_found": "d"} + + +# ── model: completeness replaces capped_field; population; fields ── + +def test_capped_field_reads_as_completeness_field_with_a_warning(): + with pytest.warns(DeprecationWarning, match="completeness_field"): + m = MeasureDeclaration(name="n", unit="assets", as_of="run.as_of", value_field="v", capped_field="capped") + assert m.completeness_field == "capped" + assert "capped_field" not in m.model_dump() + with pytest.warns(DeprecationWarning): + assert m.capped_field == "capped" + + +def test_capped_field_and_a_different_completeness_field_are_refused(): + with pytest.raises(ValidationError, match="declare that only"): + MeasureDeclaration(name="n", unit="assets", as_of="a", value_field="v", + capped_field="x", completeness_field="y") + + +def test_completeness_field_alone_does_not_warn(): + with warnings.catch_warnings(): + warnings.simplefilter("error") + MeasureDeclaration(name="n", unit="assets", as_of="a", value_field="v", completeness_field="capped") + + +@pytest.mark.parametrize("population, ok", [("", True), ("viewer", True), ("repository", True), ("scope", False)]) +def test_population_is_viewer_or_repository(population, ok): + kw = dict(name="n", unit="assets", as_of="a", value_field="v", population=population) + if ok: + assert MeasureDeclaration(**kw).population == population + else: + with pytest.raises(ValidationError, match="population"): + MeasureDeclaration(**kw) + + +def test_a_basis_on_a_share_is_refused(): + with pytest.raises(ValidationError, match="basis on a share"): + MeasureDeclaration(name="n", unit="percent of assets", as_of="a", value_field="v", + basis={"denominator_field": "t", "denominator_label": "assets"}) + + +@pytest.mark.parametrize("field, words", [ + (dict(name="a.b", label="A", type="int"), "identifier"), + (dict(name="a", type="int"), "label"), + (dict(name="a", label="A", type="number"), "not a field type"), + (dict(name="a", label="A", kind="dataset"), "names a shape"), + (dict(name="a", label="A", type="int", companions=["state"]), "companions belong to a cell"), + (dict(name="a", label="A", type="int", kind="cell", companions=["colour"]), "cell companions"), +]) +def test_bad_fields_are_refused_with_a_sentence(field, words): + with pytest.raises(ValidationError, match=words): + FieldDeclaration(**field) + + +def test_out_defaults_empty_so_older_declarations_still_load(): + d = AnalyticDeclaration(result_kind="list", absence=ABSENCE) + assert d.out == [] and d.categories is None and d.listing is None From f999244d828a61ccd1cac350cd53c55877f5d4d7 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Sat, 7 Nov 2026 18:16:02 +0000 Subject: [PATCH 2/6] feat(analytic-registry): declare the count routines; register count_relationships RS-W2-1a, routines: count_elements, count_elements_by_property, count_relationships (newly registered, decision D6), counts_by_type, sum_type_counts. Each declares its measure (unit, as_of, value_field), the four nothing_found-vocabulary absence sentences and its out fields; the count routines also list their population= parameter (#538) and a cost class in the description, for W2-2's tile_safe. What the functions return, worth knowing: - count_elements / count_elements_by_property / counts_by_type return 0 when a count fails unless strict=True (ISSUE-123, by design, overview_metrics.py:383); sum_type_counts runs non-strict, so a failed type adds 0 to its total. Not changed here: strict= is the documented switch and the Portal relies on the default. Named in the PR. - count_relationships' default path is one get_relationships page (DEFAULT_CAP): a type with more relationships than a page reads the page size, with no completeness flag (overview_metrics.py:499). Named in the PR. - A bare-number result declares value_field "value", the key metric_trend already uses for a non-dict result. Signed-off-by: Dan Wolfson --- pyegeria/view/analytic_registry.py | 94 ++++++++++++++++++- .../test_issue_170_analytic_declaration.py | 3 +- 2 files changed, 95 insertions(+), 2 deletions(-) diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 8ea733a8..48a86842 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -544,7 +544,11 @@ def _always_applies(what: str) -> str: "count_elements": AnalyticFunctionSpec( name="count_elements", function="pyegeria.view.overview_metrics.count_elements", - description="Count active elements of a given type, optionally filtered by classification.", + description="Count active elements of a given type, optionally filtered by classification. " + "Cost: one native count, sub-second in the repository population (0.2-0.8 s " + "measured); a viewer-population count reads every element and can take minutes " + "for a large type (Process: 120 s); a server with no native count falls back to " + "a capped find.", returns="scalar (int)", generic=True, params=[ @@ -554,7 +558,22 @@ def _always_applies(what: str) -> str: _strict(), AnalyticParam(name="classifications", type="list[str]", description="Match ANY of these classification names."), + _population(), ], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[_measure("elements", "elements", "value")], + absence=_absence( + not_measured="The elements were not counted: the count query failed, or the server " + "could not answer it in the population asked for.", + not_permitted="You are not permitted to count these elements.", + not_applicable="This count does not apply: the type named is not an element type " + "the server knows.", + nothing_found="Counted: there are no active elements of this type with these " + "classifications.", + ), + out=[_field("value", "Elements", "int", unit="elements")], + ), ), "counts_by_type": AnalyticFunctionSpec( name="counts_by_type", @@ -568,7 +587,22 @@ def _always_applies(what: str) -> str: description="(label, type_name) pairs to count, e.g. [('Data Stores', 'DataStore'), ...]."), _as_of(), _strict(), + _population(), ], + declaration=AnalyticDeclaration( + result_kind="distribution", + measures=[_measure("count", "elements", "count")], + # The caller picks the types; a supertype and its subtype may both be listed. + categories=CategoriesDeclaration(exclusive=False), + absence=_absence( + not_measured="The types were not counted: the count queries failed, or the server " + "could not answer them in the population asked for.", + not_permitted="You are not permitted to count elements of these types.", + not_applicable="A breakdown by type does not apply: no types were given to count.", + nothing_found="Counted: there are no active elements of any of these types.", + ), + out=ROW_SHAPES["TypeCount"], + ), ), "governed_coverage": AnalyticFunctionSpec( name="governed_coverage", @@ -752,6 +786,20 @@ def _always_applies(what: str) -> str: description="(label, type_name) pairs to count and sum."), _as_of(), ], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[_measure("total", "elements", "total")], + absence=_absence( + not_measured="The total was not counted: the per-type count queries failed.", + not_permitted="You are not permitted to count elements of these types.", + not_applicable="A total does not apply: no types were given to count.", + nothing_found="Counted: there are no active elements of any of these types.", + ), + out=[ + _field("total", "Total", "int", unit="elements"), + _field("byType", "By type", kind="dataset", shape="TypeCount"), + ], + ), ), "count_elements_by_property": AnalyticFunctionSpec( name="count_elements_by_property", @@ -771,7 +819,51 @@ def _always_applies(what: str) -> str: description="Value to match the property against, e.g. ACTIVE."), _as_of(), _strict(), + _population(), ], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[_measure("elements", "elements", "value")], + absence=_absence( + not_measured="The elements were not counted: the count query failed, or the server " + "could not answer it in the population asked for.", + not_permitted="You are not permitted to count these elements.", + not_applicable="This count does not apply: the type or property named is not one " + "the server knows.", + nothing_found="Counted: no active element of this type has this property value.", + ), + out=[_field("value", "Elements", "int", unit="elements")], + ), + ), + "count_relationships": AnalyticFunctionSpec( + name="count_relationships", + function="pyegeria.view.overview_metrics.count_relationships", + description="Count active relationships of one type. By default one capped " + "get_relationships page (the path the rest of the portal uses); a native count " + "when a MetadataExpert is passed as `expert` (opt-in: the two paths can disagree " + "for some types, PY-18). Takes ce as its leading client. Cost: one relationship " + "page, seconds; the native count is sub-second.", + returns="scalar (int | None)", + generic=True, + params=[ + AnalyticParam(name="relationship_type", type="str", required=True, + description="Relationship type to count, e.g. SemanticAssignment."), + _as_of(), + _population(), + ], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[_measure("relationships", "relationships", "value")], + absence=_absence( + not_measured="The relationships were not counted: the query failed, or a " + "repository count was asked for and no native count could answer it.", + not_permitted="You are not permitted to read these relationships.", + not_applicable="This count does not apply: the relationship type named is not one " + "the server knows.", + nothing_found="Counted: there are no active relationships of this type.", + ), + out=[_field("value", "Relationships", "int", unit="relationships")], + ), ), "contextualised_coverage": AnalyticFunctionSpec( name="contextualised_coverage", diff --git a/tests/micro-tests/test_issue_170_analytic_declaration.py b/tests/micro-tests/test_issue_170_analytic_declaration.py index 7142767d..950ff220 100644 --- a/tests/micro-tests/test_issue_170_analytic_declaration.py +++ b/tests/micro-tests/test_issue_170_analytic_declaration.py @@ -31,7 +31,8 @@ #: Built-ins that declare their results (RS-W1-4 added the first); every other spec #: still loads with no declaration -- the field stays optional. -DECLARED_BUILTINS = {"asset_composition"} +DECLARED_BUILTINS = {"asset_composition", "count_elements", "count_elements_by_property", "count_relationships", + "counts_by_type", "sum_type_counts"} def test_existing_specs_load_without_a_declaration(): From 20faf788357cc1ba18ac3a9532e9ab8d914687ef Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Sat, 7 Nov 2026 18:17:14 +0000 Subject: [PATCH 3/6] feat(analytic-registry): declare the coverage routines; ownership failure is None, not 0 RS-W2-1a, routines: governed_coverage, ownership_coverage, business_value_signals, certifications_summary, semantic_grounding. Fix in this commit: ownership_coverage used _find, which turns a failed query into an empty list, so an outage reported ownershipCount 0 ("nothing owned") with ownershipCapped False (overview_metrics.py:693 before this change). It now uses _find_or_none and returns None for both, as governed_coverage already did. The Portal assigns ownershipCount before dividing and catches the TypeError, so it shows no number instead of 0; a successful call is unchanged. What the functions return, worth knowing: - governed_coverage and ownership_coverage are not restricted to Asset: they count elements of any type carrying the classification. The declarations say so ("elements of any type ..."); restricting them to Assets is a code change, named in the PR. - certifications_summary's counts are each one get_relationships page with no completeness flag, like count_relationships. - semantic_grounding's groundingPct is links per hundred Assets (capped at 100), not the share of Assets with a link; its unit says that. Signed-off-by: Dan Wolfson --- pyegeria/view/analytic_registry.py | 126 +++++++++++++++++- pyegeria/view/overview_metrics.py | 9 +- .../test_issue_170_analytic_declaration.py | 3 +- .../test_rs_w2_1a_routine_declarations.py | 18 +++ 4 files changed, 152 insertions(+), 4 deletions(-) diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 48a86842..754a6c5a 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -614,6 +614,38 @@ def _always_applies(what: str) -> str: binding_note="Fixed to GOVERNANCE_CLASSIFICATIONS: ZoneMembership, Confidentiality, " "Criticality, Impact, Retention -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + # The find is not restricted to Asset: these count elements of any type. + measures=[ + _measure("governed_elements", "elements of any type carrying at least one of the five " + "governance classifications", "governedCount", + completeness_field="governedCapped", population="viewer"), + _measure("fully_governed", "elements carrying Confidentiality, Criticality, Impact or " + "Retention", "fullyGoverned", completeness_field="governedCapped", population="viewer", + basis=_basis("governedCount", "governed elements")), + _measure("zone_only", "elements carrying ZoneMembership and no other governance " + "classification", "partialZoneOnly", completeness_field="governedCapped", + population="viewer", basis=_basis("governedCount", "governed elements")), + ], + absence=_absence( + not_measured="Governance coverage was not measured: the find of classified elements failed.", + not_permitted="You are not permitted to read the classified elements, so governance " + "coverage was not measured.", + not_applicable=_always_applies("Governance coverage"), + nothing_found="Counted: no active element carries any of the five governance " + "classifications (ZoneMembership, Confidentiality, Criticality, Impact, " + "Retention).", + ), + out=[ + _field("governedCount", "Governed elements", "int", unit="elements"), + _field("governedCapped", "At least (page cap reached)", "bool"), + _field("fullyGoverned", "Fully governed", "int", unit="elements"), + _field("partialZoneOnly", "Zone only", "int", unit="elements"), + _field("byClassification", "By classification", "map", unit="elements"), + _field("topZones", "Top zones", kind="dataset", shape="ZoneCount"), + ], + ), ), "ownership_coverage": AnalyticFunctionSpec( name="ownership_coverage", @@ -627,6 +659,23 @@ def _always_applies(what: str) -> str: generic=False, binding_note="Fixed to the Ownership classification -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[_measure("owned_elements", "elements of any type carrying an Ownership classification", + "ownershipCount", completeness_field="ownershipCapped", population="viewer")], + absence=_absence( + not_measured="Ownership coverage was not measured: the find of owned elements failed.", + not_permitted="You are not permitted to read the owned elements, so ownership coverage " + "was not measured.", + not_applicable=_always_applies("Ownership coverage"), + nothing_found="Counted: no active element carries an Ownership classification.", + ), + out=[ + _field("ownershipCount", "Owned elements", "int", unit="elements"), + _field("ownershipCapped", "At least (page cap reached)", "bool"), + _field("byOwnerType", "By owner type", "map", unit="elements"), + ], + ), ), "business_value_signals": AnalyticFunctionSpec( name="business_value_signals", @@ -640,7 +689,37 @@ def _always_applies(what: str) -> str: generic=False, binding_note="Fixed to the Asset type hierarchy and Confidentiality/ConsolidatedDuplicate " "classifications -- not a parameter.", - params=[_as_of()], + params=[_as_of(), _population()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("assets_read", "Assets", "assetTotal", completeness_field="assetCapped", + population="viewer"), + _measure("confidential_assets", "Assets carrying a Confidentiality classification", + "confidentialCount", completeness_field="assetCapped", population="viewer", + basis=_basis("assetTotal", "Assets read")), + _measure("described_assets", "Assets with a description", "describedCount", + completeness_field="assetCapped", population="viewer", + basis=_basis("assetTotal", "Assets read")), + _measure("duplicate_elements", "elements of any type carrying ConsolidatedDuplicate", + "duplicateCount"), + ], + absence=_absence( + not_measured="The business-value signals were not measured: the Asset find or the " + "duplicate count failed.", + not_permitted="You are not permitted to read the Assets, so the business-value " + "signals were not measured.", + not_applicable=_always_applies("The business-value signals"), + nothing_found="Counted: there are no active Assets and no elements marked as duplicates.", + ), + out=[ + _field("assetTotal", "Assets read", "int", unit="Assets"), + _field("assetCapped", "At least (page cap reached)", "bool"), + _field("confidentialCount", "Confidential Assets", "int", unit="Assets"), + _field("describedCount", "Described Assets", "int", unit="Assets"), + _field("duplicateCount", "Duplicates", "int", unit="elements"), + ], + ), ), "certifications_summary": AnalyticFunctionSpec( name="certifications_summary", @@ -650,6 +729,30 @@ def _always_applies(what: str) -> str: generic=False, binding_note="Fixed to the Certification and Exception relationship types -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + # Each count is one get_relationships page (DEFAULT_CAP), with no completeness flag. + measures=[ + _measure("certifications", "Certification relationships", "active", population="viewer"), + _measure("expiring_certifications", "Certification relationships ending within 90 days", + "expiring90", population="viewer", basis=_basis("active", "certifications")), + _measure("licenses", "License relationships", "licenses", population="viewer"), + _measure("exceptions", "Exception relationships", "exceptions", population="viewer"), + ], + absence=_absence( + not_measured="Certifications were not measured: the relationship queries failed.", + not_permitted="You are not permitted to read certifications, licenses or exceptions.", + not_applicable=_always_applies("A certification summary"), + nothing_found="Counted: there are no active certifications, licenses or exceptions.", + ), + out=[ + _field("active", "Certifications", "int", unit="relationships"), + _field("expiring90", "Ending within 90 days", "int", unit="relationships"), + _field("soon", "Ending soonest", kind="dataset", shape="ExpiringCertification"), + _field("licenses", "Licenses", "int", unit="relationships"), + _field("exceptions", "Exceptions", "int", unit="relationships"), + ], + ), ), "people_counts": AnalyticFunctionSpec( name="people_counts", @@ -691,6 +794,27 @@ def _always_applies(what: str) -> str: generic=False, binding_note="Fixed to the SemanticAssignment relationship type -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("grounding_links", "SemanticAssignment relationships", "groundingLinks", + population="viewer"), + # links / Assets, not the share of Assets with a link: one Asset may carry several. + _measure("grounding_percent", "percent: SemanticAssignment links per hundred Assets, " + "at most 100", "groundingPct"), + ], + absence=_absence( + not_measured="Semantic grounding was not measured: the relationship query failed or " + "there was no Asset count to divide by.", + not_permitted="You are not permitted to read the semantic assignments.", + not_applicable=_always_applies("Semantic grounding"), + nothing_found="Counted: no glossary term is assigned to anything.", + ), + out=[ + _field("groundingLinks", "Grounding links", "int", unit="relationships"), + _field("groundingPct", "Links per hundred Assets", "int", unit="percent"), + ], + ), ), "context_readiness_funnel": AnalyticFunctionSpec( name="context_readiness_funnel", diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index 976412ab..5037afc9 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -677,7 +677,10 @@ def ownership_coverage(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: data" is repeatedly named as the foundation for trustworthy AI consumption), not a duplicate of governance-classification coverage. - Returns {"ownershipCount": int, "ownershipCapped": bool, + If the find fails, ownershipCount/ownershipCapped are None (unmeasured, as in + governed_coverage) and byOwnerType is empty -- not 0, which read as "nothing owned". + + Returns {"ownershipCount": int|None, "ownershipCapped": bool|None, "byOwnerType": {typeName: count}}. """ body = { @@ -690,7 +693,9 @@ def ownership_coverage(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: } if as_of: body["asOfTime"] = as_of - hits = _find(mgr, body) + hits = _find_or_none(mgr, body) + if hits is None: # query failed: unmeasured, not "nothing owned" + return {"ownershipCount": None, "ownershipCapped": None, "byOwnerType": {}} by_owner_type: Dict[str, int] = {} for el in hits: diff --git a/tests/micro-tests/test_issue_170_analytic_declaration.py b/tests/micro-tests/test_issue_170_analytic_declaration.py index 950ff220..14423a66 100644 --- a/tests/micro-tests/test_issue_170_analytic_declaration.py +++ b/tests/micro-tests/test_issue_170_analytic_declaration.py @@ -32,7 +32,8 @@ #: Built-ins that declare their results (RS-W1-4 added the first); every other spec #: still loads with no declaration -- the field stays optional. DECLARED_BUILTINS = {"asset_composition", "count_elements", "count_elements_by_property", "count_relationships", - "counts_by_type", "sum_type_counts"} + "counts_by_type", "sum_type_counts", "governed_coverage", "ownership_coverage", + "business_value_signals", "certifications_summary", "semantic_grounding"} def test_existing_specs_load_without_a_declaration(): diff --git a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py index 918136b4..4afd7316 100644 --- a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py +++ b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py @@ -72,3 +72,21 @@ def test_bad_fields_are_refused_with_a_sentence(field, words): def test_out_defaults_empty_so_older_declarations_still_load(): d = AnalyticDeclaration(result_kind="list", absence=ABSENCE) assert d.out == [] and d.categories is None and d.listing is None + + +# ── a failed query is None (not_measured), never 0 (RS-W2-1a §3.3) ── + +def _failing_clients(): + from unittest.mock import MagicMock + mgr = MagicMock(spec=["platform_url", "view_server", "find_metadata_elements"]) + mgr.platform_url, mgr.view_server = "https://localhost:9443", "test-server" + mgr.find_metadata_elements.side_effect = RuntimeError("boom") + ce = MagicMock(spec=["get_relationships"]) + ce.get_relationships.side_effect = RuntimeError("boom") + return mgr, ce + + +def test_ownership_coverage_failure_is_unmeasured(): + from pyegeria.view import overview_metrics as om + mgr, _ = _failing_clients() + assert om.ownership_coverage(mgr) == {"ownershipCount": None, "ownershipCapped": None, "byOwnerType": {}} From 64dca7602aaae06c67b1a06331fb7401b22e6728 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Sat, 7 Nov 2026 18:18:32 +0000 Subject: [PATCH 4/6] feat(analytic-registry): declare the people and engagement routines; contributors failure is None RS-W2-1a, routines: people_counts, feedback_summary, usage_context_counts, active_contributors, karma_leaderboard. Fix in this commit: active_contributors turned a failed relationship query into an empty set, so an outage read as 0 contributors for that type and a smaller union overall (overview_metrics.py:1811 before this change). A failed type is now None in byType and contributors is None unless every type was read, the rule feedback_summary's total already follows. test_active_contributors_degrades_per_type_on_failure pinned the old 0 and now pins the None. Not called by the Portal's Overview. What the functions return, worth knowing: - people_counts and usage_context_counts run non-strict by default: a failed count is 0 unless strict=True (ISSUE-123). Named in the PR, not changed. - karma_leaderboard returns [] both when the find fails and when nobody has karma, so not_measured and nothing_found are indistinguishable in its result (overview_metrics.py:1480). Changing [] to None would change a list routine's shape for the Portal; named in the PR. - active_contributors counts users from relationship audit headers (createdBy), viewer population, one capped page per type. Signed-off-by: Dan Wolfson --- pyegeria/view/analytic_registry.py | 120 +++++++++++++++++- pyegeria/view/overview_metrics.py | 13 +- .../test_issue_170_analytic_declaration.py | 3 +- tests/micro-tests/test_overview_metrics.py | 6 +- .../test_rs_w2_1a_routine_declarations.py | 8 ++ 5 files changed, 141 insertions(+), 9 deletions(-) diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 754a6c5a..51d44c78 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -761,7 +761,32 @@ def _always_applies(what: str) -> str: returns="dict (persons, teams, organizations, itProfiles, communities)", generic=False, binding_note="Fixed to Person/Team/Organization/ITProfile/Community -- not a parameter.", - params=[_as_of(), _strict()], + params=[_as_of(), _strict(), _population()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("persons", "Person profiles", "persons"), + _measure("teams", "Team profiles", "teams"), + _measure("organizations", "Organization profiles", "organizations"), + _measure("it_profiles", "ITProfile profiles", "itProfiles"), + _measure("communities", "Community profiles", "communities"), + ], + absence=_absence( + not_measured="The actor profiles were not counted: the count queries failed, or the " + "server could not answer them in the population asked for.", + not_permitted="You are not permitted to count actor profiles.", + not_applicable=_always_applies("Counting actor profiles"), + nothing_found="Counted: there are no active Person, Team, Organization, ITProfile or " + "Community profiles.", + ), + out=[ + _field("persons", "People", "int", unit="profiles"), + _field("teams", "Teams", "int", unit="profiles"), + _field("organizations", "Organizations", "int", unit="profiles"), + _field("itProfiles", "IT profiles", "int", unit="profiles"), + _field("communities", "Communities", "int", unit="profiles"), + ], + ), ), "feedback_summary": AnalyticFunctionSpec( name="feedback_summary", @@ -771,7 +796,30 @@ def _always_applies(what: str) -> str: returns="dict (byType, total)", generic=False, binding_note="Fixed to Collaboration OMAS's feedback relationship types -- not a parameter.", - params=[_as_of()], + params=[_as_of(), _population()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("feedback", "feedback relationships", "total"), + _measure("ratings", "AttachedRating relationships", "byType.ratings"), + _measure("comments", "AttachedComment relationships", "byType.comments"), + _measure("likes", "AttachedLike relationships", "byType.likes"), + _measure("tags", "AttachedTag relationships", "byType.tags"), + _measure("note_logs", "AttachedNoteLog relationships", "byType.noteLogs"), + ], + absence=_absence( + not_measured="Feedback was not counted: a relationship query failed, or a repository " + "count was asked for without a native count to answer it.", + not_permitted="You are not permitted to read feedback relationships.", + not_applicable=_always_applies("A feedback summary"), + nothing_found="Counted: nothing in the catalog has been rated, commented on, liked, " + "tagged or given a note log.", + ), + out=[ + _field("total", "Feedback", "int", unit="relationships"), + _field("byType", "By type", "map", unit="relationships"), + ], + ), ), "usage_context_counts": AnalyticFunctionSpec( name="usage_context_counts", @@ -782,7 +830,26 @@ def _always_applies(what: str) -> str: returns="dict (informationSupplyChains, blueprints)", generic=False, binding_note="Fixed to InformationSupplyChain and SolutionBlueprint -- not a parameter.", - params=[_as_of(), _strict()], + params=[_as_of(), _strict(), _population()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("supply_chains", "InformationSupplyChain elements", "informationSupplyChains"), + _measure("blueprints", "SolutionBlueprint elements", "blueprints"), + ], + absence=_absence( + not_measured="Supply chains and blueprints were not counted: the count queries failed, " + "or the server could not answer them in the population asked for.", + not_permitted="You are not permitted to count supply chains or blueprints.", + not_applicable=_always_applies("Counting supply chains and blueprints"), + nothing_found="Counted: there are no active information supply chains or solution " + "blueprints.", + ), + out=[ + _field("informationSupplyChains", "Information supply chains", "int", unit="elements"), + _field("blueprints", "Solution blueprints", "int", unit="elements"), + ], + ), ), "semantic_grounding": AnalyticFunctionSpec( name="semantic_grounding", @@ -883,6 +950,32 @@ def _always_applies(what: str) -> str: generic=False, binding_note="Fixed to Collaboration OMAS's feedback relationship types -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + # Users who attached feedback, read from relationship audit headers (createdBy). + measures=[ + _measure("contributors", "distinct users who attached feedback", "contributors", + population="viewer"), + _measure("raters", "distinct users who attached a rating", "byType.ratings", population="viewer"), + _measure("commenters", "distinct users who attached a comment", "byType.comments", + population="viewer"), + _measure("likers", "distinct users who attached a like", "byType.likes", population="viewer"), + _measure("taggers", "distinct users who attached a tag", "byType.tags", population="viewer"), + _measure("note_loggers", "distinct users who attached a note log", "byType.noteLogs", + population="viewer"), + ], + absence=_absence( + not_measured="Contributors were not counted: a feedback relationship query failed.", + not_permitted="You are not permitted to read feedback relationships, so contributors " + "were not counted.", + not_applicable=_always_applies("Counting contributors"), + nothing_found="Counted: nobody has attached a rating, comment, like, tag or note log.", + ), + out=[ + _field("contributors", "Contributors", "int", unit="users"), + _field("byType", "By feedback type", "map", unit="users"), + ], + ), ), "sum_type_counts": AnalyticFunctionSpec( name="sum_type_counts", @@ -1019,6 +1112,27 @@ def _always_applies(what: str) -> str: description="Anchor typeName(s) to include, e.g. ['Person', 'ITProfile']."), _as_of(), ], + declaration=AnalyticDeclaration( + result_kind="list", + measures=[_measure("karma_points", "karma points", "karmaPoints")], + listing=ListDeclaration(item_fields=["name", "karmaPoints", "anchorType"], + order="most karma first", key_field="anchorGuid", + item_label="contributors"), + absence=_absence( + not_measured="The leaderboard was not read: the find of contribution records failed.", + not_permitted="You are not permitted to read contribution records.", + not_applicable="A leaderboard does not apply to these anchor types: no contribution " + "record is anchored to them.", + nothing_found="Read: nobody of these anchor types has a contribution record with karma " + "points.", + ), + out=[ + _field("name", "Name", "string"), + _field("karmaPoints", "Karma points", "int", unit="karma points"), + _field("anchorGuid", "Profile", "guid"), + _field("anchorType", "Profile type", "string"), + ], + ), ), "engagement_series": AnalyticFunctionSpec( name="engagement_series", diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index 5037afc9..5589b2d9 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -1794,6 +1794,10 @@ def active_contributors(ce, as_of: Optional[str] = None) -> Dict[str, Any]: noteLogs}} where byType is the distinct-username count per relationship type (one person active in two types counts once in "contributors" but once per type in byType). + + A type whose query failed is None in byType, and `contributors` is None + unless every type was read -- a partial union would read as fewer people, + the same rule feedback_summary's `total` follows. """ body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None @@ -1806,17 +1810,20 @@ def _actor_usernames(rel_type: str) -> set: if (u := (rel.get("relationshipHeader") or {}).get("versions", {}).get("createdBy")) } - by_type: Dict[str, int] = {} + by_type: Dict[str, Optional[int]] = {} all_users: set = set() + measured = True for rel_type, key in _FEEDBACK_RELATIONSHIP_TYPES: try: users = _actor_usernames(rel_type) except Exception as exc: # noqa: BLE001 logger.debug(f"overview_metrics active_contributors: {rel_type} failed: {exc}") - users = set() + by_type[key] = None + measured = False + continue by_type[key] = len(users) all_users |= users - return {"contributors": len(all_users), "byType": by_type} + return {"contributors": len(all_users) if measured else None, "byType": by_type} def control_implementation_summary(client, soa_guid: str) -> Dict[str, int]: diff --git a/tests/micro-tests/test_issue_170_analytic_declaration.py b/tests/micro-tests/test_issue_170_analytic_declaration.py index 14423a66..f5b6ad23 100644 --- a/tests/micro-tests/test_issue_170_analytic_declaration.py +++ b/tests/micro-tests/test_issue_170_analytic_declaration.py @@ -33,7 +33,8 @@ #: still loads with no declaration -- the field stays optional. DECLARED_BUILTINS = {"asset_composition", "count_elements", "count_elements_by_property", "count_relationships", "counts_by_type", "sum_type_counts", "governed_coverage", "ownership_coverage", - "business_value_signals", "certifications_summary", "semantic_grounding"} + "business_value_signals", "certifications_summary", "semantic_grounding", "people_counts", "feedback_summary", + "usage_context_counts", "active_contributors", "karma_leaderboard"} def test_existing_specs_load_without_a_declaration(): diff --git a/tests/micro-tests/test_overview_metrics.py b/tests/micro-tests/test_overview_metrics.py index 95ffe3d7..9cca8830 100644 --- a/tests/micro-tests/test_overview_metrics.py +++ b/tests/micro-tests/test_overview_metrics.py @@ -567,8 +567,10 @@ def test_active_contributors_degrades_per_type_on_failure(): [], [], [], ] result = om.active_contributors(ce) - assert result["byType"]["ratings"] == 0 - assert result["contributors"] == 1 + # the failed type is unmeasured (None), and so is the union it would be part of (RS-W2-1a) + assert result["byType"]["ratings"] is None + assert result["byType"]["comments"] == 1 + assert result["contributors"] is None # ── metric_trend ────────────────────────────────────────────────────────── diff --git a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py index 4afd7316..4eac16e3 100644 --- a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py +++ b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py @@ -90,3 +90,11 @@ def test_ownership_coverage_failure_is_unmeasured(): from pyegeria.view import overview_metrics as om mgr, _ = _failing_clients() assert om.ownership_coverage(mgr) == {"ownershipCount": None, "ownershipCapped": None, "byOwnerType": {}} + + +def test_active_contributors_failure_is_unmeasured(): + from pyegeria.view import overview_metrics as om + _, ce = _failing_clients() + result = om.active_contributors(ce) + assert result["contributors"] is None + assert set(result["byType"].values()) == {None} From b423979444fb99d85e09e1b8b2e451c6208204b4 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Sat, 7 Nov 2026 18:20:00 +0000 Subject: [PATCH 5/6] feat(analytic-registry): declare the readiness routines; register drl and realisation; failures are None RS-W2-1a, routines: context_readiness_funnel, ai_ready_assets, drl_readiness_gates (newly registered, D6), contextualised_coverage, solution_component_realisation (newly registered, D6). Fixes in this commit, each a failed query that read as a measured 0: - context_readiness_funnel: `documented` came from _find, which never raises, so its try/except never fired and a failed Asset find gave documented 0 (overview_metrics.py:999 before). Now None. - ai_ready_assets: a failed Asset find gave {aiReadyCount 0, total 0, capped False}, and a failed DataFlow query gave aiReadyCount 0 ("no asset is lineage-traced") (overview_metrics.py:1061/1075 before). Now None, keeping total/capped when only the DataFlow query failed. test_ai_ready_assets_lineage_query_failure... pinned the 0 and now pins the None. - drl_readiness_gates: the same two failures (overview_metrics.py:1182/1196 before). Now every field None on an Asset-find failure; aiReadyCount/aiReadyRecentCount None on a DataFlow failure, keeping total, capped and byModality. The Portal's ai-context endpoint already guards each of these with `if x:` / try, so it shows no number instead of 0; successful calls are unchanged. What the functions return, worth knowing: - context_readiness_funnel's four stages are independent counts over different populations (Assets, elements of any type, relationships), not nested stages, and its `documented` stage has no completeness flag although it comes from one capped find. - contextualised_coverage and solution_component_realisation turn a measured 0 total into None (`total or None`, overview_metrics.py:1381/1438): a real zero reads as unmeasured, the inverse bug. Not changed (it would change a success result); named in the PR. Signed-off-by: Dan Wolfson --- pyegeria/view/analytic_registry.py | 151 ++++++++++++++++++ pyegeria/view/overview_metrics.py | 44 +++-- .../test_issue_170_analytic_declaration.py | 4 +- tests/micro-tests/test_overview_metrics.py | 6 +- .../test_rs_w2_1a_routine_declarations.py | 22 +++ 5 files changed, 208 insertions(+), 19 deletions(-) diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 51d44c78..66fcd4ae 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -896,6 +896,33 @@ def _always_applies(what: str) -> str: generic=False, binding_note="Fixed 5-stage readiness definition baked into the function body -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + # Four independent counts over different populations, not nested stages of one set. + measures=[ + _measure("cataloged", "Assets", "cataloged"), + _measure("documented", "Assets with a description, among those one capped find returned", + "documented", population="viewer"), + _measure("classified", "elements of any type carrying a governance classification", + "classified"), + _measure("lineage", "DataFlow relationships", "lineage", population="viewer"), + ], + absence=_absence( + not_measured="The readiness funnel was not measured: its counts or the Asset find failed.", + not_permitted="You are not permitted to read the Assets, so the readiness funnel was " + "not measured.", + not_applicable=_always_applies("The readiness funnel"), + nothing_found="Counted: there are no active Assets, governed elements or DataFlow " + "relationships.", + ), + out=[ + _field("cataloged", "Cataloged", "int", unit="Assets"), + _field("documented", "Documented", "int", unit="Assets"), + _field("classified", "Classified", "int", unit="elements"), + _field("lineage", "Lineage-traced", "int", unit="relationships"), + _field("aiReady", "AI-ready (always empty here; see ai_ready_assets)", "int", unit="Assets"), + ], + ), ), "ai_ready_assets": AnalyticFunctionSpec( name="ai_ready_assets", @@ -910,6 +937,77 @@ def _always_applies(what: str) -> str: generic=False, binding_note="Fixed to governed+documented+lineage-traced over Asset elements -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("assets_checked", "Assets", "total", completeness_field="capped", population="viewer"), + _measure("ai_ready_assets", "Assets that are governed, documented and lineage-traced", + "aiReadyCount", completeness_field="capped", population="viewer", + basis=_basis("total", "Assets checked")), + ], + absence=_absence( + not_measured="AI readiness was not measured: the Asset find or the DataFlow query failed.", + not_permitted="You are not permitted to read the Assets, so AI readiness was not measured.", + not_applicable=_always_applies("AI readiness"), + nothing_found="Checked: there are no active Assets to assess.", + ), + out=[ + _field("aiReadyCount", "AI-ready Assets", "int", unit="Assets"), + _field("total", "Assets checked", "int", unit="Assets"), + _field("capped", "At least (page cap reached)", "bool"), + ], + ), + ), + "drl_readiness_gates": AnalyticFunctionSpec( + name="drl_readiness_gates", + function="pyegeria.view.overview_metrics.drl_readiness_gates", + description="A recency-narrowed view of ai_ready_assets plus a modality breakdown " + "(tabular / text_media / other) of the Asset population -- the two Data " + "Readiness Level pieces computable today. Not a DRL band distribution: " + "Analytics-Ready and RAG-Ready are deliberately absent until their gates exist. " + "Takes two leading clients (mgr, ce). Cost: one capped Asset find and one capped " + "DataFlow relationship page, seconds.", + returns="dict (total, capped, aiReadyCount, aiReadyRecentCount, byModality)", + generic=False, + binding_note="Fixed to governed+documented+lineage-traced Asset elements and the " + "asset_modality type lists -- recency_days tunes the window, not what is measured.", + params=[ + _as_of(), + AnalyticParam(name="recency_days", type="int", default=180, + description="Provisional recency window, in days (not yet a decided band threshold)."), + ], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("assets_checked", "Assets", "total", completeness_field="capped", population="viewer"), + _measure("ai_ready_assets", "Assets that are governed, documented and lineage-traced", + "aiReadyCount", completeness_field="capped", population="viewer", + basis=_basis("total", "Assets checked")), + _measure("ai_ready_recent_assets", "AI-ready Assets updated within recency_days", + "aiReadyRecentCount", completeness_field="capped", population="viewer", + basis=_basis("aiReadyCount", "AI-ready Assets")), + _measure("tabular_assets", "tabular Assets", "byModality.tabular", + completeness_field="capped", population="viewer", basis=_basis("total", "Assets checked")), + _measure("text_media_assets", "text and media Assets", "byModality.text_media", + completeness_field="capped", population="viewer", basis=_basis("total", "Assets checked")), + _measure("other_assets", "Assets of other modalities", "byModality.other", + completeness_field="capped", population="viewer", basis=_basis("total", "Assets checked")), + ], + absence=_absence( + not_measured="Readiness gates were not measured: the Asset find or the DataFlow query failed.", + not_permitted="You are not permitted to read the Assets, so the readiness gates were " + "not measured.", + not_applicable=_always_applies("The readiness gates"), + nothing_found="Checked: there are no active Assets to assess.", + ), + out=[ + _field("total", "Assets checked", "int", unit="Assets"), + _field("capped", "At least (page cap reached)", "bool"), + _field("aiReadyCount", "AI-ready Assets", "int", unit="Assets"), + _field("aiReadyRecentCount", "AI-ready and recent", "int", unit="Assets"), + _field("byModality", "By modality", "map", unit="Assets"), + ], + ), ), "growth_series": AnalyticFunctionSpec( name="growth_series", @@ -1095,6 +1193,59 @@ def _always_applies(what: str) -> str: generic=False, binding_note="Fixed to the ImplementedBy relationship, filtered to Asset-subtype ends -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("contextualised_assets", "Assets that implement a SolutionComponent (ImplementedBy)", + "contextualisedCount", population="viewer"), + _measure("assets", "Assets", "assetTotal"), + _measure("contextualised_percent", "percent of Assets (0-100)", "contextualisedPct"), + ], + absence=_absence( + not_measured="Contextualised coverage was not measured: the ImplementedBy query or the " + "Asset count failed.", + not_permitted="You are not permitted to read the ImplementedBy relationships.", + not_applicable=_always_applies("Contextualised coverage"), + nothing_found="Counted: no Asset implements a solution component.", + ), + out=[ + _field("contextualisedCount", "Contextualised Assets", "int", unit="Assets"), + _field("assetTotal", "Assets", "int", unit="Assets"), + _field("contextualisedPct", "Contextualised", "float", unit="percent"), + ], + ), + ), + "solution_component_realisation": AnalyticFunctionSpec( + name="solution_component_realisation", + function="pyegeria.view.overview_metrics.solution_component_realisation", + description="SolutionComponent count and how many of them are realised (have at least one " + "ImplementedBy implementation) -- the Overview's Solution Blueprints drill-down. A " + "single-hop proxy: the implementation need not itself sit in the component's " + "supply chain or blueprint. Takes two leading clients (mgr, ce). Cost: one native " + "count plus one capped ImplementedBy relationship page, seconds.", + returns="dict (solutionComponentsTotal, solutionComponentsRealised)", + generic=False, + binding_note="Fixed to SolutionComponent and the ImplementedBy relationship -- not a parameter.", + params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("solution_components", "SolutionComponent elements", "solutionComponentsTotal"), + _measure("realised_components", "SolutionComponents with an ImplementedBy implementation", + "solutionComponentsRealised", population="viewer"), + ], + absence=_absence( + not_measured="Solution component realisation was not measured: the count or the " + "ImplementedBy query failed.", + not_permitted="You are not permitted to read solution components or their implementations.", + not_applicable=_always_applies("Solution component realisation"), + nothing_found="Counted: there are no active solution components.", + ), + out=[ + _field("solutionComponentsTotal", "Solution components", "int", unit="elements"), + _field("solutionComponentsRealised", "Realised", "int", unit="elements"), + ], + ), ), "karma_leaderboard": AnalyticFunctionSpec( name="karma_leaderboard", diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index 5589b2d9..ef305b5a 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -1001,9 +1001,9 @@ def context_readiness_funnel(mgr, ce, as_of: Optional[str] = None) -> Dict[str, "metadataElementTypeName": "Asset"} if as_of: body["asOfTime"] = as_of - assets = _find(mgr, body) - documented = 0 - for a in assets: + assets = _find_or_none(mgr, body) # None when the find failed: documented stays None, not 0 + documented = None if assets is None else 0 + for a in assets or []: pvm = (a.get("elementProperties") or {}).get("propertyValueMap") or {} desc = (pvm.get("description") or {}).get("primitiveValue") if isinstance(desc, str) and desc.strip(): @@ -1055,17 +1055,22 @@ def ai_ready_assets(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: `context_readiness_funnel`'s own `documented` stage) -- a floor, not exact, on a catalog larger than DEFAULT_CAP. - Returns {"aiReadyCount": int, "total": int, "capped": bool} -- "total" is - the (possibly capped) Asset population actually checked, so a caller can - compute a percentage without a separate cataloged-count call. + Returns {"aiReadyCount": int|None, "total": int|None, "capped": bool|None} + -- "total" is the (possibly capped) Asset population actually checked, so + a caller can compute a percentage without a separate cataloged-count call. + A failed Asset find makes all three None; a failed DataFlow query makes + aiReadyCount None (no asset can be shown lineage-traced, which is not the + same as none being so) and keeps total/capped. """ body: Dict[str, Any] = {"class": "FindRequestBody", "limitResultsByStatus": ["ACTIVE"], "metadataElementTypeName": "Asset"} if as_of: body["asOfTime"] = as_of - assets = _find(mgr, body) + assets = _find_or_none(mgr, body) + if assets is None: + return {"aiReadyCount": None, "total": None, "capped": None} - lineage_guids: set = set() + lineage_guids: Optional[set] = set() try: rel_body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None rels = _json_list(ce.get_relationships( @@ -1079,6 +1084,9 @@ def ai_ready_assets(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: lineage_guids.add(g) except Exception as exc: # noqa: BLE001 logger.debug(f"ai_ready_assets: lineage relationship query failed: {exc}") + lineage_guids = None + if lineage_guids is None: + return {"aiReadyCount": None, "total": len(assets), "capped": len(assets) >= DEFAULT_CAP} ai_ready = 0 for a in assets: @@ -1175,8 +1183,10 @@ def drl_readiness_gates(mgr, ce, as_of: Optional[str] = None, recency_days: int recency_days : provisional recency window for "recent" -- not yet a decided band threshold, see design doc "Open decisions" - Returns {"total": int, "capped": bool, "aiReadyCount": int, - "aiReadyRecentCount": int, "byModality": {"tabular", "text_media", "other"}}. + Returns {"total": int|None, "capped": bool|None, "aiReadyCount": int|None, + "aiReadyRecentCount": int|None, "byModality": {"tabular", "text_media", "other"}|None}. + A failed Asset find makes every field None; a failed DataFlow query makes + aiReadyCount/aiReadyRecentCount None and keeps the rest -- unmeasured, not 0. """ from datetime import datetime, timedelta, timezone @@ -1184,9 +1194,12 @@ def drl_readiness_gates(mgr, ce, as_of: Optional[str] = None, recency_days: int "metadataElementTypeName": "Asset"} if as_of: body["asOfTime"] = as_of - assets = _find(mgr, body) + assets = _find_or_none(mgr, body) + if assets is None: + return {"total": None, "capped": None, "aiReadyCount": None, "aiReadyRecentCount": None, + "byModality": None} - lineage_guids: set = set() + lineage_guids: Optional[set] = set() try: rel_body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None rels = _json_list(ce.get_relationships( @@ -1199,6 +1212,7 @@ def drl_readiness_gates(mgr, ce, as_of: Optional[str] = None, recency_days: int lineage_guids.add(g) except Exception as exc: # noqa: BLE001 logger.debug(f"drl_readiness_gates: DataFlow relationship query failed: {exc}") + lineage_guids = None now = datetime.fromisoformat(as_of.replace("Z", "+00:00")) if as_of else datetime.now(timezone.utc) if now.tzinfo is None: @@ -1216,7 +1230,7 @@ def drl_readiness_gates(mgr, ce, as_of: Optional[str] = None, recency_days: int desc = (pvm.get("description") or {}).get("primitiveValue") documented = isinstance(desc, str) and bool(desc.strip()) governed = bool(_classifications_of(a) & set(GOVERNANCE_CLASSIFICATIONS)) - lineage_traced = guid in lineage_guids + lineage_traced = lineage_guids is not None and guid in lineage_guids if not (documented and governed and lineage_traced): continue ai_ready += 1 @@ -1228,8 +1242,8 @@ def drl_readiness_gates(mgr, ce, as_of: Optional[str] = None, recency_days: int return { "total": len(assets), "capped": len(assets) >= DEFAULT_CAP, - "aiReadyCount": ai_ready, - "aiReadyRecentCount": ai_ready_recent, + "aiReadyCount": ai_ready if lineage_guids is not None else None, + "aiReadyRecentCount": ai_ready_recent if lineage_guids is not None else None, "byModality": by_modality, } diff --git a/tests/micro-tests/test_issue_170_analytic_declaration.py b/tests/micro-tests/test_issue_170_analytic_declaration.py index f5b6ad23..a6ee86e7 100644 --- a/tests/micro-tests/test_issue_170_analytic_declaration.py +++ b/tests/micro-tests/test_issue_170_analytic_declaration.py @@ -34,7 +34,9 @@ DECLARED_BUILTINS = {"asset_composition", "count_elements", "count_elements_by_property", "count_relationships", "counts_by_type", "sum_type_counts", "governed_coverage", "ownership_coverage", "business_value_signals", "certifications_summary", "semantic_grounding", "people_counts", "feedback_summary", - "usage_context_counts", "active_contributors", "karma_leaderboard"} + "usage_context_counts", "active_contributors", "karma_leaderboard", "context_readiness_funnel", + "ai_ready_assets", "drl_readiness_gates", "contextualised_coverage", + "solution_component_realisation"} def test_existing_specs_load_without_a_declaration(): diff --git a/tests/micro-tests/test_overview_metrics.py b/tests/micro-tests/test_overview_metrics.py index 9cca8830..b754b5b8 100644 --- a/tests/micro-tests/test_overview_metrics.py +++ b/tests/micro-tests/test_overview_metrics.py @@ -320,7 +320,7 @@ def test_ai_ready_assets_empty_catalog(): assert result == {"aiReadyCount": 0, "total": 0, "capped": False} -def test_ai_ready_assets_lineage_query_failure_degrades_to_none_ai_ready(): +def test_ai_ready_assets_lineage_query_failure_is_unmeasured(): mgr = _mgr() mgr.find_metadata_elements.return_value = [ _asset("a1", "documented", ["Confidentiality"]), @@ -328,8 +328,8 @@ def test_ai_ready_assets_lineage_query_failure_degrades_to_none_ai_ready(): ce = MagicMock() ce.get_relationships.side_effect = Exception("boom") result = om.ai_ready_assets(mgr, ce) - # lineage query failed -> no asset can be lineage-traced -> 0, not a crash - assert result["aiReadyCount"] == 0 + # lineage query failed -> aiReadyCount is unmeasured (None), not 0, and not a crash (RS-W2-1a) + assert result["aiReadyCount"] is None assert result["total"] == 1 diff --git a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py index 4eac16e3..a2663538 100644 --- a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py +++ b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py @@ -98,3 +98,25 @@ def test_active_contributors_failure_is_unmeasured(): result = om.active_contributors(ce) assert result["contributors"] is None assert set(result["byType"].values()) == {None} + + +def test_readiness_routines_failure_is_unmeasured(): + from pyegeria.view import overview_metrics as om + mgr, ce = _failing_clients() + assert om.context_readiness_funnel(mgr, ce)["documented"] is None + assert om.ai_ready_assets(mgr, ce) == {"aiReadyCount": None, "total": None, "capped": None} + assert set(om.drl_readiness_gates(mgr, ce).values()) == {None} + + +def test_drl_lineage_failure_keeps_the_asset_population(): + from unittest.mock import MagicMock + + from pyegeria.view import overview_metrics as om + mgr, _ = _failing_clients() + mgr.find_metadata_elements.side_effect = None + mgr.find_metadata_elements.return_value = [{"elementGUID": "a1", "type": {"typeName": "CSVFile"}}] + ce = MagicMock(spec=["get_relationships"]) + ce.get_relationships.side_effect = RuntimeError("boom") + result = om.drl_readiness_gates(mgr, ce) + assert (result["total"], result["aiReadyCount"], result["aiReadyRecentCount"]) == (1, None, None) + assert sum(result["byModality"].values()) == 1 From 42c75a5897786dd8b69fa44b04e06a0b5221205d Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Sat, 7 Nov 2026 18:26:25 +0000 Subject: [PATCH 6/6] feat(analytic-registry): declare the series and attention routines; census: 0 undeclared RS-W2-1a, routines: growth_series, engagement_series, metric_trend, term_definition_completeness, orphan_glossary_terms, stale_assets, control_implementation_summary. With these every one of the 28 registry entries declares its results. Fixes in this commit, each a failed find that read as a measured 0: - term_definition_completeness: _find turned a failed find into an empty glossary, {total 0, defined 0} (overview_metrics.py:1757 before). Now all three fields None. - stale_assets: staleCount 0 on a failed find (overview_metrics.py:926 before). Now None. Neither is read by the Portal's Overview in a way that changes: staleAssetCount was already None when the routine raised. What the functions return, worth knowing: - growth_series and metric_trend carry no per-point as-of time, only the formatted `date`/`label`; the series measures name `date`. growth_series' counts are non-strict, so a failed snapshot reads 0 per series. - engagement_series zero-fills a type whose query failed, so an outage reads as a flat zero line (overview_metrics.py:1564). Changing that changes a list shape; named in the PR. - stale_assets' staleCount comes from one capped find and its assetTotal from a native count, so they are not a part and its whole; no basis is declared between them. - orphan_glossary_terms' termTotal is a non-strict count: a failed count is 0, and orphanCount then floors at 0 (overview_metrics.py:871/893). Named in the PR. Also: every description now ends with its cost class ("Cost: ..."), so W2-2 can set tile_safe from evidence. Only the 10.8 points are measured (repository counts 0.2-0.8 s; viewer count of Process 120 s); the rest are read from each routine's query shape. Tests (test_rs_w2_1a_routine_declarations.py): test_every_registry_entry_is_declared, test_declared_value_fields_exist (each routine called with fake clients; every value_field, completeness_field, basis denominator, as_of and out field resolves in its real result), test_absence_sentences_use_the_four_words, kind blocks present, and a failure test per 0 -> None fix. Signed-off-by: Dan Wolfson --- pyegeria/view/analytic_registry.py | 233 ++++++++++++++++-- pyegeria/view/overview_metrics.py | 17 +- .../test_issue_170_analytic_declaration.py | 19 +- .../test_rs_w2_1a_routine_declarations.py | 175 +++++++++++++ 4 files changed, 399 insertions(+), 45 deletions(-) diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 66fcd4ae..c868562b 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -579,7 +579,8 @@ def _always_applies(what: str) -> str: name="counts_by_type", function="pyegeria.view.overview_metrics.counts_by_type", description="Per-type element counts for a set of (label, type_name) pairs -- a breakdown/" - "composition metric, e.g. the assets-by-type chart.", + "composition metric, e.g. the assets-by-type chart. " + "Cost: one native count per type, sub-second each in the repository population; a viewer-population count can take minutes for a large type.", returns="list[dict] (breakdown: {label, type, count})", generic=True, params=[ @@ -608,7 +609,8 @@ def _always_applies(what: str) -> str: name="governed_coverage", function="pyegeria.view.overview_metrics.governed_coverage", description="Share of assets carrying at least one governance classification, plus a " - "by-classification / top-zones breakdown.", + "by-classification / top-zones breakdown. " + "Cost: one capped find (one page of elements), seconds.", returns="dict (governedCount, governedCapped, byClassification, topZones)", generic=False, binding_note="Fixed to GOVERNANCE_CLASSIFICATIONS: ZoneMembership, Confidentiality, " @@ -654,7 +656,8 @@ def _always_applies(what: str) -> str: "responsible for management/governance decisions), plus a by-owner-type " "breakdown. Distinct from governed_coverage -- data mesh literature names " "'clean, owned, product-based data' as its own foundation for trustworthy " - "AI consumption, not a synonym for governance-classification coverage.", + "AI consumption, not a synonym for governance-classification coverage. " + "Cost: one capped find (one page of elements), seconds.", returns="dict (ownershipCount, ownershipCapped, byOwnerType)", generic=False, binding_note="Fixed to the Ownership classification -- not a parameter.", @@ -684,7 +687,8 @@ def _always_applies(what: str) -> str: "(Risk & Compliance, Productivity, Trust & Adoption, Cost Avoidance): " "Confidentiality-classified asset count, described-asset count, " "ConsolidatedDuplicate-flagged element count -- all proxies with a " - "documented causal-claim caveat, not direct measures (NEXT-9).", + "documented causal-claim caveat, not direct measures (NEXT-9). " + "Cost: one capped Asset find plus one count, seconds.", returns="dict (assetTotal, assetCapped, confidentialCount, describedCount, duplicateCount)", generic=False, binding_note="Fixed to the Asset type hierarchy and Confidentiality/ConsolidatedDuplicate " @@ -724,7 +728,8 @@ def _always_applies(what: str) -> str: "certifications_summary": AnalyticFunctionSpec( name="certifications_summary", function="pyegeria.view.overview_metrics.certifications_summary", - description="Active/expiring Certification relationships, licenses, and open Exception counts.", + description="Active/expiring Certification relationships, licenses, and open Exception counts. " + "Cost: three capped relationship pages, seconds.", returns="dict (active, expiring90, soon, licenses, exceptions)", generic=False, binding_note="Fixed to the Certification and Exception relationship types -- not a parameter.", @@ -757,7 +762,8 @@ def _always_applies(what: str) -> str: "people_counts": AnalyticFunctionSpec( name="people_counts", function="pyegeria.view.overview_metrics.people_counts", - description="Counts of Person / Team / Organization / ITProfile / Community actor profiles.", + description="Counts of Person / Team / Organization / ITProfile / Community actor profiles. " + "Cost: five native counts, sub-second each in the repository population.", returns="dict (persons, teams, organizations, itProfiles, communities)", generic=False, binding_note="Fixed to Person/Team/Organization/ITProfile/Community -- not a parameter.", @@ -792,7 +798,8 @@ def _always_applies(what: str) -> str: name="feedback_summary", function="pyegeria.view.overview_metrics.feedback_summary", description="Crowd-sourced feedback counts (ratings/comments/likes/tags/noteLogs) by type, " - "via Collaboration OMAS relationships.", + "via Collaboration OMAS relationships. " + "Cost: five relationship pages (native counts when an expert client is passed), seconds.", returns="dict (byType, total)", generic=False, binding_note="Fixed to Collaboration OMAS's feedback relationship types -- not a parameter.", @@ -826,7 +833,8 @@ def _always_applies(what: str) -> str: function="pyegeria.view.overview_metrics.usage_context_counts", description="InformationSupplyChain and SolutionBlueprint counts -- the two structures that " "put assets in a business usage context (supply chain membership, blueprint " - "realization).", + "realization). " + "Cost: two native counts, sub-second each in the repository population.", returns="dict (informationSupplyChains, blueprints)", generic=False, binding_note="Fixed to InformationSupplyChain and SolutionBlueprint -- not a parameter.", @@ -856,7 +864,8 @@ def _always_applies(what: str) -> str: function="pyegeria.view.overview_metrics.semantic_grounding", description="SemanticAssignment relationship count and coverage percent -- the meaning layer " "that grounds AI. Takes two leading clients (mgr, ce) -- the executor supplies the " - "same EgeriaTech instance for both.", + "same EgeriaTech instance for both. " + "Cost: one count plus one capped relationship page, seconds.", returns="dict (groundingLinks, groundingPct)", generic=False, binding_note="Fixed to the SemanticAssignment relationship type -- not a parameter.", @@ -891,7 +900,8 @@ def _always_applies(what: str) -> str: "instance for both, matching semantic_grounding's convention. This function's own " "aiReady stays None always by design -- it's four independent counts, and aiReady " "needs a true cross-criteria intersection instead. Pair with ai_ready_assets " - "(below) for that -- overview_handler.py calls both and merges the result.", + "(below) for that -- overview_handler.py calls both and merges the result. " + "Cost: two counts, one capped Asset find and one relationship page, seconds.", returns="dict (cataloged, documented, classified, lineage, aiReady)", generic=False, binding_note="Fixed 5-stage readiness definition baked into the function body -- not a parameter.", @@ -932,7 +942,8 @@ def _always_applies(what: str) -> str: "the fact. First real implementation of the composite/derived analytic metric " "pattern -- see NEXT-18 (egeria-workspaces BACKLOG.md) for why this pattern didn't " "exist here before. Takes two leading clients (mgr, ce), same convention as " - "semantic_grounding/context_readiness_funnel.", + "semantic_grounding/context_readiness_funnel. " + "Cost: one capped Asset find plus one capped DataFlow relationship page, seconds.", returns="dict (aiReadyCount, total, capped)", generic=False, binding_note="Fixed to governed+documented+lineage-traced over Asset elements -- not a parameter.", @@ -1014,7 +1025,8 @@ def _always_applies(what: str) -> str: function="pyegeria.view.overview_metrics.growth_series", description="Snapshot-based growth series (assets/terms/governed/products by default) via " "asOfTime, one point per window step. The one shape SERIES output format " - "(a Vega-Lite line chart) is proven against today.", + "(a Vega-Lite line chart) is proven against today. " + "Cost: one count per series per snapshot (four series by default), seconds to tens of seconds.", returns="list[dict] (time series: {label, date, : count, ...})", generic=True, binding_note="type_map defaults to assets/terms/governed/products but is fully overridable.", @@ -1026,24 +1038,76 @@ def _always_applies(what: str) -> str: AnalyticParam(name="type_map", type="list[tuple[str, str, list[str] | None]]", description="Override which series to snapshot; defaults to assets/terms/governed/products."), ], + declaration=AnalyticDeclaration( + result_kind="series", + # One row per snapshot, oldest first; the measures are the default type_map's keys. + measures=[ + _measure("assets", "Assets", "assets", as_of="date"), + _measure("terms", "GlossaryTerm elements", "terms", as_of="date"), + _measure("governed", "elements of any type carrying a governance classification", + "governed", as_of="date"), + _measure("products", "DigitalProduct elements", "products", as_of="date"), + ], + absence=_absence( + not_measured="The growth series was not measured: the snapshot counts failed.", + not_permitted="You are not permitted to count these elements, so the growth series " + "was not measured.", + not_applicable="A growth series does not apply to this window: it needs at least two " + "snapshots.", + nothing_found="Counted: there were no elements of these types at any snapshot in the window.", + ), + out=[ + _field("label", "Snapshot", "string"), + _field("date", "Date", "string"), + _field("assets", "Assets", "int", unit="Assets"), + _field("terms", "Terms", "int", unit="elements"), + _field("governed", "Governed", "int", unit="elements"), + _field("products", "Products", "int", unit="elements"), + ], + ), ), "term_definition_completeness": AnalyticFunctionSpec( name="term_definition_completeness", function="pyegeria.view.overview_metrics.term_definition_completeness", description="Share of GlossaryTerms carrying a non-empty description -- a definitions-" "coverage metric, distinct from semantic_grounding (term<->asset linkage, not " - "whether the term itself is actually defined).", + "whether the term itself is actually defined). " + "Cost: one capped find, seconds.", returns="dict (total, defined, undefinedPct)", generic=False, binding_note="Fixed to GlossaryTerm's description property -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + # One capped find; the result carries no flag saying the page cap was reached. + measures=[ + _measure("terms_read", "GlossaryTerm elements, among those one capped find returned", "total", + population="viewer"), + _measure("defined_terms", "GlossaryTerm elements with a description", "defined", + population="viewer", basis=_basis("total", "terms read")), + _measure("undefined_percent", "percent of terms read without a description (0-100)", + "undefinedPct"), + ], + absence=_absence( + not_measured="Term definitions were not measured: the find of glossary terms failed.", + not_permitted="You are not permitted to read the glossary terms.", + not_applicable=_always_applies("Term definition completeness"), + nothing_found="Read: there are no active glossary terms.", + ), + out=[ + _field("total", "Terms read", "int", unit="elements"), + _field("defined", "Defined", "int", unit="elements"), + _field("undefinedPct", "Undefined", "int", unit="percent"), + ], + ), ), "active_contributors": AnalyticFunctionSpec( name="active_contributors", function="pyegeria.view.overview_metrics.active_contributors", description="Distinct usernames behind at least one feedback relationship (ratings/comments/" "likes/tags/noteLogs) -- an engagement signal feedback_summary's raw relationship " - "counts don't give you (one prolific commenter vs. many occasional ones).", + "counts don't give you (one prolific commenter vs. many occasional ones). " + "Cost: five capped relationship pages, seconds.", returns="dict (contributors, byType)", generic=False, binding_note="Fixed to Collaboration OMAS's feedback relationship types -- not a parameter.", @@ -1084,7 +1148,8 @@ def _always_applies(what: str) -> str: "counts_by_type itself (already registered above, reused as-is), analytic is a " "small sum-reducer over its result; `function` above is the thin composite " "wrapper that runs both via run_analytic_action, so calling it directly (the " - "old, single-function path) still works exactly like every other entry here.", + "old, single-function path) still works exactly like every other entry here. " + "Cost: as counts_by_type: one native count per type.", returns="dict (total, byType)", generic=True, action=AnalyticActionSpec( @@ -1122,7 +1187,8 @@ def _always_applies(what: str) -> str: description="Count active elements of a given type whose named string property equals a " "given value -- e.g. DigitalProduct elements with deploymentStatus=ACTIVE. Same " "native-count-with-fallback seam as count_elements, one cheap native COUNT call " - "per distinct value, no element fetch.", + "per distinct value, no element fetch. " + "Cost: one native count, sub-second in the repository population; a viewer-population count can take minutes for a large type.", returns="scalar (int)", generic=True, params=[ @@ -1188,7 +1254,8 @@ def _always_applies(what: str) -> str: "an ISC/blueprint' metric -- confirms some solution-design context exists, not " "that the specific SolutionComponent is itself wired into an ISC/blueprint (a " "second hop this function doesn't take). Takes two leading clients (mgr, ce), " - "same convention as semantic_grounding.", + "same convention as semantic_grounding. " + "Cost: one capped relationship page plus one count, seconds.", returns="dict (contextualisedCount, assetTotal, contextualisedPct)", generic=False, binding_note="Fixed to the ImplementedBy relationship, filtered to Asset-subtype ends -- not a parameter.", @@ -1252,7 +1319,8 @@ def _always_applies(what: str) -> str: function="pyegeria.view.overview_metrics.karma_leaderboard", description="Top-N people by karma -- one bounded ContributionRecord fetch, karmaPoints is a " "scalar property on the record itself (not derived from counting related things), " - "filtered to the given anchor type(s) via each record's own Anchors classification.", + "filtered to the given anchor type(s) via each record's own Anchors classification. " + "Cost: one capped find, seconds.", returns="list[dict] (name, karmaPoints, anchorGuid, anchorType), longest-karma first", generic=False, binding_note="Fixed to ContributionRecord.karmaPoints -- top_n and anchor_types tune the " @@ -1291,7 +1359,8 @@ def _always_applies(what: str) -> str: description="Weekly-bucketed feedback-event trend (comments/ratings/likes/tags/noteLogs), " "zero-filled across the trailing window -- reuses the same 5 relationship-type " "queries feedback_summary() already makes, keeping createTime instead of only " - "the count. Takes ce as its leading client.", + "the count. Takes ce as its leading client. " + "Cost: five capped relationship pages, seconds.", returns="list[dict] (week, comments, ratings, likes, tags, noteLogs, total), oldest week first", generic=False, binding_note="Fixed to Collaboration OMAS's 5 feedback relationship types -- weeks tunes the window, not what's measured.", @@ -1299,6 +1368,39 @@ def _always_applies(what: str) -> str: AnalyticParam(name="weeks", type="int", default=12, description="Trailing window size, in weeks."), _as_of(), ], + declaration=AnalyticDeclaration( + result_kind="series", + # One row per ISO week, oldest first, zero-filled; each type is one capped relationship page. + measures=[ + _measure("feedback", "feedback relationships created in the week", "total", as_of="week", + population="viewer"), + _measure("comments", "AttachedComment relationships created in the week", "comments", + as_of="week", population="viewer"), + _measure("ratings", "AttachedRating relationships created in the week", "ratings", + as_of="week", population="viewer"), + _measure("likes", "AttachedLike relationships created in the week", "likes", + as_of="week", population="viewer"), + _measure("tags", "AttachedTag relationships created in the week", "tags", + as_of="week", population="viewer"), + _measure("note_logs", "AttachedNoteLog relationships created in the week", "noteLogs", + as_of="week", population="viewer"), + ], + absence=_absence( + not_measured="Engagement was not measured: the feedback relationship queries failed.", + not_permitted="You are not permitted to read feedback relationships.", + not_applicable="An engagement series does not apply to a window of no weeks.", + nothing_found="Counted: no feedback was attached in any week of the window.", + ), + out=[ + _field("week", "Week", "string"), + _field("comments", "Comments", "int", unit="relationships"), + _field("ratings", "Ratings", "int", unit="relationships"), + _field("likes", "Likes", "int", unit="relationships"), + _field("tags", "Tags", "int", unit="relationships"), + _field("noteLogs", "Note logs", "int", unit="relationships"), + _field("total", "Total", "int", unit="relationships"), + ], + ), ), "orphan_glossary_terms": AnalyticFunctionSpec( name="orphan_glossary_terms", @@ -1307,18 +1409,42 @@ def _always_applies(what: str) -> str: "relationship to anything was authored but never put to use grounding the " "catalog. One bounded SemanticAssignment fetch, distinct GlossaryTerm-end GUID " "count is the 'referenced' set; orphan = term total - referenced. Takes two " - "leading clients (mgr, ce), same convention as semantic_grounding.", + "leading clients (mgr, ce), same convention as semantic_grounding. " + "Cost: one count plus one capped relationship page, seconds.", returns="dict (termTotal, referencedCount, orphanCount)", generic=False, binding_note="Fixed to the SemanticAssignment relationship type and GlossaryTerm elements -- not a parameter.", params=[_as_of()], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[ + _measure("terms", "GlossaryTerm elements", "termTotal"), + _measure("referenced_terms", "GlossaryTerm elements assigned to something", "referencedCount", + population="viewer"), + _measure("orphan_terms", "GlossaryTerm elements assigned to nothing", "orphanCount", + basis=_basis("termTotal", "glossary terms")), + ], + absence=_absence( + not_measured="Orphan terms were not measured: the term count or the SemanticAssignment " + "query failed.", + not_permitted="You are not permitted to read the glossary terms or their assignments.", + not_applicable=_always_applies("Finding orphan glossary terms"), + nothing_found="Counted: every glossary term is assigned to something, or there are no terms.", + ), + out=[ + _field("termTotal", "Terms", "int", unit="elements"), + _field("referencedCount", "Assigned", "int", unit="elements"), + _field("orphanCount", "Orphans", "int", unit="elements"), + ], + ), ), "stale_assets": AnalyticFunctionSpec( name="stale_assets", function="pyegeria.view.overview_metrics.stale_assets", description="Assets with no update in the last N days (default 180) -- candidates for " "archival review. One bounded Asset element fetch, each element's own version " - "metadata compared against the cutoff, no relationship traversal.", + "metadata compared against the cutoff, no relationship traversal. " + "Cost: one capped Asset find plus one count, seconds.", returns="dict (staleCount, assetTotal)", generic=False, binding_note="Fixed to the Asset type -- population isn't a parameter, but the staleness threshold (days) is.", @@ -1326,6 +1452,25 @@ def _always_applies(what: str) -> str: AnalyticParam(name="days", type="int", default=180, description="Staleness threshold, in days."), _as_of(), ], + declaration=AnalyticDeclaration( + result_kind="measure", + # staleCount comes from one capped find, assetTotal from a native count: no basis between them. + measures=[ + _measure("stale_assets", "Assets not updated within `days`, among those one capped find returned", + "staleCount", population="viewer"), + _measure("assets", "Assets", "assetTotal"), + ], + absence=_absence( + not_measured="Stale assets were not measured: the Asset find failed.", + not_permitted="You are not permitted to read the Assets.", + not_applicable=_always_applies("Finding stale assets"), + nothing_found="Checked: every Asset read was updated within the threshold, or there are no Assets.", + ), + out=[ + _field("staleCount", "Stale Assets", "int", unit="Assets"), + _field("assetTotal", "Assets", "int", unit="Assets"), + ], + ), ), "metric_trend": AnalyticFunctionSpec( name="metric_trend", @@ -1334,7 +1479,8 @@ def _always_applies(what: str) -> str: "re-calling it once per asOfTime snapshot -- the same windowing growth_series " "uses, generalized to any function here instead of one hardcoded type_map. Takes " "two leading clients (mgr, ce) -- the executor supplies the same EgeriaTech " - "instance for both, matching semantic_grounding's convention.", + "instance for both, matching semantic_grounding's convention. " + "Cost: the target routine's cost once per snapshot.", returns="list[dict] (time series: {label, date, **snapshot})", generic=True, params=[ @@ -1349,6 +1495,23 @@ def _always_applies(what: str) -> str: description="Extra keyword arguments forwarded to the target function at " "every snapshot (e.g. classifications for count_elements)."), ], + declaration=AnalyticDeclaration( + result_kind="series", + # A row is the target routine's own result fields (a dict merged in) or `value` (anything + # else); the target's declaration says what those fields are. + measures=[_measure("value", "the target routine's unit", "value", as_of="date")], + absence=_absence( + not_measured="The trend was not measured: the target routine failed at every snapshot.", + not_permitted="You are not permitted to run the target routine, so the trend was not measured.", + not_applicable="A trend does not apply: the target routine does not take an as_of time.", + nothing_found="Measured: the target routine found nothing at any snapshot in the window.", + ), + out=[ + _field("label", "Snapshot", "string"), + _field("date", "Date", "string"), + _field("value", "Value", "float"), + ], + ), ), "asset_composition": AnalyticFunctionSpec( name="asset_composition", @@ -1359,7 +1522,8 @@ def _always_applies(what: str) -> str: "repository - viewer. Stages (reporting model §10.8): a `typedefs` producer, two " "per-row `derive`s (viewer count, repository count) and a `difference`. All counts " "share one pool of `concurrency` workers (default 3, capped at 5). Takes two " - "leading clients (mgr, vm); vm defaults to mgr (an EgeriaTech has both).", + "leading clients (mgr, vm); vm defaults to mgr (an EgeriaTech has both). " + "Cost: one count per type per population in a pool of 3-5; repository counts sub-second, viewer counts can take minutes for a large type (Process: 120 s).", returns="AssetComposition (dict: state, state_reason, root, depth, populations, as_of, concurrency, " "rows[{type_name, parent, level, exact_type, subtypes_error, viewer?, repository?, " "not_visible}], not_measured, provenance); each count cell is {value, state, " @@ -1417,7 +1581,8 @@ def _always_applies(what: str) -> str: name="control_implementation_summary", function="pyegeria.view.overview_metrics.control_implementation_summary", description="Applicable controls in a statement of applicability, counted by implementation " - "status (NOT_STARTED, PLANNED, PARTIALLY_IMPLEMENTED, IMPLEMENTED, OTHER).", + "status (NOT_STARTED, PLANNED, PARTIALLY_IMPLEMENTED, IMPLEMENTED, OTHER). " + "Cost: one read of one statement of applicability's control relationships, seconds.", returns="dict ({status: count})", generic=False, binding_note="Fixed to the ControlApplicability relationships of one StatementOfApplicability.", @@ -1425,6 +1590,26 @@ def _always_applies(what: str) -> str: AnalyticParam(name="soa_guid", type="str", required=True, description="GUID of the statement of applicability."), ], + declaration=AnalyticDeclaration( + result_kind="distribution", + # No as_of parameter: the counts are of the moment the call ran. + measures=[_measure(status.lower(), "applicable controls", status) + for status in ("NOT_STARTED", "PLANNED", "PARTIALLY_IMPLEMENTED", "IMPLEMENTED", "OTHER")], + # One control has one implementation status; controls marked not applicable are left out. + categories=CategoriesDeclaration(exclusive=True), + absence=_absence( + not_measured="Control implementation was not measured: the statement of applicability " + "could not be read.", + not_permitted="You are not permitted to read this statement of applicability.", + not_applicable="Control implementation does not apply: the element named is not a " + "statement of applicability.", + nothing_found="Counted: this statement of applicability has no applicable controls.", + ), + out=[_field(status, label, "int", unit="controls") for status, label in ( + ("NOT_STARTED", "Not started"), ("PLANNED", "Planned"), + ("PARTIALLY_IMPLEMENTED", "Partially implemented"), ("IMPLEMENTED", "Implemented"), + ("OTHER", "Other"))], + ), ), } diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index ef305b5a..b8efef0c 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -914,7 +914,7 @@ def stale_assets(mgr, as_of: Optional[str] = None, days: int = 180) -> Dict[str, anchoring). Returns {"staleCount": int|None, "assetTotal": int|None}. `staleCount` - is None on total failure; `assetTotal` reuses `count_elements` (native, + is None when the Asset find fails (not 0); `assetTotal` reuses `count_elements` (native, unaffected by this function's own element-fetch cap). """ from datetime import datetime, timezone, timedelta @@ -928,9 +928,9 @@ def stale_assets(mgr, as_of: Optional[str] = None, days: int = 180) -> Dict[str, body = {"class": "FindRequestBody", "metadataElementTypeName": "Asset", "limitResultsByStatus": ["ACTIVE"]} if as_of: body["asOfTime"] = as_of - elements = _find(mgr, body) - stale_count = 0 - for el in elements: + elements = _find_or_none(mgr, body) # None when the find failed: staleCount stays None, not 0 + stale_count = None if elements is None else 0 + for el in elements or []: updated = _update_time(el) if updated is not None and updated < cutoff: stale_count += 1 @@ -1764,16 +1764,19 @@ def term_definition_completeness(mgr, as_of: Optional[str] = None) -> Dict[str, output_format='JSON' relationship/report path other functions here use, e.g. `certifications_summary`'s `end2`, not this raw element-query path). - Returns {"total": int, "defined": int, "undefinedPct": int|None} + Returns {"total": int|None, "defined": int|None, "undefinedPct": int|None} (`undefinedPct` mirrors `semantic_grounding.groundingPct`'s naming: the gap, not the coverage, since a near-100%-defined glossary is the - uninteresting case and the gap is what's actionable). + uninteresting case and the gap is what's actionable). A failed find makes + all three None -- unmeasured, not an empty glossary. """ body: Dict[str, Any] = {"class": "FindRequestBody", "limitResultsByStatus": ["ACTIVE"], "metadataElementTypeName": "GlossaryTerm"} if as_of: body["asOfTime"] = as_of - terms = _find(mgr, body) + terms = _find_or_none(mgr, body) + if terms is None: + return {"total": None, "defined": None, "undefinedPct": None} total = len(terms) defined = 0 for t in terms: diff --git a/tests/micro-tests/test_issue_170_analytic_declaration.py b/tests/micro-tests/test_issue_170_analytic_declaration.py index a6ee86e7..a4349fe5 100644 --- a/tests/micro-tests/test_issue_170_analytic_declaration.py +++ b/tests/micro-tests/test_issue_170_analytic_declaration.py @@ -29,20 +29,11 @@ } -#: Built-ins that declare their results (RS-W1-4 added the first); every other spec -#: still loads with no declaration -- the field stays optional. -DECLARED_BUILTINS = {"asset_composition", "count_elements", "count_elements_by_property", "count_relationships", - "counts_by_type", "sum_type_counts", "governed_coverage", "ownership_coverage", - "business_value_signals", "certifications_summary", "semantic_grounding", "people_counts", "feedback_summary", - "usage_context_counts", "active_contributors", "karma_leaderboard", "context_readiness_funnel", - "ai_ready_assets", "drl_readiness_gates", "contextualised_coverage", - "solution_component_realisation"} - - -def test_existing_specs_load_without_a_declaration(): - registry = get_analytic_registry() - assert all(spec.declaration is None for name, spec in registry.items() if name not in DECLARED_BUILTINS) - assert all(registry[name].declaration is not None for name in DECLARED_BUILTINS) +def test_every_builtin_declares_its_results(): + """RS-W2-1a: every built-in now declares (asset_composition was the first, RS-W1-4); the field + itself stays optional for specs registered by others.""" + assert all(spec.declaration is not None for spec in get_analytic_registry().values()) + assert AnalyticFunctionSpec(name="x", function="pyegeria.view.overview_metrics.growth_series").declaration is None def test_declaration_round_trips_on_a_spec(): diff --git a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py index a2663538..c17d35a1 100644 --- a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py +++ b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py @@ -120,3 +120,178 @@ def test_drl_lineage_failure_keeps_the_asset_population(): result = om.drl_readiness_gates(mgr, ce) assert (result["total"], result["aiReadyCount"], result["aiReadyRecentCount"]) == (1, None, None) assert sum(result["byModality"].values()) == 1 + + +def test_stale_and_term_routines_failure_is_unmeasured(): + from pyegeria.view import overview_metrics as om + mgr, _ = _failing_clients() + assert om.stale_assets(mgr)["staleCount"] is None + assert om.term_definition_completeness(mgr) == {"total": None, "defined": None, "undefinedPct": None} + + +# ── the census: every registered routine is declared, and its declaration is true of its result ── + +from pyegeria.view import overview_metrics as om # noqa: E402 +from pyegeria.view.analytic_registry import ( # noqa: E402 + ABSENCE_STATES, + LEGACY_NOTHING_FOUND, + ROW_SHAPES, + get_analytic_registry, +) + +BUILTINS = get_analytic_registry() +AS_OF = "2026-10-01T00:00:00+00:00" + + +def test_every_registry_entry_is_declared(): + undeclared = sorted(name for name, spec in BUILTINS.items() if spec.declaration is None) + assert undeclared == [] + + +def test_the_three_overview_routines_are_registered(): + """D6: the Overview depends on these, so they are routines, registered and declared.""" + for name in ("count_relationships", "drl_readiness_gates", "solution_component_realisation"): + assert BUILTINS[name].function == f"pyegeria.view.overview_metrics.{name}" + + +@pytest.mark.parametrize("name", sorted(BUILTINS)) +def test_absence_sentences_use_the_four_words(name): + absence = BUILTINS[name].declaration.absence + dumped = absence.model_dump() + assert set(dumped) == set(ABSENCE_STATES) + assert LEGACY_NOTHING_FOUND not in dumped + assert all(s.strip() and s.strip()[-1] in ".:" for s in dumped.values()) + assert len(set(dumped.values())) == 4, "each absence says something different" + + +@pytest.mark.parametrize("name", sorted(BUILTINS)) +def test_kind_blocks_out_fields_and_shapes(name): + decl = BUILTINS[name].declaration + assert decl.out, "every routine lists its out fields" + if decl.result_kind in ("distribution", "graph"): + assert decl.categories is not None + if decl.result_kind == "list": + assert decl.listing is not None + for f in decl.out: + if f.kind == "dataset": + assert f.shape in ROW_SHAPES + names = [m.name for m in decl.measures] + assert len(names) == len(set(names)) + assert not any(m.population and m.population not in ("viewer", "repository") for m in decl.measures) + + +# Fixtures: a client with no native count (so counts fall back to the find) that answers +# every find with three Assets and every relationship query with one relationship. + +def _asset(guid, desc=None, cls=(), upd="2026-09-01T00:00:00+00:00"): + pvm = {"displayName": {"primitiveValue": f"Contribution record for {guid}"}, + "karmaPoints": {"primitiveValue": 7}} + if desc: + pvm["description"] = {"primitiveValue": desc} + classifications = [{"classificationName": c} for c in cls] + [{ + "classificationName": "Anchors", "classificationProperties": {"propertyValueMap": { + "anchorTypeName": {"primitiveValue": "Person"}, "anchorGUID": {"primitiveValue": f"p-{guid}"}}}}] + return {"elementGUID": guid, "elementProperties": {"propertyValueMap": pvm}, "classifications": classifications, + "type": {"typeName": "CSVFile", "superTypeNames": ["DataFile", "Asset"]}, + "elementHeader": {"versions": {"updateTime": upd}}} + + +_REL = {"end1": {"guid": "sc1", "type": {"typeName": "SolutionComponent"}}, + "end2": {"guid": "a1", "type": {"typeName": "CSVFile", "superTypeNames": ["Asset", "GlossaryTerm"]}}, + "relationshipHeader": {"versions": {"createTime": "2026-09-28T00:00:00+00:00", "createdBy": "erin"}}} + + +class _NoSubtypes: + def get_sub_types(self, type_name, **_): + return "No elements found" + + +def _clients(): + from unittest.mock import MagicMock + mgr = MagicMock(spec=["platform_url", "view_server", "find_metadata_elements", + "get_control_implementation_summary"]) + mgr.platform_url, mgr.view_server = "https://localhost:9443", "test-server" + mgr.find_metadata_elements.return_value = [_asset("a1", "d", ["Confidentiality", "ZoneMembership"]), + _asset("a2"), _asset("a3", "d", upd="2025-01-01T00:00:00+00:00")] + mgr.get_control_implementation_summary.return_value = {"byStatus": { + "NOT_STARTED": 1, "PLANNED": 0, "PARTIALLY_IMPLEMENTED": 0, "IMPLEMENTED": 2, "OTHER": 0}} + ce = MagicMock(spec=["get_relationships"]) + ce.get_relationships.return_value = [_REL] + return mgr, ce + + +CALLS = { + "count_elements": lambda m, c: om.count_elements(m, "Asset"), + "count_elements_by_property": lambda m, c: om.count_elements_by_property(m, "Asset", "name", "x"), + "count_relationships": lambda m, c: om.count_relationships(c, "SemanticAssignment"), + "counts_by_type": lambda m, c: om.counts_by_type(m, [("Files", "CSVFile")]), + "sum_type_counts": lambda m, c: om.sum_type_counts(m, [("Files", "CSVFile")]), + "governed_coverage": lambda m, c: om.governed_coverage(m), + "ownership_coverage": lambda m, c: om.ownership_coverage(m), + "business_value_signals": lambda m, c: om.business_value_signals(m), + "certifications_summary": lambda m, c: om.certifications_summary(c, AS_OF), + "semantic_grounding": lambda m, c: om.semantic_grounding(m, c), + "people_counts": lambda m, c: om.people_counts(m), + "feedback_summary": lambda m, c: om.feedback_summary(c), + "usage_context_counts": lambda m, c: om.usage_context_counts(m), + "active_contributors": lambda m, c: om.active_contributors(c), + "karma_leaderboard": lambda m, c: om.karma_leaderboard(m), + "context_readiness_funnel": lambda m, c: om.context_readiness_funnel(m, c), + "ai_ready_assets": lambda m, c: om.ai_ready_assets(m, c), + "drl_readiness_gates": lambda m, c: om.drl_readiness_gates(m, c, AS_OF), + "contextualised_coverage": lambda m, c: om.contextualised_coverage(m, c), + "solution_component_realisation": lambda m, c: om.solution_component_realisation(m, c), + "growth_series": lambda m, c: om.growth_series(m, window="7d", points=3), + "engagement_series": lambda m, c: om.engagement_series(c, AS_OF, weeks=3), + "metric_trend": lambda m, c: om.metric_trend(m, c, "count_elements", window="7d", points=2, + metric_params={"type_name": "Asset"}), + "term_definition_completeness": lambda m, c: om.term_definition_completeness(m), + "orphan_glossary_terms": lambda m, c: om.orphan_glossary_terms(m, c), + "stale_assets": lambda m, c: om.stale_assets(m, AS_OF), + "control_implementation_summary": lambda m, c: om.control_implementation_summary(m, "soa"), + "asset_composition": lambda m, c: om.asset_composition(m, _NoSubtypes(), depth=0), +} + +_MISSING = object() + + +def _resolve(value, path: str): + """A declared field path against a result: dotted for nested, applied to every row of a list. + A bare-number result answers the path `value`.""" + if not isinstance(value, (dict, list)): + return value if path == "value" else _MISSING + head, _, rest = path.partition(".") + if isinstance(value, list): + found = [_resolve(row, path) for row in value] + return _MISSING if not found or _MISSING in found else found + if head not in value: + return _MISSING + return _resolve(value[head], rest) if rest else value[head] + + +def test_calls_cover_the_registry(): + assert set(CALLS) == set(BUILTINS) + + +@pytest.mark.parametrize("name", sorted(CALLS)) +def test_declared_value_fields_exist(name): + om._count_caps.clear() + om._native_server_ok.clear() + mgr, ce = _clients() + if name == "asset_composition": # counts strictly: give it a native count to answer with + mgr = __import__("unittest.mock", fromlist=["MagicMock"]).MagicMock( + spec=["platform_url", "view_server", "count_metadata_elements"]) + mgr.platform_url, mgr.view_server = "https://localhost:9443", "test-server" + mgr.count_metadata_elements.return_value = {"count": 5} + result = CALLS[name](mgr, ce) + decl = BUILTINS[name].declaration + for m in decl.measures: + for path in (m.value_field, m.completeness_field, m.basis.denominator_field if m.basis else ""): + if path: + assert _resolve(result, path) is not _MISSING, f"{name}: {path} not in the result" + if not m.as_of.startswith("run."): + assert _resolve(result, m.as_of) is not _MISSING, f"{name}: as_of {m.as_of} not in the result" + rows = result if isinstance(result, list) else [result] + for f in decl.out: + if isinstance(rows[0], dict): + assert all(f.name in r for r in rows), f"{name}: out field {f.name} not in the result"