From 8892d127a3714d9ad74bfaa29409bf8acc4be216 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 14:51:48 +0000 Subject: [PATCH 1/9] feat(dr-egeria): dashboard sheet commands write Egeria 6.3 dashboards (RS-DASH PR-1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Create Dashboard Sheet, Link Report to Dashboard Sheet and Add Text on Dashboard Sheet keep their names and syntax and now write the pipeline note v5.5 §8d chain: Dashboard -Schema-> DisplayDataSchemaType -AttributeForSchema-> DisplayDataContainer -NestedSchemaAttribute(position)-> one DisplayDataField per placement, with DataSetContent (queryId = the placement's qualifiedName), ScopedBy to Trellis Perspectives (DB-2) and DataDescription to the drill-down ReportSpec. Upsert by qualifiedName; a re-run writes nothing. Removing a placement or deleting a sheet never deletes a Report or ReportSpec. DB-1: every command also writes the local JSON store; --local-only (or PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY) or an unreachable Egeria writes the store alone and says so. Create Report writes one reportParameters document (author-written values only), the typed outputFormat, and ReportTypeInstance from the spec element found under ReportSpec:: or ReportType::, with a note when the spec has no element. additionalProperties keys are kept for one release. The Dashboard asset write is shared (upsert_dashboard_asset) by Create Dashboard and Create Dashboard Sheet. DashboardSheetEgeriaWriter is the one Egeria implementation, for the processors and for migration. Signed-off-by: Dan Wolfson --- commands/cat/dr_egeria.py | 7 +- md_processing/dr_egeria.py | 4 +- md_processing/v2/dashboard_sheet.py | 904 +++++++++++++++--- md_processing/v2/report.py | 224 ++++- tests/micro-tests/dashboard_fake_egeria.py | 276 ++++++ .../test_dashboard_sheets_in_egeria.py | 385 ++++++++ .../test_dr_egeria_report_spec_types.py | 1 + 7 files changed, 1631 insertions(+), 170 deletions(-) create mode 100644 tests/micro-tests/dashboard_fake_egeria.py create mode 100644 tests/micro-tests/test_dashboard_sheets_in_egeria.py diff --git a/commands/cat/dr_egeria.py b/commands/cat/dr_egeria.py index a1b7bf6b..6fcd10a0 100644 --- a/commands/cat/dr_egeria.py +++ b/commands/cat/dr_egeria.py @@ -60,12 +60,15 @@ help="Use Advanced usage level — shows additional attributes (default: Basic)") @click.option("--summary-only", is_flag=True, default=False, help="Only display the summary table and errors/warnings") @click.option("--debug", is_flag=True, default=False, help="Print each Egeria API request URL and body to the console") +@click.option("--local-only", is_flag=True, default=False, + help="Dashboard Sheet commands write the local JSON store only, not Egeria " + "(sets PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY)") @logger.catch def process_markdown_file(input_file: str, output_folder: str, directive: str, do_validate: bool, do_process: bool, server: str, url: str, userid: str, user_pass: str, parse_summary: str, attribute_logs: str, advanced: bool, - summary_only: bool, debug: bool) -> None: + summary_only: bool, debug: bool, local_only: bool = False) -> None: """ Process a markdown file by parsing and executing Dr. Egeria md_commands. Write output to a new file. @@ -82,6 +85,8 @@ def process_markdown_file(input_file: str, output_folder: str, directive: str, # else: use --directive as-is (default "validate") usage_level = "Advanced" if advanced else "Basic" + if local_only: + os.environ["PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY"] = "1" try: # Instantiate the client from pyegeria import EgeriaTech diff --git a/md_processing/dr_egeria.py b/md_processing/dr_egeria.py index 20ebaf4a..238eb623 100644 --- a/md_processing/dr_egeria.py +++ b/md_processing/dr_egeria.py @@ -504,8 +504,8 @@ def reg(base, cls): reg("Update Saved Query", SavedQueryProcessor) reg("Link Saved Query to Results Set", SmartQueryLinkProcessor) - # Dashboard Sheets (local pyegeria-only records, not Egeria elements yet -- - # see OVERVIEW_REPORTING_MODEL.md SS10 for the planned Collection-subtype migration) + # Dashboard Sheets: written to Egeria 6.3 as Dashboard -> DisplayDataSchemaType -> DisplayDataContainer + # -> DisplayDataField placements, and to the local JSON store during the transition (dashboard_sheet.py) reg("Create Dashboard Sheet", CreateDashboardSheetProcessor) reg("Link Report to Dashboard Sheet", LinkReportToDashboardSheetProcessor) reg("Add Text on Dashboard Sheet", AddTextOnDashboardSheetProcessor) diff --git a/md_processing/v2/dashboard_sheet.py b/md_processing/v2/dashboard_sheet.py index a2223437..6f57ba29 100644 --- a/md_processing/v2/dashboard_sheet.py +++ b/md_processing/v2/dashboard_sheet.py @@ -1,37 +1,131 @@ """ Dashboard Sheet Processors for Dr.Egeria v2. -Handles `Create Dashboard Sheet` and `Link Report to Dashboard Sheet` -- the -first Dr.Egeria commands that manage a purely local, pyegeria-only record -(see pyegeria.view._output_dashboard_sheet_models.DashboardSheet) instead of -an Egeria element. No OMVS calls are made. - -Design: rather than bypass AsyncBaseCommandProcessor entirely, the base -class's Egeria-lookup primitives (fetch_element / resolve_element_guid) are -overridden to consult a local JSON store instead of Egeria -- so the -inherited create<->update upsert-transition, qualified-name derivation, -caching, and validate/display dry-run machinery all keep working, just -against local data. This is a first version: once Dashboard Sheet becomes a -real Egeria Collection subtype (see OVERVIEW_REPORTING_MODEL.md SS10 and the -"PLANNED" notes on the Dashboard Sheet Base / Report to Dashboard Sheet Link -Base Tinderbox bundles), these processors extend to call real OMVS methods -instead of the local store, without changing the compact command specs. - -Store: PYEGERIA_DASHBOARD_SHEETS_STORE (default ~/.pyegeria/dashboard_sheets.json), -a single JSON file loaded fresh and saved back on every command -- durable -across separate `dr_egeria` invocations, unlike dashboard_sheet_registry.py's -in-memory RUNTIME store (which is for app-level consumers reading a merged -CONFIG+RUNTIME view, not for this authoring path). +Handles `Create Dashboard Sheet`, `Link Report to Dashboard Sheet` and `Add Text on Dashboard Sheet`. The +commands keep their names and syntax. Since Egeria 6.3 (odpi/egeria#9432) they write each sheet into Egeria +as the element chain of the report-spec pipeline note v5.5 §8d / §10.6(c): + + Dashboard (Dashboard::; displayName = the heading) + --Schema--> DisplayDataSchemaType (DashboardSchema::) + --AttributeForSchema--> DisplayDataContainer (DashboardSheet::; the sheet) + --NestedSchemaAttribute(position)--> one DisplayDataField per placement + (DashboardPlacement::::::; + displayName ` / `, see placement_display_name) + + A REPORT placement: placementKind "report", span, presentationStyle; its Report is linked by + DataSetContent from the Dashboard (queryId = the placement's qualifiedName, queryType "placement"). + A TEXT placement: placementKind "text", markdownContent. + Every placement: ScopedBy from each Perspective it names; DataDescription to the ReportSpec it drills + into, when that spec has an element. + +DB-1 (owner, 2026-11-09): during the transition every command writes Egeria AND the local JSON store +(PYEGERIA_DASHBOARD_SHEETS_STORE, default ~/.pyegeria/dashboard_sheets.json). With the local-only switch +(`dr_egeria --local-only`, or PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY=1), or with no Egeria connection, the store +alone is written and the command output says so. + +Every write is an upsert by qualifiedName: re-running a document changes nothing. Removing a placement +detaches its DataSetContent link and deletes its field; deleting a sheet deletes its chain. Neither ever +deletes a Report or a ReportSpec -- a sheet shows reports, it does not own them. + +`DashboardSheetEgeriaWriter` is the one implementation of the Egeria side. The processors use it, and so does +`python -m pyegeria.view.dashboards migrate` (which writes sheets from the JSON store without going through +markdown, so text placements round-trip byte for byte). """ +from __future__ import annotations + import os -from typing import Any, Dict, Optional +from dataclasses import dataclass, field +from typing import Any, Callable, Dict, List, Optional from loguru import logger from md_processing.v2.processors import AsyncBaseCommandProcessor -from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement, DashboardSheetDict +from md_processing.v2.report import ( + REPORT_SPEC_QN_PREFIXES, _props_differ, find_element_by_qualified_name, + find_report_spec_element, upsert_dashboard_asset, +) +from pyegeria.core._exceptions import PyegeriaConnectionException, PyegeriaNotFoundException +from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, DashboardSheetDict, Placement + +LOCAL_ONLY_ENV = "PYEGERIA_DASHBOARD_SHEETS_LOCAL_ONLY" +PLANNED_PREFIX = "planned:" +PAGE_SIZE = 25 + +# ---------------------------------------------------------------------------- qualified names + +DASHBOARD_QN_PREFIX = "Dashboard::" +SCHEMA_QN_PREFIX = "DashboardSchema::" +SHEET_QN_PREFIX = "DashboardSheet::" +PLACEMENT_QN_PREFIX = "DashboardPlacement::" + + +def dashboard_qn(sheet_name: str) -> str: + return f"{DASHBOARD_QN_PREFIX}{sheet_name}" + + +def schema_type_qn(sheet_name: str) -> str: + return f"{SCHEMA_QN_PREFIX}{sheet_name}" + + +def sheet_container_qn(sheet_name: str) -> str: + return f"{SHEET_QN_PREFIX}{sheet_name}" + + +def placement_qn(sheet_name: str, position: int, placement_name: str) -> str: + return f"{PLACEMENT_QN_PREFIX}{sheet_name}::{position}::{placement_name}" + + +def sheet_name_from_dashboard_qn(qualified_name: str) -> Optional[str]: + if qualified_name and qualified_name.startswith(DASHBOARD_QN_PREFIX): + return qualified_name[len(DASHBOARD_QN_PREFIX):] + return None + + +# ---------------------------------------------------------------------------- perspectives (DB-2) + +# Today's sheets use the Overview keys; DB-2 (owner, 2026-11-09) maps them to the Trellis perspective names +# (pipeline note §10.8). The label stays the placement's display value; the mapping only picks the element +# that ScopedBy links to. +PERSPECTIVE_TRELLIS_NAMES = { + "governance": "Governance", + "steward": "Steward", + "owner": "Data Owner", + "consumer": "Consumer", + "builder": "App/AI Builder", + "privacy": "Privacy", + "security": "Security", + "architecture": "Architecture", + "engineer": "Data Expert", + "engineering": "Data Expert", + "community": "Community", + "financial": "Financial", + "admin": "Administration", +} + +# Where a Trellis name and the qualifiedName of the element Trellis actually creates differ. Checked live +# 2026-11-09 (read only, 12 Perspective:: elements): §10.8 calls it "Data Owner", the element is +# Perspective::Owner; "Admin" is Perspective::Administration. +PERSPECTIVE_QN_OVERRIDES = { + "Data Owner": "Perspective::Owner", + "Owner": "Perspective::Owner", + "Admin": "Perspective::Administration", +} + + +def perspective_qualified_name(label: str) -> str: + """The qualifiedName of the Trellis Perspective element a placement's perspective label maps to.""" + text = (label or "").strip() + if text.startswith("Perspective::"): + return text + trellis = PERSPECTIVE_TRELLIS_NAMES.get(text.lower()) + if trellis is None: + # Already a Trellis name ("Steward", "Data Expert", "App/AI Builder"); match it case-insensitively. + trellis = next((v for v in set(PERSPECTIVE_TRELLIS_NAMES.values()) if v.lower() == text.lower()), text) + return PERSPECTIVE_QN_OVERRIDES.get(trellis, f"Perspective::{trellis}") +# ---------------------------------------------------------------------------- helpers + def _default_store_path() -> str: return os.path.expanduser( os.getenv("PYEGERIA_DASHBOARD_SHEETS_STORE", "~/.pyegeria/dashboard_sheets.json") @@ -39,15 +133,9 @@ def _default_store_path() -> str: def _parse_placement_perspectives(attributes: Dict[str, Any]) -> list: - """Read "Placement Perspectives" (BACKLOG.md NEXT-19, egeria-workspaces-fs) - out of a command's parsed attributes -- a "Simple List"-style attribute, - which the base attribute-parsing pipeline may hand back either as an - already-split list or as a raw comma-separated string (both shapes seen - elsewhere for this attribute style, see _normalize_report_params's own - _to_string_list coercion in format_set_executor.py); tolerate either - rather than assume one. Shared by both LinkReportToDashboardSheetProcessor - and AddTextOnDashboardSheetProcessor so the parsing rule lives in one - place, not duplicated per processor.""" + """Read "Placement Perspectives" out of a command's parsed attributes -- a "Simple List"-style + attribute, which the base attribute-parsing pipeline may hand back either as an already-split list or + as a raw comma-separated string; tolerate either.""" value = attributes.get("Placement Perspectives", {}).get("value") or [] if isinstance(value, str): return [p.strip() for p in value.split(",") if p.strip()] @@ -60,45 +148,567 @@ def _load_store(path: str) -> DashboardSheetDict: return DashboardSheetDict() -def _sheet_to_element(sheet: DashboardSheet) -> Dict[str, Any]: - """Wrap a DashboardSheet in a minimal Egeria-elementHeader-shaped dict so - the inherited pipeline's generic `element.get('elementHeader', {})...` - patterns work unmodified against local data.""" +def _truthy(value: Optional[str]) -> bool: + return str(value or "").strip().lower() in ("1", "true", "yes", "on") + + +def _is_guid_like(value: Any) -> bool: + text = str(value or "").strip() + return bool(text) and not text.startswith(("(", "No ")) and " found" not in text + + +def placement_kind(placement: Placement) -> str: + return "text" if placement.content is not None else "report" + + +def placement_display_name(sheet_name: str, placement_name: str) -> str: + """A placement field's displayName: ` / `. + + Not the bare placement name: a REPORT placement is named after its Report, and Dr.Egeria resolves + `Report Name` by displayName across all types, so a field sharing the Report's displayName makes that + lookup ambiguous and the next `Link Report to Dashboard Sheet` fails. The bare name is kept in + additionalProperties `placementName` (and in the qualifiedName). + """ + return f"{sheet_name} / {placement_name}" + + +def field_placement_name(properties: Dict[str, Any]) -> str: + """The bare placement name of a DisplayDataField: `placementName`, else the qualifiedName's last part.""" + extra = properties.get("additionalProperties") or {} + if extra.get("placementName"): + return extra["placementName"] + qn = properties.get("qualifiedName") or "" + if qn.startswith(PLACEMENT_QN_PREFIX): + parts = qn[len(PLACEMENT_QN_PREFIX):].split("::", 2) + if len(parts) == 3: + return parts[2] + return properties.get("displayName") or "" + + +def placement_field_properties(sheet_name: str, position: int, placement: Placement, + qualified_name: Optional[str] = None) -> Dict[str, Any]: + """The DisplayDataField properties for one placement. + + The perspective labels and the drill-down spec name are also kept on the field (additionalProperties + `perspectives`, comma-separated, and `detailSpec`): the ScopedBy / DataDescription links carry the graph + meaning, but only when the element exists, and a label is not recoverable from the element it maps to + ("owner" and "Data Owner" both map to Perspective::Owner). The reader gives back the labels as written. + """ + extra: Dict[str, str] = {"placementName": placement.ref} + if placement.perspectives: + extra["perspectives"] = ",".join(placement.perspectives) + if placement.detail_spec: + extra["detailSpec"] = placement.detail_spec + kind = placement_kind(placement) return { - "elementHeader": {"guid": sheet.name, "type": {"typeName": "DashboardSheet"}}, - "properties": { - "qualifiedName": f"Dashboard::{sheet.name}", - "displayName": sheet.heading, - "description": sheet.description, - }, + "class": "DisplayDataFieldProperties", + "typeName": "DisplayDataField", + "qualifiedName": qualified_name or placement_qn(sheet_name, position, placement.ref), + "displayName": placement_display_name(sheet_name, placement.ref), + "placementKind": kind, + "span": placement.span, + "presentationStyle": placement.emphasis, + "markdownContent": placement.content if kind == "text" else None, + "additionalProperties": extra, } -class CreateDashboardSheetProcessor(AsyncBaseCommandProcessor): - """Processor for Create Dashboard Sheet (and its Update transition).""" +def _field_props_differ(desired: Dict[str, Any], current: Dict[str, Any]) -> bool: + """Like _props_differ, but a property set on the field and now unset also counts as a change (a + placement re-run without perspectives must clear them).""" + if _props_differ(desired, current): + return True + if desired.get("markdownContent") is None and current.get("markdownContent"): + return True + return False - def derive_qualified_name(self, attributes: Optional[Dict[str, Any]] = None) -> str: - """Override the inherited Egeria-style qn_prefix/org/version qualified-name - derivation -- local records are keyed by their plain Display Name, - so that's what fetch_as_is()/resolve_element_guid() need to match against. - 2026-07-31: switched from the family-specific "Dashboard Sheet Name" - attribute to the universal "Display Name" -- Dashboard Sheet Base no - longer carries its own duplicate naming attribute.""" +@dataclass +class SheetChain: + """The GUIDs of one sheet's chain in Egeria. A guid starting `planned:` is one a dry run would create.""" + sheet_name: str + dashboard_guid: Optional[str] = None + schema_type_guid: Optional[str] = None + container_guid: Optional[str] = None + dashboard: Optional[Dict[str, Any]] = None + + +@dataclass +class FieldInfo: + guid: str + qualified_name: str + display_name: str # the bare placement name (field_placement_name), not the field's displayName + position: Optional[int] + properties: Dict[str, Any] = field(default_factory=dict) + + +# ---------------------------------------------------------------------------- the writer + +class DashboardSheetEgeriaWriter: + """Writes Dashboard Sheets into Egeria as the §8d element chain. The one implementation, used by the + Dr.Egeria processors and by migration. + + `notes` collects what a reader of the command output must know (a report or perspective with no + element, a link not written); `actions` records every write made, or with `dry_run=True` every write + that would be made ("create DisplayDataField DashboardPlacement::..."), with "unchanged ..." for elements + already as wanted. A dry run still reads Egeria (bounded, page size 25) but writes nothing. + """ + + def __init__(self, client: Any, *, dry_run: bool = False): + self.client = client + self.dry_run = dry_run + self.notes: List[str] = [] + self.actions: List[str] = [] + self._perspective_cache: Dict[str, Optional[str]] = {} + self._planned = 0 + + # ------------------------------------------------------------ small primitives + + def _note(self, text: str) -> None: + if text not in self.notes: + self.notes.append(text) + + def _plan(self, what: str) -> str: + self._planned += 1 + return f"{PLANNED_PREFIX}{self._planned}:{what}" + + @staticmethod + def _is_planned(guid: Optional[str]) -> bool: + return bool(guid) and str(guid).startswith(PLANNED_PREFIX) + + async def _find(self, qualified_name: str) -> Optional[Dict[str, Any]]: + return await find_element_by_qualified_name(self.client, qualified_name) + + async def _related(self, guid: Optional[str], relationship: str, start_at_end: int = 1) -> List[Dict[str, Any]]: + """Every element related to `guid` by `relationship`, paged at 25. Only an empty page ends the read + (a short page is not the last page).""" + if not guid or self._is_planned(guid): + return [] + out: List[Dict[str, Any]] = [] + start = 0 + while True: + try: + page = await self.client.classification_manager._async_get_related_elements( + guid, relationship, start_at_end=start_at_end, start_from=start, page_size=PAGE_SIZE, + graph_query_depth=0) + except PyegeriaNotFoundException: + page = [] + items = [e for e in page if isinstance(e, dict) and e.get("elementHeader")] if isinstance(page, list) else [] + if not items: + return out + out.extend(items) + start += len(items) + + @staticmethod + def _guid(element: Dict[str, Any]) -> str: + return element["elementHeader"]["guid"] + + @staticmethod + def _type(element: Dict[str, Any]) -> str: + return ((element.get("elementHeader") or {}).get("type") or {}).get("typeName", "") + + @staticmethod + def _rel_props(element: Dict[str, Any]) -> Dict[str, Any]: + return ((element.get("relatedBy") or {}).get("relationshipProperties")) or {} + + def _created_guid(self, raw: Any, what: str) -> str: + if isinstance(raw, str) and raw.strip(): + return raw.strip() + if isinstance(raw, dict) and raw.get("guid"): + return raw["guid"] + raise ValueError(f"Egeria returned no GUID creating {what}: {raw!r}") + + async def _create_schema_element(self, kind: str, props: Dict[str, Any], anchor_guid: Optional[str]) -> str: + """Create a schema type (kind "type") or attribute, anchored to the Dashboard.""" + qn = props["qualifiedName"] + self.actions.append(f"create {props['typeName']} {qn}") + if self.dry_run: + return self._plan(qn) + body = {"class": "NewElementRequestBody", "isOwnAnchor": False, "anchorGUID": anchor_guid, + "properties": props} + maker = self.client.schema_maker + raw = await (maker._async_create_schema_type(body) if kind == "type" + else maker._async_create_schema_attribute(body)) + return self._created_guid(raw, qn) + + async def _update_schema_attribute(self, guid: str, props: Dict[str, Any]) -> None: + self.actions.append(f"update {props['typeName']} {props['qualifiedName']}") + if self.dry_run: + return + await self.client.schema_maker._async_update_schema_attribute( + guid, {"class": "UpdateElementRequestBody", "properties": props, "mergeUpdate": False}) + + # ------------------------------------------------------------ reading the chain (no writes) + + async def find_chain(self, sheet_name: str) -> SheetChain: + """The chain as it is in Egeria; any missing part is None.""" + chain = SheetChain(sheet_name=sheet_name) + dashboard = await self._find(dashboard_qn(sheet_name)) + if not dashboard: + return chain + chain.dashboard = dashboard + chain.dashboard_guid = self._guid(dashboard) + schema_types = [e for e in await self._related(chain.dashboard_guid, "Schema") + if self._type(e) == "DisplayDataSchemaType"] + if schema_types: + wanted = [e for e in schema_types if (e.get("properties") or {}).get("qualifiedName") + == schema_type_qn(sheet_name)] + chain.schema_type_guid = self._guid((wanted or schema_types)[0]) + containers = [e for e in await self._related(chain.schema_type_guid, "AttributeForSchema") + if self._type(e) == "DisplayDataContainer"] + wanted = [e for e in containers if (e.get("properties") or {}).get("qualifiedName") + == sheet_container_qn(sheet_name)] + if containers: + chain.container_guid = self._guid((wanted or containers)[0]) + return chain + + async def list_fields(self, container_guid: Optional[str]) -> List[FieldInfo]: + """The placements under a sheet container, in position order.""" + fields: List[FieldInfo] = [] + for e in await self._related(container_guid, "NestedSchemaAttribute"): + if self._type(e) != "DisplayDataField": + continue + props = e.get("properties") or {} + position = self._rel_props(e).get("position") + fields.append(FieldInfo(guid=self._guid(e), qualified_name=props.get("qualifiedName", ""), + display_name=field_placement_name(props), + position=int(position) if position is not None else None, + properties=props)) + fields.sort(key=lambda f: (f.position is None, f.position or 0)) + return fields + + # ------------------------------------------------------------ sheet + + async def ensure_sheet(self, sheet_name: str, heading: str, description: str = "", + family: Optional[str] = None, aliases: Optional[List[str]] = None) -> SheetChain: + """Create or update the Dashboard, its DisplayDataSchemaType and the sheet's DisplayDataContainer.""" + chain = await self.find_chain(sheet_name) + + # 1. the Dashboard asset -- through upsert_dashboard_asset, the same code as `Create Dashboard` + props: Dict[str, Any] = { + "class": "DashboardProperties", + "typeName": "Dashboard", + "qualifiedName": dashboard_qn(sheet_name), + "displayName": heading or sheet_name, + "description": description or None, + "aliases": list(aliases) if aliases else None, + "additionalProperties": {"family": family} if family else None, + } + if self.dry_run: + if chain.dashboard is None: + self.actions.append(f"create Dashboard {props['qualifiedName']}") + chain.dashboard_guid = self._plan(props["qualifiedName"]) + elif _props_differ(props, chain.dashboard.get("properties") or {}): + self.actions.append(f"update Dashboard {props['qualifiedName']}") + else: + self.actions.append(f"unchanged Dashboard {props['qualifiedName']}") + else: + guid, verb_word, _ = await upsert_dashboard_asset( + self.client, props["qualifiedName"], props, chain.dashboard, + create_body={"class": "NewElementRequestBody", "isOwnAnchor": True}) + chain.dashboard_guid = self._created_guid(guid, props["qualifiedName"]) + self.actions.append(f"{verb_word.lower()} Dashboard {props['qualifiedName']}") + + # 2. its DisplayDataSchemaType, linked by Schema + if chain.schema_type_guid is None: + st_props = {"class": "DisplayDataSchemaTypeProperties", "typeName": "DisplayDataSchemaType", + "qualifiedName": schema_type_qn(sheet_name), "displayName": f"{sheet_name} layout"} + existing = None if self._is_planned(chain.dashboard_guid) else await self._find(st_props["qualifiedName"]) + chain.schema_type_guid = (self._guid(existing) if existing + else await self._create_schema_element("type", st_props, chain.dashboard_guid)) + self.actions.append(f"link Schema {dashboard_qn(sheet_name)} -> {st_props['qualifiedName']}") + if not self.dry_run: + await self.client.schema_maker._async_link_schema(chain.dashboard_guid, chain.schema_type_guid) + else: + self.actions.append(f"unchanged DisplayDataSchemaType {schema_type_qn(sheet_name)}") + + # 3. the sheet's DisplayDataContainer, linked by AttributeForSchema (position 1) + if chain.container_guid is None: + c_props = {"class": "DisplayDataContainerProperties", "typeName": "DisplayDataContainer", + "qualifiedName": sheet_container_qn(sheet_name), "displayName": f"{sheet_name} sheet"} + existing = None if self._is_planned(chain.schema_type_guid) else await self._find(c_props["qualifiedName"]) + chain.container_guid = (self._guid(existing) if existing + else await self._create_schema_element("attribute", c_props, chain.dashboard_guid)) + self.actions.append(f"link AttributeForSchema {schema_type_qn(sheet_name)} -> {c_props['qualifiedName']} (position 1)") + if not self.dry_run: + await self.client.schema_maker._async_link_attribute_for_schema( + chain.schema_type_guid, chain.container_guid, + {"class": "NewRelationshipRequestBody", + "properties": {"class": "AttributeForSchemaProperties", "position": 1}}) + else: + self.actions.append(f"unchanged DisplayDataContainer {sheet_container_qn(sheet_name)}") + return chain + + # ------------------------------------------------------------ placements + + async def _resolve_report(self, report_name: str) -> Optional[str]: + """The GUID of the Report a placement shows, by display name or qualified name (the same lookup + Dr.Egeria uses for `Report Name`). None if there is none.""" + try: + res = await self.client.__async_get_guid__(qualified_name=report_name, display_name=report_name, + property_name="displayName", tech_type="Report") + except PyegeriaNotFoundException: + return None + if isinstance(res, str) and res and not res.startswith("No ") and " found" not in res: + return res + return None + + async def _perspective_guid(self, label: str) -> Optional[str]: + qn = perspective_qualified_name(label) + if qn not in self._perspective_cache: + element = await self._find(qn) + self._perspective_cache[qn] = self._guid(element) if element else None + return self._perspective_cache[qn] + + async def upsert_placement(self, chain: SheetChain, placement: Placement, *, + position: Optional[int] = None, + report_guid: Optional[str] = None) -> str: + """Create or update one placement's DisplayDataField and its links. Found by name within the sheet + (a re-run with the same name updates in place; its qualifiedName and position never change).""" + sheet = chain.sheet_name + fields = await self.list_fields(chain.container_guid) + existing = next((f for f in fields if f.display_name == placement.ref), None) + + if existing: + pos = existing.position if existing.position is not None else (position or 0) + props = placement_field_properties(sheet, pos, placement, existing.qualified_name) + field_guid = existing.guid + if _field_props_differ(props, existing.properties): + await self._update_schema_attribute(field_guid, props) + else: + self.actions.append(f"unchanged DisplayDataField {existing.qualified_name}") + else: + taken = [f.position for f in fields if f.position is not None] + pos = position if position is not None else (max(taken) + 1 if taken else 1) + props = placement_field_properties(sheet, pos, placement) + found = None if self._is_planned(chain.container_guid) else await self._find(props["qualifiedName"]) + if found: + field_guid = self._guid(found) + if _field_props_differ(props, found.get("properties") or {}): + await self._update_schema_attribute(field_guid, props) + else: + field_guid = await self._create_schema_element("attribute", props, chain.dashboard_guid) + self.actions.append(f"link NestedSchemaAttribute {sheet_container_qn(sheet)} -> {props['qualifiedName']} (position {pos})") + if not self.dry_run: + await self.client.schema_maker._async_link_nested_schema_attribute( + chain.container_guid, field_guid, + {"class": "NewRelationshipRequestBody", + "properties": {"class": "NestedSchemaAttributeProperties", "position": pos}}) + + qn = props["qualifiedName"] + await self._sync_report_link(chain, placement, qn, report_guid) + await self._sync_perspectives(field_guid, placement) + await self._sync_detail_spec(field_guid, placement) + return field_guid + + async def _sync_report_link(self, chain: SheetChain, placement: Placement, qn: str, + report_guid: Optional[str]) -> None: + """DataSetContent Dashboard -> Report, queryId = the placement's qualifiedName.""" + binding: Dict[str, Any] = {"state": "unbound", "links": []} + if not self._is_planned(chain.dashboard_guid): + bindings = await self.client.asset_maker._async_get_placement_reports(chain.dashboard_guid, [qn]) + binding = (bindings or {}).get(qn) or binding + if placement_kind(placement) == "text": + if binding["links"]: + await self._detach_report(chain, qn, "the placement is text now") + return + if report_guid and not _is_guid_like(report_guid): + report_guid = None # "(Planned: ...)" or a not-found string from attribute resolution + if report_guid is None: + report_guid = await self._resolve_report(placement.ref) + if not report_guid: + self._note(f"Report '{placement.ref}' was not found in Egeria: placement '{placement.ref}' on sheet " + f"'{chain.sheet_name}' was written without its report link, and reads as missing until a " + f"Report with that name exists and the command is run again.") + if binding["links"]: + await self._detach_report(chain, qn, "its report is gone") + return + if binding.get("state") == "bound" and binding.get("report_guid") == report_guid: + self.actions.append(f"unchanged DataSetContent {dashboard_qn(chain.sheet_name)} -> {placement.ref} [{qn}]") + return + if binding["links"]: + await self._detach_report(chain, qn, "it showed a different report") + self.actions.append(f"link DataSetContent {dashboard_qn(chain.sheet_name)} -> Report '{placement.ref}' " + f"(queryId {qn})") + if not self.dry_run: + await self.client.asset_maker._async_link_placement_report(chain.dashboard_guid, report_guid, qn) + + async def _detach_report(self, chain: SheetChain, qn: str, why: str) -> None: + self.actions.append(f"detach DataSetContent for {qn} ({why})") + if not self.dry_run: + await self.client.asset_maker._async_detach_placement_report(chain.dashboard_guid, qn) + + async def _sync_perspectives(self, field_guid: str, placement: Placement) -> None: + """ScopedBy Perspective -> placement, one per label whose Trellis element exists. Never creates a + Perspective: a label with no element is written without that link, with a note.""" + wanted: Dict[str, str] = {} + for label in placement.perspectives: + guid = await self._perspective_guid(label) + if guid: + wanted[guid] = label + else: + self._note(f"Perspective '{label}' (as {perspective_qualified_name(label)}) does not exist in " + f"Egeria: placement '{placement.ref}' was written without that ScopedBy link. " + f"Perspectives are not created here.") + current = {self._guid(e) for e in await self._related(field_guid, "ScopedBy", start_at_end=2) + if self._type(e) == "Perspective"} + for guid in current - set(wanted): + self.actions.append(f"detach ScopedBy {guid} -> {placement.ref}") + if not self.dry_run: + await self.client.classification_manager._async_clear_scope_from_element(guid, field_guid) + for guid, label in wanted.items(): + if guid in current: + continue + self.actions.append(f"link ScopedBy {perspective_qualified_name(label)} -> {placement.ref}") + if not self.dry_run: + await self.client.classification_manager._async_add_scope_to_element(guid, field_guid) + + async def _sync_detail_spec(self, field_guid: str, placement: Placement) -> None: + """DataDescription placement -> the ReportSpec it drills into, when the spec has an element.""" + wanted: Optional[str] = None + if placement.detail_spec: + element = await find_report_spec_element(self.client, placement.detail_spec) + if element: + wanted = self._guid(element) + else: + self._note(f"Drill-down spec '{placement.detail_spec}' of placement '{placement.ref}' has no Egeria " + f"element (looked for {' and '.join(p + placement.detail_spec for p in REPORT_SPEC_QN_PREFIXES)}): " + f"no DataDescription link was written; the name is kept on the placement.") + current = {self._guid(e) for e in await self._related(field_guid, "DataDescription", start_at_end=1)} + for guid in current - ({wanted} if wanted else set()): + self.actions.append(f"detach DataDescription {placement.ref} -> {guid}") + if not self.dry_run: + await self.client.collection_manager._async_detach_data_description(field_guid, guid) + if wanted and wanted not in current: + self.actions.append(f"link DataDescription {placement.ref} -> {placement.detail_spec}") + if not self.dry_run: + await self.client.collection_manager._async_attach_data_description(field_guid, wanted) + + # ------------------------------------------------------------ whole sheets, removal + + async def write_sheet(self, sheet: DashboardSheet) -> SheetChain: + """Write a whole sheet (migration): the chain, then every placement at its 1-based position.""" + chain = await self.ensure_sheet(sheet.name, sheet.heading, sheet.description, sheet.family, sheet.aliases) + for index, placement in enumerate(sheet.placements, start=1): + if isinstance(placement, dict): + placement = Placement(**placement) + await self.upsert_placement(chain, placement, position=index) + return chain + + async def remove_placement(self, sheet_name: str, placement_name: str) -> bool: + """Detach a placement's DataSetContent link and delete its field. Never deletes the Report. + False if the sheet or placement is not in Egeria.""" + chain = await self.find_chain(sheet_name) + fields = await self.list_fields(chain.container_guid) + target = next((f for f in fields if f.display_name == placement_name), None) + if not target: + return False + await self._detach_report(chain, target.qualified_name, "placement removed") + self.actions.append(f"delete DisplayDataField {target.qualified_name}") + if not self.dry_run: + await self.client.schema_maker._async_delete_schema_attribute(target.guid) + return True + + async def delete_sheet(self, sheet_name: str) -> bool: + """Delete a sheet's chain: each placement (link, then field), the container, the schema type, the + Dashboard. Reports and ReportSpecs are never deleted. False if the Dashboard is not in Egeria.""" + chain = await self.find_chain(sheet_name) + if not chain.dashboard_guid: + return False + for f in await self.list_fields(chain.container_guid): + await self._detach_report(chain, f.qualified_name, "sheet deleted") + self.actions.append(f"delete DisplayDataField {f.qualified_name}") + if not self.dry_run: + await self.client.schema_maker._async_delete_schema_attribute(f.guid) + if chain.container_guid: + self.actions.append(f"delete DisplayDataContainer {sheet_container_qn(sheet_name)}") + if not self.dry_run: + await self.client.schema_maker._async_delete_schema_attribute(chain.container_guid) + if chain.schema_type_guid: + self.actions.append(f"delete DisplayDataSchemaType {schema_type_qn(sheet_name)}") + if not self.dry_run: + await self.client.schema_maker._async_delete_schema_type(chain.schema_type_guid) + self.actions.append(f"delete Dashboard {dashboard_qn(sheet_name)}") + if not self.dry_run: + await self.client.asset_maker._async_delete_asset(chain.dashboard_guid) + return True + + +# ---------------------------------------------------------------------------- processors + +def local_only_reason(processor: AsyncBaseCommandProcessor) -> Optional[str]: + """Why this command writes the local store alone, or None when it writes Egeria too (DB-1).""" + if processor.context.get("dashboard_sheets_local_only"): + return "--local-only was given" + if _truthy(os.getenv(LOCAL_ONLY_ENV)): + return f"{LOCAL_ONLY_ENV} is set" + if processor.client is None: + return "there is no Egeria connection" + return None + + +def _egeria_section(writer: Optional[DashboardSheetEgeriaWriter], local_reason: Optional[str]) -> str: + if local_reason: + return f"\n- **Egeria**: not written ({local_reason}); the local store alone was written.\n" + lines = ["\n- **Egeria**: written"] + if writer is not None: + changed = [a for a in writer.actions if not a.startswith("unchanged")] + lines[0] += f" ({len(changed)} change(s))" if changed else " (no change: already as written)" + for note in writer.notes: + lines.append(f" - Note: {note}") + return "\n".join(lines) + "\n" + + +class _DashboardSheetProcessorMixin: + """Shared Egeria plumbing for the three sheet commands.""" + + async def _with_egeria(self, work: Callable[[DashboardSheetEgeriaWriter], Any]): + """Run `work` against Egeria unless the command is local-only. Returns (writer, local_reason). + An unreachable Egeria falls back to the store alone and says so; any other Egeria error fails the + command (and the store is then not written, so the two stay consistent).""" + reason = local_only_reason(self) + if reason: + return None, reason + writer = DashboardSheetEgeriaWriter(self.client) + try: + await work(writer) + except PyegeriaConnectionException as e: + return None, f"Egeria could not be reached ({e.__class__.__name__})" + for note in writer.notes: + self._add_warning(note) + return writer, None + + +class CreateDashboardSheetProcessor(_DashboardSheetProcessorMixin, AsyncBaseCommandProcessor): + """Processor for Create Dashboard Sheet (and its Update transition). + + The target is the Egeria Dashboard `Dashboard::` (or, local-only, the store record). + The Dashboard asset itself is written by `upsert_dashboard_asset`, the same code as `Create Dashboard`. + """ + + def derive_qualified_name(self, attributes: Optional[Dict[str, Any]] = None) -> str: if attributes is None: attributes = self.parsed_output.get("attributes", {}) - return attributes.get("Display Name", {}).get("value") or "" + name = attributes.get("Display Name", {}).get("value") or "" + return dashboard_qn(name) if name else "" - async def resolve_element_guid(self, name_or_guid: str, tech_type: Optional[str] = None) -> Optional[str]: - if not name_or_guid: + async def fetch_as_is(self) -> Optional[Dict[str, Any]]: + name = self.parsed_output.get("attributes", {}).get("Display Name", {}).get("value") + if not name: return None - sheets = _load_store(_default_store_path()) - return name_or_guid if name_or_guid in sheets else None - - async def fetch_element(self, guid: str) -> Optional[Dict[str, Any]]: - sheets = _load_store(_default_store_path()) - sheet = sheets.get(guid) - return _sheet_to_element(sheet) if sheet else None + if local_only_reason(self) is None: + try: + element = await find_element_by_qualified_name(self.client, dashboard_qn(name)) + except PyegeriaConnectionException: + element = None + if element: + return element + sheet = _load_store(_default_store_path()).get(name) + if sheet: + return {"elementHeader": {"guid": f"local:{sheet.name}", "type": {"typeName": "DashboardSheet"}}, + "properties": {"qualifiedName": dashboard_qn(sheet.name), "displayName": sheet.heading, + "description": sheet.description}} + return None async def apply_changes(self) -> str: attributes = self.parsed_output["attributes"] @@ -111,41 +721,57 @@ async def apply_changes(self) -> str: path = _default_store_path() sheets = _load_store(path) + aliases = list(sheets[name].aliases) if name in sheets else [] + + async def _work(writer: DashboardSheetEgeriaWriter): + chain = await writer.ensure_sheet(name, heading, description, family, aliases) + self.parsed_output["guid"] = chain.dashboard_guid + + writer, local_reason = await self._with_egeria(_work) + is_update = name in sheets sheets.upsert(name, DashboardSheet(name=name, heading=heading, description=description, family=family)) sheets.save_to_json(path) + if local_reason: + self.parsed_output["guid"] = name - self.parsed_output["guid"] = name verb_word = "Updated" if is_update else "Created" - logger.success(f"{verb_word} Dashboard Sheet '{name}' at {path}") + logger.success(f"{verb_word} Dashboard Sheet '{name}' (local store {path}; Egeria: " + f"{'not written, ' + local_reason if local_reason else 'written'})") return ( f"\n\n## {self.command.verb} Dashboard Sheet\n\n" f"{verb_word} Dashboard Sheet **{name}**\n\n" f"- **Heading**: {heading}\n" f"- **Description**: {description or '_(none)_'}\n" f"- **Family**: {family or '_(none)_'}\n" + f"- **Local store**: {path}" + f"{_egeria_section(writer, local_reason)}" ) -class LinkReportToDashboardSheetProcessor(AsyncBaseCommandProcessor): +async def _placement_chain(writer: DashboardSheetEgeriaWriter, sheet_name: str, + local_sheet: Optional[DashboardSheet]) -> SheetChain: + """The sheet's chain for a placement command. A sheet held only in the local store (made before its + commands wrote Egeria) is written to Egeria whole first, so the Egeria sheet is never a partial copy.""" + chain = await writer.find_chain(sheet_name) + if chain.container_guid: + return chain + if local_sheet is None: + raise ValueError(f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with " + f"'Create Dashboard Sheet'.") + writer._note(f"Dashboard Sheet '{sheet_name}' was only in the local store; it was written to Egeria " + f"whole ({len(local_sheet.placements)} placement(s)) before this placement.") + return await writer.write_sheet(local_sheet) + + +class LinkReportToDashboardSheetProcessor(_DashboardSheetProcessorMixin, AsyncBaseCommandProcessor): """ - Processor for Link Report to Dashboard Sheet -- places a Report (a real - Egeria `Report` asset created via `Create Report`, carrying a Report Spec - reference plus its own default execution parameters) into a Dashboard - Sheet as an ordered Placement. The target Dashboard Sheet must already - exist (created via Create Dashboard Sheet). - - Hard cutover 2026-07-29: this used to place a bare Report Spec (FormatSet) - name directly -- switched to referencing a Report element by name instead, - since a Report Spec has no way to carry fixed/scoped parameters (see - egeria-workspaces-fs BACKLOG.md NEXT-14). `Report Name` is a Reference - Name-style attribute, so the base class's generic attribute-resolution - pipeline (step 5 of execute()) already resolves it against Egeria and - populates `.get("guid")` -- used here only for a best-effort "does this - Report actually exist yet" warning, not required for the placement - record itself (which still stores the plain name as `Placement.ref`, - resolved later by the consuming app, same as the old Report Spec-ref - scheme). + Processor for Link Report to Dashboard Sheet -- places a Report (an Egeria `Report` asset created via + `Create Report`) on a Dashboard Sheet as an ordered placement. In Egeria: a DisplayDataField with + placementKind "report", linked to the Report by the Dashboard's DataSetContent (queryId = the + placement's qualifiedName); ScopedBy to its perspectives; DataDescription to its drill-down spec. In the + local store: a Placement whose `ref` is the report's name. Re-running with the same Report Name + updates the placement in place. """ async def fetch_as_is(self) -> Optional[Dict[str, Any]]: @@ -161,8 +787,6 @@ async def apply_changes(self) -> str: report_guid = attributes.get("Report Name", {}).get("guid") span = attributes.get("Placement Span", {}).get("value") or "1" emphasis = attributes.get("Placement Emphasis", {}).get("value") or "kpi" - # BACKLOG.md NEXT-19/NEXT-21 (egeria-workspaces-fs). "Placement Detail - # Spec" is a plain optional string, same pattern as report_name. perspectives = _parse_placement_perspectives(attributes) detail_spec = attributes.get("Placement Detail Spec", {}).get("value") or None @@ -171,33 +795,33 @@ async def apply_changes(self) -> str: if not report_name: raise ValueError("Report Name is required.") - if not report_guid: - self._add_warning( - f"Report '{report_name}' was not found in Egeria — the placement will be " - f"unresolved until a Report with that name exists (create one with 'Create Report')." - ) - path = _default_store_path() sheets = _load_store(path) sheet = sheets.get(sheet_name) - if not sheet: - raise ValueError( - f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with 'Create Dashboard Sheet'." - ) + placement = Placement(ref=report_name, span=span, emphasis=emphasis, + perspectives=perspectives, detail_spec=detail_spec) - placement = Placement( - ref=report_name, span=span, emphasis=emphasis, - perspectives=perspectives, detail_spec=detail_spec, - ) - replaced = False - for i, p in enumerate(sheet.placements): - if p.ref == report_name: - sheet.placements[i] = placement - replaced = True - break - if not replaced: - sheet.placements.append(placement) + async def _work(writer: DashboardSheetEgeriaWriter): + chain = await _placement_chain(writer, sheet_name, sheet) + await writer.upsert_placement(chain, placement, report_guid=report_guid) + + writer, local_reason = await self._with_egeria(_work) + if local_reason and not report_guid: + self._add_warning( + f"Report '{report_name}' was not found in Egeria — the placement will be " + f"unresolved until a Report with that name exists (create one with 'Create Report')." + ) + if not sheet: + if local_reason: + raise ValueError(f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with " + f"'Create Dashboard Sheet'.") + # Held in Egeria only (made elsewhere): start its local copy so the store stays a full fallback. + sheet = DashboardSheet(name=sheet_name, heading=sheet_name) + sheets[sheet_name] = sheet + sheet = sheets.get(sheet_name) + + replaced = _put_placement(sheet, placement) sheets.save_to_json(path) verb_word = "Updated placement of" if replaced else "Placed" logger.success(f"{verb_word} Report '{report_name}' in Dashboard Sheet '{sheet_name}'") @@ -211,18 +835,27 @@ async def apply_changes(self) -> str: f"\n\n## {self.command.verb} Report to Dashboard Sheet\n\n" f"{verb_word} **{report_name}** in Dashboard Sheet **{sheet_name}** " f"(span={span}, emphasis={emphasis}{extra_str})\n" + f"{_egeria_section(writer, local_reason)}" ) -class AddTextOnDashboardSheetProcessor(AsyncBaseCommandProcessor): +def _put_placement(sheet: DashboardSheet, placement: Placement) -> bool: + """Replace the placement with the same ref, or append it. True if replaced.""" + for i, p in enumerate(sheet.placements): + ref = p.get("ref") if isinstance(p, dict) else p.ref + if ref == placement.ref: + sheet.placements[i] = placement + return True + sheet.placements.append(placement) + return False + + +class AddTextOnDashboardSheetProcessor(_DashboardSheetProcessorMixin, AsyncBaseCommandProcessor): """ - Processor for Place Text on Dashboard Sheet -- places literal markdown - text (a section header, explanation, or caption) into a Dashboard Sheet - as an ordered Placement, alongside Report placements. Not an Egeria - element or relationship, and unlike Report placements, `Placement Name` - isn't a Reference Name-style attribute either -- there's nothing in - Egeria to resolve, it's purely the local replace-by-name key (same role - `Report Name` plays for a Report placement's `Placement.ref`). + Processor for Add Text on Dashboard Sheet -- places literal markdown text (a section header, + explanation or caption) on a Dashboard Sheet as an ordered placement, alongside report placements. In + Egeria: a DisplayDataField with placementKind "text" and markdownContent. `Placement Name` is the + placement's name (its displayName, and the local replace-by-name key). """ async def fetch_as_is(self) -> Optional[Dict[str, Any]]: @@ -238,10 +871,6 @@ async def apply_changes(self) -> str: content = attributes.get("MD Content", {}).get("value") span = attributes.get("Placement Span", {}).get("value") or "1" emphasis = attributes.get("Placement Emphasis", {}).get("value") or "kpi" - # BACKLOG.md NEXT-19 (egeria-workspaces-fs) -- a text placement (e.g. a - # section header) can be perspective-scoped too, not just a Report - # placement; no detail_spec here, a text block has no result to drill - # into. perspectives = _parse_placement_perspectives(attributes) if not sheet_name: @@ -254,24 +883,23 @@ async def apply_changes(self) -> str: path = _default_store_path() sheets = _load_store(path) sheet = sheets.get(sheet_name) - if not sheet: - raise ValueError( - f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with 'Create Dashboard Sheet'." - ) + placement = Placement(ref=placement_name, span=span, emphasis=emphasis, content=content, + perspectives=perspectives) - placement = Placement( - ref=placement_name, span=span, emphasis=emphasis, content=content, - perspectives=perspectives, - ) - replaced = False - for i, p in enumerate(sheet.placements): - if p.ref == placement_name: - sheet.placements[i] = placement - replaced = True - break - if not replaced: - sheet.placements.append(placement) + async def _work(writer: DashboardSheetEgeriaWriter): + chain = await _placement_chain(writer, sheet_name, sheet) + await writer.upsert_placement(chain, placement) + writer, local_reason = await self._with_egeria(_work) + + if not sheet: + if local_reason: + raise ValueError(f"Dashboard Sheet '{sheet_name}' does not exist. Create it first with " + f"'Create Dashboard Sheet'.") + sheets[sheet_name] = DashboardSheet(name=sheet_name, heading=sheet_name) + sheet = sheets.get(sheet_name) + + replaced = _put_placement(sheet, placement) sheets.save_to_json(path) verb_word = "Updated" if replaced else "Placed" logger.success(f"{verb_word} text placement '{placement_name}' in Dashboard Sheet '{sheet_name}'") @@ -280,4 +908,14 @@ async def apply_changes(self) -> str: f"\n\n## {self.command.verb} Text on Dashboard Sheet\n\n" f"{verb_word} text placement **{placement_name}** in Dashboard Sheet **{sheet_name}** " f"(span={span}, emphasis={emphasis}{extra_str})\n" + f"{_egeria_section(writer, local_reason)}" ) + + +__all__ = [ + "AddTextOnDashboardSheetProcessor", "CreateDashboardSheetProcessor", "DashboardSheetEgeriaWriter", + "FieldInfo", "LinkReportToDashboardSheetProcessor", "LOCAL_ONLY_ENV", "PERSPECTIVE_QN_OVERRIDES", + "PERSPECTIVE_TRELLIS_NAMES", "SheetChain", "dashboard_qn", "field_placement_name", "local_only_reason", "perspective_qualified_name", + "placement_display_name", "placement_field_properties", "placement_kind", "placement_qn", "schema_type_qn", "sheet_container_qn", + "sheet_name_from_dashboard_qn", +] diff --git a/md_processing/v2/report.py b/md_processing/v2/report.py index f22613b6..f47fba4e 100644 --- a/md_processing/v2/report.py +++ b/md_processing/v2/report.py @@ -6,10 +6,11 @@ odpi/egeria-project.ai/types/2/0239-Reports) carrying a Report Spec reference plus optional default execution parameters (Output Format, Search String, and the rest of the same 22-attribute vocabulary -`View Report` already supports ad-hoc). Short-term design: everything -beyond the base Referenceable properties lands in `additionalProperties` --- no dedicated `ReportDefinition` subtype yet (see egeria-workspaces-fs -BACKLOG.md NEXT-14). `Link Report to Dashboard Sheet` then references a +`View Report` already supports ad-hoc). Egeria 6.3 (odpi/egeria#9432) gives +Report a typed `outputFormat`, one `reportParameters` JSON document and the +`ReportTypeInstance` link from its spec; all three are written. The older +`additionalProperties` keys are still written for one release, because +today's Portal reads them. `Link Report to Dashboard Sheet` then references a Report by its `Report Name` instead of a bare Report Spec name, giving a Dashboard Sheet placement a concrete, parameterized instance to run instead of an unparameterized template. @@ -35,11 +36,21 @@ from loguru import logger +from pyegeria.core._exceptions import PyegeriaNotFoundException + from md_processing.v2.processors import AsyncBaseCommandProcessor from md_processing.md_processing_utils.common_md_utils import ( set_create_body, set_element_prop_body, update_element_dictionary, ) +# Report specs are held in Egeria under two qualified-name prefixes (pipeline note v5.5 §7a hazard): +# `ReportSpec::` from Create Report Spec, and `ReportType::` from the older report-type content. +REPORT_SPEC_QN_PREFIXES = ("ReportSpec::", "ReportType::") + +# `Report Spec` / `Output Format` have typed homes; everything else in _REPORT_PARAM_ATTRS goes into the +# one reportParameters document. +_TYPED_REPORT_KEYS = {"reportSpec", "outputFormat"} + # The 22 report-execution-parameter attributes (same set View Report exposes # ad-hoc) -- short-term, all of these land in additionalProperties rather # than typed Report fields. camelCase keys distinguish them from anything a @@ -110,6 +121,47 @@ def _snake_to_camel(snake: str) -> str: return parts[0] + "".join(p[:1].upper() + p[1:] for p in parts[1:] if p) +def _camel_to_snake(camel: str) -> str: + """camelCase -> snake_case (`searchString` -> `search_string`, `asOfTime` -> `as_of_time`).""" + out = [] + for ch in camel: + if ch.isupper(): + out.append("_" + ch.lower()) + else: + out.append(ch) + return "".join(out).lstrip("_") + + +def report_parameters_document(attributes: Dict[str, Any]) -> Dict[str, Any]: + """The one parameter document a Report carries in Egeria 6.3's `reportParameters` (pipeline note §8d). + + Today's `Create Report` holds parameters three ways; they collapse into one JSON object of snake_case + parameter names, which is what a spec's declared `required_params`/`optional_params` use: + 1. the common find attributes (`Search String`, `Page Size`, ...), authoring sugar; + 2. the `Report Parameters` map, as typed; + 3. the `Analytic Parameters` map. + Later sources win on a clash. Attribute defaults the parser fills in (`Graph Query Depth`, ...) are not + written: only what the author wrote is pinned. Values that are JSON (`25`, `true`, `[...]`) are decoded, so `Page Size 25` + is the number 25, not the string "25". `Report Spec` and `Output Format` are not parameters: they have + their own typed homes (`ReportTypeInstance`, `outputFormat`). + """ + doc: Dict[str, Any] = {} + for canonical_name, key in _REPORT_PARAM_ATTRS.items(): + if key in _TYPED_REPORT_KEYS: + continue + attr = attributes.get(canonical_name, {}) + if attr.get("is_default"): + continue # a spec default the author did not write: the report spec decides, not a pinned value + value = attr.get("value") + if value is not None and value != "": + doc[_camel_to_snake(key)] = _coerce_analytic_value(value) + for attr in ("Report Parameters", "Analytic Parameters"): + value = attributes.get(attr, {}).get("value") + if isinstance(value, dict): + doc.update({str(k): _coerce_analytic_value(v) for k, v in value.items() if v is not None}) + return doc + + def _report_additional_properties(attributes: Dict[str, Any]) -> Dict[str, str]: """Merge the user's own 'Additional Properties' dict (if any) with the report-execution params, stringified (additionalProperties is @@ -169,27 +221,135 @@ def _report_additional_properties(attributes: Dict[str, Any]) -> Dict[str, str]: return merged +def _as_element(result: Any) -> Optional[Dict[str, Any]]: + """An element dict from a lookup, or None for any not-found answer (a string, an empty list, None).""" + if isinstance(result, dict) and result.get("elementHeader"): + return result + if isinstance(result, dict) and isinstance(result.get("element"), dict): + return result["element"] + return None + + +async def find_element_by_qualified_name(client: Any, qualified_name: str) -> Optional[Dict[str, Any]]: + """One bounded exact lookup by qualifiedName (classification-explorer `by-unique-name`). None if absent. + + Never a type-wide query: the unique-name endpoint returns at most one element. + """ + if not qualified_name: + return None + try: + result = await client.classification_manager._async_get_element_by_unique_name(qualified_name) + except PyegeriaNotFoundException: + return None + return _as_element(result) + + +async def find_report_spec_element(client: Any, spec_name: str) -> Optional[Dict[str, Any]]: + """The Egeria element for a report spec named `spec_name`, looked up under both prefixes. + + Tries the name as a qualified name first (a caller may give `ReportSpec::X` or `ReportType::X`), then + `ReportSpec::`, then `ReportType::` (§7a hazard: both exist live). None if no element holds + the spec -- a spec held only in pyegeria has none. + """ + if not spec_name: + return None + candidates = [spec_name] if spec_name.startswith(REPORT_SPEC_QN_PREFIXES) else [] + candidates += [f"{prefix}{spec_name}" for prefix in REPORT_SPEC_QN_PREFIXES] + for qn in candidates: + element = await find_element_by_qualified_name(client, qn) + if element: + return element + return None + + +def _props_differ(desired: Dict[str, Any], current: Dict[str, Any]) -> bool: + """True if any non-None desired property differs from the element's current value.""" + for key, value in desired.items(): + if key in ("class", "typeName") or value is None: + continue + if current.get(key) != value: + return True + return False + + +async def upsert_dashboard_asset(client: Any, qualified_name: str, props: Dict[str, Any], + existing: Optional[Dict[str, Any]], *, merge_update: bool = True, + create_body: Optional[Dict[str, Any]] = None, + filter_update: Any = None) -> tuple: + """Create or update an Egeria 6.3 `Dashboard` asset. Returns (guid, verb_word, body_sent). + + The one implementation of the Dashboard asset write, used by `Create Dashboard` (DashboardProcessor) + and by `Create Dashboard Sheet` / dashboard migration (dashboard_sheet.py). An existing Dashboard whose + properties already match is left alone (verb_word "Unchanged", nothing sent), so re-running a document + changes nothing. + """ + if existing: + guid = existing["elementHeader"]["guid"] + if not _props_differ(props, existing.get("properties") or {}): + return guid, "Unchanged", None + update_props = filter_update(props, merge_update) if filter_update else props + update_body = {"class": "UpdateElementRequestBody", "properties": update_props, + "mergeUpdate": merge_update} + await client._async_update_asset(guid, update_body) + return guid, "Updated", update_body + body = dict(create_body or {"class": "NewElementRequestBody"}) + body["properties"] = props + raw_guid = await client._async_create_asset(["DashboardProperties"], body) + return raw_guid, "Created", body + + +async def sync_report_type_instance(client: Any, report_guid: str, spec_name: str) -> Optional[str]: + """Link the Report to its spec's element by `ReportTypeInstance`; return a note when that cannot be done. + + - Spec element found (under `ReportSpec::` or `ReportType::`): link it if not already linked, and detach + links to any other report type (a report runs one spec). + - No element (a spec held only in pyegeria): nothing is written, and the note says so -- the report + still runs from pyegeria's own spec registry. + """ + spec_element = await find_report_spec_element(client, spec_name) + if not spec_element: + return (f"Report Spec '{spec_name}' has no Egeria element (looked for " + f"{' and '.join(p + spec_name for p in REPORT_SPEC_QN_PREFIXES)}): no ReportTypeInstance was " + f"written. The report still runs from pyegeria's own spec.") + spec_guid = spec_element["elementHeader"]["guid"] + current = await client.classification_manager._async_get_related_elements( + report_guid, "ReportTypeInstance", start_at_end=2, page_size=25, graph_query_depth=0) + linked = [e["elementHeader"]["guid"] for e in (current if isinstance(current, list) else []) + if isinstance(e, dict) and e.get("elementHeader")] + for other in linked: + if other != spec_guid: + await client.data_designer._async_detach_report_type_instance(other, report_guid) + if spec_guid not in linked: + await client.data_designer._async_link_report_type_instance(spec_guid, report_guid) + return None + + class ReportProcessor(AsyncBaseCommandProcessor): - """Processor for Create Report (and its Update transition).""" + """Processor for Create Report (and its Update transition). + + Egeria 6.3 (odpi/egeria#9432) writes, beside the additionalProperties keys today's Portal reads (kept + for one release): + - `reportParameters`: ONE JSON document (report_parameters_document), not three parameter homes; + - the typed `outputFormat`; + - `ReportTypeInstance` from the named spec's element, found under `ReportSpec::` or `ReportType::`; + a spec with no element gets a note saying no link was written, not silence. + """ async def apply_changes(self) -> str: attributes = self.parsed_output["attributes"] qualified_name = self.parsed_output.get("qualified_name") or self.derive_qualified_name(attributes) display_name = attributes.get("Display Name", {}).get("value") or qualified_name - if not attributes.get("Report Spec", {}).get("value"): + spec_name = attributes.get("Report Spec", {}).get("value") + if not spec_name: raise ValueError("Report Spec is required.") props = set_element_prop_body("Report", qualified_name, attributes) props["additionalProperties"] = _report_additional_properties(attributes) - # Egeria 6.3 (odpi/egeria#9432) gives Report typed outputFormat and reportParameters (a JSON - # string). Written as well as the additionalProperties keys above, which the Portal's - # local dashboards still read. props["outputFormat"] = attributes.get("Output Format", {}).get("value") - report_params = attributes.get("Report Parameters", {}).get("value") - if isinstance(report_params, dict) and report_params: - props["reportParameters"] = json.dumps( - {str(k): v for k, v in report_params.items() if v is not None}) + parameters = report_parameters_document(attributes) + if parameters: + props["reportParameters"] = json.dumps(parameters, sort_keys=True) props["deployedImplementationType"] = attributes.get("Deployed Implementation Type", {}).get("value") props["resourceName"] = attributes.get("Resource Name", {}).get("value") @@ -211,8 +371,13 @@ async def apply_changes(self) -> str: self.parsed_output["guid"] = guid update_element_dictionary(qualified_name, {"guid": guid, "display_name": display_name}) + note = await sync_report_type_instance(self.client, guid, spec_name) + if note: + self._add_warning(note) + logger.success(f"{verb_word} Report '{display_name}' with GUID {guid}") - return await self.render_result_markdown(guid) + result = await self.render_result_markdown(guid) + return f"{result}\n\n> {note}\n" if note else result class DashboardProcessor(AsyncBaseCommandProcessor): @@ -220,8 +385,8 @@ class DashboardProcessor(AsyncBaseCommandProcessor): (DataSet subtype, sibling of Report; odpi/egeria#9432). Same AssetMaker path as ReportProcessor. Its sheets and placements are DisplayDataContainers / DisplayDataFields (Schema Maker family); - Egeria has no separate DashboardPlacement type. The local `Create Dashboard Sheet` records - (dashboard_sheet.py) are unchanged by this command. + Egeria has no separate DashboardPlacement type. The asset write itself is `upsert_dashboard_asset`, + which `Create Dashboard Sheet` (dashboard_sheet.py) also uses for its Dashboard. """ async def apply_changes(self) -> str: @@ -237,24 +402,15 @@ async def apply_changes(self) -> str: props["refreshTimeInterval"] = attributes.get("Refresh Time Interval", {}).get("value") props["layoutStyle"] = attributes.get("Layout Style", {}).get("value") - if self.as_is_element: - guid = self.as_is_element["elementHeader"]["guid"] - merge_update = attributes.get("Merge Update", {}).get("value", True) - update_body = { - "class": "UpdateElementRequestBody", - "properties": self.filter_update_properties(props, merge_update), - "mergeUpdate": merge_update, - } - self.last_body = update_body - await self.client._async_update_asset(guid, update_body) - verb_word = "Updated" - else: - create_body = set_create_body("Dashboard", attributes) - create_body["properties"] = props - self.last_body = create_body - raw_guid = await self.client._async_create_asset(["DashboardProperties"], create_body) - guid = self.extract_guid_or_raise(raw_guid, "Create Dashboard") - verb_word = "Created" + guid, verb_word, body = await upsert_dashboard_asset( + self.client, qualified_name, props, self.as_is_element, + merge_update=attributes.get("Merge Update", {}).get("value", True), + create_body=set_create_body("Dashboard", attributes), + filter_update=self.filter_update_properties) + if body is not None: + self.last_body = body + if verb_word == "Created": + guid = self.extract_guid_or_raise(guid, "Create Dashboard") self.parsed_output["guid"] = guid update_element_dictionary(qualified_name, {"guid": guid, "display_name": display_name}) diff --git a/tests/micro-tests/dashboard_fake_egeria.py b/tests/micro-tests/dashboard_fake_egeria.py new file mode 100644 index 00000000..b2e8f34e --- /dev/null +++ b/tests/micro-tests/dashboard_fake_egeria.py @@ -0,0 +1,276 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +An in-memory Egeria for the dashboard-sheet tests: entities and relationships, answering the handful of +client calls the dashboard-sheet writer and reader make, with the response shapes checked live on +2026-11-09 (related elements come back as {elementHeader, relatedBy: {relationshipHeader, +relationshipProperties}, properties}). + +Every subclient name (schema_maker, asset_maker, classification_manager, ...) is this same object, as +EgeriaTech proxies them. Every write is recorded in `writes` as (method, *args) so tests can assert "the +second run wrote nothing" and "no Report was deleted". An unknown method raises AttributeError, so a call +the fake does not model fails loudly instead of silently succeeding. + +Not a test module (no test_ prefix); tests load it with load_fake(). +""" +from __future__ import annotations + +import importlib.util +import pathlib +import uuid +from typing import Any, Dict, List, Optional + +from pyegeria.omvs.asset_maker import resolve_placement_reports + +SUPERTYPES = { + "Dashboard": ["DataSet", "Asset", "Referenceable"], + "Report": ["DataSet", "Asset", "Referenceable"], + "ReportSpec": ["Collection", "Referenceable"], + "ReportType": ["Referenceable"], + "Perspective": ["Referenceable"], + "DisplayDataSchemaType": ["RootSchemaType", "ComplexSchemaType", "SchemaType", "Referenceable"], + "DisplayDataContainer": ["SchemaAttribute", "Referenceable"], + "DisplayDataField": ["SchemaAttribute", "Referenceable"], +} + +SUBCLIENTS = ("schema_maker", "asset_maker", "classification_manager", "collection_manager", "data_designer", + "collections", "class_mgr", "metadata_expert") + + +class FakeEgeria: + def __init__(self): + self.entities: Dict[str, Dict[str, Any]] = {} + self.relationships: List[Dict[str, Any]] = [] + self.writes: List[tuple] = [] + self._n = 0 + + def __getattr__(self, name): + if name in SUBCLIENTS: + return self + raise AttributeError(name) + + # ---------------------------------------------------------------- seeding / inspection + + def _new_guid(self) -> str: + self._n += 1 + return str(uuid.UUID(int=self._n)) + + def add_entity(self, type_name: str, qualified_name: str, display_name: Optional[str] = None, + **props) -> str: + guid = self._new_guid() + self.entities[guid] = {"type": type_name, "props": {"qualifiedName": qualified_name, + "displayName": display_name or qualified_name, + **props}} + return guid + + def by_qn(self, qualified_name: str) -> Optional[str]: + return next((g for g, e in self.entities.items() if e["props"].get("qualifiedName") == qualified_name), None) + + def of_type(self, type_name: str) -> List[str]: + return [g for g, e in self.entities.items() if e["type"] == type_name] + + def rels(self, type_name: str) -> List[Dict[str, Any]]: + return [r for r in self.relationships if r["type"] == type_name] + + def write_names(self) -> List[str]: + return [w[0] for w in self.writes] + + # ---------------------------------------------------------------- element shapes + + def _header(self, guid: str) -> Dict[str, Any]: + e = self.entities[guid] + return {"class": "ElementHeader", "guid": guid, + "type": {"typeName": e["type"], "superTypeNames": SUPERTYPES.get(e["type"], [])}} + + def element(self, guid: str) -> Dict[str, Any]: + e = self.entities[guid] + return {"class": "OpenMetadataRootElement", "elementHeader": self._header(guid), + "properties": {"typeName": e["type"], **{k: v for k, v in e["props"].items() if v is not None}}} + + def _related_shape(self, guid: str, rel: Dict[str, Any]) -> Dict[str, Any]: + out = self.element(guid) + out["relatedBy"] = {"relationshipHeader": {"guid": rel["guid"], "type": {"typeName": rel["type"]}}, + "relationshipProperties": {"typeName": rel["type"], **rel["props"]}} + return out + + # ---------------------------------------------------------------- reads + + async def _async_get_element_by_unique_name(self, name, property_name=None, **kwargs): + guid = self.by_qn(name) + return self.element(guid) if guid else "No elements found" + + async def _async_get_element_by_guid_(self, guid, **kwargs): + return self.element(guid) if guid in self.entities else "No elements found" + + async def __async_get_guid__(self, guid=None, display_name=None, property_name="qualifiedName", + qualified_name=None, tech_type=None, **kwargs): + if guid: + return guid + hits = [] + for g, e in self.entities.items(): + if tech_type and tech_type not in (e["type"], *SUPERTYPES.get(e["type"], [])): + continue + if e["props"].get("qualifiedName") == qualified_name or e["props"].get("displayName") == display_name: + hits.append(g) + if len(hits) > 1: + from pyegeria.core._exceptions import PyegeriaException + raise PyegeriaException(context={"reason": "Multiple elements found"}) + return hits[0] if hits else "No elements found" + + async def _async_get_related_elements(self, element_guid, relationship_type=None, start_at_end=1, + start_from=0, page_size=0, **kwargs): + out = [] + for rel in self.relationships: + if relationship_type and rel["type"] != relationship_type: + continue + if start_at_end == 1 and rel["end1"] == element_guid: + out.append(self._related_shape(rel["end2"], rel)) + elif start_at_end == 2 and rel["end2"] == element_guid: + out.append(self._related_shape(rel["end1"], rel)) + page = out[start_from:start_from + page_size] if page_size else out[start_from:] + return page if page else "No elements found" + + async def _async_get_placement_reports(self, dashboard_guid, placement_qualified_names, **kwargs): + element = self.element(dashboard_guid) + links = [] + for rel in self.rels("DataSetContent"): + if rel["end1"] == dashboard_guid: + links.append({"relationshipHeader": {"guid": rel["guid"]}, + "relationshipProperties": rel["props"], + "relatedElement": self.element(rel["end2"])}) + if links: + element["dataSetContent"] = links + return resolve_placement_reports(element, placement_qualified_names) + + # ---------------------------------------------------------------- writes + + def _link(self, rel_type: str, end1: str, end2: str, props: Optional[Dict[str, Any]] = None) -> str: + assert end1 in self.entities and end2 in self.entities, (rel_type, end1, end2) + guid = self._new_guid() + clean = {k: v for k, v in (props or {}).items() if k not in ("class",) and v is not None} + self.relationships.append({"guid": guid, "type": rel_type, "end1": end1, "end2": end2, "props": clean}) + return guid + + def _unlink(self, rel_type: str, end1: str, end2: str) -> None: + self.relationships = [r for r in self.relationships + if not (r["type"] == rel_type and r["end1"] == end1 and r["end2"] == end2)] + + def _create(self, body: Dict[str, Any]) -> str: + props = dict(body["properties"]) + type_name = props.pop("typeName") + props.pop("class", None) + assert self.by_qn(props["qualifiedName"]) is None, f"duplicate qualifiedName {props['qualifiedName']}" + guid = self._new_guid() + self.entities[guid] = {"type": type_name, "props": props, "anchor": body.get("anchorGUID")} + return guid + + def _update(self, guid: str, body: Dict[str, Any]) -> None: + props = {k: v for k, v in body["properties"].items() if k not in ("class", "typeName")} + if body.get("mergeUpdate", True): + self.entities[guid]["props"].update({k: v for k, v in props.items() if v is not None}) + else: + self.entities[guid]["props"] = props + + def _delete(self, guid: str) -> None: + del self.entities[guid] + self.relationships = [r for r in self.relationships if guid not in (r["end1"], r["end2"])] + + async def _async_create_asset(self, prop_classes, body): + self.writes.append(("create_asset", body["properties"]["qualifiedName"])) + return self._create(body) + + async def _async_update_asset(self, guid, body): + self.writes.append(("update_asset", guid)) + self._update(guid, body) + + async def _async_delete_asset(self, guid, body=None): + self.writes.append(("delete_asset", self.entities[guid]["type"], guid)) + self._delete(guid) + + async def _async_create_schema_type(self, body): + self.writes.append(("create_schema_type", body["properties"]["qualifiedName"])) + return self._create(body) + + async def _async_create_schema_attribute(self, body): + self.writes.append(("create_schema_attribute", body["properties"]["qualifiedName"])) + return self._create(body) + + async def _async_update_schema_attribute(self, guid, body): + self.writes.append(("update_schema_attribute", guid)) + self._update(guid, body) + + async def _async_delete_schema_attribute(self, guid, body=None, cascade_delete=False): + self.writes.append(("delete_schema_attribute", self.entities[guid]["type"], guid)) + self._delete(guid) + + async def _async_delete_schema_type(self, guid, body=None, cascade_delete=False): + self.writes.append(("delete_schema_type", self.entities[guid]["type"], guid)) + self._delete(guid) + + async def _async_link_schema(self, element_guid, schema_type_guid, body=None): + self.writes.append(("link_schema", element_guid, schema_type_guid)) + return self._link("Schema", element_guid, schema_type_guid) + + async def _async_link_attribute_for_schema(self, schema_type_guid, attribute_guid, body=None): + self.writes.append(("link_attribute_for_schema", schema_type_guid, attribute_guid)) + return self._link("AttributeForSchema", schema_type_guid, attribute_guid, (body or {}).get("properties")) + + async def _async_link_nested_schema_attribute(self, parent_guid, child_guid, body=None): + self.writes.append(("link_nested_schema_attribute", parent_guid, child_guid)) + return self._link("NestedSchemaAttribute", parent_guid, child_guid, (body or {}).get("properties")) + + async def _async_link_placement_report(self, dashboard_guid, report_guid, placement_qualified_name, body=None): + self.writes.append(("link_placement_report", dashboard_guid, report_guid, placement_qualified_name)) + return self._link("DataSetContent", dashboard_guid, report_guid, + {"queryId": placement_qualified_name, "queryType": "placement"}) + + async def _async_detach_placement_report(self, dashboard_guid, placement_qualified_name, body=None): + self.writes.append(("detach_placement_report", dashboard_guid, placement_qualified_name)) + before = len(self.relationships) + self.relationships = [r for r in self.relationships + if not (r["type"] == "DataSetContent" and r["end1"] == dashboard_guid + and r["props"].get("queryId") == placement_qualified_name)] + return before - len(self.relationships) + + async def _async_add_scope_to_element(self, scoped_by_guid, element_guid, body=None): + self.writes.append(("add_scope", scoped_by_guid, element_guid)) + return self._link("ScopedBy", scoped_by_guid, element_guid) + + async def _async_clear_scope_from_element(self, scoped_by_guid, element_guid, body=None, cascade_delete=False): + self.writes.append(("clear_scope", scoped_by_guid, element_guid)) + self._unlink("ScopedBy", scoped_by_guid, element_guid) + + async def _async_attach_data_description(self, element_guid, collection_guid, body=None): + self.writes.append(("attach_data_description", element_guid, collection_guid)) + return self._link("DataDescription", element_guid, collection_guid) + + async def _async_detach_data_description(self, element_guid, collection_guid, body=None): + self.writes.append(("detach_data_description", element_guid, collection_guid)) + self._unlink("DataDescription", element_guid, collection_guid) + + async def _async_link_report_type_instance(self, report_type_guid, report_guid, body=None): + self.writes.append(("link_report_type_instance", report_type_guid, report_guid)) + return self._link("ReportTypeInstance", report_type_guid, report_guid) + + async def _async_detach_report_type_instance(self, report_type_guid, report_guid, body=None, + cascade_delete=False): + self.writes.append(("detach_report_type_instance", report_type_guid, report_guid)) + self._unlink("ReportTypeInstance", report_type_guid, report_guid) + + +# The 12 Perspective:: elements Trellis creates (checked live, read only, 2026-11-09). +TRELLIS_PERSPECTIVES = ["Financial", "Privacy", "Governance", "App/AI Builder", "Data Expert", "Architecture", + "Owner", "Community", "Consumer", "Administration", "Security", "Steward"] + + +def seed_perspectives(fake: FakeEgeria) -> None: + for name in TRELLIS_PERSPECTIVES: + fake.add_entity("Perspective", f"Perspective::{name}", f"{name.upper()}-PERSPECTIVE") + + +def load_fake(): + """Import this module by path (micro-tests is not an importable package name).""" + spec = importlib.util.spec_from_file_location("dashboard_fake_egeria", pathlib.Path(__file__)) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module diff --git a/tests/micro-tests/test_dashboard_sheets_in_egeria.py b/tests/micro-tests/test_dashboard_sheets_in_egeria.py new file mode 100644 index 00000000..3e5d20b5 --- /dev/null +++ b/tests/micro-tests/test_dashboard_sheets_in_egeria.py @@ -0,0 +1,385 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +Dashboard sheets held in Egeria (BRIEF RS-DASH PR-1, pipeline note v5.5 §8d / §10.6(c)). + +The three sheet commands keep their names and syntax and now write the Egeria 6.3 chain: +Dashboard -Schema-> DisplayDataSchemaType -AttributeForSchema-> DisplayDataContainer +-NestedSchemaAttribute(position)-> DisplayDataField per placement, plus DataSetContent (Dashboard -> Report, +queryId = the placement's qualifiedName), ScopedBy (Perspective -> placement) and DataDescription +(placement -> ReportSpec). DB-1: the local JSON store is written too. + +Every command goes through the real setup_dispatcher() / V2Dispatcher.dispatch() with an in-memory fake +Egeria (dashboard_fake_egeria.py), so command resolution, parsing and processor routing are the +production ones. No live server. +""" +import json +from typing import Any, Dict + +import pytest + +from md_processing.dr_egeria import setup_dispatcher +from md_processing.md_processing_utils.common_md_utils import clear_element_dictionary +from md_processing.v2.dashboard_sheet import ( + DashboardSheetEgeriaWriter, LOCAL_ONLY_ENV, perspective_qualified_name, +) +from md_processing.v2.extraction import DrECommand +from pyegeria.view._output_dashboard_sheet_models import DashboardSheetDict + +import importlib.util as _ilu +import pathlib as _pl + +_spec = _ilu.spec_from_file_location("dashboard_fake_egeria", _pl.Path(__file__).with_name("dashboard_fake_egeria.py")) +fake_egeria = _ilu.module_from_spec(_spec) +_spec.loader.exec_module(fake_egeria) + +SHEET = "glossary-health" + + +@pytest.fixture(autouse=True) +def _store(tmp_path, monkeypatch): + path = tmp_path / "dashboard_sheets.json" + monkeypatch.setenv("PYEGERIA_DASHBOARD_SHEETS_STORE", str(path)) + monkeypatch.delenv(LOCAL_ONLY_ENV, raising=False) + clear_element_dictionary() + yield path + clear_element_dictionary() + + +@pytest.fixture +def egeria(): + fake = fake_egeria.FakeEgeria() + fake_egeria.seed_perspectives(fake) + fake.add_entity("Report", "DeployedReport::Coco Terms Total", "Coco Terms Total") + fake.add_entity("Report", "DeployedReport::Coco Term Counts", "Coco Term Counts") + fake.add_entity("ReportSpec", "ReportSpec::Glossary-Term-Counts", "Glossary-Term-Counts") + return fake + + +def _command(verb: str, object_type: str, attributes: Dict[str, str]) -> DrECommand: + raw = f"## {verb} {object_type}\n" + "".join(f"### {k}\n{v}\n\n" for k, v in attributes.items()) + return DrECommand(verb=verb, object_type=object_type, attributes=attributes, raw_block=raw) + + +async def _run(client, verb, object_type, attributes): + dispatcher = setup_dispatcher(client) + context: Dict[str, Any] = {"directive": "process"} + result = await dispatcher.dispatch(_command(verb, object_type, attributes), context) + assert result["status"] == "success", result + return result + + +CREATE = {"Display Name": SHEET, "Dashboard Sheet Heading": "Glossary Health", + "Dashboard Sheet Description": "How complete and how used the glossaries are.", + "Dashboard Sheet Family": "Glossary Manager"} +TEXT = {"Dashboard Sheet Name": SHEET, "Placement Name": "Coverage header", + "MD Content": "**Coverage** - counts and definition completeness per glossary.", + "Placement Span": "full", "Placement Emphasis": "panel"} +LINK_1 = {"Dashboard Sheet Name": SHEET, "Report Name": "Coco Terms Total", "Placement Span": "1", + "Placement Emphasis": "kpi", "Placement Perspectives": "Steward, owner", + "Placement Detail Spec": "Glossary-Term-Counts"} +LINK_2 = {"Dashboard Sheet Name": SHEET, "Report Name": "Coco Term Counts", "Placement Span": "2", + "Placement Emphasis": "panel", "Placement Perspectives": "steward", + "Placement Detail Spec": "Glossary-With-Terms"} + + +async def _document(client): + await _run(client, "Create", "Dashboard Sheet", CREATE) + await _run(client, "Add", "Text on Dashboard Sheet", TEXT) + await _run(client, "Link", "Report to Dashboard Sheet", LINK_1) + return await _run(client, "Link", "Report to Dashboard Sheet", LINK_2) + + +def _fields(fake): + """(position, qualifiedName, props) for each placement, in position order.""" + out = [] + for rel in fake.rels("NestedSchemaAttribute"): + out.append((rel["props"]["position"], fake.entities[rel["end2"]]["props"])) + return sorted(out, key=lambda x: x[0]) + + +# ---------------------------------------------------------------------------- create + +@pytest.mark.asyncio +async def test_create_sheet_writes_dashboard_schema_and_container(egeria, _store): + result = await _run(egeria, "Create", "Dashboard Sheet", CREATE) + + dash = egeria.by_qn("Dashboard::glossary-health") + st = egeria.by_qn("DashboardSchema::glossary-health") + container = egeria.by_qn("DashboardSheet::glossary-health") + assert egeria.entities[dash]["type"] == "Dashboard" + assert egeria.entities[dash]["props"]["displayName"] == "Glossary Health" + assert egeria.entities[dash]["props"]["description"] == "How complete and how used the glossaries are." + assert egeria.entities[dash]["props"]["additionalProperties"] == {"family": "Glossary Manager"} + assert egeria.entities[st]["type"] == "DisplayDataSchemaType" + assert egeria.entities[container]["type"] == "DisplayDataContainer" + assert [(r["end1"], r["end2"]) for r in egeria.rels("Schema")] == [(dash, st)] + afs, = egeria.rels("AttributeForSchema") + assert (afs["end1"], afs["end2"], afs["props"]["position"]) == (st, container, 1) + # schema elements are anchored to the Dashboard + assert egeria.entities[st]["anchor"] == dash and egeria.entities[container]["anchor"] == dash + # DB-1: the local store is written too + sheets = DashboardSheetDict.load_from_json(str(_store)) + assert sheets[SHEET].heading == "Glossary Health" + assert "Egeria**: written" in result["output"] + + +@pytest.mark.asyncio +async def test_full_document_writes_the_10_6_chain(egeria): + result = await _document(egeria) + + fields = _fields(egeria) + assert [(pos, p["qualifiedName"]) for pos, p in fields] == [ + (1, "DashboardPlacement::glossary-health::1::Coverage header"), + (2, "DashboardPlacement::glossary-health::2::Coco Terms Total"), + (3, "DashboardPlacement::glossary-health::3::Coco Term Counts"), + ] + text, kpi, panel = (p for _, p in fields) + assert (text["placementKind"], text["span"], text["presentationStyle"]) == ("text", "full", "panel") + assert text["markdownContent"].startswith("**Coverage**") + assert (kpi["placementKind"], kpi["span"], kpi["presentationStyle"]) == ("report", "1", "kpi") + assert kpi.get("markdownContent") is None + assert kpi["additionalProperties"] == {"placementName": "Coco Terms Total", "perspectives": "Steward,owner", + "detailSpec": "Glossary-Term-Counts"} + # not the Report's own displayName: Dr.Egeria's untyped `Report Name` lookup must stay unambiguous + assert kpi["displayName"] == "glossary-health / Coco Terms Total" + + # DataSetContent: Dashboard -> Report, queryId = the placement's qualifiedName, for REPORT placements only + dash = egeria.by_qn("Dashboard::glossary-health") + dsc = {(r["end1"], egeria.entities[r["end2"]]["props"]["displayName"], r["props"]["queryId"], r["props"]["queryType"]) + for r in egeria.rels("DataSetContent")} + assert dsc == {(dash, "Coco Terms Total", kpi["qualifiedName"], "placement"), + (dash, "Coco Term Counts", panel["qualifiedName"], "placement")} + + # ScopedBy: Perspective -> placement; "owner" maps to the Trellis element Perspective::Owner (DB-2) + kpi_guid = egeria.by_qn(kpi["qualifiedName"]) + scopes = sorted(egeria.entities[r["end1"]]["props"]["qualifiedName"] + for r in egeria.rels("ScopedBy") if r["end2"] == kpi_guid) + assert scopes == ["Perspective::Owner", "Perspective::Steward"] + + # DataDescription: placement -> the ReportSpec element; a spec with no element is a note, not silence + dd = [(r["end1"], egeria.entities[r["end2"]]["props"]["qualifiedName"]) for r in egeria.rels("DataDescription")] + assert dd == [(kpi_guid, "ReportSpec::Glossary-Term-Counts")] + assert "Glossary-With-Terms" in result["output"] and "no DataDescription link" in result["output"] + + # membership is not anchoring: nothing created a Report or a Perspective + assert len(egeria.of_type("Report")) == 2 and len(egeria.of_type("Perspective")) == 12 + + +@pytest.mark.asyncio +async def test_rerunning_the_document_changes_nothing(egeria, _store): + await _document(egeria) + writes_after_first = list(egeria.writes) + store_after_first = _store.read_text() + + result = await _document(egeria) + + assert egeria.writes == writes_after_first, egeria.writes[len(writes_after_first):] + assert _store.read_text() == store_after_first + assert "no change" in result["output"] + + +@pytest.mark.asyncio +async def test_update_changes_only_what_changed(egeria): + await _document(egeria) + before = len(egeria.writes) + + await _run(egeria, "Link", "Report to Dashboard Sheet", {**LINK_2, "Placement Span": "full"}) + await _run(egeria, "Create", "Dashboard Sheet", {**CREATE, "Dashboard Sheet Heading": "Glossary Health v2"}) + + new = egeria.writes[before:] + assert [w[0] for w in new] == ["update_schema_attribute", "update_asset"] + panel = egeria.entities[egeria.by_qn("DashboardPlacement::glossary-health::3::Coco Term Counts")]["props"] + assert panel["span"] == "full" + assert egeria.entities[egeria.by_qn("Dashboard::glossary-health")]["props"]["displayName"] == "Glossary Health v2" + + +@pytest.mark.asyncio +async def test_update_clears_removed_perspectives(egeria): + await _document(egeria) + await _run(egeria, "Link", "Report to Dashboard Sheet", {**LINK_1, "Placement Perspectives": "Steward"}) + kpi_qn = "DashboardPlacement::glossary-health::2::Coco Terms Total" + kpi_guid = egeria.by_qn(kpi_qn) + scopes = [egeria.entities[r["end1"]]["props"]["qualifiedName"] for r in egeria.rels("ScopedBy") if r["end2"] == kpi_guid] + assert scopes == ["Perspective::Steward"] + assert egeria.entities[kpi_guid]["props"]["additionalProperties"]["perspectives"] == "Steward" + + +# ---------------------------------------------------------------------------- remove / delete + +@pytest.mark.asyncio +async def test_remove_placement_deletes_field_and_link_not_report(egeria): + await _document(egeria) + reports_before = set(egeria.of_type("Report")) + + writer = DashboardSheetEgeriaWriter(egeria) + assert await writer.remove_placement(SHEET, "Coco Terms Total") is True + + assert egeria.by_qn("DashboardPlacement::glossary-health::2::Coco Terms Total") is None + assert [r["props"]["queryId"] for r in egeria.rels("DataSetContent")] == [ + "DashboardPlacement::glossary-health::3::Coco Term Counts"] + assert set(egeria.of_type("Report")) == reports_before + assert not [w for w in egeria.writes if w[0] == "delete_asset"] + + # a placement added afterwards takes the next free position, never a taken one + await _run(egeria, "Link", "Report to Dashboard Sheet", LINK_1) + assert [pos for pos, _ in _fields(egeria)] == [1, 3, 4] + + +@pytest.mark.asyncio +async def test_delete_sheet_deletes_chain_only(egeria): + await _document(egeria) + keep = set(egeria.of_type("Report")) | set(egeria.of_type("ReportSpec")) | set(egeria.of_type("Perspective")) + + writer = DashboardSheetEgeriaWriter(egeria) + assert await writer.delete_sheet(SHEET) is True + + assert set(egeria.entities) == keep + assert not egeria.rels("DataSetContent") and not egeria.rels("ScopedBy") + deleted_types = sorted(w[1] for w in egeria.writes if w[0].startswith("delete")) + assert deleted_types == ["Dashboard", "DisplayDataContainer", "DisplayDataField", "DisplayDataField", + "DisplayDataField", "DisplayDataSchemaType"] + assert await DashboardSheetEgeriaWriter(egeria).delete_sheet(SHEET) is False + + +@pytest.mark.asyncio +async def test_dry_run_writes_nothing_and_lists_every_element(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + sheet = DashboardSheet(name="dry", heading="Dry", placements=[ + Placement(ref="Coco Terms Total", perspectives=["governance"]), + Placement(ref="Intro", content="hello", span="full", emphasis="panel")]) + writer = DashboardSheetEgeriaWriter(egeria, dry_run=True) + await writer.write_sheet(sheet) + + assert egeria.writes == [] + creates = [a for a in writer.actions if a.startswith("create")] + assert creates == ["create Dashboard Dashboard::dry", "create DisplayDataSchemaType DashboardSchema::dry", + "create DisplayDataContainer DashboardSheet::dry", + "create DisplayDataField DashboardPlacement::dry::1::Coco Terms Total", + "create DisplayDataField DashboardPlacement::dry::2::Intro"] + assert any(a.startswith("link DataSetContent") for a in writer.actions) + assert any(a.startswith("link ScopedBy Perspective::Governance") for a in writer.actions) + + +# ---------------------------------------------------------------------------- absences and local-only + +@pytest.mark.asyncio +async def test_missing_report_command_is_refused_as_today(egeria, _store): + """Dr.Egeria refuses `Link Report to Dashboard Sheet` for a Report it cannot find (unchanged): nothing is + written to Egeria or to the store.""" + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + writes, store = list(egeria.writes), _store.read_text() + result = await setup_dispatcher(egeria).dispatch( + _command("Link", "Report to Dashboard Sheet", {**LINK_2, "Report Name": "No Such Report"}), + {"directive": "process"}) + assert result["status"] == "failure" + assert egeria.writes == writes and _store.read_text() == store + + +@pytest.mark.asyncio +async def test_missing_report_in_migration_is_written_without_link_and_said(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + writer = DashboardSheetEgeriaWriter(egeria) + await writer.write_sheet(DashboardSheet(name="m", heading="M", placements=[Placement(ref="No Such Report")])) + assert egeria.by_qn("DashboardPlacement::m::1::No Such Report") + assert not egeria.rels("DataSetContent") + assert any("reads as missing" in n for n in writer.notes) + + +@pytest.mark.asyncio +async def test_missing_perspective_is_written_without_link_and_said(egeria): + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + result = await _run(egeria, "Link", "Report to Dashboard Sheet", + {**LINK_2, "Placement Perspectives": "Astrologer", "Placement Detail Spec": ""}) + assert not egeria.rels("ScopedBy") + assert "Perspective 'Astrologer'" in result["output"] and "not created here" in result["output"] + assert len(egeria.of_type("Perspective")) == 12 + + +@pytest.mark.asyncio +async def test_local_only_writes_store_alone_and_says_so(egeria, _store, monkeypatch): + monkeypatch.setenv(LOCAL_ONLY_ENV, "1") + result = await _document(egeria) + + assert egeria.writes == [] + assert "not written" in result["output"] and LOCAL_ONLY_ENV in result["output"] + sheets = DashboardSheetDict.load_from_json(str(_store)) + assert [p.ref for p in sheets[SHEET].placements] == ["Coverage header", "Coco Terms Total", "Coco Term Counts"] + + +@pytest.mark.asyncio +async def test_local_only_sheet_is_written_whole_on_next_egeria_command(egeria, monkeypatch): + monkeypatch.setenv(LOCAL_ONLY_ENV, "1") + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + await _run(egeria, "Add", "Text on Dashboard Sheet", TEXT) + monkeypatch.delenv(LOCAL_ONLY_ENV) + + result = await _run(egeria, "Link", "Report to Dashboard Sheet", LINK_1) + + assert [p["additionalProperties"]["placementName"] for _, p in _fields(egeria)] == [ + "Coverage header", "Coco Terms Total"] + assert "only in the local store" in result["output"] + + +def test_perspective_mapping_db2(): + assert perspective_qualified_name("governance") == "Perspective::Governance" + assert perspective_qualified_name("owner") == "Perspective::Owner" # Trellis "Data Owner" + assert perspective_qualified_name("Data Owner") == "Perspective::Owner" + assert perspective_qualified_name("engineer") == "Perspective::Data Expert" + assert perspective_qualified_name("builder") == "Perspective::App/AI Builder" + assert perspective_qualified_name("data expert") == "Perspective::Data Expert" + assert perspective_qualified_name("Perspective::Steward") == "Perspective::Steward" + + +# ---------------------------------------------------------------------------- Create Report + +REPORT = {"Display Name": "Coco Glossaries", "Report Spec": "Glossary-With-Terms", "Output Format": "MD", + "Page Size": "25", "Search String": "Coco"} + + +def _report_props(fake): + guid = fake.by_qn(next(e["props"]["qualifiedName"] for e in fake.entities.values() + if e["props"].get("displayName") == "Coco Glossaries")) + return guid, fake.entities[guid]["props"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("prefix", ["ReportSpec::", "ReportType::"]) +async def test_create_report_writes_parameters_and_report_type_instance(prefix): + fake = fake_egeria.FakeEgeria() + spec_type = "ReportSpec" if prefix == "ReportSpec::" else "ReportType" + spec_guid = fake.add_entity(spec_type, f"{prefix}Glossary-With-Terms", "Glossary-With-Terms") + + result = await _run(fake, "Create", "Report", REPORT) + + report_guid, props = _report_props(fake) + assert props["outputFormat"] == "MD" + assert json.loads(props["reportParameters"]) == {"page_size": 25, "search_string": "Coco"} + assert props["additionalProperties"]["reportSpec"] == "Glossary-With-Terms" # kept one release + assert [(r["end1"], r["end2"]) for r in fake.rels("ReportTypeInstance")] == [(spec_guid, report_guid)] + assert "no ReportTypeInstance" not in result["output"] + + # re-run: the link is not duplicated + await _run(fake, "Create", "Report", REPORT) + assert len(fake.rels("ReportTypeInstance")) == 1 + + +@pytest.mark.asyncio +async def test_create_report_spec_without_element_says_so(): + fake = fake_egeria.FakeEgeria() + result = await _run(fake, "Create", "Report", REPORT) + assert not fake.rels("ReportTypeInstance") + assert "has no Egeria element" in result["output"] + assert "ReportSpec::Glossary-With-Terms and ReportType::Glossary-With-Terms" in result["output"] + + +@pytest.mark.asyncio +async def test_create_report_relinks_when_spec_changes(): + fake = fake_egeria.FakeEgeria() + old = fake.add_entity("ReportSpec", "ReportSpec::Glossary-With-Terms", "Glossary-With-Terms") + new = fake.add_entity("ReportSpec", "ReportSpec::Glossary-Term-Counts", "Glossary-Term-Counts") + await _run(fake, "Create", "Report", REPORT) + await _run(fake, "Create", "Report", {**REPORT, "Report Spec": "Glossary-Term-Counts"}) + report_guid, _ = _report_props(fake) + assert [(r["end1"], r["end2"]) for r in fake.rels("ReportTypeInstance")] == [(new, report_guid)] + assert old in fake.entities # a spec is never deleted diff --git a/tests/micro-tests/test_dr_egeria_report_spec_types.py b/tests/micro-tests/test_dr_egeria_report_spec_types.py index d63b6a3a..e9e141cb 100644 --- a/tests/micro-tests/test_dr_egeria_report_spec_types.py +++ b/tests/micro-tests/test_dr_egeria_report_spec_types.py @@ -44,6 +44,7 @@ def __init__(self): super().__init__() self.data_designer = _Recorder() self.schema_maker = _Recorder() + self.classification_manager = _Recorder() def _processor(cls, verb, object_type, om_type, attributes, as_is=None): From 608480e545f8d28f2aa3e11444e4d5398e11d954 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 14:58:39 +0000 Subject: [PATCH 2/9] fix(dr-egeria): resolve a placement's Report by exact name among Reports A live dry run found two real Reports ('Term Definition Completeness', 'Governance Classification Coverage') that __async_get_guid__ cannot resolve: its unique-name lookup is rejected when another element type shares the display name. The writer now finds the one Report whose displayName matches exactly (the Portal's own lookup), else by qualifiedName; two same-named Reports give a note and no link. Signed-off-by: Dan Wolfson --- md_processing/v2/dashboard_sheet.py | 39 +++++++++++++++---- tests/micro-tests/dashboard_fake_egeria.py | 15 +++++++ .../test_dashboard_sheets_in_egeria.py | 26 +++++++++++++ 3 files changed, 72 insertions(+), 8 deletions(-) diff --git a/md_processing/v2/dashboard_sheet.py b/md_processing/v2/dashboard_sheet.py index 6f57ba29..d7af040b 100644 --- a/md_processing/v2/dashboard_sheet.py +++ b/md_processing/v2/dashboard_sheet.py @@ -442,15 +442,38 @@ async def ensure_sheet(self, sheet_name: str, heading: str, description: str = " # ------------------------------------------------------------ placements async def _resolve_report(self, report_name: str) -> Optional[str]: - """The GUID of the Report a placement shows, by display name or qualified name (the same lookup - Dr.Egeria uses for `Report Name`). None if there is none.""" - try: - res = await self.client.__async_get_guid__(qualified_name=report_name, display_name=report_name, - property_name="displayName", tech_type="Report") - except PyegeriaNotFoundException: + """The GUID of the Report a placement shows: the one `Report` whose displayName is exactly + `report_name` (the lookup the Portal uses), else the Report whose qualifiedName it is. None if there + is none; two or more exact matches are a note, and no link. + + Not Dr.Egeria's `__async_get_guid__`: it tries a unique-name lookup first, which Egeria rejects + when the name is shared with an element of another type -- seen live 2026-11-09 for 'Term + Definition Completeness' and 'Governance Classification Coverage', both real Reports.""" + matches: List[str] = [] + start = 0 + while True: + try: + page = await self.client.classification_manager._async_find_elements_by_property_value( + report_name, ["displayName"], metadata_element_type="Report", starts_with=False, + start_from=start, page_size=PAGE_SIZE, graph_query_depth=0) + except PyegeriaNotFoundException: + page = [] + items = [e for e in page if isinstance(e, dict) and e.get("elementHeader")] if isinstance(page, list) else [] + if not items: + break + matches += [self._guid(e) for e in items + if (e.get("properties") or {}).get("displayName") == report_name + and self._type(e) == "Report"] + start += len(items) + if len(matches) == 1: + return matches[0] + if len(matches) > 1: + self._note(f"{len(matches)} Reports are named '{report_name}' in Egeria: no report link was written " + f"for that placement. Give the placement's report a unique name.") return None - if isinstance(res, str) and res and not res.startswith("No ") and " found" not in res: - return res + element = await self._find(report_name) + if element and self._type(element) == "Report": + return self._guid(element) return None async def _perspective_guid(self, label: str) -> Optional[str]: diff --git a/tests/micro-tests/dashboard_fake_egeria.py b/tests/micro-tests/dashboard_fake_egeria.py index b2e8f34e..3150d4be 100644 --- a/tests/micro-tests/dashboard_fake_egeria.py +++ b/tests/micro-tests/dashboard_fake_egeria.py @@ -130,6 +130,21 @@ async def _async_get_related_elements(self, element_guid, relationship_type=None page = out[start_from:start_from + page_size] if page_size else out[start_from:] return page if page else "No elements found" + async def _async_find_elements_by_property_value(self, property_value, property_names, metadata_element_type=None, + starts_with=True, start_from=0, page_size=0, **kwargs): + hits = [] + for g, e in self.entities.items(): + if metadata_element_type and e["type"] != metadata_element_type: + continue + for prop in property_names: + value = str(e["props"].get(prop) or "") + # live Egeria: starts_with=False is a contains match, not an exact one + if (value.startswith(property_value) if starts_with else property_value in value): + hits.append(self.element(g)) + break + page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] + return page if page else "No elements found" + async def _async_get_placement_reports(self, dashboard_guid, placement_qualified_names, **kwargs): element = self.element(dashboard_guid) links = [] diff --git a/tests/micro-tests/test_dashboard_sheets_in_egeria.py b/tests/micro-tests/test_dashboard_sheets_in_egeria.py index 3e5d20b5..5f323c3e 100644 --- a/tests/micro-tests/test_dashboard_sheets_in_egeria.py +++ b/tests/micro-tests/test_dashboard_sheets_in_egeria.py @@ -383,3 +383,29 @@ async def test_create_report_relinks_when_spec_changes(): report_guid, _ = _report_props(fake) assert [(r["end1"], r["end2"]) for r in fake.rels("ReportTypeInstance")] == [(new, report_guid)] assert old in fake.entities # a spec is never deleted + + +@pytest.mark.asyncio +async def test_report_found_when_its_name_is_shared_with_another_type(egeria): + """Live 2026-11-09: a Report whose displayName another element also has (and a longer Report name that + contains it) is still found -- exact displayName among Reports only.""" + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + report = egeria.add_entity("Report", "X::Report::TDC", "Term Definition Completeness") + egeria.add_entity("Report", "X::Report::TDC-metric", "Term Definition Completeness Metric Report") + egeria.add_entity("GovernanceMetric", "X::Metric::TDC", "Term Definition Completeness") + writer = DashboardSheetEgeriaWriter(egeria) + await writer.write_sheet(DashboardSheet(name="s", heading="S", + placements=[Placement(ref="Term Definition Completeness")])) + assert [r["end2"] for r in egeria.rels("DataSetContent")] == [report] + assert writer.notes == [] + + +@pytest.mark.asyncio +async def test_two_reports_with_one_name_is_a_note_not_a_guess(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + egeria.add_entity("Report", "X::Report::1", "Twin") + egeria.add_entity("Report", "X::Report::2", "Twin") + writer = DashboardSheetEgeriaWriter(egeria) + await writer.write_sheet(DashboardSheet(name="s", heading="S", placements=[Placement(ref="Twin")])) + assert not egeria.rels("DataSetContent") + assert any("2 Reports are named 'Twin'" in n for n in writer.notes) From 2b4c7166d2108f18962bde701e86549fcd9980d2 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 15:09:11 +0000 Subject: [PATCH 3/9] perf(dr-egeria): exact type-filtered lookup for a placement's Report The contains-search took ~35 s per placement on the live platform; the exact by-property-value lookup filtered to type Report takes 0.1 s. Signed-off-by: Dan Wolfson --- md_processing/v2/dashboard_sheet.py | 7 ++++--- tests/micro-tests/dashboard_fake_egeria.py | 9 +++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/md_processing/v2/dashboard_sheet.py b/md_processing/v2/dashboard_sheet.py index d7af040b..20c970c4 100644 --- a/md_processing/v2/dashboard_sheet.py +++ b/md_processing/v2/dashboard_sheet.py @@ -443,7 +443,8 @@ async def ensure_sheet(self, sheet_name: str, heading: str, description: str = " async def _resolve_report(self, report_name: str) -> Optional[str]: """The GUID of the Report a placement shows: the one `Report` whose displayName is exactly - `report_name` (the lookup the Portal uses), else the Report whose qualifiedName it is. None if there + `report_name` (an exact, type-filtered lookup: 0.1 s live, where a contains-search took ~35 s), + else the Report whose qualifiedName it is. None if there is none; two or more exact matches are a note, and no link. Not Dr.Egeria's `__async_get_guid__`: it tries a unique-name lookup first, which Egeria rejects @@ -453,8 +454,8 @@ async def _resolve_report(self, report_name: str) -> Optional[str]: start = 0 while True: try: - page = await self.client.classification_manager._async_find_elements_by_property_value( - report_name, ["displayName"], metadata_element_type="Report", starts_with=False, + page = await self.client.classification_manager._async_get_elements_by_property_value( + report_name, ["displayName"], metadata_element_type="Report", start_from=start, page_size=PAGE_SIZE, graph_query_depth=0) except PyegeriaNotFoundException: page = [] diff --git a/tests/micro-tests/dashboard_fake_egeria.py b/tests/micro-tests/dashboard_fake_egeria.py index 3150d4be..3f497496 100644 --- a/tests/micro-tests/dashboard_fake_egeria.py +++ b/tests/micro-tests/dashboard_fake_egeria.py @@ -145,6 +145,15 @@ async def _async_find_elements_by_property_value(self, property_value, property_ page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] return page if page else "No elements found" + async def _async_get_elements_by_property_value(self, property_value, property_names, metadata_element_type=None, + start_from=0, page_size=0, **kwargs): + """Exact match (classification-explorer by-exact-property-value).""" + hits = [self.element(g) for g, e in self.entities.items() + if (not metadata_element_type or e["type"] == metadata_element_type) + and any(e["props"].get(p) == property_value for p in property_names)] + page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] + return page if page else "No elements found" + async def _async_get_placement_reports(self, dashboard_guid, placement_qualified_names, **kwargs): element = self.element(dashboard_guid) links = [] From 1c899ed321231f506e0736fcad5eb8bf06d43912 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 15:10:43 +0000 Subject: [PATCH 4/9] feat(view): read dashboard sheets held in Egeria; migrate CLI (RS-DASH PR-2) load_dashboard_sheet(name) and list_dashboard_sheets() walk the Egeria 6.3 chain (Dashboard -> DisplayDataSchemaType -> DisplayDataContainer -> DisplayDataField placements) with the PR-1 writer's own primitives and return today's DashboardSheet / Placement model (EgeriaDashboardSheet / EgeriaPlacement subclasses add source, kind, note, breaks). Placement.ref is the linked Report's display name, through DataSetContent by queryId. Absence in words: a report placement whose DataSetContent is gone reads kind "missing", "report link missing in Egeria"; a sheet with a broken chain is listed with the break named, not dropped. dashboard_sheet_registry gains an EGERIA tier below the local sources; a local sheet overrides a same-named Egeria sheet with one warning. python -m pyegeria.view.dashboards list|show|migrate|delete: migrate writes from the JSON store through the PR-1 writer (idempotent, --dry-run lists every write, --rename for a scratch copy) and never writes the store. Gate: round trip of the five live sheets (fixture copied read-only 2026-11-09) gives equal models. Signed-off-by: Dan Wolfson --- pyegeria/view/dashboard_sheet_registry.py | 87 +++- pyegeria/view/dashboards.py | 384 +++++++++++++++++ tests/micro-tests/dashboard_fake_egeria.py | 5 + .../dashboard_sheets_live_2026_11_09.json | 398 ++++++++++++++++++ tests/micro-tests/test_dashboards_reader.py | 189 +++++++++ 5 files changed, 1050 insertions(+), 13 deletions(-) create mode 100644 pyegeria/view/dashboards.py create mode 100644 tests/micro-tests/data/dashboard_sheets_live_2026_11_09.json create mode 100644 tests/micro-tests/test_dashboards_reader.py diff --git a/pyegeria/view/dashboard_sheet_registry.py b/pyegeria/view/dashboard_sheet_registry.py index e2b847fa..281c680f 100644 --- a/pyegeria/view/dashboard_sheet_registry.py +++ b/pyegeria/view/dashboard_sheet_registry.py @@ -8,13 +8,16 @@ two stay co-elements: same env-var-driven JSON config pattern, same runtime registration API, same collision semantics. -Unlike report specs, there is no generated/built-in source here — no -Tinderbox/`refresh_specs` pipeline authors dashboard sheets as Egeria -elements (yet; see egeria-workspaces `OVERVIEW_REPORTING_MODEL.md` §10 for -the plan — Dashboard Sheet is planned to become an Egeria `Collection` -subtype). The registry is CONFIG (env-var JSON files) + RUNTIME (dynamically -registered, e.g. by the Dr.Egeria `Create Dashboard Sheet` command's -processor) only. +Unlike report specs, there is no generated/built-in source here. The tiers, +lowest first: + - EGERIA: sheets held in Egeria 6.3 as Dashboard element chains + (`pyegeria.view.dashboards`), loaded with `refresh_egeria_dashboard_sheets(client)` + or set with `set_egeria_dashboard_sheets(...)`. Never fetched implicitly: reading + the registry makes no Egeria call. + - CONFIG (env-var JSON files) and RUNTIME (registered at run time): the local + sources. Same precedence as report specs: a local sheet overrides a same-named + Egeria sheet, with one warning per name per process; never raised. +`get_dashboard_sheet_tier(name)` says which tier a sheet came from. This module is hand-written and safe to edit — unlike `base_report_formats.py`, nothing regenerates it. @@ -30,6 +33,10 @@ __all__ = [ 'DashboardSheetCollision', + 'clear_egeria_dashboard_sheets', + 'get_dashboard_sheet_tier', + 'refresh_egeria_dashboard_sheets', + 'set_egeria_dashboard_sheets', 'refresh_dashboard_sheets', 'get_dashboard_sheet_registry', 'register_dashboard_sheets', @@ -39,6 +46,9 @@ _RUNTIME_DASHBOARD_SHEETS = DashboardSheetDict() _CONFIG_DASHBOARD_SHEETS = DashboardSheetDict() +_EGERIA_DASHBOARD_SHEETS = DashboardSheetDict() +_REGISTRY_TIERS: dict = {} +_SHADOW_WARNED: set = set() class DashboardSheetCollision(ValueError): @@ -101,21 +111,72 @@ def refresh_dashboard_sheets() -> None: def get_dashboard_sheet_registry() -> DashboardSheetDict: - """Combine config-loaded and runtime dashboard sheets. Enforce no - duplicate names across sources.""" + """Combine the Egeria, config-loaded and runtime dashboard sheets. + + The local sources (CONFIG, RUNTIME) must not repeat a name between them (that raises, as before). A + local sheet overrides a same-named Egeria sheet: the Egeria one is left out, with one warning per name + per process.""" + local = DashboardSheetDict() + _add_with_collision_check(local, _CONFIG_DASHBOARD_SHEETS, source="CONFIG") + _add_with_collision_check(local, _RUNTIME_DASHBOARD_SHEETS, source="RUNTIME") + combined = DashboardSheetDict() - _add_with_collision_check(combined, _CONFIG_DASHBOARD_SHEETS, source="CONFIG") - _add_with_collision_check(combined, _RUNTIME_DASHBOARD_SHEETS, source="RUNTIME") + tiers = {} + for name, sheet in _EGERIA_DASHBOARD_SHEETS.items(): + if name in local.keys(): + if name not in _SHADOW_WARNED: + _SHADOW_WARNED.add(name) + logger.warning(f"Dashboard Sheet '{name}' is defined locally and held in Egeria; the local " + f"definition is used.") + continue + combined[name] = sheet + tiers[name] = "egeria" + for name, sheet in local.items(): + combined[name] = sheet + tiers[name] = "local" + _REGISTRY_TIERS.clear() + _REGISTRY_TIERS.update(tiers) return combined +def get_dashboard_sheet_tier(name: str): + """"egeria" or "local" for a sheet in the last registry read, else None.""" + if not _REGISTRY_TIERS: + get_dashboard_sheet_registry() + return _REGISTRY_TIERS.get(name) + + +def set_egeria_dashboard_sheets(sheets) -> None: + """Replace the EGERIA tier with these sheets (a DashboardSheetDict, a dict, or a list of sheets).""" + global _EGERIA_DASHBOARD_SHEETS + if isinstance(sheets, list): + sheets = {s.name: s for s in sheets} + _EGERIA_DASHBOARD_SHEETS = sheets if isinstance(sheets, DashboardSheetDict) else DashboardSheetDict(sheets) + + +def refresh_egeria_dashboard_sheets(client=None) -> int: + """Load the EGERIA tier from Egeria (`pyegeria.view.dashboards.list_dashboard_sheets`). Returns the + number of sheets. With no client, one is made from the environment.""" + from pyegeria.view.dashboards import list_dashboard_sheets + sheets = list_dashboard_sheets(client) + set_egeria_dashboard_sheets(sheets) + return len(sheets) + + +def clear_egeria_dashboard_sheets() -> None: + _EGERIA_DASHBOARD_SHEETS.clear() + _SHADOW_WARNED.clear() + + def register_dashboard_sheets(new_sheets: Union[DashboardSheetDict, dict], *, source: str = "runtime") -> None: """Dynamically add dashboard sheets at runtime. Raises on duplicate name.""" global _RUNTIME_DASHBOARD_SHEETS if not isinstance(new_sheets, DashboardSheetDict): new_sheets = DashboardSheetDict(new_sheets) - existing = get_dashboard_sheet_registry() - for name in new_sheets.keys(): + existing = DashboardSheetDict() + _add_with_collision_check(existing, _CONFIG_DASHBOARD_SHEETS, source="CONFIG") + _add_with_collision_check(existing, _RUNTIME_DASHBOARD_SHEETS, source="RUNTIME") + for name in new_sheets.keys(): # a runtime sheet may override an Egeria one; not another local one if name in existing.keys(): raise DashboardSheetCollision( f"Dashboard Sheet '{name}' already exists; cannot register from {source}") diff --git a/pyegeria/view/dashboards.py b/pyegeria/view/dashboards.py new file mode 100644 index 00000000..24b72723 --- /dev/null +++ b/pyegeria/view/dashboards.py @@ -0,0 +1,384 @@ +""" +SPDX-License-Identifier: Apache-2.0 +Copyright Contributors to the ODPi Egeria project. + +Dashboard sheets held in Egeria: the reader, and the migration from the local JSON store +(report-spec pipeline note v5.5 §8d / §10.6(c); BRIEF RS-DASH PR-2). + + load_dashboard_sheet(name) -> the sheet, read from its Egeria element chain, or None + list_dashboard_sheets() -> every sheet held in Egeria (Dashboard::* elements) + +Both return today's `DashboardSheet` / `Placement` model, so a consumer keeps its code. The objects are the +subclasses `EgeriaDashboardSheet` / `EgeriaPlacement`, which add only what an Egeria-held sheet must say: +`source` ("egeria"), a placement's `kind` ("report" / "text" / "missing") and `note`, and a sheet's `breaks`. +`as_local_model()` drops those, giving a plain `DashboardSheet` that compares equal to the JSON record it +was written from. + +Absence is said in words, never as an empty value: + - a REPORT placement whose field exists but whose DataSetContent link is gone reads `kind: "missing"`, + note "report link missing in Egeria" (its `ref` is the placement's name, so it can still be shown); + - a sheet whose chain is broken (no layout schema, no sheet container) is listed with the break named + in `breaks`, not dropped. + +The chain is walked with the same primitives that write it (md_processing.v2.dashboard_sheet), so the +writer and the reader cannot disagree about its shape. Every Egeria read is bounded: page size 25, +graph_query_depth 0, paged until an empty page. + +Command line (writes are shared writes: run them only with the owner's word and the Coordinator's CLEAR): + + python -m pyegeria.view.dashboards list + python -m pyegeria.view.dashboards show NAME + python -m pyegeria.view.dashboards migrate [--sheet NAME] [--rename NEW_NAME] [--store PATH] [--dry-run] + python -m pyegeria.view.dashboards delete --sheet NAME [--dry-run] [--local] + +`migrate` reads the JSON store and writes each sheet through PR-1's writer (one implementation); it is +idempotent by qualifiedName, and `--dry-run` lists every element it would create. It never writes the +store. `delete` removes a sheet's Egeria chain (never its Reports or ReportSpecs); `--local` also removes +the store record. +""" +from __future__ import annotations + +import argparse +import asyncio +import os +import sys +from typing import Any, Dict, List, Literal, Optional + +from loguru import logger +from pydantic import Field + +from md_processing.v2.dashboard_sheet import ( + DASHBOARD_QN_PREFIX, DashboardSheetEgeriaWriter, _default_store_path, _load_store, dashboard_qn, + sheet_name_from_dashboard_qn, +) +from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, DashboardSheetDict, Placement + +__all__ = [ + "EgeriaDashboardSheet", "EgeriaPlacement", "REPORT_LINK_MISSING", "as_local_model", + "async_list_dashboard_sheets", "async_load_dashboard_sheet", "async_migrate_dashboard_sheets", + "list_dashboard_sheets", "load_dashboard_sheet", "main", "read_sheet_from_chain", +] + +PAGE_SIZE = 25 +REPORT_LINK_MISSING = "report link missing in Egeria" +_SPANS = ("1", "2", "full") +_STYLES = ("kpi", "panel") + + +class EgeriaPlacement(Placement): + """A Placement read from Egeria. `kind`: "report", "text", or "missing" (a report placement whose + report link is gone); `note` says what is missing or odd, in words.""" + kind: Literal["report", "text", "missing"] = "report" + note: Optional[str] = None + source: str = "egeria" + + +class EgeriaDashboardSheet(DashboardSheet): + """A DashboardSheet read from Egeria. `breaks` names each broken link of its element chain (empty when + the chain is whole); `guid` is the Dashboard's.""" + source: str = "egeria" + guid: Optional[str] = None + breaks: List[str] = Field(default_factory=list) + + +def as_local_model(sheet: DashboardSheet) -> DashboardSheet: + """The plain DashboardSheet / Placement form of a sheet (Egeria-only fields dropped), as the JSON store + holds it. A whole Egeria sheet compares equal to the record it was written from.""" + base_fields = set(Placement.model_fields) + placements = [Placement(**{k: v for k, v in (p if isinstance(p, dict) else p.model_dump()).items() + if k in base_fields}) for p in sheet.placements] + return DashboardSheet(name=sheet.name, heading=sheet.heading, description=sheet.description, + aliases=list(sheet.aliases), family=sheet.family, placements=placements) + + +# ---------------------------------------------------------------------------- reading + +def _split_labels(value: Any) -> List[str]: + if isinstance(value, list): + return [str(v).strip() for v in value if str(v).strip()] + return [p.strip() for p in str(value or "").split(",") if p.strip()] + + +async def _perspective_labels(writer: DashboardSheetEgeriaWriter, field_guid: str) -> List[str]: + """Labels from the field's ScopedBy links, for a field that does not carry its labels.""" + out = [] + for e in await writer._related(field_guid, "ScopedBy", start_at_end=2): + if writer._type(e) != "Perspective": + continue + qn = (e.get("properties") or {}).get("qualifiedName") or "" + out.append(qn.split("::", 1)[1] if qn.startswith("Perspective::") else qn) + return out + + +async def _detail_spec_name(writer: DashboardSheetEgeriaWriter, field_guid: str) -> Optional[str]: + for e in await writer._related(field_guid, "DataDescription", start_at_end=1): + props = e.get("properties") or {} + return props.get("displayName") or props.get("qualifiedName") + return None + + +async def read_sheet_from_chain(client: Any, sheet_name: str, + dashboard: Optional[Dict[str, Any]] = None) -> Optional[EgeriaDashboardSheet]: + """Read one sheet by walking its Egeria chain. None if there is no `Dashboard::`.""" + writer = DashboardSheetEgeriaWriter(client) + chain = await writer.find_chain(sheet_name) + if not chain.dashboard_guid: + return None + props = (chain.dashboard or dashboard or {}).get("properties") or {} + extra = props.get("additionalProperties") or {} + sheet = EgeriaDashboardSheet( + name=sheet_name, heading=props.get("displayName") or sheet_name, + description=props.get("description") or "", aliases=list(props.get("aliases") or []), + family=extra.get("family") or None, guid=chain.dashboard_guid) + + if not chain.schema_type_guid: + sheet.breaks.append("no layout schema: the Dashboard has no Schema link to a DisplayDataSchemaType") + return sheet + if not chain.container_guid: + sheet.breaks.append("no sheet container: the DisplayDataSchemaType has no AttributeForSchema link to a " + "DisplayDataContainer") + return sheet + + fields = await writer.list_fields(chain.container_guid) + bindings: Dict[str, Dict[str, Any]] = {} + report_qns = [f.qualified_name for f in fields if (f.properties.get("placementKind") or "report") != "text"] + if report_qns: + bindings = await client.asset_maker._async_get_placement_reports(chain.dashboard_guid, report_qns) or {} + + for f in fields: + fp = f.properties + f_extra = fp.get("additionalProperties") or {} + notes: List[str] = [] + if f.position is None: + notes.append("no position on its NestedSchemaAttribute link; shown last") + span = str(fp.get("span") or "1") + if span not in _SPANS: + notes.append(f"span '{span}' is not one of {', '.join(_SPANS)}; shown as 1") + span = "1" + style = str(fp.get("presentationStyle") or "kpi") + if style not in _STYLES: + notes.append(f"presentationStyle '{style}' is not one of {', '.join(_STYLES)}; shown as kpi") + style = "kpi" + if "perspectives" in f_extra: + perspectives = _split_labels(f_extra.get("perspectives")) + else: + perspectives = await _perspective_labels(writer, f.guid) + detail_spec = f_extra.get("detailSpec") or await _detail_spec_name(writer, f.guid) + + kind = fp.get("placementKind") or "report" + if kind == "text": + content = fp.get("markdownContent") + if content is None: + notes.append("text placement with no markdownContent in Egeria") + content = "" + placement = EgeriaPlacement(ref=f.display_name, span=span, emphasis=style, content=content, + perspectives=perspectives, detail_spec=detail_spec, kind="text") + else: + binding = bindings.get(f.qualified_name) or {"state": "unbound", "links": []} + if binding.get("state") == "bound" and binding.get("report_name"): + placement = EgeriaPlacement(ref=binding["report_name"], span=span, emphasis=style, + perspectives=perspectives, detail_spec=detail_spec, kind="report") + else: + if binding.get("state") == "ambiguous": + notes.insert(0, f"{len(binding['links'])} reports are linked to this placement in Egeria; " + f"none is chosen") + else: + notes.insert(0, REPORT_LINK_MISSING) + placement = EgeriaPlacement(ref=f.display_name, span=span, emphasis=style, + perspectives=perspectives, detail_spec=detail_spec, kind="missing") + if notes: + placement.note = "; ".join(notes) + sheet.placements.append(placement) + return sheet + + +async def async_load_dashboard_sheet(client: Any, name: str) -> Optional[EgeriaDashboardSheet]: + """The Egeria-held sheet `name` (its Dashboard is `Dashboard::`), or None.""" + return await read_sheet_from_chain(client, name) + + +async def _dashboard_elements(client: Any) -> List[Dict[str, Any]]: + """Every Dashboard whose qualifiedName starts `Dashboard::`. Read by type in pages of 25 (Dashboard is a + small type; only an empty page ends the read) and filtered here: a starts-with search on qualifiedName + took 21 s on the live platform with no Dashboards at all, the type read 2.8 s.""" + out: List[Dict[str, Any]] = [] + start = 0 + while True: + page = await client.classification_manager._async_get_elements( + "Dashboard", start_from=start, page_size=PAGE_SIZE, graph_query_depth=0) + items = [e for e in page if isinstance(e, dict) and e.get("elementHeader")] if isinstance(page, list) else [] + if not items: + return out + out.extend(e for e in items + if ((e.get("properties") or {}).get("qualifiedName") or "").startswith(DASHBOARD_QN_PREFIX)) + start += len(items) + + +async def async_list_dashboard_sheets(client: Any) -> List[EgeriaDashboardSheet]: + """Every sheet held in Egeria, by name. A Dashboard whose chain is broken (for example one made with + plain `Create Dashboard`) is listed with its `breaks`, not dropped.""" + sheets: List[EgeriaDashboardSheet] = [] + seen = set() + for element in await _dashboard_elements(client): + name = sheet_name_from_dashboard_qn((element.get("properties") or {}).get("qualifiedName") or "") + if not name or name in seen: + continue + seen.add(name) + sheet = await read_sheet_from_chain(client, name, dashboard=element) + if sheet is not None: + sheets.append(sheet) + sheets.sort(key=lambda s: s.name.lower()) + return sheets + + +def _client_from_env() -> Any: + """An EgeriaTech client from the environment (EGERIA_VIEW_SERVER, EGERIA_VIEW_SERVER_URL or + EGERIA_PLATFORM_URL, EGERIA_USER / EGERIA_USER_PASSWORD, else pyegeria's settings), not yet signed in.""" + from pyegeria import EgeriaTech + from pyegeria.core.config import resolve_egeria_credentials, settings + server = os.environ.get("EGERIA_VIEW_SERVER") or settings.Environment.egeria_view_server + url = (os.environ.get("EGERIA_VIEW_SERVER_URL") or os.environ.get("EGERIA_PLATFORM_URL") + or settings.Environment.egeria_view_server_url) + user, pwd = resolve_egeria_credentials() + return EgeriaTech(server, url, user, pwd) + + +async def _signed_in_client() -> Any: + client = _client_from_env() + await client._async_create_egeria_bearer_token(client.user_id, client.user_pwd) + return client + + +def load_dashboard_sheet(name: str, client: Any = None) -> Optional[EgeriaDashboardSheet]: + """Sync form of async_load_dashboard_sheet. With no client, one is made from the environment.""" + from pyegeria.core.async_runner import run_sync + + async def _go(): + return await async_load_dashboard_sheet(client or await _signed_in_client(), name) + return run_sync(_go()) + + +def list_dashboard_sheets(client: Any = None) -> List[EgeriaDashboardSheet]: + """Sync form of async_list_dashboard_sheets. With no client, one is made from the environment.""" + from pyegeria.core.async_runner import run_sync + + async def _go(): + return await async_list_dashboard_sheets(client or await _signed_in_client()) + return run_sync(_go()) + + +# ---------------------------------------------------------------------------- migration + +async def async_migrate_dashboard_sheets(client: Any, sheets: DashboardSheetDict, *, + only: Optional[str] = None, rename: Optional[str] = None, + dry_run: bool = False) -> Dict[str, DashboardSheetEgeriaWriter]: + """Write sheets from the JSON store to Egeria through the PR-1 writer, one writer per sheet (so each + sheet's actions and notes stay apart). Idempotent by qualifiedName. Never writes the store. + + `only` picks one sheet; `rename` writes it under another name (a scratch copy, e.g. for a live test). + """ + if rename and not only: + raise ValueError("--rename needs --sheet: it renames one sheet") + selected = [sheets[only]] if only else list(sheets.values()) + results: Dict[str, DashboardSheetEgeriaWriter] = {} + for sheet in selected: + target = sheet.model_copy(deep=True) + if rename: + target.name = rename + writer = DashboardSheetEgeriaWriter(client, dry_run=dry_run) + await writer.write_sheet(target) + results[target.name] = writer + return results + + +# ---------------------------------------------------------------------------- command line + +def _print_actions(name: str, writer: DashboardSheetEgeriaWriter, dry_run: bool) -> None: + changed = [a for a in writer.actions if not a.startswith("unchanged")] + title = "would make" if dry_run else "made" + print(f"\n== {name}: {title} {len(changed)} change(s), {len(writer.actions) - len(changed)} unchanged") + for action in writer.actions: + print(f" {'(dry run) ' if dry_run and not action.startswith('unchanged') else ''}{action}") + for note in writer.notes: + print(f" NOTE: {note}") + + +def _print_sheet(sheet: EgeriaDashboardSheet) -> None: + print(f"{sheet.name} | {sheet.heading} | {len(sheet.placements)} placement(s)" + + (f" | BROKEN: {'; '.join(sheet.breaks)}" if sheet.breaks else "")) + for i, p in enumerate(sheet.placements, start=1): + print(f" {i:>2}. [{p.kind}] {p.ref} (span {p.span}, {p.emphasis})" + + (f" perspectives={','.join(p.perspectives)}" if p.perspectives else "") + + (f" detail={p.detail_spec}" if p.detail_spec else "") + + (f" -- {p.note}" if p.note else "")) + + +async def _amain(args: argparse.Namespace) -> int: + client = await _signed_in_client() + if args.command == "list": + for sheet in await async_list_dashboard_sheets(client): + _print_sheet(sheet) + return 0 + if args.command == "show": + sheet = await async_load_dashboard_sheet(client, args.name) + if sheet is None: + print(f"No dashboard sheet '{args.name}' in Egeria (looked for {dashboard_qn(args.name)}).") + return 1 + _print_sheet(sheet) + return 0 + if args.command == "migrate": + store = args.store or _default_store_path() + sheets = _load_store(store) + if args.sheet and args.sheet not in sheets: + print(f"No sheet '{args.sheet}' in {store}.") + return 1 + print(f"Migrating from {store}{' (DRY RUN: nothing is written)' if args.dry_run else ''}") + results = await async_migrate_dashboard_sheets(client, sheets, only=args.sheet, rename=args.rename, + dry_run=args.dry_run) + for name, writer in results.items(): + _print_actions(name, writer, args.dry_run) + return 0 + if args.command == "delete": + writer = DashboardSheetEgeriaWriter(client, dry_run=args.dry_run) + found = await writer.delete_sheet(args.sheet) + if not found: + print(f"No dashboard sheet '{args.sheet}' in Egeria (looked for {dashboard_qn(args.sheet)}).") + else: + _print_actions(args.sheet, writer, args.dry_run) + if args.local and not args.dry_run: + store = args.store or _default_store_path() + sheets = _load_store(store) + if args.sheet in sheets.keys(): + del sheets[args.sheet] + sheets.save_to_json(store) + print(f"Removed '{args.sheet}' from {store}.") + return 0 if found else 1 + return 2 + + +def main(argv: Optional[List[str]] = None) -> int: + parser = argparse.ArgumentParser(prog="python -m pyegeria.view.dashboards", + description="Dashboard sheets held in Egeria: read, migrate, delete.") + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("list", help="list the sheets held in Egeria") + show = sub.add_parser("show", help="read one sheet from Egeria") + show.add_argument("name") + mig = sub.add_parser("migrate", help="write sheets from the JSON store to Egeria (a shared write)") + mig.add_argument("--sheet", help="migrate only this sheet") + mig.add_argument("--rename", help="write the --sheet under this name instead (a scratch copy)") + mig.add_argument("--store", help="the JSON store (default PYEGERIA_DASHBOARD_SHEETS_STORE or " + "~/.pyegeria/dashboard_sheets.json)") + mig.add_argument("--dry-run", action="store_true", help="list every write; write nothing") + dele = sub.add_parser("delete", help="delete a sheet's Egeria chain (never its Reports)") + dele.add_argument("--sheet", required=True) + dele.add_argument("--dry-run", action="store_true") + dele.add_argument("--local", action="store_true", help="also remove the sheet from the JSON store") + dele.add_argument("--store") + args = parser.parse_args(argv) + logger.remove() + logger.add(sys.stderr, level=os.environ.get("PYEGERIA_DASHBOARDS_LOG_LEVEL", "WARNING")) + return asyncio.run(_amain(args)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/micro-tests/dashboard_fake_egeria.py b/tests/micro-tests/dashboard_fake_egeria.py index 3f497496..8d40b93e 100644 --- a/tests/micro-tests/dashboard_fake_egeria.py +++ b/tests/micro-tests/dashboard_fake_egeria.py @@ -154,6 +154,11 @@ async def _async_get_elements_by_property_value(self, property_value, property_n page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] return page if page else "No elements found" + async def _async_get_elements(self, metadata_element_type="Referenceable", start_from=0, page_size=10, **kwargs): + hits = [self.element(g) for g, e in self.entities.items() if e["type"] == metadata_element_type] + page = hits[start_from:start_from + page_size] if page_size else hits[start_from:] + return page if page else "No elements found" + async def _async_get_placement_reports(self, dashboard_guid, placement_qualified_names, **kwargs): element = self.element(dashboard_guid) links = [] diff --git a/tests/micro-tests/data/dashboard_sheets_live_2026_11_09.json b/tests/micro-tests/data/dashboard_sheets_live_2026_11_09.json new file mode 100644 index 00000000..5b30c471 --- /dev/null +++ b/tests/micro-tests/data/dashboard_sheets_live_2026_11_09.json @@ -0,0 +1,398 @@ +{ + "local-dashboards-next-steps": { + "name": "local-dashboards-next-steps", + "heading": "Local Dashboards \u2014 Next Steps", + "description": "The open punch list for the Local Dashboards / Egeria Overview feature, tracked as a real Egeria Work Item List and browsable right here as a Dashboard Sheet.", + "aliases": [], + "family": null, + "placements": [ + { + "ref": "Next Steps Work Item List", + "span": "2", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Next Steps Membership Diagram", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Project Count", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Term Count", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Term Definition Completeness", + "span": "2", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Tasks", + "span": "2", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "My own mermaid", + "span": "full", + "emphasis": "panel", + "content": "This is could be a bunch of content.\n**italics?**", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Test-MD", + "span": "full", + "emphasis": "panel", + "content": "This is a simple test.", + "perspectives": [], + "detail_spec": null + } + ] + }, + "Assets by Type and Location Demo": { + "name": "Assets by Type and Location Demo", + "heading": "Assets by Type & Location", + "description": "Demo dashboard: how many assets, of which type, are cataloged, and where they're located \u2014 a mix of live charts, KPI numbers, and a location snapshot.", + "aliases": [], + "family": "dashboard", + "placements": [ + { + "ref": "Total Cataloged Assets", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Total Locations Tracked", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Assets by Type (Pie Chart)", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Assets by Type (Bar Chart)", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Assets by Location Snapshot", + "span": "full", + "emphasis": "panel", + "content": "**Assets by Location** \u2014 snapshot as of authoring time, built from real live\n`/api/locations` data (no live \"group assets by Location\" analytic function\nexists yet, so unlike the tiles above this panel doesn't re-query on every\nview \u2014 see this step's own commentary above for what a live version would\nneed). 37 locations are tracked in Egeria; 5 currently have assets\nregistered against them, all `SoftwareServer` infrastructure, 9 assets\ntotal.\n\n```mermaid\npie title Assets by Location (SoftwareServer)\n \"Amsterdam Data Centre\" : 5\n \"Austin Data Center\" : 1\n \"New York Data Center\" : 1\n \"Sales4U\" : 1\n \"Winchester Data Centre\" : 1\n```\n\n| Location | Asset Count | Asset Type |\n|---|---|---|\n| Amsterdam Data Centre | 5 | SoftwareServer |\n| Austin Data Center | 1 | SoftwareServer |\n| New York Data Center | 1 | SoftwareServer |\n| Sales4U | 1 | SoftwareServer |\n| Winchester Data Centre | 1 | SoftwareServer |\n\nThe remaining 32 tracked locations have no assets registered against them\nyet in this demo dataset.", + "perspectives": [], + "detail_spec": null + } + ] + }, + "digital-product-portfolio": { + "name": "digital-product-portfolio", + "heading": "Digital Product Portfolio & Subscriptions", + "description": "A high-level view of our data product ecosystem and adoption metrics.", + "aliases": [], + "family": null, + "placements": [ + { + "ref": "Total Products Count", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Active Subscriptions Count", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Subscription Growth Trend", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Product Subscription Map", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + } + ] + }, + "my-team-dashboard": { + "name": "my-team-dashboard", + "heading": "My Team Dashboard", + "description": "Whatever this dashboard is for.", + "aliases": [], + "family": null, + "placements": [ + { + "ref": "My Team Work Items", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + } + ] + }, + "Chief Data Officer Dashboard": { + "name": "Chief Data Officer Dashboard", + "heading": "How the Data Governance Program is Going", + "description": "Jules Keeper's view of the data governance program at Coco Pharmaceuticals: whether the program has been built, whether the DATA domain's own metrics are moving, whether the common vocabulary is in use, whether the data hub is delivering, and where things stand against the ninety day plan and the risk register.", + "aliases": [], + "family": "dashboard", + "placements": [ + { + "ref": "Introduction", + "span": "full", + "emphasis": "panel", + "content": "**How is the data governance program going?** Every tile below is a live query against Egeria, so this page changes as the domain teams, the data hub team and the data governance team add to the catalog. The DATA domain exists in service of the domains that carry business and regulatory responsibility, so most tiles measure the shared foundation those domains depend on. Where a governance metric has no live measure yet, the dashboard says so rather than leaving it out.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Section 1 - Program Built", + "span": "full", + "emphasis": "panel", + "content": "**1. Has the governance program been built?** The governance definitions defined by all the governance leaders and their teams, the metrics that make them observable, and the information supply chains and blueprints that put the data in a business context.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Governance Definitions by Type", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": null + }, + { + "ref": "Governance Metrics Defined", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": "Governance-Metric-DrE-Basic" + }, + { + "ref": "Supply Chains and Blueprints", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": null + }, + { + "ref": "Section 2 - DATA Metrics", + "span": "full", + "emphasis": "panel", + "content": "**2. Are the DATA domain's own metrics moving?** The data governance program defines six metrics. Three have a live measure below: *Percentage of Data Assets with Designated Owner* (Data Asset Ownership, a direct measure), *Catalog Registration Coverage* (Governance Classification Coverage and Catalog Freshness, a partial measure until discovery scanning runs) and *Lineage Coverage for Critical Data Elements* (Solution Design Context, a proxy: the first hop from an asset to the design it implements, not an end-to-end lineage path).", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Data Asset Ownership", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "owner" + ], + "detail_spec": null + }, + { + "ref": "Governance Classification Coverage", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Catalog Freshness", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Solution Design Context", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "engineer" + ], + "detail_spec": null + }, + { + "ref": "Data Quality Not Yet Measured", + "span": "full", + "emphasis": "panel", + "content": "**Not yet measured: data quality.** Three of the DATA domain's metrics \u2014 *Critical Data Element Quality Expectation Coverage*, *Data Quality Rule Pass Rate* (target 98% or above) and *Open Data Quality Issues by Age* (target: nothing older than seven days on critical data) \u2014 need automated quality rule results and a record of the issues they raise. The clinical trials pipeline in `2. clinical-trials` runs quality checks, but their results are not yet recorded in the catalog in a form these tiles can count. Until they are, the honest answer to *how good is our data?* is *we cannot yet say*, and closing this gap is the next priority for Erin Overview and Peter Profile.", + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Section 3 - Vocabulary", + "span": "full", + "emphasis": "panel", + "content": "**3. Is the common vocabulary being used?** A glossary term is only useful once it is defined, and only does its job once it is attached to the data it describes. The first tile shows how many terms have a definition; the second shows how many terms are actually assigned to something in the catalog.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Glossary Definition Completeness", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Glossary Terms in Use", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [ + "governance", + "steward" + ], + "detail_spec": null + }, + { + "ref": "Section 4 - Data Hub", + "span": "full", + "emphasis": "panel", + "content": "**4. Is the data hub delivering?** The digital products that deliver critical data between systems, how the catalog has grown over the last ninety days, and the register of strategic information supply chains the company governs and monitors at company level.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Digital Products Published", + "span": "1", + "emphasis": "kpi", + "content": null, + "perspectives": [], + "detail_spec": "Digital-Products" + }, + { + "ref": "Catalog Growth - Last Ninety Days", + "span": "2", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Strategic Information Supply Chain Register", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": "Information-Supply-Chain-DrE-Basic" + }, + { + "ref": "Section 5 - Plan Risks Metrics", + "span": "full", + "emphasis": "panel", + "content": "**5. The plan, the risks and the metrics.** The ninety day plan with the status of each phase and task, the company risk register built by all the governance leaders, and the full governance metric register \u2014 the metrics system the Impact Phase set out to build, of which the tiles above are the first live measures.", + "perspectives": [], + "detail_spec": null + }, + { + "ref": "My Ninety Day Plan Progress", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [], + "detail_spec": null + }, + { + "ref": "Company Risk Register", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": null + }, + { + "ref": "Governance Metric Register", + "span": "full", + "emphasis": "panel", + "content": null, + "perspectives": [ + "governance" + ], + "detail_spec": null + } + ] + } +} \ No newline at end of file diff --git a/tests/micro-tests/test_dashboards_reader.py b/tests/micro-tests/test_dashboards_reader.py new file mode 100644 index 00000000..6d03fe2e --- /dev/null +++ b/tests/micro-tests/test_dashboards_reader.py @@ -0,0 +1,189 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright Contributors to the ODPi Egeria project. +""" +Dashboard sheets held in Egeria: the reader (BRIEF RS-DASH PR-2). + +Gate: a round trip on fakes. Every live sheet's JSON (the five sheets in the Portal's store, copied read +only on 2026-11-09 to data/dashboard_sheets_live_2026_11_09.json) -> Egeria elements (through the PR-1 +writer, as `migrate` does) -> DashboardSheet gives an EQUAL model: order, span, style, perspectives, text +and refs. Plus the two absence cases, worded; the registry's EGERIA tier; migrate's idempotence. +""" +import importlib.util +import json +import pathlib + +import pytest + +from md_processing.v2.dashboard_sheet import DashboardSheetEgeriaWriter +from pyegeria.view import dashboard_sheet_registry as registry +from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, DashboardSheetDict +from pyegeria.view.dashboards import ( + REPORT_LINK_MISSING, EgeriaDashboardSheet, as_local_model, async_list_dashboard_sheets, + async_load_dashboard_sheet, async_migrate_dashboard_sheets, +) + +_HERE = pathlib.Path(__file__).parent +_spec = importlib.util.spec_from_file_location("dashboard_fake_egeria", _HERE / "dashboard_fake_egeria.py") +fake_egeria = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(fake_egeria) + +LIVE = json.loads((_HERE / "data" / "dashboard_sheets_live_2026_11_09.json").read_text()) + + +def _egeria_with_reports(sheets: dict): + fake = fake_egeria.FakeEgeria() + fake_egeria.seed_perspectives(fake) + for sheet in sheets.values(): + for p in sheet["placements"]: + if p.get("content") is None and not fake.by_qn(f"DeployedReport::{p['ref']}"): + fake.add_entity("Report", f"DeployedReport::{p['ref']}", p["ref"]) + return fake + + +def test_fixture_is_the_five_live_sheets(): + assert sorted(LIVE) == sorted(["Chief Data Officer Dashboard", "local-dashboards-next-steps", + "Assets by Type and Location Demo", "digital-product-portfolio", + "my-team-dashboard"]) + placements = [p for s in LIVE.values() for p in s["placements"]] + assert len(placements) == 40 + assert sum(1 for p in placements if p.get("content") is not None) == 10 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("name", sorted(LIVE)) +async def test_round_trip_every_live_sheet(name): + fake = _egeria_with_reports(LIVE) + original = DashboardSheet(**LIVE[name]) + + await DashboardSheetEgeriaWriter(fake).write_sheet(original) + loaded = await async_load_dashboard_sheet(fake, name) + + assert isinstance(loaded, EgeriaDashboardSheet) and loaded.breaks == [] + assert as_local_model(loaded) == original + assert all(p.kind in ("report", "text") and p.note is None for p in loaded.placements) + # still the base model, so consumers keep their code + assert isinstance(loaded, DashboardSheet) + + +@pytest.mark.asyncio +async def test_list_returns_all_live_sheets_and_migrate_is_idempotent(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + + first = await async_migrate_dashboard_sheets(fake, store) + writes = list(fake.writes) + second = await async_migrate_dashboard_sheets(fake, store) + + assert fake.writes == writes + assert all(not [a for a in w.actions if not a.startswith("unchanged")] for w in second.values()) + sheets = await async_list_dashboard_sheets(fake) + assert [s.name for s in sheets] == sorted(LIVE, key=str.lower) + assert {s.name: as_local_model(s) for s in sheets} == {k: DashboardSheet(**v) for k, v in LIVE.items()} + # element counts: per sheet Dashboard + schema type + container, one field per placement + assert len(fake.of_type("Dashboard")) == 5 and len(fake.of_type("DisplayDataField")) == 40 + assert len(fake.rels("DataSetContent")) == 30 + assert sum(len(w.actions) for w in first.values()) > 0 + + +@pytest.mark.asyncio +async def test_dry_run_migrate_writes_nothing(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + results = await async_migrate_dashboard_sheets(fake, store, dry_run=True) + assert fake.writes == [] + creates = [a for w in results.values() for a in w.actions if a.startswith("create")] + assert len(creates) == 5 * 3 + 40 + + +@pytest.mark.asyncio +async def test_rename_writes_a_scratch_copy(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + await async_migrate_dashboard_sheets(fake, store, only="my-team-dashboard", + rename="scratch-my-team-dashboard") + loaded = await async_load_dashboard_sheet(fake, "scratch-my-team-dashboard") + expected = DashboardSheet(**{**LIVE["my-team-dashboard"], "name": "scratch-my-team-dashboard"}) + assert as_local_model(loaded) == expected + assert await async_load_dashboard_sheet(fake, "my-team-dashboard") is None + + +# ---------------------------------------------------------------------------- absences, in words + +@pytest.mark.asyncio +async def test_report_link_gone_reads_missing(): + fake = _egeria_with_reports(LIVE) + name = "digital-product-portfolio" + await DashboardSheetEgeriaWriter(fake).write_sheet(DashboardSheet(**LIVE[name])) + gone = next(r for r in fake.rels("DataSetContent") if r["props"]["queryId"].endswith("::Total Products Count")) + fake.relationships.remove(gone) + + loaded = await async_load_dashboard_sheet(fake, name) + + first = loaded.placements[0] + assert (first.kind, first.ref, first.note) == ("missing", "Total Products Count", REPORT_LINK_MISSING) + assert [p.kind for p in loaded.placements[1:]] == ["report"] * 3 + + +@pytest.mark.asyncio +async def test_broken_chain_is_listed_with_the_break_named(): + fake = _egeria_with_reports(LIVE) + await DashboardSheetEgeriaWriter(fake).write_sheet(DashboardSheet(**LIVE["my-team-dashboard"])) + fake.relationships = [r for r in fake.relationships if r["type"] != "AttributeForSchema"] + fake.add_entity("Dashboard", "Dashboard::plain", "A plain Create Dashboard") # no chain at all + + sheets = {s.name: s for s in await async_list_dashboard_sheets(fake)} + + assert sheets["my-team-dashboard"].breaks == [ + "no sheet container: the DisplayDataSchemaType has no AttributeForSchema link to a DisplayDataContainer"] + assert sheets["plain"].breaks == [ + "no layout schema: the Dashboard has no Schema link to a DisplayDataSchemaType"] + assert sheets["plain"].heading == "A plain Create Dashboard" and sheets["plain"].placements == [] + + +@pytest.mark.asyncio +async def test_unknown_sheet_is_none(): + assert await async_load_dashboard_sheet(fake_egeria.FakeEgeria(), "nope") is None + + +# ---------------------------------------------------------------------------- registry tier + +@pytest.fixture +def clean_registry(monkeypatch): + monkeypatch.delenv("PYEGERIA_DASHBOARD_SHEETS_JSON", raising=False) + monkeypatch.delenv("PYEGERIA_DASHBOARD_SHEETS_MODULES", raising=False) + registry.refresh_dashboard_sheets() + registry.clear_runtime_dashboard_sheets() + registry.clear_egeria_dashboard_sheets() + yield + registry.clear_runtime_dashboard_sheets() + registry.clear_egeria_dashboard_sheets() + registry.refresh_dashboard_sheets() + + +def test_local_overrides_egeria_with_one_warning(clean_registry, tmp_path, monkeypatch): + egeria_a = EgeriaDashboardSheet(name="a", heading="A from Egeria") + egeria_b = EgeriaDashboardSheet(name="b", heading="B from Egeria") + registry.set_egeria_dashboard_sheets([egeria_a, egeria_b]) + path = tmp_path / "local.json" + path.write_text(json.dumps({"a": {"name": "a", "heading": "A local"}})) + monkeypatch.setenv("PYEGERIA_DASHBOARD_SHEETS_JSON", str(path)) + registry.refresh_dashboard_sheets() + + warnings = [] + handler = registry.logger.add(lambda m: warnings.append(m), level="WARNING") + try: + combined = registry.get_dashboard_sheet_registry() + registry.get_dashboard_sheet_registry() + finally: + registry.logger.remove(handler) + + assert combined["a"].heading == "A local" and combined["b"].heading == "B from Egeria" + assert registry.get_dashboard_sheet_tier("a") == "local" + assert registry.get_dashboard_sheet_tier("b") == "egeria" + assert len([w for w in warnings if "'a'" in w]) == 1 + + +def test_runtime_registration_may_shadow_egeria(clean_registry): + registry.set_egeria_dashboard_sheets([EgeriaDashboardSheet(name="x", heading="X from Egeria")]) + registry.register_dashboard_sheets({"x": DashboardSheet(name="x", heading="X runtime")}) + assert registry.get_dashboard_sheet_registry()["x"].heading == "X runtime" From 4da60729c0cb4e3af4679d61aad6ef6bc241c86c Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 15:12:03 +0000 Subject: [PATCH 5/9] feat(view): migrated dashboards are owned by the migrating user (DB-3) migrate classifies each Dashboard with Ownership (owner = the signed-in user, or --owner), once; no zone is set, so the sheet is shared in the default zone. The dry run lists the classification. Signed-off-by: Dan Wolfson --- pyegeria/view/dashboards.py | 32 +++++++++++++++++++-- tests/micro-tests/dashboard_fake_egeria.py | 11 +++++-- tests/micro-tests/test_dashboards_reader.py | 23 +++++++++++++++ 3 files changed, 61 insertions(+), 5 deletions(-) diff --git a/pyegeria/view/dashboards.py b/pyegeria/view/dashboards.py index 24b72723..710569cc 100644 --- a/pyegeria/view/dashboards.py +++ b/pyegeria/view/dashboards.py @@ -271,14 +271,18 @@ async def _go(): async def async_migrate_dashboard_sheets(client: Any, sheets: DashboardSheetDict, *, only: Optional[str] = None, rename: Optional[str] = None, - dry_run: bool = False) -> Dict[str, DashboardSheetEgeriaWriter]: + dry_run: bool = False, + owner: Optional[str] = None) -> Dict[str, DashboardSheetEgeriaWriter]: """Write sheets from the JSON store to Egeria through the PR-1 writer, one writer per sheet (so each sheet's actions and notes stay apart). Idempotent by qualifiedName. Never writes the store. `only` picks one sheet; `rename` writes it under another name (a scratch copy, e.g. for a live test). + DB-3: the sheets are shared (default zone) and owned by `owner`, by default the client's user. """ if rename and not only: raise ValueError("--rename needs --sheet: it renames one sheet") + if owner is None: + owner = getattr(client, "user_id", None) selected = [sheets[only]] if only else list(sheets.values()) results: Dict[str, DashboardSheetEgeriaWriter] = {} for sheet in selected: @@ -286,11 +290,32 @@ async def async_migrate_dashboard_sheets(client: Any, sheets: DashboardSheetDict if rename: target.name = rename writer = DashboardSheetEgeriaWriter(client, dry_run=dry_run) - await writer.write_sheet(target) + chain = await writer.write_sheet(target) + if owner: + await _ensure_ownership(writer, chain.dashboard_guid, dashboard_qn(target.name), owner) results[target.name] = writer return results +async def _ensure_ownership(writer: DashboardSheetEgeriaWriter, dashboard_guid: Optional[str], qn: str, + owner: str) -> None: + """DB-3: a migrated sheet is owned by the user who migrates it -- the Dashboard's Ownership + classification (owner = that userId). Left alone when the Dashboard already has an owner. No zone is + set: the sheet is shared, in the default zone.""" + current = None if writer._is_planned(dashboard_guid) else await writer._find(qn) + header = (current or {}).get("elementHeader") or {} + if header.get("ownership"): + writer.actions.append(f"unchanged Ownership {qn}") + return + writer.actions.append(f"classify Ownership {qn} (owner {owner})") + if writer.dry_run: + return + await writer.client.classification_manager._async_add_ownership_to_element( + dashboard_guid, {"class": "NewClassificationRequestBody", + "properties": {"class": "OwnershipProperties", "owner": owner, + "ownerTypeName": "UserIdentity", "ownerPropertyName": "userId"}}) + + # ---------------------------------------------------------------------------- command line def _print_actions(name: str, writer: DashboardSheetEgeriaWriter, dry_run: bool) -> None: @@ -334,7 +359,7 @@ async def _amain(args: argparse.Namespace) -> int: return 1 print(f"Migrating from {store}{' (DRY RUN: nothing is written)' if args.dry_run else ''}") results = await async_migrate_dashboard_sheets(client, sheets, only=args.sheet, rename=args.rename, - dry_run=args.dry_run) + dry_run=args.dry_run, owner=args.owner) for name, writer in results.items(): _print_actions(name, writer, args.dry_run) return 0 @@ -369,6 +394,7 @@ def main(argv: Optional[List[str]] = None) -> int: mig.add_argument("--store", help="the JSON store (default PYEGERIA_DASHBOARD_SHEETS_STORE or " "~/.pyegeria/dashboard_sheets.json)") mig.add_argument("--dry-run", action="store_true", help="list every write; write nothing") + mig.add_argument("--owner", help="owner of the migrated Dashboards (default: the signed-in user; DB-3)") dele = sub.add_parser("delete", help="delete a sheet's Egeria chain (never its Reports)") dele.add_argument("--sheet", required=True) dele.add_argument("--dry-run", action="store_true") diff --git a/tests/micro-tests/dashboard_fake_egeria.py b/tests/micro-tests/dashboard_fake_egeria.py index 8d40b93e..22093ece 100644 --- a/tests/micro-tests/dashboard_fake_egeria.py +++ b/tests/micro-tests/dashboard_fake_egeria.py @@ -79,8 +79,11 @@ def write_names(self) -> List[str]: def _header(self, guid: str) -> Dict[str, Any]: e = self.entities[guid] - return {"class": "ElementHeader", "guid": guid, - "type": {"typeName": e["type"], "superTypeNames": SUPERTYPES.get(e["type"], [])}} + header = {"class": "ElementHeader", "guid": guid, + "type": {"typeName": e["type"], "superTypeNames": SUPERTYPES.get(e["type"], [])}} + if e.get("ownership"): + header["ownership"] = {"classificationName": "Ownership", "classificationProperties": e["ownership"]} + return header def element(self, guid: str) -> Dict[str, Any]: e = self.entities[guid] @@ -261,6 +264,10 @@ async def _async_detach_placement_report(self, dashboard_guid, placement_qualifi and r["props"].get("queryId") == placement_qualified_name)] return before - len(self.relationships) + async def _async_add_ownership_to_element(self, element_guid, body, timeout=None): + self.writes.append(("add_ownership", element_guid, body["properties"]["owner"])) + self.entities[element_guid]["ownership"] = {k: v for k, v in body["properties"].items() if k != "class"} + async def _async_add_scope_to_element(self, scoped_by_guid, element_guid, body=None): self.writes.append(("add_scope", scoped_by_guid, element_guid)) return self._link("ScopedBy", scoped_by_guid, element_guid) diff --git a/tests/micro-tests/test_dashboards_reader.py b/tests/micro-tests/test_dashboards_reader.py index 6d03fe2e..6e0b76cb 100644 --- a/tests/micro-tests/test_dashboards_reader.py +++ b/tests/micro-tests/test_dashboards_reader.py @@ -83,6 +83,18 @@ async def test_list_returns_all_live_sheets_and_migrate_is_idempotent(): assert len(fake.of_type("Dashboard")) == 5 and len(fake.of_type("DisplayDataField")) == 40 assert len(fake.rels("DataSetContent")) == 30 assert sum(len(w.actions) for w in first.values()) > 0 + # DB-3: owned by the migrating user (the fake has none, so owner is given), set once + assert [w for w in writes if w[0] == "add_ownership"] == [] # no owner known -> not classified + + +@pytest.mark.asyncio +async def test_migrate_sets_ownership_once_db3(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + await async_migrate_dashboard_sheets(fake, store, only="my-team-dashboard", owner="garygeeke") + await async_migrate_dashboard_sheets(fake, store, only="my-team-dashboard", owner="garygeeke") + owned = [w for w in fake.writes if w[0] == "add_ownership"] + assert owned == [("add_ownership", fake.by_qn("Dashboard::my-team-dashboard"), "garygeeke")] @pytest.mark.asyncio @@ -93,6 +105,17 @@ async def test_dry_run_migrate_writes_nothing(): assert fake.writes == [] creates = [a for w in results.values() for a in w.actions if a.startswith("create")] assert len(creates) == 5 * 3 + 40 + assert not [a for w in results.values() for a in w.actions if a.startswith("classify")] # no owner known + + +@pytest.mark.asyncio +async def test_dry_run_lists_ownership(): + fake = _egeria_with_reports(LIVE) + store = DashboardSheetDict({k: DashboardSheet(**v) for k, v in LIVE.items()}) + results = await async_migrate_dashboard_sheets(fake, store, only="my-team-dashboard", dry_run=True, + owner="erinoverview") + assert "classify Ownership Dashboard::my-team-dashboard (owner erinoverview)" in results["my-team-dashboard"].actions + assert fake.writes == [] @pytest.mark.asyncio From 54e91b424f25694d68c6b9ffea0b3efa2b100363 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 15:16:13 +0000 Subject: [PATCH 6/9] fix(view): dashboards CLI runs through run_sync, not asyncio.run The library rule (test_async_runner) forbids asyncio.run outside a __main__ block, since it fails inside a running loop. Signed-off-by: Dan Wolfson --- pyegeria/view/dashboards.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyegeria/view/dashboards.py b/pyegeria/view/dashboards.py index 710569cc..e9b2ff82 100644 --- a/pyegeria/view/dashboards.py +++ b/pyegeria/view/dashboards.py @@ -39,7 +39,6 @@ from __future__ import annotations import argparse -import asyncio import os import sys from typing import Any, Dict, List, Literal, Optional @@ -403,7 +402,8 @@ def main(argv: Optional[List[str]] = None) -> int: args = parser.parse_args(argv) logger.remove() logger.add(sys.stderr, level=os.environ.get("PYEGERIA_DASHBOARDS_LOG_LEVEL", "WARNING")) - return asyncio.run(_amain(args)) + from pyegeria.core.async_runner import run_sync + return run_sync(_amain(args)) if __name__ == "__main__": From a8a5e395540adfbb243412f7227fab50fd10362f Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 15:34:52 +0000 Subject: [PATCH 7/9] fix(dr-egeria): dashboard sheet read-back P3s (positions, names, Report lookup) - A placement added after a removal never reuses a taken position: an explicit migrate index that is already taken falls back to max+1. - A sheet with two placements of one name is refused before any write (they would collapse into one); a report and a text placement cannot share a name, in Egeria or the store. - Link Report to Dashboard Sheet resolves Report Name with the exact Report-typed lookup first, so a Report whose name another element type shares no longer fails validation. Signed-off-by: Dan Wolfson --- md_processing/v2/dashboard_sheet.py | 60 +++++++++++++++++-- tests/micro-tests/dashboard_fake_egeria.py | 2 +- .../test_dashboard_sheets_in_egeria.py | 49 +++++++++++++++ 3 files changed, 105 insertions(+), 6 deletions(-) diff --git a/md_processing/v2/dashboard_sheet.py b/md_processing/v2/dashboard_sheet.py index 20c970c4..f5cddf19 100644 --- a/md_processing/v2/dashboard_sheet.py +++ b/md_processing/v2/dashboard_sheet.py @@ -213,6 +213,27 @@ def placement_field_properties(sheet_name: str, position: int, placement: Placem } +def _refuse_kind_clash(sheet_name: str, placement: Placement, existing_kind: str) -> None: + """Placements are matched by name within a sheet, so a report and a text placement cannot share a name: + the second would silently replace the first. Refuse, in words.""" + kind = placement_kind(placement) + if existing_kind != kind: + raise ValueError( + f"Dashboard Sheet '{sheet_name}' already has a {existing_kind} placement named '{placement.ref}'; a " + f"{kind} placement cannot share its name (placements are matched by name). Give it another name.") + + +def duplicate_placement_names(sheet: DashboardSheet) -> List[str]: + """Names used by more than one placement of a sheet (they would collapse into one placement).""" + seen, dups = set(), [] + for p in sheet.placements: + ref = p.get("ref") if isinstance(p, dict) else p.ref + if ref in seen and ref not in dups: + dups.append(ref) + seen.add(ref) + return dups + + def _field_props_differ(desired: Dict[str, Any], current: Dict[str, Any]) -> bool: """Like _props_differ, but a property set on the field and now unset also counts as a change (a placement re-run without perspectives must clear them).""" @@ -494,6 +515,7 @@ async def upsert_placement(self, chain: SheetChain, placement: Placement, *, existing = next((f for f in fields if f.display_name == placement.ref), None) if existing: + _refuse_kind_clash(sheet, placement, existing.properties.get("placementKind") or "report") pos = existing.position if existing.position is not None else (position or 0) props = placement_field_properties(sheet, pos, placement, existing.qualified_name) field_guid = existing.guid @@ -503,7 +525,10 @@ async def upsert_placement(self, chain: SheetChain, placement: Placement, *, self.actions.append(f"unchanged DisplayDataField {existing.qualified_name}") else: taken = [f.position for f in fields if f.position is not None] - pos = position if position is not None else (max(taken) + 1 if taken else 1) + if position is not None and position not in taken: + pos = position + else: # never reuse a taken position (after a removal, an index can equal one) + pos = max(taken) + 1 if taken else 1 props = placement_field_properties(sheet, pos, placement) found = None if self._is_planned(chain.container_guid) else await self._find(props["qualifiedName"]) if found: @@ -611,7 +636,14 @@ async def _sync_detail_spec(self, field_guid: str, placement: Placement) -> None # ------------------------------------------------------------ whole sheets, removal async def write_sheet(self, sheet: DashboardSheet) -> SheetChain: - """Write a whole sheet (migration): the chain, then every placement at its 1-based position.""" + """Write a whole sheet (migration): the chain, then every placement at its 1-based position. + A sheet with two placements of one name is refused before anything is written: they would collapse + into one placement.""" + dups = duplicate_placement_names(sheet) + if dups: + raise ValueError(f"Dashboard Sheet '{sheet.name}' has more than one placement named " + f"{', '.join(repr(d) for d in dups)}; placements are matched by name, so they would " + f"collapse into one. Rename them in the store first. Nothing was written.") chain = await self.ensure_sheet(sheet.name, sheet.heading, sheet.description, sheet.family, sheet.aliases) for index, placement in enumerate(sheet.placements, start=1): if isinstance(placement, dict): @@ -804,6 +836,21 @@ async def fetch_as_is(self) -> Optional[Dict[str, Any]]: def supports_target_element_lookup(self) -> bool: return False + async def resolve_element_guid(self, name_or_guid: str, tech_type: Optional[str] = None) -> Optional[str]: + """`Report Name` is resolved first as the one Report with exactly that displayName (the writer's typed + lookup), then as before. Dr.Egeria's untyped lookup is refused by Egeria when another element type + shares the name (live 2026-11-09: 'Term Definition Completeness', 'Governance Classification + Coverage'), which failed this command at validation.""" + text = str(name_or_guid or "").strip() + if text and "(guid:" not in text and self.client is not None: + try: + guid = await DashboardSheetEgeriaWriter(self.client)._resolve_report(text) + except (AttributeError, PyegeriaConnectionException): + guid = None + if guid: + return guid + return await super().resolve_element_guid(name_or_guid, tech_type) + async def apply_changes(self) -> str: attributes = self.parsed_output["attributes"] sheet_name = attributes.get("Dashboard Sheet Name", {}).get("value") @@ -864,10 +911,13 @@ async def _work(writer: DashboardSheetEgeriaWriter): def _put_placement(sheet: DashboardSheet, placement: Placement) -> bool: - """Replace the placement with the same ref, or append it. True if replaced.""" + """Replace the placement with the same ref, or append it. True if replaced. A same-named placement of the + other kind (report vs text) is refused, as in Egeria.""" for i, p in enumerate(sheet.placements): - ref = p.get("ref") if isinstance(p, dict) else p.ref - if ref == placement.ref: + if isinstance(p, dict): + p = Placement(**p) + if p.ref == placement.ref: + _refuse_kind_clash(sheet.name, placement, placement_kind(p)) sheet.placements[i] = placement return True sheet.placements.append(placement) diff --git a/tests/micro-tests/dashboard_fake_egeria.py b/tests/micro-tests/dashboard_fake_egeria.py index 3f497496..2d7ab7d1 100644 --- a/tests/micro-tests/dashboard_fake_egeria.py +++ b/tests/micro-tests/dashboard_fake_egeria.py @@ -114,7 +114,7 @@ async def __async_get_guid__(self, guid=None, display_name=None, property_name=" hits.append(g) if len(hits) > 1: from pyegeria.core._exceptions import PyegeriaException - raise PyegeriaException(context={"reason": "Multiple elements found"}) + raise PyegeriaException(f"Multiple elements found for '{display_name}'") return hits[0] if hits else "No elements found" async def _async_get_related_elements(self, element_guid, relationship_type=None, start_at_end=1, diff --git a/tests/micro-tests/test_dashboard_sheets_in_egeria.py b/tests/micro-tests/test_dashboard_sheets_in_egeria.py index 5f323c3e..5fccadcf 100644 --- a/tests/micro-tests/test_dashboard_sheets_in_egeria.py +++ b/tests/micro-tests/test_dashboard_sheets_in_egeria.py @@ -409,3 +409,52 @@ async def test_two_reports_with_one_name_is_a_note_not_a_guess(egeria): await writer.write_sheet(DashboardSheet(name="s", heading="S", placements=[Placement(ref="Twin")])) assert not egeria.rels("DataSetContent") assert any("2 Reports are named 'Twin'" in n for n in writer.notes) + + +# ---------------------------------------------------------------------------- read-back P3s (2026-11-09) + +@pytest.mark.asyncio +async def test_migrate_after_removal_never_reuses_a_position(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + for name in ("A", "B", "C", "D"): + egeria.add_entity("Report", f"R::{name}", name) + writer = DashboardSheetEgeriaWriter(egeria) + await writer.write_sheet(DashboardSheet(name="p", heading="P", placements=[Placement(ref=n) for n in "ABC"])) + await writer.remove_placement("p", "B") + await writer.write_sheet(DashboardSheet(name="p", heading="P", placements=[Placement(ref=n) for n in "ACD"])) + positions = sorted((rel["props"]["position"], egeria.entities[rel["end2"]]["props"]["additionalProperties"]["placementName"]) + for rel in egeria.rels("NestedSchemaAttribute")) + assert positions == [(1, "A"), (3, "C"), (4, "D")] + + +@pytest.mark.asyncio +async def test_sheet_with_duplicate_placement_names_is_refused_before_any_write(egeria): + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + sheet = DashboardSheet(name="dup", heading="Dup", placements=[ + Placement(ref="Coco Terms Total", emphasis="kpi"), Placement(ref="Coco Terms Total", emphasis="panel")]) + with pytest.raises(ValueError, match="more than one placement named 'Coco Terms Total'"): + await DashboardSheetEgeriaWriter(egeria).write_sheet(sheet) + assert egeria.writes == [] + + +@pytest.mark.asyncio +async def test_text_placement_cannot_take_a_report_placements_name(egeria, _store): + await _document(egeria) + writes, store = list(egeria.writes), _store.read_text() + result = await setup_dispatcher(egeria).dispatch( + _command("Add", "Text on Dashboard Sheet", {**TEXT, "Placement Name": "Coco Terms Total"}), + {"directive": "process"}) + assert result["status"] == "failure" + assert "already has a report placement named 'Coco Terms Total'" in json.dumps(result) + assert egeria.writes == writes and _store.read_text() == store + + +@pytest.mark.asyncio +async def test_link_command_finds_a_report_whose_name_another_type_shares(egeria): + """Dr.Egeria's untyped lookup is ambiguous here (and refused live); the command's typed lookup is not.""" + report = egeria.add_entity("Report", "X::Report::TDC", "Term Definition Completeness") + egeria.add_entity("GovernanceMetric", "X::Metric::TDC", "Term Definition Completeness") + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + await _run(egeria, "Link", "Report to Dashboard Sheet", + {**LINK_2, "Report Name": "Term Definition Completeness", "Placement Detail Spec": ""}) + assert [r["end2"] for r in egeria.rels("DataSetContent")] == [report] From 57b3deeb4c7444adb44b3865d45f706037b9074a Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 15:35:41 +0000 Subject: [PATCH 8/9] feat(view): reader notes drift between stored labels and Egeria links A placement's stored perspective labels and drill-down name are what the author wrote; ScopedBy and DataDescription carry the graph meaning. The reader now reads both and adds a note where they disagree (a link edited in Egeria directly), instead of returning the stored labels silently. A stored drill-down with no link is not drift: a spec held only in pyegeria has no element. Signed-off-by: Dan Wolfson --- pyegeria/view/dashboards.py | 70 +++++++++++++++------ tests/micro-tests/test_dashboards_reader.py | 45 +++++++++++++ 2 files changed, 96 insertions(+), 19 deletions(-) diff --git a/pyegeria/view/dashboards.py b/pyegeria/view/dashboards.py index e9b2ff82..f60a9d6a 100644 --- a/pyegeria/view/dashboards.py +++ b/pyegeria/view/dashboards.py @@ -14,11 +14,13 @@ `as_local_model()` drops those, giving a plain `DashboardSheet` that compares equal to the JSON record it was written from. -Absence is said in words, never as an empty value: +Absence and drift are said in words, never as an empty value: - a REPORT placement whose field exists but whose DataSetContent link is gone reads `kind: "missing"`, note "report link missing in Egeria" (its `ref` is the placement's name, so it can still be shown); - a sheet whose chain is broken (no layout schema, no sheet container) is listed with the break named - in `breaks`, not dropped. + in `breaks`, not dropped; + - a placement whose stored perspective labels or drill-down name disagree with its ScopedBy / + DataDescription links (edited in Egeria directly) gets a note naming the difference. The chain is walked with the same primitives that write it (md_processing.v2.dashboard_sheet), so the writer and the reader cannot disagree about its shape. Every Egeria read is bounded: page size 25, @@ -48,7 +50,7 @@ from md_processing.v2.dashboard_sheet import ( DASHBOARD_QN_PREFIX, DashboardSheetEgeriaWriter, _default_store_path, _load_store, dashboard_qn, - sheet_name_from_dashboard_qn, + perspective_qualified_name, sheet_name_from_dashboard_qn, ) from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, DashboardSheetDict, Placement @@ -98,22 +100,43 @@ def _split_labels(value: Any) -> List[str]: return [p.strip() for p in str(value or "").split(",") if p.strip()] -async def _perspective_labels(writer: DashboardSheetEgeriaWriter, field_guid: str) -> List[str]: - """Labels from the field's ScopedBy links, for a field that does not carry its labels.""" - out = [] - for e in await writer._related(field_guid, "ScopedBy", start_at_end=2): - if writer._type(e) != "Perspective": - continue - qn = (e.get("properties") or {}).get("qualifiedName") or "" - out.append(qn.split("::", 1)[1] if qn.startswith("Perspective::") else qn) - return out +async def _scoped_by_qns(writer: DashboardSheetEgeriaWriter, field_guid: str) -> List[str]: + """qualifiedNames of the Perspectives linked to a placement by ScopedBy.""" + return [(e.get("properties") or {}).get("qualifiedName") or "" + for e in await writer._related(field_guid, "ScopedBy", start_at_end=2) + if writer._type(e) == "Perspective"] + + +async def _data_descriptions(writer: DashboardSheetEgeriaWriter, field_guid: str) -> List[Dict[str, Any]]: + return [e.get("properties") or {} for e in await writer._related(field_guid, "DataDescription", start_at_end=1)] + + +def _perspective_drift(labels: List[str], linked_qns: List[str]) -> List[str]: + """Where the stored labels and the ScopedBy links disagree (someone edited one in Egeria), in words.""" + expected = {perspective_qualified_name(label): label for label in labels} + notes = [] + unlinked = [label for qn, label in expected.items() if qn not in linked_qns] + extra = [qn for qn in linked_qns if qn not in expected] + if unlinked: + notes.append(f"stored perspective(s) {', '.join(unlinked)} have no ScopedBy link in Egeria") + if extra: + notes.append(f"ScopedBy link(s) to {', '.join(extra)} are not in the stored perspectives") + return notes -async def _detail_spec_name(writer: DashboardSheetEgeriaWriter, field_guid: str) -> Optional[str]: - for e in await writer._related(field_guid, "DataDescription", start_at_end=1): - props = e.get("properties") or {} - return props.get("displayName") or props.get("qualifiedName") - return None +def _detail_drift(stored: Optional[str], linked: List[Dict[str, Any]]) -> List[str]: + """A DataDescription link that the stored drill-down name does not explain. A stored name with no link is + not drift: a spec held only in pyegeria has no element to link to.""" + names = [] + for props in linked: + qn = props.get("qualifiedName") or "" + names.append((props.get("displayName"), qn, qn.split("::", 1)[1] if "::" in qn else qn)) + if not names: + return [] + if stored and any(stored in n for n in names): + return [] + shown = ", ".join(n[1] or n[0] or "?" for n in names) + return [f"DataDescription links to {shown}, but the stored drill-down is {stored or 'none'}"] async def read_sheet_from_chain(client: Any, sheet_name: str, @@ -158,11 +181,20 @@ async def read_sheet_from_chain(client: Any, sheet_name: str, if style not in _STYLES: notes.append(f"presentationStyle '{style}' is not one of {', '.join(_STYLES)}; shown as kpi") style = "kpi" + # The labels and drill-down name stored on the field are what the author wrote; the ScopedBy / + # DataDescription links carry the graph meaning. Read both, and say where they disagree. + linked_qns = await _scoped_by_qns(writer, f.guid) if "perspectives" in f_extra: perspectives = _split_labels(f_extra.get("perspectives")) + notes += _perspective_drift(perspectives, linked_qns) else: - perspectives = await _perspective_labels(writer, f.guid) - detail_spec = f_extra.get("detailSpec") or await _detail_spec_name(writer, f.guid) + perspectives = [qn.split("::", 1)[1] if qn.startswith("Perspective::") else qn for qn in linked_qns] + linked_specs = await _data_descriptions(writer, f.guid) + detail_spec = f_extra.get("detailSpec") or None + if "detailSpec" in f_extra or "placementName" in f_extra: + notes += _detail_drift(detail_spec, linked_specs) + if detail_spec is None and linked_specs: + detail_spec = linked_specs[0].get("displayName") or linked_specs[0].get("qualifiedName") kind = fp.get("placementKind") or "report" if kind == "text": diff --git a/tests/micro-tests/test_dashboards_reader.py b/tests/micro-tests/test_dashboards_reader.py index 6e0b76cb..be10932a 100644 --- a/tests/micro-tests/test_dashboards_reader.py +++ b/tests/micro-tests/test_dashboards_reader.py @@ -210,3 +210,48 @@ def test_runtime_registration_may_shadow_egeria(clean_registry): registry.set_egeria_dashboard_sheets([EgeriaDashboardSheet(name="x", heading="X from Egeria")]) registry.register_dashboard_sheets({"x": DashboardSheet(name="x", heading="X runtime")}) assert registry.get_dashboard_sheet_registry()["x"].heading == "X runtime" + + +# ---------------------------------------------------------------------------- drift (read-back P3, 2026-11-09) + +async def _cdo_with_link_edits(edit): + fake = _egeria_with_reports(LIVE) + name = "Chief Data Officer Dashboard" + await DashboardSheetEgeriaWriter(fake).write_sheet(DashboardSheet(**LIVE[name])) + edit(fake) + loaded = await async_load_dashboard_sheet(fake, name) + return fake, {p.ref: p for p in loaded.placements} + + +@pytest.mark.asyncio +async def test_extra_scopedby_link_is_a_note(): + def edit(fake): + field = fake.by_qn("DashboardPlacement::Chief Data Officer Dashboard::4::Governance Metrics Defined") + fake.relationships.append({"guid": "x1", "type": "ScopedBy", "end1": fake.by_qn("Perspective::Privacy"), + "end2": field, "props": {}}) + _, placements = await _cdo_with_link_edits(edit) + p = placements["Governance Metrics Defined"] + assert p.perspectives == ["governance"] # the stored labels stay the value + assert p.note == "ScopedBy link(s) to Perspective::Privacy are not in the stored perspectives" + + +@pytest.mark.asyncio +async def test_removed_scopedby_link_is_a_note(): + def edit(fake): + field = fake.by_qn("DashboardPlacement::Chief Data Officer Dashboard::7::Data Asset Ownership") + owner = fake.by_qn("Perspective::Owner") + fake.relationships = [r for r in fake.relationships + if not (r["type"] == "ScopedBy" and r["end1"] == owner and r["end2"] == field)] + _, placements = await _cdo_with_link_edits(edit) + assert placements["Data Asset Ownership"].note == "stored perspective(s) owner have no ScopedBy link in Egeria" + + +@pytest.mark.asyncio +async def test_unexplained_datadescription_link_is_a_note(): + def edit(fake): + spec = fake.add_entity("ReportSpec", "ReportSpec::Something-Else", "Something-Else") + field = fake.by_qn("DashboardPlacement::Chief Data Officer Dashboard::4::Governance Metrics Defined") + fake.relationships.append({"guid": "x2", "type": "DataDescription", "end1": field, "end2": spec, "props": {}}) + _, placements = await _cdo_with_link_edits(edit) + assert placements["Governance Metrics Defined"].note == ( + "DataDescription links to ReportSpec::Something-Else, but the stored drill-down is Governance-Metric-DrE-Basic") From 12a35ea64d1a20fca94a656d79b5a56064ac8d70 Mon Sep 17 00:00:00 2001 From: Dan Wolfson Date: Mon, 9 Nov 2026 16:10:17 +0000 Subject: [PATCH 9/9] fix(dr-egeria): itemise unchanged structural links on a re-run A re-run's action list now names the Schema, AttributeForSchema and NestedSchemaAttribute links it found in place, so its "unchanged" count matches the first run's change count (live step (a): 9 and 9, not 9 and 6). Signed-off-by: Dan Wolfson --- md_processing/v2/dashboard_sheet.py | 7 +++++++ .../test_dashboard_sheets_in_egeria.py | 17 +++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/md_processing/v2/dashboard_sheet.py b/md_processing/v2/dashboard_sheet.py index f5cddf19..5dace9e2 100644 --- a/md_processing/v2/dashboard_sheet.py +++ b/md_processing/v2/dashboard_sheet.py @@ -442,6 +442,9 @@ async def ensure_sheet(self, sheet_name: str, heading: str, description: str = " await self.client.schema_maker._async_link_schema(chain.dashboard_guid, chain.schema_type_guid) else: self.actions.append(f"unchanged DisplayDataSchemaType {schema_type_qn(sheet_name)}") + # found through the Schema link, so that link is in place too; itemised so a re-run's + # "unchanged" count matches the first run's change count + self.actions.append(f"unchanged Schema {dashboard_qn(sheet_name)} -> {schema_type_qn(sheet_name)}") # 3. the sheet's DisplayDataContainer, linked by AttributeForSchema (position 1) if chain.container_guid is None: @@ -458,6 +461,8 @@ async def ensure_sheet(self, sheet_name: str, heading: str, description: str = " "properties": {"class": "AttributeForSchemaProperties", "position": 1}}) else: self.actions.append(f"unchanged DisplayDataContainer {sheet_container_qn(sheet_name)}") + self.actions.append(f"unchanged AttributeForSchema {schema_type_qn(sheet_name)} -> " + f"{sheet_container_qn(sheet_name)}") return chain # ------------------------------------------------------------ placements @@ -523,6 +528,8 @@ async def upsert_placement(self, chain: SheetChain, placement: Placement, *, await self._update_schema_attribute(field_guid, props) else: self.actions.append(f"unchanged DisplayDataField {existing.qualified_name}") + self.actions.append(f"unchanged NestedSchemaAttribute {sheet_container_qn(sheet)} -> " + f"{existing.qualified_name} (position {pos})") else: taken = [f.position for f in fields if f.position is not None] if position is not None and position not in taken: diff --git a/tests/micro-tests/test_dashboard_sheets_in_egeria.py b/tests/micro-tests/test_dashboard_sheets_in_egeria.py index 5fccadcf..9ba99323 100644 --- a/tests/micro-tests/test_dashboard_sheets_in_egeria.py +++ b/tests/micro-tests/test_dashboard_sheets_in_egeria.py @@ -458,3 +458,20 @@ async def test_link_command_finds_a_report_whose_name_another_type_shares(egeria await _run(egeria, "Link", "Report to Dashboard Sheet", {**LINK_2, "Report Name": "Term Definition Completeness", "Placement Detail Spec": ""}) assert [r["end2"] for r in egeria.rels("DataSetContent")] == [report] + + +@pytest.mark.asyncio +async def test_rerun_itemises_every_unchanged_element_and_link(egeria): + """A re-run's 'unchanged' list itemises what the first run made, so the counts match (live step (a): 9).""" + from pyegeria.view._output_dashboard_sheet_models import DashboardSheet, Placement + sheet = DashboardSheet(name="s", heading="S", placements=[Placement(ref="Coco Terms Total", span="full")]) + first = DashboardSheetEgeriaWriter(egeria) + await first.write_sheet(sheet) + second = DashboardSheetEgeriaWriter(egeria) + await second.write_sheet(sheet) + made = [a for a in first.actions if not a.startswith("unchanged")] + assert all(a.startswith("unchanged") for a in second.actions) + assert len(second.actions) == len(made) == 8 # 4 elements + Schema, AttributeForSchema, NestedSchemaAttribute, DataSetContent + kinds = sorted(a.split()[1] for a in second.actions) + assert kinds == sorted(["Dashboard", "DisplayDataSchemaType", "Schema", "DisplayDataContainer", + "AttributeForSchema", "DisplayDataField", "NestedSchemaAttribute", "DataSetContent"])