diff --git a/docs/output-formats-and-report-specs.md b/docs/output-formats-and-report-specs.md index ec5a454e..fc281f36 100644 --- a/docs/output-formats-and-report-specs.md +++ b/docs/output-formats-and-report-specs.md @@ -1100,7 +1100,9 @@ A count a routine could not establish is `None`, never `0` and never the cap (#5 - a `SERIES`/`BAR`/`PIE` over a result that holds one becomes `kind: "absent"` too: a missing bar, or a pie re-proportioned without its missing slice, would read as an answer; - a dict or list result keeps its measured values; the unmeasured ones are `None` and the notes name each one. -Measured results are unchanged. One exception to "never `0`": a `viewer` count with `strict=False` still returns `0` when the query itself fails; pass `strict=True` for `None`. +Measured results are unchanged. Since 6.2.28 there is no exception to "never `0`": a `viewer` count whose query fails is `None` with a note too, whatever `strict` says (6.2.27 still returned `0` there unless `strict=True`). `strict` is still accepted, and changes nothing. + +**Scans (6.2.28).** A figure computed from a scan, rather than from a native count, is only a figure when the scan read everything. The relationship scans (`orphan_glossary_terms`, `certifications_summary`, `contextualised_coverage`, `solution_component_realisation`, `active_contributors`, `engagement_series`, the DataFlow lineage in `ai_ready_assets`/`drl_readiness_gates`, and `count_relationships` in the viewer population) and the element finds of `governed_coverage`, `ownership_coverage` and `karma_leaderboard` page until Egeria returns an **empty** page. That is Egeria's paging contract: a short page is not the last page. A scan that cannot finish (more than `MAX_SCAN_PAGES` pages, 40 by default, or a server that repeats its page) is `None` with a note, never a figure from the part it read. `stale_assets`, `ai_ready_assets` and `drl_readiness_gates` read one page of Assets, which is too many to page through; when that page is full, their figures are `None` with a note (`capped` is `true` for the readiness routines), because a page of Assets is a sample, not the catalog. In 6.2.27 `orphan_glossary_terms` read one 500-relationship page that held 8 distinct terms, so it reported 1,053 orphans where all 747 relationships give 984. **Population (#556, 6.2.27).** The count routines take `population=` (`"viewer"` or `"repository"`; `scope=` is a deprecated alias and passing both with different values is a `ValueError`). They now default to `"repository"`: totals count the whole repository, **including elements the viewer may not be able to see**, via the native push-down count. This is a deliberate interim choice until zone-aware push-down exists, and the registry descriptions say so. `"viewer"` is an explicit opt-in; `scope=None` omits the argument and takes the server default. A failed repository count has no find fallback, so it is `None` with a note, strict or not. Routines that scan elements (for example `certifications_summary`, `orphan_glossary_terms`, `stale_assets`) stay viewer-scoped, and no payload mixes the two populations in one ratio. diff --git a/docs/release-notes/6.2.27.md b/docs/release-notes/6.2.27.md index 1babe774..73202b7a 100644 --- a/docs/release-notes/6.2.27.md +++ b/docs/release-notes/6.2.27.md @@ -8,7 +8,7 @@ `exec_report_spec` puts the notes on the output as `unmeasured` (`[{"count", "reason", "at_least"}, ...]`); a scalar count that was not measured, and a `SERIES`/`BAR`/`PIE` over one, come back as `kind: "absent"` with the reason and the lower bound - in `content`. Measured results are unchanged. A `viewer` count with `strict=False` still returns `0` when the query itself fails; pass `strict=True` for `None`. See + in `content`. Measured results are unchanged. In 6.2.27 a `viewer` count with `strict=False` still returned `0` when the query itself failed; from 6.2.28 that is `None` with a note too (see [6.2.28](6.2.28.md)). See [Counts: not measured, and whose population](../output-formats-and-report-specs.md#counts-not-measured-and-whose-population). - **Totals count the whole repository by default (#556).** The count routines (`count_elements`, `count_elements_by_property`, `count_relationships`, `counts_by_type`, `people_counts`, diff --git a/docs/release-notes/6.2.28.md b/docs/release-notes/6.2.28.md index fc0233fc..341f6cf1 100644 --- a/docs/release-notes/6.2.28.md +++ b/docs/release-notes/6.2.28.md @@ -25,3 +25,28 @@ a table. - **`exec_report_spec` no longer returns `None` when a find method raises `ValueError`.** It logs the error and raises it, so the caller sees the words. + +## Changed + +- **A failed viewer count is `None`, not `0`.** `count_elements`, `count_elements_by_property` and + the composites built on them (`counts_by_type`, `people_counts`, `usage_context_counts`) returned + `0` in the viewer population when the query itself failed, unless `strict=True`. That read as + "none of them". It is now `None` with an `unmeasured` note, strict or not, as a repository count + already was. `strict` is still accepted and changes nothing. +- **Scans read every page, or report nothing.** A figure computed from a scan is only a figure + when the scan read everything. The relationship scans and the governance, ownership and karma + finds now page until Egeria returns an empty page (a short page is not the last page). A scan + that cannot finish (more than `MAX_SCAN_PAGES` pages, or a server that repeats its page) is + `None` with an `unmeasured` note, never a figure from the part it read. In 6.2.27, + `orphan_glossary_terms` read one 500-relationship page that held 8 distinct terms, and reported + 1,053 orphan terms where all 747 relationships give 984. +- **A full page of Assets is a sample, not a count.** `stale_assets` reported `staleCount` `0` + from a full 500-Asset page beside a not-measured `assetTotal`. It is now `None` with a note when + the page is full. `ai_ready_assets` and `drl_readiness_gates` do the same, with `capped: true`; + they used to report the sample's figures. +- `engagement_series`: a feedback type whose query failed is `None` in every week, and so is + every week's `total`, where it used to read as a week of no activity. +- `governedCapped`, `ownershipCapped` and the readiness routines' `capped` are `false` whenever + the figures were measured. + +See [Counts: not measured, and whose population](../output-formats-and-report-specs.md#counts-not-measured-and-whose-population). diff --git a/pyegeria/view/analytic_demo_specs.py b/pyegeria/view/analytic_demo_specs.py index 1cba4361..0db07849 100644 --- a/pyegeria/view/analytic_demo_specs.py +++ b/pyegeria/view/analytic_demo_specs.py @@ -104,8 +104,8 @@ def _demo( heading="Ownership Coverage", what="Count of elements carrying an Ownership classification -- NOT a percentage, same " "caveat as Governance Coverage (no cheap total-elements denominator yet). " - "ownershipCapped=true means the query hit its result-page cap (DEFAULT_CAP), so " - "ownershipCount is a floor, not exact, when true. byOwnerType is a nested breakdown " + "The find is paged until Egeria returns an empty page, so ownershipCount is every owned " + "element (ownershipCapped is false when measured; an incomplete scan is not measured). byOwnerType is a nested breakdown " "of the same ownershipCount elements by the owner's type (Person, Team, " "SolutionActorRole, ...) -- pick BAR below for a chart of byOwnerType.", analytic_function_name="ownership_coverage", @@ -132,8 +132,8 @@ def _demo( what="Count of elements carrying at least one governance classification " "(ZoneMembership/Confidentiality/Criticality/Impact/Retention) -- NOT a percentage " "despite 'coverage' in the name (there's no cheap total-elements denominator to " - "divide by yet). governedCapped=true means the query hit its result-page cap " - "(DEFAULT_CAP), so governedCount is a floor, not exact, when true. byClassification " + "divide by yet). The find is paged until Egeria returns an empty page, so governedCount " + "is every governed element (governedCapped is false when measured). byClassification " "and topZones are nested breakdowns of the same governedCount elements -- pick BAR " "below for a chart of byClassification.", analytic_function_name="governed_coverage", @@ -212,13 +212,14 @@ def _demo( heading="AI-Ready Assets (Composite)", what="The actual per-asset intersection context_readiness_funnel's 'aiReady' field can't " "give you: Asset elements that are governed AND documented AND lineage-traced, all " - "three, checked per element from a single capped Asset fetch plus one DataFlow " - "relationship query (not three separate counts intersected client-side after the " + "three, checked per element from one Asset find page plus every DataFlow " + "relationship (not three separate counts intersected client-side after the " "fact -- see the function's own docstring for the exact field-name gotchas this hit " "while being built, e.g. find_metadata_elements results key their GUID as " "'elementGUID' but a relationship end's GUID is plain 'guid'). 'total' is the " - "(possibly capped) Asset population actually checked -- divide aiReadyCount by total " - "for a percentage, don't assume it's the full catalog. First worked example of the " + "Asset population checked. A full Asset page is a sample, not the catalog, so then " + "nothing is measured (capped=true, with a note); otherwise divide aiReadyCount by " + "total for a percentage. First worked example of the " "composite/derived analytic metric pattern NEXT-18 (egeria-workspaces BACKLOG.md) " "flagged as missing.", analytic_function_name="ai_ready_assets", diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 90d68e55..ca83dd05 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -761,8 +761,9 @@ def _as_of(description: str = "ISO-8601 asOfTime for a point-in-time value (None def _strict() -> AnalyticParam: return AnalyticParam(name="strict", type="bool", default=False, - description="Return None instead of 0 when a count could not be measured " - "(query failed, or the fallback hit the page-size cap). ISSUE-123.") + description="Accepted for compatibility; changes nothing. Since 6.2.28 a count " + "that could not be measured (query failed, or the fallback hit the " + "page-size cap) is None in every population, never 0. ISSUE-123.") def _population() -> AnalyticParam: @@ -918,7 +919,7 @@ def _always_applies(what: str) -> str: inputs=["egeria_client:MetadataExpert"], description="Share of assets carrying at least one governance classification, plus a " "by-classification / top-zones breakdown. " - "Cost: one capped find (one page of elements), seconds.", + "Cost: one find, paged until Egeria returns an empty page (an incomplete scan is not measured), seconds.", returns="dict (governedCount, governedCapped, byClassification, topZones)", generic=False, binding_note="Fixed to GOVERNANCE_CLASSIFICATIONS: ZoneMembership, Confidentiality, " @@ -949,7 +950,7 @@ def _always_applies(what: str) -> str: ), out=[ _field("governedCount", "Governed elements", "int", unit="elements"), - _field("governedCapped", "At least (page cap reached)", "bool"), + _field("governedCapped", "At least (false when measured: every page is read)", "bool"), _field("fullyGoverned", "Fully governed", "int", unit="elements"), _field("partialZoneOnly", "Zone only", "int", unit="elements"), _field("byClassification", "By classification", "map", unit="elements"), @@ -966,7 +967,7 @@ def _always_applies(what: str) -> str: "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. " - "Cost: one capped find (one page of elements), seconds.", + "Cost: one find, paged until Egeria returns an empty page (an incomplete scan is not measured), seconds.", returns="dict (ownershipCount, ownershipCapped, byOwnerType)", generic=False, binding_note="Fixed to the Ownership classification -- not a parameter.", @@ -984,7 +985,7 @@ def _always_applies(what: str) -> str: ), out=[ _field("ownershipCount", "Owned elements", "int", unit="elements"), - _field("ownershipCapped", "At least (page cap reached)", "bool"), + _field("ownershipCapped", "At least (false when measured: every page is read)", "bool"), _field("byOwnerType", "By owner type", "map", unit="elements"), ], ), @@ -1040,14 +1041,14 @@ def _always_applies(what: str) -> str: function="pyegeria.view.overview_metrics.certifications_summary", inputs=["egeria_client:ClassificationExplorer"], description="Active/expiring Certification relationships, licenses, and open Exception counts. " - "Cost: three capped relationship pages, seconds.", + "Cost: one relationship scan, paged until Egeria returns an empty page, plus two counts, seconds.", returns="dict (active, expiring90, soon, licenses, exceptions)", 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. + # active/expiring90 come from every Certification page; an incomplete scan is None, noted. measures=[ _measure("certifications", "Certification relationships", "active", population="viewer"), _measure("expiring_certifications", "Certification relationships ending within 90 days", @@ -1117,7 +1118,7 @@ def _always_applies(what: str) -> str: "Takes an EgeriaTech: the repository count is MetadataExpert's native relationship count, " "and the viewer path is ClassificationExplorer's get_relationships. " "Cost: five native counts, sub-second each in the repository population; population=viewer " - "reads five capped relationship pages instead." + REPOSITORY_WORDS, + "reads five relationship scans instead, paged until Egeria returns an empty page." + REPOSITORY_WORDS, returns="dict (byType, total)", generic=False, binding_note="Fixed to Collaboration OMAS's feedback relationship types -- not a parameter.", @@ -1271,7 +1272,8 @@ def _always_applies(what: str) -> str: "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. " - "Cost: one capped Asset find plus one capped DataFlow relationship page, seconds.", + "Cost: one Asset find page (a full page is a sample, so not measured) plus every 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.", @@ -1293,7 +1295,7 @@ def _always_applies(what: str) -> str: out=[ _field("aiReadyCount", "AI-ready Assets", "int", unit="Assets"), _field("total", "Assets checked", "int", unit="Assets"), - _field("capped", "At least (page cap reached)", "bool"), + _field("capped", "Asset page full (true: a sample, so nothing is measured)", "bool"), ], ), ), @@ -1305,8 +1307,8 @@ def _always_applies(what: str) -> str: "(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.", + "Takes two leading clients (mgr, ce). Cost: one Asset find page (a full page is a sample, " + "so not measured) and every 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 " @@ -1342,7 +1344,7 @@ def _always_applies(what: str) -> str: ), out=[ _field("total", "Assets checked", "int", unit="Assets"), - _field("capped", "At least (page cap reached)", "bool"), + _field("capped", "Asset page full (true: a sample, so nothing is measured)", "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"), @@ -1444,7 +1446,7 @@ def _always_applies(what: str) -> str: 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). " - "Cost: five capped relationship pages, seconds.", + "Cost: five relationship scans, paged until Egeria returns an empty page, seconds.", returns="dict (contributors, byType)", generic=False, binding_note="Fixed to Collaboration OMAS's feedback relationship types -- not a parameter.", @@ -1603,7 +1605,7 @@ def _always_applies(what: str) -> str: "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. " - "Cost: one capped relationship page plus one count, seconds.", + "Cost: one relationship scan, paged until Egeria returns an empty 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.", @@ -1638,7 +1640,7 @@ def _always_applies(what: str) -> str: "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.", + "count plus one ImplementedBy relationship scan, paged until Egeria returns an empty page, seconds.", returns="dict (solutionComponentsTotal, solutionComponentsRealised)", generic=False, binding_note="Fixed to SolutionComponent and the ImplementedBy relationship -- not a parameter.", @@ -1667,10 +1669,10 @@ def _always_applies(what: str) -> str: name="karma_leaderboard", function="pyegeria.view.overview_metrics.karma_leaderboard", inputs=["egeria_client:MetadataExpert"], - description="Top-N people by karma -- one bounded ContributionRecord fetch, karmaPoints is a " + description="Top-N people by karma -- every ContributionRecord, 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. " - "Cost: one capped find, seconds.", + "Cost: one find, paged until Egeria returns an empty page, 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 " @@ -1711,7 +1713,7 @@ def _always_applies(what: str) -> str: "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. " - "Cost: five capped relationship pages, seconds.", + "Cost: five relationship scans, paged until Egeria returns an empty page, 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.", @@ -1721,7 +1723,7 @@ def _always_applies(what: str) -> str: ], declaration=AnalyticDeclaration( result_kind="series", - # One row per ISO week, oldest first, zero-filled; each type is one capped relationship page. + # One row per ISO week, oldest first, zero-filled; each type is read in full (None when not measured). measures=[ _measure("feedback", "feedback relationships created in the week", "total", as_of="week", population="viewer"), @@ -1762,7 +1764,7 @@ def _always_applies(what: str) -> str: "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. " - "Cost: one count plus one capped relationship page, seconds.", + "Cost: one count plus one relationship scan, paged until Egeria returns an empty page, seconds.", returns="dict (termTotal, referencedCount, orphanCount)", generic=False, binding_note="Fixed to the SemanticAssignment relationship type and GlossaryTerm elements -- not a parameter.", @@ -1797,7 +1799,8 @@ def _always_applies(what: str) -> str: 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. " - "Cost: one capped Asset find plus one count, seconds.", + "Cost: one Asset find page (a full page is a sample, so staleCount is not measured) 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.", @@ -1807,14 +1810,15 @@ def _always_applies(what: str) -> str: ], declaration=AnalyticDeclaration( result_kind="measure", - # staleCount comes from one capped find, assetTotal from a native count: no basis between them. + # staleCount comes from one find page (None when full), assetTotal from a native count: no basis. measures=[ - _measure("stale_assets", "Assets not updated within `days`, among those one capped find returned", + _measure("stale_assets", "Assets not updated within `days` (not measured when the Asset find fills its page)", "staleCount", population="viewer"), _measure("assets", "Assets", "assetTotal"), ], absence=_absence( - not_measured="Stale assets were not measured: the Asset find failed.", + not_measured="Stale assets were not measured: the Asset find failed, or it filled its page, " + "so it held only some of the Assets.", 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.", diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index 9ef72047..3d833dde 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -232,7 +232,7 @@ def _find(mgr, body: dict, page_size: int = DEFAULT_CAP) -> list: return _find_or_none(mgr, body, page_size) or [] -def _find_or_none(mgr, body: dict, page_size: int = DEFAULT_CAP) -> Optional[list]: +def _find_or_none(mgr, body: dict, page_size: int = DEFAULT_CAP, start_from: int = 0) -> Optional[list]: """Run a FindRequestBody: a list of elements, [] when nothing matched (a list or pyegeria's "No elements found" string), or None when the query failed or answered with something else. Never raises.""" @@ -244,7 +244,7 @@ def _find_or_none(mgr, body: dict, page_size: int = DEFAULT_CAP) -> Optional[lis # stopped working once Egeria moved pagination for this endpoint # into the request body; find_metadata_elements no longer accepts # them as parameters at all, to avoid this drifting stale again). - b = {**body, "graphQueryDepth": 0, "startFrom": 0, "pageSize": page_size} + b = {**body, "graphQueryDepth": 0, "startFrom": start_from, "pageSize": page_size} raw = mgr.find_metadata_elements(b) except Exception as exc: # noqa: BLE001 -- best-effort, degrade don't fail logger.debug(f"overview_metrics _find failed for {body.get('metadataElementTypeName')!r}: {exc}") @@ -258,6 +258,125 @@ def _find_or_none(mgr, body: dict, page_size: int = DEFAULT_CAP) -> Optional[lis return None +# ── exhaustive scans ─────────────────────────────────────────────────────── +# A figure computed from a scan (distinct relationship ends, per-element checks) is only a figure when +# the scan read everything. Egeria's paging contract: only an EMPTY page means done -- a short page is not +# the last page, because a server may filter hits out of a page after fetching it. So these helpers page +# until an empty page, advancing startFrom by the full page size every time, and a scan that would need +# more than MAX_SCAN_PAGES pages stops and is not measured (None plus a note), never reported from the +# part it had read. Found live 2026-11-08: one 500-relationship SemanticAssignment page held 8 distinct +# terms, all 747 held 77, so the orphan-term count read 1,053 instead of 984. +MAX_SCAN_PAGES = 40 + + +class _ScanIncomplete(Exception): + """Internal: a scan helper returned None (its note is already recorded).""" + + +def _scan_stopped_reason(kind: str, n: int) -> str: + return (f"the {kind} scan stopped after {MAX_SCAN_PAGES} pages of {DEFAULT_CAP} ({n} read) before " + f"Egeria returned an empty page, so it is incomplete") + + +def _repeated_page_reason(kind: str, n: int) -> str: + return (f"the {kind} scan got a page that repeated only what it had already read, so the server " + f"is not paging and the scan is incomplete ({n} read)") + + +def _all_relationships(ce, relationship_type: str, as_of: Optional[str] = None) -> Optional[list]: + """Every relationship of `relationship_type` (as of `as_of`), paged until Egeria returns an empty page. + + Distinct by relationship GUID: a page may repeat relationships an earlier page returned. Returns None, + with a note for `recording_unmeasured()`, when the scan is incomplete -- it reached MAX_SCAN_PAGES, or a + page added nothing new (the server ignored startFrom). Raises when a page query fails, so each caller + keeps its own failure path. + + The body always carries startFrom/pageSize: ClassificationExplorer.get_relationships ignores its + start_from/page_size arguments whenever a body is given.""" + out: list = [] + seen: set = set() + prev: Optional[list] = None + what = f"{relationship_type} relationships" + for i in range(MAX_SCAN_PAGES): + start = i * DEFAULT_CAP + body: Dict[str, Any] = {"class": "ResultsRequestBody", "startFrom": start, "pageSize": DEFAULT_CAP} + if as_of: + body["asOfTime"] = as_of + page = _json_list(ce.get_relationships(relationship_type=relationship_type, output_format="JSON", + start_from=start, page_size=DEFAULT_CAP, body=body)) + if not page: + return out + if page == prev: # the same page again: startFrom was ignored (a GUID check cannot see it without GUIDs) + _not_measured(what, _repeated_page_reason("relationship", len(out)), at_least=len(out)) + return None + prev = page + added = 0 + for r in page: + g = (r.get("relationshipHeader") or {}).get("guid") or r.get("guid") + if g: + if g in seen: + continue + seen.add(g) + out.append(r) + added += 1 + if added == 0: + _not_measured(what, _repeated_page_reason("relationship", len(out)), at_least=len(out)) + return None + _not_measured(what, _scan_stopped_reason("relationship", len(out)), at_least=len(out)) + return None + + +def _element_guid(el: dict) -> Optional[str]: + return el.get("elementGUID") or (el.get("elementHeader") or {}).get("guid") or el.get("guid") + + +def _all_elements(mgr, body: dict) -> Optional[list]: + """Every element a FindRequestBody matches, paged until Egeria returns an empty page. + + Distinct by element GUID. Returns None when a page query fails (no note: the caller's own failure + path), and None with a note when the scan is incomplete (MAX_SCAN_PAGES reached, or a page that added + nothing new). Never raises.""" + out: list = [] + seen: set = set() + prev: Optional[list] = None + for i in range(MAX_SCAN_PAGES): + page = _find_or_none(mgr, body, DEFAULT_CAP, start_from=i * DEFAULT_CAP) + if page is None: + return None + if not page: + return out + if page == prev: # the same page again: startFrom was ignored + _not_measured(_count_label(body), _repeated_page_reason("find", len(out)), at_least=len(out)) + return None + prev = page + added = 0 + for el in page: + g = _element_guid(el) + if g: + if g in seen: + continue + seen.add(g) + out.append(el) + added += 1 + if added == 0: + _not_measured(_count_label(body), _repeated_page_reason("find", len(out)), at_least=len(out)) + return None + _not_measured(_count_label(body), _scan_stopped_reason("find", len(out)), at_least=len(out)) + return None + + +def _one_page_or_none(mgr, body: dict, what: str) -> Optional[list]: + """One find page, for a routine whose population is too large to page through (Asset): the page, + [] when nothing matched, or None when the query failed or the page was full. A full page is a sample, + not the population, so a figure computed from it is not measured (a note says so).""" + page = _find_or_none(mgr, body) + if page is not None and len(page) >= DEFAULT_CAP: + _not_measured(what, f"the find stopped at its {DEFAULT_CAP}-element page cap, so this figure would " + f"describe only the first {len(page)} elements, not all of them", at_least=len(page)) + return None + return page + + SCOPE_VIEWER = "viewer" SCOPE_REPOSITORY = "repository" @@ -384,11 +503,13 @@ def _element_count(mgr, body: dict, as_of: Optional[str] = None, strict: bool = or not) with a note, never 0 and never a viewer number masquerading as a repository one. - scope="viewer" or None: strict=False gives 0 when the fallback query fails - (the historical behaviour); strict=True gives None. - Either way: None when the fallback returned a full page (DEFAULT_CAP). That - is only a lower bound, never a total, so it is never returned as one; the - bound and the reason go to `recording_unmeasured()`'s notes. + scope="viewer" or None: the len(find) fallback answers when the native + count cannot. None, with a note, when that query fails too (strict or not: + a 0 would read as "none of them", 6.2.28), and None when it returned a full + page (DEFAULT_CAP). That is only a lower bound, never a total, so it is + never returned as one; the bound and the reason go to + `recording_unmeasured()`'s notes. `strict` no longer changes any result; it + is kept so existing callers still work. """ push_down = _push_down(scope) kw = {} if push_down is None else {"push_down": push_down} @@ -414,9 +535,7 @@ def _element_count(mgr, body: dict, as_of: Optional[str] = None, strict: bool = f"(the find fallback only sees what the viewer may see)") return None found = _find_or_none(mgr, b) - if found is None: - if not strict: - return 0 + if found is None: # strict or not: a failed query is not "none of them" (6.2.28) _not_measured(what, f"{native_words}, and the find fallback failed") return None if len(found) >= DEFAULT_CAP: # a full page is a lower bound, never a total (strict or not) @@ -444,7 +563,7 @@ def count_elements( Only in the viewer population (or scope=None) does a missing or failed native count fall back to `len(find_metadata_elements(...))`. There a - failed query counts as 0 unless strict=True (ISSUE-123), and a fallback + failed query is None, not 0 (strict or not, since 6.2.28), and a fallback that stops at DEFAULT_CAP gives None, never the cap: that page is a lower bound, not a total (its bound and reason are recorded too). @@ -455,8 +574,9 @@ def count_elements( as_of : ISO-8601 asOfTime for a point-in-time count (None = now) classifications : classification names to match ANY of -- keep to a single call's worth (some connectors mishandle 2+ ANY conditions) - strict : when True, return None (not 0) if the query failed. A fallback - count that hit DEFAULT_CAP is None in either mode + strict : no longer changes the result: a count that is not measured is + None either way (since 6.2.28 a failed viewer query is None too, not 0). + Kept so existing callers still work scope : "repository" (the default: push_down=True, a whole-repository raw count -- fast, and it includes elements the caller may not be able to see; a deliberate interim choice, until zone-aware push-down exists), @@ -467,9 +587,9 @@ def count_elements( Returns ------- - Optional[int] -- None whenever a repository count is not measured, and on - a capped fallback; in viewer scope a failed query is 0 unless strict=True - (never raises) + Optional[int] -- None whenever the count is not measured: a failed or + unavailable repository count, a failed viewer query, or a capped fallback + (never 0 for any of those, and never raises) """ body: Dict[str, Any] = {"class": "FindRequestBody", "limitResultsByStatus": ["ACTIVE"]} if type_name: @@ -510,7 +630,7 @@ def count_elements_by_property( property_name : the element property to match (e.g. "deploymentStatus") property_value : the exact string value to match as_of : ISO-8601 asOfTime for a point-in-time count (None = now) - strict : as for count_elements -- None instead of 0 when not measured + strict : as for count_elements -- accepted, changes nothing (not measured is always None) scope : as for count_elements ("repository" by default | "viewer" | None) operator : "EQ" (the default: the property equals `property_value`) or "NEQ" (it is set and differs -- e.g. property_value="" counts elements @@ -606,19 +726,15 @@ def count_relationships(ce, relationship_type: str, as_of: Optional[str] = None, f"(get_relationships only sees what the viewer may see)") return None try: - body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None - n = len(_json_list(ce.get_relationships( - relationship_type=relationship_type, output_format="JSON", - start_from=0, page_size=DEFAULT_CAP, body=body))) + # Paged to an empty page (Egeria's contract), so the count is every relationship the viewer may + # see, not one page of them; an incomplete scan is None with its note (see _all_relationships). + rels = _all_relationships(ce, relationship_type, as_of) except Exception as exc: # noqa: BLE001 logger.debug(f"overview_metrics count_relationships({relationship_type}) failed: {exc}") + _not_measured(relationship_type, f"{_native_failure_words(native_exc, tried)}, and the " + f"get_relationships fallback failed") return None - if n >= DEFAULT_CAP: - page = f"get_relationships stopped at its {DEFAULT_CAP}-relationship page cap, so there are at least {n}" - _not_measured(relationship_type, (f"{_native_failure_words(native_exc, tried)}, and {page}" if tried - else f"{page} (no native count was asked for)"), at_least=n) - return None - return n + return None if rels is None else len(rels) @_population_keyword @@ -626,10 +742,11 @@ def counts_by_type(mgr, type_map: Sequence[Tuple[str, str]], as_of: Optional[str strict: bool = False, scope: Optional[str] = SCOPE_REPOSITORY) -> List[Dict[str, Any]]: """ Per-type counts for a set of (label, type_name) pairs -- e.g. the assets- - by-type composition breakdown. Unknown/wrong types just yield 0 rather - than failing the whole call. With strict=True, a count that could not be - measured is None (see count_elements); a capped fallback is None either - way, never the cap. `scope` is passed to count_elements. + by-type composition breakdown. A type that cannot be counted (unknown, + failed, timed out, or a capped fallback) is None for its own row, never 0, + rather than failing the whole call (see count_elements). `scope` is passed + to count_elements; `strict` is accepted for compatibility and changes + nothing. Returns a list of {"label": ..., "type": ..., "count": ...} dicts, in the order given. @@ -724,8 +841,12 @@ def governed_coverage(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: type, so these are catalog-wide counts, not Asset-only -- an existing, already-accepted proxy in this dashboard, not a new one introduced here. - If the find fails, governedCount/governedCapped/fullyGoverned/partialZoneOnly - are None (unmeasured) and byClassification/topZones are empty. + The find is paged until Egeria returns an empty page, so every figure + covers every governed element. If it fails or the scan is incomplete + (MAX_SCAN_PAGES; a note is recorded), governedCount/governedCapped/ + fullyGoverned/partialZoneOnly are None (unmeasured) and byClassification/ + topZones are empty. `governedCapped` is False whenever measured (kept for + callers that read it). Returns {"governedCount": int|None, "byClassification": {name: count}, "topZones": [{"zone": name, "count": count}, ...8 max], @@ -741,8 +862,8 @@ def governed_coverage(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: } if as_of: body["asOfTime"] = as_of - hits = _find_or_none(mgr, body) - if hits is None: # query failed: unmeasured, not "nothing governed" + hits = _all_elements(mgr, body) # every page; None when it failed or was incomplete (noted) + if hits is None: # unmeasured, not "nothing governed" return { "governedCount": None, "governedCapped": None, @@ -773,7 +894,7 @@ def governed_coverage(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: return { "governedCount": len(hits), - "governedCapped": len(hits) >= DEFAULT_CAP, + "governedCapped": False, # every page was read "byClassification": by_classification, "topZones": [{"zone": z, "count": c} for z, c in top_zones], "fullyGoverned": fully_governed, @@ -801,8 +922,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. - If the find fails, ownershipCount/ownershipCapped are None (unmeasured, as in - governed_coverage) and byOwnerType is empty -- not 0, which read as "nothing owned". + The find is paged until Egeria returns an empty page. If it fails or the + scan is incomplete, ownershipCount/ownershipCapped are None (unmeasured, as + in governed_coverage) and byOwnerType is empty -- not 0, which read as + "nothing owned". `ownershipCapped` is False whenever measured. Returns {"ownershipCount": int|None, "ownershipCapped": bool|None, "byOwnerType": {typeName: count}}. @@ -817,8 +940,8 @@ def ownership_coverage(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: } if as_of: body["asOfTime"] = as_of - hits = _find_or_none(mgr, body) - if hits is None: # query failed: unmeasured, not "nothing owned" + hits = _all_elements(mgr, body) # every page; None when it failed or was incomplete (noted) + if hits is None: # unmeasured, not "nothing owned" return {"ownershipCount": None, "ownershipCapped": None, "byOwnerType": {}} by_owner_type: Dict[str, int] = {} @@ -828,7 +951,7 @@ def ownership_coverage(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: return { "ownershipCount": len(hits), - "ownershipCapped": len(hits) >= DEFAULT_CAP, + "ownershipCapped": False, # every page was read "byOwnerType": by_owner_type, } @@ -926,15 +1049,17 @@ def certifications_summary(ce, as_of: Optional[str] = None) -> Dict[str, Any]: Returns {"active": int|None, "expiring90": int|None, "soon": [...], "licenses": int|None, "exceptions": int|None}. Degrades to Nones on failure rather than raising (a demo/dev server may simply have none). + The Certification relationships are paged to Egeria's empty page; an + incomplete scan leaves active/expiring90 None (with a note), never a count + of the first page. """ from datetime import datetime, timezone, timedelta out: Dict[str, Any] = {"active": None, "expiring90": None, "soon": [], "licenses": None, "exceptions": None} - body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None try: - certs = _json_list(ce.get_relationships(relationship_type="Certification", - output_format="JSON", start_from=0, - page_size=DEFAULT_CAP, body=body)) + certs = _all_relationships(ce, "Certification", as_of) # every page, not the first + if certs is None: # incomplete scan (noted): active/expiring are not measured, not a count of a page + raise _ScanIncomplete() now = datetime.fromisoformat(as_of.replace("Z", "+00:00")) if as_of else datetime.now(timezone.utc) if now.tzinfo is None: now = now.replace(tzinfo=timezone.utc) @@ -955,10 +1080,12 @@ def certifications_summary(ce, as_of: Optional[str] = None) -> Dict[str, Any]: out["active"] = len(certs) out["expiring90"] = expiring out["soon"] = soon[:5] + except _ScanIncomplete: + pass except Exception as exc: # noqa: BLE001 logger.debug(f"overview_metrics certifications_summary: query failed: {exc}") - # One population per payload: active/expiring come from a get_relationships page (viewer-scoped). + # One population per payload: active/expiring come from a get_relationships scan (viewer-scoped). out["licenses"] = count_relationships(ce, "License", as_of, population=SCOPE_VIEWER) out["exceptions"] = count_relationships(ce, "Exception", as_of, population=SCOPE_VIEWER) return out @@ -974,10 +1101,14 @@ def orphan_glossary_terms(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Opt much of the catalog is grounded"; this one asks "how much of the glossary is idle"). - Same single-bounded-relationship-fetch shape as `contextualised_coverage` - (ImplementedBy) -- one `SemanticAssignment` fetch, filtered to the - GlossaryTerm-typed end, distinct-GUID count is the "referenced" set; - orphan = term total - referenced. Not scoped to "approved" status + Same relationship-scan shape as `contextualised_coverage` (ImplementedBy): + every `SemanticAssignment` relationship, paged until Egeria returns an + empty page, filtered to the GlossaryTerm-typed end; the distinct-GUID count + is the "referenced" set; orphan = term total - referenced. An incomplete + scan makes referencedCount and orphanCount None (with a note), never a + figure from the pages it did read: one 500-relationship page held 8 + distinct terms live (2026-11-08), all 747 held 77, so a one-page scan + reported 1,053 orphans instead of 984. Not scoped to "approved" status specifically (Egeria's term status isn't filtered here) -- same catalog-wide-not-sub-filtered tradeoff `governedCount` etc. already carry, not a new one. @@ -993,19 +1124,16 @@ def orphan_glossary_terms(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Opt referenced_count = None try: - rel_body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None - rels = _json_list(ce.get_relationships( - relationship_type="SemanticAssignment", output_format="JSON", - start_from=0, page_size=max_paging_size, body=rel_body)) + rels = _all_relationships(ce, "SemanticAssignment", as_of) # every page: one page is not the set term_guids: set = set() - for r in rels: + for r in rels or []: for end_key in ("end1", "end2"): end = (r.get(end_key) or {}) if isinstance(r, dict) else {} end_type = end.get("type") or {} type_names = {end_type.get("typeName")} | set(end_type.get("superTypeNames") or []) if "GlossaryTerm" in type_names and end.get("guid"): term_guids.add(end["guid"]) - referenced_count = len(term_guids) + referenced_count = None if rels is None else len(term_guids) except Exception as exc: # noqa: BLE001 logger.debug(f"orphan_glossary_terms: SemanticAssignment query failed: {exc}") @@ -1030,8 +1158,11 @@ 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 when the Asset find fails (not 0); `assetTotal` reuses `count_elements` (native, - unaffected by this function's own element-fetch cap). + is None when the Asset find fails, and None with an `unmeasured` note when + the find filled its DEFAULT_CAP page (6.2.28): the page is a sample, not + every Asset, so a count of stale ones in it is not the stale count and was + shown as 0 beside a not-measured assetTotal. `assetTotal` reuses + `count_elements` (native, unaffected by this function's own page). """ from datetime import datetime, timezone, timedelta @@ -1044,7 +1175,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_or_none(mgr, body) # None when the find failed: staleCount stays None, not 0 + # None when the find failed, and None (with a note) when it filled its page: a page of Assets is + # a sample, so a stale count from it is not the stale count -- never 0 beside an unmeasured total. + elements = _one_page_or_none(mgr, body, f"Assets not updated within {days} days") stale_count = None if elements is None else 0 for el in elements or []: updated = _update_time(el) @@ -1137,6 +1270,20 @@ def context_readiness_funnel(mgr, ce, as_of: Optional[str] = None) -> Dict[str, } +def _lineage_guids(ce, as_of: Optional[str], who: str) -> Optional[set]: + """GUIDs at either end of any DataFlow relationship (every page), or None when the scan failed or was + incomplete (an incomplete one is noted).""" + try: + rels = _all_relationships(ce, "DataFlow", as_of) + except Exception as exc: # noqa: BLE001 + logger.debug(f"{who}: DataFlow relationship query failed: {exc}") + return None + if rels is None: + return None + return {g for r in rels if isinstance(r, dict) for k in ("end1", "end2") + if (g := (r.get(k) or {}).get("guid"))} + + def ai_ready_assets(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: """ The actual "AI-Ready" claim `context_readiness_funnel`'s own UI already @@ -1165,17 +1312,19 @@ def ai_ready_assets(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: an empty intersection instead of an error, so this was checked against live responses before writing the intersection logic, not assumed. - Same DEFAULT_CAP tradeoff every field-value-check function in this - module already accepts (`term_definition_completeness`, - `context_readiness_funnel`'s own `documented` stage) -- a floor, not - exact, on a catalog larger than DEFAULT_CAP. + The Asset find is one DEFAULT_CAP page. When that page is full it is a + sample, not the catalog, so aiReadyCount and total are None with an + `unmeasured` note and capped is True (6.2.28; it used to report the + sample's count). The DataFlow relationships are paged until Egeria returns + an empty page. 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. + -- "total" is the Asset population checked (every Asset, since a full page + is not measured), so a caller can compute a percentage without a separate + cataloged-count call. A failed Asset find makes all three None; a failed or + incomplete DataFlow scan 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"} @@ -1184,24 +1333,15 @@ def ai_ready_assets(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: assets = _find_or_none(mgr, body) if assets is None: return {"aiReadyCount": None, "total": None, "capped": None} + if len(assets) >= DEFAULT_CAP: + # A full page is a sample of the Assets, not all of them: a count from it is not the count. + _not_measured("AI-ready Assets", f"the Asset find stopped at its {DEFAULT_CAP}-element page cap, so " + f"only the first {len(assets)} Assets could be checked", at_least=None) + return {"aiReadyCount": None, "total": None, "capped": True} - lineage_guids: Optional[set] = set() - try: - rel_body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None - rels = _json_list(ce.get_relationships( - relationship_type="DataFlow", output_format="JSON", - start_from=0, page_size=DEFAULT_CAP, body=rel_body)) - for r in rels: - for end_key in ("end1", "end2"): - end = (r.get(end_key) or {}) if isinstance(r, dict) else {} - g = end.get("guid") - if g: - lineage_guids.add(g) - except Exception as exc: # noqa: BLE001 - logger.debug(f"ai_ready_assets: lineage relationship query failed: {exc}") - lineage_guids = None + lineage_guids = _lineage_guids(ce, as_of, "ai_ready_assets") if lineage_guids is None: - return {"aiReadyCount": None, "total": len(assets), "capped": len(assets) >= DEFAULT_CAP} + return {"aiReadyCount": None, "total": len(assets), "capped": False} ai_ready = 0 for a in assets: @@ -1214,7 +1354,7 @@ def ai_ready_assets(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: if documented and governed and lineage_traced: ai_ready += 1 - return {"aiReadyCount": ai_ready, "total": len(assets), "capped": len(assets) >= DEFAULT_CAP} + return {"aiReadyCount": ai_ready, "total": len(assets), "capped": False} # ── Modality tagging (§1.9) ────────────────────────────────────────────────── @@ -1300,7 +1440,9 @@ def drl_readiness_gates(mgr, ce, as_of: Optional[str] = None, recency_days: int 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 + A failed Asset find makes every field None; a full Asset page (a sample, + not the catalog) makes every field None too, with capped True and an + `unmeasured` note (6.2.28); a failed or incomplete DataFlow scan makes aiReadyCount/aiReadyRecentCount None and keeps the rest -- unmeasured, not 0. """ from datetime import datetime, timedelta, timezone @@ -1313,21 +1455,14 @@ def drl_readiness_gates(mgr, ce, as_of: Optional[str] = None, recency_days: int if assets is None: return {"total": None, "capped": None, "aiReadyCount": None, "aiReadyRecentCount": None, "byModality": None} + if len(assets) >= DEFAULT_CAP: + # A full page is a sample of the Assets, not all of them: no figure here may describe it as all. + _not_measured("DRL readiness gates", f"the Asset find stopped at its {DEFAULT_CAP}-element page cap, " + f"so only the first {len(assets)} Assets could be checked") + return {"total": None, "capped": True, "aiReadyCount": None, "aiReadyRecentCount": None, + "byModality": None} - lineage_guids: Optional[set] = set() - try: - rel_body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None - rels = _json_list(ce.get_relationships( - relationship_type="DataFlow", output_format="JSON", - start_from=0, page_size=DEFAULT_CAP, body=rel_body)) - for r in rels: - for end_key in ("end1", "end2"): - g = ((r.get(end_key) or {}) if isinstance(r, dict) else {}).get("guid") - if g: - lineage_guids.add(g) - except Exception as exc: # noqa: BLE001 - logger.debug(f"drl_readiness_gates: DataFlow relationship query failed: {exc}") - lineage_guids = None + lineage_guids = _lineage_guids(ce, as_of, "drl_readiness_gates") now = datetime.fromisoformat(as_of.replace("Z", "+00:00")) if as_of else datetime.now(timezone.utc) if now.tzinfo is None: @@ -1356,7 +1491,7 @@ def drl_readiness_gates(mgr, ce, as_of: Optional[str] = None, recency_days: int return { "total": len(assets), - "capped": len(assets) >= DEFAULT_CAP, + "capped": False, "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, @@ -1387,9 +1522,9 @@ def people_counts(mgr, as_of: Optional[str] = None, strict: bool = False, scope: filtered set, so totals may differ from an older implementation -- this raw count is the authoritative repository count. - Returns {"persons": int, "teams": int, "organizations": int, - "itProfiles": int, "communities": int}. With strict=True, a count that - could not be measured is None (see count_elements). + Returns {"persons": int|None, "teams": int|None, "organizations": int|None, + "itProfiles": int|None, "communities": int|None}. A count that could not be + measured is None, never 0 (see count_elements; `strict` changes nothing). """ return { "persons": count_elements(mgr, "Person", as_of, strict=strict, **_pop(scope)), @@ -1438,8 +1573,9 @@ def usage_context_counts(mgr, as_of: Optional[str] = None, strict: bool = False, in a *usage context* ("this store feeds the Clinical Trial supply chain", "this component realises the Sales blueprint"). - Returns {"informationSupplyChains": int, "blueprints": int}. With - strict=True, a count that could not be measured is None (see count_elements). + Returns {"informationSupplyChains": int|None, "blueprints": int|None}. A + count that could not be measured is None, never 0 (see count_elements; + `strict` changes nothing). """ return { "informationSupplyChains": count_elements(mgr, "InformationSupplyChain", as_of, strict=strict, **_pop(scope)), @@ -1477,10 +1613,9 @@ def contextualised_coverage(mgr, ce, as_of: Optional[str] = None) -> Dict[str, O counting DataFlow relationships rather than confirming each one sits on a path Egeria would call "lineage" in the strict sense). - Capped at max_paging_size ImplementedBy relationships (matches every - other relationship fetch in this module) -- undercounts if a deployment - has more, same documented tradeoff as governed_coverage/ - certifications_summary's own caps. + Every ImplementedBy relationship is read, paged until Egeria returns an + empty page; an incomplete scan makes contextualisedCount None (with a + note), never a count from the pages it did read. Returns {"contextualisedCount": int|None, "assetTotal": int|None, "contextualisedPct": float|None}. Any field is None on total failure for @@ -1488,10 +1623,9 @@ def contextualised_coverage(mgr, ce, as_of: Optional[str] = None) -> Dict[str, O """ contextualised_count = None try: - rel_body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None - rels = _json_list(ce.get_relationships( - relationship_type="ImplementedBy", output_format="JSON", - start_from=0, page_size=max_paging_size, body=rel_body)) + rels = _all_relationships(ce, "ImplementedBy", as_of) # every page; None when incomplete (noted) + if rels is None: + raise _ScanIncomplete() asset_guids: set = set() for r in rels: for end_key in ("end1", "end2"): @@ -1501,6 +1635,8 @@ def contextualised_coverage(mgr, ce, as_of: Optional[str] = None) -> Dict[str, O if "Asset" in type_names and end.get("guid"): asset_guids.add(end["guid"]) contextualised_count = len(asset_guids) + except _ScanIncomplete: + pass except Exception as exc: # noqa: BLE001 logger.debug(f"contextualised_coverage: ImplementedBy query failed: {exc}") @@ -1559,10 +1695,9 @@ def solution_component_realisation(mgr, ce, as_of: Optional[str] = None) -> Dict realised_count = None try: - rel_body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None - rels = _json_list(ce.get_relationships( - relationship_type="ImplementedBy", output_format="JSON", - start_from=0, page_size=max_paging_size, body=rel_body)) + rels = _all_relationships(ce, "ImplementedBy", as_of) # every page; None when incomplete (noted) + if rels is None: + raise _ScanIncomplete() component_guids: set = set() for r in rels: end1 = (r.get("end1") or {}) if isinstance(r, dict) else {} @@ -1571,6 +1706,8 @@ def solution_component_realisation(mgr, ce, as_of: Optional[str] = None) -> Dict if "SolutionComponent" in type_names and end1.get("guid"): component_guids.add(end1["guid"]) realised_count = len(component_guids) + except _ScanIncomplete: + pass except Exception as exc: # noqa: BLE001 logger.debug(f"solution_component_realisation: ImplementedBy query failed: {exc}") @@ -1593,9 +1730,10 @@ def karma_leaderboard(mgr, as_of: Optional[str] = None, top_n: int = 10, to the element itself, no relationship traversal needed to know whose karma it is. - One bounded `find_metadata_elements` call (capped at max_paging_size, - same discipline as every other fetch in this module) returns every - ContributionRecord with properties + classifications attached; this + `find_metadata_elements`, paged until Egeria returns an empty page, + returns every ContributionRecord with properties + classifications + attached (an incomplete scan gives an empty list with an `unmeasured` + note, never the top of one page); this filters to `anchor_types` (Person only by default -- pass e.g. `("Person", "ITProfile")` to include automation/engine contributors too), sorts by karmaPoints descending, and returns the top N. Display name is @@ -1614,10 +1752,13 @@ def karma_leaderboard(mgr, as_of: Optional[str] = None, top_n: int = 10, "metadataElementTypeName": "ContributionRecord"} if as_of: body["asOfTime"] = as_of - records = _find(mgr, body) + # Every page: a top-N from one page is the top of that page, not of everyone. + records = _all_elements(mgr, body) except Exception as exc: # noqa: BLE001 logger.debug(f"karma_leaderboard: find failed: {exc}") return [] + if records is None: # failed, or incomplete (noted): no leaderboard rather than a wrong one + return [] entries: List[Dict[str, Any]] = [] for el in records: @@ -1671,9 +1812,14 @@ def engagement_series(ce, as_of: Optional[str] = None, weeks: int = 12) -> List[ a near-flat line with one or two non-zero weeks -- that's the real signal, not a rendering bug. - Returns a list of {"week": "2026-W33", "comments": int, "ratings": int, - "likes": int, "tags": int, "noteLogs": int, "total": int}, oldest week - first, length == `weeks`. Empty list on total failure (never raises). + Each relationship type is read in full, paged until Egeria returns an + empty page. A type whose query failed or whose scan was incomplete is None + in every week (with an `unmeasured` note), and so is every week's total -- + never a row of zeros (6.2.28; a failed type used to read as no activity). + + Returns a list of {"week": "2026-W33", "comments": int|None, "ratings": + int|None, "likes": int|None, "tags": int|None, "noteLogs": int|None, + "total": int|None}, oldest week first, length == `weeks` (never raises). """ from datetime import datetime, timedelta, timezone @@ -1693,14 +1839,16 @@ def _week_key(dt: datetime) -> str: buckets: Dict[str, Dict[str, int]] = {wk: {"comments": 0, "ratings": 0, "likes": 0, "tags": 0, "noteLogs": 0} for wk in week_keys} + unmeasured_fields: set = set() for rel_type, field in _FEEDBACK_RELATIONSHIP_TYPES_FOR_SERIES: try: - rel_body = {"class": "ResultsRequestBody", "asOfTime": as_of} if as_of else None - rels = _json_list(ce.get_relationships( - relationship_type=rel_type, output_format="JSON", - start_from=0, page_size=max_paging_size, body=rel_body)) + rels = _all_relationships(ce, rel_type, as_of) # every page; None when incomplete (noted) except Exception as exc: # noqa: BLE001 logger.debug(f"engagement_series: {rel_type} query failed: {exc}") + _not_measured(f"{rel_type} relationships", "the get_relationships query failed") + rels = None + if rels is None: # not measured: None in every week, never a row of zeros + unmeasured_fields.add(field) continue for r in rels: create_time = (((r.get("relationshipHeader") or {}).get("versions") or {}).get("createTime")) @@ -1716,8 +1864,8 @@ def _week_key(dt: datetime) -> str: series = [] for wk in week_keys: - b = buckets[wk] - series.append({"week": wk, **b, "total": sum(b.values())}) + b: Dict[str, Optional[int]] = {k: (None if k in unmeasured_fields else v) for k, v in buckets[wk].items()} + series.append({"week": wk, **b, "total": None if unmeasured_fields else sum(b.values())}) return series @@ -1937,16 +2085,15 @@ def active_contributors(ce, as_of: Optional[str] = None) -> Dict[str, Any]: 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, + Each type is read in full, paged until Egeria returns an empty page. A + type whose query failed or whose scan was incomplete 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 - def _actor_usernames(rel_type: str) -> set: - rels = _json_list(ce.get_relationships( - relationship_type=rel_type, output_format="JSON", - start_from=0, page_size=DEFAULT_CAP, body=body)) + rels = _all_relationships(ce, rel_type, as_of) # every page; None when incomplete (noted) + if rels is None: + raise _ScanIncomplete() return { u for rel in rels if (u := (rel.get("relationshipHeader") or {}).get("versions", {}).get("createdBy")) @@ -1958,6 +2105,10 @@ def _actor_usernames(rel_type: str) -> set: for rel_type, key in _FEEDBACK_RELATIONSHIP_TYPES: try: users = _actor_usernames(rel_type) + except _ScanIncomplete: + by_type[key] = None + measured = False + continue except Exception as exc: # noqa: BLE001 logger.debug(f"overview_metrics active_contributors: {rel_type} failed: {exc}") by_type[key] = None diff --git a/tests/micro-tests/test_capped_count_not_measured.py b/tests/micro-tests/test_capped_count_not_measured.py index 4dc5e3d8..6711c036 100644 --- a/tests/micro-tests/test_capped_count_not_measured.py +++ b/tests/micro-tests/test_capped_count_not_measured.py @@ -107,8 +107,14 @@ def test_a_native_count_above_the_cap_is_trusted(): assert notes == [] -def test_non_strict_viewer_failure_keeps_its_historical_zero(): - assert om.count_elements(_mgr(find_error=RuntimeError("boom")), "Asset", population="viewer") == 0 +def test_a_failed_viewer_count_is_none_with_a_note_strict_or_not(): + # 6.2.28: the non-strict viewer 0 is gone -- a failed query is not "no Assets". + for strict in (False, True): + with om.recording_unmeasured() as notes: + assert om.count_elements(_mgr(find_error=RuntimeError("boom")), "Asset", population="viewer", + strict=strict) is None + assert notes == [{"count": "Asset", "reason": "no native count is available, and the find fallback failed", + "at_least": None}] def test_a_classification_count_names_what_it_counted(): @@ -130,16 +136,47 @@ def test_notes_are_only_kept_inside_a_recording_block(): assert [n["count"] for n in outer] == ["Process"] -def test_a_full_relationship_page_is_not_a_relationship_count(): +def _rel_pages(rows): + """get_relationships paging like Egeria: rows from the body's startFrom, then an empty page.""" + def fake(*a, body=None, **kw): + start, size = body["startFrom"], body["pageSize"] + return rows[start:start + size] + return fake + + +def test_a_viewer_relationship_count_reads_every_page(): + # A full page is not the last page: the viewer count pages on until Egeria returns an empty page. ce = MagicMock() - ce.get_relationships.return_value = [{"guid": f"r{i}"} for i in range(CAP)] + ce.get_relationships.side_effect = _rel_pages([{"relationshipHeader": {"guid": f"r{i}"}} + for i in range(CAP + 247)]) + with om.recording_unmeasured() as notes: + assert om.count_relationships(ce, "SemanticAssignment", population="viewer") == CAP + 247 + assert notes == [] + assert [c.kwargs["body"]["startFrom"] for c in ce.get_relationships.call_args_list] == [0, CAP, 2 * CAP] + + +def test_a_relationship_scan_that_cannot_finish_is_not_a_count(): + # A server that ignores startFrom repeats the page: the count is not measured, never the page. + ce = MagicMock() + ce.get_relationships.return_value = [{"relationshipHeader": {"guid": f"r{i}"}} for i in range(CAP)] with om.recording_unmeasured() as notes: assert om.count_relationships(ce, "SemanticAssignment", population="viewer") is None - assert notes[0]["count"] == "SemanticAssignment" and notes[0]["at_least"] == CAP - ce.get_relationships.return_value = [{"guid": "r1"}] + assert notes[0]["count"] == "SemanticAssignment relationships" and notes[0]["at_least"] == CAP + ce.get_relationships.reset_mock(return_value=True) + ce.get_relationships.side_effect = _rel_pages([{"relationshipHeader": {"guid": "r1"}}]) assert om.count_relationships(ce, "SemanticAssignment", population="viewer") == 1 +def test_a_relationship_scan_stops_at_max_scan_pages_and_is_not_measured(monkeypatch): + monkeypatch.setattr(om, "MAX_SCAN_PAGES", 3) + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages([{"relationshipHeader": {"guid": f"r{i}"}} + for i in range(3 * CAP + 1)]) + with om.recording_unmeasured() as notes: + assert om.count_relationships(ce, "SemanticAssignment", population="viewer") is None + assert "stopped after 3 pages" in notes[0]["reason"] and notes[0]["at_least"] == 3 * CAP + + def test_semantic_grounding_no_longer_reports_500_links_100_percent(): mgr = _mgr(native=MagicMock(side_effect=TIMEOUT), find_result=_page(CAP)) ce = MagicMock() diff --git a/tests/micro-tests/test_capped_scans_not_counts.py b/tests/micro-tests/test_capped_scans_not_counts.py new file mode 100644 index 00000000..bf350da7 --- /dev/null +++ b/tests/micro-tests/test_capped_scans_not_counts.py @@ -0,0 +1,220 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +A figure computed from a scan is only a figure when the scan read everything (6.2.28). + +Found live 2026-11-08 (READBACK-6.2.27): `orphan_glossary_terms` read one 500-relationship +SemanticAssignment page, which held 8 distinct terms, so it reported 1,053 orphans; all 747 +relationships hold 77 terms, so the answer is 984. `stale_assets` reported staleCount 0 from a full +500-Asset page beside a not-measured assetTotal. + +Egeria's paging contract: only an EMPTY page means done; a short page is not the last page. So the +relationship scans page until an empty page, and a scan that cannot finish (MAX_SCAN_PAGES, or a +server that repeats its page) is None plus an `unmeasured` note, never a figure from the part it read. +Routines whose population is too large to page (an Asset find) report None plus a note when their +page is full, never the sample's figure. +""" +from unittest.mock import MagicMock + +import pytest + +from pyegeria.view import overview_metrics as om + +CAP = om.DEFAULT_CAP + + +@pytest.fixture(autouse=True) +def _clean(): + om._count_caps.clear() + om._native_server_ok.clear() + yield + om._count_caps.clear() + om._native_server_ok.clear() + + +def _rel_pages(table): + """get_relationships paging like Egeria, keyed by type: rows from the body's startFrom, then [].""" + def fake(*a, relationship_type=None, body=None, **kw): + rows = table.get(relationship_type, []) + if isinstance(rows, BaseException): + raise rows + return rows[body["startFrom"]:body["startFrom"] + body["pageSize"]] + return fake + + +def _find_pages(rows): + def fake(body, *a, **kw): + return rows[body["startFrom"]:body["startFrom"] + body["pageSize"]] + return fake + + +def _semantic_assignments(n_rels, n_terms): + """n_rels SemanticAssignments over n_terms distinct terms, the first page holding few of them + (as live: the first 500 relationships held 8 terms).""" + rels = [] + for i in range(n_rels): + term = f"t{i % 8}" if i < CAP else f"t{8 + (i - CAP) % (n_terms - 8)}" + rels.append({"relationshipHeader": {"guid": f"r{i}"}, + "end1": {"guid": f"a{i}", "type": {"typeName": "CSVFile", "superTypeNames": ["Asset"]}}, + "end2": {"guid": term, "type": {"typeName": "GlossaryTerm"}}}) + return rels + + +def _mgr(term_total=1061, find=None): + mgr = MagicMock(spec=["platform_url", "view_server", "find_metadata_elements", "count_metadata_elements"]) + mgr.platform_url, mgr.view_server = "https://localhost:9443", "test-server" + mgr.count_metadata_elements.return_value = {"count": term_total} + if find is not None: + mgr.find_metadata_elements.side_effect = find + return mgr + + +# ── orphan_glossary_terms ────────────────────────────────────────────────── + +def test_orphan_terms_read_every_semantic_assignment_page(): + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({"SemanticAssignment": _semantic_assignments(747, 77)}) + with om.recording_unmeasured() as notes: + r = om.orphan_glossary_terms(_mgr(), ce) + assert r == {"termTotal": 1061, "referencedCount": 77, "orphanCount": 984} # not 8 / 1,053 + assert notes == [] + assert [c.kwargs["body"]["startFrom"] for c in ce.get_relationships.call_args_list] == [0, CAP, 2 * CAP] + + +def test_a_short_page_is_not_the_last_page(): + # A server may filter hits out of a page after fetching it: a short page with more behind it. + rels = _semantic_assignments(747, 77) + pages = [rels[:300], rels[CAP:], []] + ce = MagicMock() + ce.get_relationships.side_effect = lambda *a, body=None, **kw: pages[body["startFrom"] // CAP] + r = om.orphan_glossary_terms(_mgr(), ce) + assert r["referencedCount"] == 77 and len(ce.get_relationships.call_args_list) == 3 + + +def test_an_incomplete_semantic_assignment_scan_is_not_an_orphan_count(monkeypatch): + monkeypatch.setattr(om, "MAX_SCAN_PAGES", 1) + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({"SemanticAssignment": _semantic_assignments(747, 77)}) + with om.recording_unmeasured() as notes: + r = om.orphan_glossary_terms(_mgr(), ce) + assert r == {"termTotal": 1061, "referencedCount": None, "orphanCount": None} + assert notes == [{"count": "SemanticAssignment relationships", "at_least": CAP, + "reason": f"the relationship scan stopped after 1 pages of {CAP} ({CAP} read) before Egeria " + f"returned an empty page, so it is incomplete"}] + + +def test_relationship_scans_carry_paging_and_as_of_in_the_body(): + # get_relationships ignores start_from/page_size whenever a body is given, so the body must carry them. + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({}) + om.orphan_glossary_terms(_mgr(), ce, as_of="2026-11-01T00:00:00Z") + assert ce.get_relationships.call_args.kwargs["body"] == { + "class": "ResultsRequestBody", "startFrom": 0, "pageSize": CAP, "asOfTime": "2026-11-01T00:00:00Z"} + + +# ── stale_assets ──────────────────────────────────────────────────────────── + +def _assets(n, updated="2020-01-01T00:00:00+00:00"): + return [{"elementGUID": f"a{i}", "elementHeader": {"versions": {"updateTime": updated}}} for i in range(n)] + + +def test_a_full_asset_page_is_not_a_stale_count(): + mgr = _mgr(find=lambda body, *a, **kw: _assets(CAP, updated="2026-11-01T00:00:00+00:00")) + mgr.count_metadata_elements.side_effect = RuntimeError("timed out") + with om.recording_unmeasured() as notes: + r = om.stale_assets(mgr, as_of="2026-11-08T00:00:00Z") + assert r["staleCount"] is None # was 0: none of the first 500 were stale + assert r["assetTotal"] is None + stale = [n for n in notes if n["count"] == "Assets not updated within 180 days"] + assert stale and stale[0]["at_least"] == CAP and "only the first 500" in stale[0]["reason"] + + +def test_a_short_asset_page_is_counted(): + mgr = _mgr(find=lambda body, *a, **kw: _assets(3) + _assets(2, "2026-11-01T00:00:00+00:00")) + r = om.stale_assets(mgr, as_of="2026-11-08T00:00:00Z") + assert r["staleCount"] == 3 + + +# ── the other scanners ───────────────────────────────────────────────────── + +def test_ai_ready_and_drl_on_a_full_asset_page_measure_nothing(): + mgr = _mgr(find=lambda body, *a, **kw: _assets(CAP)) + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({}) + with om.recording_unmeasured() as notes: + assert om.ai_ready_assets(mgr, ce) == {"aiReadyCount": None, "total": None, "capped": True} + assert om.drl_readiness_gates(mgr, ce) == {"total": None, "capped": True, "aiReadyCount": None, + "aiReadyRecentCount": None, "byModality": None} + assert [n["count"] for n in notes] == ["AI-ready Assets", "DRL readiness gates"] + ce.get_relationships.assert_not_called() + + +def test_lineage_reads_every_dataflow_page(): + asset = {"elementGUID": "a1", "classifications": [{"classificationName": "Confidentiality"}], + "elementProperties": {"propertyValueMap": {"description": {"primitiveValue": "d"}}}} + mgr = _mgr(find=_find_pages([asset])) + flows = [{"relationshipHeader": {"guid": f"f{i}"}, "end1": {"guid": f"x{i}"}, "end2": {"guid": f"y{i}"}} + for i in range(CAP)] + [{"relationshipHeader": {"guid": "last"}, "end1": {"guid": "a1"}, "end2": {}}] + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({"DataFlow": flows}) + assert om.ai_ready_assets(mgr, ce) == {"aiReadyCount": 1, "total": 1, "capped": False} # a1 is on page 2 + + +@pytest.mark.parametrize("routine,field", [(om.governed_coverage, "governedCount"), + (om.ownership_coverage, "ownershipCount")]) +def test_coverage_finds_page_past_the_first_page(routine, field): + els = [{"elementGUID": f"e{i}", "classifications": [{"classificationName": "Ownership"}]} + for i in range(CAP + 1)] + r = routine(_mgr(find=_find_pages(els))) + assert r[field] == CAP + 1 + + +def test_karma_leaderboard_reads_every_page(): + def rec(i, karma): + return {"elementGUID": f"c{i}", "elementProperties": {"propertyValueMap": { + "karmaPoints": {"primitiveValue": karma}, + "displayName": {"primitiveValue": f"Contribution record for p{i}"}}}, + "classifications": [{"classificationName": "Anchors", "classificationProperties": { + "propertyValueMap": {"anchorTypeName": {"primitiveValue": "Person"}}}}]} + records = [rec(i, 1) for i in range(CAP)] + [rec(CAP, 99)] # the top contributor is on page 2 + top = om.karma_leaderboard(_mgr(find=_find_pages(records)), top_n=1) + assert top[0]["name"] == f"p{CAP}" and top[0]["karmaPoints"] == 99 + + +def test_certifications_scan_reads_every_page(): + certs = [{"relationshipHeader": {"guid": f"c{i}"}} for i in range(CAP + 3)] + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({"Certification": certs}) + assert om.certifications_summary(ce)["active"] == CAP + 3 + + +@pytest.mark.parametrize("routine,field", [(om.contextualised_coverage, "contextualisedCount"), + (om.solution_component_realisation, "solutionComponentsRealised")]) +def test_implemented_by_scans_read_every_page(routine, field): + rels = [{"relationshipHeader": {"guid": f"r{i}"}, + "end1": {"guid": f"sc{i}", "type": {"typeName": "SolutionComponent"}}, + "end2": {"guid": f"a{i}", "type": {"typeName": "CSVFile", "superTypeNames": ["Asset"]}}} + for i in range(CAP + 2)] + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({"ImplementedBy": rels}) + assert routine(_mgr(term_total=2000), ce)[field] == CAP + 2 + + +def test_active_contributors_read_every_page_and_an_incomplete_type_is_none(monkeypatch): + rows = [{"relationshipHeader": {"guid": f"r{i}", "versions": {"createdBy": f"u{i}"}}} for i in range(CAP + 1)] + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({"AttachedRating": rows}) + assert om.active_contributors(ce)["byType"]["ratings"] == CAP + 1 + monkeypatch.setattr(om, "MAX_SCAN_PAGES", 1) + r = om.active_contributors(ce) + assert r["byType"]["ratings"] is None and r["contributors"] is None + + +def test_engagement_series_a_failed_type_is_none_never_a_row_of_zeros(): + ce = MagicMock() + ce.get_relationships.side_effect = _rel_pages({"AttachedComment": RuntimeError("down")}) + with om.recording_unmeasured() as notes: + series = om.engagement_series(ce, as_of="2026-11-08T00:00:00Z", weeks=3) + assert len(series) == 3 + assert all(p["comments"] is None and p["total"] is None and p["ratings"] == 0 for p in series) + assert notes and notes[0]["count"] == "AttachedComment relationships" diff --git a/tests/micro-tests/test_issue_123_strict_counts.py b/tests/micro-tests/test_issue_123_strict_counts.py index ce8720dc..e26540a3 100644 --- a/tests/micro-tests/test_issue_123_strict_counts.py +++ b/tests/micro-tests/test_issue_123_strict_counts.py @@ -40,8 +40,9 @@ def _reset_seam_caches(): om._native_server_ok.clear() -def test_default_still_returns_zero_on_failure_in_the_viewer_population(): - assert om.count_elements(_mgr(find_error=RuntimeError("401")), "Asset", population="viewer") == 0 +def test_a_failed_viewer_count_is_none_not_zero(): + # 6.2.28: the historical non-strict 0 is gone -- a failed query is not "none of them". + assert om.count_elements(_mgr(find_error=RuntimeError("401")), "Asset", population="viewer") is None def test_a_failed_repository_count_is_none_never_zero(): @@ -86,7 +87,7 @@ def test_strict_native_count_is_trusted_even_above_the_cap(): def test_strict_by_property(): mgr = _mgr(find_error=RuntimeError("500")) assert om.count_elements_by_property(mgr, "DigitalProduct", "deploymentStatus", "ACTIVE", - population="viewer") == 0 + population="viewer") is None assert om.count_elements_by_property(mgr, "DigitalProduct", "deploymentStatus", "ACTIVE", strict=True) is None @@ -96,7 +97,7 @@ def test_strict_propagates_through_the_composite_counts(): assert om.counts_by_type(mgr, [("Stores", "DataStore")], strict=True)[0]["count"] is None assert set(om.people_counts(mgr, strict=True).values()) == {None} assert set(om.usage_context_counts(mgr, strict=True).values()) == {None} - assert set(om.people_counts(mgr, population="viewer").values()) == {0} + assert set(om.people_counts(mgr, population="viewer").values()) == {None} # never 0 (6.2.28) assert set(om.people_counts(mgr).values()) == {None} # repository: no fallback, never 0 diff --git a/tests/micro-tests/test_overview_metrics.py b/tests/micro-tests/test_overview_metrics.py index 730a716b..037b2758 100644 --- a/tests/micro-tests/test_overview_metrics.py +++ b/tests/micro-tests/test_overview_metrics.py @@ -25,6 +25,27 @@ def _mgr(**attrs): return m +def _pages(rows): + """A get_relationships / find_metadata_elements fake that pages like Egeria: the rows from the + body's startFrom (where the scans put it), then an empty page -- the only end-of-scan signal.""" + def fake(*args, **kw): + body = kw.get("body") or next((a for a in args if isinstance(a, dict)), None) or {} + start = body.get("startFrom", kw.get("start_from", 0)) or 0 + size = body.get("pageSize", kw.get("page_size", 0)) or om.DEFAULT_CAP + return list(rows[start:start + size]) + return fake + + +def _by_type(table): + """A paging get_relationships fake keyed by relationship type; an exception value is raised.""" + def fake(*args, relationship_type=None, **kw): + rows = table.get(relationship_type, []) + if isinstance(rows, BaseException): + raise rows + return _pages(rows)(*args, **kw) + return fake + + def _native(answer): """A native count method fake: `answer(body)` gives the count for each request body.""" return MagicMock(side_effect=lambda body, **kw: {"count": answer(body)}) @@ -67,7 +88,7 @@ def test_count_elements_native_returns_plain_int(): def test_count_elements_falls_back_when_no_native_method(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [{"a": 1}, {"b": 2}, {"c": 3}] + mgr.find_metadata_elements.side_effect = _pages([{"a": 1}, {"b": 2}, {"c": 3}]) n = om.count_elements(mgr, type_name="Asset", population="viewer") assert n == 3 mgr.find_metadata_elements.assert_called_once() @@ -75,7 +96,7 @@ def test_count_elements_falls_back_when_no_native_method(): def test_count_elements_falls_back_when_native_raises(): mgr = _mgr(count_metadata_elements=MagicMock(side_effect=RuntimeError("not supported"))) - mgr.find_metadata_elements.return_value = [{"a": 1}] + mgr.find_metadata_elements.side_effect = _pages([{"a": 1}]) n = om.count_elements(mgr, type_name="Asset", population="viewer") assert n == 1 # second call should skip native entirely (server marked unsupported) @@ -86,7 +107,7 @@ def test_count_elements_falls_back_when_native_raises(): def test_count_elements_passes_as_of_and_classifications(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [] + mgr.find_metadata_elements.side_effect = _pages([]) om.count_elements(mgr, type_name="Asset", as_of="2026-01-01T00:00:00+00:00", classifications=["ZoneMembership", "Confidentiality"], population="viewer") body = mgr.find_metadata_elements.call_args[0][0] @@ -100,7 +121,7 @@ def test_count_elements_passes_as_of_and_classifications(): def test_count_relationships_viewer_path_without_expert(): ce = MagicMock() - ce.get_relationships.return_value = [{"a": 1}, {"b": 2}] + ce.get_relationships.side_effect = _pages([{"a": 1}, {"b": 2}]) n = om.count_relationships(ce, "Certification", population="viewer") assert n == 2 @@ -186,17 +207,33 @@ def test_governed_coverage_extracts_classifications_and_zones(): }}}}, ]}, ] - mgr.find_metadata_elements.return_value = hits + mgr.find_metadata_elements.side_effect = _pages(hits) result = om.governed_coverage(mgr) assert result["governedCount"] == 2 assert result["byClassification"] == {"Confidentiality": 1, "ZoneMembership": 1} assert result["topZones"] == [{"zone": "clinical-trial", "count": 1}] -def test_governed_coverage_capped_flag(): +def test_governed_coverage_pages_past_the_first_page(): + # Every page is read until Egeria returns an empty one: 501 governed elements is 501, not "at least 500". mgr = _mgr() - mgr.find_metadata_elements.return_value = [{}] * om.DEFAULT_CAP - assert om.governed_coverage(mgr)["governedCapped"] is True + hits = [{"elementGUID": f"g{i}", "classifications": [{"classificationName": "Confidentiality"}]} + for i in range(om.DEFAULT_CAP + 1)] + mgr.find_metadata_elements.side_effect = _pages(hits) + r = om.governed_coverage(mgr) + assert r["governedCount"] == om.DEFAULT_CAP + 1 and r["governedCapped"] is False + assert r["byClassification"] == {"Confidentiality": om.DEFAULT_CAP + 1} + assert [c.args[0]["startFrom"] for c in mgr.find_metadata_elements.call_args_list] == [0, 500, 1000] + + +def test_governed_coverage_incomplete_scan_is_not_measured(): + # A server that ignores startFrom repeats its page: the scan is incomplete, so nothing is reported. + mgr = _mgr() + mgr.find_metadata_elements.return_value = [{"elementGUID": f"g{i}"} for i in range(om.DEFAULT_CAP)] + with om.recording_unmeasured() as notes: + r = om.governed_coverage(mgr) + assert r["governedCount"] is None and r["governedCapped"] is None and r["fullyGoverned"] is None + assert notes and "repeated only what it had already read" in notes[0]["reason"] # ── certifications_summary ──────────────────────────────────────────────── @@ -206,14 +243,14 @@ def test_certifications_summary_shape_and_expiry(): from datetime import datetime, timezone, timedelta soon_date = (datetime.now(timezone.utc) + timedelta(days=30)).isoformat() far_date = (datetime.now(timezone.utc) + timedelta(days=400)).isoformat() - ce.get_relationships.side_effect = [ - [ + ce.get_relationships.side_effect = _by_type({ + "Certification": [ {"relationshipProperties": {"coverageEnd": soon_date}, "end2": {"properties": {"displayName": "cert-A"}}}, {"relationshipProperties": {"coverageEnd": far_date}}, ], - [{"x": 1}], # License - [], # Exception - ] + "License": [{"x": 1}], + "Exception": [], + }) result = om.certifications_summary(ce) assert result["active"] == 2 assert result["expiring90"] == 1 @@ -247,9 +284,9 @@ def test_semantic_grounding_computes_percent(): def test_semantic_grounding_handles_zero_cataloged(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [] + mgr.find_metadata_elements.side_effect = _pages([]) ce = MagicMock() - ce.get_relationships.return_value = [] + ce.get_relationships.side_effect = _pages([]) result = om.semantic_grounding(mgr, ce) assert result["groundingPct"] is None @@ -315,35 +352,35 @@ def _asset(guid, description=None, classifications=None): def test_ai_ready_assets_requires_all_three_criteria(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [ + mgr.find_metadata_elements.side_effect = _pages([ _asset("a1", "documented", ["Confidentiality"]), # governed + documented, NOT lineage-traced _asset("a2", "documented", ["Confidentiality"]), # governed + documented + lineage-traced -> AI-ready _asset("a3", None, ["Confidentiality"]), # governed + lineage-traced, NOT documented _asset("a4", "documented", []), # documented + lineage-traced, NOT governed - ] + ]) ce = MagicMock() - ce.get_relationships.return_value = [ + ce.get_relationships.side_effect = _pages([ {"end1": {"guid": "a2"}, "end2": {"guid": "a3"}}, {"end1": {"guid": "a4"}, "end2": {"guid": "other-asset"}}, - ] + ]) result = om.ai_ready_assets(mgr, ce) assert result == {"aiReadyCount": 1, "total": 4, "capped": False} def test_ai_ready_assets_empty_catalog(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [] + mgr.find_metadata_elements.side_effect = _pages([]) ce = MagicMock() - ce.get_relationships.return_value = [] + ce.get_relationships.side_effect = _pages([]) result = om.ai_ready_assets(mgr, ce) assert result == {"aiReadyCount": 0, "total": 0, "capped": False} def test_ai_ready_assets_lineage_query_failure_is_unmeasured(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [ + mgr.find_metadata_elements.side_effect = _pages([ _asset("a1", "documented", ["Confidentiality"]), - ] + ]) ce = MagicMock() ce.get_relationships.side_effect = Exception("boom") result = om.ai_ready_assets(mgr, ce) @@ -393,18 +430,18 @@ def _asset_full(guid, description=None, classifications=None, type_name=None, up def test_drl_readiness_gates_narrows_ai_ready_by_recency(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [ + mgr.find_metadata_elements.side_effect = _pages([ _asset_full("a1", "documented", ["Confidentiality"], "RelationalTable", update_time="2026-08-01T00:00:00Z"), # AI-ready + recent _asset_full("a2", "documented", ["Confidentiality"], "PDFFile", update_time="2020-01-01T00:00:00Z"), # AI-ready, stale _asset_full("a3", None, ["Confidentiality"], "APIEndpoint"), # not documented - ] + ]) ce = MagicMock() - ce.get_relationships.return_value = [ + ce.get_relationships.side_effect = _pages([ {"end1": {"guid": "a1"}, "end2": {"guid": "x"}}, {"end1": {"guid": "a2"}, "end2": {"guid": "y"}}, - ] + ]) result = om.drl_readiness_gates(mgr, ce, as_of="2026-08-02T00:00:00Z", recency_days=180) assert result["total"] == 3 assert result["aiReadyCount"] == 2 @@ -414,9 +451,9 @@ def test_drl_readiness_gates_narrows_ai_ready_by_recency(): def test_drl_readiness_gates_empty_catalog(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [] + mgr.find_metadata_elements.side_effect = _pages([]) ce = MagicMock() - ce.get_relationships.return_value = [] + ce.get_relationships.side_effect = _pages([]) result = om.drl_readiness_gates(mgr, ce) assert result["total"] == 0 assert result["aiReadyCount"] == 0 @@ -426,11 +463,11 @@ def test_drl_readiness_gates_empty_catalog(): def test_drl_readiness_gates_missing_update_time_not_counted_recent(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [ + mgr.find_metadata_elements.side_effect = _pages([ _asset_full("a1", "documented", ["Confidentiality"], "RelationalTable"), # no updateTime - ] + ]) ce = MagicMock() - ce.get_relationships.return_value = [{"end1": {"guid": "a1"}, "end2": {"guid": "x"}}] + ce.get_relationships.side_effect = _pages([{"end1": {"guid": "a1"}, "end2": {"guid": "x"}}]) result = om.drl_readiness_gates(mgr, ce) assert result["aiReadyCount"] == 1 assert result["aiReadyRecentCount"] == 0 @@ -502,7 +539,8 @@ def test_usage_context_counts_shape(): def test_feedback_summary_sums_by_type(): ce = MagicMock() - ce.get_relationships.side_effect = [[{}] * 3, [{}] * 1, [], [{}] * 2, []] + ce.get_relationships.side_effect = _by_type({"AttachedRating": [{}] * 3, "AttachedComment": [{}], + "AttachedTag": [{}] * 2}) result = om.feedback_summary(ce, population="viewer") assert result["byType"] == {"ratings": 3, "comments": 1, "likes": 0, "tags": 2, "noteLogs": 0} assert result["total"] == 6 @@ -589,14 +627,12 @@ def answer(body): def test_active_contributors_dedupes_by_username_across_types(): ce = MagicMock() - ce.get_relationships.side_effect = [ - [{"relationshipHeader": {"versions": {"createdBy": "alice"}}}, - {"relationshipHeader": {"versions": {"createdBy": "alice"}}}], # ratings - [{"relationshipHeader": {"versions": {"createdBy": "bob"}}}], # comments - [], # likes - [], # tags - [{"relationshipHeader": {"versions": {"createdBy": "alice"}}}], # noteLogs - ] + ce.get_relationships.side_effect = _by_type({ + "AttachedRating": [{"relationshipHeader": {"guid": "r1", "versions": {"createdBy": "alice"}}}, + {"relationshipHeader": {"guid": "r2", "versions": {"createdBy": "alice"}}}], + "AttachedComment": [{"relationshipHeader": {"guid": "c1", "versions": {"createdBy": "bob"}}}], + "AttachedNoteLog": [{"relationshipHeader": {"guid": "n1", "versions": {"createdBy": "alice"}}}], + }) result = om.active_contributors(ce) assert result["contributors"] == 2 # alice, bob assert result["byType"] == {"ratings": 1, "comments": 1, "likes": 0, "tags": 0, "noteLogs": 1} @@ -604,11 +640,10 @@ def test_active_contributors_dedupes_by_username_across_types(): def test_active_contributors_degrades_per_type_on_failure(): ce = MagicMock() - ce.get_relationships.side_effect = [ - RuntimeError("boom"), - [{"relationshipHeader": {"versions": {"createdBy": "bob"}}}], - [], [], [], - ] + ce.get_relationships.side_effect = _by_type({ + "AttachedRating": RuntimeError("boom"), + "AttachedComment": [{"relationshipHeader": {"versions": {"createdBy": "bob"}}}], + }) result = om.active_contributors(ce) # 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 @@ -678,7 +713,7 @@ def test_count_elements_by_property_uses_native_when_available(): def test_count_elements_by_property_falls_back_when_no_native_method(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [{}, {}, {}] + mgr.find_metadata_elements.side_effect = _pages([{}, {}, {}]) n = om.count_elements_by_property(mgr, "DigitalProduct", "deploymentStatus", "ACTIVE", population="viewer") assert n == 3 @@ -711,11 +746,11 @@ def _implemented_by(end1_type, end2_type, end2_guid, super_types=None): def test_contextualised_coverage_counts_only_asset_subtype_ends(): mgr = _mgr(count_metadata_elements=MagicMock(return_value={"count": 384})) ce = MagicMock() - ce.get_relationships.return_value = [ + ce.get_relationships.side_effect = _pages([ _implemented_by("SolutionComponent", "GovernanceActionType", "gat-1"), _implemented_by("SolutionComponent", "IntegrationConnector", "asset-1", super_types=["Asset"]), _implemented_by("SolutionComponent", "SoftwareServer", "asset-2", super_types=["Asset"]), - ] + ]) result = om.contextualised_coverage(mgr, ce) assert result["contextualisedCount"] == 2 assert result["assetTotal"] == 384 @@ -725,10 +760,10 @@ def test_contextualised_coverage_counts_only_asset_subtype_ends(): def test_contextualised_coverage_dedupes_by_guid(): mgr = _mgr(count_metadata_elements=MagicMock(return_value={"count": 10})) ce = MagicMock() - ce.get_relationships.return_value = [ + ce.get_relationships.side_effect = _pages([ _implemented_by("SolutionComponent", "SoftwareServer", "asset-1", super_types=["Asset"]), _implemented_by("SolutionComponent", "SoftwareServer", "asset-1", super_types=["Asset"]), - ] + ]) result = om.contextualised_coverage(mgr, ce) assert result["contextualisedCount"] == 1 @@ -737,9 +772,9 @@ def test_contextualised_coverage_matches_asset_typename_directly_too(): # end2's own typeName (not just its superTypeNames) can be "Asset". mgr = _mgr(count_metadata_elements=MagicMock(return_value={"count": 5})) ce = MagicMock() - ce.get_relationships.return_value = [ + ce.get_relationships.side_effect = _pages([ _implemented_by("SolutionComponent", "Asset", "asset-1"), - ] + ]) result = om.contextualised_coverage(mgr, ce) assert result["contextualisedCount"] == 1 @@ -757,7 +792,7 @@ def test_contextualised_coverage_relationship_fetch_failure_yields_none_count(): def test_contextualised_coverage_zero_asset_total_yields_none_pct_not_zero_division(): mgr = _mgr(count_metadata_elements=MagicMock(return_value={"count": 0})) ce = MagicMock() - ce.get_relationships.return_value = [] + ce.get_relationships.side_effect = _pages([]) result = om.contextualised_coverage(mgr, ce) assert result["contextualisedCount"] == 0 assert result["assetTotal"] is None @@ -775,7 +810,7 @@ def test_funnel_keeps_measured_zero_and_none_on_failure(): mgr.count_metadata_elements.side_effect = RuntimeError("down") mgr.count_relationships_between_elements.side_effect = RuntimeError("down") - mgr.find_metadata_elements.return_value = [] # a viewer answer must never stand in + mgr.find_metadata_elements.side_effect = _pages([]) # a viewer answer must never stand in r = om.context_readiness_funnel(mgr, ce) assert r["cataloged"] is None and r["classified"] is None assert r["documented"] is None and r["lineage"] is None @@ -783,7 +818,7 @@ def test_funnel_keeps_measured_zero_and_none_on_failure(): def test_feedback_summary_total_none_unless_all_measured(): ce = MagicMock() - ce.get_relationships.side_effect = [[{}] * 3, RuntimeError("x"), [], [], []] + ce.get_relationships.side_effect = _by_type({"AttachedRating": [{}] * 3, "AttachedComment": RuntimeError("x")}) r = om.feedback_summary(ce, population="viewer") assert r["byType"]["comments"] is None and r["byType"]["ratings"] == 3 assert r["total"] is None @@ -804,7 +839,7 @@ def test_governed_coverage_and_business_value_none_on_failed_find(): def test_timeout_does_not_disable_native_counting(): from pyegeria.core._exceptions import PyegeriaTimeoutException mgr = _mgr(count_metadata_elements=MagicMock(side_effect=[PyegeriaTimeoutException(), 987])) - mgr.find_metadata_elements.return_value = [{}] * 3 + mgr.find_metadata_elements.side_effect = _pages([{}] * 3) assert om.count_elements(mgr, "Asset", population="viewer") == 3 # that one count falls back assert not om._native_disabled(mgr) assert om.count_elements(mgr, "GlossaryTerm", strict=True) == 987 # native still used @@ -812,7 +847,7 @@ def test_timeout_does_not_disable_native_counting(): def test_transient_generic_error_does_not_disable_native(): mgr = _mgr(count_metadata_elements=MagicMock(side_effect=[RuntimeError("boom"), 5])) - mgr.find_metadata_elements.return_value = [] + mgr.find_metadata_elements.side_effect = _pages([]) om.count_elements(mgr, "Asset") assert not om._native_disabled(mgr) assert om.count_elements(mgr, "Asset") == 5 @@ -825,7 +860,7 @@ def test_not_supported_error_disables_native(): for exc in (PyegeriaNotFoundException(resp), RuntimeError("Operation not implemented")): om._native_server_ok.clear(); om._count_caps.clear() mgr = _mgr(count_metadata_elements=MagicMock(side_effect=exc)) - mgr.find_metadata_elements.return_value = [{}] * 2 + mgr.find_metadata_elements.side_effect = _pages([{}] * 2) assert om.count_elements(mgr, "Asset", population="viewer") == 2 assert om._native_disabled(mgr) om.count_elements(mgr, "Asset", population="viewer") @@ -867,7 +902,7 @@ def test_invalid_scope_raises(): 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 + mgr.find_metadata_elements.side_effect = _pages([{}] * 43) # viewer-scope answer with om.recording_unmeasured() as notes: assert om.count_elements(mgr, "Asset", strict=True, population="repository") is None assert om.count_elements(mgr, "Asset", population="repository") is None # never 0, strict or not @@ -877,7 +912,7 @@ def test_repository_scope_failure_strict_is_none_not_find_result(): def test_repository_scope_without_native_method_is_none(): mgr = _mgr() - mgr.find_metadata_elements.return_value = [{}] * 3 + mgr.find_metadata_elements.side_effect = _pages([{}] * 3) 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 @@ -898,12 +933,12 @@ def test_count_relationships_scope(): expert.platform_url, expert.view_server = "u", "v" expert.count_relationships_between_elements.return_value = 4 ce = MagicMock() - ce.get_relationships.return_value = [{}] * 9 + ce.get_relationships.side_effect = _pages([{}] * 9) 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, and ce has no native count: repository scope cannot be answered by the viewer-scoped path ce = MagicMock(spec=["get_relationships"]) - ce.get_relationships.return_value = [{}] * 9 + ce.get_relationships.side_effect = _pages([{}] * 9) with om.recording_unmeasured() as notes: assert om.count_relationships(ce, "License", population="repository") is None assert om.count_relationships(ce, "License") is None # repository is the default @@ -1188,5 +1223,5 @@ def test_scope_none_reaches_the_server_default_through_every_composite(): calls = mgr.count_metadata_elements.call_args_list assert len(calls) == 1 + 5 + 2 + 4 + 2 * 4 and all(c.kwargs == {} for c in calls) ce = MagicMock() - ce.get_relationships.return_value = [{}] * 2 + ce.get_relationships.side_effect = _pages([{}] * 2) assert om.feedback_summary(ce, scope=None)["total"] == 10 # the get_relationships path, not None 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 86f3855d..4e2a1299 100644 --- a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py +++ b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py @@ -238,12 +238,15 @@ def _clients(): 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")] + assets = [_asset("a1", "d", ["Confidentiality", "ZoneMembership"]), + _asset("a2"), _asset("a3", "d", upd="2025-01-01T00:00:00+00:00")] + # Both fakes page like Egeria (rows from startFrom, then an empty page): the scans read to an empty page. + mgr.find_metadata_elements.side_effect = lambda body, *a, **k: assets[body.get("startFrom", 0):][:body.get( + "pageSize") or len(assets)] 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] + ce.get_relationships.side_effect = lambda *a, body=None, **k: [_REL][(body or {}).get("startFrom", 0):] return mgr, ce