From d5b99a446e55d5ba0298de9c8d0774553691bbdd Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 09:55:53 +0000 Subject: [PATCH 1/6] fix(view): an Egeria-held spec's analytic_binders warns as a local one does (O1-a) Architect read-back P2 of RS-EGERIA-TIER stage 1 (#563) against RS-W2-4 PR-0 (#561): a stage's analytic_binders key on a spec held in Egeria was recorded only as a generic "ignored" note, so #561's BINDERS_DEPRECATED_PREFIX warning never fired for the very case owner decision O1-a was for. - microflow_to_format_set now passes a stage's analytic_binders into the action. The PR-B ActionParameter shim drops it there, raises its DeprecationWarning and records the names, and the spec resolver warns with BINDERS_DEPRECATED_PREFIX, the same text as for a local spec. An empty binder stays silent; other unknown stage keys are still notes. Works for format 0 and microflow/1, and on every tier load, since the tier rebuilds from the cached micro-flow text, which keeps the key. - PR-0 P3: the shim's docstring now says the marker survives model_copy but not model_dump and a reload. - Tests: a synced Egeria-held spec (format 0 and microflow/1) with a non-empty binder resolves with exactly the #561 warning; empty, None, [] and absent stay silent. Signed-off-by: Dan Wolfson --- pyegeria/view/_output_format_models.py | 6 ++ pyegeria/view/microflow.py | 17 +++++- tests/micro-tests/test_rs_egeria_tier.py | 70 +++++++++++++++++++++++- 3 files changed, 89 insertions(+), 4 deletions(-) diff --git a/pyegeria/view/_output_format_models.py b/pyegeria/view/_output_format_models.py index 8c44dacf..0793b8ad 100644 --- a/pyegeria/view/_output_format_models.py +++ b/pyegeria/view/_output_format_models.py @@ -273,6 +273,12 @@ def _drop_deprecated_binders(cls, values, handler): one is dropped with a DeprecationWarning and a log warning naming the parameters: the routine must declare them as `inputs` instead, or its call will lack them. The names are kept on the model (`_dropped_binders`) so the spec resolver can report them as a warning. + + The marker is a private attribute: it survives `model_copy`, but NOT `model_dump` and a + reload (`model_validate_json(fs.model_dump_json())` has no marker and so no warning), since + the dump no longer holds the key. Resolve the loaded spec, not a serialised copy of it. The + EGERIA tier rebuilds its specs from the cached micro-flow text, which keeps the key, so + its marker is set afresh on every load. """ names: List[str] = [] if isinstance(values, dict) and "analytic_binders" in values: diff --git a/pyegeria/view/microflow.py b/pyegeria/view/microflow.py index bc868704..bb9f4a25 100644 --- a/pyegeria/view/microflow.py +++ b/pyegeria/view/microflow.py @@ -436,8 +436,20 @@ def microflow_to_format_set(mf: MicroflowV1, *, label: str, heading: Optional[st notes = notes if notes is not None else [] stages = list(mf.stages) kinds = [s.stage for s in stages] + binders: Dict[str, Any] = {} for i, s in enumerate(stages): - unknown = sorted((s.model_extra or {}).keys()) + extra = dict(s.model_extra or {}) + # A stage's `analytic_binders` (removed in RS-W2-3 PR-B) is passed on to the action, so the + # ActionParameter shim drops it there and records the names, and the spec resolver warns + # with BINDERS_DEPRECATED_PREFIX (owner decision O1-a): exactly as for a local spec. An + # empty one is dropped silently, as the shim does. + stage_binders = extra.pop("analytic_binders", None) + if stage_binders: + if isinstance(stage_binders, dict): + binders.update(stage_binders) + else: + binders[repr(stage_binders)] = stage_binders + unknown = sorted(extra.keys()) if unknown: notes.append(f"stage {i} ({s.stage}) carries key(s) this pyegeria does not read: " f"{', '.join(unknown)}; ignored") @@ -479,6 +491,9 @@ def microflow_to_format_set(mf: MicroflowV1, *, label: str, heading: Optional[st if not finds: action.update(required_params=required, optional_params=optional) + if binders and action: + action["analytic_binders"] = binders + formats = [] for out_type, f in mf.formatters.items(): if f.columns == "*": diff --git a/tests/micro-tests/test_rs_egeria_tier.py b/tests/micro-tests/test_rs_egeria_tier.py index 381d3abb..87721765 100644 --- a/tests/micro-tests/test_rs_egeria_tier.py +++ b/tests/micro-tests/test_rs_egeria_tier.py @@ -392,14 +392,78 @@ def test_no_allowlisted_method_reads_as_a_write(): assert not stale, f"reviewed entries no longer hit (remove them): {sorted(stale)}" -def test_unknown_stage_keys_are_recorded_as_notes(): +def test_unknown_stage_keys_are_recorded_as_notes_and_binders_go_to_the_action(): + import warnings mf, _, _ = mfm.parse_microflow({"format": "microflow/1", "stages": [ {"stage": "producer/find", "function": "CollectionManager.find_collections", "analytic_binders": {"x": 1}, "colour": "blue"}], "formatters": {"DICT": {"columns": ["display_name"]}}}) notes = [] - mfm.microflow_to_format_set(mf, label="T", notes=notes) - assert any("stage 0 (producer/find)" in n and "analytic_binders, colour" in n for n in notes), notes + with warnings.catch_warnings(record=True): + warnings.simplefilter("always") + fs = mfm.microflow_to_format_set(mf, label="T", notes=notes) + assert any("stage 0 (producer/find)" in n and n.endswith("colour; ignored") for n in notes), notes + assert not any("analytic_binders" in n for n in notes), notes + assert fs.action._dropped_binders == ["x"] + assert "analytic_binders" not in fs.model_dump()["action"] + + +# ── 2b. A binder on an Egeria-held spec warns exactly as #561 does for a local one (O1-a) ── + +def _binder_text(names): + from pyegeria.view import spec_resolver as sr + return (f"{sr.BINDERS_DEPRECATED_PREFIX} (binders for: {names}); declare these arguments as the routine's " + f"inputs, which the environment's role supply provides") + + +def _binder_microflow(fmt, binders): + stage = {"stage": "producer/find", "type": "Collection", "function": "CollectionManager.find_collections", + "params": {"search_string": "$search_string"}} + if binders is not _ABSENT: + stage["analytic_binders"] = binders + if fmt == 0: + return json.dumps([dict(stage, required_params=["search_string"], columns=["display_name"])]) + return json.dumps({"format": "microflow/1", "params": {"search_string": {"type": "string", "required": True}}, + "stages": [stage], "formatters": {"ALL": {"columns": ["display_name"]}}}) + + +_ABSENT = object() +_BINDER_GUID = "b1d0e400-0000-0000-0000-000000000002" + + +def _sync_and_resolve(fmt, binders): + import warnings + from pyegeria.view import spec_resolver as sr + eg = FakeEgeria() + eg.put(spec_element("E-Binder", guid=_BINDER_GUID, microflow=_binder_microflow(fmt, binders), aliases=[])) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + report = esc.sync_report_specs(eg, folders=[FOLDER_QN]) + assert report.added == ["E-Binder"] and not report.skipped, report.render() + esc._invalidate_tier() + assert brf.report_spec_source("E-Binder")["tier"] == "egeria" + result = sr.resolve_all()["E-Binder"] + found = [w for w in result.warnings if w.startswith(sr.BINDERS_DEPRECATED_PREFIX)] + deprecations = [w for w in caught if issubclass(w.category, DeprecationWarning) + and "analytic_binders" in str(w.message)] + brf.unregister_report_spec("E-Binder") + return found, deprecations, report + + +@pytest.mark.parametrize("fmt", [0, 1]) +def test_egeria_held_spec_with_a_binder_resolves_with_exactly_the_561_warning(tier, fmt): + found, deprecations, report = _sync_and_resolve(fmt, {"ods": "x.OdsReader", "mgr": "os.getcwd"}) + assert found == [_binder_text("mgr, ods")] + assert deprecations # the PR-B shim's DeprecationWarning fired on the Egeria-held spec too + assert not any("analytic_binders" in n and "ignored" in n and "does not read" in n for n in report.notes) + + +@pytest.mark.parametrize("fmt", [0, 1]) +@pytest.mark.parametrize("empty", [{}, None, [], _ABSENT]) +def test_egeria_held_spec_with_an_empty_binder_stays_silent(tier, fmt, empty): + found, deprecations, report = _sync_and_resolve(fmt, empty) + assert found == [] and deprecations == [] + assert not any("analytic_binders" in n for n in report.notes) # ── 3. The sync ── From d39a0decb14a7caa35f56ff9924d8f40176cc429 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 10:16:18 +0000 Subject: [PATCH 2/6] feat(view): a positive find-method allowlist for specs held in Egeria The Architect's stage-2 allowlist items (read-back of RS-EGERIA-TIER stage 1, P2 and note (a) on 224f189c), pulled forward so pyegeria 6.2.28, the first release with the EGERIA tier, ships them. - The find_/get_/list_ prefix rule is gone. FIND_METHOD_ALLOWLIST is a positive list of Class.method entries (an _async_ twin is allowed too). It is _CENSUS_FIND_METHODS, the 45 find methods today's runnable built-in specs name (taken from the 437-spec census; the two unrunnable specs' missing methods are left out), plus FIND_METHOD_ADDITIONS, the reviewed additions, which is empty for now. A method not on it is refused with words, whatever its prefix. - FIND_METHOD_DENYLIST is kept as a second, independent check: it is tested first, it denies on any class, and a test fails if the two lists overlap. - The write-word scan now runs over the allowlist itself, on the name and on the first docstring line of both the sync method and its _async_ twin. The reviewed reads are keyed by Class.method: DataDiscovery.get_security_posture_history and ServerClient.get_attached_comments. - New test: every runnable built-in or generated spec's function is on the list, so the stage-2 seed cannot be refused. Plus tests that every entry resolves, that an _async_ twin is allowed, and that same-method different-class spellings are refused. - microflow-1.json and the module docstring describe the allowlist. Signed-off-by: Dan Wolfson --- pyegeria/view/microflow.py | 101 ++++++++++++++++---- pyegeria/view/schemas/microflow-1.json | 2 +- tests/micro-tests/test_rs_egeria_tier.py | 115 +++++++++++++---------- 3 files changed, 152 insertions(+), 66 deletions(-) diff --git a/pyegeria/view/microflow.py b/pyegeria/view/microflow.py index bb9f4a25..c2a1db08 100644 --- a/pyegeria/view/microflow.py +++ b/pyegeria/view/microflow.py @@ -21,9 +21,9 @@ `producer/analytic` stage) and raises `CannotRunYet` with words for anything else. Every Egeria-held spec is untrusted input. `check_allowlist` enforces §7a "Safety": a find stage -may name only `Class.method` on an EgeriaTech client class, read-only by name (`find_`, `get_`, -`list_`); an analytic stage only a registered analytic name; never a dotted module path or a -`python` binding. +may name only a `Class.method` on `FIND_METHOD_ALLOWLIST` (a positive list: the methods today's +built-in specs name, plus reviewed additions) and never one on `FIND_METHOD_DENYLIST`; an analytic +stage only a registered analytic name; never a dotted module path or a `python` binding. """ from __future__ import annotations @@ -36,6 +36,8 @@ __all__ = [ "MICROFLOW_FORMAT", + "FIND_METHOD_ALLOWLIST", + "FIND_METHOD_ADDITIONS", "FIND_METHOD_DENYLIST", "LEGACY_CLASS_ALIASES", "ParamDecl", @@ -56,12 +58,79 @@ MICROFLOW_FORMAT = "microflow/1" -#: Find methods an Egeria-held spec may never name even though they pass the name rules (§7a -#: "Safety"). A name prefix is not proof a method is read-only: each entry here starts with get_, -#: find_ or list_ but writes to Egeria. An entry denies the method on every class that has it (and its -#: `_async_` twin), since EgeriaTech and its subclasses inherit it. The micro-test -#: `test_no_allowlisted_method_reads_as_a_write` scans every method that passes the rules for write -#: words and fails on any hit that is neither here nor in its reviewed list. +#: The find methods a spec held in Egeria may name, as `Class.method` exactly as the spec writes it +#: (an `_async_` twin of an entry is allowed too). A POSITIVE list: a method that is not on it is +#: refused, whatever its name (a find_/get_/list_ prefix is not proof that a method only reads; see +#: FIND_METHOD_DENYLIST). It is the union of two named parts: +#: +#: - `_CENSUS_FIND_METHODS`: every find method a runnable built-in or generated spec names, taken from +#: the 437-spec census on 2026-11-09 (45 methods; the two unrunnable specs' methods, which do not +#: exist, are left out). The micro-test `test_every_runnable_builtin_spec_function_is_on_the_allowlist` +#: fails when a built-in or generated spec names one that is missing, so the stage-2 seed (today's +#: built-ins written into Egeria) can never be refused. +#: - `FIND_METHOD_ADDITIONS`: methods no built-in names yet, each added after reading it. +#: +#: Every entry is scanned for write words in its name and docstring by +#: `test_no_allowlisted_method_reads_as_a_write`; a hit must be reviewed there, by Class.method. +_CENSUS_FIND_METHODS: frozenset = frozenset({ + "ActorManager.find_actor_profiles", + "ActorManager.find_actor_roles", + "ActorManager.find_perspectives", + "ActorManager.find_skills", + "ActorManager.find_user_identities", + "AssetMaker.find_assets", + "ClassificationExplorer.get_elements", + "ClassificationExplorer.get_owners_elements", + "CollectionManager.find_collections", + "CollectionManager.get_collection_members", + "DataDesigner.find_data_fields", + "DataDesigner.find_data_structures", + "DataDesigner.find_data_value_specifications", + "DataDiscovery.get_security_findings", + "DataDiscovery.get_security_posture_history", + "EgeriaTech.get_elements_by_property_value", + "EgeriaTech.get_technology_type_elements", + "ExternalReference.find_external_identifiers", + "ExternalReference.find_external_references", + "ExternalReferences.find_external_references", + "GlossaryManager.find_glossaries", + "GlossaryManager.find_glossary_terms", + "GovernanceOfficer.find_governance_definitions", + "MetadataExpert.find_metadata_elements_with_string", + "MyProfile.get_my_profile", + "MyProfile.get_my_to_dos", + "ProjectManager.find_projects", + "ReferenceDataManager.find_valid_value_definitions", + "SecurityOfficer.find_statements_of_applicability", + "SecurityOfficer.get_statement_of_applicability_controls", + "ServerClient.find_comments", + "ServerClient.find_notes", + "ServerClient.find_tags", + "ServerClient.find_technology_types", + "ServerClient.get_attached_comments", + "ServerClient.get_tech_type_detail", + "SolutionArchitect.find_concept_model_elements", + "SolutionArchitect.find_design_patterns", + "SolutionArchitect.find_information_supply_chains", + "SolutionArchitect.find_solution_blueprints", + "SolutionArchitect.find_solution_components", + "SolutionArchitect.find_solution_roles", + "ValidMetadataManager.get_valid_metadata_values", + "_client_new.find_search_keywords", + "reference_data.find_valid_value_definitions", +}) + +#: Reviewed additions: find methods no built-in spec names yet. Empty in 6.2.28; add an entry only +#: after reading the method (it must only read), and give the reason in a comment beside it. +FIND_METHOD_ADDITIONS: frozenset = frozenset() + +FIND_METHOD_ALLOWLIST: frozenset = _CENSUS_FIND_METHODS | FIND_METHOD_ADDITIONS + +#: Find methods an Egeria-held spec may never name. Kept beside the positive allowlist as a second, +#: independent check (belt and braces): an entry here is refused even if it is ever added to the +#: allowlist by mistake, and the micro-tests fail if the two lists overlap. Each entry here reads +#: like a find but writes to Egeria. An entry denies the method on every class that has it (and its +#: `_async_` twin), since EgeriaTech and its subclasses inherit it. FIND_METHOD_DENYLIST: frozenset = frozenset({ # "Create a CSV file element from a template if it doesn't exist": an Egeria write. "AutomatedCuration.get_create_csv_data_file_element_from_template", @@ -73,7 +142,6 @@ #: the allowlist accepts exactly these, and no other unknown name. LEGACY_CLASS_ALIASES: Dict[str, str] = {"_client_new": "EgeriaTech"} -_READ_ONLY_PREFIXES = ("find_", "get_", "list_") _FIND_STAGE = "producer/find" _ANALYTIC_STAGE = "producer/analytic" _STAGE_KINDS_RUNNABLE = (_FIND_STAGE, _ANALYTIC_STAGE) @@ -283,9 +351,9 @@ def find_method_allowed(func_decl: Any) -> Tuple[bool, str]: """Whether an Egeria-held spec may name `func_decl` as its find method, and the words why not. Allowed: `Class.method` (exactly one dot) where `Class` is an EgeriaTech client class (or a - name the executor maps to one, `_CLIENT_CLASS_MAP` / `LEGACY_CLASS_ALIASES`), the method exists - there, its name starts with find_, get_ or list_, and it is not on `FIND_METHOD_DENYLIST` (on any - class).""" + name the executor maps to one, `_CLIENT_CLASS_MAP` / `LEGACY_CLASS_ALIASES`), `Class.method` + (or the method's `_async_` twin) is on `FIND_METHOD_ALLOWLIST`, it is not on + `FIND_METHOD_DENYLIST` (on any class), and the method exists there.""" from pyegeria.view.format_set_executor import _CLIENT_CLASS_MAP from pyegeria.view.spec_resolver import _find_method @@ -307,12 +375,13 @@ def find_method_allowed(func_decl: Any) -> Tuple[bool, str]: pass else: return False, f"its find method's class '{class_name}' is not an EgeriaTech client class" - if not bare.startswith(_READ_ONLY_PREFIXES): - return False, (f"its find method '{func_decl}' is not read-only by name (it must start with " - f"{', '.join(_READ_ONLY_PREFIXES)})") if (func_decl in FIND_METHOD_DENYLIST or f"{class_name}.{bare}" in FIND_METHOD_DENYLIST or bare in _DENIED_METHOD_NAMES): return False, f"its find method '{func_decl}' is on the denylist" + if f"{class_name}.{bare}" not in FIND_METHOD_ALLOWLIST: + return False, (f"its find method '{func_decl}' is not on the allowlist of find methods a spec held in " + f"Egeria may name (FIND_METHOD_ALLOWLIST: the methods today's built-in specs name, " + f"plus reviewed additions)") method, why = _find_method(f"{class_name}.{bare}") if method is None: return False, why diff --git a/pyegeria/view/schemas/microflow-1.json b/pyegeria/view/schemas/microflow-1.json index d4da356e..c9d21a98 100644 --- a/pyegeria/view/schemas/microflow-1.json +++ b/pyegeria/view/schemas/microflow-1.json @@ -33,7 +33,7 @@ "description": "producer/find or producer/analytic in stage 1; other kinds are valid but not run yet."}, "type": {"type": "string", "description": "The open metadata type a find stage looks for."}, "function": {"type": "string", - "description": "producer/find: Class.method on an EgeriaTech client class, read-only by name (find_, get_, list_). producer/analytic: a registered analytic name. Never a dotted module path."}, + "description": "producer/find: Class.method on an EgeriaTech client class, on pyegeria's find-method allowlist (FIND_METHOD_ALLOWLIST). producer/analytic: a registered analytic name. Never a dotted module path."}, "params": {"type": "object", "description": "Argument bindings: \"$name\" names a spec parameter, anything else is a constant."}, "out": {"type": "string", "description": "The shape the stage produces (recorded, not checked, in stage 1)."} }, diff --git a/tests/micro-tests/test_rs_egeria_tier.py b/tests/micro-tests/test_rs_egeria_tier.py index 87721765..9730aae1 100644 --- a/tests/micro-tests/test_rs_egeria_tier.py +++ b/tests/micro-tests/test_rs_egeria_tier.py @@ -292,10 +292,12 @@ def test_every_function_todays_runnable_local_specs_name_passes_the_allowlist(ti @pytest.mark.parametrize("func,words", [ ("pyegeria.omvs.collection_manager.CollectionManager.find_collections", "dotted module path"), ("os.system", "not an EgeriaTech client class"), - ("CollectionManager.create_collection", "not read-only by name"), - ("CollectionManager.delete_collection", "not read-only by name"), + ("CollectionManager.create_collection", "not on the allowlist"), + ("CollectionManager.delete_collection", "not on the allowlist"), + ("CollectionManager.get_collection_by_guid", "not on the allowlist"), # read-only by name, not listed + ("EgeriaTech.find_collections", "not on the allowlist"), # entries are Class.method as written ("NotAClient.find_things", "not an EgeriaTech client class"), - ("CollectionManager.find_no_such_thing", "does not exist"), + ("CollectionManager.find_no_such_thing", "not on the allowlist"), ]) def test_allowlist_refuses_with_words(func, words): ok, why = mfm.find_method_allowed(func) @@ -326,66 +328,81 @@ def test_denylist_refuses_the_csv_template_write_on_every_class_and_async_twin() assert not ok and "denylist" in why, (decl, why) +def test_async_twin_of_an_allowlisted_method_is_allowed(): + assert mfm.find_method_allowed("CollectionManager._async_find_collections") == (True, "") + + +def test_allowlist_is_the_census_plus_additions_and_never_meets_the_denylist(): + assert mfm.FIND_METHOD_ALLOWLIST == mfm._CENSUS_FIND_METHODS | mfm.FIND_METHOD_ADDITIONS + assert len(mfm._CENSUS_FIND_METHODS) == 45 + assert not (mfm.FIND_METHOD_ALLOWLIST & mfm.FIND_METHOD_DENYLIST) + denied = {e.rsplit(".", 1)[-1] for e in mfm.FIND_METHOD_DENYLIST} + assert not {e.rsplit(".", 1)[-1] for e in mfm.FIND_METHOD_ALLOWLIST} & denied + + +def test_every_allowlist_entry_passes_the_allowlist(): + """Each entry's class maps to an EgeriaTech client class and the method exists there.""" + refused = {} + for decl in sorted(mfm.FIND_METHOD_ALLOWLIST): + ok, why = mfm.find_method_allowed(decl) + if not ok: + refused[decl] = why + assert not refused, refused + + +def test_every_runnable_builtin_spec_function_is_on_the_allowlist(tier): + """The stage-2 seed writes today's built-in and generated specs into Egeria; none may be refused.""" + from pyegeria.view.spec_resolver import resolve + missing = {} + for source in (brf.base_report_specs, brf.generated_format_sets): + for label, fs in source.items(): + a = fs.action if isinstance(fs.action, dict) or fs.action is None else fs.action.model_dump() + func = (a or {}).get("function") + if not func or not resolve(fs, label).runnable: + continue + ok, why = mfm.find_method_allowed(func) + if not ok: + missing.setdefault(func, []).append(label) + assert not missing, missing + + # Write words, per the Architect's read-back of stage 1 (P1). A name matches when one of its # _-separated words starts with one; a docstring's first line when a word there does. _WRITE_WORDS = r"(create|add|update|delete|remove|attach|detach|set|start|stop|run|register|refresh|clear|load)" -# Reviewed 2026-11-09: each passes the allowlist, matches a write word, and is a read. Why it matched: +# Reviewed 2026-11-09, keyed by Class.method as on the allowlist: each matches a write word and is a +# read. Why it matched: _REVIEWED_READS = { - "find_tabular_data_sets": "'data sets' (set) - retrieves tabular data set elements", - "get_tabular_data_set": "'data set' (set) - retrieves a tabular data set report", - "get_active_configuration": "'if it is running' - returns a server's configuration", - "get_active_server_instance_status": "'services running' - status of a server's services", - "get_approved_engine_actions": "'approved to run' - lists engine actions", - "get_attached_collections": "'attached' - lists linked collections", - "get_attached_comments": "'attached' - lists comments", - "get_attached_likes": "'attached' - lists likes", - "get_attached_note_logs": "'attached' - lists note logs", - "get_attached_ratings": "'attached' - lists ratings", - "get_attached_tags": "'attached' - lists informal tags", - "get_connector_config": "'connector running' - reads configuration properties", - "get_integration_connector_config_properties": "'connector running' - reads configuration properties", - "get_connector_type": "'as registered' - returns a connector type", - "get_endpoints_by_network_address": "'address' (add) - POST to /endpoints/by-network-address, a search", - "get_platform_report": "'running platform' - returns platform details", - "get_server_report": "'running server' - returns server details", - "get_project_hierarchy": "'starting with' - returns a project hierarchy", - "get_registered_services": "'registered' - lists registered services", - "get_security_posture_history": "'test run' - returns posture summaries", - "get_software_capabilities_for_infrastructure": "'attached' - lists software capabilities", - "get_user_list": "'registered' - lists platform users", - "get_valid_classification_types": "'can be attached' - returns TypeDefs", - "get_valid_relationship_types": "'can be attached' - returns TypeDefs", + "DataDiscovery.get_security_posture_history": "'one per test run' - returns posture summaries", + "ServerClient.get_attached_comments": "'attached' - lists the comments attached to an element", } def test_no_allowlisted_method_reads_as_a_write(): - """Scan every method on the EgeriaTech classes that passes the allowlist for write words in its - name or its docstring's first line. Any hit must be on the denylist (and so not pass) or in - `_REVIEWED_READS`. A new hit means: read the method; if it writes, add it to - FIND_METHOD_DENYLIST; if it reads, add it to `_REVIEWED_READS` with why it matched.""" + """Scan every FIND_METHOD_ALLOWLIST entry for write words in its method name or its docstring's + first line (sync and `_async_` twin). A hit must be in `_REVIEWED_READS`, keyed by Class.method. + A new hit means: read the method; if it writes, take it off the allowlist (and add it to + FIND_METHOD_DENYLIST); if it reads, add it to `_REVIEWED_READS` with why it matched.""" import inspect import re - from pyegeria.view.spec_resolver import _egeria_tech_classes + import sys + from pyegeria.view.spec_resolver import _find_method name_re = re.compile(r"(^|_)" + _WRITE_WORDS) doc_re = re.compile(r"\b" + _WRITE_WORDS, re.I) - passing, hits = 0, {} - for cls in _egeria_tech_classes(): - for attr in dir(cls): - bare = attr[len("_async_"):] if attr.startswith("_async_") else attr - if not bare.startswith(("find_", "get_", "list_")) or not callable(getattr(cls, attr, None)): - continue - ok, _why = mfm.find_method_allowed(f"{cls.__name__}.{attr}") - if not ok: - continue - passing += 1 - doc = (inspect.getdoc(getattr(cls, attr)) or "").strip().splitlines() - first = doc[0] if doc else "" - if name_re.search(bare) or doc_re.search(first): - hits.setdefault(bare, f"{cls.__name__}.{attr}: {first[:120]}") - assert passing > 1000 # the scan really ran over the client classes - assert _WRITE_CSV not in hits + hits = {} + for decl in sorted(mfm.FIND_METHOD_ALLOWLIST): + bare = decl.rsplit(".", 1)[-1] + method, why = _find_method(decl) + assert method is not None, (decl, why) + # `_find_method` returns the `_async_` function; its defining class holds the sync twin. + owner = getattr(sys.modules.get(method.__module__), method.__qualname__.split(".")[0], None) + firsts = [] + for m in (method, getattr(owner, bare, None)): + doc = (inspect.getdoc(m) or "").strip().splitlines() if m is not None else [] + firsts.append(doc[0] if doc else "") + if name_re.search(bare) or any(doc_re.search(f) for f in firsts): + hits[decl] = " | ".join(f[:120] for f in firsts if f) unreviewed = {k: v for k, v in hits.items() if k not in _REVIEWED_READS} assert not unreviewed, unreviewed stale = set(_REVIEWED_READS) - set(hits) From e2e8a8c87b89b06cde2ddafb4cdf030e3cdf9845 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 10:30:11 +0000 Subject: [PATCH 3/6] fix(view): repoint the two unrunnable built-in specs; census 0 unrunnable The owner's fix for the census's two unrunnable specs (pyegeria 6.2.28). - Asset-Graph named ServerClient.get_asset_graph, which no longer exists. It now calls AssetCatalog.get_asset_graph_by_guid. The required parameter is now guid instead of asset_guid; the optional ones are start_from and page_size. commands/cat/ get_asset_graph.py (the hey_egeria asset graph command) passes the new name. - Data-Classes named DataDesigner.find_data_classes, which no longer exists. It now calls DataDesigner.find_data_value_specifications with spec_params={"metadata_element_subtypes": ["DataClass"]}. DataClass is a DataValueSpecification subtype that shares the same search endpoint, and the filter travels in the search body as metadataElementSubtypeNames (through **kwargs into _async_find_request). The two subtype keys are removed from the spec's optional params so a caller cannot override the filter. - Live READ against qs-view-server (no writes): - The DataClass filter returns 6 DataClass elements; DataGrain returns none, so the filter is honoured. - Data-Classes DICT returns 6 DataClass rows. It fills the same columns as Data-Value-Spec does on the same data. - Asset-Graph DICT and MERMAID run on a real asset guid. - AssetCatalog.get_asset_graph_by_guid is added to the positive allowlist (46 entries). find_data_value_specifications was already on it. The every-runnable- built-in test now covers both specs. - Census: 437 specs, 376 runnable, 61 format-only, 0 unrunnable (was 374 / 61 / 2). The resolver tests that used Data-Classes as their unrunnable example now register a probe spec. KNOWN_UNRUNNABLE is now empty. The log_lines fixture re-enables the pyegeria logger, because another module's test can leave it disabled. - Docs: the census numbers in output-formats-and-report-specs.md are updated, and the two "unrunnable today" examples are now history with their fix. A new docs/release-notes/6.2.28.md is added. Signed-off-by: Dan Wolfson --- commands/cat/get_asset_graph.py | 2 +- docs/output-formats-and-report-specs.md | 6 ++- docs/release-notes/6.2.28.md | 12 ++++++ pyegeria/view/base_report_formats.py | 17 +++++--- pyegeria/view/microflow.py | 5 ++- tests/micro-tests/test_rs_egeria_tier.py | 19 +++++---- .../micro-tests/test_rs_w2_2_spec_resolver.py | 42 +++++++++++++------ 7 files changed, 73 insertions(+), 30 deletions(-) create mode 100644 docs/release-notes/6.2.28.md diff --git a/commands/cat/get_asset_graph.py b/commands/cat/get_asset_graph.py index ff56cba3..6499c43c 100644 --- a/commands/cat/get_asset_graph.py +++ b/commands/cat/get_asset_graph.py @@ -40,7 +40,7 @@ def asset_viewer(asset_guid: str, output_format: str = "TABLE", view_server: str render_table: bool = False, table_caption: str | None = None, use_pager: bool = True): try: list_generic(report_spec="Asset-Graph", output_format=output_format, view_server=view_server, - view_url=view_url, user=user, user_pass=user_pass, params={"asset_guid": asset_guid}, + view_url=view_url, user=user, user_pass=user_pass, params={"guid": asset_guid}, render_table=render_table, write_file = write_file, table_caption=table_caption, use_pager=use_pager, width=width, jupyter=jupyter, prompt_missing=prompt_missing) diff --git a/docs/output-formats-and-report-specs.md b/docs/output-formats-and-report-specs.md index 0eacccca..2e0b536f 100644 --- a/docs/output-formats-and-report-specs.md +++ b/docs/output-formats-and-report-specs.md @@ -1227,7 +1227,7 @@ Check 1 on a report spec that names a dotted path says, for example: *Report spe - **Runnable:** a `ResolvedSpec`. Its `notes` say which checks did not run and why; its `warnings` are defects that bite only when a caller uses an optional parameter. - **Unrunnable:** an `Unrunnable` with `words` and `checks`. It failed at least one check. -- **Format-only:** an `Unrunnable` of `kind="format_only"` with `checks=[1]`: the spec has no `action`, so it formats elements another call fetched (a detail view, or a command's output format). **This is not broken**: the words say `it has no action, so it formats elements another call fetched`. On the registry as of 6.2.27 there are 374 runnable, 61 format-only and 2 unrunnable specs. +- **Format-only:** an `Unrunnable` of `kind="format_only"` with `checks=[1]`: the spec has no `action`, so it formats elements another call fetched (a detail view, or a command's output format). **This is not broken**: the words say `it has no action, so it formats elements another call fetched`. On the registry as of 6.2.28 there are 376 runnable, 61 format-only and no unrunnable specs (6.2.27 had 374 runnable and 2 unrunnable; see below). **Listing them.** @@ -1249,13 +1249,15 @@ for name, spec in unrunnable_specs().items(): # format-only left out; p - `load_egeria_report_specs()` (the Egeria question-spec load); - `commands/tech/refresh_specs.py`, which resolves everything after regenerating and logs the count. -**Reading the words: the two specs that are unrunnable today.** Both fail check 1, both are `find` specs, and both name a find method that does not exist, so the words tell you exactly what to fix: +**Reading the words: the two specs that were unrunnable in 6.2.27.** Both failed check 1, both were `find` specs, and both named a find method that no longer existed, so the words said exactly what to fix: - `Spec 'Asset-Graph' cannot run (check 1): its find method 'ServerClient.get_asset_graph' does not exist: EgeriaTech or any client it proxies to has no '_async_get_asset_graph'.` - `Spec 'Data-Classes' cannot run (check 1): its find method 'DataDesigner.find_data_classes' does not exist: client class DataDesigner has no '_async_find_data_classes'.` Read it left to right: *the check* (1, names), *the thing named* (`ServerClient.get_asset_graph`), *where the resolver looked* (the client class the executor would use for that name, here EgeriaTech and everything it proxies to), and *what was missing* (an `_async_` method of that name). They are listed with these words by `list_report_specs(with_status=True)` rather than being left to fail when someone runs them. +6.2.28 fixed both, as the words pointed: `Asset-Graph` now calls `AssetCatalog.get_asset_graph_by_guid` (parameter `guid`), and `Data-Classes` calls `DataDesigner.find_data_value_specifications` with `metadata_element_subtypes=["DataClass"]` (a DataClass is a DataValueSpecification subtype and shares its search). + > **Planned, not shipped.** Report specs held in Egeria itself (synced, cached and addressed as `egeria:...`) are being built in a first stage; see `portal-docs/Internals/report-spec-pipeline-model.md` (v5.5) in egeria-workspaces. This section describes only specs loaded from files, entry points and the runtime registry. diff --git a/docs/release-notes/6.2.28.md b/docs/release-notes/6.2.28.md new file mode 100644 index 00000000..9184b986 --- /dev/null +++ b/docs/release-notes/6.2.28.md @@ -0,0 +1,12 @@ +# pyegeria 6.2.28 + +## Fixed + +- **The two unrunnable built-in report specs run again.** `Asset-Graph` named + `ServerClient.get_asset_graph`, which no longer exists; it now calls + `AssetCatalog.get_asset_graph_by_guid`, and its required parameter is `guid` (was `asset_guid`; the + `hey_egeria` asset graph command passes the new name). + `Data-Classes` named `DataDesigner.find_data_classes`, which no longer exists; it now calls + `DataDesigner.find_data_value_specifications` restricted to the `DataClass` subtype + (`metadata_element_subtypes=["DataClass"]`). The load-time census is now 437 specs: 376 runnable, + 61 format-only, none unrunnable (6.2.27: 374 runnable, 2 unrunnable). diff --git a/pyegeria/view/base_report_formats.py b/pyegeria/view/base_report_formats.py index 17fcf206..606310f0 100644 --- a/pyegeria/view/base_report_formats.py +++ b/pyegeria/view/base_report_formats.py @@ -1423,9 +1423,11 @@ def _user_report_specs_dir() -> str: ) ], action=ActionParameter( - function="ServerClient.get_asset_graph", - optional_params=OPTIONAL_FILTER_PARAMS + TIME_PARAMETERS, - required_params=["asset_guid"], + # ServerClient.get_asset_graph no longer exists; the asset graph is AssetCatalog's + # assets/{guid}/as-graph (6.2.28). + function="AssetCatalog.get_asset_graph_by_guid", + required_params=["guid"], + optional_params=["start_from", "page_size"], spec_params={}, ) ), @@ -2949,9 +2951,14 @@ def _user_report_specs_dir() -> str: )], action=ActionParameter( - function="DataDesigner.find_data_classes", + # DataDesigner.find_data_classes no longer exists. DataClass is a subtype of + # DataValueSpecification and shares its search endpoint; the subtype filter travels in the + # search body as metadataElementSubtypeNames (6.2.28). + function="DataDesigner.find_data_value_specifications", required_params=["search_string"], - spec_params={}, + optional_params=[p for p in OPTIONAL_SEARCH_PARAMS + if p not in ("metadata_element_subtypes", "metadata_element_type")], + spec_params={"metadata_element_subtypes": ["DataClass"]}, ) ), "Data-Value-Spec": FormatSet( diff --git a/pyegeria/view/microflow.py b/pyegeria/view/microflow.py index c2a1db08..ccb1e175 100644 --- a/pyegeria/view/microflow.py +++ b/pyegeria/view/microflow.py @@ -64,8 +64,8 @@ #: FIND_METHOD_DENYLIST). It is the union of two named parts: #: #: - `_CENSUS_FIND_METHODS`: every find method a runnable built-in or generated spec names, taken from -#: the 437-spec census on 2026-11-09 (45 methods; the two unrunnable specs' methods, which do not -#: exist, are left out). The micro-test `test_every_runnable_builtin_spec_function_is_on_the_allowlist` +#: the 437-spec census on 2026-11-09 (46 methods, every spec runnable since 6.2.28 repointed +#: Asset-Graph and Data-Classes). The micro-test `test_every_runnable_builtin_spec_function_is_on_the_allowlist` #: fails when a built-in or generated spec names one that is missing, so the stage-2 seed (today's #: built-ins written into Egeria) can never be refused. #: - `FIND_METHOD_ADDITIONS`: methods no built-in names yet, each added after reading it. @@ -78,6 +78,7 @@ "ActorManager.find_perspectives", "ActorManager.find_skills", "ActorManager.find_user_identities", + "AssetCatalog.get_asset_graph_by_guid", "AssetMaker.find_assets", "ClassificationExplorer.get_elements", "ClassificationExplorer.get_owners_elements", diff --git a/tests/micro-tests/test_rs_egeria_tier.py b/tests/micro-tests/test_rs_egeria_tier.py index 9730aae1..67493bad 100644 --- a/tests/micro-tests/test_rs_egeria_tier.py +++ b/tests/micro-tests/test_rs_egeria_tier.py @@ -130,6 +130,7 @@ def tier(monkeypatch, tmp_path): def log_lines(): from loguru import logger lines = [] + logger.enable("pyegeria") # another test module may have left pyegeria's logger disabled sink = logger.add(lambda m: lines.append(m.record["message"]), level="WARNING") yield lines logger.remove(sink) @@ -279,11 +280,10 @@ def test_every_function_todays_runnable_local_specs_name_passes_the_allowlist(ti ok, why = mfm.find_method_allowed(func) if not ok: refused[func] = (labels, why) - # Exactly the find methods of the two specs the resolver already lists as unrunnable (their - # methods do not exist); every other find method a local spec names is allowed. - assert set(refused) == {"ServerClient.get_asset_graph", "DataDesigner.find_data_classes"}, refused - for func, (labels, _why) in refused.items(): - assert all(not results[lb].runnable for lb in labels) + # Since 6.2.28 repointed Asset-Graph and Data-Classes, every spec is runnable and every find + # method a local spec names is allowed. + assert not refused, refused + assert all(r.runnable or r.kind == "format_only" for r in results.values()) for name in analytics: ok, why = mfm._analytic_allowed(name) assert ok, (name, why) @@ -334,7 +334,7 @@ def test_async_twin_of_an_allowlisted_method_is_allowed(): def test_allowlist_is_the_census_plus_additions_and_never_meets_the_denylist(): assert mfm.FIND_METHOD_ALLOWLIST == mfm._CENSUS_FIND_METHODS | mfm.FIND_METHOD_ADDITIONS - assert len(mfm._CENSUS_FIND_METHODS) == 45 + assert len(mfm._CENSUS_FIND_METHODS) == 46 assert not (mfm.FIND_METHOD_ALLOWLIST & mfm.FIND_METHOD_DENYLIST) denied = {e.rsplit(".", 1)[-1] for e in mfm.FIND_METHOD_DENYLIST} assert not {e.rsplit(".", 1)[-1] for e in mfm.FIND_METHOD_ALLOWLIST} & denied @@ -351,7 +351,8 @@ def test_every_allowlist_entry_passes_the_allowlist(): def test_every_runnable_builtin_spec_function_is_on_the_allowlist(tier): - """The stage-2 seed writes today's built-in and generated specs into Egeria; none may be refused.""" + """The stage-2 seed writes today's built-in and generated specs into Egeria; none may be refused. + Covers the two specs 6.2.28 repointed (Asset-Graph, Data-Classes).""" from pyegeria.view.spec_resolver import resolve missing = {} for source in (brf.base_report_specs, brf.generated_format_sets): @@ -364,6 +365,10 @@ def test_every_runnable_builtin_spec_function_is_on_the_allowlist(tier): if not ok: missing.setdefault(func, []).append(label) assert not missing, missing + assert brf.base_report_specs["Asset-Graph"].action.function == "AssetCatalog.get_asset_graph_by_guid" + assert brf.base_report_specs["Data-Classes"].action.function == "DataDesigner.find_data_value_specifications" + for label in ("Asset-Graph", "Data-Classes"): + assert resolve(brf.base_report_specs[label], label).runnable, label # Write words, per the Architect's read-back of stage 1 (P1). A name matches when one of its diff --git a/tests/micro-tests/test_rs_w2_2_spec_resolver.py b/tests/micro-tests/test_rs_w2_2_spec_resolver.py index 6b4a22cd..7c835256 100644 --- a/tests/micro-tests/test_rs_w2_2_spec_resolver.py +++ b/tests/micro-tests/test_rs_w2_2_spec_resolver.py @@ -42,11 +42,10 @@ def _clean(): # ── The census over every registered spec (base_report_formats + analytic demo specs) ── -#: The unrunnable specs the first resolution found, each a real defect (see the PR body). -KNOWN_UNRUNNABLE = { - "Asset-Graph": "its find method 'ServerClient.get_asset_graph' does not exist", - "Data-Classes": "its find method 'DataDesigner.find_data_classes' does not exist", -} +#: The unrunnable specs: the first resolution found two (Asset-Graph naming the missing +#: ServerClient.get_asset_graph, Data-Classes naming the missing DataDesigner.find_data_classes); +#: 6.2.28 repointed both, so there are none. +KNOWN_UNRUNNABLE: dict = {} def test_every_registered_spec_resolves_and_the_unrunnable_ones_are_the_known_defects(): @@ -216,10 +215,16 @@ def test_formatset_accepts_target_type_name(): def test_list_report_specs_is_unchanged_by_default_and_gains_status_on_request(): names = brf.list_report_specs() assert names and all(isinstance(n, str) for n in names) - status = {d["name"]: d for d in brf.list_report_specs(with_status=True)} - assert set(status) == set(names) - assert status["Data-Classes"]["runnable"] is False - assert "check 1" in status["Data-Classes"]["unrunnable_reason"] + brf.register_report_specs({"Probe-Missing": _spec(_find(function="DataDesigner.find_no_such_things"))}, + source="test") + try: + status = {d["name"]: d for d in brf.list_report_specs(with_status=True)} + finally: + brf.unregister_report_spec("Probe-Missing") + assert set(status) == set(names) | {"Probe-Missing"} + assert status["Probe-Missing"]["runnable"] is False + assert "check 1" in status["Probe-Missing"]["unrunnable_reason"] + assert status["Data-Classes"]["runnable"] is True and status["Asset-Graph"]["runnable"] is True assert status["Analytic Demo - Element Count by Type"] == { "name": "Analytic Demo - Element Count by Type", "runnable": True, "unrunnable_reason": "", # RS-EGERIA-TIER: where the spec comes from, and whether it shadows or is shadowed @@ -268,14 +273,25 @@ def _captured(fn) -> str: return "".join(lines) -def test_refresh_report_specs_logs_the_unrunnable_count_and_words(): +def test_refresh_report_specs_logs_all_runnable_when_none_is_unrunnable(): brf.get_report_registry() # startup has happened text = _captured(brf.refresh_report_specs) - assert "Report specs resolved at refresh_report_specs: 2 of" in text - assert "Spec 'Data-Classes' cannot run (check 1)" in text + assert "Report specs resolved at refresh_report_specs: all " in text and "cannot run" not in text + + +def test_refresh_report_specs_logs_the_unrunnable_count_and_words(): + brf.get_report_registry() # startup has happened + brf.register_report_specs({"Probe-Missing": _spec(_find(function="DataDesigner.find_no_such_things"))}, + source="test") + try: + text = _captured(lambda: sr.log_resolution_summary(force=True, where="refresh_report_specs")) + finally: + brf.unregister_report_spec("Probe-Missing") + assert "Report specs resolved at refresh_report_specs: 1 of" in text + assert "Spec 'Probe-Missing' cannot run (check 1)" in text def test_the_summary_is_logged_once_unless_forced(): sr.log_resolution_summary() assert _captured(sr.log_resolution_summary) == "" - assert "cannot run" in _captured(lambda: sr.log_resolution_summary(force=True, where="test")) + assert "Report specs resolved at test" in _captured(lambda: sr.log_resolution_summary(force=True, where="test")) From 883d33e4d00d46aeda7d4644ac1f2d5e6bcd94ce Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 11:11:43 +0000 Subject: [PATCH 4/6] fix(view): Asset-Graph renders the asset graph in every format it declares MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This fixes the Architect's P2 on e2e8a8c8 (READBACK-allowlist-specfix-cappedscans-2026-11-09 §2). Asset-Graph resolved and ran, but its output was not the graph. What was actually wrong, checked live and against a recorded response: - The anchor graph column's key was misspelt `anchorMermaidGRaph`, so Anchor Graph was always empty. It is now `anchorMermaidGraph`, and an Action Graph column (`actionMermaidGraph`, which the response also carries) is added. - The spec declared only ALL. Requesting ALL as an output format returned a 62-82 char markdown string holding just the asset's name, labelled kind "json". - Requesting MD or FORM rendered a Dr.Egeria "Update Asset" form, and LIST a markdown table, none of which can show a graph. Two read-back findings did not reproduce: - REPORT and MERMAID were not empty. They return kind "text" with the graph in `content` (`data` is not used for text results). The read-back read `data`. - DICT's single row is the asset itself. On this repository the first find_assets result is a GovernanceActionProcessInstance, whose display name reads like an audit message. DICT gave one row equal to the asset on four asset types live. Changes: - Asset-Graph declares DICT/TABLE/JSON, REPORT/HTML and MERMAID: - DICT, TABLE and JSON give the asset's own fields plus the graphs as text. - REPORT and HTML give the fields, with the asset, anchor and action graphs rendered as mermaid. - MERMAID gives the asset graph. - The columns are a named ASSET_GRAPH_COLUMNS list. ALL, MD, FORM and LIST are dropped, with the reason in a comment. Asking for one now raises the executor's existing error, which lists the declared formats. - format_set_executor: a ValueError from the find path was printed and swallowed, so the call returned None. It is now logged and re-raised. - Tests (17) against a recorded get_asset_graph_by_guid response (tests/micro-tests/data/asset_graph_by_guid_response.json, from qs-view-server, read only, relationships trimmed). They run the real path from exec_report_spec down to _generate_asset_output; only the HTTP request is replaced, and building a real client fails the test. They cover: - each declared format, with DICT a single row that is the asset and has all three graphs; - REPORT with three mermaid blocks; - MERMAID equal to the rendered mermaidGraph; - ALL, MD, FORM and LIST raising with words; - no declared format returning None. - Live READ against qs-view-server, after the fix: - DICT is 1 row with Mermaid 740 / Anchor 878 / Action 804 characters. - REPORT has 3 mermaid blocks; HTML and MERMAID carry the graph. - ALL and MD raise with words. - DICT is one row, the asset itself, on Notification, EngineAction and ConnectorActivityReport assets. - docs/release-notes/6.2.28.md is updated. Signed-off-by: Dan Wolfson --- docs/release-notes/6.2.28.md | 11 + pyegeria/view/base_report_formats.py | 49 +- pyegeria/view/format_set_executor.py | 5 +- .../data/asset_graph_by_guid_response.json | 485 ++++++++++++++++++ tests/micro-tests/test_asset_graph_spec.py | 152 ++++++ 5 files changed, 685 insertions(+), 17 deletions(-) create mode 100644 tests/micro-tests/data/asset_graph_by_guid_response.json create mode 100644 tests/micro-tests/test_asset_graph_spec.py diff --git a/docs/release-notes/6.2.28.md b/docs/release-notes/6.2.28.md index 9184b986..242b40c6 100644 --- a/docs/release-notes/6.2.28.md +++ b/docs/release-notes/6.2.28.md @@ -10,3 +10,14 @@ `DataDesigner.find_data_value_specifications` restricted to the `DataClass` subtype (`metadata_element_subtypes=["DataClass"]`). The load-time census is now 437 specs: 376 runnable, 61 format-only, none unrunnable (6.2.27: 374 runnable, 2 unrunnable). +- **`Asset-Graph` renders the graph in every format it declares.** It declares DICT, TABLE and + JSON (the asset's own fields plus its graphs as text), REPORT and HTML (the asset's fields with + the asset, anchor and action graphs rendered as mermaid), and MERMAID (the asset graph). Each + returns one row or one document for the asset itself. The anchor graph's column key was + misspelt (`anchorMermaidGRaph`), so the anchor graph was always empty; it is now + `anchorMermaidGraph`, and an Action Graph column (`actionMermaidGraph`) is added. ALL, MD, FORM + and LIST are no longer declared: MD and FORM are Dr.Egeria update forms, LIST is a markdown + table that cannot show a graph, and ALL rendered only the asset's name. Asking for one of them + is an error that names the formats the spec does declare. +- **`exec_report_spec` no longer returns `None` when a find method raises `ValueError`.** It logs + the error and raises it, so the caller sees the words. diff --git a/pyegeria/view/base_report_formats.py b/pyegeria/view/base_report_formats.py index 606310f0..ea9d368b 100644 --- a/pyegeria/view/base_report_formats.py +++ b/pyegeria/view/base_report_formats.py @@ -628,6 +628,22 @@ def _user_report_specs_dir() -> str: TIME_PARAMETERS = ["as_of_time", "effective_time"] +#: The Asset-Graph spec's columns: the asset's own fields, then the graphs get_asset_graph_by_guid +#: returns at the top level of its response (keys as Egeria writes them). +ASSET_GRAPH_COLUMNS = COMMON_COLUMNS + COMMON_METADATA_COLUMNS + [ + Column(name="Classifications", key='classifications'), + Column(name="Created By", key='created_by'), + Column(name="Create Time", key='create_time'), + Column(name="Updated By", key='updated_by'), + Column(name="Update Time", key='update_time'), + Column(name="Version", key='version'), + Column(name="Open Metadata Type Name", key='type_name'), + Column(name="Mermaid Graph", key='mermaidGraph'), + Column(name="Anchor Graph", key='anchorMermaidGraph'), + Column(name="Action Graph", key='actionMermaidGraph'), + Column(name="Field Level Lineage Graph", key='fieldLevelLineageGraph'), +] + # Modularized report_specs base_report_specs = FormatSetDict({ "Referenceable": FormatSet( @@ -1402,25 +1418,28 @@ def _user_report_specs_dir() -> str: "Asset-Graph": FormatSet( target_type="Asset", heading="Asset Graph", - description="Attributes that apply to all Assets", + description=("An asset, the elements anchored to it and their relationships, as Egeria's asset graph " + "(AssetCatalog.get_asset_graph_by_guid): the asset's own fields and its mermaid graphs."), annotations={}, # No specific annotations family="AssetCatalog", + # One element (the asset) with its graphs. Declared formats only (6.2.28): ALL, MD, FORM and LIST + # are left out on purpose. MD and FORM are Dr.Egeria update forms ("Update Asset"), which do not + # fit a read-only graph view; LIST is a markdown table, where a mermaid graph cannot render; and + # ALL, requested as an output format, rendered only the asset's name. Asking for one of them is + # an error with words (the executor lists the formats this spec declares), never a silent None. formats=[ Format( - types=["ALL"], - attributes=COMMON_COLUMNS + COMMON_METADATA_COLUMNS + [ - Column(name="Classifications", key='classifications'), - Column(name="Created By", key='created_by'), - Column(name="Create Time", key='create_time'), - Column(name="Updated By", key='updated_by'), - Column(name="Update Time", key='update_time'), - Column(name="Version", key='version'), - Column(name="Open Metadata Type Name", key='type_name'), - Column(name="Mermaid Graph", key='mermaidGraph'), - Column(name="Anchor Graph", key='anchorMermaidGRaph'), - Column(name="Field Level Lineage Graph", key='fieldLevelLineageGraph'), - ], - ) + types=["DICT", "TABLE", "JSON"], + attributes=ASSET_GRAPH_COLUMNS, + ), + Format( + types=["REPORT", "HTML"], + attributes=ASSET_GRAPH_COLUMNS, + ), + Format( + types=["MERMAID"], + attributes=[Column(name="Mermaid Graph", key='mermaidGraph')], + ), ], action=ActionParameter( # ServerClient.get_asset_graph no longer exists; the asset graph is AssetCatalog's diff --git a/pyegeria/view/format_set_executor.py b/pyegeria/view/format_set_executor.py index 4d40438e..3be2cb28 100644 --- a/pyegeria/view/format_set_executor.py +++ b/pyegeria/view/format_set_executor.py @@ -1308,8 +1308,9 @@ def _exec_report_spec_impl( print_validation_error(e) raise except ValueError as e: - import traceback - traceback.print_exc() + # 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}") + raise finally: try: diff --git a/tests/micro-tests/data/asset_graph_by_guid_response.json b/tests/micro-tests/data/asset_graph_by_guid_response.json new file mode 100644 index 00000000..e5a867ef --- /dev/null +++ b/tests/micro-tests/data/asset_graph_by_guid_response.json @@ -0,0 +1,485 @@ +{ + "_recorded": "AssetCatalog.get_asset_graph_by_guid(output_format='JSON') against qs-view-server, 2026-11-09, read only; relationships trimmed to the first of 4", + "response": { + "class": "AssetGraph", + "elementHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "206a6e44-ffe7-408b-8e59-79842d362776", + "typeName": "GovernanceActionProcessInstance", + "superTypeNames": [ + "TransientEmbeddedProcess", + "EmbeddedProcess", + "Action", + "Process", + "Asset", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "Represents a single run of a governance action process. It is linked to the parent governance action process using the GovernedBy relationship.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "egeriagovernanceengine", + "maintainedBy": [ + "baudotnpa", + "egeriagovernanceengine" + ], + "createTime": "2026-11-09T11:05:12.882+00:00", + "updateTime": "2026-11-09T11:05:17.237+00:00", + "version": 4, + "lastRequestId": "7807c843-3774-40b4-bd2c-31460308ebb9" + }, + "guid": "bf1d5f61-9d79-41bc-a89a-d863222585ff", + "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": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:12.871+00:00", + "updateTime": "2026-11-09T11:05:12.871+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "33884dcc-c0b8-455e-8991-52c704a84d46", + "anchorTypeName": "ProvisioningActionProcess", + "anchorDomainName": "AuthoredReferenceable" + } + } + }, + "properties": { + "class": "GovernanceActionProcessInstanceProperties", + "typeName": "GovernanceActionProcessInstance", + "qualifiedName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9@1794222312842::77bd32e3-074f-4405-98c0-8df53021a9df", + "displayName": "provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026", + "requestedTime": "2026-11-09T11:05:12.842+00:00", + "requestedStartTime": "2026-11-09T11:05:13.136+00:00", + "startTime": "2026-11-09T11:05:17.104+00:00", + "activityStatus": "IN_PROGRESS" + }, + "governedBy": [ + { + "class": "RelatedMetadataElementSummary", + "relationshipHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "89c3c695-9e8d-4660-9f44-ed971fd55f89", + "typeName": "GovernedBy", + "superTypeNames": [ + "LabeledRelationship" + ], + "typeVersion": 1, + "typeDescription": "Shows the resources that are governed by a specific governance definition.", + "typeCategory": "RELATIONSHIP_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:13.014+00:00", + "updateTime": "2026-11-09T11:05:13.014+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "guid": "6d6fc1ff-4717-41cf-8f73-ea2b8025f4b1" + }, + "relatedElement": { + "elementHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "c010a7df-ac08-4ad6-ac86-c9292fae2961", + "typeName": "ProvisioningActionProcess", + "superTypeNames": [ + "GovernanceActionProcess", + "GovernanceAction", + "GovernanceControl", + "GovernanceDefinition", + "AuthoredReferenceable", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "A governance action process that is used to provision a digital resource to a target environment.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "egeriagovernanceengine", + "updatedBy": "egeriagovernanceengine", + "maintainedBy": [ + "egeriagovernanceengine" + ], + "createTime": "2026-11-07T22:59:57.540+00:00", + "updateTime": "2026-11-07T22:59:57.540+00:00", + "version": 1, + "lastRequestId": "5c93efd8-f28d-44e9-a1db-cad2c92ae15f" + }, + "guid": "33884dcc-c0b8-455e-8991-52c704a84d46", + "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": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "egeriagovernanceengine", + "updatedBy": "egeriagovernanceengine", + "maintainedBy": [ + "egeriagovernanceengine" + ], + "createTime": "2026-11-07T22:59:57.538+00:00", + "updateTime": "2026-11-07T22:59:57.538+00:00", + "version": 1, + "lastRequestId": "5c93efd8-f28d-44e9-a1db-cad2c92ae15f" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "95ff50a4-13fe-4479-90f2-22d4c9c48ad9", + "anchorTypeName": "DigitalSubscription", + "anchorDomainName": "AuthoredReferenceable" + } + } + }, + "properties": { + "class": "ProvisioningActionProcessProperties", + "typeName": "ProvisioningActionProcess", + "qualifiedName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9", + "displayName": "provisioningGovernanceActionType", + "description": "The governance action type that implements the provisioning action." + } + }, + "relatedElementAtEnd1": false + } + ], + "relationships": [ + { + "class": "RelatedMetadataNodeSummary", + "relationshipHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "207e2594-e3e4-4be8-a12c-4c401656e241", + "typeName": "ActionTarget", + "typeVersion": 1, + "typeDescription": "Associates an action with one or more elements to work on.", + "typeCategory": "RELATIONSHIP_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:15.465+00:00", + "updateTime": "2026-11-09T11:05:15.465+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "guid": "bc072387-85c6-4e91-a5af-68be4e8d38b4" + }, + "relationshipProperties": { + "class": "ActionTargetProperties", + "typeName": "ActionTarget", + "actionTargetName": "destinationDataSet" + }, + "relatedElement": { + "elementHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "8f5614c5-1777-4760-a500-07e60ba29746", + "typeName": "TabularDataSetCollection", + "superTypeNames": [ + "DataSet", + "DataAsset", + "Asset", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "Collection of related tabular data sets, not necessarily stored together.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "peterprofile", + "updatedBy": "peterprofile", + "maintainedBy": [ + "peterprofile" + ], + "createTime": "2026-11-07T22:59:45.646+00:00", + "updateTime": "2026-11-07T22:59:45.646+00:00", + "version": 1, + "lastRequestId": "d57a595b-b11b-46a8-bcc4-ea44fec06456", + "lastOperationId": "28401e15-455a-4179-9aec-0bda05f1796b" + }, + "guid": "408e542a-272d-4773-ba9b-4cea3d539f01", + "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": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "peterprofile", + "updatedBy": "peterprofile", + "maintainedBy": [ + "peterprofile" + ], + "createTime": "2026-11-07T22:59:45.629+00:00", + "updateTime": "2026-11-07T22:59:45.629+00:00", + "version": 1, + "lastRequestId": "d57a595b-b11b-46a8-bcc4-ea44fec06456" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorTypeName": "TabularDataSetCollection", + "anchorDomainName": "Asset" + } + }, + "dataScope": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "22f996d0-c4b7-433a-af0b-6a3e9478e488", + "typeName": "DataScope", + "typeVersion": 2, + "typeDescription": "Identifies the scope of the data stored in the digital resource(s).", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "egeriagovernanceengine", + "updatedBy": "olcatnpa", + "maintainedBy": [ + "egeriagovernanceengine", + "olcatnpa" + ], + "createTime": "2026-11-08T00:42:56.193+00:00", + "updateTime": "2026-11-09T11:05:15.494+00:00", + "version": 124, + "lastRequestId": "6859ec57-a5a4-4b18-91ca-82728bb4ea76" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "DataScope", + "classificationProperties": { + "class": "DataScopeProperties", + "typeName": "DataScope", + "dataCollectionStartTime": "2026-11-07T23:36:00.865+00:00", + "dataCollectionEndTime": "2026-11-09T09:57:27.956+00:00", + "additionalProperties": { + "lastWrittenAt": "2026-11-09T09:57:27.956Z", + "analysisTime": "2026-11-09T09:43:16Z", + "writePattern": "APPENDED", + "lastWrittenByRunId": "ee66603d-6075-43c5-a446-ae7edb660d97", + "analysisWindowEnd": "2026-11-09T09:43:16Z", + "writersInWindow": "1", + "analysisService": "open-lineage-data-scope-governance-service", + "writesPerDay": "2.84", + "writesInWindow": "82", + "lastWriteInWindow": "2026-11-09T09:39:24Z", + "firstWriteInWindow": "2026-11-07T23:41:36Z", + "writeCount": "68", + "analysisWindowStart": "2026-10-10T09:43:16Z" + } + } + }, + "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": "peterprofile", + "updatedBy": "pepysnpa", + "maintainedBy": [ + "peterprofile", + "pepysnpa" + ], + "createTime": "2026-11-07T22:59:45.639+00:00", + "updateTime": "2026-11-08T23:29:46.590+00:00", + "version": 8, + "lastRequestId": "a5b5ae2c-02f5-4114-bf0e-7b97eb0084f3" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "UsageActivity", + "classificationProperties": { + "class": "UsageActivityProperties", + "typeName": "UsageActivity", + "explicitGetCount": 2608, + "findCount": 87, + "updatePropertyCount": 0, + "updateAttachmentCount": 1, + "updateFeedbackCount": 0, + "deleteAttachmentCount": 0, + "deleteFeedbackCount": 0 + } + }, + "dataAssetEncoding": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "3f6a1513-d3ea-4666-b5fd-c76477b0245e", + "typeName": "DataAssetEncoding", + "typeVersion": 1, + "typeDescription": "Description for how data is organized and represented in a data asset.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "peterprofile", + "updatedBy": "peterprofile", + "maintainedBy": [ + "peterprofile" + ], + "createTime": "2026-11-07T22:59:45.639+00:00", + "updateTime": "2026-11-07T22:59:45.639+00:00", + "version": 1, + "lastRequestId": "d57a595b-b11b-46a8-bcc4-ea44fec06456", + "lastOperationId": "28401e15-455a-4179-9aec-0bda05f1796b" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "DataAssetEncoding", + "classificationProperties": { + "class": "DataAssetEncodingProperties", + "typeName": "DataAssetEncoding", + "encodingType": "relational", + "encodingLanguage": "SQL" + } + } + }, + "properties": { + "class": "TabularDataSetCollectionProperties", + "typeName": "TabularDataSetCollection", + "qualifiedName": "PostgreSQL Tabular Data Set Collection::Coco PostgreSQL Server 1::subscription_staging.coco_austin_haz_mat__goods_inventory_stock", + "displayName": "subscription_staging.coco_austin_haz_mat__goods_inventory_stock", + "description": "Austin HazMat Inventory (Coco core) copy of the Goods Inventory Stock digital product. Hazardous Material Holdings depends on it (hazardous holdings).", + "versionIdentifier": "V1.0", + "deployedImplementationType": "PostgreSQL Tabular Data Set Collection", + "contentStatus": "ACTIVE" + } + }, + "relatedElementAtEnd1": false, + "startingElementGUID": "1de658d3-6af5-4c32-b915-5fb6bd5bb524" + } + ], + "mermaidGraph": "---\ntitle: GovernanceActionProcessInstance - provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026 [bf1d5f61-9d79-41bc-a89a-d863222585ff]\n---\nflowchart TD\n%%{init: {\"flowchart\": {\"htmlLabels\": false}} }%%\n\n1@{ shape: rounded, label: \"*Governance Action Process Instance*\n**provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026**\"}\n2@{ shape: trap-t, label: \"*Engine Action*\n**provision-subscription (EgeriaGovernance)**\"}\n1==>|\"Action Requester\"|2\n3@{ shape: processes, label: \"*Provisioning Action Process*\n**provisioningGovernanceActionType**\"}\n1==>|\"Governed By\"|3\nstyle 1 color:#000000, fill:#e0ab18, stroke:#004563\nstyle 2 color:#000000, fill:#7fffd4, stroke:#000000\nstyle 3 color:#000000, fill:#40E0D0, stroke:#000000\n", + "anchorMermaidGraph": "---\ntitle: Asset - provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026 [bf1d5f61-9d79-41bc-a89a-d863222585ff]\n---\nflowchart LR\n%%{init: {\"flowchart\": {\"htmlLabels\": false}} }%%\n\nsubgraph 1 [Classifications]\ndirection TB\n2@{ shape: rounded, label: \"*Anchors*\n\"}\nend\n3@{ shape: rounded, label: \"*Governance Action Process Instance*\n**provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026**\"}\n4@{ shape: rounded, label: \"*Engine Action*\n**provision-subscription (EgeriaGovernance)**\"}\n5@{ shape: stadium, label: \"*Integration Connector*\n**BaudotDigitalProductSubscriptionManagerIntegrationConnector**\"}\n5==>|\"Action Requester\"|4\n3==>|\"Action Requester\"|4\nstyle 1 color:#000000, fill:#F9F7ED, stroke:#b7c0c7\nstyle 3 color:#000000, fill:#e0ab18, stroke:#004563\nstyle 4 color:#000000, fill:#ffffe0, stroke:#004563\nstyle 5 color:#000000, fill:#BDB76B, stroke:#004563\n", + "actionMermaidGraph": "---\ntitle: Actions associated with Asset - provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026 [bf1d5f61-9d79-41bc-a89a-d863222585ff]\n---\nflowchart LR\n%%{init: {\"flowchart\": {\"htmlLabels\": false}} }%%\n\n1@{ shape: rounded, label: \"*Governance Action Process Instance*\n**provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026**\"}\n2@{ shape: cyl, label: \"*Tabular Data Set Collection*\n**subscription_staging.coco_austin_haz_mat__goods_inventory_stock**\"}\n3==>|\"destinationDataSet [Action Target]\"|2\n4@{ shape: cyl, label: \"*Tabular Data Set Collection*\n**coco_data_hub.goods_inventory_stock**\"}\n3==>|\"sourceDataSet [Action Target]\"|4\nstyle 1 color:#000000, fill:#e0ab18, stroke:#004563\nstyle 2 color:#000000, fill:#BDB76B, stroke:#004563\nstyle 4 color:#000000, fill:#BDB76B, stroke:#004563\n" + } +} \ No newline at end of file diff --git a/tests/micro-tests/test_asset_graph_spec.py b/tests/micro-tests/test_asset_graph_spec.py new file mode 100644 index 00000000..5a4f38a1 --- /dev/null +++ b/tests/micro-tests/test_asset_graph_spec.py @@ -0,0 +1,152 @@ +"""The Asset-Graph report spec renders Egeria's asset graph in every format it declares (6.2.28). + +Recorded input: `data/asset_graph_by_guid_response.json`, one AssetCatalog.get_asset_graph_by_guid +response from qs-view-server (read only). The executor tests run the real path, +exec_report_spec -> AssetCatalog.get_asset_graph_by_guid -> _async_get_results_body_request -> +_generate_asset_output; only the HTTP request is replaced by the recording. +""" +from __future__ import annotations + +import copy +import json +from pathlib import Path + +import pytest + +import pyegeria.view.base_report_formats as brf +from pyegeria.omvs.asset_catalog import AssetCatalog +from pyegeria.view.format_set_executor import exec_report_spec + +pytestmark = pytest.mark.unit + +RECORDED = json.loads((Path(__file__).parent / "data" / "asset_graph_by_guid_response.json").read_text())["response"] +GUID = RECORDED["elementHeader"]["guid"] +NAME = RECORDED["properties"]["displayName"] +DECLARED = ["DICT", "TABLE", "JSON", "REPORT", "HTML", "MERMAID"] +GRAPH_COLUMNS = {"Mermaid Graph": "mermaidGraph", "Anchor Graph": "anchorMermaidGraph", + "Action Graph": "actionMermaidGraph"} + + +class _Response: + status_code = 200 + + def __init__(self, body): + self._body = body + + def json(self): + return copy.deepcopy(self._body) + + +@pytest.fixture +def offline_asset_catalog(monkeypatch): + """AssetCatalog with no platform: the request returns the recorded graph.""" + calls = [] + + 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, method, url, payload=None, *a, **k): + calls.append((method, url)) + return _Response({"class": "AssetGraphResponse", "element": RECORDED}) + + # The executor maps every class name to EgeriaTech, which proxies to AssetCatalog; build the + # AssetCatalog directly so nothing can reach a platform, and fail loudly if EgeriaTech is built. + import pyegeria.view.format_set_executor as fse + from pyegeria.egeria_tech_client import EgeriaTech + 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 calls + + +def _run(fmt): + return exec_report_spec("Asset-Graph", output_format=fmt, params={"guid": GUID}, + view_server="qs-view-server", view_url="https://localhost:9443", + user="tester", user_pass="unused") + + +def test_the_spec_declares_exactly_the_graph_formats_and_the_corrected_key(): + spec = brf.base_report_specs["Asset-Graph"] + types = sorted(t for f in spec.formats for t in f.types) + assert types == sorted(DECLARED) + keys = {c.key for f in spec.formats for c in f.attributes} + assert "anchorMermaidGRaph" not in keys + assert {"mermaidGraph", "anchorMermaidGraph", "actionMermaidGraph"} <= keys + assert spec.action.function == "AssetCatalog.get_asset_graph_by_guid" + assert spec.action.required_params == ["guid"] + + +@pytest.mark.parametrize("fmt", ["DICT", "TABLE"]) +def test_dict_and_table_are_one_row_the_asset_itself_with_its_graphs(offline_asset_catalog, fmt): + result = _run(fmt) + assert result["kind"] == "json" + rows = result["data"] + assert isinstance(rows, list) and len(rows) == 1 # the asset, not its related elements + row = rows[0] + assert row["GUID"] == GUID and row["Display Name"] == NAME + for column, key in GRAPH_COLUMNS.items(): + assert row[column] == RECORDED[key], column + assert offline_asset_catalog and offline_asset_catalog[0][1].endswith(f"/assets/{GUID}/as-graph") + + +def test_json_is_the_raw_graph(offline_asset_catalog): + result = _run("JSON") + assert result["kind"] == "json" and result["data"]["mermaidGraph"] == RECORDED["mermaidGraph"] + + +def test_report_carries_the_asset_fields_and_every_graph(offline_asset_catalog): + result = _run("REPORT") + assert result["kind"] == "text" and result["content"] + content = result["content"] + assert NAME in content and GUID in content + assert content.count("```mermaid") == len(GRAPH_COLUMNS) + for column in GRAPH_COLUMNS: + assert f"### {column}" in content, column + + +def test_html_carries_the_graphs(offline_asset_catalog): + result = _run("HTML") + assert result["kind"] == "text" and result["mime"] == "text/html" + assert "mermaid" in result["content"] and NAME in result["content"] + + +def test_mermaid_is_the_asset_graph(offline_asset_catalog): + result = _run("MERMAID") + assert result["kind"] == "text" + content = result["content"] + assert content.count("```mermaid") == 1 + # Exactly the recorded asset graph (mermaidGraph) as the formatter renders it, not the anchor + # or action graph. + from pyegeria.view.output_formatter import _format_mermaid_value + assert _format_mermaid_value(RECORDED["mermaidGraph"]) in content + for other in ("anchorMermaidGraph", "actionMermaidGraph"): + assert _format_mermaid_value(RECORDED[other]) not in content + + +@pytest.mark.parametrize("fmt", ["ALL", "MD", "FORM", "LIST"]) +def test_a_format_the_spec_does_not_declare_is_an_error_with_words(offline_asset_catalog, fmt): + with pytest.raises(ValueError) as exc: + _run(fmt) + words = str(exc.value) + assert f"does not support requested output_format '{fmt}'" in words + assert "Available formats: DICT, HTML, JSON, MERMAID, REPORT, TABLE." in words + assert not offline_asset_catalog # refused before any request + + +@pytest.mark.parametrize("fmt", DECLARED) +def test_no_declared_format_returns_none_or_empty(offline_asset_catalog, fmt): + result = _run(fmt) + assert result is not None and result.get("kind") in {"json", "text"} + assert result.get("data") is not None or result.get("content") From 5fbc3c440a06831436324700dc9a6c8f1c25a972 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 11:33:08 +0000 Subject: [PATCH 5/6] feat(view): Asset-Graph is an edge table, with a shape per output format The owner asked what it means for a table to return a graph: after 883d33e4, TABLE/DICT returned one row holding ~740 characters of mermaid text. The owner's direction: "A table of edges and a different shape for other OutputTYpes". New pyegeria/view/asset_graph.py (pure functions) gives each declared format a shape: - DICT and TABLE: one row per edge, with From Display Name / From Type / From GUID / Relationship / To Display Name / To Type / To GUID. - The asset's own relationships (top-level lists such as governedBy and requestedActions) are included. - Direction comes from relatedElementAtEnd1 and startingElementGUID. - Each relationship is listed once, by relationship GUID. - Rows are sorted, so the order never depends on Egeria's. Paging stays Egeria's, on the graph request. - LIST: the nodes (the asset, its anchored elements, the related elements), with their role. - REPORT and MD: the asset summary, its graph(s) as mermaid, then the edge table. HTML renders that document. - MERMAID: the graph. - JSON: the full graph response. - FORM and ALL are not declared, so asking for them is an error that names the declared formats. Supporting changes: - AssetCatalog._generate_asset_graph_output applies these shapes for get_asset_graph_by_guid. MERMAID and other formats take the generic asset path. - The Architect's P3: a by-GUID REPORT no longer says "found from the search string". - markdown_to_html now enables GFM tables. The CommonMark preset had them off, so markdown tables came out as plain text in HTML, although the page CSS styles tables. Tests and checks: - The tests use a complete recorded response, rewritten to cover each format, the hand-read expected edges (5, one reported twice), deterministic order under a shuffled response, the no-edge case, and the P3 wording. - Live READ: edge rows equal the distinct relationship GUIDs on three asset types (5, 6 and 3), node counts are right, and REPORT never says "search string". - The spec docs (output-formats-and-report-specs.md) and the 6.2.28 note record the shape per format. Signed-off-by: Dan Wolfson --- docs/output-formats-and-report-specs.md | 13 + docs/release-notes/6.2.28.md | 20 +- pyegeria/omvs/asset_catalog.py | 20 +- pyegeria/view/asset_graph.py | 218 +++++ pyegeria/view/base_report_formats.py | 42 +- pyegeria/view/output_formatter.py | 5 +- .../data/asset_graph_by_guid_response.json | 795 +++++++++++++++++- tests/micro-tests/test_asset_graph_spec.py | 119 ++- 8 files changed, 1164 insertions(+), 68 deletions(-) create mode 100644 pyegeria/view/asset_graph.py diff --git a/docs/output-formats-and-report-specs.md b/docs/output-formats-and-report-specs.md index 2e0b536f..ead72470 100644 --- a/docs/output-formats-and-report-specs.md +++ b/docs/output-formats-and-report-specs.md @@ -1258,6 +1258,19 @@ Read it left to right: *the check* (1, names), *the thing named* (`ServerClient. 6.2.28 fixed both, as the words pointed: `Asset-Graph` now calls `AssetCatalog.get_asset_graph_by_guid` (parameter `guid`), and `Data-Classes` calls `DataDesigner.find_data_value_specifications` with `metadata_element_subtypes=["DataClass"]` (a DataClass is a DataValueSpecification subtype and shares its search). +**A graph has a shape per output format (`Asset-Graph`, 6.2.28).** A graph is not a list of elements, so `Asset-Graph` does not render one row per element, and never one row holding mermaid text. Each format it declares gets the shape that fits it (`pyegeria/view/asset_graph.py`): + +| Output format | Shape | +|---|---| +| `DICT`, `TABLE` | One row per edge: `From Display Name`, `From Type`, `From GUID`, `Relationship`, `To Display Name`, `To Type`, `To GUID`. The asset's own relationships are included, each relationship is listed once (by relationship GUID), and rows are sorted, so their order does not depend on Egeria's. Paging (`start_from`, `page_size`) is Egeria's, on the graph request. | +| `LIST` | The nodes, as a markdown table: `Display Name`, `Type`, `GUID`, `Role` (`asset`, `anchored`, `related`). | +| `REPORT`, `MD` | The asset summary, its graph (plus the anchor and action graphs when Egeria returns them) as mermaid, and the edge table. | +| `HTML` | The `REPORT` document rendered to HTML. | +| `MERMAID` | The graph. | +| `JSON` | The full graph response. | + +`FORM` (a Dr.Egeria update form) and `ALL` are not declared; asking for them is an error that names the declared formats. + > **Planned, not shipped.** Report specs held in Egeria itself (synced, cached and addressed as `egeria:...`) are being built in a first stage; see `portal-docs/Internals/report-spec-pipeline-model.md` (v5.5) in egeria-workspaces. This section describes only specs loaded from files, entry points and the runtime registry. diff --git a/docs/release-notes/6.2.28.md b/docs/release-notes/6.2.28.md index 242b40c6..6dc32f44 100644 --- a/docs/release-notes/6.2.28.md +++ b/docs/release-notes/6.2.28.md @@ -10,14 +10,16 @@ `DataDesigner.find_data_value_specifications` restricted to the `DataClass` subtype (`metadata_element_subtypes=["DataClass"]`). The load-time census is now 437 specs: 376 runnable, 61 format-only, none unrunnable (6.2.27: 374 runnable, 2 unrunnable). -- **`Asset-Graph` renders the graph in every format it declares.** It declares DICT, TABLE and - JSON (the asset's own fields plus its graphs as text), REPORT and HTML (the asset's fields with - the asset, anchor and action graphs rendered as mermaid), and MERMAID (the asset graph). Each - returns one row or one document for the asset itself. The anchor graph's column key was - misspelt (`anchorMermaidGRaph`), so the anchor graph was always empty; it is now - `anchorMermaidGraph`, and an Action Graph column (`actionMermaidGraph`) is added. ALL, MD, FORM - and LIST are no longer declared: MD and FORM are Dr.Egeria update forms, LIST is a markdown - table that cannot show a graph, and ALL rendered only the asset's name. Asking for one of them - is an error that names the formats the spec does declare. +- **`Asset-Graph` gives each output format a shape that fits a graph.** DICT and TABLE are an + edge table: one row per edge, with the from element (display name, type, GUID), the relationship + type, and the to element. It includes the asset's own relationships, lists each relationship + once, and is sorted, so the order is deterministic. LIST is the nodes. REPORT and MD are the + asset summary, its graph(s) as mermaid and the edge table; HTML renders that. MERMAID is the + graph. JSON is the full graph response. No format returns one row of mermaid text. A by-GUID + REPORT no longer says "found from the search string". FORM and ALL are not declared; asking + for them is an error that names the declared formats. The anchor graph's misspelt column key + (`anchorMermaidGRaph`) is corrected. +- **HTML output renders markdown tables.** The HTML renderer had GFM tables switched off, so a + markdown table in a REPORT came out as text; it is now a table. - **`exec_report_spec` no longer returns `None` when a find method raises `ValueError`.** It logs the error and raises it, so the caller sees the words. diff --git a/pyegeria/omvs/asset_catalog.py b/pyegeria/omvs/asset_catalog.py index e5f155c1..53b6681a 100644 --- a/pyegeria/omvs/asset_catalog.py +++ b/pyegeria/omvs/asset_catalog.py @@ -174,6 +174,24 @@ def _generate_asset_output(self, elements: dict | list[dict], filter_string: Opt **kwargs ) + def _generate_asset_graph_output(self, elements: dict | list[dict], filter_string: Optional[str] = None, + element_type_name: Optional[str] = None, output_format: str = "DICT", + report_spec: dict | str | None = None, **kwargs) -> str | list[dict]: + """Shape an asset graph for `output_format` (pyegeria/view/asset_graph.py): DICT/TABLE one row + per edge, LIST the nodes, REPORT/MD/HTML the asset summary with its graph and edge table. + MERMAID (the graph) and any other format take the generic asset path.""" + from pyegeria.view import asset_graph + + shaped = asset_graph.render(elements, output_format) + if shaped is None: + return self._generate_asset_output(elements, filter_string, element_type_name, output_format, + report_spec, **kwargs) + if isinstance(report_spec, str) and isinstance(shaped, str): + # Provenance footer for an Egeria-held spec on REPORT/MD/HTML (RS-EGERIA-TIER §7a). + from pyegeria.view.base_report_formats import add_spec_footer + shaped = add_spec_footer(shaped, report_spec, output_format) + return shaped + @dynamic_catch async def _async_find_in_asset_domain( self, @@ -408,7 +426,7 @@ async def _async_get_asset_graph_by_guid( response = await self._async_get_results_body_request( url=url, _type="Asset", - _gen_output=self._generate_asset_output, + _gen_output=self._generate_asset_graph_output, start_from=start_from, page_size=page_size, output_format=output_format, diff --git a/pyegeria/view/asset_graph.py b/pyegeria/view/asset_graph.py new file mode 100644 index 00000000..38eac6d7 --- /dev/null +++ b/pyegeria/view/asset_graph.py @@ -0,0 +1,218 @@ +""" +SPDX-License-Identifier: Apache-2.0 +Copyright Contributors to the ODPi Egeria project. + +Shapes for an Egeria asset graph (AssetCatalog.get_asset_graph_by_guid, the `Asset-Graph` report +spec), one per output format (pyegeria 6.2.28): + +- DICT / TABLE: one row per edge: the from element (display name, type, GUID), the relationship + type, and the to element (display name, type, GUID). Includes the asset's own relationships. +- LIST: the nodes, as a markdown table: the asset, the elements anchored to it, and every element + an edge reaches. +- REPORT / MD: the asset summary, its graph (mermaid) and the edge table, as markdown. HTML is the + same document rendered to HTML. +- MERMAID: the graph (handled by the generic mermaid path; see AssetCatalog). +- JSON: the full graph response, unchanged. + +A graph is never one row of mermaid text. + +How the response holds edges: `relationships` lists the edges among the asset and its anchored +elements, each with `startingElementGUID` (one end), `relatedElement` (the other end) and +`relatedElementAtEnd1` (which end that is). The asset's own relationships are keyed lists at the +top level (for example `governedBy`, `requestedActions`), each item a `relatedElement` with +`relatedElementAtEnd1`, the asset being the other end. An edge reported twice (the same +relationship GUID) is listed once. Rows are sorted, so the order never depends on the order Egeria +returned them in. Paging (`start_from`, `page_size`) is Egeria's, on the graph request. + +Pure functions: no I/O, no client. +""" +from __future__ import annotations + +from typing import Any, Dict, List, Optional, Tuple + +#: DICT/TABLE row keys, in column order: the edge table. +EDGE_COLUMNS: List[Tuple[str, str]] = [ + ("From Display Name", "from_display_name"), + ("From Type", "from_type"), + ("From GUID", "from_guid"), + ("Relationship", "relationship_type"), + ("To Display Name", "to_display_name"), + ("To Type", "to_type"), + ("To GUID", "to_guid"), +] + +#: LIST columns: the node table. +NODE_COLUMNS: List[Tuple[str, str]] = [ + ("Display Name", "display_name"), + ("Type", "type_name"), + ("GUID", "guid"), + ("Role", "role"), +] + +#: The REPORT/MD asset summary: (label, how to read it from the asset element). +_SUMMARY_FIELDS = [ + ("Display Name", ("properties", "displayName")), + ("Qualified Name", ("properties", "qualifiedName")), + ("Description", ("properties", "description")), + ("Type", ("elementHeader", "type", "typeName")), + ("GUID", ("elementHeader", "guid")), + ("Created By", ("elementHeader", "versions", "createdBy")), + ("Create Time", ("elementHeader", "versions", "createTime")), + ("Updated By", ("elementHeader", "versions", "updatedBy")), + ("Update Time", ("elementHeader", "versions", "updateTime")), + ("Version", ("elementHeader", "versions", "version")), +] + +#: The graphs the REPORT shows, in order, when the response carries them. +_REPORT_GRAPHS = [("Graph", "mermaidGraph"), ("Anchor Graph", "anchorMermaidGraph"), + ("Action Graph", "actionMermaidGraph"), ("Field Level Lineage Graph", "fieldLevelLineageGraph")] + + +def _dig(obj: Any, path) -> Any: + for key in path: + if not isinstance(obj, dict): + return None + obj = obj.get(key) + return obj + + +def _node(element: Dict[str, Any]) -> Dict[str, str]: + header = element.get("elementHeader") or {} + props = element.get("properties") or {} + return {"guid": header.get("guid") or "", + "type_name": _dig(header, ("type", "typeName")) or "", + "display_name": (props.get("displayName") or props.get("name") or props.get("qualifiedName") + or element.get("uniqueName") or "")} + + +def _is_edge(item: Any) -> bool: + return isinstance(item, dict) and "relationshipHeader" in item and isinstance(item.get("relatedElement"), dict) + + +def _asset_edge_lists(graph: Dict[str, Any]) -> List[List[Dict[str, Any]]]: + """The asset's own relationships: every top-level list (other than `relationships`) of edges.""" + return [v for k, v in graph.items() + if k != "relationships" and isinstance(v, list) and v and all(_is_edge(i) for i in v)] + + +def graph_nodes(graph: Dict[str, Any]) -> List[Dict[str, str]]: + """Every node: the asset first, then anchored elements, then other related elements, by name.""" + asset = _node(graph) + asset["role"] = "asset" + seen = {asset["guid"]: asset} + anchored, related = [], [] + for el in graph.get("anchoredElements") or []: + n = _node(el) + if n["guid"] and n["guid"] not in seen: + n["role"] = "anchored" + seen[n["guid"]] = n + anchored.append(n) + for edges in [graph.get("relationships") or []] + _asset_edge_lists(graph): + for item in edges: + if not _is_edge(item): + continue + n = _node(item["relatedElement"]) + if n["guid"] and n["guid"] not in seen: + n["role"] = "related" + seen[n["guid"]] = n + related.append(n) + order = lambda n: (n["display_name"].lower(), n["type_name"], n["guid"]) # noqa: E731 + return [asset] + sorted(anchored, key=order) + sorted(related, key=order) + + +def graph_edges(graph: Dict[str, Any]) -> List[Dict[str, str]]: + """One row per edge (keys: the labels of EDGE_COLUMNS), sorted, each relationship once.""" + nodes = {n["guid"]: n for n in graph_nodes(graph)} + asset_guid = _node(graph)["guid"] + rows: Dict[str, Dict[str, str]] = {} + + def add(item: Dict[str, Any], starting_guid: Optional[str]) -> None: + header = item["relationshipHeader"] + rel_guid = header.get("guid") or "" + related = _node(item["relatedElement"]) + start = nodes.get(starting_guid or "") or {"guid": starting_guid or "", "type_name": "", "display_name": ""} + if item.get("relatedElementAtEnd1"): + end1, end2 = related, start + else: + end1, end2 = start, related + key = rel_guid or f"{end1['guid']}|{_dig(header, ('type', 'typeName'))}|{end2['guid']}" + if key in rows: + return + values = {"from_display_name": end1["display_name"], "from_type": end1["type_name"], + "from_guid": end1["guid"], "relationship_type": _dig(header, ("type", "typeName")) or "", + "to_display_name": end2["display_name"], "to_type": end2["type_name"], "to_guid": end2["guid"]} + rows[key] = {label: values[k] for label, k in EDGE_COLUMNS} | {"_relationship_guid": rel_guid} + + for item in graph.get("relationships") or []: + if _is_edge(item): + add(item, item.get("startingElementGUID") or asset_guid) + for edges in _asset_edge_lists(graph): + for item in edges: + add(item, asset_guid) + + def order(r): + return (r["From Display Name"].lower(), r["Relationship"], r["To Display Name"].lower(), + r["From GUID"], r["To GUID"], r["_relationship_guid"]) + + out = sorted(rows.values(), key=order) + for r in out: + r.pop("_relationship_guid") + return out + + +def _md_cell(value: Any) -> str: + return str(value if value is not None else "").replace("|", "\\|").replace("\n", " ") + + +def _md_table(columns: List[str], rows: List[Dict[str, Any]]) -> str: + lines = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)] + lines += ["| " + " | ".join(_md_cell(r.get(c)) for c in columns) + " |" for r in rows] + return "\n".join(lines) + + +def render_nodes_list(graph: Dict[str, Any]) -> str: + """LIST: the nodes as a markdown table.""" + nodes = graph_nodes(graph) + rows = [{label: n[key] for label, key in NODE_COLUMNS} for n in nodes] + name = nodes[0]["display_name"] or nodes[0]["guid"] + return f"### Asset Graph nodes: {name} ({len(nodes)})\n\n" + _md_table([c for c, _ in NODE_COLUMNS], rows) + "\n" + + +def render_report(graph: Dict[str, Any]) -> str: + """REPORT/MD: the asset summary, its graph(s) and the edge table, as markdown.""" + from pyegeria.view.output_formatter import _format_mermaid_value + + asset = _node(graph) + name = asset["display_name"] or asset["guid"] + parts = [f"# Asset Graph: {name}", "", "## Asset", ""] + summary = [(label, _dig(graph, path)) for label, path in _SUMMARY_FIELDS] + parts.append(_md_table(["Property", "Value"], + [{"Property": label, "Value": value} for label, value in summary + if value not in (None, "")])) + for title, key in _REPORT_GRAPHS: + if graph.get(key): + parts += ["", f"## {title}", "", _format_mermaid_value(graph[key])] + edges = graph_edges(graph) + parts += ["", f"## Relationships ({len(edges)})", ""] + parts.append(_md_table([c for c, _ in EDGE_COLUMNS], edges) if edges else "No relationships.") + return "\n".join(parts) + "\n" + + +def render(graph: Any, output_format: str) -> Any: + """The shape for `output_format` (DICT, TABLE, LIST, REPORT, MD, HTML), or None when this module + has no shape for it (the caller uses its generic path). A list of graphs is shaped one by one: + rows concatenated, documents joined.""" + fmt = (output_format or "").upper() + if fmt not in {"DICT", "TABLE", "LIST", "REPORT", "MD", "HTML"}: + return None + graphs = graph if isinstance(graph, list) else [graph] + graphs = [g for g in graphs if isinstance(g, dict)] + if fmt in {"DICT", "TABLE"}: + return [row for g in graphs for row in graph_edges(g)] + if fmt == "LIST": + return "\n".join(render_nodes_list(g) for g in graphs) + report = "\n".join(render_report(g) for g in graphs) + if fmt == "HTML": + from pyegeria.view.output_formatter import markdown_to_html + return markdown_to_html(report) + return report diff --git a/pyegeria/view/base_report_formats.py b/pyegeria/view/base_report_formats.py index ea9d368b..5ab2c006 100644 --- a/pyegeria/view/base_report_formats.py +++ b/pyegeria/view/base_report_formats.py @@ -628,8 +628,11 @@ def _user_report_specs_dir() -> str: TIME_PARAMETERS = ["as_of_time", "effective_time"] -#: The Asset-Graph spec's columns: the asset's own fields, then the graphs get_asset_graph_by_guid -#: returns at the top level of its response (keys as Egeria writes them). +from pyegeria.view.asset_graph import EDGE_COLUMNS as ASSET_GRAPH_EDGE_COLUMNS # noqa: E402 +from pyegeria.view.asset_graph import NODE_COLUMNS as ASSET_GRAPH_NODE_COLUMNS # noqa: E402 + +#: The Asset-Graph spec's REPORT/MD/HTML/JSON columns: the asset's own fields, then the graphs +#: get_asset_graph_by_guid returns at the top level of its response (keys as Egeria writes them). ASSET_GRAPH_COLUMNS = COMMON_COLUMNS + COMMON_METADATA_COLUMNS + [ Column(name="Classifications", key='classifications'), Column(name="Created By", key='created_by'), @@ -1419,27 +1422,26 @@ def _user_report_specs_dir() -> str: target_type="Asset", heading="Asset Graph", description=("An asset, the elements anchored to it and their relationships, as Egeria's asset graph " - "(AssetCatalog.get_asset_graph_by_guid): the asset's own fields and its mermaid graphs."), + "(AssetCatalog.get_asset_graph_by_guid)."), annotations={}, # No specific annotations family="AssetCatalog", - # One element (the asset) with its graphs. Declared formats only (6.2.28): ALL, MD, FORM and LIST - # are left out on purpose. MD and FORM are Dr.Egeria update forms ("Update Asset"), which do not - # fit a read-only graph view; LIST is a markdown table, where a mermaid graph cannot render; and - # ALL, requested as an output format, rendered only the asset's name. Asking for one of them is - # an error with words (the executor lists the formats this spec declares), never a silent None. + # A graph has a shape per output format (6.2.28; pyegeria/view/asset_graph.py): + # - DICT/TABLE: one row per edge (from element, relationship type, to element), the asset's own + # relationships included, sorted, each relationship once; + # - LIST: the nodes (the asset, its anchored elements, every element an edge reaches); + # - REPORT/MD/HTML: the asset summary, its graph(s) and the edge table; + # - MERMAID: the graph; + # - JSON: the full graph response. + # FORM is not declared: it is a Dr.Egeria update form, which a read-only graph does not fit. ALL is + # not declared either, so a format not listed here is an error with words (the executor names the + # declared formats), never a silent None and never one row of mermaid text. formats=[ - Format( - types=["DICT", "TABLE", "JSON"], - attributes=ASSET_GRAPH_COLUMNS, - ), - Format( - types=["REPORT", "HTML"], - attributes=ASSET_GRAPH_COLUMNS, - ), - Format( - types=["MERMAID"], - attributes=[Column(name="Mermaid Graph", key='mermaidGraph')], - ), + Format(types=["DICT", "TABLE"], + attributes=[Column(name=label, key=key) for label, key in ASSET_GRAPH_EDGE_COLUMNS]), + Format(types=["LIST"], + attributes=[Column(name=label, key=key) for label, key in ASSET_GRAPH_NODE_COLUMNS]), + Format(types=["REPORT", "MD", "HTML", "JSON"], attributes=ASSET_GRAPH_COLUMNS), + Format(types=["MERMAID"], attributes=[Column(name="Mermaid Graph", key='mermaidGraph')]), ], action=ActionParameter( # ServerClient.get_asset_graph no longer exists; the asset graph is AssetCatalog's diff --git a/pyegeria/view/output_formatter.py b/pyegeria/view/output_formatter.py index fcca361e..d78d2337 100644 --- a/pyegeria/view/output_formatter.py +++ b/pyegeria/view/output_formatter.py @@ -382,8 +382,9 @@ def markdown_to_html(markdown_text: str) -> str: Returns: HTML string """ - # Initialize markdown-it - md = MarkdownIt() + # Initialize markdown-it. The CommonMark preset leaves GFM tables off, so markdown tables (the + # Asset-Graph edge table, LIST tables) came out as text; the page's CSS already styles tables. + md = MarkdownIt().enable("table") # Find all mermaid code blocks mermaid_blocks = re.findall(r'```mermaid\n(.*?)\n```', markdown_text, re.DOTALL) diff --git a/tests/micro-tests/data/asset_graph_by_guid_response.json b/tests/micro-tests/data/asset_graph_by_guid_response.json index e5a867ef..7599460d 100644 --- a/tests/micro-tests/data/asset_graph_by_guid_response.json +++ b/tests/micro-tests/data/asset_graph_by_guid_response.json @@ -1,5 +1,5 @@ { - "_recorded": "AssetCatalog.get_asset_graph_by_guid(output_format='JSON') against qs-view-server, 2026-11-09, read only; relationships trimmed to the first of 4", + "_recorded": "AssetCatalog.get_asset_graph_by_guid(output_format='JSON') against qs-view-server, 2026-11-09, read only, complete (4 relationships, the asset's own governedBy and requestedActions, 1 anchored element)", "response": { "class": "AssetGraph", "elementHeader": { @@ -90,6 +90,146 @@ "startTime": "2026-11-09T11:05:17.104+00:00", "activityStatus": "IN_PROGRESS" }, + "requestedActions": [ + { + "class": "RelatedMetadataElementSummary", + "relationshipHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "a0b7ba50-4c97-4b76-9a7d-c6a00e1be646", + "typeName": "ActionRequester", + "superTypeNames": [ + "LineageRelationship", + "LabeledRelationship" + ], + "typeVersion": 2, + "typeDescription": "The source of the action, such as a person, meeting or a governance action.", + "typeCategory": "RELATIONSHIP_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:15.883+00:00", + "updateTime": "2026-11-09T11:05:15.883+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "guid": "5342dbf4-07db-4e63-95a2-9ed274c8e72f" + }, + "relatedElement": { + "elementHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "c976d88a-2b11-4b40-b972-c38d41bfc6be", + "typeName": "EngineAction", + "superTypeNames": [ + "Action", + "Process", + "Asset", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 2, + "typeDescription": "An engine action that has been created to support the active governance of the open metadata ecosystem and/or digital landscape.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "egeriagovernanceengine", + "maintainedBy": [ + "baudotnpa", + "egeriagovernanceengine" + ], + "createTime": "2026-11-09T11:05:13.379+00:00", + "updateTime": "2026-11-09T11:05:17.141+00:00", + "version": 4, + "lastRequestId": "7807c843-3774-40b4-bd2c-31460308ebb9" + }, + "guid": "1de658d3-6af5-4c32-b915-5fb6bd5bb524", + "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": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:13.365+00:00", + "updateTime": "2026-11-09T11:05:13.365+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "bf1d5f61-9d79-41bc-a89a-d863222585ff", + "anchorTypeName": "GovernanceActionProcessInstance", + "anchorDomainName": "Asset" + } + } + }, + "properties": { + "class": "EngineActionProperties", + "typeName": "EngineAction", + "qualifiedName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9:processStep1::16383ead-5a2b-480b-a1fe-cfb1b9e422bf", + "displayName": "provision-subscription (EgeriaGovernance)", + "description": "Governance Action Service that provisions the data identified in a digital subscription to the requested destination.", + "requestedStartTime": "2026-11-09T11:05:13.136+00:00", + "startTime": "2026-11-09T11:05:17.104+00:00", + "activityStatus": "IN_PROGRESS", + "domainIdentifier": 8, + "executorEngineGUID": "81d0292d-f074-41e3-93ec-dbecc45cc0c1", + "executorEngineName": "EgeriaGovernance", + "processName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9@1794222312842::77bd32e3-074f-4405-98c0-8df53021a9df", + "processStepGUID": "83306c9d-d122-48bb-8861-519cf03ddc2b", + "processStepName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9:processStep1", + "requesterUserId": "baudotnpa", + "requestType": "provision-subscription", + "requestParameters": { + "topLevelProcessLineageOnly": "true" + }, + "processingEngineUserId": "egeriagovernanceengine" + } + }, + "relatedElementAtEnd1": false + } + ], "governedBy": [ { "class": "RelatedMetadataElementSummary", @@ -215,6 +355,108 @@ "relatedElementAtEnd1": false } ], + "anchoredElements": [ + { + "elementHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "c976d88a-2b11-4b40-b972-c38d41bfc6be", + "typeName": "EngineAction", + "superTypeNames": [ + "Action", + "Process", + "Asset", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 2, + "typeDescription": "An engine action that has been created to support the active governance of the open metadata ecosystem and/or digital landscape.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "egeriagovernanceengine", + "maintainedBy": [ + "baudotnpa", + "egeriagovernanceengine" + ], + "createTime": "2026-11-09T11:05:13.379+00:00", + "updateTime": "2026-11-09T11:05:17.141+00:00", + "version": 4, + "lastRequestId": "7807c843-3774-40b4-bd2c-31460308ebb9" + }, + "guid": "1de658d3-6af5-4c32-b915-5fb6bd5bb524", + "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": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:13.365+00:00", + "updateTime": "2026-11-09T11:05:13.365+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "bf1d5f61-9d79-41bc-a89a-d863222585ff", + "anchorTypeName": "GovernanceActionProcessInstance", + "anchorDomainName": "Asset" + } + } + }, + "properties": { + "class": "EngineActionProperties", + "typeName": "EngineAction", + "qualifiedName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9:processStep1::16383ead-5a2b-480b-a1fe-cfb1b9e422bf", + "displayName": "provision-subscription (EgeriaGovernance)", + "description": "Governance Action Service that provisions the data identified in a digital subscription to the requested destination.", + "requestedStartTime": "2026-11-09T11:05:13.136+00:00", + "startTime": "2026-11-09T11:05:17.104+00:00", + "activityStatus": "IN_PROGRESS", + "domainIdentifier": 8, + "executorEngineGUID": "81d0292d-f074-41e3-93ec-dbecc45cc0c1", + "executorEngineName": "EgeriaGovernance", + "processName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9@1794222312842::77bd32e3-074f-4405-98c0-8df53021a9df", + "processStepGUID": "83306c9d-d122-48bb-8861-519cf03ddc2b", + "processStepName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9:processStep1", + "requesterUserId": "baudotnpa", + "requestType": "provision-subscription", + "requestParameters": { + "topLevelProcessLineageOnly": "true" + }, + "processingEngineUserId": "egeriagovernanceengine" + } + } + ], "relationships": [ { "class": "RelatedMetadataNodeSummary", @@ -476,6 +718,557 @@ }, "relatedElementAtEnd1": false, "startingElementGUID": "1de658d3-6af5-4c32-b915-5fb6bd5bb524" + }, + { + "class": "RelatedMetadataNodeSummary", + "relationshipHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "a0b7ba50-4c97-4b76-9a7d-c6a00e1be646", + "typeName": "ActionRequester", + "superTypeNames": [ + "LineageRelationship", + "LabeledRelationship" + ], + "typeVersion": 2, + "typeDescription": "The source of the action, such as a person, meeting or a governance action.", + "typeCategory": "RELATIONSHIP_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:14.327+00:00", + "updateTime": "2026-11-09T11:05:14.327+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "guid": "070c3f4b-3899-41ab-95b3-02d93ac26a02" + }, + "relatedElement": { + "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": "e8e06304-2eb9-4ebe-bb8c-1ae44635244b", + "homeMetadataCollectionName": "OpenMetadataDigitalProductsContentPack", + "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": 1790859400371 + }, + "guid": "fed3e17d-6aa0-4959-8af4-a2cbfde1717b", + "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": "e8e06304-2eb9-4ebe-bb8c-1ae44635244b", + "homeMetadataCollectionName": "OpenMetadataDigitalProductsContentPack" + }, + "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": 1790859400371 + }, + "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-07T16:19:11.579+00:00", + "updateTime": "2026-11-09T00:18:04.593+00:00", + "version": 13, + "lastRequestId": "5736f99b-3be0-4707-bd0f-d18943a85043" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "UsageActivity", + "classificationProperties": { + "class": "UsageActivityProperties", + "typeName": "UsageActivity", + "explicitGetCount": 68, + "findCount": 516, + "updatePropertyCount": 0, + "updateAttachmentCount": 67, + "updateFeedbackCount": 0, + "deleteAttachmentCount": 0, + "deleteFeedbackCount": 0 + } + } + }, + "properties": { + "class": "IntegrationConnectorProperties", + "typeName": "IntegrationConnector", + "qualifiedName": "Egeria:IntegrationGroup:Jacquard::BaudotDigitalProductSubscriptionManagerIntegrationConnector", + "displayName": "BaudotDigitalProductSubscriptionManagerIntegrationConnector", + "description": "Notifies the subscribers of the digital products' notification types, on its refresh cycle and as their monitored resources change.", + "versionIdentifier": "6.3-SNAPSHOT", + "category": "Egeria-Supplied Connectors", + "resourceName": "org.odpi.openmetadata.adapters.connectors.baudot.BaudotSubscriptionManagementProvider", + "deployedImplementationType": "Integration Connector", + "activityStatus": "IN_PROGRESS" + } + }, + "relatedElementAtEnd1": true, + "startingElementGUID": "1de658d3-6af5-4c32-b915-5fb6bd5bb524" + }, + { + "class": "RelatedMetadataNodeSummary", + "relationshipHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "a0b7ba50-4c97-4b76-9a7d-c6a00e1be646", + "typeName": "ActionRequester", + "superTypeNames": [ + "LineageRelationship", + "LabeledRelationship" + ], + "typeVersion": 2, + "typeDescription": "The source of the action, such as a person, meeting or a governance action.", + "typeCategory": "RELATIONSHIP_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:15.883+00:00", + "updateTime": "2026-11-09T11:05:15.883+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "guid": "5342dbf4-07db-4e63-95a2-9ed274c8e72f" + }, + "relatedElement": { + "elementHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "206a6e44-ffe7-408b-8e59-79842d362776", + "typeName": "GovernanceActionProcessInstance", + "superTypeNames": [ + "TransientEmbeddedProcess", + "EmbeddedProcess", + "Action", + "Process", + "Asset", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "Represents a single run of a governance action process. It is linked to the parent governance action process using the GovernedBy relationship.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "egeriagovernanceengine", + "maintainedBy": [ + "baudotnpa", + "egeriagovernanceengine" + ], + "createTime": "2026-11-09T11:05:12.882+00:00", + "updateTime": "2026-11-09T11:05:17.237+00:00", + "version": 4, + "lastRequestId": "7807c843-3774-40b4-bd2c-31460308ebb9" + }, + "guid": "bf1d5f61-9d79-41bc-a89a-d863222585ff", + "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": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:12.871+00:00", + "updateTime": "2026-11-09T11:05:12.871+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "33884dcc-c0b8-455e-8991-52c704a84d46", + "anchorTypeName": "ProvisioningActionProcess", + "anchorDomainName": "AuthoredReferenceable" + } + } + }, + "properties": { + "class": "GovernanceActionProcessInstanceProperties", + "typeName": "GovernanceActionProcessInstance", + "qualifiedName": "ProvisioningActionProcess::provisioningGovernanceActionType::95ff50a4-13fe-4479-90f2-22d4c9c48ad9@1794222312842::77bd32e3-074f-4405-98c0-8df53021a9df", + "displayName": "provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026", + "requestedTime": "2026-11-09T11:05:12.842+00:00", + "requestedStartTime": "2026-11-09T11:05:13.136+00:00", + "startTime": "2026-11-09T11:05:17.104+00:00", + "activityStatus": "IN_PROGRESS" + } + }, + "relatedElementAtEnd1": true, + "startingElementGUID": "1de658d3-6af5-4c32-b915-5fb6bd5bb524" + }, + { + "class": "RelatedMetadataNodeSummary", + "relationshipHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "207e2594-e3e4-4be8-a12c-4c401656e241", + "typeName": "ActionTarget", + "typeVersion": 1, + "typeDescription": "Associates an action with one or more elements to work on.", + "typeCategory": "RELATIONSHIP_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "baudotnpa", + "updatedBy": "baudotnpa", + "maintainedBy": [ + "baudotnpa" + ], + "createTime": "2026-11-09T11:05:15.260+00:00", + "updateTime": "2026-11-09T11:05:15.260+00:00", + "version": 1, + "lastRequestId": "669900de-7c7d-4916-8290-815f1547fd78" + }, + "guid": "52d9d7d6-9416-4a03-96f4-2a4bdb1e2d31" + }, + "relationshipProperties": { + "class": "ActionTargetProperties", + "typeName": "ActionTarget", + "actionTargetName": "sourceDataSet" + }, + "relatedElement": { + "elementHeader": { + "class": "ElementHeader", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "8f5614c5-1777-4760-a500-07e60ba29746", + "typeName": "TabularDataSetCollection", + "superTypeNames": [ + "DataSet", + "DataAsset", + "Asset", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "Collection of related tabular data sets, not necessarily stored together.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "erinoverview", + "updatedBy": "erinoverview", + "maintainedBy": [ + "erinoverview" + ], + "createTime": "2026-11-07T15:31:54.666+00:00", + "updateTime": "2026-11-07T15:31:54.666+00:00", + "version": 1, + "lastRequestId": "73251768-0a0d-4e83-90ae-74e63799ec6d", + "lastOperationId": "3d835fcb-4a32-4e87-8c0c-85479ca7300c" + }, + "guid": "1c365ba1-9f05-4e4c-accc-98fe576ad098", + "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": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "erinoverview", + "updatedBy": "erinoverview", + "maintainedBy": [ + "erinoverview" + ], + "createTime": "2026-11-07T15:31:54.658+00:00", + "updateTime": "2026-11-07T15:31:54.658+00:00", + "version": 1, + "lastRequestId": "73251768-0a0d-4e83-90ae-74e63799ec6d" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "73568c6c-284d-4ed8-ae85-67b58d5be49c", + "anchorTypeName": "DigitalProduct", + "anchorDomainName": "AuthoredReferenceable" + } + }, + "dataScope": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "22f996d0-c4b7-433a-af0b-6a3e9478e488", + "typeName": "DataScope", + "typeVersion": 2, + "typeDescription": "Identifies the scope of the data stored in the digital resource(s).", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "egeriagovernanceengine", + "updatedBy": "egeriagovernanceengine", + "maintainedBy": [ + "egeriagovernanceengine" + ], + "createTime": "2026-11-07T15:54:52.953+00:00", + "updateTime": "2026-11-07T16:29:10.552+00:00", + "version": 2, + "lastRequestId": "04d483a5-ddbc-42c1-8875-0abb1fd8afcf" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "DataScope", + "classificationProperties": { + "class": "DataScopeProperties", + "typeName": "DataScope", + "additionalProperties": { + "analysisTime": "2026-11-07T16:16:45Z", + "lastReadInWindow": "2026-11-07T08:19:38Z", + "readersInWindow": "2", + "readsPerDay": "0.54", + "analysisWindowEnd": "2026-11-07T16:16:45Z", + "readsInWindow": "16", + "analysisService": "open-lineage-data-scope-governance-service", + "analysisWindowStart": "2026-10-08T16:16:45Z" + } + } + }, + "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-07T15:43:30.365+00:00", + "updateTime": "2026-11-09T00:31:03.962+00:00", + "version": 9, + "lastRequestId": "5736f99b-3be0-4707-bd0f-d18943a85043" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "UsageActivity", + "classificationProperties": { + "class": "UsageActivityProperties", + "typeName": "UsageActivity", + "explicitGetCount": 1, + "findCount": 30, + "updatePropertyCount": 0, + "updateAttachmentCount": 0, + "updateFeedbackCount": 0, + "deleteAttachmentCount": 0, + "deleteFeedbackCount": 0 + } + }, + "dataAssetEncoding": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "3f6a1513-d3ea-4666-b5fd-c76477b0245e", + "typeName": "DataAssetEncoding", + "typeVersion": 1, + "typeDescription": "Description for how data is organized and represented in a data asset.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "erinoverview", + "updatedBy": "erinoverview", + "maintainedBy": [ + "erinoverview" + ], + "createTime": "2026-11-07T15:31:54.662+00:00", + "updateTime": "2026-11-07T15:31:54.662+00:00", + "version": 1, + "lastRequestId": "73251768-0a0d-4e83-90ae-74e63799ec6d", + "lastOperationId": "3d835fcb-4a32-4e87-8c0c-85479ca7300c" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "DataAssetEncoding", + "classificationProperties": { + "class": "DataAssetEncodingProperties", + "typeName": "DataAssetEncoding", + "encodingType": "relational", + "encodingLanguage": "SQL" + } + } + }, + "properties": { + "class": "TabularDataSetCollectionProperties", + "typeName": "TabularDataSetCollection", + "qualifiedName": "PostgreSQL Tabular Data Set Collection::Coco PostgreSQL Server 1::coco_data_hub.goods_inventory_stock", + "displayName": "coco_data_hub.goods_inventory_stock", + "description": "The stock of materials and finished goods at every location: the current position, the movements that produced it, and the issues of material to manufacturing with their quarantine status. It also carries serialised finished goods once they are commissioned.", + "versionIdentifier": "V1.0", + "deployedImplementationType": "PostgreSQL Tabular Data Set Collection", + "contentStatus": "ACTIVE" + } + }, + "relatedElementAtEnd1": false, + "startingElementGUID": "1de658d3-6af5-4c32-b915-5fb6bd5bb524" } ], "mermaidGraph": "---\ntitle: GovernanceActionProcessInstance - provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026 [bf1d5f61-9d79-41bc-a89a-d863222585ff]\n---\nflowchart TD\n%%{init: {\"flowchart\": {\"htmlLabels\": false}} }%%\n\n1@{ shape: rounded, label: \"*Governance Action Process Instance*\n**provisioningGovernanceActionType@Mon Nov 09 11:05:12 GMT 2026**\"}\n2@{ shape: trap-t, label: \"*Engine Action*\n**provision-subscription (EgeriaGovernance)**\"}\n1==>|\"Action Requester\"|2\n3@{ shape: processes, label: \"*Provisioning Action Process*\n**provisioningGovernanceActionType**\"}\n1==>|\"Governed By\"|3\nstyle 1 color:#000000, fill:#e0ab18, stroke:#004563\nstyle 2 color:#000000, fill:#7fffd4, stroke:#000000\nstyle 3 color:#000000, fill:#40E0D0, stroke:#000000\n", diff --git a/tests/micro-tests/test_asset_graph_spec.py b/tests/micro-tests/test_asset_graph_spec.py index 5a4f38a1..b3c14aa5 100644 --- a/tests/micro-tests/test_asset_graph_spec.py +++ b/tests/micro-tests/test_asset_graph_spec.py @@ -1,4 +1,6 @@ -"""The Asset-Graph report spec renders Egeria's asset graph in every format it declares (6.2.28). +"""The Asset-Graph report spec gives each output format a shape that fits a graph (6.2.28): +DICT/TABLE an edge table, LIST the nodes, REPORT/MD/HTML the asset summary with its graph and +edge table, MERMAID the graph, JSON the full response. Recorded input: `data/asset_graph_by_guid_response.json`, one AssetCatalog.get_asset_graph_by_guid response from qs-view-server (read only). The executor tests run the real path, @@ -22,9 +24,23 @@ RECORDED = json.loads((Path(__file__).parent / "data" / "asset_graph_by_guid_response.json").read_text())["response"] GUID = RECORDED["elementHeader"]["guid"] NAME = RECORDED["properties"]["displayName"] -DECLARED = ["DICT", "TABLE", "JSON", "REPORT", "HTML", "MERMAID"] -GRAPH_COLUMNS = {"Mermaid Graph": "mermaidGraph", "Anchor Graph": "anchorMermaidGraph", - "Action Graph": "actionMermaidGraph"} +DECLARED = ["DICT", "TABLE", "LIST", "REPORT", "MD", "HTML", "JSON", "MERMAID"] +EDGE_KEYS = ["From Display Name", "From Type", "From GUID", "Relationship", "To Display Name", "To Type", + "To GUID"] + +# The recorded graph's edges, read off the response by hand (end1 -> end2). The asset's own +# ActionRequester appears both in `relationships` and in `requestedActions`: one edge. +GAPI, ENGINE, CONNECTOR = "bf1d5f61-9d79-41bc-a89a-d863222585ff", "1de658d3-6af5-4c32-b915-5fb6bd5bb524", \ + "fed3e17d-6aa0-4959-8af4-a2cbfde1717b" +PROCESS, STOCK, STAGING = "33884dcc-c0b8-455e-8991-52c704a84d46", "1c365ba1-9f05-4e4c-accc-98fe576ad098", \ + "408e542a-272d-4773-ba9b-4cea3d539f01" +EXPECTED_EDGES = { + (GAPI, "GovernedBy", PROCESS), # the asset's own relationship (governedBy) + (GAPI, "ActionRequester", ENGINE), # in requestedActions and in relationships + (CONNECTOR, "ActionRequester", ENGINE), + (ENGINE, "ActionTarget", STOCK), + (ENGINE, "ActionTarget", STAGING), +} class _Response: @@ -77,76 +93,109 @@ def _run(fmt): user="tester", user_pass="unused") -def test_the_spec_declares_exactly_the_graph_formats_and_the_corrected_key(): +def test_the_spec_declares_a_shape_per_format_and_no_form_or_all(): spec = brf.base_report_specs["Asset-Graph"] - types = sorted(t for f in spec.formats for t in f.types) - assert types == sorted(DECLARED) + assert sorted(t for f in spec.formats for t in f.types) == sorted(DECLARED) + by_type = {t: f for f in spec.formats for t in f.types} + assert [c.name for c in by_type["DICT"].attributes] == EDGE_KEYS + assert [c.name for c in by_type["LIST"].attributes] == ["Display Name", "Type", "GUID", "Role"] keys = {c.key for f in spec.formats for c in f.attributes} - assert "anchorMermaidGRaph" not in keys - assert {"mermaidGraph", "anchorMermaidGraph", "actionMermaidGraph"} <= keys + assert "anchorMermaidGRaph" not in keys and "anchorMermaidGraph" in keys assert spec.action.function == "AssetCatalog.get_asset_graph_by_guid" assert spec.action.required_params == ["guid"] @pytest.mark.parametrize("fmt", ["DICT", "TABLE"]) -def test_dict_and_table_are_one_row_the_asset_itself_with_its_graphs(offline_asset_catalog, fmt): +def test_dict_and_table_are_one_row_per_edge(offline_asset_catalog, fmt): result = _run(fmt) assert result["kind"] == "json" rows = result["data"] - assert isinstance(rows, list) and len(rows) == 1 # the asset, not its related elements - row = rows[0] - assert row["GUID"] == GUID and row["Display Name"] == NAME - for column, key in GRAPH_COLUMNS.items(): - assert row[column] == RECORDED[key], column + assert all(list(r.keys()) == EDGE_KEYS for r in rows) + assert {(r["From GUID"], r["Relationship"], r["To GUID"]) for r in rows} == EXPECTED_EDGES + assert len(rows) == len(EXPECTED_EDGES) # each relationship once + names = {r["From GUID"]: (r["From Display Name"], r["From Type"]) for r in rows} + assert names[GAPI] == (NAME, "GovernanceActionProcessInstance") + assert not any("mermaid" in str(v) or "flowchart" in str(v) for r in rows for v in r.values()) assert offline_asset_catalog and offline_asset_catalog[0][1].endswith(f"/assets/{GUID}/as-graph") -def test_json_is_the_raw_graph(offline_asset_catalog): - result = _run("JSON") - assert result["kind"] == "json" and result["data"]["mermaidGraph"] == RECORDED["mermaidGraph"] +def test_edge_order_is_deterministic_whatever_order_egeria_returns(): + from pyegeria.view import asset_graph + shuffled = copy.deepcopy(RECORDED) + shuffled["relationships"].reverse() + shuffled = dict(reversed(list(shuffled.items()))) + assert asset_graph.graph_edges(shuffled) == asset_graph.graph_edges(RECORDED) + +def test_list_is_the_nodes(offline_asset_catalog): + result = _run("LIST") + assert result["kind"] == "text" + content = result["content"] + assert "| Display Name | Type | GUID | Role |" in content + for guid in (GAPI, ENGINE, CONNECTOR, PROCESS, STOCK, STAGING): + assert content.count(guid) == 1, guid + assert f"| {NAME} | GovernanceActionProcessInstance | {GAPI} | asset |" in content + assert "| anchored |" in content and "```mermaid" not in content -def test_report_carries_the_asset_fields_and_every_graph(offline_asset_catalog): - result = _run("REPORT") - assert result["kind"] == "text" and result["content"] + +@pytest.mark.parametrize("fmt", ["REPORT", "MD"]) +def test_report_and_md_are_the_summary_the_graph_and_the_edge_table(offline_asset_catalog, fmt): + result = _run(fmt) + assert result["kind"] == "text" content = result["content"] - assert NAME in content and GUID in content - assert content.count("```mermaid") == len(GRAPH_COLUMNS) - for column in GRAPH_COLUMNS: - assert f"### {column}" in content, column + assert content.startswith(f"# Asset Graph: {NAME}") + assert "## Asset" in content and f"| GUID | {GUID} |" in content + assert "## Graph" in content and content.count("```mermaid") == 3 # graph, anchor graph, action graph + assert f"## Relationships ({len(EXPECTED_EDGES)})" in content + assert "| " + " | ".join(EDGE_KEYS) + " |" in content + # Architect P3: a by-GUID fetch is not a search. + assert "search string" not in content and "Members" not in content -def test_html_carries_the_graphs(offline_asset_catalog): +def test_html_is_the_report_rendered(offline_asset_catalog): result = _run("HTML") assert result["kind"] == "text" and result["mime"] == "text/html" - assert "mermaid" in result["content"] and NAME in result["content"] + content = result["content"] + assert " 1 or not any("```mermaid" in str(v) for v in result["data"][0].values()) + + +def test_a_graph_with_no_edges_has_an_empty_edge_table_and_says_so(): + from pyegeria.view import asset_graph + lone = {k: v for k, v in RECORDED.items() if k not in ("relationships", "governedBy", "requestedActions")} + assert asset_graph.graph_edges(lone) == [] + assert "## Relationships (0)" in asset_graph.render(lone, "REPORT") + assert "No relationships." in asset_graph.render(lone, "REPORT") From 9b0fffef10e1ed9d38e1bcf1cbe3a69983dbcbd4 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 12:59:53 +0000 Subject: [PATCH 6/6] feat(view): Asset-Graph declares DICT/JSON for code, REPORT/HTML/MERMAID for people The Architect's choice, accepted by the owner. Supersedes the edge table of 5fbc3c44. - Asset-Graph no longer declares TABLE. A TABLE (or LIST, MD, FORM, ALL) request is refused with words naming the declared formats; a named NO_TABLE_FALLBACK set stops the generic TABLE->DICT fallback for this spec only. - DICT is the asset itself with its graph fields; JSON is the full graph response; REPORT and HTML render the asset's fields and graphs; MERMAID is the graph. - pyegeria/view/asset_graph.py is trimmed to the edge/node helpers kept for the Wave 3 edge-table spec; no spec uses them yet (tested directly). - Keeps the P3 fix: a fetch by GUID no longer says "search string"; a search REPORT still names its search string. - Tests, docs and the 6.2.28 note updated; the note says the edge table is planned as its own spec in Wave 3. Signed-off-by: Dan Wolfson --- docs/output-formats-and-report-specs.md | 12 +- docs/release-notes/6.2.28.md | 22 ++-- pyegeria/omvs/asset_catalog.py | 18 +-- pyegeria/view/asset_graph.py | 100 ++------------- pyegeria/view/base_report_formats.py | 41 +++--- pyegeria/view/output_formatter.py | 16 ++- tests/micro-tests/test_asset_graph_spec.py | 139 +++++++++++---------- 7 files changed, 135 insertions(+), 213 deletions(-) diff --git a/docs/output-formats-and-report-specs.md b/docs/output-formats-and-report-specs.md index ead72470..ec5a454e 100644 --- a/docs/output-formats-and-report-specs.md +++ b/docs/output-formats-and-report-specs.md @@ -1258,18 +1258,16 @@ Read it left to right: *the check* (1, names), *the thing named* (`ServerClient. 6.2.28 fixed both, as the words pointed: `Asset-Graph` now calls `AssetCatalog.get_asset_graph_by_guid` (parameter `guid`), and `Data-Classes` calls `DataDesigner.find_data_value_specifications` with `metadata_element_subtypes=["DataClass"]` (a DataClass is a DataValueSpecification subtype and shares its search). -**A graph has a shape per output format (`Asset-Graph`, 6.2.28).** A graph is not a list of elements, so `Asset-Graph` does not render one row per element, and never one row holding mermaid text. Each format it declares gets the shape that fits it (`pyegeria/view/asset_graph.py`): +**What `Asset-Graph` returns (6.2.28).** It declares DICT and JSON for code, and REPORT, HTML and MERMAID for people: | Output format | Shape | |---|---| -| `DICT`, `TABLE` | One row per edge: `From Display Name`, `From Type`, `From GUID`, `Relationship`, `To Display Name`, `To Type`, `To GUID`. The asset's own relationships are included, each relationship is listed once (by relationship GUID), and rows are sorted, so their order does not depend on Egeria's. Paging (`start_from`, `page_size`) is Egeria's, on the graph request. | -| `LIST` | The nodes, as a markdown table: `Display Name`, `Type`, `GUID`, `Role` (`asset`, `anchored`, `related`). | -| `REPORT`, `MD` | The asset summary, its graph (plus the anchor and action graphs when Egeria returns them) as mermaid, and the edge table. | -| `HTML` | The `REPORT` document rendered to HTML. | -| `MERMAID` | The graph. | +| `DICT` | One row: the asset itself, with its own fields and its graph fields (`Mermaid Graph`, `Anchor Graph`, `Action Graph`, `Field Level Lineage Graph`) as text. | | `JSON` | The full graph response. | +| `REPORT`, `HTML` | The asset's fields, with the asset, anchor and action graphs rendered as mermaid. A fetch by GUID is not a search, so the report does not say "found from the search string". | +| `MERMAID` | The asset graph. | -`FORM` (a Dr.Egeria update form) and `ALL` are not declared; asking for them is an error that names the declared formats. +`TABLE`, `LIST`, `MD`, `FORM` and `ALL` are not declared, and asking for them is an error that names the declared formats. `Asset-Graph` is in `NO_TABLE_FALLBACK`, so `TABLE` does not fall back to the DICT row: a table of a graph is its edges, and that edge table is planned as its own spec in Wave 3, built by a processor stage (`pyegeria/view/asset_graph.py` holds the edge helper it will use). > **Planned, not shipped.** Report specs held in Egeria itself (synced, cached and addressed as `egeria:...`) are being built in a first stage; see `portal-docs/Internals/report-spec-pipeline-model.md` (v5.5) in egeria-workspaces. This section describes only specs loaded from files, entry points and the runtime registry. diff --git a/docs/release-notes/6.2.28.md b/docs/release-notes/6.2.28.md index 6dc32f44..fc0233fc 100644 --- a/docs/release-notes/6.2.28.md +++ b/docs/release-notes/6.2.28.md @@ -10,16 +10,18 @@ `DataDesigner.find_data_value_specifications` restricted to the `DataClass` subtype (`metadata_element_subtypes=["DataClass"]`). The load-time census is now 437 specs: 376 runnable, 61 format-only, none unrunnable (6.2.27: 374 runnable, 2 unrunnable). -- **`Asset-Graph` gives each output format a shape that fits a graph.** DICT and TABLE are an - edge table: one row per edge, with the from element (display name, type, GUID), the relationship - type, and the to element. It includes the asset's own relationships, lists each relationship - once, and is sorted, so the order is deterministic. LIST is the nodes. REPORT and MD are the - asset summary, its graph(s) as mermaid and the edge table; HTML renders that. MERMAID is the - graph. JSON is the full graph response. No format returns one row of mermaid text. A by-GUID - REPORT no longer says "found from the search string". FORM and ALL are not declared; asking - for them is an error that names the declared formats. The anchor graph's misspelt column key - (`anchorMermaidGRaph`) is corrected. +- **`Asset-Graph` renders the asset graph.** It declares DICT and JSON for code, and REPORT, + HTML and MERMAID for people. DICT is one row, the asset itself with its own fields and its graph + fields. JSON is the full graph response. REPORT and HTML show the asset's fields with its + asset, anchor and action graphs rendered as mermaid. MERMAID is the asset graph. The anchor + graph's misspelt column key (`anchorMermaidGRaph`) is corrected, and an Action Graph column is + added. TABLE, LIST, MD, FORM and ALL are not declared; asking for them is an error that names + the declared formats, and TABLE does not fall back to the DICT row (`NO_TABLE_FALLBACK`). A table + of a graph is its edges; that edge table is planned as its own spec in Wave 3. +- **A REPORT names a search string only when there was one.** A fetch by GUID, or a find with no + search string, no longer says "found from the search string: `All`" (or `Members`). - **HTML output renders markdown tables.** The HTML renderer had GFM tables switched off, so a - markdown table in a REPORT came out as text; it is now a table. + markdown table in a REPORT came out as text, although the page's CSS styles tables; it is now + a table. - **`exec_report_spec` no longer returns `None` when a find method raises `ValueError`.** It logs the error and raises it, so the caller sees the words. diff --git a/pyegeria/omvs/asset_catalog.py b/pyegeria/omvs/asset_catalog.py index 53b6681a..d359a379 100644 --- a/pyegeria/omvs/asset_catalog.py +++ b/pyegeria/omvs/asset_catalog.py @@ -177,20 +177,10 @@ def _generate_asset_output(self, elements: dict | list[dict], filter_string: Opt def _generate_asset_graph_output(self, elements: dict | list[dict], filter_string: Optional[str] = None, element_type_name: Optional[str] = None, output_format: str = "DICT", report_spec: dict | str | None = None, **kwargs) -> str | list[dict]: - """Shape an asset graph for `output_format` (pyegeria/view/asset_graph.py): DICT/TABLE one row - per edge, LIST the nodes, REPORT/MD/HTML the asset summary with its graph and edge table. - MERMAID (the graph) and any other format take the generic asset path.""" - from pyegeria.view import asset_graph - - shaped = asset_graph.render(elements, output_format) - if shaped is None: - return self._generate_asset_output(elements, filter_string, element_type_name, output_format, - report_spec, **kwargs) - if isinstance(report_spec, str) and isinstance(shaped, str): - # Provenance footer for an Egeria-held spec on REPORT/MD/HTML (RS-EGERIA-TIER §7a). - from pyegeria.view.base_report_formats import add_spec_footer - shaped = add_spec_footer(shaped, report_spec, output_format) - return shaped + """Output for get_asset_graph_by_guid: the generic asset output, without a search string. A fetch + by GUID is not a search, so its REPORT does not say "found from the search string" (6.2.28).""" + return self._generate_asset_output(elements, None, element_type_name, output_format, report_spec, + **kwargs) @dynamic_catch async def _async_find_in_asset_domain( diff --git a/pyegeria/view/asset_graph.py b/pyegeria/view/asset_graph.py index 38eac6d7..c063a438 100644 --- a/pyegeria/view/asset_graph.py +++ b/pyegeria/view/asset_graph.py @@ -2,27 +2,18 @@ SPDX-License-Identifier: Apache-2.0 Copyright Contributors to the ODPi Egeria project. -Shapes for an Egeria asset graph (AssetCatalog.get_asset_graph_by_guid, the `Asset-Graph` report -spec), one per output format (pyegeria 6.2.28): +Edges and nodes of an Egeria asset graph (the response of AssetCatalog.get_asset_graph_by_guid). -- DICT / TABLE: one row per edge: the from element (display name, type, GUID), the relationship - type, and the to element (display name, type, GUID). Includes the asset's own relationships. -- LIST: the nodes, as a markdown table: the asset, the elements anchored to it, and every element - an edge reaches. -- REPORT / MD: the asset summary, its graph (mermaid) and the edge table, as markdown. HTML is the - same document rendered to HTML. -- MERMAID: the graph (handled by the generic mermaid path; see AssetCatalog). -- JSON: the full graph response, unchanged. - -A graph is never one row of mermaid text. +A helper kept for the planned Wave 3 edge-table spec (a processor stage that turns a graph into one +row per edge). No report spec uses it yet: `Asset-Graph` declares DICT and JSON for code and REPORT, +HTML and MERMAID for people (6.2.28). How the response holds edges: `relationships` lists the edges among the asset and its anchored elements, each with `startingElementGUID` (one end), `relatedElement` (the other end) and `relatedElementAtEnd1` (which end that is). The asset's own relationships are keyed lists at the top level (for example `governedBy`, `requestedActions`), each item a `relatedElement` with `relatedElementAtEnd1`, the asset being the other end. An edge reported twice (the same -relationship GUID) is listed once. Rows are sorted, so the order never depends on the order Egeria -returned them in. Paging (`start_from`, `page_size`) is Egeria's, on the graph request. +relationship GUID) is listed once, and rows are sorted, so the order never depends on Egeria's. Pure functions: no I/O, no client. """ @@ -30,7 +21,7 @@ from typing import Any, Dict, List, Optional, Tuple -#: DICT/TABLE row keys, in column order: the edge table. +#: Edge row keys, in column order. EDGE_COLUMNS: List[Tuple[str, str]] = [ ("From Display Name", "from_display_name"), ("From Type", "from_type"), @@ -41,7 +32,7 @@ ("To GUID", "to_guid"), ] -#: LIST columns: the node table. +#: Node keys, in column order. NODE_COLUMNS: List[Tuple[str, str]] = [ ("Display Name", "display_name"), ("Type", "type_name"), @@ -49,25 +40,6 @@ ("Role", "role"), ] -#: The REPORT/MD asset summary: (label, how to read it from the asset element). -_SUMMARY_FIELDS = [ - ("Display Name", ("properties", "displayName")), - ("Qualified Name", ("properties", "qualifiedName")), - ("Description", ("properties", "description")), - ("Type", ("elementHeader", "type", "typeName")), - ("GUID", ("elementHeader", "guid")), - ("Created By", ("elementHeader", "versions", "createdBy")), - ("Create Time", ("elementHeader", "versions", "createTime")), - ("Updated By", ("elementHeader", "versions", "updatedBy")), - ("Update Time", ("elementHeader", "versions", "updateTime")), - ("Version", ("elementHeader", "versions", "version")), -] - -#: The graphs the REPORT shows, in order, when the response carries them. -_REPORT_GRAPHS = [("Graph", "mermaidGraph"), ("Anchor Graph", "anchorMermaidGraph"), - ("Action Graph", "actionMermaidGraph"), ("Field Level Lineage Graph", "fieldLevelLineageGraph")] - - def _dig(obj: Any, path) -> Any: for key in path: if not isinstance(obj, dict): @@ -158,61 +130,3 @@ def order(r): for r in out: r.pop("_relationship_guid") return out - - -def _md_cell(value: Any) -> str: - return str(value if value is not None else "").replace("|", "\\|").replace("\n", " ") - - -def _md_table(columns: List[str], rows: List[Dict[str, Any]]) -> str: - lines = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)] - lines += ["| " + " | ".join(_md_cell(r.get(c)) for c in columns) + " |" for r in rows] - return "\n".join(lines) - - -def render_nodes_list(graph: Dict[str, Any]) -> str: - """LIST: the nodes as a markdown table.""" - nodes = graph_nodes(graph) - rows = [{label: n[key] for label, key in NODE_COLUMNS} for n in nodes] - name = nodes[0]["display_name"] or nodes[0]["guid"] - return f"### Asset Graph nodes: {name} ({len(nodes)})\n\n" + _md_table([c for c, _ in NODE_COLUMNS], rows) + "\n" - - -def render_report(graph: Dict[str, Any]) -> str: - """REPORT/MD: the asset summary, its graph(s) and the edge table, as markdown.""" - from pyegeria.view.output_formatter import _format_mermaid_value - - asset = _node(graph) - name = asset["display_name"] or asset["guid"] - parts = [f"# Asset Graph: {name}", "", "## Asset", ""] - summary = [(label, _dig(graph, path)) for label, path in _SUMMARY_FIELDS] - parts.append(_md_table(["Property", "Value"], - [{"Property": label, "Value": value} for label, value in summary - if value not in (None, "")])) - for title, key in _REPORT_GRAPHS: - if graph.get(key): - parts += ["", f"## {title}", "", _format_mermaid_value(graph[key])] - edges = graph_edges(graph) - parts += ["", f"## Relationships ({len(edges)})", ""] - parts.append(_md_table([c for c, _ in EDGE_COLUMNS], edges) if edges else "No relationships.") - return "\n".join(parts) + "\n" - - -def render(graph: Any, output_format: str) -> Any: - """The shape for `output_format` (DICT, TABLE, LIST, REPORT, MD, HTML), or None when this module - has no shape for it (the caller uses its generic path). A list of graphs is shaped one by one: - rows concatenated, documents joined.""" - fmt = (output_format or "").upper() - if fmt not in {"DICT", "TABLE", "LIST", "REPORT", "MD", "HTML"}: - return None - graphs = graph if isinstance(graph, list) else [graph] - graphs = [g for g in graphs if isinstance(g, dict)] - if fmt in {"DICT", "TABLE"}: - return [row for g in graphs for row in graph_edges(g)] - if fmt == "LIST": - return "\n".join(render_nodes_list(g) for g in graphs) - report = "\n".join(render_report(g) for g in graphs) - if fmt == "HTML": - from pyegeria.view.output_formatter import markdown_to_html - return markdown_to_html(report) - return report diff --git a/pyegeria/view/base_report_formats.py b/pyegeria/view/base_report_formats.py index 5ab2c006..73f17f92 100644 --- a/pyegeria/view/base_report_formats.py +++ b/pyegeria/view/base_report_formats.py @@ -628,10 +628,7 @@ def _user_report_specs_dir() -> str: TIME_PARAMETERS = ["as_of_time", "effective_time"] -from pyegeria.view.asset_graph import EDGE_COLUMNS as ASSET_GRAPH_EDGE_COLUMNS # noqa: E402 -from pyegeria.view.asset_graph import NODE_COLUMNS as ASSET_GRAPH_NODE_COLUMNS # noqa: E402 - -#: The Asset-Graph spec's REPORT/MD/HTML/JSON columns: the asset's own fields, then the graphs +#: The Asset-Graph spec's columns: the asset's own fields, then the graphs #: get_asset_graph_by_guid returns at the top level of its response (keys as Egeria writes them). ASSET_GRAPH_COLUMNS = COMMON_COLUMNS + COMMON_METADATA_COLUMNS + [ Column(name="Classifications", key='classifications'), @@ -1425,22 +1422,18 @@ def _user_report_specs_dir() -> str: "(AssetCatalog.get_asset_graph_by_guid)."), annotations={}, # No specific annotations family="AssetCatalog", - # A graph has a shape per output format (6.2.28; pyegeria/view/asset_graph.py): - # - DICT/TABLE: one row per edge (from element, relationship type, to element), the asset's own - # relationships included, sorted, each relationship once; - # - LIST: the nodes (the asset, its anchored elements, every element an edge reaches); - # - REPORT/MD/HTML: the asset summary, its graph(s) and the edge table; - # - MERMAID: the graph; - # - JSON: the full graph response. - # FORM is not declared: it is a Dr.Egeria update form, which a read-only graph does not fit. ALL is - # not declared either, so a format not listed here is an error with words (the executor names the - # declared formats), never a silent None and never one row of mermaid text. + # Declared formats (6.2.28): DICT and JSON for code, REPORT, HTML and MERMAID for people. + # - DICT: the asset itself, one row, with its own fields and its graph fields (as text); + # - JSON: the full graph response; + # - REPORT/HTML: the asset's fields with the asset, anchor and action graphs rendered as mermaid; + # - MERMAID: the asset graph. + # TABLE, LIST, MD, FORM and ALL are not declared: a table of a graph is its edges, which is planned + # as its own spec in Wave 3 (built by a processor stage; pyegeria/view/asset_graph.py holds the + # edge helper); MD and FORM are Dr.Egeria update forms; ALL rendered only the asset's name. A + # format not listed here is an error with words (the executor names the declared formats). formats=[ - Format(types=["DICT", "TABLE"], - attributes=[Column(name=label, key=key) for label, key in ASSET_GRAPH_EDGE_COLUMNS]), - Format(types=["LIST"], - attributes=[Column(name=label, key=key) for label, key in ASSET_GRAPH_NODE_COLUMNS]), - Format(types=["REPORT", "MD", "HTML", "JSON"], attributes=ASSET_GRAPH_COLUMNS), + Format(types=["DICT", "JSON"], attributes=ASSET_GRAPH_COLUMNS), + Format(types=["REPORT", "HTML"], attributes=ASSET_GRAPH_COLUMNS), Format(types=["MERMAID"], attributes=[Column(name="Mermaid Graph", key='mermaidGraph')]), ], action=ActionParameter( @@ -4878,6 +4871,12 @@ def load_egeria_report_specs( return True +#: Specs whose TABLE requests are refused instead of falling back to their DICT format. A table of +#: an asset graph is its edges, not the asset's one DICT row; that edge table is planned as its own +#: spec in Wave 3 (6.2.28). The label is matched with any tier prefix (egeria:/builtin:) removed. +NO_TABLE_FALLBACK = frozenset({"Asset-Graph"}) + + def _select_from_registry(registry: FormatSetDict, kind: str, output_type: str) -> dict | None: # Normalize if output_type is None: @@ -4933,8 +4932,8 @@ def _select_from_registry(registry: FormatSetDict, kind: str, output_type: str) output_struct["formats"] = fmt.dict() return output_struct - # Fallback for TABLE -> DICT - if output_type == "TABLE": + # Fallback for TABLE -> DICT, except for the specs in NO_TABLE_FALLBACK, which refuse TABLE. + if output_type == "TABLE" and split_tier_prefix(resolved_key or kind)[1] not in NO_TABLE_FALLBACK: for fmt in element.formats: if "DICT" in fmt.types: output_struct["formats"] = fmt.dict() diff --git a/pyegeria/view/output_formatter.py b/pyegeria/view/output_formatter.py index d78d2337..5025971b 100644 --- a/pyegeria/view/output_formatter.py +++ b/pyegeria/view/output_formatter.py @@ -480,8 +480,12 @@ def make_preamble(obj_type: str, search_string: str, output_format: str = 'MD') preamble += f"\t {obj_type} found from the search string: `{search_string}`\n\n" return preamble, elements_action elif output_format == "REPORT": - elements_md += (f"# {obj_type} Report - created at {datetime.now().strftime('%Y-%m-%d %H:%M')}\n" - f"\t{obj_type} found from the search string: `{search_string}`\n\n") + elements_md += f"# {obj_type} Report - created at {datetime.now().strftime('%Y-%m-%d %H:%M')}\n" + # A fetch by GUID is not a search: name a search string only when there is one (6.2.28). + if search_string: + elements_md += f"\t{obj_type} found from the search string: `{search_string}`\n\n" + else: + elements_md += "\n" elements_action = None return elements_md, elements_action else: @@ -2275,7 +2279,9 @@ def generate_output(elements: Union[Dict, List[Dict]], if isinstance(elements, dict): elements = [elements] - # Handle empty search string + # Handle empty search string. The REPORT preamble names a search string only when the caller + # searched (a fetch by GUID is not a search; 6.2.28), so remember whether one was given. + searched_for = search_string or None if search_string is None or search_string == '': search_string = "All" @@ -2293,7 +2299,7 @@ def generate_output(elements: Union[Dict, List[Dict]], elif output_format in ('HTML', 'GRAPH'): report_output = generate_output( elements=elements, - search_string=search_string, + search_string=searched_for, entity_type=entity_type, output_format="REPORT", extract_properties_func=extract_properties_func, @@ -2322,7 +2328,7 @@ def generate_output(elements: Union[Dict, List[Dict]], if include_preamble: elements_md, elements_action = make_preamble( obj_type=target_type, - search_string=search_string, + search_string=searched_for if output_format == "REPORT" else search_string, output_format=output_format ) diff --git a/tests/micro-tests/test_asset_graph_spec.py b/tests/micro-tests/test_asset_graph_spec.py index b3c14aa5..b0b7086c 100644 --- a/tests/micro-tests/test_asset_graph_spec.py +++ b/tests/micro-tests/test_asset_graph_spec.py @@ -1,6 +1,8 @@ -"""The Asset-Graph report spec gives each output format a shape that fits a graph (6.2.28): -DICT/TABLE an edge table, LIST the nodes, REPORT/MD/HTML the asset summary with its graph and -edge table, MERMAID the graph, JSON the full response. +"""The Asset-Graph report spec (6.2.28): DICT and JSON for code, REPORT, HTML and MERMAID for people. +DICT is the asset itself with its graph fields, JSON the full graph response, REPORT/HTML the +asset's fields with its graphs rendered, MERMAID the graph. Any other format is refused with words. +The edge helper (pyegeria/view/asset_graph.py), kept for the Wave 3 edge-table spec, is tested +directly at the end, not through the spec. Recorded input: `data/asset_graph_by_guid_response.json`, one AssetCatalog.get_asset_graph_by_guid response from qs-view-server (read only). The executor tests run the real path, @@ -24,7 +26,9 @@ RECORDED = json.loads((Path(__file__).parent / "data" / "asset_graph_by_guid_response.json").read_text())["response"] GUID = RECORDED["elementHeader"]["guid"] NAME = RECORDED["properties"]["displayName"] -DECLARED = ["DICT", "TABLE", "LIST", "REPORT", "MD", "HTML", "JSON", "MERMAID"] +DECLARED = ["DICT", "JSON", "REPORT", "HTML", "MERMAID"] +GRAPH_COLUMNS = {"Mermaid Graph": "mermaidGraph", "Anchor Graph": "anchorMermaidGraph", + "Action Graph": "actionMermaidGraph"} EDGE_KEYS = ["From Display Name", "From Type", "From GUID", "Relationship", "To Display Name", "To Type", "To GUID"] @@ -93,109 +97,118 @@ def _run(fmt): user="tester", user_pass="unused") -def test_the_spec_declares_a_shape_per_format_and_no_form_or_all(): +def test_the_spec_declares_dict_json_report_html_mermaid_and_the_corrected_key(): spec = brf.base_report_specs["Asset-Graph"] assert sorted(t for f in spec.formats for t in f.types) == sorted(DECLARED) - by_type = {t: f for f in spec.formats for t in f.types} - assert [c.name for c in by_type["DICT"].attributes] == EDGE_KEYS - assert [c.name for c in by_type["LIST"].attributes] == ["Display Name", "Type", "GUID", "Role"] keys = {c.key for f in spec.formats for c in f.attributes} - assert "anchorMermaidGRaph" not in keys and "anchorMermaidGraph" in keys + assert "anchorMermaidGRaph" not in keys + assert {"mermaidGraph", "anchorMermaidGraph", "actionMermaidGraph"} <= keys assert spec.action.function == "AssetCatalog.get_asset_graph_by_guid" assert spec.action.required_params == ["guid"] -@pytest.mark.parametrize("fmt", ["DICT", "TABLE"]) -def test_dict_and_table_are_one_row_per_edge(offline_asset_catalog, fmt): - result = _run(fmt) +def test_dict_is_one_row_the_asset_itself_with_its_graph_fields(offline_asset_catalog): + result = _run("DICT") assert result["kind"] == "json" rows = result["data"] - assert all(list(r.keys()) == EDGE_KEYS for r in rows) - assert {(r["From GUID"], r["Relationship"], r["To GUID"]) for r in rows} == EXPECTED_EDGES - assert len(rows) == len(EXPECTED_EDGES) # each relationship once - names = {r["From GUID"]: (r["From Display Name"], r["From Type"]) for r in rows} - assert names[GAPI] == (NAME, "GovernanceActionProcessInstance") - assert not any("mermaid" in str(v) or "flowchart" in str(v) for r in rows for v in r.values()) + assert isinstance(rows, list) and len(rows) == 1 # the asset, not its related elements + row = rows[0] + assert row["GUID"] == GUID and row["Display Name"] == NAME + for column, key in GRAPH_COLUMNS.items(): + assert row[column] == RECORDED[key], column assert offline_asset_catalog and offline_asset_catalog[0][1].endswith(f"/assets/{GUID}/as-graph") -def test_edge_order_is_deterministic_whatever_order_egeria_returns(): - from pyegeria.view import asset_graph - shuffled = copy.deepcopy(RECORDED) - shuffled["relationships"].reverse() - shuffled = dict(reversed(list(shuffled.items()))) - assert asset_graph.graph_edges(shuffled) == asset_graph.graph_edges(RECORDED) - - -def test_list_is_the_nodes(offline_asset_catalog): - result = _run("LIST") - assert result["kind"] == "text" - content = result["content"] - assert "| Display Name | Type | GUID | Role |" in content - for guid in (GAPI, ENGINE, CONNECTOR, PROCESS, STOCK, STAGING): - assert content.count(guid) == 1, guid - assert f"| {NAME} | GovernanceActionProcessInstance | {GAPI} | asset |" in content - assert "| anchored |" in content and "```mermaid" not in content +def test_json_is_the_full_graph(offline_asset_catalog): + result = _run("JSON") + assert result["kind"] == "json" and result["data"] == RECORDED -@pytest.mark.parametrize("fmt", ["REPORT", "MD"]) -def test_report_and_md_are_the_summary_the_graph_and_the_edge_table(offline_asset_catalog, fmt): - result = _run(fmt) - assert result["kind"] == "text" +def test_report_carries_the_asset_fields_and_every_graph(offline_asset_catalog): + result = _run("REPORT") + assert result["kind"] == "text" and result["content"] content = result["content"] - assert content.startswith(f"# Asset Graph: {NAME}") - assert "## Asset" in content and f"| GUID | {GUID} |" in content - assert "## Graph" in content and content.count("```mermaid") == 3 # graph, anchor graph, action graph - assert f"## Relationships ({len(EXPECTED_EDGES)})" in content - assert "| " + " | ".join(EDGE_KEYS) + " |" in content - # Architect P3: a by-GUID fetch is not a search. + assert NAME in content and GUID in content + assert content.count("```mermaid") == len(GRAPH_COLUMNS) + for column in GRAPH_COLUMNS: + assert f"### {column}" in content, column + # Architect P3: a fetch by GUID is not a search. assert "search string" not in content and "Members" not in content -def test_html_is_the_report_rendered(offline_asset_catalog): +def test_html_carries_the_graphs(offline_asset_catalog): result = _run("HTML") assert result["kind"] == "text" and result["mime"] == "text/html" content = result["content"] - assert " 1 or not any("```mermaid" in str(v) for v in result["data"][0].values()) -def test_a_graph_with_no_edges_has_an_empty_edge_table_and_says_so(): +def test_a_search_report_still_names_its_search_string(): + catalog = object.__new__(AssetCatalog) + out = catalog._generate_asset_output(elements=copy.deepcopy(RECORDED), filter_string="orders", + element_type_name="Asset", output_format="REPORT", + report_spec="Asset-Graph") + assert "found from the search string: `orders`" in out + + +def test_other_specs_keep_the_table_to_dict_fallback(): + # Data-Structures declares DICT and neither TABLE nor ALL: TABLE still gets its DICT format. + table = brf.select_report_spec("Data-Structures", "TABLE") + assert table is not None and "DICT" in table["formats"]["types"] + assert brf.select_report_spec("Asset-Graph", "TABLE") is None + assert brf.select_report_spec("builtin:Asset-Graph", "TABLE") is None + + +# ── The edge helper kept for the Wave 3 edge-table spec (not used by Asset-Graph) ── + +def test_edge_helper_lists_each_relationship_once_with_its_direction(): + from pyegeria.view import asset_graph + rows = asset_graph.graph_edges(RECORDED) + assert all(list(r.keys()) == EDGE_KEYS for r in rows) + assert {(r["From GUID"], r["Relationship"], r["To GUID"]) for r in rows} == EXPECTED_EDGES + assert len(rows) == len(EXPECTED_EDGES) + + +def test_edge_helper_order_is_deterministic_whatever_order_egeria_returns(): + from pyegeria.view import asset_graph + shuffled = copy.deepcopy(RECORDED) + shuffled["relationships"].reverse() + shuffled = dict(reversed(list(shuffled.items()))) + assert asset_graph.graph_edges(shuffled) == asset_graph.graph_edges(RECORDED) + + +def test_node_helper_lists_the_asset_first_then_anchored_then_related(): from pyegeria.view import asset_graph - lone = {k: v for k, v in RECORDED.items() if k not in ("relationships", "governedBy", "requestedActions")} - assert asset_graph.graph_edges(lone) == [] - assert "## Relationships (0)" in asset_graph.render(lone, "REPORT") - assert "No relationships." in asset_graph.render(lone, "REPORT") + nodes = asset_graph.graph_nodes(RECORDED) + assert nodes[0]["guid"] == GAPI and nodes[0]["role"] == "asset" + assert {n["guid"] for n in nodes} == {GAPI, ENGINE, CONNECTOR, PROCESS, STOCK, STAGING} + assert [n["role"] for n in nodes] == ["asset", "anchored"] + ["related"] * 4