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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
992 changes: 957 additions & 35 deletions pyegeria/view/analytic_registry.py

Large diffs are not rendered by default.

83 changes: 56 additions & 27 deletions pyegeria/view/overview_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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:
Expand Down Expand Up @@ -909,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
Expand All @@ -923,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
Expand Down Expand Up @@ -996,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():
Expand Down Expand Up @@ -1050,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(
Expand All @@ -1074,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:
Expand Down Expand Up @@ -1170,18 +1183,23 @@ 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

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 {"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(
Expand All @@ -1194,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:
Expand All @@ -1211,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
Expand All @@ -1223,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,
}

Expand Down Expand Up @@ -1745,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:
Expand Down Expand Up @@ -1789,6 +1811,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

Expand All @@ -1801,17 +1827,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]:
Expand Down
71 changes: 71 additions & 0 deletions tests/micro-tests/test_declarations_match_library.py
Original file line number Diff line number Diff line change
@@ -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])})
14 changes: 5 additions & 9 deletions tests/micro-tests/test_issue_170_analytic_declaration.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +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"}


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():
Expand Down
12 changes: 7 additions & 5 deletions tests/micro-tests/test_overview_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,16 +320,16 @@ 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"]),
]
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


Expand Down Expand Up @@ -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 ──────────────────────────────────────────────────────────
Expand Down
Loading
Loading