From 85803ecbff3b57833d1ad766fecd7c410f9a770b Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Tue, 10 Nov 2026 21:24:33 +0000 Subject: [PATCH 01/12] fix(trends): every metric_trend point says whether its number is exact (W2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brief W2 (2026-11-10): a trend must never show a capped count as a measured value. Finding first (read-only on laz, and in Egeria's source): the live trend 200, 200, 1065 is true. Egeria's native count honours asOfTime (countMetadataElements passes it to the repository's SQL COUNT). GlossaryTerm is 200 up to 96 h ago and 1061 from 72 h ago. Paged finds at 45 days end at 200 for page sizes 70, 200 and 1000, and Asset reads 288 on the same dates. count_elements never returned the find cap anyway; what was missing was the per-point truth. - _element_count records how each count was answered (native, find, find-capped, not-measured) for an enclosing _recording_how(). - metric_trend: each point carries measurement {exact, capped, at_least, how, reasons}; a scalar point also carries display ("200", "≥500" for a lower bound, "not measured"). Notes still reach an enclosing recording_unmeasured(). New strict=True is passed to a target that takes strict, and raises TrendNotExact if any point is not exact. - SERIES: a trend whose only inexact points are lower bounds is drawn, each bound plotted at its bound with a "≥N" text layer and tooltip, subtitled "N of M points are lower bounds". A point with no number still withholds the chart. BAR, PIE and DICT are unchanged. - Registry: metric_trend declares strict, display and measurement. Tests (fakes that answer like Egeria): the live shape exact and native at every point; a refused asOfTime count giving lower bounds (viewer) or not-measured (repository); a short find page exact; strict raising and passed through; a failed snapshot; a dict target; the SERIES chart exact, bounded (marked) and withheld; no bound shown without its marker in SERIES, BAR or DICT. Signed-off-by: Dan Wolfson --- docs/release-notes/6.2.34.md | 32 +++ pyegeria/view/analytic_registry.py | 6 + pyegeria/view/format_set_executor.py | 56 ++++- pyegeria/view/overview_metrics.py | 125 ++++++++- .../micro-tests/test_w2_trend_points_exact.py | 237 ++++++++++++++++++ 5 files changed, 446 insertions(+), 10 deletions(-) create mode 100644 docs/release-notes/6.2.34.md create mode 100644 tests/micro-tests/test_w2_trend_points_exact.py diff --git a/docs/release-notes/6.2.34.md b/docs/release-notes/6.2.34.md new file mode 100644 index 00000000..c1596304 --- /dev/null +++ b/docs/release-notes/6.2.34.md @@ -0,0 +1,32 @@ +# pyegeria 6.2.34 (draft) + +## Changed + +- **Every trend point says whether its number is exact (W2).** `metric_trend` points now carry + `measurement = {exact, capped, at_least, how, reasons}`. A scalar point also carries `display`. + - **`how`:** "native" (Egeria's count), "find" (a short find page), "find-capped", "not-measured", + "error" (the snapshot failed), "mixed", or "measured" (the target made no element count). + - **A lower bound is never a bare number:** a count that stopped at the find page cap keeps its value + None, and its `display` reads "≥500" (the cap). The reason, with the bound, is in + `measurement.reasons`. An enclosing `recording_unmeasured()` still collects every note, as before. + - **SERIES:** a trend whose only inexact points are lower bounds is now drawn. Each bound is plotted at + its bound, with a "≥N" label and a tooltip, and the subtitle says "N of M points are lower bounds". + A trend with a point that has no number at all still draws no chart, and says why. BAR, PIE and DICT + are unchanged: no chart over an unmeasured count. + - **`strict=True`** (new on `metric_trend`) is passed to a target that takes `strict`. If any point is + not exact, the call raises `TrendNotExact` with those points, instead of returning them. +- **Finding, checked 2026-11-10:** the live trend 200, 200, 1065 that raised W2 is true. + - **Source:** Egeria's native count honours `asOfTime`; `countMetadataElements` passes it to the + repository's SQL COUNT. + - **Live, read-only on laz:** GlossaryTerm reads 200 up to 96 hours ago and 1061 from 72 hours ago (a + glossary load). Paged finds 45 days back end at exactly 200 with page sizes of 70, 200 and 1000. + Asset reads 288 on the same dates, so nothing caps at 200. + - **Already safe:** pyegeria's `count_elements` never returned the find cap as a value: the + repository population has no fallback, and the viewer fallback at the cap returns None plus a note. + - **What was missing:** that truth didn't reach each trend point, so a trend with one bound drew no + chart at all. + +## Follow-ups (other apps, after release) + +- The Portal's and Egeria Advisor's own trend renderers should show `display` (or the "≥N" marker) for a + point whose `measurement.capped` is true, never `value` alone. diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 1221c819..59e879f4 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -1878,6 +1878,10 @@ def _always_applies(what: str) -> str: AnalyticParam(name="metric_params", type="dict", description="Extra keyword arguments forwarded to the target function at " "every snapshot (e.g. classifications for count_elements)."), + AnalyticParam(name="strict", type="bool", default=False, + description="Raise TrendNotExact when any point is not exact (a lower bound, " + "not measured or failed), instead of returning it; passed to a " + "target that takes strict."), ], declaration=AnalyticDeclaration( result_kind="series", @@ -1894,6 +1898,8 @@ def _always_applies(what: str) -> str: _field("label", "Snapshot", "string"), _field("date", "Date", "string"), _field("value", "Value", "float"), + _field("display", "Shown as", "string"), + _field("measurement", "Measurement", "map"), ], ), ), diff --git a/pyegeria/view/format_set_executor.py b/pyegeria/view/format_set_executor.py index aae2e33f..6c8f2a10 100644 --- a/pyegeria/view/format_set_executor.py +++ b/pyegeria/view/format_set_executor.py @@ -1018,9 +1018,12 @@ def _exec_analytic_chart( ) envelope = _result_envelope(result) result = _jsonable(result) + # W2 (6.2.34): a trend whose only unmeasured points are lower bounds is drawn, each bound + # plotted at its bound and labelled "≥N", with a subtitle saying how many there are. + bounded = _bounded_trend(result) if chart_kind == "line" and notes else None # A count in the result was not measured: its value is None, and a chart would draw that as # a missing bar, a gap or a re-proportioned pie. Withhold the chart and say why instead. - if notes and (envelope is None or envelope["state"] in CHARTABLE_STATES): + if notes and bounded is None and (envelope is None or envelope["state"] in CHARTABLE_STATES): envelope = _unmeasured_envelope(notes) absence = _absence_for(envelope, action["analytic_function"]) # Chart only an established answer (ISSUE-140): measured, or nothing_found (a real @@ -1045,6 +1048,19 @@ def _chart_out(chart): out = {"kind": "json", "data": chart, **({"absence": absence} if absence else {})} return _with_envelope(out, envelope) + if chart_kind == "line" and bounded is not None: + records, n_bounds = bounded + chart = generate_vega_line_chart(records, x_field="label", y_fields=["value"], title=heading, + x_label="Label", y_label="Count") + if not chart: + return _with_envelope({"kind": "json", "data": result}, envelope) + chart = _mark_lower_bounds(chart) + chart["title"] = {"text": heading, "subtitle": ( + f"{n_bounds} of {len(records)} points are lower bounds (shown as \u2265N): " + f"the count stopped at its page cap")} + return {"kind": "json", "data": chart, "unmeasured": notes, + **({"absence": absence} if absence else {})} + if chart_kind == "line": if not isinstance(result, list) or not all(isinstance(pt, dict) for pt in result): return _with_envelope({"kind": "json", "data": result}, envelope) @@ -1070,6 +1086,44 @@ def _chart_out(chart): return _chart_out(chart) +def _bounded_trend(result: Any) -> Optional[Tuple[List[Dict[str, Any]], int]]: + """A scalar `metric_trend` series whose every inexact point is a lower bound: the records to + plot (a bound at its bound, flagged `lowerBound`, with its `display` "≥N") and how many bounds. + None for anything else, so the caller withholds the chart as before.""" + if not isinstance(result, list) or not result: + return None + records, n_bounds = [], 0 + for pt in result: + m = pt.get("measurement") if isinstance(pt, dict) else None + if not isinstance(m, dict) or "display" not in pt: + return None # not a scalar metric_trend point + if m.get("exact") and isinstance(pt.get("value"), (int, float)): + records.append({"label": pt.get("label"), "date": pt.get("date"), "value": pt["value"], + "display": pt["display"], "lowerBound": False}) + elif m.get("capped") and m.get("at_least") is not None and m.get("how") != "error": + n_bounds += 1 + records.append({"label": pt.get("label"), "date": pt.get("date"), "value": m["at_least"], + "display": pt["display"], "lowerBound": True}) + else: + return None # a point with no number at all: no chart + return (records, n_bounds) if n_bounds else None + + +def _mark_lower_bounds(chart: Dict[str, Any]) -> Dict[str, Any]: + """Layer a "≥N" label over every lower-bound point, and show `display` in the tooltip, so a + bound is never read as an exact number.""" + line = {k: chart.pop(k) for k in ("mark", "encoding")} + line["mark"] = {"type": "line", "point": True} + line["encoding"]["tooltip"] = [{"field": "label", "type": "nominal"}, + {"field": "display", "type": "nominal", "title": "Count"}] + label = {"transform": [{"filter": "datum.lowerBound"}], + "mark": {"type": "text", "dy": -10}, + "encoding": {"x": line["encoding"]["x"], "y": line["encoding"]["y"], + "text": {"field": "display", "type": "nominal"}}} + chart["layer"] = [line, label] + return chart + + def _as_category_value_dict(result: Any) -> Optional[Dict[str, Union[int, float]]]: """Coerce an analytic result into {category: numeric_value} for a bar/pie chart, or None if it doesn't fit that shape. Handles two real shapes: diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index d07f1bde..fc5a4ee4 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -69,6 +69,7 @@ "stale_assets", "growth_series", "metric_trend", + "TrendNotExact", "term_definition_completeness", "active_contributors", "asset_subtype_tree", @@ -540,6 +541,29 @@ def _not_measured(what: str, reason: str, at_least: Optional[int] = None) -> Non notes.append({"count": what, "reason": reason, "at_least": at_least}) +# How each element count was answered, per context, for `metric_trend`'s per-point truth: +# "native" (Egeria's count), "find" (a short find page: every element seen), "find-capped" (the +# find stopped at DEFAULT_CAP: a lower bound, not measured) or "not-measured" (no number at all). +_COUNT_HOW: "contextvars.ContextVar[Optional[List[str]]]" = contextvars.ContextVar( + "pyegeria_count_how", default=None) + + +@contextlib.contextmanager +def _recording_how(): + hows: List[str] = [] + token = _COUNT_HOW.set(hows) + try: + yield hows + finally: + _COUNT_HOW.reset(token) + + +def _how(how: str) -> None: + hows = _COUNT_HOW.get() + if hows is not None: + hows.append(how) + + def _native_failure_words(exc: Optional[BaseException], tried: bool) -> str: """What happened to the native count, in words, for a not-measured reason.""" if not tried: @@ -601,6 +625,7 @@ def _element_count(mgr, body: dict, as_of: Optional[str] = None, strict: bool = try: c = _as_count(getattr(mgr, name)(b, **kw)) if c is not None: + _how("native") return c except Exception as exc: # noqa: BLE001 -- old server: mark unsupported, fall back native_exc = exc @@ -610,14 +635,18 @@ def _element_count(mgr, body: dict, as_of: Optional[str] = None, strict: bool = # Strict or not: a repository count has no fallback, and 0 here would read as an empty catalog. _not_measured(what, f"{native_words}, and a repository-population count has no fallback " f"(the find fallback only sees what the viewer may see)") + _how("not-measured") return None found = _find_or_none(mgr, b) 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") + _how("not-measured") return None if len(found) >= DEFAULT_CAP: # a full page is a lower bound, never a total (strict or not) _not_measured(what, _capped_reason(native_words, len(found)), at_least=len(found)) + _how("find-capped") return None + _how("find") return len(found) @@ -2143,6 +2172,7 @@ def metric_trend( window: str = "6mo", points: Optional[int] = None, metric_params: Optional[Dict[str, Any]] = None, + strict: bool = False, ) -> List[Dict[str, Any]]: """ Turn any single-snapshot function in this module into a time series, by @@ -2177,6 +2207,27 @@ def metric_trend( dict (matching growth_series's flat-per-point shape), else stored under "value". A snapshot that raises logs at debug and stores None instead of aborting the whole series. + + Every point also carries the truth about its own number (W2, 6.2.34): + `measurement = {"exact", "capped", "at_least", "how", "reasons"}`. + - `exact`: the snapshot was measured, with no count left unmeasured. + - `capped`: a count stopped at the find page cap, so `at_least` is a lower + bound, never a total. The point's value stays None (as the count + returns it), and `display` reads "≥". + - `how`: "native", "find", "find-capped", "not-measured" or "error" (a + snapshot that raised), "mixed" when one snapshot made several kinds of + count, or "measured" when the target made no element count. + - `reasons`: the not-measured notes for that point (also recorded for an + enclosing `recording_unmeasured()`, as before). + A scalar point also gets `display`: the number as text, "≥N" for a lower + bound, or "not measured". + + Egeria's native count honours `asOfTime` (checked 2026-11-10, in source + and live), so past points are native counts, exact like today's. + + `strict=True` is passed to a target that takes `strict`. A series with + any point that isn't exact then raises `TrendNotExact`, naming how many + points and why, instead of returning numbers. """ from datetime import datetime, timezone from pyegeria.view.format_set_executor import resolve_report_spec_function # lazy: keeps the design boundary @@ -2204,6 +2255,10 @@ def metric_trend( step = span_s / (n - 1) date_fmt = "%d %b %Y %H:%M" if span_s <= 2 * 86400 else "%d %b %Y" + kwargs = dict(metric_params or {}) + if strict and "strict" in inspect.signature(func).parameters: + kwargs["strict"] = True + outer_notes = _UNMEASURED.get() series = [] for i in range(n - 1, -1, -1): if i == 0: @@ -2212,19 +2267,71 @@ def metric_trend( d = datetime.fromtimestamp(now.timestamp() - i * step, tz=timezone.utc) as_of = d.isoformat() point = {"label": growth_label(d, span_s), "date": d.strftime(date_fmt)} - try: - result = func(*bound_args, as_of=as_of, **(metric_params or {})) - if isinstance(result, dict): - point.update(result) - else: - point["value"] = result - except Exception as exc: # noqa: BLE001 - logger.debug(f"overview_metrics metric_trend: snapshot {i} of {metric_path} failed: {exc}") - point["value"] = None + failed = None + with recording_unmeasured() as notes, _recording_how() as hows: + try: + result = func(*bound_args, as_of=as_of, **kwargs) + except Exception as exc: # noqa: BLE001 + logger.debug(f"overview_metrics metric_trend: snapshot {i} of {metric_path} failed: {exc}") + result, failed = None, exc + if outer_notes is not None: # the enclosing recorder still hears every note, as before + outer_notes.extend(notes) + if isinstance(result, dict): + point.update(result) + else: + point["value"] = result + point["measurement"] = _point_measurement(notes, hows, failed) + if not isinstance(result, dict): + point["display"] = _point_display(result, point["measurement"]) series.append(point) + if strict: + inexact = [p for p in series if not p["measurement"]["exact"]] + if inexact: + raise TrendNotExact(metric_path, inexact, len(series)) return series +class TrendNotExact(ValueError): + """`metric_trend(strict=True)`: one or more points are not exact (a lower bound, not measured, + or a snapshot that failed). `points` holds those points, measurement included.""" + + def __init__(self, metric_path: str, points: List[Dict[str, Any]], total: int): + self.metric_path, self.points, self.total = metric_path, points, total + bounds = sum(1 for p in points if p["measurement"]["capped"]) + words = [f"{p['date']}: {p.get('display') or p['measurement']['how']}" for p in points] + super().__init__(f"metric_trend({metric_path}): {len(points)} of {total} points are not exact " + f"({bounds} lower bounds); " + "; ".join(words)) + + +def _point_measurement(notes: List[Dict[str, Any]], hows: List[str], + failed: Optional[BaseException]) -> Dict[str, Any]: + """The truth about one trend point's number, from the counts made while it was taken.""" + bounds = [n["at_least"] for n in notes if n.get("at_least") is not None] + if failed is not None: + how = "error" + elif not hows: + how = "not-measured" if notes else "measured" + elif len(set(hows)) == 1: + how = hows[0] + else: + how = "mixed" + reasons = [dict(n) for n in notes] + if failed is not None: + reasons.append({"count": "snapshot", "reason": f"the snapshot failed ({type(failed).__name__})", + "at_least": None}) + return {"exact": failed is None and not notes, "capped": bool(bounds), + "at_least": max(bounds) if bounds else None, "how": how, "reasons": reasons} + + +def _point_display(value: Any, measurement: Dict[str, Any]) -> str: + """A scalar point as text: never a bare number for a lower bound.""" + if measurement["exact"] and value is not None: + return str(value) + if measurement["capped"]: + return f"\u2265{measurement['at_least']}" + return "not measured" + + def term_definition_completeness(mgr, as_of: Optional[str] = None) -> Dict[str, Any]: """ Share of GlossaryTerms carrying a non-empty `description` -- a diff --git a/tests/micro-tests/test_w2_trend_points_exact.py b/tests/micro-tests/test_w2_trend_points_exact.py new file mode 100644 index 00000000..823cdf66 --- /dev/null +++ b/tests/micro-tests/test_w2_trend_points_exact.py @@ -0,0 +1,237 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +"""W2 (6.2.34): every metric_trend point says whether its number is exact, and a lower bound is +never shown as a bare number. + +Live finding (2026-11-10): `metric_trend` over count_elements(GlossaryTerm), 90d / 3 points, gave +200, 200, 1065. Checked the same day on laz, read-only: those are true. Egeria's native count honours +asOfTime (MetadataElementHandler.countMetadataElements passes it to the repository's SQL COUNT), the +GlossaryTerm count is 200 at 96 hours ago and 1061 at 72 (a glossary load), and paged finds at the +past time end at 200 for page sizes 70, 200 and 1000; Asset reads 288 at the same times, above the +cap. The first test is that real shape: all exact, all native. + +The fakes below answer like Egeria: count_metadata_elements(body) gives {"count": n}, and +find_metadata_elements gives a page of at most DEFAULT_CAP. Nothing reaches Egeria. +""" +import json + +import pytest + +from pyegeria.view import format_set_executor as fse +from pyegeria.view import overview_metrics as om +from pyegeria.view.role_supply import Subject, Viewer + +pytestmark = pytest.mark.unit + +CAP = om.DEFAULT_CAP +GE = "≥" + + +@pytest.fixture(autouse=True) +def _reset_seam_caches(): + om._count_caps.clear() + om._native_server_ok.clear() + yield + om._count_caps.clear() + om._native_server_ok.clear() + + +class _Egeria: + """GlossaryTerm: `past` before now, `now` today. `as_of_ok=False`: a native count with asOfTime + is refused (an old server), and the find fallback sees a full page in the past.""" + platform_url, view_server = "https://fake:9443", "fake" + + def __init__(self, past=200, now=1065, as_of_ok=True): + self.past, self.now, self.as_of_ok = past, now, as_of_ok + self.native_calls, self.find_calls = [], [] + + def count_metadata_elements(self, body, **kw): + self.native_calls.append(body.get("asOfTime")) + if body.get("asOfTime") and not self.as_of_ok: + raise RuntimeError("PROPERTY_SERVER_ERROR_500 the history query for the count failed") + return {"count": self.past if body.get("asOfTime") else self.now} + + def find_metadata_elements(self, body, *a, **kw): + self.find_calls.append(body.get("asOfTime")) + n = self.past if body.get("asOfTime") else self.now + return [{"elementGUID": f"g{i}"} for i in range(min(n, body.get("pageSize") or CAP, CAP))] + + +def _trend(egeria, population="repository", **kw): + return om.metric_trend(egeria, egeria, "count_elements", window="90d", points=3, + metric_params={"type_name": "GlossaryTerm", "population": population}, **kw) + + +def test_the_live_shape_is_exact_at_every_point(): + egeria = _Egeria(past=200, now=1065) + series = _trend(egeria) + assert [p["value"] for p in series] == [200, 200, 1065] + assert [p["display"] for p in series] == ["200", "200", "1065"] + for p in series: + assert p["measurement"] == {"exact": True, "capped": False, "at_least": None, "how": "native", + "reasons": []} + assert len([a for a in egeria.native_calls if a]) == 2 # asOfTime reached the native count + assert egeria.find_calls == [] + + +def test_a_native_count_that_refuses_as_of_time_gives_lower_bounds_in_the_viewer_population(): + egeria = _Egeria(past=5000, now=1065, as_of_ok=False) + with om.recording_unmeasured() as notes: + series = _trend(egeria, population="viewer") + past, today = series[:2], series[2] + for p in past: + assert p["value"] is None # never the cap as a value + assert p["display"] == f"{GE}{CAP}" + assert p["measurement"]["exact"] is False and p["measurement"]["capped"] is True + assert p["measurement"]["at_least"] == CAP and p["measurement"]["how"] == "find-capped" + assert f"at least {CAP}" in p["measurement"]["reasons"][0]["reason"] + assert today["value"] == 1065 and today["display"] == "1065" and today["measurement"]["exact"] + assert len(notes) == 2 # the enclosing recorder still hears each point's note + + +def test_a_repository_count_that_refuses_as_of_time_is_not_measured_not_a_bound(): + series = _trend(_Egeria(as_of_ok=False)) + for p in series[:2]: + assert p["value"] is None and p["display"] == "not measured" + assert p["measurement"]["how"] == "not-measured" and p["measurement"]["capped"] is False + assert series[2]["measurement"]["exact"] + + +def test_a_short_find_page_is_exact_and_says_find(): + series = _trend(_Egeria(past=40, now=50, as_of_ok=False), population="viewer") + assert [p["display"] for p in series] == ["40", "40", "50"] + assert [p["measurement"]["how"] for p in series] == ["find", "find", "native"] + assert all(p["measurement"]["exact"] for p in series) + + +def test_strict_raises_with_the_points_that_are_not_exact(): + with pytest.raises(om.TrendNotExact) as exc: + _trend(_Egeria(past=5000, as_of_ok=False), population="viewer", strict=True) + assert exc.value.total == 3 and len(exc.value.points) == 2 + assert "2 of 3 points are not exact (2 lower bounds)" in str(exc.value) + assert f"{GE}{CAP}" in str(exc.value) + + +def test_strict_on_an_exact_series_returns_it(): + assert [p["value"] for p in _trend(_Egeria(), strict=True)] == [200, 200, 1065] + + +def test_strict_reaches_a_target_that_takes_it(monkeypatch): + seen = [] + real = om.count_elements + + def spy(mgr, type_name=None, as_of=None, strict=False, population=None): + seen.append(strict) + return real(mgr, type_name, as_of, strict=strict, population=population) + + monkeypatch.setattr(om, "count_elements", spy) + from pyegeria.view import format_set_executor + monkeypatch.setattr(format_set_executor, "resolve_report_spec_function", lambda name: spy) + _trend(_Egeria(), strict=True) + assert seen == [True, True, True] + + +def test_a_failed_snapshot_says_error_and_is_not_exact(): + def boom(mgr, as_of=None): + raise RuntimeError("boom") + + from pyegeria.view.analytic_registry import clear_runtime_analytic_functions, register_analytic_functions + om._w2_boom = boom + register_analytic_functions({"w2-boom": {"name": "w2-boom", "function": "pyegeria.view.overview_metrics._w2_boom"}}) + try: + series = om.metric_trend(_Egeria(), _Egeria(), "w2-boom", window="7d", points=2) + assert all(p["value"] is None and p["display"] == "not measured" for p in series) + assert all(p["measurement"]["how"] == "error" and not p["measurement"]["exact"] for p in series) + with pytest.raises(om.TrendNotExact): + om.metric_trend(_Egeria(), _Egeria(), "w2-boom", window="7d", points=2, strict=True) + finally: + clear_runtime_analytic_functions() + del om._w2_boom + + +def test_a_dict_target_carries_measurement_but_no_display(): + series = om.metric_trend(_Egeria(), _Egeria(), "term_definition_completeness", window="7d", points=2) + assert all("measurement" in p and "display" not in p for p in series) + + +# ── what a reader sees: the SERIES chart ── + +class _Supply: + def __init__(self, egeria): + self.egeria = egeria + + def client(self, cls): + return self.egeria + + def viewer(self): + return Viewer(user_id="u", is_admin=False, display_name="U") + + def reader(self, source): + return None + + def subject(self): + return Subject(guid="g", type_name="Asset") + + def refusal_words(self, kind): + return f"cannot supply {kind}" + + +def _series(egeria, fmt="SERIES", population="repository"): + return fse.exec_report_spec( + "Analytic Demo - Metric Trend (Governance Coverage)", output_format=fmt, + params={"metric_path": "count_elements", "window": "90d", "points": 3, + "metric_params": {"type_name": "GlossaryTerm", "population": population}}, + view_server="vs", view_url="https://x", user="u", user_pass="p", supply=_Supply(egeria)) + + +def _layers(chart): + return chart.get("layer") or [chart] + + +def test_an_exact_trend_is_charted_with_its_values(): + out = _series(_Egeria()) + assert out["kind"] == "json" and "unmeasured" not in out + assert [r["value"] for r in out["data"]["data"]["values"]] == [200, 200, 1065] + + +def test_a_lower_bounded_trend_is_charted_with_every_bound_marked(): + out = _series(_Egeria(past=5000, as_of_ok=False), population="viewer") + assert out["kind"] == "json" + chart = out["data"] + rows = chart["data"]["values"] + assert [r["display"] for r in rows] == [f"{GE}{CAP}", f"{GE}{CAP}", "1065"] + assert [r["lowerBound"] for r in rows] == [True, True, False] + assert chart["title"]["subtitle"].startswith("2 of 3 points are lower bounds") + label = chart["layer"][1] + assert label["encoding"]["text"]["field"] == "display" + assert label["transform"] == [{"filter": "datum.lowerBound"}] + assert {"field": "display", "type": "nominal", "title": "Count"} in chart["layer"][0]["encoding"]["tooltip"] + assert [n["at_least"] for n in out["unmeasured"]] == [CAP] # one note, not one per point + + +def test_a_trend_with_an_unmeasured_point_draws_no_chart(): + out = _series(_Egeria(as_of_ok=False)) # repository: no bound, no number + assert out["kind"] == "absent" and "data" not in out + + +@pytest.mark.parametrize("past,population,bounded", [ + (5000, "viewer", True), + (5000, "repository", False), +]) +@pytest.mark.parametrize("fmt", ["SERIES", "BAR", "DICT"]) +def test_no_lower_bound_is_ever_shown_without_its_marker(past, population, bounded, fmt): + out = _series(_Egeria(past=past, as_of_ok=False), fmt, population) + text = json.dumps(out, ensure_ascii=False) + if out["kind"] == "absent": + assert "data" not in out + return + data = out["data"] + rows = data["data"]["values"] if isinstance(data, dict) and "data" in data else data + for r in rows: + if r.get("lowerBound") or (isinstance(r.get("measurement"), dict) and r["measurement"]["capped"]): + assert r["display"].startswith(GE), (fmt, r) + assert r.get("value") in (None, CAP) + if r.get("value") == CAP: + assert r.get("lowerBound") is True + assert (f"{GE}{CAP}" in text) == bounded + assert f'"value": {CAP}' not in text or bounded and fmt == "SERIES" # only a marked chart bound From 67f75fcdc91b558d97c43f9bbfdadd2a403e47a5 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Tue, 10 Nov 2026 21:31:00 +0000 Subject: [PATCH 02/12] feat(report-specs): saved_query, a saved query as the source of a Report (Route B) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brief BRIEF-USEFUL-SHEETS-AND-SAVED-QUERY-REPORTS-2026-11-10, Route B, Builder 2 (owner: "Both routes"). saved_query(client, name, mode="cached"|"live", output="count"|"list"), registered as an analytic function (inputs: EgeriaTech, the viewer's). - Finds the SavedQuery by an exact qualifiedName find, as the viewer (zones apply). Missing, ambiguous, hidden or failed lookups are not_established with the reason, never 0. - cached: Results Set members (from additionalProperties.resultsSetGuid), asOf lastRefreshedTime; never refreshed is not_established, not empty. - live: runs the stored request with the viewer's token, paging to an empty page, at most 20 pages of 500. A stopped read is capped: value None, atLeast N, display "≥N". - Security: the stored Query URL is checked, never followed. Its path must be the one allow-listed endpoint (metadata-expert by-search-conditions), relative or under this client's /servers/. An absolute URL is accepted only for this client's own scheme/host/port and view server (the shape the Portal stores). Another host, port, scheme, user info or view server, a query string or fragment, an encoded or dotted path, or a non-FindRequestBody body is refused with a sentence and nothing is sent. The call is pyegeria's own find_metadata_elements on the viewer's client. Tests (48): the Portal's real SavedQuery shape (absolute same-origin queryURL, JSON-string body, map additionalProperties); cached as-of, never refreshed, empty, capped, no Results Set; the exact-QN lookup, a near miss, missing and hidden; live paging, capped, list, refused and failed requests; 5 accepted URL forms and 20 refused ones, each proving the lookup was the only call; refused bodies; the executor running it on the supply's EgeriaTech. Registry coverage tests list saved_query (29 built-ins). Signed-off-by: Dan Wolfson --- docs/release-notes/6.2.34.md | 29 ++ pyegeria/view/analytic_registry.py | 46 +++ pyegeria/view/saved_query.py | 326 ++++++++++++++++++ .../test_rs_w2_1a_routine_declarations.py | 2 + .../test_rs_w2_3_inputs_by_role.py | 2 +- .../micro-tests/test_saved_query_analytic.py | 312 +++++++++++++++++ 6 files changed, 716 insertions(+), 1 deletion(-) create mode 100644 pyegeria/view/saved_query.py create mode 100644 tests/micro-tests/test_saved_query_analytic.py diff --git a/docs/release-notes/6.2.34.md b/docs/release-notes/6.2.34.md index c1596304..ad68cb86 100644 --- a/docs/release-notes/6.2.34.md +++ b/docs/release-notes/6.2.34.md @@ -1,5 +1,34 @@ # pyegeria 6.2.34 (draft) +## New + +- **`saved_query`: a saved query as the source of a Report (Route B).** + `saved_query(client, name, mode="cached"|"live", output="count"|"list")` is a registered analytic + function, so a Report can name a SavedQuery by qualifiedName and a tile can show its answer as a count + KPI or a list. + - **As the viewer:** the SavedQuery is found by an exact qualifiedName find, as the viewer, so zones + apply. + - **cached:** the members of its Results Set, `asOf` its last refresh. A query never refreshed is "not + established", not 0. + - **live:** runs the stored request now with the viewer's token. It reads every page (an empty page is + the end), up to 20 pages of 500. A read that stops at that bound is a lower bound: `value` is None, + `capped` is true and `display` reads "≥N". + - **Absence is never 0:** a missing, ambiguous, hidden (not_permitted) or failed read is + `not_established`, with the reason. + - **Security:** a SavedQuery's Query URL is authored data, so it never chooses where the viewer's token + goes. The same class of problem was behind the Portal's `?url=` leak. The URL is only checked, never + followed: + - its path must be the one allow-listed endpoint, MetadataExpert + `metadata-elements/by-search-conditions`, given relative or under this client's own + `/servers/`; + - an absolute URL is accepted only when it names this client's own platform (same scheme, host and + port, no user info) and view server. That is the shape the Portal stores; + - any other host, port, scheme or view server is refused with a sentence, and nothing is sent. So is + a query string, a fragment, an encoded or dotted path, or a body that isn't a FindRequestBody; + - the request is made by pyegeria's own `find_metadata_elements` on the viewer's client. + - The Portal's `/api/insights/search` formula isn't run here: it's the Portal's own API. Use cached + mode, or save the query as a Smart Collection, which stores the find request. + ## Changed - **Every trend point says whether its number is exact (W2).** `metric_trend` points now carry diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index 59e879f4..03c6432f 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -1903,6 +1903,52 @@ def _always_applies(what: str) -> str: ], ), ), + "saved_query": AnalyticFunctionSpec( + name="saved_query", + function="pyegeria.view.saved_query.saved_query", + inputs=["egeria_client:EgeriaTech"], + description="The answer of a SavedQuery, named by qualifiedName and found as the viewer (zones " + "apply): a count for a KPI tile, or a list. mode=cached reads its Results Set (the last " + "refresh, shown 'as of' its time); mode=live runs the stored request now with the " + "viewer's token, only through an allow-listed view-server query endpoint on this " + "platform (a stored URL never chooses where the token goes). A read stopped at its " + "bound is a lower bound ('\u2265N'), never a total. " + "Cost: one lookup plus one call per page of the answer (500 per page, 20 pages at most).", + returns="dict (value, display, capped, atLeast, asOf, elements for a list)", + generic=True, + params=[ + AnalyticParam(name="name", type="str", required=True, + description="The SavedQuery's qualifiedName."), + AnalyticParam(name="mode", type="str", default="cached", + description="cached (its Results Set, as of the last refresh) or live (run it now)."), + AnalyticParam(name="output", type="str", default="count", + description="count (a KPI) or list (the elements)."), + AnalyticParam(name="page_size", type="int", default=500, + description="Elements per page read (at most 1000)."), + AnalyticParam(name="max_pages", type="int", default=20, + description="Pages read at most; a read stopped here is a lower bound."), + ], + declaration=AnalyticDeclaration( + result_kind="measure", + measures=[_measure("value", "elements", "value", population="viewer", as_of="asOf")], + absence=_absence( + not_measured="The saved query's answer was not read: it was never refreshed, it records no " + "Results Set, no saved query by that name is visible to you, or the read failed.", + not_permitted="The saved query, its Results Set or its request is not visible to you.", + not_applicable="The saved query's stored request is not one a Report may run: its Query URL " + "names another host or a path outside the allow-listed query endpoints.", + nothing_found="Read: the saved query's answer is empty.", + ), + out=[ + _field("value", "Elements", "int", unit="elements"), + _field("display", "Shown as", "string"), + _field("capped", "Lower bound", "bool"), + _field("atLeast", "At least", "int", unit="elements"), + _field("asOf", "As of", "string"), + _field("elements", "Elements", "list"), + ], + ), + ), "asset_composition": AnalyticFunctionSpec( name="asset_composition", function="pyegeria.view.overview_metrics.asset_composition", diff --git a/pyegeria/view/saved_query.py b/pyegeria/view/saved_query.py new file mode 100644 index 00000000..d2d3c2d9 --- /dev/null +++ b/pyegeria/view/saved_query.py @@ -0,0 +1,326 @@ +""" +SPDX-License-Identifier: Apache-2.0 +Copyright Contributors to the ODPi Egeria project. + +`saved_query`: a saved query as the source of a Report (Route B, 6.2.34). + +A Report names a SavedQuery by qualifiedName, and a tile shows its answer as a count (KPI) or a list. +The SavedQuery is found as the viewer, so zones apply. +- mode="cached": the members of its Results Set (the last answer, materialised by the Portal's + refresh or by Egeria's Smart Collections connector), with the refresh time ("as of ..."). +- mode="live": runs the stored request now, with the viewer's token. It reads every page (an empty + page is the end) up to a bound, and marks a stopped read `capped` with a lower bound, never a total. + +Security. A SavedQuery's Query URL is authored data, and a Report can name anyone's SavedQuery, so the +stored URL never chooses where the viewer's token goes (the Portal's ?url= leak was this class). The +URL is only checked, never followed: +- its path must name one allow-listed view-server query endpoint, as a relative path or under this + client's own `/servers/`; +- an absolute URL is accepted only when it names this client's own platform (same scheme, host and + port, no user info) and view server: the shape the Portal itself stores. Any other host, port, + scheme or view server, a query string, a fragment, or an encoded or dotted path is refused with a + sentence; +- the request is then made by pyegeria's own method for that endpoint, on the viewer's own client. +""" + +from __future__ import annotations + +import json +from datetime import datetime, timezone +from typing import Any, Dict, List, Optional, Tuple +from urllib.parse import urlsplit + +from loguru import logger + +__all__ = ["saved_query", "SavedQueryRefused", "ALLOWED_QUERY_ENDPOINTS", "SAVED_QUERY_PAGE_SIZE", + "SAVED_QUERY_MAX_PAGES"] + +# Allow-listed view-server query endpoints (path below /servers/), each with the pyegeria +# method that calls it and the request-body classes it takes. Nothing else is ever run. +ALLOWED_QUERY_ENDPOINTS: Dict[str, Tuple[str, Tuple[str, ...]]] = { + "/api/open-metadata/metadata-expert/metadata-elements/by-search-conditions": + ("find_metadata_elements", ("FindRequestBody",)), +} + +SAVED_QUERY_PAGE_SIZE = 500 +SAVED_QUERY_MAX_PAGES = 20 # 10,000 elements; a read that has not ended by then is a lower bound + +_QUERY_TYPE = "SavedQuery" + + +class SavedQueryRefused(ValueError): + """The saved query's stored request is not one this function will run. `sentence` says why.""" + + def __init__(self, sentence: str): + self.sentence = sentence + super().__init__(sentence) + + +# ── reading an OpenMetadataElement ───────────────────────────────────────── + +def _value(v: Any) -> Any: + """A property value from an OpenMetadataElement's propertyValueMap, as plain Python.""" + if not isinstance(v, dict): + return v + if "primitiveValue" in v: + return v["primitiveValue"] + if "mapValues" in v: + return {k: _value(x) for k, x in ((v["mapValues"] or {}).get("propertyValueMap") or {}).items()} + if "arrayValues" in v: + items = ((v["arrayValues"] or {}).get("propertyValueMap") or {}) + return [_value(items[k]) for k in sorted(items, key=lambda k: int(k) if str(k).isdigit() else k)] + return v + + +def _properties(el: Dict[str, Any]) -> Dict[str, Any]: + """Properties of an element in either shape: OpenMetadataElement or a view-service bean.""" + pvm = ((el.get("elementProperties") or {}).get("propertyValueMap")) + if isinstance(pvm, dict): + return {k: _value(v) for k, v in pvm.items()} + return dict(el.get("properties") or {}) + + +def _guid(el: Dict[str, Any]) -> str: + return el.get("elementGUID") or (el.get("elementHeader") or {}).get("guid") or "" + + +def _type_name(el: Dict[str, Any]) -> str: + t = el.get("type") or (el.get("elementHeader") or {}).get("type") or {} + return t.get("typeName") or "" + + +def _elements(result: Any) -> List[Dict[str, Any]]: + """An Egeria list result; its 'No elements found' string is an empty list.""" + if isinstance(result, dict): + result = [result] + return [e for e in result if isinstance(e, dict)] if isinstance(result, list) else [] + + +def _summary(el: Dict[str, Any]) -> Dict[str, Any]: + p = _properties(el) + return {"guid": _guid(el), "typeName": _type_name(el), "qualifiedName": p.get("qualifiedName"), + "displayName": p.get("displayName") or p.get("name")} + + +# ── the allow-list ───────────────────────────────────────────────────────── + +def _client_origin(client) -> Tuple[str, str]: + parts = urlsplit(str(getattr(client, "platform_url", "") or "")) + return parts.scheme.lower(), parts.netloc.lower() + + +def _allowed_endpoint(query_url: Any, client) -> Tuple[str, Tuple[str, ...]]: + """The pyegeria method and body classes for a stored Query URL, or SavedQueryRefused.""" + if not isinstance(query_url, str) or not query_url.strip(): + raise SavedQueryRefused("The saved query has no Query URL, so there is no stored request to run.") + raw = query_url.strip() + if any(c in raw for c in ("\\", "%", "\n", "\r", "\t", " ")): + raise SavedQueryRefused(f"The saved query's Query URL {raw!r} has characters a query endpoint path " + f"never has, so it is not run.") + parts = urlsplit(raw) + if parts.query or parts.fragment: + raise SavedQueryRefused(f"The saved query's Query URL {raw!r} carries a query string or fragment; " + f"only a bare endpoint path is run.") + if parts.scheme or parts.netloc or raw.startswith("//"): + scheme, origin = _client_origin(client) + if "@" in parts.netloc or parts.scheme.lower() != scheme or parts.netloc.lower() != origin: + raise SavedQueryRefused( + f"The saved query's Query URL names {parts.scheme}://{parts.netloc}, not this platform: a stored " + f"URL never chooses where your token is sent, so it is not run.") + path = parts.path if parts.path.startswith("/") else "/" + parts.path + if "//" in path or any(seg in (".", "..") for seg in path.split("/")): + raise SavedQueryRefused(f"The saved query's Query URL path {path!r} is not a plain endpoint path, " + f"so it is not run.") + if path.startswith("/servers/"): + segs = path.split("/", 3) # ['', 'servers', '', 'api/...'] + server = segs[2] if len(segs) > 2 else "" + if server != str(getattr(client, "view_server", "")): + raise SavedQueryRefused(f"The saved query's Query URL names view server {server!r}, not " + f"{getattr(client, 'view_server', '')!r}, so it is not run.") + path = "/" + (segs[3] if len(segs) > 3 else "") + if path not in ALLOWED_QUERY_ENDPOINTS: + raise SavedQueryRefused(f"The saved query's Query URL path {path!r} is not one of the query endpoints a " + f"Report may run ({', '.join(sorted(ALLOWED_QUERY_ENDPOINTS))}).") + return ALLOWED_QUERY_ENDPOINTS[path] + + +def _request_body(stored: Any, classes: Tuple[str, ...]) -> Dict[str, Any]: + if isinstance(stored, str): + try: + stored = json.loads(stored) if stored.strip() else None + except ValueError: + raise SavedQueryRefused("The saved query's Query Request Body is not JSON, so it is not run.") + if not isinstance(stored, dict): + raise SavedQueryRefused("The saved query has no Query Request Body to run.") + if stored.get("class") not in classes: + raise SavedQueryRefused(f"The saved query's Query Request Body is a {stored.get('class')!r}; this " + f"endpoint takes {', '.join(classes)}.") + return stored + + +# ── the function ─────────────────────────────────────────────────────────── + +def _exact_qn_body(qn: str) -> Dict[str, Any]: + return {"class": "FindRequestBody", "metadataElementTypeName": _QUERY_TYPE, "graphQueryDepth": 0, + "startFrom": 0, "pageSize": 10, + "searchProperties": {"class": "SearchProperties", "matchCriteria": "ALL", "conditions": [{ + "property": "qualifiedName", "operator": "EQ", + "value": {"class": "PrimitiveTypePropertyValue", "typeName": "string", "primitiveValue": qn}}]}} + + +def _result(name: str, mode: str, output: str, *, state: str, reason: str = "", absence: Optional[str] = None, + count: Optional[int] = None, elements: Optional[List[Dict[str, Any]]] = None, + capped: bool = False, as_of: Optional[str] = None, refused: bool = False) -> Dict[str, Any]: + out: Dict[str, Any] = {"savedQuery": name, "mode": mode, "output": output, "state": state, + "state_reason": reason, "value": count, "capped": capped, + "atLeast": count if capped else None, "asOf": as_of, + "display": None if count is None else (f"≥{count}" if capped else str(count))} + if capped: + out["value"] = None # a lower bound is never a total + if absence: + out["absence"] = absence + if refused: + out["refused"] = True + out["elements"] = (elements if elements is not None else []) if output == "list" else None + if as_of and state in ("measured", "nothing_found"): + out["subtitle"] = f"as of {as_of}" + (f" · at least {count}: the read stopped at its bound" + if capped else "") + return out + + +def _is_not_visible(exc: BaseException) -> bool: + from pyegeria.view.dashboard_resolver import is_not_visible_error # lazy: keeps imports light + return is_not_visible_error(exc) + + +def _not_measured(name, mode, output, reason): + return _result(name, mode, output, state="not_established", reason=reason, absence="not_measured") + + +def _read_pages(fetch, page_size: int, max_pages: int) -> Tuple[List[Dict[str, Any]], bool]: + """Every element `fetch(start_from, page_size)` returns, paging until an empty page. Returns + (elements, capped): capped when `max_pages` pages were read and the next was not shown to be empty.""" + found: List[Dict[str, Any]] = [] + start = 0 + for _ in range(max_pages): + page = _elements(fetch(start, page_size)) + if not page: + return found, False + found.extend(page) + start += len(page) + return found, True + + +def saved_query(client, name: str, mode: str = "cached", output: str = "count", + page_size: int = SAVED_QUERY_PAGE_SIZE, max_pages: int = SAVED_QUERY_MAX_PAGES) -> Dict[str, Any]: + """ + The answer of a SavedQuery named by `name` (its qualifiedName), as the viewer sees it. + + Parameters + ---------- + client : EgeriaTech, already authenticated as the viewer + name : the SavedQuery's qualifiedName + mode : "cached" (its Results Set's members, as of the last refresh) or "live" (run the stored + request now, with the viewer's token, through the allow-list) + output : "count" (a KPI: `value`) or "list" (`elements`: guid, typeName, qualifiedName, displayName) + page_size, max_pages : the read's page size and bound; a read stopped by the bound is a lower bound + + Returns a dict: + - `value`: the count; None when it is not established or is only a lower bound; + - `capped` and `atLeast`: whether the read stopped at its bound, and the lower bound; + - `display`: "N", or "≥N" for a bound; + - `asOf`: the refresh time for a cached answer, now for a live one; + - `state`, `state_reason` and `absence`: the state envelope. + + It never returns 0 for an answer it could not read. A query that was never refreshed, a missing + or hidden SavedQuery, or a refused URL is `not_established`, with the reason; a refused URL also + sets `refused`. A refused Query URL never raises. + """ + mode = (mode or "cached").lower() + output = (output or "count").lower() + if mode not in ("cached", "live"): + raise ValueError(f"saved_query: mode must be 'cached' or 'live', not {mode!r}") + if output not in ("count", "list"): + raise ValueError(f"saved_query: output must be 'count' or 'list', not {output!r}") + if not name: + raise ValueError("saved_query: name (the SavedQuery's qualifiedName) is required") + page_size = max(1, min(int(page_size or SAVED_QUERY_PAGE_SIZE), 1000)) + max_pages = max(1, int(max_pages or SAVED_QUERY_MAX_PAGES)) + + try: + found = _elements(client.find_metadata_elements(body=_exact_qn_body(name))) + except Exception as exc: # noqa: BLE001 + if _is_not_visible(exc): + return _result(name, mode, output, state="not_established", absence="not_permitted", + reason=f"the saved query {name!r} is not visible to you") + logger.debug(f"saved_query: lookup of {name!r} failed: {exc}") + return _not_measured(name, mode, output, f"the saved query {name!r} could not be read " + f"({type(exc).__name__})") + exact = [e for e in found if _properties(e).get("qualifiedName") == name] + if not exact: + return _not_measured(name, mode, output, f"no saved query named {name!r} is visible to you (it may " + f"not exist, or may be in a zone you cannot see)") + if len(exact) > 1: + return _not_measured(name, mode, output, f"{len(exact)} saved queries are named {name!r}; name one by " + f"a unique qualifiedName") + props = _properties(exact[0]) + additional = props.get("additionalProperties") or {} + if not isinstance(additional, dict): + additional = {} + + if mode == "cached": + return _cached(client, name, output, additional, page_size, max_pages) + return _live(client, name, output, props, page_size, max_pages) + + +def _cached(client, name, output, additional, page_size, max_pages): + as_of = additional.get("lastRefreshedTime") or None + results_set = additional.get("resultsSetGuid") or None + if not results_set: + return _not_measured(name, "cached", output, "the saved query records no Results Set, so it has no " + "cached answer; use mode live, or refresh it") + if not as_of: + return _not_measured(name, "cached", output, "the saved query has never been refreshed, so its " + "Results Set holds no answer yet (not an empty answer)") + try: + members, capped = _read_pages( + lambda start, size: client.get_collection_members(collection_guid=results_set, start_from=start, + page_size=size, output_format="JSON"), + page_size, max_pages) + except Exception as exc: # noqa: BLE001 + if _is_not_visible(exc): + return _result(name, "cached", output, state="not_established", absence="not_permitted", + reason="the saved query's Results Set is not visible to you") + return _not_measured(name, "cached", output, f"its Results Set could not be read ({type(exc).__name__})") + return _answer(name, "cached", output, members, capped, as_of) + + +def _live(client, name, output, props, page_size, max_pages): + try: + method, classes = _allowed_endpoint(props.get("queryURL"), client) + body = _request_body(props.get("queryRequestBody"), classes) + except SavedQueryRefused as refused: + logger.warning(f"saved_query: refused to run {name!r}: {refused.sentence}") + return _result(name, "live", output, state="not_established", reason=refused.sentence, + absence="not_applicable", refused=True) + fn = getattr(client, method) + now = datetime.now(timezone.utc).isoformat(timespec="seconds") + try: + found, capped = _read_pages( + lambda start, size: fn(body={**body, "startFrom": start, "pageSize": size, "graphQueryDepth": 0}), + page_size, max_pages) + except Exception as exc: # noqa: BLE001 + if _is_not_visible(exc): + return _result(name, "live", output, state="not_established", absence="not_permitted", + reason="Egeria refused the saved query's request for you") + return _not_measured(name, "live", output, f"the saved query's request failed ({type(exc).__name__})") + return _answer(name, "live", output, found, capped, now) + + +def _answer(name, mode, output, elements, capped, as_of): + n = len(elements) + listed = [_summary(e) for e in elements] if output == "list" else None + if n == 0: + return _result(name, mode, output, state="nothing_found", absence="nothing_found", count=0, + elements=listed, as_of=as_of, reason="the saved query's answer is empty") + return _result(name, mode, output, state="measured", count=n, elements=listed, capped=capped, as_of=as_of) 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 4e2a1299..fd36a3d2 100644 --- a/tests/micro-tests/test_rs_w2_1a_routine_declarations.py +++ b/tests/micro-tests/test_rs_w2_1a_routine_declarations.py @@ -280,6 +280,8 @@ def _clients(): "stale_assets": lambda m, c: om.stale_assets(m, AS_OF), "control_implementation_summary": lambda m, c: om.control_implementation_summary(m, "soa"), "asset_composition": lambda m, c: om.asset_composition(m, _NoSubtypes(), depth=0), + "saved_query": lambda m, c: __import__("pyegeria.view.saved_query", fromlist=["saved_query"]).saved_query( + m, "SavedQuery::not-there"), } _MISSING = object() diff --git a/tests/micro-tests/test_rs_w2_3_inputs_by_role.py b/tests/micro-tests/test_rs_w2_3_inputs_by_role.py index 800b2cea..bded6ae9 100644 --- a/tests/micro-tests/test_rs_w2_3_inputs_by_role.py +++ b/tests/micro-tests/test_rs_w2_3_inputs_by_role.py @@ -128,7 +128,7 @@ def refusal_words(self, kind): # ── The 28 built-in declarations ── def test_every_builtin_declares_its_client_inputs_and_they_match_its_binding(): - assert len(BUILTIN_ANALYTIC_FUNCTIONS) == 28 + assert len(BUILTIN_ANALYTIC_FUNCTIONS) == 29 # + saved_query (6.2.34) served = {c.__name__ for c in egeria_tech_classes()} for name, entry in BUILTIN_ANALYTIC_FUNCTIONS.items(): assert entry.inputs, f"{name} declares no inputs" diff --git a/tests/micro-tests/test_saved_query_analytic.py b/tests/micro-tests/test_saved_query_analytic.py new file mode 100644 index 00000000..5f0847a6 --- /dev/null +++ b/tests/micro-tests/test_saved_query_analytic.py @@ -0,0 +1,312 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +"""Route B (6.2.34): `saved_query`, a saved query as the source of a Report. + +The SavedQuery below has the shape the Portal's insights_handler writes (create_saved_query) and a find +returns (an OpenMetadataElement): +- a queryURL that is absolute, on this platform and view server; +- a queryRequestBody that is a JSON string; +- additionalProperties (a map value) carrying resultsSetGuid and lastRefreshedTime. + +The security tests prove that the stored URL never chooses where the viewer's token goes. Every refused +URL leaves the fake with exactly one call: the lookup. The fake has no other way to reach anything. +Nothing reaches Egeria. +""" +import json + +import pytest + +from pyegeria.view import saved_query as sq +from pyegeria.view.saved_query import saved_query + +pytestmark = pytest.mark.unit + +PLATFORM, VIEW = "https://localhost:9443", "qs-view-server" +ENDPOINT = "/api/open-metadata/metadata-expert/metadata-elements/by-search-conditions" +PORTAL_URL = f"{PLATFORM}/servers/{VIEW}{ENDPOINT}" +QN = "SavedQuery::insights-query::Assets with no lineage::a1b2" +QUERY_BODY = {"class": "FindRequestBody", "metadataElementTypeName": "Asset", "limitResultsByStatus": ["ACTIVE"], + "graphQueryDepth": 0, "startFrom": 0, "pageSize": 500} +GE = "≥" + + +def _str(v): + return {"class": "PrimitiveTypePropertyValue", "typeName": "string", "primitiveValue": v} + + +def _saved_query(query_url=PORTAL_URL, body=json.dumps(QUERY_BODY), refreshed="2026-11-10T18:02:11+00:00", + results_set="rs-guid", qn=QN): + additional = {"pyegeriaInsightsQuery": "true", "queryUrl": "/api/insights/search", "queryHttpMethod": "POST", + "resultsSetGuid": results_set or "", "lastRefreshedTime": refreshed or "", "resultCount": ""} + pvm = {"qualifiedName": _str(qn), "displayName": _str("Assets with no lineage"), + "formula": _str(json.dumps({"type_name": "Asset"})), "formulaType": _str("egeria-insights-search-v1"), + "additionalProperties": {"class": "MapTypePropertyValue", "mapValues": { + "class": "InstanceProperties", "propertyValueMap": {k: _str(v) for k, v in additional.items()}}}} + if query_url is not None: + pvm["queryURL"] = _str(query_url) + if body is not None: + pvm["queryRequestBody"] = _str(body) + return {"elementGUID": "sq-guid", "type": {"typeName": "SavedQuery"}, + "elementProperties": {"class": "ElementProperties", "propertyValueMap": pvm}} + + +def _element(i, type_name="DataSet"): + return {"elementGUID": f"g{i}", "type": {"typeName": type_name}, + "elementProperties": {"propertyValueMap": {"qualifiedName": _str(f"Asset::{i}"), + "displayName": _str(f"Asset {i}")}}} + + +def _member(i): + return {"elementHeader": {"guid": f"m{i}", "type": {"typeName": "DataSet"}}, + "properties": {"qualifiedName": f"Asset::{i}", "displayName": f"Asset {i}"}} + + +class _Viewer: + """The viewer's own client. Records every call; it is the only way anything is reached.""" + platform_url, view_server = PLATFORM, VIEW + + def __init__(self, stored=None, answer=0, members=0, lookup_error=None, run_error=None): + self.stored = [_saved_query()] if stored is None else stored + self.answer, self.members = answer, members + self.lookup_error, self.run_error = lookup_error, run_error + self.calls = [] + + def find_metadata_elements(self, body=None, **kw): + self.calls.append(("find", json.loads(json.dumps(body)))) + if body.get("metadataElementTypeName") == "SavedQuery": + if self.lookup_error: + raise self.lookup_error + return self.stored or "No elements found" + if self.run_error: + raise self.run_error + start, size = body["startFrom"], body["pageSize"] + page = [_element(i) for i in range(start, min(start + size, self.answer))] + return page or "No elements found" + + def get_collection_members(self, collection_guid=None, start_from=0, page_size=0, output_format="JSON", **kw): + self.calls.append(("members", collection_guid, start_from, page_size)) + page = [_member(i) for i in range(start_from, min(start_from + page_size, self.members))] + return page or "No elements found" + + +# ── cached ── + +def test_cached_count_is_the_results_set_as_of_its_refresh(): + viewer = _Viewer(members=37) + out = saved_query(viewer, QN) + assert out["value"] == 37 and out["display"] == "37" and out["state"] == "measured" + assert out["asOf"] == "2026-11-10T18:02:11+00:00" + assert out["subtitle"] == "as of 2026-11-10T18:02:11+00:00" + assert [c[0] for c in viewer.calls] == ["find", "members", "members"] # paged to the empty page + assert viewer.calls[1][1] == "rs-guid" + + +def test_cached_list_names_each_member(): + out = saved_query(_Viewer(members=2), QN, output="list") + assert out["elements"] == [ + {"guid": "m0", "typeName": "DataSet", "qualifiedName": "Asset::0", "displayName": "Asset 0"}, + {"guid": "m1", "typeName": "DataSet", "qualifiedName": "Asset::1", "displayName": "Asset 1"}] + + +def test_never_refreshed_is_not_an_empty_answer(): + viewer = _Viewer(stored=[_saved_query(refreshed="")], members=0) + out = saved_query(viewer, QN) + assert out["value"] is None and out["state"] == "not_established" and out["absence"] == "not_measured" + assert "never been refreshed" in out["state_reason"] + assert [c[0] for c in viewer.calls] == ["find"] + + +def test_an_empty_refreshed_answer_is_nothing_found(): + out = saved_query(_Viewer(members=0), QN) + assert out["value"] == 0 and out["state"] == "nothing_found" + + +def test_a_cached_read_stopped_at_its_bound_is_a_lower_bound(): + out = saved_query(_Viewer(members=50), QN, page_size=10, max_pages=3) + assert out["value"] is None and out["capped"] is True and out["atLeast"] == 30 + assert out["display"] == f"{GE}30" + assert "at least 30" in out["subtitle"] + + +def test_no_results_set_is_said(): + out = saved_query(_Viewer(stored=[_saved_query(results_set="")]), QN) + assert out["state"] == "not_established" and "no Results Set" in out["state_reason"] + + +# ── finding the saved query, as the viewer ── + +def test_the_lookup_is_an_exact_qualified_name_find_of_a_saved_query(): + viewer = _Viewer(members=1) + saved_query(viewer, QN) + body = viewer.calls[0][1] + assert body["metadataElementTypeName"] == "SavedQuery" + cond = body["searchProperties"]["conditions"][0] + assert (cond["property"], cond["operator"], cond["value"]["primitiveValue"]) == ("qualifiedName", "EQ", QN) + + +def test_a_missing_saved_query_is_not_a_zero(): + out = saved_query(_Viewer(stored=[]), QN) + assert out["value"] is None and out["state"] == "not_established" + assert "no saved query named" in out["state_reason"] + + +def test_a_near_miss_qualified_name_is_not_taken(): + out = saved_query(_Viewer(stored=[_saved_query(qn=QN + "-copy")]), QN) + assert out["value"] is None and "no saved query named" in out["state_reason"] + + +def test_a_saved_query_in_a_hidden_zone_is_not_permitted(): + err = RuntimeError("OPEN-METADATA-SECURITY-403-020 The element sq-guid is not visible to user erinoverview") + out = saved_query(_Viewer(lookup_error=err), QN) + assert out["state"] == "not_established" and out["absence"] == "not_permitted" and out["value"] is None + + +# ── live ── + +def test_live_runs_the_stored_body_through_pyegeria_paging_to_the_end(): + viewer = _Viewer(answer=1200) + out = saved_query(viewer, QN, mode="live") + assert out["value"] == 1200 and out["display"] == "1200" and out["capped"] is False + runs = [c[1] for c in viewer.calls[1:]] + assert [b["startFrom"] for b in runs] == [0, 500, 1000, 1200] + assert all(b["metadataElementTypeName"] == "Asset" and b["limitResultsByStatus"] == ["ACTIVE"] for b in runs) + assert out["asOf"] # now + + +def test_live_stopped_at_its_bound_is_marked_never_a_total(): + out = saved_query(_Viewer(answer=10_000), QN, mode="live", page_size=100, max_pages=4) + assert out["value"] is None and out["capped"] is True and out["atLeast"] == 400 + assert out["display"] == f"{GE}400" + + +def test_live_list_output(): + out = saved_query(_Viewer(answer=3), QN, mode="live", output="list") + assert [e["guid"] for e in out["elements"]] == ["g0", "g1", "g2"] + assert out["elements"][0]["qualifiedName"] == "Asset::0" + + +def test_a_live_request_egeria_refuses_is_not_permitted(): + err = RuntimeError("OPEN-METADATA-SECURITY-403-020 not visible to user erinoverview") + out = saved_query(_Viewer(run_error=err), QN, mode="live") + assert out["absence"] == "not_permitted" and out["value"] is None + + +def test_a_live_request_that_fails_is_not_measured(): + out = saved_query(_Viewer(run_error=TimeoutError("timed out")), QN, mode="live") + assert out["absence"] == "not_measured" and out["value"] is None and "TimeoutError" in out["state_reason"] + + +# ── the allow-list: a stored URL never chooses where the token goes ── + +@pytest.mark.parametrize("url", [ + PORTAL_URL, # the Portal's own shape: this platform, this view server + ENDPOINT, # relative to the view server + ENDPOINT.lstrip("/"), + f"/servers/{VIEW}{ENDPOINT}", + PORTAL_URL.replace("https://localhost", "HTTPS://LOCALHOST"), +]) +def test_allow_listed_requests_run(url): + viewer = _Viewer(stored=[_saved_query(query_url=url)], answer=2) + out = saved_query(viewer, QN, mode="live") + assert out["value"] == 2 and "refused" not in out + + +REFUSED = [ + ("https://evil.example.com/servers/qs-view-server" + ENDPOINT, "names https://evil.example.com"), + ("https://evil.example.com" + ENDPOINT, "not this platform"), + ("http://localhost:9443/servers/qs-view-server" + ENDPOINT, "not this platform"), # scheme downgrade + ("https://localhost:9444/servers/qs-view-server" + ENDPOINT, "not this platform"), # another port + ("https://erin@localhost:9443/servers/qs-view-server" + ENDPOINT, "not this platform"), # user info + ("https://localhost:9443@evil.example.com/servers/qs-view-server" + ENDPOINT, "not this platform"), + ("//evil.example.com/servers/qs-view-server" + ENDPOINT, "not this platform"), # scheme-relative + ("ftp://localhost:9443/servers/qs-view-server" + ENDPOINT, "not this platform"), + ("/servers/another-view-server" + ENDPOINT, "names view server 'another-view-server'"), + ("/api/open-metadata/metadata-expert/metadata-elements/by-search-string", "not one of the query endpoints"), + ("/api/open-metadata/asset-maker/assets", "not one of the query endpoints"), + ("/api/insights/search", "not one of the query endpoints"), # the Portal's own API + ("/api/open-metadata/metadata-expert/../asset-maker/assets", "not a plain endpoint path"), + ("/api/open-metadata/metadata-expert/metadata-elements/./by-search-conditions", "not a plain endpoint path"), + ("/api/open-metadata/metadata-expert//metadata-elements/by-search-conditions", "not a plain endpoint path"), + ("/api/open-metadata/metadata-expert/metadata-elements/%2e%2e/by-search-conditions", "characters"), + (ENDPOINT + "?pushDown=true", "query string"), + (ENDPOINT + "#x", "query string or fragment"), + ("", "no Query URL"), + (None, "no Query URL"), +] + + +@pytest.mark.parametrize("url,words", REFUSED) +def test_every_other_url_is_refused_with_a_sentence_and_reaches_nothing(url, words): + viewer = _Viewer(stored=[_saved_query(query_url=url)], answer=5) + out = saved_query(viewer, QN, mode="live") + assert out["refused"] is True and out["value"] is None + assert out["state"] == "not_established" and out["absence"] == "not_applicable" + assert words in out["state_reason"] + assert [c[0] for c in viewer.calls] == ["find"] # the lookup only: the stored request never ran + + +@pytest.mark.parametrize("body,words", [ + (json.dumps({**QUERY_BODY, "class": "NewElementRequestBody"}), "takes FindRequestBody"), + ("not json", "not JSON"), + (None, "no Query Request Body"), + ("[1, 2]", "no Query Request Body"), +]) +def test_a_request_body_that_is_not_a_find_is_refused(body, words): + viewer = _Viewer(stored=[_saved_query(body=body)], answer=5) + out = saved_query(viewer, QN, mode="live") + assert out["refused"] is True and words in out["state_reason"] + assert [c[0] for c in viewer.calls] == ["find"] + + +def test_the_allow_list_is_the_one_find_endpoint(): + assert set(sq.ALLOWED_QUERY_ENDPOINTS) == {ENDPOINT} + + +def test_bad_arguments_are_errors_not_answers(): + for kw in ({"mode": "both"}, {"output": "chart"}): + with pytest.raises(ValueError): + saved_query(_Viewer(), QN, **kw) + with pytest.raises(ValueError): + saved_query(_Viewer(), "") + + +def test_it_is_a_registered_analytic_function(): + from pyegeria.view.analytic_registry import get_analytic_registry + from pyegeria.view.format_set_executor import resolve_report_spec_function + spec = get_analytic_registry()["saved_query"] + assert spec.inputs == ["egeria_client:EgeriaTech"] + assert resolve_report_spec_function("saved_query") is saved_query + + +def test_through_the_report_executor_it_runs_on_the_viewers_own_client(): + from pyegeria.view import format_set_executor as fse + from pyegeria.view.role_supply import Subject, Viewer + + viewer = _Viewer(answer=4) + + class _Supply: + asked = [] + + def client(self, cls): + self.asked.append(cls.__name__) + return viewer + + def viewer(self): + return Viewer(user_id="erinoverview", is_admin=False, display_name="Erin") + + def reader(self, source): + return None + + def subject(self): + return Subject(guid="g", type_name="Asset") + + def refusal_words(self, kind): + return f"cannot supply {kind}" + + supply = _Supply() + out = fse._run_analytic_function({"analytic_function": "saved_query"}, + params={"name": QN, "mode": "live"}, view_server="vs", view_url="https://x", + user="u", user_pass="p", supply=supply) + assert out["value"] == 4 + assert supply.asked == ["EgeriaTech"] + assert all(c[0] == "find" for c in viewer.calls) From 69f05b0cf3db2c2814e6d2c47559afa68fbc3e5d Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Tue, 10 Nov 2026 21:31:29 +0000 Subject: [PATCH 03/12] fix(view): Collection Members takes the collection's qualifiedName (W1) The "Collection Members" report spec required collection_guid, so a Report had to pin a GUID, and its dashboard tile broke (CLIENT_ERROR_400) once the collection was re-created. The spec now takes any one of collection_guid, collection_qname or collection_name. get_collection_members resolves a name through _resolve_collection_guid: qualifiedName first, then display name. A name that matches nothing raises PyegeriaNotFoundException (relatedHTTPCode 404) naming the collection, before any members request. Before, a missing qualifiedName surfaced as "Neither server_guid nor server_name were provided" and a missing display name was put in the URL as the GUID "No elements found". Report-spec seed rebuilt (External References.json). Signed-off-by: Dan Wolfson --- pyegeria/omvs/collection_manager.py | 37 +++++- pyegeria/view/base_report_formats.py | 7 +- pyegeria/view/seed/External References.json | 6 +- .../test_collection_members_by_qname.py | 114 ++++++++++++++++++ 4 files changed, 156 insertions(+), 8 deletions(-) create mode 100644 tests/micro-tests/test_collection_members_by_qname.py diff --git a/pyegeria/omvs/collection_manager.py b/pyegeria/omvs/collection_manager.py index 1d3e2c23..f87aa5b0 100644 --- a/pyegeria/omvs/collection_manager.py +++ b/pyegeria/omvs/collection_manager.py @@ -17,7 +17,7 @@ from pyegeria.core.request_filters import deprecated_names from pyegeria.core.request_filters import ListFilters from pyegeria.core.request_filters import filter_body_kwargs -from pyegeria.core._exceptions import PyegeriaInvalidParameterException +from pyegeria.core._exceptions import PyegeriaInvalidParameterException, PyegeriaNotFoundException from pyegeria.core._globals import NO_ELEMENTS_FOUND, NO_GUID_RETURNED from pyegeria.view.base_report_formats import select_report_spec, get_report_spec_match from pyegeria.models import (SearchStringRequestBody, FilterRequestBody, GetRequestBody, NewElementRequestBody, @@ -1186,6 +1186,36 @@ def get_collection_by_guid( ) + async def _resolve_collection_guid(self, collection_name: Optional[str] = None, + collection_qname: Optional[str] = None) -> str: + """The GUID of the collection with this qualifiedName (tried first) or display name. + + Raises PyegeriaInvalidParameterException when neither is given, and PyegeriaNotFoundException + (relatedHTTPCode 404) when nothing matches. The shared __async_get_guid__ helper is not used + alone here: a qualifiedName it can't find surfaced as "Neither server_guid nor server_name + were provided", and a display name it can't find came back as the string NO_ELEMENTS_FOUND, + which was then put in the URL as if it were a GUID. + """ + if not (collection_qname or collection_name): + raise PyegeriaInvalidParameterException(None, None, { + "reason": "Give collection_guid, collection_qname or collection_name."}) + guid = None + if collection_qname: + try: + guid = await self.__async_get_guid__(None, None, "qualifiedName", collection_qname, None) + except PyegeriaInvalidParameterException: + guid = None # not found: the helper falls through to its "nothing given" error + if (not guid or guid == NO_ELEMENTS_FOUND) and collection_name: + guid = await self.__async_get_guid__(None, collection_name, "displayName", None, None) + if not guid or guid == NO_ELEMENTS_FOUND: + named = collection_qname or collection_name + raise PyegeriaNotFoundException(None, None, { + "reason": f"The collection {named!r} was not found.", + "relatedHTTPCode": 404, + "collection": named, + }) + return guid + @dynamic_catch async def _async_get_collection_members(self, collection_guid: Optional[str] = None, collection_name: Optional[str] = None, collection_qname: Optional[str] = None, body: Optional[dict | ResultsRequestBody] = None, start_from: int = 0, @@ -1249,9 +1279,8 @@ async def _async_get_collection_members(self, collection_guid: Optional[str] = N """ - if collection_guid is None: - collection_guid = self.__get_guid__(collection_guid, collection_name, "displayName", - collection_qname, None, ) + if not collection_guid: + collection_guid = await self._resolve_collection_guid(collection_name, collection_qname) url = str(HttpUrl(f"{self.collection_command_root}/{collection_guid}/members")) diff --git a/pyegeria/view/base_report_formats.py b/pyegeria/view/base_report_formats.py index 1ffdb8db..bf410827 100644 --- a/pyegeria/view/base_report_formats.py +++ b/pyegeria/view/base_report_formats.py @@ -2465,8 +2465,11 @@ def _user_report_specs_dir() -> str: formats=[COLLECTION_DICT, COLLECTION_TABLE], action=ActionParameter( function="CollectionManager.get_collection_members", - required_params=["collection_guid"], - optional_params=OPTIONAL_FILTER_PARAMS + TIME_PARAMETERS + ["body"], + # One of the three names the collection. A Report should pin it by qualifiedName + # (collection_qname): a GUID goes stale when the collection is re-created (W1). + required_params=[], + optional_params=["collection_guid", "collection_qname", "collection_name"] + + OPTIONAL_FILTER_PARAMS + TIME_PARAMETERS + ["body"], spec_params={"output_format": "DICT"}, ) ), diff --git a/pyegeria/view/seed/External References.json b/pyegeria/view/seed/External References.json index 4da74d40..bb3079a2 100644 --- a/pyegeria/view/seed/External References.json +++ b/pyegeria/view/seed/External References.json @@ -305,7 +305,9 @@ "microflow": { "format": "microflow/1", "params": { - "collection_guid": {"type": "string", "required": true}, + "collection_guid": {"type": "string", "required": false}, + "collection_qname": {"type": "string", "required": false}, + "collection_name": {"type": "string", "required": false}, "sequencing_order": {"type": "string", "required": false}, "sequencing_property": {"type": "string", "required": false}, "page_size": {"type": "string", "required": false}, @@ -319,7 +321,7 @@ "stage": "producer/find", "type": "Collection", "function": "CollectionManager.get_collection_members", - "params": {"collection_guid": "$collection_guid", "output_format": "DICT"} + "params": {"output_format": "DICT"} } ], "formatters": { diff --git a/tests/micro-tests/test_collection_members_by_qname.py b/tests/micro-tests/test_collection_members_by_qname.py new file mode 100644 index 00000000..2b623172 --- /dev/null +++ b/tests/micro-tests/test_collection_members_by_qname.py @@ -0,0 +1,114 @@ +"""W1: a Report pins its collection by qualifiedName, not GUID. + +The "Collection Members" report spec required collection_guid, so a Report had to hard-code a GUID, and it +broke (CLIENT_ERROR_400) once the collection was re-created. The spec now takes any one of collection_guid, +collection_qname or collection_name, and get_collection_members resolves a name at run time. A name that +matches nothing raises PyegeriaNotFoundException (relatedHTTPCode 404) naming the collection; it used to +surface as "Neither server_guid nor server_name were provided" (qualifiedName) or as a request for the +GUID "No elements found" (display name). +""" +import asyncio + +import pytest + +from pyegeria.core._exceptions import PyegeriaInvalidParameterException, PyegeriaNotFoundException +from pyegeria.core._globals import NO_ELEMENTS_FOUND +from pyegeria.omvs.collection_manager import CollectionManager +from pyegeria.view.base_report_formats import get_report_registry + +QN = "Coco Pharmaceuticals::WorkItemList::Local-Dashboards---Next-Steps::1.0" + + +@pytest.fixture +def client(monkeypatch): + monkeypatch.setattr(CollectionManager, "check_connection", lambda self: "test") + c = CollectionManager("view-server", "https://localhost:1", "user", "pwd") + c.lookups = [] + c.requests = [] + + async def fake_lookup(guid=None, display_name=None, property_name="qualifiedName", qualified_name=None, + tech_type=None, organization_name=None, for_lineage=False): + c.lookups.append((property_name, qualified_name or display_name)) + known = {("qualifiedName", QN): "coll-guid-1", ("displayName", "Local Dashboards - Next Steps"): "coll-guid-1"} + if qualified_name: + if ("qualifiedName", qualified_name) in known: + return known[("qualifiedName", qualified_name)] + if display_name is None: # the real helper's fall-through when a qualifiedName isn't found + raise PyegeriaInvalidParameterException(None, None, {"reason": "Neither server_guid nor server_name were provided"}) + return known.get(("displayName", display_name), NO_ELEMENTS_FOUND) + + async def fake_results(url, **kwargs): + c.requests.append(url) + return [{"guid": "member-1"}] + + monkeypatch.setattr(c, "_ServerClient__async_get_guid__", fake_lookup, raising=False) + monkeypatch.setattr(c, "__async_get_guid__", fake_lookup, raising=False) + monkeypatch.setattr(c, "_async_get_results_body_request", fake_results) + return c + + +def _members(c, **kw): + return asyncio.run(c._async_get_collection_members(output_format="JSON", **kw)) + + +def test_members_by_qualified_name(client): + assert _members(client, collection_qname=QN) == [{"guid": "member-1"}] + assert client.requests[-1].endswith("/collections/coll-guid-1/members") + assert client.lookups == [("qualifiedName", QN)] + + +def test_members_by_display_name(client): + _members(client, collection_name="Local Dashboards - Next Steps") + assert client.requests[-1].endswith("/collections/coll-guid-1/members") + + +def test_a_guid_is_used_as_given(client): + _members(client, collection_guid="g-direct") + assert client.requests[-1].endswith("/collections/g-direct/members") + assert client.lookups == [] + + +@pytest.mark.parametrize("kw, named", [ + ({"collection_qname": "Coco Pharmaceuticals::WorkItemList::Gone::1.0"}, "Coco Pharmaceuticals::WorkItemList::Gone::1.0"), + ({"collection_name": "Gone"}, "Gone"), +]) +def test_a_name_that_matches_nothing_is_not_found_and_never_requested(client, kw, named): + with pytest.raises(PyegeriaNotFoundException) as info: + _members(client, **kw) + assert info.value.related_http_code == 404 + assert named in str(info.value) + assert client.requests == [], "no members request with a made-up GUID" + + +def test_nothing_given_is_an_invalid_parameter(client): + with pytest.raises(PyegeriaInvalidParameterException, match="collection_qname"): + _members(client) + + +def test_the_report_spec_accepts_a_qualified_name(): + action = get_report_registry()["Collection Members"].action + assert action.required_params == [] + for p in ("collection_guid", "collection_qname", "collection_name"): + assert p in action.optional_params + + +def test_exec_report_spec_passes_the_qualified_name_through(monkeypatch): + """The dashboard path: a Report's flat params reach get_collection_members unchanged.""" + import pyegeria.view.format_set_executor as fse + calls = [] + + class _Fake: + def __init__(self, *a, **k): pass + def create_egeria_bearer_token(self, *a, **k): return "token" + def set_bearer_token(self, token): pass + def close_session(self): pass + def get_collection_members(self, collection_guid=None, collection_name=None, collection_qname=None, + body=None, start_from=0, page_size=0, output_format="JSON", report_spec=None, **kw): + calls.append({"collection_guid": collection_guid, "collection_qname": collection_qname, + "collection_name": collection_name}) + return [{"guid": "member-1"}] + + monkeypatch.setattr(fse, "_resolve_client_and_method", lambda decl: (_Fake, decl.split(".")[-1])) + fse.exec_report_spec("Collection Members", output_format="DICT", params={"collection_qname": QN}, + view_server="v", view_url="https://x", user="u", user_pass="p") + assert calls == [{"collection_guid": None, "collection_qname": QN, "collection_name": None}] From aa70ca930c96fb4cb380bd02a1e8a136ce4b45a0 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Tue, 10 Nov 2026 21:33:18 +0000 Subject: [PATCH 04/12] =?UTF-8?q?feat(report-specs):=20saved=5Fquery=20par?= =?UTF-8?q?ameters,=20a=20saved=20query=20as=20a=20template=20(=C2=A79)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Brief §9 (owner: "parameterize a saved query rather than just run it plain"). - additionalProperties.parameters declares {name, type string|int|bool| enum, default, required, values}; a bad declaration is refused. - saved_query(..., params={...}) binds the given values plus defaults, typed. In the request body a placeholder is a whole value "{{name}}", replaced by the typed value: never concatenated, never in a key, never in the URL (which is not a template; the allow-list rule is unchanged). - Refused with a sentence before anything runs: undeclared names, missing required values, wrong types, enum values outside the list, strings with control characters or "{{", placeholders in keys, inside longer strings or naming an unbound value, and params on a query that declares none. A URL or path in a string value is data only. - Cached: one Results Set holds one answer, for the values its refresh recorded (additionalProperties.lastRefreshParams). It is returned only for exactly those values (defaults included), labelled "as of