From 1f7ec15d2125d922c525abe766f5ac8f3c4bee65 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 16:14:55 +0000 Subject: [PATCH] fix(overview-metrics): stale_assets counts by update-time bisection; orphan terms count while scanning Egeria cannot count by an update-time condition: a search condition reaches only an element's own properties, so `updateTime LT ` counts 0 (checked live and in the postgres QueryBuilder). It does sort by update time, and startFrom is an offset into the repository's sorted rows. So stale_assets now finds the stale count as the offset of the first Asset updated at or after the cutoff: about log2(N/25) one-row reads plus one read of the last 25-row window, never a page of Assets. Both figures are in the repository population. Live as erinoverview: 287 of 37,568 Assets in 13.3 s, where 6.2.28 took 34.5 s to report "not measured". Hidden rows exactly at the cutoff, a failed read or an exhausted read budget give None plus a note (with the range). Distinct relationship ends cannot be counted natively, so orphan_glossary_terms keeps its SemanticAssignment scan; its slow viewer term count (13.5 s) now runs on its own thread while the scan pages: 22.6 s -> 16.8 s, same answer (984 of 1,061). Catalog Growth, Ownership and Governance were reviewed: none pages where a count would do (see the PR body). Signed-off-by: Dan Wolfson --- docs/output-formats-and-report-specs.md | 8 +- docs/release-notes/6.2.29.md | 20 ++ pyegeria/view/analytic_registry.py | 32 +-- pyegeria/view/overview_metrics.py | 171 ++++++++++--- .../test_capped_scans_not_counts.py | 17 +- .../test_native_counts_dashboard.py | 233 ++++++++++++++++++ 6 files changed, 414 insertions(+), 67 deletions(-) create mode 100644 docs/release-notes/6.2.29.md create mode 100644 tests/micro-tests/test_native_counts_dashboard.py diff --git a/docs/output-formats-and-report-specs.md b/docs/output-formats-and-report-specs.md index fc281f36..ff44a4a2 100644 --- a/docs/output-formats-and-report-specs.md +++ b/docs/output-formats-and-report-specs.md @@ -1102,9 +1102,13 @@ A count a routine could not establish is `None`, never `0` and never the cap (#5 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. +**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. `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`), because a page of Assets is a sample, not the catalog. (`stale_assets` did the same in 6.2.28; see **Counting by update time** below.) 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. +**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`) stay viewer-scoped, and no payload mixes the two populations in one ratio. `stale_assets` is in the repository population from 6.2.29. + +**Counting by update time (6.2.29).** Egeria cannot count by an update-time condition: a search condition reaches only an element's own properties, and `updateTime` is in its header, so a count with `updateTime LT ` answers 0. Egeria can sort by update time (`sequencingOrder: LAST_UPDATE_OLDEST`), and `startFrom` is an offset into the repository's own sorted rows: a row the viewer cannot see keeps its offset and comes back as an empty one-row page. So `stale_assets` counts the Assets last updated before the cutoff as the offset of the first row updated at or after it, found by bisection: about log2(total / 25) one-row reads, then one read of the last window of at most 25 rows (12 reads for 37,000 Assets). A hidden row between two rows updated before the cutoff was updated before it too, so `staleCount` is in the repository population, like its `assetTotal`. Only hidden rows exactly at the cutoff cannot be placed; then `staleCount` is `None` with a note giving the range. Live, as `erinoverview` on 2026-11-09: 287 of 37,568 Assets in 13 s, where 6.2.28 took 35 s to report "not measured". + +**Distinct relationship ends cannot be counted natively.** `orphan_glossary_terms` therefore still scans every `SemanticAssignment` relationship (about 8 KB each). Its term total is a viewer count, to match the scan's population, and that is slow (13.5 s live for 1,061 terms, against 0.7 s in the repository population); from 6.2.29 it runs on its own thread while the scan pages. #### Routines, declarations and roles diff --git a/docs/release-notes/6.2.29.md b/docs/release-notes/6.2.29.md new file mode 100644 index 00000000..d63e058a --- /dev/null +++ b/docs/release-notes/6.2.29.md @@ -0,0 +1,20 @@ +# pyegeria 6.2.29 + +## Changed + +- **`stale_assets` gives a real answer.** It read one page of 500 Assets, so on any catalog with + more Assets its `staleCount` was `None` ("not measured") every time, and it took about 35 s to say + so (most of it a viewer Asset count that timed out). Egeria cannot count by an update-time + condition, but it sorts by update time, and `startFrom` is an offset into the repository's own + sorted rows. So `staleCount` is now the offset of the first Asset updated at or after the cutoff, + found by bisection: about log2(Assets / 25) one-row reads, then one read of the last window of at + most 25 rows. Live, as `erinoverview`: 287 of 37,568 Assets, in 13 s. Both figures are now in the + **repository** population (they include Assets you may not be able to see); 6.2.28 counted + `assetTotal` in the viewer population. `staleCount` is `None` with a note when Assets you cannot + see sit exactly at the cutoff (the note gives the range), when a read fails, or when the + bisection's 64 reads run out. The declaration says `population="repository"` for both measures, + and `staleCount` has `assetTotal` as its basis. +- **`orphan_glossary_terms` is faster.** Distinct relationship ends cannot be counted natively, so + it still scans every `SemanticAssignment` relationship. Its viewer term count (13.5 s live) now + runs on its own thread while the scan pages: 22.6 s became 16.8 s live, with the same answer (984 + orphans of 1,061 terms). diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index ca83dd05..b6d74b1b 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -1761,10 +1761,11 @@ def _always_applies(what: str) -> str: inputs=["egeria_client:MetadataExpert", "egeria_client:ClassificationExplorer"], description="Approved-but-unassigned glossary terms -- a term with no SemanticAssignment " "relationship to anything was authored but never put to use grounding the " - "catalog. One bounded SemanticAssignment fetch, distinct GlossaryTerm-end GUID " - "count is the 'referenced' set; orphan = term total - referenced. Takes two " + "catalog. Every SemanticAssignment relationship, paged until Egeria returns an empty " + "page; the distinct GlossaryTerm-end GUID count is the 'referenced' set (Egeria cannot " + "count distinct relationship ends natively); orphan = term total - referenced. Takes two " "leading clients (mgr, ce), same convention as semantic_grounding. " - "Cost: one count plus one relationship scan, paged until Egeria returns an empty page, seconds.", + "Cost: one viewer count, run at the same time as one relationship scan, seconds.", returns="dict (termTotal, referencedCount, orphanCount)", generic=False, binding_note="Fixed to the SemanticAssignment relationship type and GlossaryTerm elements -- not a parameter.", @@ -1797,10 +1798,13 @@ def _always_applies(what: str) -> str: function="pyegeria.view.overview_metrics.stale_assets", inputs=["egeria_client:MetadataExpert"], 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 Asset find page (a full page is a sample, so staleCount is not measured) plus one " - "count, seconds.", + "archival review. Egeria cannot count by update time, but it sorts by it, so the " + "stale count is a bisection over the Assets' offsets in update-time order, using " + "one-row reads, never a page of Assets." + + REPOSITORY_WORDS + + " Cost: one native count plus about log2(Assets / 25) one-row reads and one 25-row read (12 for " + "37,000 Assets), " + "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.", @@ -1810,18 +1814,18 @@ def _always_applies(what: str) -> str: ], declaration=AnalyticDeclaration( result_kind="measure", - # staleCount comes from one find page (None when full), assetTotal from a native count: no basis. + # Both in the repository population: the bisection's offsets are the repository's own rows. measures=[ - _measure("stale_assets", "Assets not updated within `days` (not measured when the Asset find fills its page)", - "staleCount", population="viewer"), - _measure("assets", "Assets", "assetTotal"), + _measure("stale_assets", "Assets not updated within `days`", "staleCount", + population="repository", basis=_basis("assetTotal", "Assets")), + _measure("assets", "Assets", "assetTotal", population="repository"), ], absence=_absence( - 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_measured="Stale assets were not measured: the Asset count or a read in update-time order " + "failed, or Assets you cannot see sit exactly at the cutoff (the note gives the range).", 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.", + nothing_found="Counted: every Asset was updated within the threshold, or there are no Assets.", ), out=[ _field("staleCount", "Stale Assets", "int", unit="Assets"), diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index 3d833dde..caef10aa 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -377,6 +377,83 @@ def _one_page_or_none(mgr, body: dict, what: str) -> Optional[list]: return page +# ── counting by last-update time ─────────────────────────────────────────── +# Egeria cannot count by an updateTime condition: a search condition only reaches an element's own +# properties, and the header's updateTime (set at create, so never empty) is not one of them -- a count +# with `updateTime LT ` answers 0 for every Asset (checked live 2026-11-09, and in the postgres +# connector's QueryBuilder, where update_time is only a sort column). It can SORT by it (sequencingOrder +# LAST_UPDATE_OLDEST), and startFrom is an offset into the repository's own sorted rows: a row the +# viewer may not see still takes its offset and reads as an empty one-row page. So the number of rows +# last updated before a cutoff is the offset of the first row updated at or after it, and a bisection +# over offsets finds it in about log2(total / 25) one-row reads plus one read of the last window (12 for +# 37,000 Assets), never paging the population. +MAX_BISECT_READS = 64 +BISECT_WINDOW = 25 # the last window is read as one page of at most this many rows + + +def _rows_updated_before(mgr, body: dict, cutoff, total: int, what: str) -> Optional[int]: + """How many of the `total` rows `body` matches were last updated before `cutoff`, by bisection over + their offsets in LAST_UPDATE_OLDEST order. One-row reads, then one read of the last window of at most + BISECT_WINDOW rows (it settles the count when every row in it is visible), at most MAX_BISECT_READS. + + A row the viewer cannot see reads as an empty page, and it still counts: a hidden row between two rows + updated before the cutoff was updated before it too (the order is by update time), so the count is in + the repository population, like `total`. Only hidden rows between the last row seen before the cutoff + and the first row seen after it cannot be placed; then the result is None with a note giving the + range. None with a note, too, when a read fails or the reads run out. Never raises.""" + b = {**body, "sequencingOrder": "LAST_UPDATE_OLDEST"} + lo, hi = 0, total # rows [0, lo) were updated before the cutoff; rows [hi, total) were not + unknown: set = set() # offsets that read as empty (hidden) or carried no update time + reads = 0 + window_read = False + while lo < hi: + if not window_read and hi - lo <= BISECT_WINDOW and reads < MAX_BISECT_READS: + # One read of the whole remaining window settles it when every row in it is visible: then the + # page's positions are the offsets. With a hidden row in it, carry on one row at a time. + window_read = True + reads += 1 + page = _find_or_none(mgr, b, hi - lo, start_from=lo) + if page is None: + _not_measured(what, "a read of the rows in update-time order failed") + return None + times = [_update_time(el) for el in page] + if len(page) == hi - lo and all(t is not None for t in times): + return lo + sum(1 for t in times if t < cutoff) + continue + mid = (lo + hi) // 2 + found = None + for k in list(range(mid, hi)) + list(range(mid - 1, lo - 1, -1)): + if k in unknown: + continue + if reads >= MAX_BISECT_READS: + _not_measured(what, f"the update-time bisection used all {MAX_BISECT_READS} of its one-row reads " + f"(rows you cannot see lie between offsets {lo} and {hi}), so there are " + f"between {lo} and {hi}", at_least=lo) + return None + reads += 1 + page = _find_or_none(mgr, b, 1, start_from=k) + if page is None: + _not_measured(what, "a read of the rows in update-time order failed") + return None + when = _update_time(page[0]) if page else None + if when is None: + unknown.add(k) + continue + found = (k, when) + break + if found is None: + _not_measured(what, f"the {hi - lo} rows between the last one updated before the cutoff and the " + f"first one updated after it are not visible to you, so there are between " + f"{lo} and {hi}", at_least=lo) + return None + k, when = found + if when < cutoff: + lo = k + 1 + else: + hi = k + return lo + + SCOPE_VIEWER = "viewer" SCOPE_REPOSITORY = "repository" @@ -1113,14 +1190,26 @@ def orphan_glossary_terms(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Opt catalog-wide-not-sub-filtered tradeoff `governedCount` etc. already carry, not a new one. + Egeria cannot count the distinct ends of a relationship type natively, so + the referenced set needs the scan. The term total is counted in the + viewer population, because the scan only sees what the viewer may see, + and a viewer count is slow (13.5 s live for 1,061 terms, against 0.7 s + for the repository count). So it runs on its own thread while the scan + pages (6.2.29): the routine takes about as long as the slower of the two, + not their sum. Its note, if any, still reaches the caller's + `recording_unmeasured()`. + Returns {"termTotal": int|None, "referencedCount": int|None, "orphanCount": int|None}. Any field is None on total failure for its own step (never raises). """ - # One population per payload: this payload's other figures come from a find, which only sees what the + # One population per payload: this payload's other figures come from a scan, which only sees what the # viewer may see, so its native total is counted in the viewer population too (never a repository - # total under a viewer numerator). - term_total = count_elements(mgr, "GlossaryTerm", as_of, strict=True, population=SCOPE_VIEWER) + # total under a viewer numerator). Two reads at once, not one after the other. + pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="orphan-terms") + term_future = pool.submit(contextvars.copy_context().run, count_elements, mgr, "GlossaryTerm", as_of, + strict=True, population=SCOPE_VIEWER) + pool.shutdown(wait=False) referenced_count = None try: @@ -1137,6 +1226,13 @@ def orphan_glossary_terms(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Opt except Exception as exc: # noqa: BLE001 logger.debug(f"orphan_glossary_terms: SemanticAssignment query failed: {exc}") + try: + term_total = term_future.result() + except Exception as exc: # noqa: BLE001 -- count_elements does not raise; belt and braces + logger.debug(f"orphan_glossary_terms: GlossaryTerm count failed: {exc}") + _not_measured("GlossaryTerm", f"the count failed ({type(exc).__name__})") + term_total = None + orphan_count = None if term_total is not None and referenced_count is not None: orphan_count = max(term_total - referenced_count, 0) @@ -1147,50 +1243,53 @@ def orphan_glossary_terms(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Opt def stale_assets(mgr, as_of: Optional[str] = None, days: int = 180) -> Dict[str, Optional[int]]: """ Assets with no update in the last `days` -- the Attention Queue's "Stale - assets" row, candidates for archival review. One bounded `Asset` element - fetch (same cap as every other full-element scan in this module), each - element's own version metadata (`_update_time`, already used elsewhere - in this file) compared against the cutoff -- no relationship traversal. + assets" row, candidates for archival review. + + Both figures are in the repository population (the whole repository, + including Assets the viewer may not be able to see), so the payload never + mixes populations: + + - assetTotal: the native push-down count of ACTIVE Assets. + - staleCount: how many of those were last updated before the cutoff. + Egeria cannot count by an update-time condition, but it sorts by update + time, so this is a bisection over the sorted rows' offsets + (`_rows_updated_before`): about log2(assetTotal / 25) one-row reads and + one read of the last 25-row window (12 for 37,000 Assets), never a page + of Assets (6.2.29). An Asset updated while + the bisection runs can shift the offsets by one. `as_of` anchors both the query and the cutoff clock (an as-of-time dashboard view should ask "stale as of that moment", not "stale as of right now" -- consistent with `certifications_summary`'s own as_of anchoring). - Returns {"staleCount": int|None, "assetTotal": int|None}. `staleCount` - 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). + Returns {"staleCount": int|None, "assetTotal": int|None}. Either is None, + with an `unmeasured` note, when it is not measured: the native count + failed (staleCount bisects over it, so it is None too), a read failed, + rows the viewer cannot see sit exactly at the cutoff (the note gives the + range), or the reads ran out. Never a figure from a sample of Assets. """ from datetime import datetime, timezone, timedelta - stale_count = None - try: - anchor = datetime.fromisoformat(as_of.replace("Z", "+00:00")) if as_of else datetime.now(timezone.utc) + what = f"Assets not updated within {days} days" + body: Dict[str, Any] = {"class": "FindRequestBody", "metadataElementTypeName": "Asset", + "limitResultsByStatus": ["ACTIVE"]} + total = _element_count(mgr, body, as_of, scope=SCOPE_REPOSITORY) # noted when not measured + if total is None: + _not_measured(what, "the Asset count it bisects over was not measured") + return {"staleCount": None, "assetTotal": None} + anchor = datetime.now(timezone.utc) + if as_of: + try: + anchor = datetime.fromisoformat(as_of.replace("Z", "+00:00")) + except ValueError: + _not_measured(what, f"as_of {as_of!r} is not an ISO-8601 time, so there is no cutoff") + return {"staleCount": None, "assetTotal": total} if anchor.tzinfo is None: anchor = anchor.replace(tzinfo=timezone.utc) - cutoff = anchor - timedelta(days=days) - body = {"class": "FindRequestBody", "metadataElementTypeName": "Asset", "limitResultsByStatus": ["ACTIVE"]} - if as_of: - body["asOfTime"] = as_of - # 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) - if updated is not None and updated < cutoff: - stale_count += 1 - except Exception as exc: # noqa: BLE001 - logger.debug(f"stale_assets: query failed: {exc}") - - # One population per payload: this payload's other figures come from a find, which only sees what the - # viewer may see, so its native total is counted in the viewer population too (never a repository - # total under a viewer numerator). - return {"staleCount": stale_count, - "assetTotal": count_elements(mgr, "Asset", as_of, strict=True, population=SCOPE_VIEWER)} + b = dict(body, asOfTime=as_of) if as_of else dict(body) + stale_count = _rows_updated_before(mgr, b, anchor - timedelta(days=days), total, what) + return {"staleCount": stale_count, "assetTotal": total} def semantic_grounding(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: diff --git a/tests/micro-tests/test_capped_scans_not_counts.py b/tests/micro-tests/test_capped_scans_not_counts.py index bf350da7..2a96fb42 100644 --- a/tests/micro-tests/test_capped_scans_not_counts.py +++ b/tests/micro-tests/test_capped_scans_not_counts.py @@ -118,21 +118,8 @@ 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 +# stale_assets no longer reads a page of Assets (6.2.29): it bisects over Egeria's update-time order. +# Its tests are in test_native_counts_dashboard.py. # ── the other scanners ───────────────────────────────────────────────────── diff --git a/tests/micro-tests/test_native_counts_dashboard.py b/tests/micro-tests/test_native_counts_dashboard.py new file mode 100644 index 00000000..b8e626ea --- /dev/null +++ b/tests/micro-tests/test_native_counts_dashboard.py @@ -0,0 +1,233 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +Dashboard analytics that count inside Egeria instead of paging results (6.2.29). + +`stale_assets`: Egeria cannot count by an update-time condition (a search condition reaches only an +element's own properties; `updateTime LT ` counts 0, checked live 2026-11-09). It does sort by +update time, and `startFrom` is an offset into the repository's sorted rows -- a row the viewer cannot +see keeps its offset and reads as an empty one-row page. So the stale count is the offset of the first +row updated at or after the cutoff, found by bisection: about log2(total / 25) one-row reads, then one +read of the last 25-row window. Live, as erinoverview: 287 of 37,431 Assets, where 6.2.28 read a +500-Asset page and reported "not measured". + +`orphan_glossary_terms`: distinct relationship ends cannot be counted natively, so the +SemanticAssignment scan stays; its slow viewer term count now runs while the scan pages. + +The fake below is a sorted repository: a list of update times (None = a row the viewer cannot see). +""" +import random +import threading +from datetime import datetime, timedelta, timezone + +import pytest +from unittest.mock import MagicMock + +from pyegeria.view import overview_metrics as om + +AS_OF = "2026-11-09T00:00:00Z" +NOW = datetime(2026, 11, 9, tzinfo=timezone.utc) +CUTOFF = NOW - timedelta(days=180) +OLD, NEW = "2026-04-01T06:45:49.989+00:00", "2026-11-07T15:09:37.189+00:00" +WHAT = "Assets not updated within 180 days" + + +@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() + + +class _SortedRepo: + """count_metadata_elements answers len(rows); find_metadata_elements serves rows[startFrom:+pageSize] + in LAST_UPDATE_OLDEST order, leaving out hidden rows (None), as Egeria does.""" + + def __init__(self, rows, count=None, fail_find_at=None): + self.rows, self.count, self.fail_find_at = rows, count, fail_find_at + self.finds, self.counts = [], [] + self.platform_url, self.view_server = "https://localhost:9443", "test-server" + + def count_metadata_elements(self, body, **kw): + self.counts.append((body, kw)) + if isinstance(self.count, BaseException): + raise self.count + return {"count": len(self.rows) if self.count is None else self.count} + + def find_metadata_elements(self, body, *a, **kw): + self.finds.append(body) + if self.fail_find_at is not None and len(self.finds) > self.fail_find_at: + raise RuntimeError("read failed") + assert body["sequencingOrder"] == "LAST_UPDATE_OLDEST" + s, n = body["startFrom"], body["pageSize"] + return [{"elementGUID": f"a{i}", "versions": {"createTime": t, "updateTime": t}} + for i, t in enumerate(self.rows[s:s + n], start=s) if t is not None] + + +def _rows(n_stale, n_recent, hidden=()): + rows = [OLD] * n_stale + [NEW] * n_recent + for i in hidden: + rows[i] = None + return rows + + +def test_stale_count_is_the_offset_of_the_first_recent_row_found_by_bisection(): + repo = _SortedRepo(_rows(287, 37431 - 287)) + with om.recording_unmeasured() as notes: + r = om.stale_assets(repo, as_of=AS_OF) + assert r == {"staleCount": 287, "assetTotal": 37431} + assert notes == [] + # log2(37,431 / 25) one-row reads, then one read of the last window: never a page of Assets + assert len(repo.finds) <= 13 + assert [b["pageSize"] for b in repo.finds][:-1] == [1] * (len(repo.finds) - 1) + assert repo.finds[-1]["pageSize"] <= om.BISECT_WINDOW + assert all(b["asOfTime"] == AS_OF and b["metadataElementTypeName"] == "Asset" for b in repo.finds) + assert repo.counts[0][1] == {"push_down": True} # the repository population + + +def test_hidden_rows_among_stale_rows_are_stale_too(): + # Rows the viewer cannot see between two stale rows were updated before the cutoff (the order is by + # update time), so they count: the figure is in the repository population, like assetTotal. + repo = _SortedRepo(_rows(300, 700, hidden=range(100, 150))) + assert om.stale_assets(repo, as_of=AS_OF) == {"staleCount": 300, "assetTotal": 1000} + + +@pytest.mark.parametrize("hidden", [[290], [299], [300], [296, 297, 303]]) +def test_a_hidden_row_near_the_cutoff_still_gives_the_exact_count(hidden): + # Hidden rows strictly inside the stale run or the recent run are placed by the order; the last window + # is read once, and if it holds a hidden row the bisection carries on one row at a time. + repo = _SortedRepo(_rows(300, 700, hidden=hidden)) + with om.recording_unmeasured() as notes: + r = om.stale_assets(repo, as_of=AS_OF) + if r["staleCount"] is None: # a hidden row sat exactly at the cutoff: the range must hold 300 + assert notes[0]["at_least"] <= 300 and "between" in notes[0]["reason"] + else: + assert r == {"staleCount": 300, "assetTotal": 1000} + assert sum(1 for b in repo.finds if b["pageSize"] > 1) <= 1 + + +def test_hidden_rows_at_the_cutoff_give_a_range_not_a_count(): + repo = _SortedRepo(_rows(300, 700, hidden=range(295, 305))) + with om.recording_unmeasured() as notes: + r = om.stale_assets(repo, as_of=AS_OF) + assert r == {"staleCount": None, "assetTotal": 1000} + assert notes == [{"count": WHAT, "at_least": 295, + "reason": "the 10 rows between the last one updated before the cutoff and the first one " + "updated after it are not visible to you, so there are between 295 and 305"}] + + +def test_a_failed_asset_count_measures_neither_and_reads_nothing(): + repo = _SortedRepo(_rows(10, 10), count=RuntimeError("timed out")) + with om.recording_unmeasured() as notes: + r = om.stale_assets(repo, as_of=AS_OF) + assert r == {"staleCount": None, "assetTotal": None} # never 0 + assert repo.finds == [] + assert [n["count"] for n in notes] == ["Asset", WHAT] + assert notes[1]["reason"] == "the Asset count it bisects over was not measured" + + +def test_a_failed_read_is_not_measured(): + repo = _SortedRepo(_rows(300, 700), fail_find_at=3) + with om.recording_unmeasured() as notes: + r = om.stale_assets(repo, as_of=AS_OF) + assert r == {"staleCount": None, "assetTotal": 1000} + assert notes == [{"count": WHAT, "at_least": None, + "reason": "a read of the rows in update-time order failed"}] + + +def test_the_bisection_has_a_read_budget(monkeypatch): + monkeypatch.setattr(om, "MAX_BISECT_READS", 4) + repo = _SortedRepo(_rows(300, 700)) + with om.recording_unmeasured() as notes: + assert om.stale_assets(repo, as_of=AS_OF)["staleCount"] is None + assert len(repo.finds) == 4 + assert notes[0]["count"] == WHAT and "used all 4 of its one-row reads" in notes[0]["reason"] + + +@pytest.mark.parametrize("n_stale, n_recent, want", [(0, 50, 0), (50, 0, 50), (0, 0, 0), (1, 0, 1), (0, 1, 0)]) +def test_the_edges(n_stale, n_recent, want): + repo = _SortedRepo(_rows(n_stale, n_recent)) + assert om.stale_assets(repo, as_of=AS_OF) == {"staleCount": want, "assetTotal": n_stale + n_recent} + + +def test_as_of_anchors_the_cutoff(): + # 2026-04-01 is stale on 2026-11-09 but not on 2026-05-01. + repo = _SortedRepo(_rows(5, 5)) + assert om.stale_assets(repo, as_of="2026-05-01T00:00:00Z")["staleCount"] == 0 + assert om.stale_assets(repo, as_of=AS_OF, days=1)["staleCount"] == 10 + + +@pytest.mark.parametrize("seed", range(40)) +def test_bisection_agrees_with_counting_every_row(seed): + rng = random.Random(seed) + n = rng.randint(1, 3000) + start = CUTOFF - timedelta(days=400) + times = sorted(start + timedelta(minutes=rng.randint(0, 800 * 24 * 60)) for _ in range(n)) + rows = [t.isoformat() if rng.random() > 0.2 else None for t in times] # a fifth hidden + truth = sum(1 for t in times if t < CUTOFF) + repo = _SortedRepo(rows) + with om.recording_unmeasured() as notes: + r = om.stale_assets(repo, as_of=AS_OF) + if r["staleCount"] is None: # hidden rows at the cutoff: the note's range holds the truth + lo = notes[0]["at_least"] + hi = int(notes[0]["reason"].rsplit(" and ", 1)[1]) + assert lo <= truth <= hi + assert all(rows[i] is None for i in range(lo, hi)) + else: + assert r["staleCount"] == truth + assert len(repo.finds) <= om.MAX_BISECT_READS + + +def test_stale_assets_is_declared_in_the_repository_population(): + from pyegeria.view.analytic_registry import get_analytic_registry + measures = {m.name: m for m in get_analytic_registry()["stale_assets"].declaration.measures} + assert measures["stale_assets"].population == "repository" + assert measures["assets"].population == "repository" + + +# ── orphan_glossary_terms ────────────────────────────────────────────────── + +def _assignments(n_rels, n_terms): + return [{"relationshipHeader": {"guid": f"r{i}"}, + "end1": {"guid": f"a{i}", "type": {"typeName": "CSVFile"}}, + "end2": {"guid": f"t{i % n_terms}", "type": {"typeName": "GlossaryTerm"}}} for i in range(n_rels)] + + +def _ce(rels, on_read=None): + ce = MagicMock() + + def fake(*a, relationship_type=None, body=None, **kw): + if on_read: + on_read() + return rels[body["startFrom"]:body["startFrom"] + body["pageSize"]] + ce.get_relationships.side_effect = fake + return ce + + +def test_orphan_term_count_runs_while_the_scan_pages(): + scan_started = threading.Event() + seen = {} + mgr = MagicMock(spec=["platform_url", "view_server", "count_metadata_elements", "find_metadata_elements"]) + + def count(body, **kw): + # Sequential code would count first and wait here for a scan that has not started. + seen["concurrent"] = scan_started.wait(timeout=5) + seen["push_down"] = kw.get("push_down") + return {"count": 1061} + mgr.count_metadata_elements.side_effect = count + r = om.orphan_glossary_terms(mgr, _ce(_assignments(747, 77), on_read=scan_started.set)) + assert r == {"termTotal": 1061, "referencedCount": 77, "orphanCount": 984} + assert seen == {"concurrent": True, "push_down": False} # the viewer population, as the scan + + +def test_the_term_count_note_from_its_thread_reaches_the_caller(): + mgr = MagicMock(spec=["platform_url", "view_server", "count_metadata_elements", "find_metadata_elements"]) + mgr.count_metadata_elements.side_effect = RuntimeError("timed out") + mgr.find_metadata_elements.side_effect = RuntimeError("down") + with om.recording_unmeasured() as notes: + r = om.orphan_glossary_terms(mgr, _ce(_assignments(10, 3))) + assert r == {"termTotal": None, "referencedCount": 3, "orphanCount": None} + assert [n["count"] for n in notes] == ["GlossaryTerm"] + assert notes[0]["reason"] == "the native count timed out, and the find fallback failed"