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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/release-notes/6.2.29.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,14 @@
`userAccountStatusProfile` pie charts, and others.
- Vega-Lite keys (`...BarGraph`, `...PieGraph`) are not matched.
- A column title ending in "Mermaid Graph", "Mermaid Mind Map", "Mermaid Pie Chart" or "Lineage Graph" also counts.

## Fixed

- **A report spec refusal logs at WARNING, not ERROR.** A refusal that reaches `exec_report_spec`'s
failure log (today the `'*'` search refusals, now `SearchRefused`) logs at WARNING; any other
`ValueError` still logs at ERROR; both are raised. The analytic and role refusals are raised before
that log. `SearchRefused` is raised by `find_elements_by_property_value` and
`find_metadata_elements_with_string` for `'*'` with no type (or a root type); it is a `ValueError`
subclass in `pyegeria.core.request_filters`, so `except ValueError` still catches it.
- **`metric_trend`'s docstring no longer says a dotted `metric_path` still works.** Only registered
names are accepted; a dotted path has been refused (`AnalyticFunctionRefused`) since 6.2.19.
7 changes: 7 additions & 0 deletions pyegeria/core/request_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"SearchFilters",
"FindFilters",
"UnknownFilterWarning",
"SearchRefused",
"FilterKind",
"valid_filter_names",
"filter_body_kwargs",
Expand All @@ -74,6 +75,12 @@
]


class SearchRefused(ValueError):
"""A find_* call refused a search it should not send, such as '*' with no type or a root type
(it would list every element). A ``ValueError``, so ``except ValueError`` still catches it; the
report executor logs it at WARNING, as an expected refusal."""


class UnknownFilterWarning(UserWarning):
"""A find_*/get_* call was given a keyword argument that is not a filter for its request.

Expand Down
3 changes: 2 additions & 1 deletion pyegeria/omvs/classification_explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from pyegeria.core.request_filters import deprecated_names
from pyegeria.core.request_filters import GetFilters, ListFilters, SearchFilters
from pyegeria.core.request_filters import filter_body_kwargs
from pyegeria.core.request_filters import SearchRefused
from pyegeria.core._exceptions import PyegeriaException, PyegeriaInvalidParameterException
from pyegeria.core._server_client import ServerClient
from pyegeria.core._globals import default_timeout, NO_ELEMENTS_FOUND
Expand Down Expand Up @@ -3128,7 +3129,7 @@ async def _async_find_elements_by_property_value(
if not metadata_element_type or metadata_element_type in _ROOT_TYPES:
# A root type is no narrower than no type: listing every element of the repository
# ran the quickstart platform out of heap (2026-11-09), so it is refused like '*'.
raise ValueError("find_elements_by_property_value: give a search string or a narrower type "
raise SearchRefused("find_elements_by_property_value: give a search string or a narrower type "
"('*' with no metadata_element_type, or with "
f"{'/'.join(sorted(_ROOT_TYPES))}, would list every element)")
# Never fetch a whole type in one call: one page of at most STAR_PAGE_MAX, paged by start_from.
Expand Down
3 changes: 2 additions & 1 deletion pyegeria/omvs/metadata_expert.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from pyegeria.core.request_filters import deprecated_names
from pyegeria.core.request_filters import FindFilters
from pyegeria.core.request_filters import filter_body_kwargs
from pyegeria.core.request_filters import SearchRefused
from pyegeria.models import (NewOpenMetadataElementRequestBody, TemplateRequestBody,
UpdatePropertiesRequestBody, MetadataSourceRequestBody,
ReIdentifyRequestBody, ReTypeRequestBody, ReHomeRequestBody,
Expand Down Expand Up @@ -2266,7 +2267,7 @@ async def _async_find_metadata_elements_with_string(self, search_string: str = "
if search_string in (None, "", "*") and body is None and not (
metadata_element_type or metadata_element_subtypes or include_only_classified_elements):
# Egeria refuses this with "searchString is null" (OMAG-COMMON-400-022); say why in plain words.
raise ValueError("find_metadata_elements_with_string: give a search string or a type "
raise SearchRefused("find_metadata_elements_with_string: give a search string or a type "
"(metadata_element_type, metadata_element_subtypes or "
"include_only_classified_elements); '*' alone is not a search")
url = (
Expand Down
18 changes: 17 additions & 1 deletion pyegeria/view/format_set_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,20 @@ class AnalyticFunctionRefused(ValueError):
pass


def _is_spec_refusal(exc: BaseException) -> bool:
"""True when `exc` is a report spec refusal: an expected outcome, not a failure.

The refusals are the allowlist's (AllowlistRefusal), the analytic-function resolver's
(AnalyticFunctionRefused), a declared input the environment cannot supply (RoleRefused),
a microflow this pyegeria cannot run or parse (CannotRunYet, MicroflowError), and a search a
find method refuses to send (SearchRefused: '*' with no type or a root type).
"""
from pyegeria.view.microflow import AllowlistRefusal, CannotRunYet, MicroflowError # lazy: microflow imports this module
from pyegeria.core.request_filters import SearchRefused
return isinstance(exc, (AllowlistRefusal, AnalyticFunctionRefused, RoleRefused, CannotRunYet, MicroflowError,
SearchRefused))


def analytic_module_prefixes() -> tuple:
"""The allowed module prefixes: PYEGERIA_ANALYTIC_MODULE_PREFIXES if set, else the defaults."""
raw = os.getenv("PYEGERIA_ANALYTIC_MODULE_PREFIXES", "").strip()
Expand Down Expand Up @@ -1379,7 +1393,9 @@ def _exec_report_spec_impl(
raise
except ValueError as e:
# Never a silent None (6.2.28): the caller gets the error and its words.
logger.error(f"Report spec '{format_set_name}' ({output_format}) failed: {e}")
# A refusal is expected (WARNING); any other ValueError is a real failure (ERROR).
log = logger.warning if _is_spec_refusal(e) else logger.error
log(f"Report spec '{format_set_name}' ({output_format}) failed: {e}")
# Re-raised, as the async path does: a plain-words refusal must not reach the caller as "no result".
raise

Expand Down
5 changes: 3 additions & 2 deletions pyegeria/view/overview_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -2058,8 +2058,9 @@ def metric_trend(
`metric_path` names the function the way a report spec's
`analytic_function` does: a registered analytic function name (e.g.
"governed_coverage"). It is resolved through the report-spec resolver
(ISSUE-173), so a caller-supplied value gets the same allowlist check;
a dotted path still works but is deprecated.
(ISSUE-173), so a caller-supplied value gets the same allowlist check.
Only registered names are accepted; a dotted path is refused
(AnalyticFunctionRefused, since 6.2.19).

Pass both `mgr` and `ce` regardless of what the target function actually
needs -- only the client parameter names it declares (by leading
Expand Down
112 changes: 112 additions & 0 deletions tests/micro-tests/test_report_spec_refusal_log_level.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""exec_report_spec logs a spec refusal at WARNING and any other ValueError at ERROR (6.2.29).

Both are still raised (6.2.28: never a silent None). Offline: the find method's request raises.
"""
from __future__ import annotations

import pytest
from loguru import logger

import pyegeria.view.format_set_executor as fse
from pyegeria.egeria_tech_client import EgeriaTech
from pyegeria.omvs.asset_catalog import AssetCatalog
from pyegeria.view.format_set_executor import AnalyticFunctionRefused, exec_report_spec
from pyegeria.view.microflow import AllowlistRefusal, CannotRunYet, MicroflowError
from pyegeria.view.role_supply import RoleRefused
from pyegeria.core.request_filters import SearchRefused

pytestmark = pytest.mark.unit


@pytest.fixture
def raising_asset_catalog(monkeypatch):
"""AssetCatalog with no platform, whose request raises the exception the test sets."""
box = {}

def _init(self, view_server, platform_url, user_id=None, user_pwd=None, **_):
self.view_server, self.platform_url, self.user_id = view_server, platform_url, user_id

async def _request(self, *a, **k):
raise box["exc"]

real_resolve = fse._resolve_client_and_method

def _resolve(decl):
cls, method = real_resolve(decl)
return (AssetCatalog, method) if decl == "AssetCatalog.get_asset_graph_by_guid" else (cls, method)

def _no_egeria_tech(self, *a, **k):
raise AssertionError("the test would have built a real EgeriaTech client")

monkeypatch.setattr(fse, "_resolve_client_and_method", _resolve)
monkeypatch.setattr(EgeriaTech, "__init__", _no_egeria_tech)
monkeypatch.setattr(AssetCatalog, "__init__", _init)
monkeypatch.setattr(AssetCatalog, "_async_make_request", _request)
monkeypatch.setattr(AssetCatalog, "create_egeria_bearer_token", lambda self, *a, **k: "token")
monkeypatch.setattr(AssetCatalog, "close_session", lambda self: None)
return box


@pytest.fixture
def log_records():
records = []
sink = logger.add(lambda m: records.append((m.record["level"].name, m.record["message"])), level="DEBUG")
yield records
logger.remove(sink)


def _run():
return exec_report_spec("Asset-Graph", output_format="DICT", params={"guid": "g-1"},
view_server="qs-view-server", view_url="https://localhost:9443",
user="tester", user_pass="unused")


def _failed_lines(records):
return [(level, msg) for level, msg in records if "Report spec 'Asset-Graph' (DICT) failed:" in msg]


@pytest.mark.parametrize("exc", [
AllowlistRefusal("stage 0: not on the allowlist"),
AnalyticFunctionRefused("not a registered name"),
RoleRefused("Routine 'x' cannot run: no reader."),
CannotRunYet("producer/join"),
MicroflowError("not valid JSON"),
SearchRefused("give a search string or a narrower type"),
], ids=lambda e: type(e).__name__)
def test_a_refusal_logs_at_warning_and_is_raised(raising_asset_catalog, log_records, exc):
raising_asset_catalog["exc"] = exc
with pytest.raises(type(exc)):
_run()
lines = _failed_lines(log_records)
assert [level for level, _ in lines] == ["WARNING"]
assert str(exc) in lines[0][1]


def test_an_unexpected_value_error_still_logs_at_error(raising_asset_catalog, log_records):
raising_asset_catalog["exc"] = ValueError("something broke")
with pytest.raises(ValueError, match="something broke"):
_run()
assert [level for level, _ in _failed_lines(log_records)] == ["ERROR"]


def test_search_refused_is_a_value_error():
assert issubclass(SearchRefused, ValueError)


def test_star_on_a_root_type_logs_at_warning_through_exec_report_spec(monkeypatch, log_records):
"""End to end: Element-DrE-Basic searches OpenMetadataRoot; '*' is refused before any request."""
from pyegeria.omvs.classification_explorer import ClassificationExplorer

async def _no_request(self, *a, **k):
raise AssertionError("the refusal should come before any request")

monkeypatch.setattr(ClassificationExplorer, "_async_make_request", _no_request)
monkeypatch.setattr(EgeriaTech, "close_session", lambda self: None, raising=False)
with pytest.raises(ValueError) as exc:
exec_report_spec("Element-DrE-Basic", output_format="DICT", params={"search_string": "*"},
view_server="qs-view-server", view_url="https://localhost:9443",
user="tester", user_pass="unused", token="offline-token")
assert isinstance(exc.value, SearchRefused)
assert "give a search string or a narrower type" in str(exc.value)
lines = [(level, msg) for level, msg in log_records if "Report spec 'Element-DrE-Basic' (DICT) failed:" in msg]
assert [level for level, _ in lines] == ["WARNING"]
8 changes: 5 additions & 3 deletions tests/micro-tests/test_search_get_filter_kwargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,15 +406,16 @@ def test_every_generic_search_spec_names_a_type():


def test_untyped_star_is_refused_with_words(explorer, monkeypatch):
from pyegeria.core.request_filters import SearchRefused
from pyegeria.omvs.metadata_expert import MetadataExpert

with pytest.raises(ValueError, match="give a search string or a"):
with pytest.raises(SearchRefused, match="give a search string or a"):
explorer.find_elements_by_property_value("*", ["displayName"])
assert not explorer.sent

monkeypatch.setattr(MetadataExpert, "check_connection", lambda self: "test")
expert = MetadataExpert("view-server", "https://egeria.example:9443", "user", "pwd")
with pytest.raises(ValueError, match="give a search string or a type"):
with pytest.raises(SearchRefused, match="give a search string or a type"):
expert.find_metadata_elements_with_string("*")


Expand Down Expand Up @@ -557,7 +558,8 @@ def close_session(self):
pass

def find_things(self, search_string="*", **kwargs):
raise ValueError("give a search string or a narrower type")
from pyegeria.core.request_filters import SearchRefused
raise SearchRefused("give a search string or a narrower type")

fmt = {"action": {"function": "X.find_things", "required_params": ["search_string"], "spec_params": {}}}
monkeypatch.setattr(fse, "select_report_spec", lambda name, kind: fmt)
Expand Down
Loading