diff --git a/PYEGERIA_ISSUES.md b/PYEGERIA_ISSUES.md index 276bc491..4dca53e6 100644 --- a/PYEGERIA_ISSUES.md +++ b/PYEGERIA_ISSUES.md @@ -172,6 +172,8 @@ re-test candidates moved into *Awaiting re-test* below the open sections. create-from-template) and 7 (`viewElementGUID`) are still open. **Open pyegeria items** +- ISSUE-184: a Smart Collection was recognised by the Portal's `smartCollection` flag, not by Egeria's catalog target (fixed for 6.2.35) +- ISSUE-183: deleting a SavedQuery left its SmartQuery links, and pyegeria had no delete that detached them (fixed for 6.2.35) - ISSUE-182: an element hidden by zone security (403-020) was reported as AUTHORIZATION_ERROR_401 (fixed in 6.2.34) - ISSUE-181 (HIGH): Dr.Egeria Parent ID on an Update deleted an unrelated relationship of the parent type, e.g. a folder's member (fixed for 6.2.32; moves to the Appendix on release) - ISSUE-174: link methods discarded the new relationship GUID (fixed for 6.2.19; moves to the Appendix on release) @@ -195,6 +197,26 @@ into the entry now, so it isn't rediscovered from scratch later. --- +### ISSUE-184: a Smart Collection was recognised by a flag, not by Egeria's record + +**Layer:** pyegeria · **Severity:** medium: a cached answer could be served as "kept current by Egeria" when it was not, or refused when it was · **Status:** fixed 2026-11-11 on branch `feat/smart-collection-catalog-target`, targets 6.2.35 · **Found:** backlog, from the Smart Collections design (Egeria #9200, 0725). + +**What:** `saved_query` treated a SavedQuery as a registered Smart Collection when `additionalProperties.smartCollection == "true"`, the Portal's flag. Egeria records registration differently: the Smart Collections integration connector maintains a Results Set that is its CatalogTarget, under the target name `resultsSetToMaintain` (`SmartCollectionsCatalogTarget.CATALOG_TARGET`), and the SavedQuery reaches that Results Set through SmartQuery. A flag can be set without the registration, or the registration made without the flag, so the "answered only for the stored values" rule could apply to the wrong queries. + +**Done:** `_smart_collection_results_set` reads SmartQuery from the SavedQuery (end 2) and CatalogTarget from each Results Set (end 2); registered means an IntegrationConnector holds it as `resultsSetToMaintain`, and that Results Set is the one read. Only in cached mode. A failed read is not a registration (the ordinary cached path then serves only recorded values, so it is never wrong). + +Tests: `tests/micro-tests/test_saved_query_analytic.py`, with a CatalogTarget related element captured read-only from a quickstart platform (`data/catalog_target_related_2026_11_11.json`). + +### ISSUE-183: deleting a SavedQuery left its SmartQuery links behind + +**Layer:** pyegeria · **Severity:** medium: an orphaned link, and a delete Egeria refuses · **Status:** fixed 2026-11-11 on branch `feat/saved-query-delete-detach`, targets 6.2.35 · **Found:** backlog; the Portal's insights handler works around it by hand. + +**What:** pyegeria had no SavedQuery delete beyond `delete_asset`. Egeria deletes only what the deleted element anchors, so a SmartQuery link to an independently anchored Results Set was left behind, and blocks the delete (OMAG-GENERIC-HANDLERS-403-005). The Portal detaches it first, finding it from its own `additionalProperties` markers. + +**Done:** `pyegeria.view.saved_query.delete_saved_query(client, guid)` finds every Results Set linked by SmartQuery from Egeria's relationships, detaches each (`detach_smart_query`), then deletes the SavedQuery. Results Sets are kept and named in the result. A link that cannot be detached stops the delete with the reason. + +Tests: `tests/micro-tests/test_saved_query_delete.py`. + ### ISSUE-182: an element hidden by zone security is reported as "AUTHORIZATION_ERROR_401" **Layer:** pyegeria · **Severity:** medium: misleading diagnosis, no wrong data · **Status:** fixed 2026-11-10 on branch `docs/issue-182-unauthorized-banner`; released in 6.2.34 · **Found:** 2026-11-10 on 6.2.32 (laz), reading a Report zoned `['peterprofile']` as erinoverview; the Architect confirmed `is_not_visible_error` is True for it. diff --git a/docs/release-notes/6.2.35.md b/docs/release-notes/6.2.35.md new file mode 100644 index 00000000..b9c5688c --- /dev/null +++ b/docs/release-notes/6.2.35.md @@ -0,0 +1,49 @@ +# pyegeria 6.2.35 + +pyegeria 6.2.35 makes these changes: +- A tool can list the zone-restricted report specs one signed-in user may see (B6). +- A saved query is a Smart Collection when Egeria records it as one, not when a flag says so (ISSUE-184). +- `delete_saved_query` detaches a saved query's SmartQuery links before deleting it (ISSUE-183). +- A Dashboard Sheet's report tiles get their stored params: they reached the spec under the wrong names. +- A Smart Collection that Egeria has not refreshed yet reads "not refreshed yet", never 0. + +## New + +- **`list_visible_restricted_specs(client_as_user, folders=None)`** (`pyegeria.view.egeria_spec_cache`, B6). + A shared report-spec cache never holds a zoned spec, so a tool that shows restricted specs reads them per + user with this function, as that user's token: Egeria enforces the zones, so what comes back is exactly what + that user may see. Nothing is written to any cache. Folders are walked as a sync walks them (recursive inside + consumer folders); the result says which folders were read and why any were not. +- **`delete_saved_query(client, guid)`** (`pyegeria.view.saved_query`, ISSUE-183). Finds every Results Set + linked to the SavedQuery by SmartQuery, from Egeria's relationships rather than the Portal's + `additionalProperties`, detaches each through the collection-manager endpoint, then deletes the SavedQuery. + The Results Sets are kept and named in the result (deleting one also means unlinking its members and, for a + Smart Collection, its catalog target). A link Egeria will not detach stops the delete with the reason. + It deletes only a SavedQuery: the element is read and its type checked first, and anything else (a GUID of a + Report, a UserIdentity, ...) is refused with nothing deleted. The links are read page by page until Egeria + returns an empty page; more than 2,000 is refused rather than deleted with some left behind. + +## Changed + +- **A Smart Collection is detected by its catalog target** (`saved_query`, ISSUE-184). A SavedQuery is + registered as a Smart Collection, and so answered only for its stored values and labelled "kept current by + Egeria", when a Results Set linked to it by SmartQuery is a CatalogTarget of an IntegrationConnector under the + target name `resultsSetToMaintain` (the Smart Collections connector's declared target, Egeria #9200). That + Results Set is the one read. Until 6.2.34 the test was the Portal's `additionalProperties.smartCollection == + "true"`; the flag alone no longer registers. A lookup that fails is not a registration: the query takes the + ordinary cached path, which serves only the values its refresh recorded. + +## Fixed + +- **A Report's stored params reach its spec** (`dashboard_resolver`). A Report element stores its params + camelCase in additionalProperties (`searchString`, `pageSize`, `collectionQname`, `collectionGuid`, ...) and its + analytic params as a JSON string under `analyticParams`. `exec_report_spec` keeps only the names a spec + declares, which are snake_case, so every stored param was dropped, and collection-scoped tiles (catalog-health's + "Assets with No Lineage", local-dashboards-next-steps' "Tasks") failed for want of their collection. Both are + now passed in snake_case; a key already snake_case is unchanged and wins over a converted one. The Report as + read (`ResolvedReport.params`) keeps the stored names. +- **A Smart Collection not refreshed yet is not an empty answer** (`saved_query`). Egeria's Smart Collections + connector stamps the Results Set's `completionTime` on each refresh, so that is the answer's "as of" (it wins + over the Portal's refresh time). With no refresh recorded anywhere, the answer is `not_established`, "not + refreshed yet", and the (empty) Results Set is not read as 0. A Smart Collection lookup that cannot be made is + now said in the answer's `note`. diff --git a/pyegeria/view/dashboard_resolver.py b/pyegeria/view/dashboard_resolver.py index fd67e7a3..5406731e 100644 --- a/pyegeria/view/dashboard_resolver.py +++ b/pyegeria/view/dashboard_resolver.py @@ -42,6 +42,7 @@ import asyncio import json +import re from typing import Any, Callable, Dict, List, Literal, Optional, Tuple from loguru import logger @@ -250,13 +251,37 @@ def _all_resolutions() -> Dict[str, Any]: return {} +_CAMEL_RUN = re.compile(r"(.)([A-Z][a-z]+)") +_CAMEL_END = re.compile(r"([a-z0-9])([A-Z])") + + +def _snake(key: str) -> str: + """`collectionQname` -> `collection_qname`, `collectionGUID` -> `collection_guid`; snake_case is unchanged.""" + return _CAMEL_END.sub(r"\1_\2", _CAMEL_RUN.sub(r"\1_\2", key)).lower() + + +def _snake_params(params: Dict[str, Any]) -> Dict[str, Any]: + """A Report's stored params in the spec's own (snake_case) names. The Report element stores them camelCase in + additionalProperties (searchString, pageSize, collectionQname, ...), and exec_report_spec keeps only the names + the spec declares, so a camelCase key was dropped and a collection-scoped tile failed for want of its + collection (the Architect's LD-2 read-back, 2026-11-11). A key already snake_case wins over a converted one.""" + out: Dict[str, Any] = {} + for k, v in params.items(): + if isinstance(k, str) and _snake(k) != k: + out.setdefault(_snake(k), v) + for k, v in params.items(): + if not (isinstance(k, str) and _snake(k) != k): + out[k] = v + return out + + def _run_report(client: Any, placement: ResolvedPlacement) -> Dict[str, Any]: """exec_report_spec as the viewer: the client's own token, server and platform.""" from pyegeria.view.format_set_executor import exec_report_spec report = placement.report action = getattr(placement.format_set, "action", None) analytic = bool(getattr(action, "analytic_function", None)) if action is not None else False - params = dict(report.analytic_params if analytic else report.params) + params = _snake_params(dict(report.analytic_params if analytic else report.params)) return exec_report_spec( placement.fetched_as or placement.spec, output_format=report.output_format or "DICT", params=params, view_server=getattr(client, "server_name", None) or getattr(client, "view_server", None), diff --git a/pyegeria/view/egeria_spec_cache.py b/pyegeria/view/egeria_spec_cache.py index 0136ece4..92902a4b 100644 --- a/pyegeria/view/egeria_spec_cache.py +++ b/pyegeria/view/egeria_spec_cache.py @@ -56,6 +56,8 @@ "refresh_consumer_index", "read_consumer_index", "build_consumer_index", + "list_visible_restricted_specs", + "RESTRICTED_FORMAT", "CONSUMER_PREFIX", "DEFAULT_ROOT", "DEPTH_CAP", @@ -861,6 +863,117 @@ def build_consumer_index(client, *, root: Optional[str] = None, depth_cap: int = count_field="specs") +RESTRICTED_FORMAT = "pyegeria-restricted-specs/1" + + +def list_visible_restricted_specs(client_as_user, folders: Optional[Iterable[str]] = None, *, + recursive: Optional[bool] = None, depth_cap: int = DEPTH_CAP) -> Dict[str, Any]: + """The zone-restricted ReportSpecs one signed-in user can see in the configured folders (B6). + + A shared cache never holds a zoned spec (§9, `ZONED_REASON`), so a tool that shows restricted + specs reads them per user with this function, **as that user's token**: Egeria enforces the + zones, so what comes back is exactly what this user may see. Nothing is written to any cache. + **The caller caches the result per credential identity (the token), never by bare user id**: two + sessions of one user id can hold different zone grants, and a cache keyed on the id would show + one session's restricted specs to the other. + + - `folders`: CollectionFolder qualified names; default `configured_folders()`. Consumer folders + are walked recursively (as `sync_report_specs` does), any other folder reads its direct members, + unless `recursive` says otherwise. + - Only ACTIVE ReportSpecs that carry at least one zone are returned: public ones are the shared + cache's business. The zones come from the full element when the member listing carries none. + + Returns `{"format", "identity", "status", "reason", "specs", "folders", "notes"}`: + - `specs`: `[{"label", "qualified_name", "guid", "version", "zones", "folders"}]`, sorted by label. + - `folders`: one `{"folder", "result", "detail", "count"}` per folder, `result` in + ok | not_found | unreadable | partial. A folder that is not found, or not visible to this user, + says so; it is never an empty list. + - `status`: "read" (every folder read), "partial" (some read), or "not read" (none, with `reason`). + An empty `specs` with status "read" means the folders were read and hold no restricted spec this + user can see; `reason` then says so in words. + """ + identity = _client_identity(client_as_user) + folder_qns = list(folders) if folders is not None else configured_folders() + out: Dict[str, Any] = {"format": RESTRICTED_FORMAT, "identity": identity, "status": "read", "reason": None, + "specs": [], "folders": [], "notes": []} + if not folder_qns: + out.update(status="not read", reason=f"no report spec folders are configured (set {FOLDERS_ENV} or " + f"config.json's \"Pyegeria Report Spec Folders\")") + return out + found: Dict[str, Dict[str, Any]] = {} # guid -> spec row + by_label: Dict[str, set] = {} + for qn in folder_qns: + row = {"folder": qn, "result": "ok", "detail": None, "count": 0} + out["folders"].append(row) + try: + folder = _find_folder(client_as_user, qn) + except Exception as exc: # noqa: BLE001 -- one folder's failure is stated, never hides the others + row.update(result="unreadable", detail=f"the folder could not be read: {exc}") + continue + if folder is None: + row.update(result="not_found", detail=f"folder not found, or not visible to {identity}") + continue + walk_recursive = _is_consumer_qn(qn) if recursive is None else bool(recursive) + try: + walk = _walk_folder(client_as_user, folder, recursive=walk_recursive, depth_cap=depth_cap, + stop_qns=folder_qns) + except Exception as exc: # noqa: BLE001 + row.update(result="unreadable", detail=f"the folder's members could not be read: {exc}") + continue + partial = [f"{p}: depth cap reached ({depth_cap} levels)" for p in walk.capped] + partial += [f"{p}: could not be read: {why}" for p, why in walk.errors] + if partial: + row.update(result="partial", detail="; ".join(partial)) + out["notes"].extend(f"{p}: not visible to {identity}, or not found" for p, _why in walk.gone) + for m in walk.members: + g = _guid(m) + try: + label, mqn = _identify(m) + except _Skip: + continue # not a ReportSpec: nothing restricted to show + if g in found: + if qn not in found[g]["folders"]: + found[g]["folders"].append(qn) + row["count"] += 1 + continue + el, zones = m, _zones(m) + if not zones: + try: + el = _get_full(client_as_user, g) or m + except Exception as exc: # noqa: BLE001 + out["notes"].append(f"{label}: its zones could not be read, so it is not listed: {exc}") + continue + zones = _zones(el) + if not zones: + continue # public: the shared cache holds it + status = _status(el, []) + if status != _ACTIVE: + out["notes"].append(f"{label}: contentStatus {status}, not listed") + continue + found[g] = {"label": label, "qualified_name": mqn, "guid": g, "version": _version(el), + "zones": zones, "folders": [qn]} + by_label.setdefault(label, set()).add(g) + row["count"] += 1 + for label, guids in by_label.items(): + if len(guids) > 1: + out["notes"].append(f"{label}: one label held by {len(guids)} elements ({', '.join(sorted(guids))}); " + f"neither is listed") + for g in guids: + found.pop(g, None) + out["specs"] = sorted(found.values(), key=lambda r: r["label"]) + read = [r for r in out["folders"] if r["result"] in ("ok", "partial")] + if not read: + out.update(status="not read", reason="no folder could be read: " + + "; ".join(f"{r['folder']}: {r['detail']}" for r in out["folders"])) + elif len(read) < len(out["folders"]) or any(r["result"] == "partial" for r in read): + out.update(status="partial", reason="not fully read: " + "; ".join( + f"{r['folder']}: {r['detail']}" for r in out["folders"] if r["result"] != "ok")) + elif not out["specs"]: + out["reason"] = (f"the folders were read as {identity} and hold no zone-restricted report spec " + f"visible to {identity}") + return out + + def refresh_consumer_index(client, *, cache_dir: Optional[str] = None, root: Optional[str] = None, depth_cap: int = DEPTH_CAP) -> Dict[str, Any]: """Build the consumer index and write it to `consumers.json` in the spec cache directory. diff --git a/pyegeria/view/saved_query.py b/pyegeria/view/saved_query.py index 0b18e49a..3b265925 100644 --- a/pyegeria/view/saved_query.py +++ b/pyegeria/view/saved_query.py @@ -33,7 +33,7 @@ from loguru import logger -__all__ = ["saved_query", "SavedQueryRefused", "ALLOWED_QUERY_ENDPOINTS", "SAVED_QUERY_PAGE_SIZE", +__all__ = ["saved_query", "delete_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 @@ -85,6 +85,11 @@ def _guid(el: Dict[str, Any]) -> str: return el.get("elementGUID") or (el.get("elementHeader") or {}).get("guid") or "" +def _type_names(el: Dict[str, Any]) -> List[str]: + t = (el.get("elementHeader") or {}).get("type") or {} + return [t.get("typeName") or ""] + list(t.get("superTypeNames") 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 "" @@ -259,9 +264,11 @@ def saved_query(client, name: str, mode: str = "cached", output: str = "count", size, and `startFrom` stays the read's own. A parameter with no `requestPath` applies to the Portal's search only, so live mode refuses it when it is given, or when its effective value is a default the stored search doesn't hold. - - A SavedQuery registered as a Smart Collection (`additionalProperties.smartCollection == "true"`, - the Portal's test) is re-run by Egeria's SmartCollectionsMembershipManager about every 30 - minutes from its stored request. Its cached answer stands only for the stored effective values + - A SavedQuery registered as a Smart Collection is re-run by Egeria's Smart Collections integration + connector about every 30 minutes from its stored request. Registered means what Egeria records, not a + flag: a Results Set linked to it by SmartQuery is a CatalogTarget of an IntegrationConnector, under + the connector's target name `resultsSetToMaintain` (6.2.35; the Portal's `smartCollection` flag was + the test before). That Results Set is the one read. Its cached answer stands only for the stored effective values (whatever a refresh recorded), is labelled "kept current by Egeria", and is refused for other values, pointing to live mode. An undeclared name, a value of the wrong type, a string with control characters or over 512 @@ -317,8 +324,9 @@ def saved_query(client, name: str, mode: str = "cached", output: str = "count", return _result(name, mode, output, state="not_established", reason=refused.sentence, absence="not_applicable", refused=True) - registered = _is_registered_smart_collection(additional) - if mode == "cached" and registered: + registered, registration_note = (_smart_collection_results_set(client, _guid(exact[0])) if mode == "cached" + else (None, None)) + if registered: # P-3: Egeria's SmartCollectionsMembershipManager re-runs the STORED request about every 30 minutes, # so the Results Set answers only for the stored effective values, whatever a refresh recorded. used = _effective_parameters(declared, None, _stored_search(props, additional)) if declared else {} @@ -326,7 +334,8 @@ def saved_query(client, name: str, mode: str = "cached", output: str = "count", return _not_measured(name, "cached", output, f"this saved query is a Smart Collection, kept current by " f"Egeria with its stored values ({_label(used)}), so its cached answer cannot " f"stand for {_label(effective)}; use mode live for these values") - out = _cached(client, name, output, additional, page_size, max_pages, kept_current=True) + out = _cached(client, name, output, {**additional, "resultsSetGuid": registered}, page_size, max_pages, + kept_current=True) elif mode == "cached": used = effective if declared: @@ -353,6 +362,8 @@ def saved_query(client, name: str, mode: str = "cached", output: str = "count", page_size = max(1, min(body["pageSize"], 1000)) # a declared page size is the read's page size out = _live(client, name, output, method, body, page_size, max_pages) out["how"] = f"{method} on this client's platform" + (f"; {note}" if note else "") + if registration_note: + out["note"] = registration_note if declared: out["params"] = used if out.get("subtitle") and out.get("asOf"): @@ -363,9 +374,40 @@ def saved_query(client, name: str, mode: str = "cached", output: str = "count", return out -def _is_registered_smart_collection(additional: Dict[str, Any]) -> bool: - """The Portal's own test (insights_handler._is_registered_smart_collection).""" - return str((additional or {}).get("smartCollection") or "").strip().lower() == "true" +#: The catalog target name Egeria's Smart Collections integration connector declares for the Results Sets it +#: maintains (SmartCollectionsCatalogTarget.CATALOG_TARGET, Egeria #9200). +SMART_COLLECTIONS_TARGET = "resultsSetToMaintain" + + +def _related(client, guid: str, relationship: str, end: int) -> List[Dict[str, Any]]: + return _elements(client.get_related_elements(guid, relationship, start_at_end=end, start_from=0, page_size=50, + output_format="JSON")) + + +def _smart_collection_results_set(client, saved_query_guid: str) -> Tuple[Optional[str], Optional[str]]: + """(the GUID of the Results Set that makes this SavedQuery a Smart Collection, or None; a note when the + lookup could not be made, else None). + + Registered is what Egeria records: a Results Set linked to the SavedQuery by SmartQuery (the SavedQuery is + end 2) that is a CatalogTarget (the Results Set is end 2) of an IntegrationConnector under the target name + `resultsSetToMaintain`. Not a name and not a flag. A read that fails is not a registration: the query then + takes the ordinary cached path, which serves only the values its refresh recorded, so it is never wrong.""" + if not saved_query_guid: + return None, None + try: + for rs in _related(client, saved_query_guid, "SmartQuery", 2): + if "ResultsSet" not in _type_names(rs): + continue + for connector in _related(client, _guid(rs), "CatalogTarget", 2): + rel = (connector.get("relatedBy") or {}).get("relationshipProperties") or {} + if ("IntegrationConnector" in _type_names(connector) + and rel.get("catalogTargetName") == SMART_COLLECTIONS_TARGET): + return _guid(rs), None + except Exception as exc: # noqa: BLE001 -- not registered as far as this viewer can tell; said in the answer + logger.debug(f"saved_query: Smart Collection lookup for {saved_query_guid} failed: {exc}") + return None, (f"whether this saved query is a Smart Collection could not be read ({type(exc).__name__}), " + f"so it is answered as one that is not") + return None, None # ── parameters: one model with the Portal (insights_handler, b9dce798) ────── @@ -559,7 +601,15 @@ def _cached(client, name, output, additional, page_size, max_pages, kept_current 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 and not kept_current: + if kept_current: + # Egeria's Smart Collections connector stamps the Results Set's completionTime on every refresh, so that + # is when this answer is from. With no refresh recorded anywhere, the Results Set holds nothing YET: an + # empty membership there is "not refreshed yet", never 0 (the Architect's LD-2 read-back, 2026-11-11). + as_of = _results_set_completion(client, results_set) or as_of + if not as_of: + return _not_measured(name, "cached", output, "this saved query is a Smart Collection that Egeria has " + "not refreshed yet, so its Results Set holds no answer yet (not an empty answer)") + elif 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: @@ -582,6 +632,20 @@ def _cached(client, name, output, additional, page_size, max_pages, kept_current return out +def _results_set_completion(client, results_set_guid: str) -> Optional[str]: + """When Egeria last refreshed a Smart Collection's Results Set (its completionTime), or None when it has not, + or the Results Set cannot be read (then the Portal's refresh time, if any, is what there is).""" + try: + found = _elements(client.get_collection_by_guid(results_set_guid, output_format="JSON")) + except Exception as exc: # noqa: BLE001 -- unknown, not "never": the caller falls back to the Portal's time + logger.debug(f"saved_query: Results Set {results_set_guid} could not be read: {exc}") + return None + when = _properties(found[0]).get("completionTime") if found else None + if isinstance(when, (int, float)) and when > 0: # epoch milliseconds + return datetime.fromtimestamp(when / 1000, tz=timezone.utc).isoformat(timespec="seconds") + return str(when) if when else None + + def _live(client, name, output, method, body, page_size, max_pages): fn = getattr(client, method) now = datetime.now(timezone.utc).isoformat(timespec="seconds") @@ -604,3 +668,70 @@ def _answer(name, mode, output, elements, capped, as_of): 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) + + +# ── deleting a saved query (6.2.35) ── + +DELETE_LINK_PAGE = 50 +DELETE_LINK_MAX_PAGES = 40 + + +def _all_related(client, guid: str, relationship: str, end: int) -> List[Dict[str, Any]]: + """Every element related to `guid` by `relationship`, read until Egeria returns an EMPTY page (a short page is + not the last page). More than DELETE_LINK_MAX_PAGES pages is refused rather than half read.""" + out: List[Dict[str, Any]] = [] + for page in range(DELETE_LINK_MAX_PAGES): + got = _elements(client.get_related_elements(guid, relationship, start_at_end=end, + start_from=page * DELETE_LINK_PAGE, + page_size=DELETE_LINK_PAGE, output_format="JSON")) + if not got: + return out + out.extend(got) + raise RuntimeError(f"delete_saved_query: {guid} has more than {DELETE_LINK_MAX_PAGES * DELETE_LINK_PAGE} " + f"{relationship} links; refused rather than delete with some left behind") + + +def delete_saved_query(client, saved_query_guid: str) -> Dict[str, Any]: + """Delete a SavedQuery, detaching its SmartQuery links first, so no Results Set is left linked to a query + that no longer exists. + + Egeria deletes only what the deleted element anchors; a SmartQuery link to an independently anchored Results + Set is left behind, and blocks the delete (OMAG-GENERIC-HANDLERS-403-005). So every Results Set linked to the + SavedQuery by SmartQuery (found from Egeria's relationships, not from the Portal's additionalProperties) is + detached through the dedicated endpoint, and then the SavedQuery is deleted. + + The Results Sets themselves are kept: deleting one also means unlinking its members and, for a Smart + Collection, its catalog target, which is the owner's call. They are named in the result. + + Returns {"deleted": guid, "detached": [results set guids], "results_sets_kept": [...]}. A link that cannot be + detached stops the delete, raising RuntimeError with the reason, so nothing is half done silently. + """ + if not saved_query_guid: + raise ValueError("delete_saved_query: the SavedQuery's GUID is required") + # It deletes only a SavedQuery: an asset delete reaches any element it is given a GUID for (remove_note's once + # reached a UserIdentity), so the element is read and its type checked first (the Architect's 6.2.35 read-back). + try: + found = _elements(client.get_asset_by_guid(saved_query_guid, graph_query_depth=0, output_format="JSON")) + except Exception as exc: # said; nothing is deleted + raise RuntimeError(f"delete_saved_query: {saved_query_guid} could not be read ({type(exc).__name__}: " + f"{exc}), so it was not deleted") from exc + kinds = _type_names(found[0]) if found else [] + if "SavedQuery" not in kinds: + raise RuntimeError(f"delete_saved_query: {saved_query_guid} is " + f"{'a ' + kinds[0] if kinds and kinds[0] else 'not found'}, not a SavedQuery; " + f"nothing was deleted") + linked = _all_related(client, saved_query_guid, "SmartQuery", 2) + detached: List[str] = [] + for rs in linked: + rs_guid = _guid(rs) + if not rs_guid: + continue + try: + client.detach_smart_query(rs_guid, saved_query_guid) + except Exception as exc: # said, and the delete does not go ahead + raise RuntimeError(f"delete_saved_query: the SmartQuery link from Results Set {rs_guid} could not be " + f"detached ({type(exc).__name__}: {exc}); the saved query was not deleted") from exc + detached.append(rs_guid) + client.delete_asset(saved_query_guid) + logger.info(f"Deleted saved query {saved_query_guid}; detached {len(detached)} SmartQuery link(s)") + return {"deleted": saved_query_guid, "detached": detached, "results_sets_kept": list(detached)} diff --git a/pyproject.toml b/pyproject.toml index 00efcf4e..2f711204 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ [project] name = "pyegeria" -version = "6.2.34" +version = "6.2.35" license = 'Apache-2.0' license-files = ["LICENSE"] authors = [{name = "Dan Wolfson", email = "dan.wolfson@pdr-associates.com"},] diff --git a/tests/micro-tests/data/catalog_target_related_2026_11_11.json b/tests/micro-tests/data/catalog_target_related_2026_11_11.json new file mode 100644 index 00000000..42f38b5c --- /dev/null +++ b/tests/micro-tests/data/catalog_target_related_2026_11_11.json @@ -0,0 +1,197 @@ +{ + "_about": "A CatalogTarget related element as Egeria returns it, captured read-only from a quickstart platform on 2026-11-11 (get_related_elements(, 'CatalogTarget', start_at_end=2)): the IntegrationConnector at end 1, with the relationship's properties under relatedBy. Bulky arrays the code never reads were removed; nothing else was changed. That platform's Smart Collections connector (Egeria:IntegrationGroup:SmartCollections::SmartCollectionsIntegrationConnector) had no targets yet, so the test derives its Smart Collections case from this shape, changing only the connector's names and the catalogTargetName.", + "catalogTargetFromTarget": { + "class": "OpenMetadataRootElement", + "elementHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "759da11b-ebb6-4382-bdc9-72adc7c922db", + "typeName": "IntegrationConnector", + "superTypeNames": [ + "DeployedConnector", + "DeployedSoftwareComponent", + "Process", + "Asset", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "A definition to control the execution of an integration connector.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "CONTENT_PACK", + "homeMetadataCollectionId": "e6756296-3fa3-4aa3-9450-0dc44b8beae2", + "homeMetadataCollectionName": "UnityCatalogContentPack", + "license": "Apache 2.0" + }, + "versions": { + "createdBy": "Egeria Project", + "updatedBy": "Egeria Project", + "maintainedBy": [ + "Egeria Project" + ], + "createTime": "2026-04-01T06:45:49.989+00:00", + "updateTime": "2026-04-01T06:45:49.989+00:00", + "version": 1791116345633 + }, + "guid": "74dde22f-2249-4ea3-af2b-b39e73f79b81", + "anchor": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "aa44f302-2e43-4669-a1e7-edaae414fc6e", + "typeName": "Anchors", + "typeVersion": 1, + "typeDescription": "Identifies the anchor entity for an element that is part of a large composite object such as an asset.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "CONTENT_PACK", + "homeMetadataCollectionId": "e6756296-3fa3-4aa3-9450-0dc44b8beae2", + "homeMetadataCollectionName": "UnityCatalogContentPack" + }, + "versions": { + "createdBy": "Egeria Project", + "updatedBy": "Egeria Project", + "maintainedBy": [ + "Egeria Project" + ], + "createTime": "2026-04-01T06:45:49.989+00:00", + "updateTime": "2026-04-01T06:45:49.989+00:00", + "version": 1791116345633 + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorTypeName": "IntegrationConnector", + "anchorDomainName": "Asset" + } + }, + "usageActivity": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "cfae23a1-8020-431f-a603-1f1bb0e01cb3", + "typeName": "UsageActivity", + "typeVersion": 1, + "typeDescription": "Describes the usage activity around an anchor element and its anchored elements: how often it is explicitly retrieved, found through searches, has its properties updated, and has its attachments and feedback updated or deleted.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "pepysnpa", + "updatedBy": "pepysnpa", + "maintainedBy": [ + "pepysnpa" + ], + "createTime": "2026-11-07T18:36:51.688+00:00", + "updateTime": "2026-11-10T21:44:18.246+00:00", + "version": 2, + "lastRequestId": "4219be5e-4f79-45ee-9bed-b7beedff9c3a" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "UsageActivity", + "classificationProperties": { + "class": "UsageActivityProperties", + "typeName": "UsageActivity", + "explicitGetCount": 0, + "findCount": 5, + "updatePropertyCount": 0, + "updateAttachmentCount": 0, + "updateFeedbackCount": 0, + "deleteAttachmentCount": 0, + "deleteFeedbackCount": 0 + } + } + }, + "relatedBy": { + "relationshipHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "bc5a5eb1-881b-4055-aa2c-78f314282ac2", + "typeName": "CatalogTarget", + "typeVersion": 1, + "typeDescription": "Identifies an element that an integration connector is to work with.", + "typeCategory": "RELATIONSHIP_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "ucservernpa", + "updatedBy": "ucservernpa", + "maintainedBy": [ + "ucservernpa" + ], + "createTime": "2026-11-07T18:20:24.330+00:00", + "updateTime": "2026-11-07T18:20:24.330+00:00", + "version": 1, + "lastRequestId": "e6c97de2-c734-4fe7-b224-9de8b3f57de7" + }, + "guid": "ef27dc65-cdc8-465f-9dc3-e3c2dc6b4a61" + }, + "relationshipProperties": { + "class": "CatalogTargetProperties", + "typeName": "CatalogTarget", + "catalogTargetName": "unity", + "metadataCollectionQualifiedName": "Unity Catalog Server::Coco Unity Catalog_metadataCollection", + "configurationProperties": { + "versionIdentifier": "v0.4.0", + "ucCatalogName": "unity", + "description": "Coco's instance of the Unity Catalog (UC) Server.", + "serverName": "Coco Unity Catalog", + "guid": "81fd1db1-7249-4d68-b414-a3c19ef6f23f", + "resourceName": "http://host.docker.internal:8087", + "hostURL": "http://host.docker.internal", + "serverUserId": "uc1", + "UnityCatalogFriendshipGUID": "74dde22f-2249-4ea3-af2b-b39e73f79b81", + "portNumber": "8087", + "templateGUID": "dcca9788-b30f-4007-b1ac-ec634aff6879" + }, + "templates": { + "Unity Catalog Registered Model Version": "1364bfe7-8295-4e99-9243-8840aeac4cf1", + "Unity Catalog Registered Model": "0d762ec5-c1f5-4364-aa64-e7e00d27f837", + "Unity Catalog Server": "dcca9788-b30f-4007-b1ac-ec634aff6879", + "Unity Catalog Catalog": "5ee006aa-a6d6-411b-9b8d-5f720c079cae", + "Unity Catalog Volume": "92d2d2dc-0798-41f0-9512-b10548d312b7", + "Unity Catalog Table": "6cc1e5f5-4c1e-4290-a80e-e06643ffb13d", + "Unity Catalog Function": "a490ba65-6104-4213-9be9-524e16fed8aa", + "Unity Catalog Schema": "5bf92b0f-3970-41ea-b0a3-aacfbf6fd92e", + "Databricks Unity Catalog Server": "3f7f62f6-4abc-424e-9f92-523306e7d5d5" + }, + "permittedSynchronization": "BOTH_DIRECTIONS" + } + }, + "properties": { + "class": "IntegrationConnectorProperties", + "typeName": "IntegrationConnector", + "qualifiedName": "Egeria:IntegrationGroup:UnityCatalog::UnityCatalogAssetExchange", + "displayName": "UnityCatalogAssetExchange", + "description": "Synchronizes metadata information about the contents of catalogs found in the OSS Unity Catalog 'catalog of catalogs' with the open metadata ecosystem.", + "versionIdentifier": "6.3-SNAPSHOT", + "category": "Egeria-Supplied Connectors", + "resourceName": "org.odpi.openmetadata.adapters.connectors.unitycatalog.sync.OSSUnityCatalogInsideCatalogSyncProvider", + "deployedImplementationType": "Integration Connector", + "activityStatus": "IN_PROGRESS" + } + } +} \ No newline at end of file diff --git a/tests/micro-tests/test_dashboard_report_params.py b/tests/micro-tests/test_dashboard_report_params.py new file mode 100644 index 00000000..927ed3ae --- /dev/null +++ b/tests/micro-tests/test_dashboard_report_params.py @@ -0,0 +1,67 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +"""A Report's stored params reach its spec in the spec's own names (6.2.35, the Architect's LD-2 read-back). + +A Report element keeps its params in additionalProperties, camelCase (searchString, pageSize, collectionQname, +collectionGuid ...), all strings, as Egeria stores a map of strings; its analytic params are a JSON string under +analyticParams. exec_report_spec keeps only the names the spec declares, which are snake_case, so the stored ones +were all dropped ("'collectionQname' ignored -- it takes: collection_qname") and a collection-scoped tile failed +with "Give collection_guid, collection_qname or collection_name". With snake_case keys the same specs work. +""" +import json +from types import SimpleNamespace + +import pytest + +import pyegeria.view.format_set_executor as fse +from pyegeria.view import dashboard_resolver as dr + +pytestmark = pytest.mark.unit + + +def _report_element(**additional): + return {"elementHeader": {"guid": "rep-1", "type": {"typeName": "Report"}}, + "properties": {"typeName": "Report", "qualifiedName": "DeployedReport::Assets with No Lineage", + "displayName": "Assets with No Lineage", "additionalProperties": additional}} + + +def _run(element, *, analytic: bool, monkeypatch): + sent = {} + monkeypatch.setattr(fse, "exec_report_spec", lambda name, **kw: sent.update(name=name, **kw) or {"kind": "x"}) + report = dr.report_from_element(element) + action = SimpleNamespace(analytic_function="trellis_curation_coverage" if analytic else None) + placement = dr.ResolvedPlacement(position=1, ref="Assets with No Lineage", kind="report", title="t", + report=report, spec=report.report_spec, format_set=SimpleNamespace(action=action)) + dr._run_report(SimpleNamespace(user_id="erinoverview"), placement) + return sent["params"], report + + +def test_stored_camel_case_params_reach_the_spec_in_snake_case(monkeypatch): + el = _report_element(reportSpec="Assets-No-Lineage", outputFormat="DICT", collectionQname="Collection::Catalog Health", + collectionGuid="c0ffee00-0000-0000-0000-000000000001", searchString="*", pageSize="50") + params, report = _run(el, analytic=False, monkeypatch=monkeypatch) + assert params == {"collection_qname": "Collection::Catalog Health", + "collection_guid": "c0ffee00-0000-0000-0000-000000000001", + "search_string": "*", "page_size": "50"} + assert report.params["collectionQname"] == "Collection::Catalog Health" # the stored record is unchanged + + +def test_analytic_params_are_mapped_too(monkeypatch): + el = _report_element(reportSpec="Tasks", outputFormat="DICT", + analyticParams=json.dumps({"collectionQname": "Collection::Next Steps", "top": 5})) + params, _ = _run(el, analytic=True, monkeypatch=monkeypatch) + assert params == {"collection_qname": "Collection::Next Steps", "top": 5} + + +def test_snake_case_keys_are_left_alone_and_win_over_a_converted_one(monkeypatch): + el = _report_element(reportSpec="Tasks", outputFormat="DICT", collection_qname="Collection::Explicit", + collectionQname="Collection::Converted", metric_path="trellis_x") + params, _ = _run(el, analytic=False, monkeypatch=monkeypatch) + assert params == {"collection_qname": "Collection::Explicit", "metric_path": "trellis_x"} + + +@pytest.mark.parametrize(("key", "snake"), [("collectionQname", "collection_qname"), + ("collectionGUID", "collection_guid"), ("pageSize", "page_size"), + ("asOfTime", "as_of_time"), ("top", "top"), ("search_string", "search_string")]) +def test_the_name_mapping(key, snake): + assert dr._snake(key) == snake diff --git a/tests/micro-tests/test_rs_restricted_specs.py b/tests/micro-tests/test_rs_restricted_specs.py new file mode 100644 index 00000000..f56a527b --- /dev/null +++ b/tests/micro-tests/test_rs_restricted_specs.py @@ -0,0 +1,136 @@ +"""B6: `list_visible_restricted_specs`, the zone-restricted report specs one signed-in user can see. + +The shared cache never takes a zoned spec (§9), so restricted specs are read per user, as that +user's token, and Egeria's zone check decides what comes back. The fake below enforces zones the way +Egeria does (an element in a zone the reader lacks is simply not returned, and a direct read is a +403), on the same in-memory tree and element shapes as the consumer-folder tests. No live Egeria. +""" +from __future__ import annotations + +import copy + +import pytest + +import pyegeria.view.egeria_spec_cache as esc +from test_rs_consumer_folders import ADVISOR, PORTAL, Tree, zone + +pytestmark = pytest.mark.unit + + +class ZonedEgeria(Tree): + """A Tree read as one user holding `grants`: zoned elements outside them are invisible.""" + + def __init__(self, grants=()): + super().__init__() + self.grants = set(grants) + + def _visible(self, el): + zones = esc._zones(self.by_guid.get(el["elementHeader"]["guid"], el)) + return not zones or bool(set(zones) & self.grants) + + def get_collection_members(self, collection_guid=None, output_format="JSON", **kw): + got = super().get_collection_members(collection_guid=collection_guid, output_format=output_format, **kw) + if isinstance(got, str): + return got + return [m for m in got if self._visible(m)] or "No elements found" + + def get_collection_by_guid(self, guid, output_format="JSON", **_): + e = self.by_guid.get(guid) + if e and not self._visible(e): + raise RuntimeError(f"OPEN-METADATA-SECURITY-403-020 The element {guid} is not visible to user " + f"{self.user_id}") + return copy.deepcopy(e) if e else "No elements found" + + def as_user(self, user_id, grants): + other = copy.copy(self) + other.user_id, other.grants = user_id, set(grants) + return other + + +@pytest.fixture +def advisor_tree(): + """EA's folder holds a public spec, Fin (zone finance) and, in a sub-folder, Hr (zone hr).""" + t = ZonedEgeria() + advisor = t.new_folder(ADVISOR, "EgeriaAdvisor") + sub = t.new_folder(ADVISOR + "::People", "People") + pub, fin, hr = t.new_spec("Spec-Public"), zone(t.new_spec("Spec-Fin"), "finance"), \ + zone(t.new_spec("Spec-Hr"), "hr", where="classifications") + for parent, child in ((advisor, pub), (advisor, fin), (advisor, sub), (sub, hr)): + t.link(parent, child) + return t + + +def test_a_user_with_the_zone_sees_the_spec_and_its_zones(advisor_tree): + out = esc.list_visible_restricted_specs(advisor_tree.as_user("ivorpadlock", {"finance"}), folders=[ADVISOR]) + assert out["status"] == "read" and out["identity"] == "ivorpadlock" + assert [(s["label"], s["zones"], s["folders"]) for s in out["specs"]] == [("Spec-Fin", ["finance"], [ADVISOR])] + assert out["specs"][0]["qualified_name"] == "ReportSpec::Spec-Fin" + + +def test_a_user_without_the_zone_does_not_see_it_and_is_told_why(advisor_tree): + out = esc.list_visible_restricted_specs(advisor_tree.as_user("peterprofile", set()), folders=[ADVISOR]) + assert out["specs"] == [] and out["status"] == "read" + assert "hold no zone-restricted report spec visible to peterprofile" in out["reason"] + + +def test_public_specs_are_never_listed_they_belong_to_the_shared_cache(advisor_tree): + out = esc.list_visible_restricted_specs(advisor_tree.as_user("u", {"finance", "hr"}), folders=[ADVISOR]) + assert [s["label"] for s in out["specs"]] == ["Spec-Fin", "Spec-Hr"] # the sub-folder is walked too + + +def test_zones_only_on_the_full_element_are_found(advisor_tree): + t = advisor_tree + advisor = t.get_collections_by_name(ADVISOR, metadata_element_type="CollectionFolder")[0] + z = t.new_spec("Spec-Late") + t.link(advisor, copy.deepcopy(z)) # the listing carries no zones + zone(t.by_guid[z["elementHeader"]["guid"]], "finance") # the full element does + out = esc.list_visible_restricted_specs(t.as_user("u", {"finance"}), folders=[ADVISOR]) + assert "Spec-Late" in [s["label"] for s in out["specs"]] + + +def test_a_spec_in_two_folders_is_listed_once_with_both(advisor_tree): + t = advisor_tree + portal = t.new_folder(PORTAL, "Portal") + fin = next(e for e in t.by_guid.values() if e["properties"]["qualifiedName"] == "ReportSpec::Spec-Fin") + t.link(portal, fin) + out = esc.list_visible_restricted_specs(t.as_user("u", {"finance"}), folders=[ADVISOR, PORTAL]) + assert [(s["label"], s["folders"]) for s in out["specs"]] == [("Spec-Fin", [ADVISOR, PORTAL])] + + +def test_a_missing_folder_is_stated_never_an_empty_list(advisor_tree): + out = esc.list_visible_restricted_specs(advisor_tree.as_user("u", {"finance"}), + folders=["ReportSpecFolder::Consumer::Nowhere"]) + assert out["status"] == "not read" and out["specs"] == [] + assert out["folders"][0]["result"] == "not_found" and "not visible to u" in out["folders"][0]["detail"] + assert "no folder could be read" in out["reason"] + + +def test_one_unreadable_folder_makes_the_result_partial(advisor_tree): + t = advisor_tree + broken = t.new_folder(PORTAL, "Portal") + t.failing.add(broken["elementHeader"]["guid"]) + out = esc.list_visible_restricted_specs(t.as_user("u", {"finance"}), folders=[ADVISOR, PORTAL]) + assert out["status"] == "partial" and [s["label"] for s in out["specs"]] == ["Spec-Fin"] + assert {r["folder"]: r["result"] for r in out["folders"]} == {ADVISOR: "ok", PORTAL: "unreadable"} + + +def test_no_folders_configured_says_so(advisor_tree, monkeypatch): + monkeypatch.setenv(esc.FOLDERS_ENV, "") + out = esc.list_visible_restricted_specs(advisor_tree) + assert out["status"] == "not read" and "no report spec folders are configured" in out["reason"] + + +def test_a_draft_restricted_spec_is_not_listed_and_says_so(): + t = ZonedEgeria({"finance"}) + advisor = t.new_folder(ADVISOR) + d = zone(t.new_spec("Spec-Draft"), "finance") + d["properties"]["contentStatus"] = "DRAFT" + t.link(advisor, d) + out = esc.list_visible_restricted_specs(t, folders=[ADVISOR]) + assert out["specs"] == [] and any("Spec-Draft: contentStatus DRAFT" in n for n in out["notes"]) + + +def test_nothing_is_written_to_any_cache(advisor_tree, tmp_path, monkeypatch): + monkeypatch.setenv(esc.CACHE_DIR_ENV, str(tmp_path / "cache")) + esc.list_visible_restricted_specs(advisor_tree.as_user("u", {"finance"}), folders=[ADVISOR]) + assert not (tmp_path / "cache").exists() diff --git a/tests/micro-tests/test_saved_query_analytic.py b/tests/micro-tests/test_saved_query_analytic.py index ffcd9087..78e32eb6 100644 --- a/tests/micro-tests/test_saved_query_analytic.py +++ b/tests/micro-tests/test_saved_query_analytic.py @@ -14,6 +14,7 @@ """ import json import os +import sys import pytest @@ -62,16 +63,63 @@ def _member(i): "properties": {"qualifiedName": f"Asset::{i}", "displayName": f"Asset {i}"}} +# Egeria's record of a Smart Collection (6.2.35): the SavedQuery -> SmartQuery -> a Results Set that is a +# CatalogTarget of the Smart Collections integration connector, under its target name "resultsSetToMaintain". +# The connector end is the CatalogTarget related element captured from a quickstart platform (see the fixture's +# _about), with only the connector's names and the catalogTargetName changed. +with open(os.path.join(os.path.dirname(__file__), "data", "catalog_target_related_2026_11_11.json")) as _f: + CAPTURED = json.load(_f) +SMART_RS = "5e7a0000-0000-0000-0000-00000000c0de" + + +def _smart_shapes(target_name="resultsSetToMaintain", connector_type="IntegrationConnector"): + connector = json.loads(json.dumps(CAPTURED["catalogTargetFromTarget"])) + connector["elementHeader"]["type"]["typeName"] = connector_type + connector["properties"]["qualifiedName"] = "Egeria:IntegrationGroup:SmartCollections::SmartCollectionsIntegrationConnector" + connector["properties"]["displayName"] = "Smart Collections Integration Connector" + rel = connector["relatedBy"]["relationshipProperties"] + for k in ("templates", "metadataCollectionQualifiedName"): + rel.pop(k, None) + rel["catalogTargetName"] = target_name + results_set = {"elementHeader": {"guid": SMART_RS, "type": {"typeName": "ResultsSet", + "superTypeNames": ["Collection", "Referenceable"]}}, + "relatedBy": {"relationshipHeader": {"guid": "sq-rel", "type": {"typeName": "SmartQuery"}}, + "relationshipProperties": {"class": "SmartQueryProperties", "typeName": "SmartQuery"}}, + "properties": {"qualifiedName": "ResultsSet::insights-query::a1b2"}} + return results_set, connector + + 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): + def __init__(self, stored=None, answer=0, members=0, lookup_error=None, run_error=None, smart=False, + completion=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.smart = smart # True: Egeria records this SavedQuery as a Smart Collection (see _smart_shapes) + self.completion = completion # the Results Set's completionTime, stamped by Egeria on each refresh self.calls = [] + def get_collection_by_guid(self, guid, output_format="JSON", **kw): + self.calls.append(("results_set", guid)) + props = {"class": "ResultsSetProperties", "typeName": "ResultsSet", "qualifiedName": f"ResultsSet::{guid}"} + if self.completion is not None: + props["completionTime"] = self.completion + return {"elementHeader": {"guid": guid, "type": {"typeName": "ResultsSet"}}, "properties": props} + + def get_related_elements(self, guid, relationship_type=None, start_at_end=1, **kw): + self.calls.append(("related", guid, relationship_type, start_at_end)) + if not self.smart: + return "No elements found" + results_set, connector = _smart_shapes() + if relationship_type == "SmartQuery" and start_at_end == 2: + return [results_set] + if relationship_type == "CatalogTarget" and start_at_end == 2 and guid == SMART_RS: + return [connector] + return "No elements found" + def find_metadata_elements(self, body=None, **kw): self.calls.append(("find", json.loads(json.dumps(body)))) if body.get("metadataElementTypeName") == "SavedQuery": @@ -98,8 +146,9 @@ def test_cached_count_is_the_results_set_as_of_its_refresh(): 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" + reads = [c for c in viewer.calls if c[0] != "related"] # relationship reads: is it a Smart Collection? (no) + assert [c[0] for c in reads] == ["find", "members", "members"] # paged to the empty page + assert reads[1][1] == "rs-guid" def test_cached_list_names_each_member(): @@ -114,7 +163,7 @@ def test_never_refreshed_is_not_an_empty_answer(): 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"] + assert [c[0] for c in viewer.calls if c[0] != "related"] == ["find"] def test_an_empty_refreshed_answer_is_nothing_found(): @@ -264,7 +313,7 @@ def test_every_other_url_is_refused_with_a_sentence_and_reaches_nothing(url, wor 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 + assert [c[0] for c in viewer.calls if c[0] != "related"] == ["find"] # the lookup only: the stored request never ran @pytest.mark.parametrize("body,words", [ @@ -277,7 +326,7 @@ 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"] + assert [c[0] for c in viewer.calls if c[0] != "related"] == ["find"] def test_the_allow_list_is_the_one_find_endpoint(): @@ -409,7 +458,7 @@ def test_each_contract_case_is_served_cached_only_when_it_is_what_was_recorded(c else: assert out["value"] is None and out["state"] == "not_established" assert "use mode live" in out["state_reason"] and "the cached answer is for " in out["state_reason"] - assert [c[0] for c in viewer.calls] == ["find"] # the members were never read + assert [c[0] for c in viewer.calls if c[0] != "related"] == ["find"] # the members were never read def test_a_cached_answer_for_other_values_is_never_returned(): @@ -417,7 +466,7 @@ def test_a_cached_answer_for_other_values_is_never_returned(): viewer = _Viewer(stored=[_unregistered()], members=7) out = saved_query(viewer, FQN, params=other) assert out["value"] is None and f"min_level={RECORDED['min_level'] + 1}" in out["state_reason"] - assert [c[0] for c in viewer.calls] == ["find"] + assert [c[0] for c in viewer.calls if c[0] != "related"] == ["find"] def test_an_unregistered_refresh_with_other_values_is_served_for_those_values(): @@ -449,12 +498,15 @@ def test_search_spec_is_read_when_formula_is_empty_as_the_portal_does(): STORED = FIXTURE["cases"][0]["effective"] # the effective values with no request -def test_the_fixture_is_a_registered_smart_collection(): +def test_the_portals_flag_alone_does_not_register_it(): + # 6.2.35: registered is what Egeria records (SmartQuery -> Results Set -> CatalogTarget), not the Portal's flag. assert SQ["properties"]["additionalProperties"]["smartCollection"] == "true" + out = saved_query(_Viewer(stored=[_shared()], members=7), FQN) + assert "keptCurrentBy" not in out def test_a_registered_answer_is_served_for_its_stored_values_and_labelled_kept_current(): - out = saved_query(_Viewer(stored=[_shared()], members=7), FQN) + out = saved_query(_Viewer(stored=[_shared()], members=7, smart=True), FQN) assert out["value"] == 7 and out["params"] == STORED assert out["keptCurrentBy"].startswith("Egeria (Smart Collection") label = ", ".join(f"{k}={json.dumps(v)}" for k, v in sorted(STORED.items())) @@ -463,33 +515,49 @@ def test_a_registered_answer_is_served_for_its_stored_values_and_labelled_kept_c @pytest.mark.parametrize("case", FIXTURE["cases"], ids=[c["why"][:40] for c in FIXTURE["cases"]]) def test_a_registered_answer_is_served_only_for_the_stored_values(case): - viewer = _Viewer(stored=[_shared()], members=7) + viewer = _Viewer(stored=[_shared()], members=7, smart=True) out = saved_query(viewer, FQN, params=case["request"]) if case["effective"] == STORED: assert out["value"] == 7 else: assert out["value"] is None and "is a Smart Collection, kept current by Egeria" in out["state_reason"] assert "use mode live" in out["state_reason"] - assert [c[0] for c in viewer.calls] == ["find"] + assert [c[0] for c in viewer.calls if c[0] != "related"] == ["find"] def test_a_registered_answer_ignores_a_refresh_record_naming_other_values(): # a Portal refresh with min_level 4 would be overwritten by Egeria within the half hour q = _shared(lastRefreshParams={**STORED, "min_level": 4}) - assert saved_query(_Viewer(stored=[q], members=7), FQN)["value"] == 7 - out = saved_query(_Viewer(stored=[q], members=7), FQN, params={"min_level": 4}) + assert saved_query(_Viewer(stored=[q], members=7, smart=True), FQN)["value"] == 7 + out = saved_query(_Viewer(stored=[q], members=7, smart=True), FQN, params={"min_level": 4}) assert out["value"] is None and "kept current by Egeria" in out["state_reason"] -def test_a_registered_answer_needs_no_portal_refresh_time(): - out = saved_query(_Viewer(stored=[_shared(lastRefreshedTime="", lastRefreshParams=None)], members=3), FQN) - assert out["value"] == 3 and out["asOf"] is None - assert out["subtitle"].startswith("kept current by Egeria \u00b7 no refresh time recorded, for ") +def test_a_registered_answer_is_as_of_egerias_refresh_when_the_portal_recorded_none(): + q = _shared(lastRefreshedTime="", lastRefreshParams=None) + out = saved_query(_Viewer(stored=[q], members=3, smart=True, completion="2026-11-11T09:30:00.000+00:00"), FQN) + assert out["value"] == 3 and out["asOf"] == "2026-11-11T09:30:00.000+00:00" + assert out["subtitle"].startswith("kept current by Egeria \u00b7 as of 2026-11-11T09:30:00.000+00:00, for ") + + +def test_a_registered_query_egeria_has_not_refreshed_yet_is_not_an_empty_answer(): + # The LD-2 read-back: the Results Set exists but no refresh has run, so it is empty; that is "not refreshed + # yet", never 0, and its (empty) members are not read as an answer. + viewer = _Viewer(stored=[_shared(lastRefreshedTime="", lastRefreshParams=None)], members=0, smart=True) + out = saved_query(viewer, FQN) + assert out["value"] is None and out["state"] == "not_established" + assert "not refreshed yet" in out["state_reason"] and "not an empty answer" in out["state_reason"] + assert not [c for c in viewer.calls if c[0] == "members"] + + +def test_egerias_refresh_time_wins_for_a_registered_query(): + out = saved_query(_Viewer(stored=[_shared()], members=7, smart=True, completion=1762853400000), FQN) + assert out["asOf"] == "2025-11-11T09:30:00+00:00" # epoch ms from Egeria, not the Portal's 2026-11-10 time def test_a_registered_query_with_no_parameters_is_served_and_labelled(): q = _shared(parameters=None, lastRefreshParams=None) - out = saved_query(_Viewer(stored=[q], members=4), FQN) + out = saved_query(_Viewer(stored=[q], members=4, smart=True), FQN) assert out["value"] == 4 and "params" not in out assert out["subtitle"] == "kept current by Egeria \u00b7 as of 2026-11-10T18:00:00+00:00" @@ -506,7 +574,7 @@ def test_live_is_refused_while_a_portal_only_parameter_is_declared(): viewer = _Viewer(stored=[_shared()], answer=3) out = saved_query(viewer, FQN, mode="live", params={"min_level": 4}) assert out["refused"] is True and "'sort' applies to the Portal's search only" in out["state_reason"] - assert [c[0] for c in viewer.calls] == ["find"] + assert [c[0] for c in viewer.calls if c[0] != "related"] == ["find"] def test_live_refuses_a_portal_only_parameter_that_is_given(): @@ -581,7 +649,7 @@ def test_injection_and_type_mismatch_are_refused_and_nothing_runs(given, words): viewer = _Viewer(stored=[_shared(drop=("sort",))], answer=3) out = saved_query(viewer, FQN, mode="live", params=given) assert out["refused"] is True and out["value"] is None and words in out["state_reason"] - assert [c[0] for c in viewer.calls] == ["find"] + assert [c[0] for c in viewer.calls if c[0] != "related"] == ["find"] def test_params_on_a_query_that_declares_none_are_refused(): @@ -604,3 +672,42 @@ def test_params_on_a_query_that_declares_none_are_refused(): def test_a_bad_declaration_is_refused(params, words): out = saved_query(_Viewer(stored=[_shared(parameters=params)], answer=1), FQN, mode="live") assert out["refused"] is True and words in out["state_reason"] + + +# ── Smart Collection: detected by Egeria's record, the catalog target (6.2.35) ── + +def test_registration_reads_the_results_set_egeria_records_not_the_flags_guid(): + viewer = _Viewer(stored=[_shared(resultsSetGuid="the-flags-results-set")], members=3, smart=True) + out = saved_query(viewer, FQN) + assert out["keptCurrentBy"].startswith("Egeria (Smart Collection") + assert {c[1] for c in viewer.calls if c[0] == "members"} == {SMART_RS} # paged, all from Egeria's Results Set + assert [c[2:] for c in viewer.calls if c[0] == "related"] == [("SmartQuery", 2), ("CatalogTarget", 2)] + + +def test_a_catalog_target_of_another_connector_is_not_a_smart_collection(monkeypatch): + # the captured connector, as captured: a catalog target named "unity" + monkeypatch.setattr(sys.modules[__name__], "_smart_shapes", + lambda: (_smart_shapes()[0], json.loads(json.dumps(CAPTURED["catalogTargetFromTarget"])))) + out = saved_query(_Viewer(stored=[_unregistered()], members=7, smart=True), FQN, params=REFRESHED_WITH) + assert "keptCurrentBy" not in out and out["value"] == 7 + + +def test_the_target_must_be_held_by_an_integration_connector(monkeypatch): + monkeypatch.setattr(sys.modules[__name__], "_smart_shapes", lambda: _smart_shapes(connector_type="Process")) + out = saved_query(_Viewer(stored=[_shared()], members=7, smart=True), FQN) + assert "keptCurrentBy" not in out + + +def test_a_lookup_that_fails_is_not_a_registration(): + class Failing(_Viewer): + def get_related_elements(self, *a, **kw): + raise RuntimeError("HTTP 500 from the view server") + out = saved_query(Failing(stored=[_unregistered()], members=7), FQN, params=REFRESHED_WITH) + assert "keptCurrentBy" not in out and out["value"] == 7 # the ordinary cached path, for its recorded values + assert "could not be read (RuntimeError)" in out["note"] and "answered as one that is not" in out["note"] + + +def test_live_mode_never_looks_up_registration(): + viewer = _Viewer(stored=[_shared(drop=("sort",))], answer=2, smart=True) + saved_query(viewer, FQN, mode="live", params={"min_level": 5}) + assert not [c for c in viewer.calls if c[0] == "related"] diff --git a/tests/micro-tests/test_saved_query_delete.py b/tests/micro-tests/test_saved_query_delete.py new file mode 100644 index 00000000..2b82e0f3 --- /dev/null +++ b/tests/micro-tests/test_saved_query_delete.py @@ -0,0 +1,119 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +"""delete_saved_query (6.2.35): deleting a SavedQuery detaches its SmartQuery links first, so no Results Set is left +linked to a query that no longer exists, and a link Egeria would not let go of stops the delete with the reason. + +The related elements below have the shape Egeria returns from get_related_elements (checked live on 2026-11-09, +tests/micro-tests/dashboard_fake_egeria.py): {elementHeader, relatedBy: {relationshipHeader, +relationshipProperties}, properties}, with the Results Set at end 1 of SmartQuery and the SavedQuery at end 2. +""" +import pytest + +from pyegeria.view.saved_query import delete_saved_query + +pytestmark = pytest.mark.unit + +SQ = "5a7e0000-0000-0000-0000-0000000000a1" + + +def _results_set(guid): + return {"class": "OpenMetadataRootElement", + "elementHeader": {"class": "ElementHeader", "guid": guid, + "type": {"typeName": "ResultsSet", "superTypeNames": ["Collection", "Referenceable"]}}, + "relatedBy": {"relationshipHeader": {"guid": f"rel-{guid}", "type": {"typeName": "SmartQuery"}}, + "relationshipProperties": {"class": "SmartQueryProperties", "typeName": "SmartQuery"}}, + "properties": {"typeName": "ResultsSet", "qualifiedName": f"ResultsSet::{guid}"}} + + +class _Client: + """Records every call; a SmartQuery read pages through `linked`; the element read is a `kind`.""" + + def __init__(self, linked=(), detach_error=None, kind="SavedQuery", read_error=None): + self.linked, self.detach_error, self.calls = list(linked), detach_error, [] + self.kind, self.read_error = kind, read_error + + def get_asset_by_guid(self, guid, graph_query_depth=3, output_format="JSON", **kw): + self.calls.append(("read", guid)) + if self.read_error: + raise self.read_error + if self.kind is None: + return "No elements found" + return {"elementHeader": {"guid": guid, "type": {"typeName": self.kind, "superTypeNames": ["Asset"]}}, + "properties": {"qualifiedName": f"{self.kind}::{guid}"}} + + def get_related_elements(self, guid, relationship_type=None, start_at_end=1, start_from=0, page_size=0, **kw): + self.calls.append(("related", guid, relationship_type, start_at_end, start_from)) + page = self.linked[start_from:start_from + page_size] + return [_results_set(g) for g in page] or "No elements found" + + def detach_smart_query(self, results_set_guid, saved_query_guid, body=None): + self.calls.append(("detach", results_set_guid, saved_query_guid)) + if self.detach_error: + raise self.detach_error + + def delete_asset(self, guid, body=None): + self.calls.append(("delete", guid)) + + +def test_every_smart_query_link_is_detached_before_the_saved_query_is_deleted(): + client = _Client(linked=["rs-1", "rs-2"]) + out = delete_saved_query(client, SQ) + assert client.calls == [("read", SQ), + ("related", SQ, "SmartQuery", 2, 0), ("related", SQ, "SmartQuery", 2, 50), + ("detach", "rs-1", SQ), ("detach", "rs-2", SQ), + ("delete", SQ)] + assert out == {"deleted": SQ, "detached": ["rs-1", "rs-2"], "results_sets_kept": ["rs-1", "rs-2"]} + + +def test_a_saved_query_with_no_results_set_is_just_deleted(): + client = _Client() + out = delete_saved_query(client, SQ) + assert [c[0] for c in client.calls] == ["read", "related", "delete"] and out["detached"] == [] + + +def test_a_link_egeria_will_not_detach_stops_the_delete_and_says_why(): + client = _Client(linked=["rs-1"], detach_error=RuntimeError("OMAG-GENERIC-HANDLERS-403-005")) + with pytest.raises(RuntimeError, match=r"Results Set rs-1 could not be detached .*403-005.*not deleted"): + delete_saved_query(client, SQ) + assert ("delete", SQ) not in client.calls + + +def test_a_guid_is_required(): + with pytest.raises(ValueError): + delete_saved_query(_Client(), "") + + +# the Architect's 6.2.35 read-back: only a SavedQuery is deleted, and every link is read + +@pytest.mark.parametrize("kind", ["UserIdentity", "Report", "Collection"]) +def test_a_guid_that_is_not_a_saved_query_is_refused_and_nothing_is_deleted(kind): + client = _Client(linked=["rs-1"], kind=kind) + with pytest.raises(RuntimeError, match=rf"is a {kind}, not a SavedQuery; nothing was deleted"): + delete_saved_query(client, SQ) + assert [c[0] for c in client.calls] == ["read"] + + +def test_a_guid_that_finds_nothing_or_cannot_be_read_is_refused(): + with pytest.raises(RuntimeError, match="is not found, not a SavedQuery"): + delete_saved_query(_Client(kind=None), SQ) + client = _Client(read_error=RuntimeError("HTTP 500")) + with pytest.raises(RuntimeError, match="could not be read .*HTTP 500.*not deleted"): + delete_saved_query(client, SQ) + assert [c[0] for c in client.calls] == ["read"] + + +def test_links_are_read_until_an_empty_page_not_a_short_one(): + rs = [f"rs-{i}" for i in range(120)] # a full page, a full page, a short page, then the empty one + client = _Client(linked=rs) + out = delete_saved_query(client, SQ) + assert [c[4] for c in client.calls if c[0] == "related"] == [0, 50, 100, 150] + assert out["detached"] == rs and client.calls[-1] == ("delete", SQ) + + +def test_more_links_than_the_bound_is_refused_with_nothing_detached(monkeypatch): + from pyegeria.view import saved_query as sq + monkeypatch.setattr(sq, "DELETE_LINK_MAX_PAGES", 2) + client = _Client(linked=[f"rs-{i}" for i in range(100)]) + with pytest.raises(RuntimeError, match="more than 100 SmartQuery links; refused"): + delete_saved_query(client, SQ) + assert not [c for c in client.calls if c[0] in ("detach", "delete")] diff --git a/uv.lock b/uv.lock index 080e5322..66d6bc28 100644 --- a/uv.lock +++ b/uv.lock @@ -2238,7 +2238,7 @@ sdist = { url = "https://files.pythonhosted.org/packages/f8/f6/8f49005d581cff883 [[package]] name = "pyegeria" -version = "6.2.34" +version = "6.2.35" source = { editable = "." } dependencies = [ { name = "altair" },