diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 7f6fea54..3d0c2c0e 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -637,7 +637,7 @@ def _strict() -> AnalyticParam: "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).", - returns="AssetComposition (dict: state, state_reason, root, depth, scopes, as_of, concurrency, " + 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, " "completeness, as_of, population, reason, elapsed_s}", @@ -649,7 +649,7 @@ def _strict() -> AnalyticParam: AnalyticParam(name="depth", type="int", default=2, description="Subtype levels below root (0 = root only)."), _as_of("ISO-8601 asOfTime for point-in-time counts (None = now); the subtype tree is today's."), - AnalyticParam(name="scopes", type="list[str]", default=["viewer", "repository"], + AnalyticParam(name="populations", type="list[str]", default=["viewer", "repository"], description="Populations to count: viewer (what the caller may see) and/or " "repository (whole repository, fast). Each cell names its " "population under `population`."), diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index 18c16cef..976412ab 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -24,8 +24,10 @@ for the original inline versions this was extracted from. """ +import functools import inspect import time +import warnings from concurrent.futures import ThreadPoolExecutor, as_completed from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, TypedDict @@ -255,6 +257,33 @@ def _find_or_none(mgr, body: dict, page_size: int = DEFAULT_CAP) -> Optional[lis SCOPE_REPOSITORY = "repository" +def _population_keyword(fn): + """Accept `population=` ("viewer" | "repository"), the owner's word (RS-W1-1 §5, 2026-11-06), as the + count helpers' keyword. `scope=` still works as a deprecated alias: `scope` already means result level + (resource, container, member, field) in the declaration model, so the population word must not reuse it. + Passing both with different values is a ValueError.""" + sig = inspect.signature(fn) + params = list(sig.parameters.values()) + [ + inspect.Parameter("population", inspect.Parameter.KEYWORD_ONLY, default=None, annotation=Optional[str])] + + @functools.wraps(fn) + def wrapper(*args, population: Optional[str] = None, **kwargs): + scope = kwargs.get("scope") + if scope is not None: + if population is not None and population != scope: + raise ValueError(f"{fn.__name__}: population={population!r} and scope={scope!r} disagree; " + f"pass population= only") + if population is None: + warnings.warn(f"{fn.__name__}(scope=...) is deprecated; use population=", + DeprecationWarning, stacklevel=2) + if population is not None: + kwargs["scope"] = population + return fn(*args, **kwargs) + + wrapper.__signature__ = sig.replace(parameters=params) + return wrapper + + def _push_down(scope: Optional[str]) -> Optional[bool]: """Map a count scope to the native `push_down` argument: "viewer" -> False (server counts only what the caller may see), "repository" -> True (a raw @@ -316,6 +345,7 @@ def _element_count(mgr, body: dict, as_of: Optional[str] = None, strict: bool = return len(found) +@_population_keyword def count_elements( mgr, type_name: Optional[str] = None, @@ -363,6 +393,7 @@ def count_elements( return _element_count(mgr, body, as_of, strict, scope) +@_population_keyword def count_elements_by_property( mgr, type_name: str, @@ -412,6 +443,7 @@ def count_elements_by_property( return _element_count(mgr, body, as_of, strict, scope) +@_population_keyword def count_relationships(ce, relationship_type: str, as_of: Optional[str] = None, expert=None, scope: Optional[str] = None) -> Optional[int]: """ @@ -472,6 +504,7 @@ def count_relationships(ce, relationship_type: str, as_of: Optional[str] = None, return None +@_population_keyword def counts_by_type(mgr, type_map: Sequence[Tuple[str, str]], as_of: Optional[str] = None, strict: bool = False, scope: Optional[str] = None) -> List[Dict[str, Any]]: """ @@ -483,7 +516,7 @@ def counts_by_type(mgr, type_map: Sequence[Tuple[str, str]], as_of: Optional[str Returns a list of {"label": ..., "type": ..., "count": ...} dicts, in the order given. """ - return [{"label": label, "type": type_name, "count": count_elements(mgr, type_name, as_of, strict=strict, scope=scope)} + return [{"label": label, "type": type_name, "count": count_elements(mgr, type_name, as_of, strict=strict, population=scope)} for label, type_name in type_map] @@ -671,6 +704,7 @@ def ownership_coverage(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: } +@_population_keyword def business_value_signals(mgr, as_of: Optional[str] = None, scope: Optional[str] = None) -> Dict[str, Any]: """ Real signals behind the Overview dashboard's four "Business Value" tiles @@ -736,7 +770,7 @@ def business_value_signals(mgr, as_of: Optional[str] = None, scope: Optional[str if isinstance(desc, str) and desc.strip(): described += 1 - duplicate = count_elements(mgr, None, as_of, classifications=["ConsolidatedDuplicate"], strict=True, scope=scope) + duplicate = count_elements(mgr, None, as_of, classifications=["ConsolidatedDuplicate"], strict=True, population=scope) return { "assetTotal": len(assets) if assets is not None else None, @@ -1209,6 +1243,7 @@ def _update_time(el: dict): return None +@_population_keyword def people_counts(mgr, as_of: Optional[str] = None, strict: bool = False, scope: Optional[str] = None) -> Dict[str, Optional[int]]: """ Person / Team / Organization / ITProfile / Community counts via native @@ -1223,11 +1258,11 @@ def people_counts(mgr, as_of: Optional[str] = None, strict: bool = False, scope: could not be measured is None (see count_elements). """ return { - "persons": count_elements(mgr, "Person", as_of, strict=strict, scope=scope), - "teams": count_elements(mgr, "Team", as_of, strict=strict, scope=scope), - "organizations": count_elements(mgr, "Organization", as_of, strict=strict, scope=scope), - "itProfiles": count_elements(mgr, "ITProfile", as_of, strict=strict, scope=scope), - "communities": count_elements(mgr, "Community", as_of, strict=strict, scope=scope), + "persons": count_elements(mgr, "Person", as_of, strict=strict, population=scope), + "teams": count_elements(mgr, "Team", as_of, strict=strict, population=scope), + "organizations": count_elements(mgr, "Organization", as_of, strict=strict, population=scope), + "itProfiles": count_elements(mgr, "ITProfile", as_of, strict=strict, population=scope), + "communities": count_elements(mgr, "Community", as_of, strict=strict, population=scope), } @@ -1240,6 +1275,7 @@ def people_counts(mgr, as_of: Optional[str] = None, strict: bool = False, scope: ) +@_population_keyword def feedback_summary(ce, as_of: Optional[str] = None, scope: Optional[str] = None, expert=None) -> Dict[str, Any]: """ Crowd-sourced feedback tally -- ratings/comments/likes/tags/note-logs @@ -1256,11 +1292,12 @@ def feedback_summary(ce, as_of: Optional[str] = None, scope: Optional[str] = Non Returns {"byType": {ratings, comments, likes, tags, noteLogs: int|None}, "total": int|None}. """ - by_type = {key: count_relationships(ce, rel, as_of, expert=expert, scope=scope) for rel, key in _FEEDBACK_RELATIONSHIP_TYPES} + by_type = {key: count_relationships(ce, rel, as_of, expert=expert, population=scope) for rel, key in _FEEDBACK_RELATIONSHIP_TYPES} measured = all(v is not None for v in by_type.values()) return {"byType": by_type, "total": sum(by_type.values()) if measured else None} +@_population_keyword def usage_context_counts(mgr, as_of: Optional[str] = None, strict: bool = False, scope: Optional[str] = None) -> Dict[str, Optional[int]]: """ InformationSupplyChain and SolutionBlueprint counts -- what puts assets @@ -1271,8 +1308,8 @@ def usage_context_counts(mgr, as_of: Optional[str] = None, strict: bool = False, strict=True, a count that could not be measured is None (see count_elements). """ return { - "informationSupplyChains": count_elements(mgr, "InformationSupplyChain", as_of, strict=strict, scope=scope), - "blueprints": count_elements(mgr, "SolutionBlueprint", as_of, strict=strict, scope=scope), + "informationSupplyChains": count_elements(mgr, "InformationSupplyChain", as_of, strict=strict, population=scope), + "blueprints": count_elements(mgr, "SolutionBlueprint", as_of, strict=strict, population=scope), } @@ -1811,8 +1848,8 @@ def control_implementation_summary(client, soa_guid: str) -> Dict[str, int]: # parent's `other` row = parent - sum(children). #: The cell's word for which population was counted ("viewer" | "repository"). The -#: owner chose `population` (RS-W1-1 §5); the routine's keyword stays `scopes=` and -#: count_elements' keyword stays `scope=`. +#: owner chose `population` (RS-W1-1 §5). The keywords are `populations=` (asset_composition) and +#: `population=` (the count helpers); `scopes=` / `scope=` remain as deprecated aliases. POPULATION_WORD = "population" #: Cell and row states. A 0 is nothing_found; a failure is not_measured, never 0. @@ -1943,7 +1980,7 @@ def _count_cell(mgr, type_name: str, as_of: Optional[str], scope: str, stamp: st started = time.monotonic() reason = "" try: - value = count_elements(mgr, type_name, as_of, strict=True, scope=scope) + value = count_elements(mgr, type_name, as_of, strict=True, population=scope) if value is None: reason = (f"the {scope} count of {type_name} could not be measured " f"(query failed, native count unavailable, or the fallback hit its cap)") @@ -2004,9 +2041,11 @@ def asset_composition( root: str = "Asset", depth: int = 2, as_of: Optional[str] = None, - scopes: Sequence[str] = (SCOPE_VIEWER, SCOPE_REPOSITORY), + scopes: Optional[Sequence[str]] = None, concurrency: int = COMPOSITION_DEFAULT_CONCURRENCY, strict: bool = True, + *, + populations: Optional[Sequence[str]] = None, ) -> Dict[str, Any]: """ The composition of `root` by subtype: one row per type in the subtype tree to @@ -2042,8 +2081,8 @@ def asset_composition( depth : how many subtype levels below root (0 = root only) as_of : ISO-8601 asOfTime for point-in-time counts (None = now). The subtype tree is always today's. - scopes : any of "viewer", "repository" -- the populations to count. The - keyword is `scopes`; each cell names its population under `population`. + populations : any of "viewer", "repository" -- the populations to count; each cell + names its population under `population`. `scopes=` is a deprecated alias. concurrency : counts in flight at once, 1..5 (default 3) strict : must be True -- the routine never turns a failure into a 0 @@ -2056,6 +2095,16 @@ def asset_composition( """ if not strict: raise ValueError("asset_composition always counts strictly: a failed count is not_measured, never 0") + if scopes is not None: + if populations is not None and list(populations) != list(scopes): + raise ValueError("asset_composition: populations= and scopes= disagree; pass populations= only") + if populations is None: + warnings.warn("asset_composition(scopes=...) is deprecated; use populations=", + DeprecationWarning, stacklevel=2) + populations = scopes + if populations is None: + populations = (SCOPE_VIEWER, SCOPE_REPOSITORY) + scopes = populations wanted: List[str] = [] for s in scopes: _push_down(s) # ValueError for an unknown scope @@ -2126,7 +2175,8 @@ def asset_composition( "state_reason": "; ".join(reasons), "root": root, "depth": depth, - "scopes": wanted, + "populations": wanted, + "scopes": wanted, # deprecated key, same value as "populations" "as_of": stamp, "concurrency": concurrency, "rows": rows, diff --git a/tests/micro-tests/test_overview_metrics.py b/tests/micro-tests/test_overview_metrics.py index edc35a73..95ffe3d7 100644 --- a/tests/micro-tests/test_overview_metrics.py +++ b/tests/micro-tests/test_overview_metrics.py @@ -789,7 +789,7 @@ def test_native_disable_expires(monkeypatch): @pytest.mark.parametrize("scope,expected", [("viewer", False), ("repository", True)]) def test_scope_maps_to_push_down(scope, expected): mgr = _mgr(count_metadata_elements=MagicMock(return_value=11)) - assert om.count_elements(mgr, "Asset", scope=scope) == 11 + assert om.count_elements(mgr, "Asset", population=scope) == 11 assert mgr.count_metadata_elements.call_args.kwargs == {"push_down": expected} @@ -801,30 +801,30 @@ def test_scope_none_omits_push_down(): def test_invalid_scope_raises(): with pytest.raises(ValueError): - om.count_elements(_mgr(), "Asset", scope="everyone") + om.count_elements(_mgr(), "Asset", population="everyone") def test_repository_scope_failure_strict_is_none_not_find_result(): mgr = _mgr(count_metadata_elements=MagicMock(side_effect=RuntimeError("boom"))) mgr.find_metadata_elements.return_value = [{}] * 43 # viewer-scope answer - assert om.count_elements(mgr, "Asset", strict=True, scope="repository") is None - assert om.count_elements(mgr, "Asset", scope="repository") == 0 + assert om.count_elements(mgr, "Asset", strict=True, population="repository") is None + assert om.count_elements(mgr, "Asset", population="repository") == 0 mgr.find_metadata_elements.assert_not_called() def test_repository_scope_without_native_method_is_none(): mgr = _mgr() mgr.find_metadata_elements.return_value = [{}] * 3 - assert om.count_elements(mgr, "Asset", strict=True, scope="repository") is None - assert om.count_elements(mgr, "Asset", strict=True, scope="viewer") == 3 # viewer may fall back + assert om.count_elements(mgr, "Asset", strict=True, population="repository") is None + assert om.count_elements(mgr, "Asset", strict=True, population="viewer") == 3 # viewer may fall back def test_scope_threads_through_helpers(): mgr = _mgr(count_metadata_elements=MagicMock(return_value=2)) - om.counts_by_type(mgr, [("A", "Asset")], scope="repository") - om.people_counts(mgr, scope="repository") - om.usage_context_counts(mgr, scope="repository") - om.count_elements_by_property(mgr, "DigitalProduct", "deploymentStatus", "ACTIVE", scope="repository") + om.counts_by_type(mgr, [("A", "Asset")], population="repository") + om.people_counts(mgr, population="repository") + om.usage_context_counts(mgr, population="repository") + om.count_elements_by_property(mgr, "DigitalProduct", "deploymentStatus", "ACTIVE", population="repository") calls = mgr.count_metadata_elements.call_args_list assert len(calls) == 1 + 5 + 2 + 1 assert all(c.kwargs == {"push_down": True} for c in calls) @@ -836,12 +836,12 @@ def test_count_relationships_scope(): expert.count_relationships_between_elements.return_value = 4 ce = MagicMock() ce.get_relationships.return_value = [{}] * 9 - assert om.count_relationships(ce, "License", expert=expert, scope="repository") == 4 + assert om.count_relationships(ce, "License", expert=expert, population="repository") == 4 assert expert.count_relationships_between_elements.call_args.kwargs == {"push_down": True} # no expert: repository scope cannot be answered by the viewer-scoped path - assert om.count_relationships(ce, "License", scope="repository") is None + assert om.count_relationships(ce, "License", population="repository") is None assert om.count_relationships(ce, "License") == 9 - assert om.feedback_summary(ce, scope="repository")["total"] is None + assert om.feedback_summary(ce, population="repository")["total"] is None # ── asset_subtype_tree / asset_composition (RS-W1-4) ───────────────────────── @@ -886,8 +886,10 @@ def __init__(self, counts=_COUNTS, fail=(), raise_on=(), delay=0.02): self.active = self.peak = 0 self.calls = [] - def __call__(self, mgr, type_name=None, as_of=None, classifications=None, strict=False, scope=None): + def __call__(self, mgr, type_name=None, as_of=None, classifications=None, strict=False, scope=None, + population=None): assert strict is True + scope = population or scope with self.lock: self.active += 1 self.peak = max(self.peak, self.active) @@ -1002,16 +1004,16 @@ def test_asset_composition_failure_is_not_measured_never_zero(monkeypatch): def test_asset_composition_all_failed_is_not_established(monkeypatch): monkeypatch.setattr(om, "count_elements", lambda *a, **k: None) - res = om.asset_composition(MagicMock(), _FakeVM(), depth=1, scopes=("repository",)) + res = om.asset_composition(MagicMock(), _FakeVM(), depth=1, populations=("repository",)) assert res["state"] == "not_established" assert all(r["repository"]["value"] is None for r in res["rows"]) def test_asset_composition_single_scope_not_visible_needs_both(monkeypatch): monkeypatch.setattr(om, "count_elements", _FakeCounter()) - res = om.asset_composition(MagicMock(), _FakeVM(), depth=1, scopes=("repository",)) + res = om.asset_composition(MagicMock(), _FakeVM(), depth=1, populations=("repository",)) asset = _rows(res)[("Asset", False)] - assert "viewer" not in asset and res["scopes"] == ["repository"] + assert "viewer" not in asset and res["populations"] == ["repository"] assert asset["not_visible"] == {"value": None, "state": "not_measured", "reason": "needs both scopes"} @@ -1042,10 +1044,10 @@ def test_asset_composition_passes_as_of_and_vm_defaults_to_mgr(monkeypatch): assert both.calls == ["Asset"] assert {a for _, _, a in counter.calls} == {"2026-01-01T00:00:00+00:00"} assert res["as_of"] == "2026-01-01T00:00:00+00:00" - assert all(r[s]["as_of"] == res["as_of"] for r in res["rows"] for s in res["scopes"]) + assert all(r[s]["as_of"] == res["as_of"] for r in res["rows"] for s in res["populations"]) -@pytest.mark.parametrize("kwargs", [{"scopes": ()}, {"scopes": ("everyone",)}, {"concurrency": 0}, +@pytest.mark.parametrize("kwargs", [{"populations": ()}, {"populations": ("everyone",)}, {"concurrency": 0}, {"strict": False}]) def test_asset_composition_rejects_bad_arguments(kwargs): with pytest.raises(ValueError): @@ -1070,3 +1072,34 @@ def test_asset_composition_is_registered_with_a_declaration(): assert {m.name for m in decl.measures} == {"repository_count", "viewer_count", "not_visible"} assert all(m.unit == "elements" and m.as_of == "as_of" for m in decl.measures) assert decl.absence.nothing_found + + +# ── population= is the keyword; scope= / scopes= are deprecated aliases (RS-W1-1 §5) ── + +def test_count_elements_scope_alias_warns_and_matches_population(): + mgr = _mgr() + mgr.count_metadata_elements = MagicMock(return_value=7) + with pytest.warns(DeprecationWarning, match="population="): + old = om.count_elements(mgr, "Asset", scope="repository") + new = om.count_elements(mgr, "Asset", population="repository") + assert old == new == 7 + + +def test_count_elements_population_and_scope_must_agree(): + with pytest.raises(ValueError, match="disagree"): + om.count_elements(_mgr(), "Asset", population="viewer", scope="repository") + + +def test_population_keyword_is_in_every_count_helper_signature(): + import inspect + for fn in (om.count_elements, om.count_elements_by_property, om.count_relationships, om.counts_by_type, + om.business_value_signals, om.people_counts, om.feedback_summary, om.usage_context_counts): + assert "population" in inspect.signature(fn).parameters, fn.__name__ + + +def test_asset_composition_scopes_alias_warns_and_matches_populations(): + with pytest.warns(DeprecationWarning, match="populations="): + old = om.asset_composition(MagicMock(), _FakeVM(), depth=1, scopes=("repository",)) + assert old["populations"] == old["scopes"] == ["repository"] + with pytest.raises(ValueError, match="disagree"): + om.asset_composition(MagicMock(), _FakeVM(), depth=1, scopes=("viewer",), populations=("repository",))