diff --git a/commands/tech/gen_report_specs.py b/commands/tech/gen_report_specs.py index 77aa4fbc..623550de 100644 --- a/commands/tech/gen_report_specs.py +++ b/commands/tech/gen_report_specs.py @@ -72,6 +72,9 @@ "anchor_id", "anchor_scope_id", "anchor_scope_ids", + # Create Dashboard Sheet's owner input: written as the Dashboard's Ownership classification, not a + # property, so a column for it would always be empty -- and an empty owner reads as "no owner". + "dashboard_owner", "external_source_guid", "external_source_name", "for_duplicate_processing", diff --git a/docs/release-notes/6.2.31.md b/docs/release-notes/6.2.31.md new file mode 100644 index 00000000..e1592beb --- /dev/null +++ b/docs/release-notes/6.2.31.md @@ -0,0 +1,49 @@ +# pyegeria 6.2.31 + +## Changed + +- **The Dashboard Sheet command help says where a sheet lives.** The Dr.Egeria templates and help for + `Create Dashboard Sheet`, `Link Report to Dashboard Sheet` and `Add Text on Dashboard Sheet` described a + sheet as a "local pyegeria-managed record". Since 6.2.29 a sheet is held in Egeria: a Dashboard with a + DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement. The + local JSON store is a fallback, written alone with `--local-only` or with no Egeria connection. The + three commands' descriptions, the `Dashboard Sheet Name` and `MD Content` attributes, and the + regenerated templates now say so. `Create Dashboard Sheet` and `Link Report to Dashboard Sheet` had no + description before. +- **`Create Dashboard Sheet` sets the Dashboard's owner, as `migrate` does (DB-3).** The sheet's + Dashboard gets an Ownership classification for the user the command runs as (in the Portal, by + default, its service user), or for the userId given in the + new Advanced attribute `Dashboard Owner` (the same meaning as `python -m pyegeria.view.dashboards + migrate --owner`). It is set once: a Dashboard that already has an owner keeps it, a re-run writes + nothing, and the output says "Ownership: unchanged (already owned)" (with a note when a different + owner was asked for). With `--local-only` or no Egeria connection nothing is set, and the output says + "Ownership: not written (local only)". Both commands use one implementation, + `DashboardSheetEgeriaWriter.ensure_ownership`. `Dashboard Owner` is not a column in the generated + report specs: the owner is held in the classification, not a property. +- **"Analytic Demo - Governance Coverage" says what it counts.** Its description, and the + `governed_coverage` registry entry, said "share of assets". It counts elements of **any type that the + caller can see** carrying any of the five governance classifications, by a paged find: not a share of + Assets, and not a percentage. The Overview's Governed tile is a different metric (Assets only, a native + repository-wide count, as a share of all Assets), so the two numbers differ by definition; the spec now + says so. The spec's label and heading are unchanged. +- **Semantic grounding counts distinct Assets.** `semantic_grounding` (and "Analytic Demo - Semantic + Grounding") returns six new fields: + - `groundedAssets`: the number of **distinct** Assets with a glossary term on it or on any of its + parts (tables, columns): a SemanticAssignment on the Asset itself, or on an element anchored to it. Live, terms are assigned to + Assets' columns, not to Assets directly, so a column's term grounds its Asset. The Asset is read + from the `anchor` each relationship end carries, with no extra reads. A deleted (memento) element + grounds nothing. + - `groundedAssetTotal`: the Asset total it divides by. + - `groundedAssetPct`: the share of Assets grounded. + - `groundedAssetNote`: why the share is empty, when it is. + - `groundingLinksNotOnAsset`: the links that ground no Asset (a term on a process, say), so none + silently drop out. + - `groundingLinksScanned`: the links the scan read, the ones you can see. It can be below + `groundingLinks` (the native, repository-wide count) by the links you cannot see. + Egeria cannot count distinct relationship ends natively, so the count comes from a scan of every + SemanticAssignment the caller can see, and the total is counted in that same (viewer) population. + When the viewer Asset total cannot be measured (it can time out on a large catalog), + `groundedAssetPct` is None and `groundedAssetNote` says why: never a viewer count over a repository + total. `groundingLinks` and `groundingPct` are unchanged: the native, repository-wide link count, + and links per hundred Assets (links, not Assets). The routine is now slower: a relationship scan + and a viewer Asset count run beside the two native counts. diff --git a/md_processing/data/compact_commands/commands_report_compact.json b/md_processing/data/compact_commands/commands_report_compact.json index 3ae0059c..c6a39c6a 100644 --- a/md_processing/data/compact_commands/commands_report_compact.json +++ b/md_processing/data/compact_commands/commands_report_compact.json @@ -105,7 +105,7 @@ "default_value": "", "valid_values": [], "existing_element": "", - "description": "The unique name of a Dashboard Sheet \u2014 a local pyegeria-managed record (planned to become a Collection subtype in Egeria; see Container/ContainerDict in pyegeria.view._output_container_models for the current pre-Egeria model). Used both to define a new Dashboard Sheet's identity (Create Dashboard Sheet) and to reference an existing one (Link Report to Dashboard Sheet).", + "description": "The unique name of a Dashboard Sheet, held in Egeria as a Dashboard with its layout (a DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement). Used both to name a new Dashboard Sheet (Create Dashboard Sheet) and to refer to an existing one (Link Report to Dashboard Sheet, Add Text on Dashboard Sheet).", "generated": false, "style": "Simple", "user_specified": true, @@ -114,7 +114,7 @@ "min_cardinality": 1, "max_cardinality": 1, "level": "Basic", - "Journal Entry": "The unique name of a Container \u2014 a local pyegeria-managed record (see Container/ContainerDict in pyegeria.view._output_container_models), not an Egeria element. Used both to define a new Container's identity (Create Container) and to reference an existing one (Link Report to Container)." + "Journal Entry": "The unique name of a Container \u2014 a local pyegeria-managed record (see Container/ContainerDict in pyegeria.view._output_container_models), not an Egeria element. Used both to define a new Container's identity (Create Container) and to reference an existing one (Link Report to Container). 2026-11-10: wording updated -- since 6.2.29 the sheet is held in Egeria (\u00a78d chain); the local store is a fallback." }, "Effective Time": { "variable_name": "effective_time", @@ -295,7 +295,7 @@ "default_value": "", "valid_values": [], "existing_element": "", - "description": "Markdown text to display at this placement \u2014 section headers, explanations, captions. Rendered as-is (mermaid fences supported), no Egeria element involved.", + "description": "Markdown text to display at this placement -- section headers, explanations, captions. Rendered as-is (mermaid fences supported). Held in Egeria as the placement's markdownContent.", "generated": false, "style": "Simple", "user_specified": true, @@ -1028,6 +1028,25 @@ "max_cardinality": 1, "level": "Basic", "Journal Entry": "2026-11-07 -- Egeria 6.3 report specs / measurements / dashboards (odpi/egeria#9432)." + }, + "Dashboard Owner": { + "variable_name": "dashboard_owner", + "inUpdate": true, + "attr_labels": "", + "examples": "", + "default_value": "", + "valid_values": [], + "existing_element": "", + "description": "The userId that owns the sheet's Dashboard (its Ownership classification, owner type UserIdentity). Leave it empty for the user the command runs as (in the Portal, by default, its service user). Set once: a Dashboard that already has an owner keeps it. Not written to Egeria with --local-only or with no Egeria connection.", + "generated": false, + "style": "Simple", + "user_specified": true, + "unique": false, + "input_required": false, + "min_cardinality": 0, + "max_cardinality": 1, + "level": "Advanced", + "Journal Entry": "2026-11-10: added -- Create Dashboard Sheet sets Ownership the way `pyegeria.view.dashboards migrate --owner` does (DB-3)." } }, "bundles": { @@ -1172,6 +1191,7 @@ "Dashboard Sheet Base": { "inherits": "Collection Base", "own_attributes": [ + "Dashboard Owner", "Dashboard Sheet Description", "Dashboard Sheet Family", "Dashboard Sheet Heading" @@ -1313,7 +1333,7 @@ "Sheet" ], "family": "Views & Reports", - "description": "", + "description": "Creates or updates a Dashboard Sheet: a named, ordered layout of report and text placements, held in Egeria as a Dashboard with its layout (a DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement). Re-running it updates the sheet in place. The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so.", "verb": "Create", "upsert": true, "attach": false, @@ -1325,14 +1345,14 @@ "OM_TYPE": "", "bundle": "Dashboard Sheet Base", "custom_attributes": [], - "Journal Entry": "Creates a named, ordered, nestable Dashboard Sheet \u2014 a local pyegeria-managed layout record (see Container/ContainerDict in pyegeria.view._output_container_models), NOT yet an Egeria element. PLANNED: Dashboard Sheet will become an Egeria Collection subtype \u2014 when that lands, this bundle (Dashboard Sheet Base) should switch BundleInherits from none to Collection Base (see /Command Specifications/Common Bundles/Collection Base), picking up Purpose + the full Referenceable/AuthoredReferenceable chain. Not immediate \u2014 until then this stays a local record: no upsert, no qualified name prefix, mirroring the Report command's own non-element-creation pattern. 2026-11-07: dropped the 'Dashboard' alias -- 'Create Dashboard' now creates an Egeria Dashboard (odpi/egeria#9432)." + "Journal Entry": "Creates or updates a Dashboard Sheet, written to Egeria as the \u00a78d chain: Dashboard (Dashboard::) --Schema--> DisplayDataSchemaType --AttributeForSchema--> DisplayDataContainer (the sheet); placements are DisplayDataFields under it. Upsert by qualifiedName. 2026-11-07: dropped the 'Dashboard' alias -- 'Create Dashboard' now creates an Egeria Dashboard (odpi/egeria#9432). 2026-11-10: wording updated -- since 6.2.29 the sheet is held in Egeria (\u00a78d chain); the local store is a fallback." }, "Link Report to Dashboard Sheet": { "display_name": "", "qn_prefix": "", "alternate_names": [], "family": "Views & Reports", - "description": "", + "description": "Places a Report into a Dashboard Sheet as an ordered placement, with layout hints (span and emphasis). In Egeria the placement is a DisplayDataField of the sheet, and the Report is linked from the Dashboard (DataSetContent). Re-running it with the same Report Name updates the placement in place. The Dashboard Sheet must already exist (Create Dashboard Sheet). The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so.", "verb": "Link", "upsert": false, "attach": false, @@ -1344,14 +1364,14 @@ "OM_TYPE": "", "bundle": "Report to Dashboard Sheet Link Base", "custom_attributes": [], - "Journal Entry": "Places a Report Spec (FormatSet) into a Dashboard Sheet as an ordered Placement, with layout hints (span/emphasis). A local pyegeria Container/Placement record, not an Egeria relationship \u2014 no upsert. The target Dashboard Sheet must already exist (created via Create Dashboard Sheet)." + "Journal Entry": "Places a Report into a Dashboard Sheet as an ordered placement (DisplayDataField, placementKind 'report'), with span/emphasis; the Report is linked by DataSetContent from the Dashboard. 2026-11-10: wording updated -- since 6.2.29 the sheet is held in Egeria (\u00a78d chain); the local store is a fallback." }, "Add Text on Dashboard Sheet": { "display_name": "", "qn_prefix": "", "alternate_names": [], "family": "Views & Reports", - "description": "Places literal markdown text (a section header, explanation, or caption) into a Dashboard Sheet as an ordered Placement, alongside Report placements. A local pyegeria Placement record, not an Egeria element or relationship \u2014 no upsert. The target Dashboard Sheet must already exist (Create Dashboard Sheet).", + "description": "Places literal markdown text (a section header, explanation, or caption) into a Dashboard Sheet as an ordered placement, alongside Report placements. In Egeria the placement is a DisplayDataField of the sheet that holds the text. Re-running it with the same Placement Name updates it in place. The Dashboard Sheet must already exist (Create Dashboard Sheet). The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so.", "verb": "Place", "upsert": false, "attach": false, @@ -1363,7 +1383,7 @@ "OM_TYPE": "", "bundle": "Text Placement Base", "custom_attributes": [], - "Journal Entry": "Places a Report Spec (FormatSet) into a Dashboard Sheet as an ordered Placement, with layout hints (span/emphasis). A local pyegeria Container/Placement record, not an Egeria relationship \u2014 no upsert. The target Dashboard Sheet must already exist (created via Create Dashboard Sheet)." + "Journal Entry": "Places markdown text into a Dashboard Sheet as an ordered placement (DisplayDataField, placementKind 'text', markdownContent). 2026-11-10: wording updated -- since 6.2.29 the sheet is held in Egeria (\u00a78d chain); the local store is a fallback." }, "Create Saved Query": { "display_name": "Saved Query", diff --git a/md_processing/v2/dashboard_sheet.py b/md_processing/v2/dashboard_sheet.py index ac4f65d1..675109de 100644 --- a/md_processing/v2/dashboard_sheet.py +++ b/md_processing/v2/dashboard_sheet.py @@ -465,6 +465,29 @@ async def ensure_sheet(self, sheet_name: str, heading: str, description: str = " f"{sheet_container_qn(sheet_name)}") return chain + async def ensure_ownership(self, dashboard_guid: Optional[str], qn: str, owner: str) -> str: + """DB-3: the Dashboard's Ownership classification (owner = a userId), set once. A Dashboard that + already has an owner keeps it. No zone is set. Used by `Create Dashboard Sheet` and by + `python -m pyegeria.view.dashboards migrate`. + + Returns "set", "unchanged" (already owned) or "planned" (dry run).""" + current = None if self._is_planned(dashboard_guid) else await self._find(qn) + existing = (((current or {}).get("elementHeader") or {}).get("ownership") or {}) + if existing: + have = (existing.get("classificationProperties") or {}).get("owner") + self.actions.append(f"unchanged Ownership {qn}") + if have and have != owner: + self._note(f"Dashboard '{qn}' is already owned by '{have}'; its owner was not changed to '{owner}'.") + return "unchanged" + self.actions.append(f"classify Ownership {qn} (owner {owner})") + if self.dry_run: + return "planned" + await self.client.classification_manager._async_add_ownership_to_element( + dashboard_guid, {"class": "NewClassificationRequestBody", + "properties": {"class": "OwnershipProperties", "owner": owner, + "ownerTypeName": "UserIdentity", "ownerPropertyName": "userId"}}) + return "set" + # ------------------------------------------------------------ placements async def _resolve_report(self, report_name: str) -> Optional[str]: @@ -786,23 +809,36 @@ async def apply_changes(self) -> str: sheets = _load_store(path) aliases = list(sheets[name].aliases) if name in sheets else [] + # DB-3: owned by the user the command runs as (client.user_id; in the Portal, by default, its service + # user) unless Dashboard Owner names another userId; set once. + explicit_owner = attributes.get("Dashboard Owner", {}).get("value") or None + owner = explicit_owner or getattr(self.client, "user_id", None) or None + ownership = {} + async def _work(writer: DashboardSheetEgeriaWriter): chain = await writer.ensure_sheet(name, heading, description, family, aliases) self.parsed_output["guid"] = chain.dashboard_guid + if owner: + ownership["status"] = await writer.ensure_ownership(chain.dashboard_guid, dashboard_qn(name), owner) 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) - zones_note = "" + status_notes = "" if local_reason: # `name` stands in for the GUID (the sheet is in the local store only), so the base # processor must not sync anything to Egeria with it. self.parsed_output["guid"] = name self.parsed_output["local_only"] = local_reason if attributes.get("Zone Membership", {}).get("value"): - zones_note = "\n- **Zone Membership**: not written (local only)" + status_notes = "\n- **Zone Membership**: not written (local only)" + status_notes += "\n- **Ownership**: not written (local only)" + elif ownership.get("status") == "set": + status_notes = f"\n- **Ownership**: {owner}" + elif ownership.get("status") == "unchanged": + status_notes = "\n- **Ownership**: unchanged (already owned)" verb_word = "Updated" if is_update else "Created" logger.success(f"{verb_word} Dashboard Sheet '{name}' (local store {path}; Egeria: " @@ -814,7 +850,7 @@ async def _work(writer: DashboardSheetEgeriaWriter): f"- **Description**: {description or '_(none)_'}\n" f"- **Family**: {family or '_(none)_'}\n" f"- **Local store**: {path}" - f"{zones_note}" + f"{status_notes}" f"{_egeria_section(writer, local_reason)}" ) diff --git a/pyegeria/view/analytic_demo_specs.py b/pyegeria/view/analytic_demo_specs.py index 0db07849..79438ae1 100644 --- a/pyegeria/view/analytic_demo_specs.py +++ b/pyegeria/view/analytic_demo_specs.py @@ -129,13 +129,15 @@ def _demo( ), "Analytic Demo - Governance Coverage": _demo( heading="Governance Classification Coverage", - what="Count of elements carrying at least one governance classification " - "(ZoneMembership/Confidentiality/Criticality/Impact/Retention) -- NOT a percentage " - "despite 'coverage' in the name (there's no cheap total-elements denominator to " - "divide by yet). The find is paged until Egeria returns an empty page, so governedCount " - "is every governed element (governedCapped is false when measured). byClassification " - "and topZones are nested breakdowns of the same governedCount elements -- pick BAR " - "below for a chart of byClassification.", + what="Count of elements of ANY type that you can see carrying at least one of the five governance " + "classifications (ZoneMembership/Confidentiality/Criticality/Impact/Retention) -- not a share " + "of Assets, and not a percentage. It counts what the caller may see (zone security applies), " + "by a find paged until Egeria returns an empty page, so governedCount is every governed element " + "you can see (governedCapped is false when measured). It is not the Overview's Governed tile, " + "which counts Assets only, natively across the whole repository, as a share of all Assets: the " + "two numbers differ by definition. byClassification and topZones are nested breakdowns of the " + "same elements (byClassification tallies every classification they carry, not only the five) " + "-- pick BAR below for a chart of byClassification.", analytic_function_name="governed_coverage", demo_params={}, result_shape="dict (governedCount, governedCapped, byClassification, topZones)", @@ -180,17 +182,23 @@ def _demo( ), "Analytic Demo - Semantic Grounding": _demo( heading="Semantic Grounding Coverage", - what="groundingLinks = count of SemanticAssignment relationships (term<->asset). " - "groundingPct = that count as a percent of the broad Asset supertype count; both are " - "native counts over the whole repository, including elements the viewer may not see " - "(i.e. 'percent of Assets' as the denominator, capped at 100 -- an asset with " - "multiple assignments can push the raw ratio over 100%, which is why it's capped, " - "not because grounding coverage is literally bounded there). A per-asset detail " - "breakdown (which assets are/aren't grounded) isn't available from this metric -- " - "a real gap for later.", + what="groundedAssets = the number of DISTINCT Assets with a glossary term on it or on any of its " + "parts (tables, columns): a SemanticAssignment on the Asset itself, or on an element anchored to " + "it, counts that Asset once. A deleted element grounds nothing. groundingLinksNotOnAsset = the " + "links that ground no Asset (a term on a process, say); groundingLinksScanned = the links " + "the scan read (the ones you can see, so it can be below groundingLinks). groundedAssetPct = that number as a percent of all Assets " + "(groundedAssetTotal). Both are what you can see: the count comes from a scan of every " + "SemanticAssignment, and the total is counted in the same population, so groundedAssetPct " + "is empty, and groundedAssetNote says why, when your Asset total cannot be counted -- never " + "a number mixing populations. groundingLinks = the number of SemanticAssignment links " + "across the whole repository, and groundingPct = links per hundred Assets (at most 100): " + "that is links, not Assets -- an Asset with three terms counts three times. A per-asset " + "breakdown (which assets are or aren't grounded) isn't available from this metric -- a real " + "gap for later.", analytic_function_name="semantic_grounding", demo_params={}, - result_shape="dict (groundingLinks, groundingPct)", + result_shape="dict (groundedAssets, groundedAssetTotal, groundedAssetPct, groundedAssetNote, " + "groundingLinksScanned, groundingLinksNotOnAsset, groundingLinks, groundingPct)", ), "Analytic Demo - AI Context Readiness": _demo( heading="AI Context Readiness Funnel", diff --git a/pyegeria/view/analytic_registry.py b/pyegeria/view/analytic_registry.py index b6d74b1b..1221c819 100644 --- a/pyegeria/view/analytic_registry.py +++ b/pyegeria/view/analytic_registry.py @@ -917,8 +917,9 @@ def _always_applies(what: str) -> str: name="governed_coverage", function="pyegeria.view.overview_metrics.governed_coverage", inputs=["egeria_client:MetadataExpert"], - description="Share of assets carrying at least one governance classification, plus a " - "by-classification / top-zones breakdown. " + description="Count of elements of any type that the caller can see carrying at least one of the " + "five governance classifications -- not a share of Assets -- plus a by-classification / " + "top-zones breakdown. " "Cost: one find, paged until Egeria returns an empty page (an incomplete scan is not measured), seconds.", returns="dict (governedCount, governedCapped, byClassification, topZones)", generic=False, @@ -1184,19 +1185,33 @@ def _always_applies(what: str) -> str: name="semantic_grounding", function="pyegeria.view.overview_metrics.semantic_grounding", inputs=["egeria_client:MetadataExpert", "egeria_client:ClassificationExplorer"], - description="SemanticAssignment relationship count and coverage percent -- the meaning layer " - "that grounds AI. Takes two leading clients (mgr, ce) -- the executor supplies the " - "same EgeriaTech instance for both. " - "Both counts are native, in the repository population, so the percentage never divides " - "one population by the other. " - "Cost: two native counts, sub-second each." + REPOSITORY_WORDS, - returns="dict (groundingLinks, groundingPct)", + description="Semantic grounding -- the meaning layer that grounds AI. groundedAssets is the " + "number of DISTINCT Assets grounded by a glossary term (the Asset itself, or an element " + "anchored to it such as a column, has a SemanticAssignment), and groundedAssetPct that " + "number as a percent of all Assets: both in the viewer population (a scan of every " + "SemanticAssignment the caller may see, over a viewer Asset count), so groundedAssetPct is " + "None, and groundedAssetNote says why, when the viewer Asset total cannot be measured. groundingLinks is " + "the native, repository-wide count of SemanticAssignment links, and groundingPct links per " + "hundred Assets (repository; links, not distinct Assets). Takes two leading clients " + "(mgr, ce) -- the executor supplies the same EgeriaTech instance for both. " + "Cost: two native counts (sub-second), a relationship scan (one read per 500 links) and a " + "viewer Asset count beside it (slow on a large catalog: it can time out).", + returns="dict (groundedAssets, groundedAssetTotal, groundedAssetPct, groundedAssetNote, " + "groundingLinksScanned, groundingLinksNotOnAsset, groundingLinks, groundingPct)", generic=False, binding_note="Fixed to the SemanticAssignment relationship type -- not a parameter.", params=[_as_of()], declaration=AnalyticDeclaration( result_kind="measure", measures=[ + _measure("grounded_assets", "distinct Assets grounded by a glossary term (directly or through " + "an anchored element such as a column)", + "groundedAssets", population="viewer", + basis=_basis("groundedAssetTotal", "Assets you can see")), + _measure("grounded_asset_percent", "percent of Assets grounded by a glossary term", + "groundedAssetPct", population="viewer"), + _measure("grounding_links_not_on_asset", "SemanticAssignment links that ground no Asset " + "(on an element not anchored to an Asset)", "groundingLinksNotOnAsset", population="viewer"), _measure("grounding_links", "SemanticAssignment relationships", "groundingLinks", population="repository"), # links / Assets, not the share of Assets with a link: one Asset may carry several. @@ -1204,14 +1219,19 @@ def _always_applies(what: str) -> str: "at most 100", "groundingPct", population="repository"), ], absence=_absence( - not_measured="Semantic grounding was not measured: the SemanticAssignment count or the " - "Asset count to divide by failed or timed out, or the server could not " - "answer it in the repository population.", + not_measured="Semantic grounding was not measured: the SemanticAssignment scan or count, or " + "the Asset count to divide by, failed, timed out or was incomplete.", not_permitted="You are not permitted to read the semantic assignments.", not_applicable=_always_applies("Semantic grounding"), nothing_found="Counted: no glossary term is assigned to anything.", ), out=[ + _field("groundedAssets", "Grounded Assets", "int", unit="Assets"), + _field("groundedAssetTotal", "Assets you can see", "int", unit="Assets"), + _field("groundedAssetPct", "Share of Assets grounded", "int", unit="percent"), + _field("groundedAssetNote", "Why the share is empty", "string"), + _field("groundingLinksScanned", "Term links you can see (scanned)", "int", unit="relationships"), + _field("groundingLinksNotOnAsset", "Term links not on an Asset", "int", unit="relationships"), _field("groundingLinks", "Grounding links", "int", unit="relationships"), _field("groundingPct", "Links per hundred Assets", "int", unit="percent"), ], diff --git a/pyegeria/view/dashboards.py b/pyegeria/view/dashboards.py index f60a9d6a..b7795a90 100644 --- a/pyegeria/view/dashboards.py +++ b/pyegeria/view/dashboards.py @@ -330,21 +330,9 @@ async def async_migrate_dashboard_sheets(client: Any, sheets: DashboardSheetDict 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"}}) + """DB-3: a migrated sheet is owned by the user who migrates it. The one implementation is + `DashboardSheetEgeriaWriter.ensure_ownership`, which `Create Dashboard Sheet` uses too.""" + await writer.ensure_ownership(dashboard_guid, qn, owner) # ---------------------------------------------------------------------------- command line diff --git a/pyegeria/view/overview_metrics.py b/pyegeria/view/overview_metrics.py index 9a6b47e7..d07f1bde 100644 --- a/pyegeria/view/overview_metrics.py +++ b/pyegeria/view/overview_metrics.py @@ -1292,23 +1292,120 @@ def stale_assets(mgr, as_of: Optional[str] = None, days: int = 180) -> Dict[str, return {"staleCount": stale_count, "assetTotal": total} -def semantic_grounding(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: - """ - Semantic-grounding tally: `SemanticAssignment` relationships (term <-> - asset), as a count and as a percentage of the broad `Asset` supertype - count -- the "meaning layer" that grounds AI context. +def _grounded_asset_guid(end: Dict[str, Any]) -> Optional[str]: + """The Asset a SemanticAssignment end grounds, or None. + + The end itself when it is an Asset (its type, or one of its supertypes, is Asset); otherwise the + Asset it is anchored to, read from the `anchor` the relationship end carries (anchorDomainName + "Asset") -- live, terms are assigned to Assets' columns (TabularColumn), not to Assets directly. + An end carrying `memento` (deleted, visible only to lineage) grounds nothing.""" + if not isinstance(end, dict) or end.get("memento"): + return None + end_type = end.get("type") or {} + if "Asset" in ({end_type.get("typeName")} | set(end_type.get("superTypeNames") or [])): + return end.get("guid") or None + anchor = end.get("anchor") or {} + if not isinstance(anchor, dict): + return None + # An ElementClassification: its fields are under classificationProperties (a bare dict is accepted too). + props = anchor.get("classificationProperties") or anchor + if isinstance(props, dict) and props.get("anchorDomainName") == "Asset": + return props.get("anchorGUID") or None + return None - Both counts are native and in the repository population (the whole - repository, including elements the viewer may not be able to see), so the - percentage never divides one population by the other. `mgr` is the - MetadataExpert the repository relationship count needs. - Returns {"groundingLinks": int|None, "groundingPct": int|None}. +def semantic_grounding(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Any]: """ + Semantic-grounding tally: how much of the catalog is linked to glossary + terms by `SemanticAssignment` -- the "meaning layer" that grounds AI context. + + Two measures, each in one population: + + - `groundedAssets` / `groundedAssetPct` (6.2.31): the number of + DISTINCT Assets grounded by a glossary term -- the Asset itself, or one + of its anchored elements such as a column, has a SemanticAssignment -- + and that number as a percent of all Assets. Egeria cannot count the + distinct ends of a relationship type natively, so the count comes from a + scan of every SemanticAssignment (paged until Egeria returns an empty + page): an Asset-typed end counts as itself, any other end as the Asset + its `anchor` names (no extra reads), and a deleted (`memento`) end not + at all. `groundingLinksNotOnAsset` counts the scanned links that + ground no Asset (a term on a process, say), so none silently drop out. + `groundingLinksScanned` is the number of links the scan read: the links + you can see. It can be below `groundingLinks`, the native repository + count, by the links you cannot see; it is never added to it. A scan sees only what the caller may see, so the + Asset total it divides by is counted in the same, viewer population + (`groundedAssetTotal`), on its own thread while the scan pages. When + that total cannot be measured (it times out on a large catalog), + `groundedAssetPct` is None and `groundedAssetNote` says why: never a + viewer count over a repository total. An incomplete scan makes both + None, with a note too. + - `groundingLinks` / `groundingPct`: the native, repository-wide count of + SemanticAssignment relationships, and that count per hundred Assets + (the repository Asset total), at most 100. This is links, not Assets: + one Asset with three terms counts three times, and a link to a + non-Asset counts too. Kept for callers that read it. + + `mgr` is the MetadataExpert the native counts need. + + Returns {"groundedAssets": int|None, "groundedAssetTotal": int|None, + "groundedAssetPct": int|None, "groundedAssetNote": str|None, + "groundingLinksScanned": int|None, "groundingLinksNotOnAsset": int|None, + "groundingLinks": int|None, + "groundingPct": int|None}. + """ + pool = ThreadPoolExecutor(max_workers=1, thread_name_prefix="grounding-assets") + total_future = pool.submit(contextvars.copy_context().run, count_elements, mgr, "Asset", as_of, + strict=True, population=SCOPE_VIEWER) + pool.shutdown(wait=False) + cataloged = count_elements(mgr, "Asset", as_of, strict=True, population=SCOPE_REPOSITORY) links = count_relationships(ce, "SemanticAssignment", as_of, expert=mgr, population=SCOPE_REPOSITORY) pct = min(100, round(100 * links / cataloged)) if cataloged and links is not None else None - return {"groundingLinks": links, "groundingPct": pct} + + grounded = None + links_not_on_asset = None + links_scanned = None + try: + rels = _all_relationships(ce, "SemanticAssignment", as_of) # every page: one page is not the set + if rels is not None: + assets: set = set() + off_asset = 0 + for r in rels: + found = [a for a in (_grounded_asset_guid(r.get(k) if isinstance(r, dict) else None) + for k in ("end1", "end2")) if a] + assets.update(found) + if not found: + off_asset += 1 # e.g. a term on a process: reported, never silently dropped + grounded = len(assets) + links_not_on_asset = off_asset + links_scanned = len(rels) + except Exception as exc: # noqa: BLE001 + logger.debug(f"semantic_grounding: SemanticAssignment scan failed: {exc}") + _not_measured("SemanticAssignment relationships", f"the scan failed ({type(exc).__name__})") + + try: + asset_total = total_future.result() + except Exception as exc: # noqa: BLE001 -- count_elements does not raise; belt and braces + logger.debug(f"semantic_grounding: viewer Asset count failed: {exc}") + _not_measured("Asset", f"the count failed ({type(exc).__name__})") + asset_total = None + + grounded_pct = (min(100, round(100 * grounded / asset_total)) + if grounded is not None and asset_total else None) + note = None + if grounded is None: + note = ("Grounded Assets were not measured: the scan of glossary-term assignments failed or was " + "incomplete.") + elif asset_total is None: + note = ("The share of Assets grounded was not measured: the total of Assets you can see could not be " + "counted (the count timed out, or it stopped at its page limit).") + elif asset_total == 0: + note = "The share of Assets grounded is empty: you can see no Assets." + return {"groundedAssets": grounded, "groundedAssetTotal": asset_total, "groundedAssetPct": grounded_pct, + "groundedAssetNote": note, "groundingLinksScanned": links_scanned, + "groundingLinksNotOnAsset": links_not_on_asset, + "groundingLinks": links, "groundingPct": pct} def context_readiness_funnel(mgr, ce, as_of: Optional[str] = None) -> Dict[str, Optional[int]]: diff --git a/pyegeria/view/seed/Analytic Function Demo.json b/pyegeria/view/seed/Analytic Function Demo.json index 80f03fb9..76b6792f 100644 --- a/pyegeria/view/seed/Analytic Function Demo.json +++ b/pyegeria/view/seed/Analytic Function Demo.json @@ -125,7 +125,7 @@ "label": "Analytic Demo - Governance Coverage", "envelope": { "heading": "Governance Classification Coverage", - "description": "Count of elements carrying at least one governance classification (ZoneMembership/Confidentiality/Criticality/Impact/Retention) -- NOT a percentage despite 'coverage' in the name (there's no cheap total-elements denominator to divide by yet). The find is paged until Egeria returns an empty page, so governedCount is every governed element (governedCapped is false when measured). byClassification and topZones are nested breakdowns of the same governedCount elements -- pick BAR below for a chart of byClassification. FIXED metric -- Fixed to GOVERNANCE_CLASSIFICATIONS: ZoneMembership, Confidentiality, Criticality, Impact, Retention -- not a parameter. This spec always returns that one metric. Result shape: dict (governedCount, governedCapped, byClassification, topZones).", + "description": "Count of elements of ANY type that you can see carrying at least one of the five governance classifications (ZoneMembership/Confidentiality/Criticality/Impact/Retention) -- not a share of Assets, and not a percentage. It counts what the caller may see (zone security applies), by a find paged until Egeria returns an empty page, so governedCount is every governed element you can see (governedCapped is false when measured). It is not the Overview's Governed tile, which counts Assets only, natively across the whole repository, as a share of all Assets: the two numbers differ by definition. byClassification and topZones are nested breakdowns of the same elements (byClassification tallies every classification they carry, not only the five) -- pick BAR below for a chart of byClassification. FIXED metric -- Fixed to GOVERNANCE_CLASSIFICATIONS: ZoneMembership, Confidentiality, Criticality, Impact, Retention -- not a parameter. This spec always returns that one metric. Result shape: dict (governedCount, governedCapped, byClassification, topZones).", "family": "Analytic Function Demo", "target_type_name": null, "aliases": [] @@ -265,7 +265,7 @@ "label": "Analytic Demo - Semantic Grounding", "envelope": { "heading": "Semantic Grounding Coverage", - "description": "groundingLinks = count of SemanticAssignment relationships (term<->asset). groundingPct = that count as a percent of the broad Asset supertype count; both are native counts over the whole repository, including elements the viewer may not see (i.e. 'percent of Assets' as the denominator, capped at 100 -- an asset with multiple assignments can push the raw ratio over 100%, which is why it's capped, not because grounding coverage is literally bounded there). A per-asset detail breakdown (which assets are/aren't grounded) isn't available from this metric -- a real gap for later. FIXED metric -- Fixed to the SemanticAssignment relationship type -- not a parameter. This spec always returns that one metric. Result shape: dict (groundingLinks, groundingPct).", + "description": "groundedAssets = the number of DISTINCT Assets with a glossary term on it or on any of its parts (tables, columns): a SemanticAssignment on the Asset itself, or on an element anchored to it, counts that Asset once. A deleted element grounds nothing. groundingLinksNotOnAsset = the links that ground no Asset (a term on a process, say); groundingLinksScanned = the links the scan read (the ones you can see, so it can be below groundingLinks). groundedAssetPct = that number as a percent of all Assets (groundedAssetTotal). Both are what you can see: the count comes from a scan of every SemanticAssignment, and the total is counted in the same population, so groundedAssetPct is empty, and groundedAssetNote says why, when your Asset total cannot be counted -- never a number mixing populations. groundingLinks = the number of SemanticAssignment links across the whole repository, and groundingPct = links per hundred Assets (at most 100): that is links, not Assets -- an Asset with three terms counts three times. A per-asset breakdown (which assets are or aren't grounded) isn't available from this metric -- a real gap for later. FIXED metric -- Fixed to the SemanticAssignment relationship type -- not a parameter. This spec always returns that one metric. Result shape: dict (groundedAssets, groundedAssetTotal, groundedAssetPct, groundedAssetNote, groundingLinksScanned, groundingLinksNotOnAsset, groundingLinks, groundingPct).", "family": "Analytic Function Demo", "target_type_name": null, "aliases": [] diff --git a/pyproject.toml b/pyproject.toml index 3cc5a185..e5d0c64d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ [project] name = "pyegeria" -version = "6.2.30" +version = "6.2.31" license = 'Apache-2.0' license-files = ["LICENSE"] authors = [{name = "Dan Wolfson", email = "dan.wolfson@pdr-associates.com"},] diff --git a/sample-data/templates/advanced/Views & Reports/Add_Text_on_Dashboard_Sheet.md b/sample-data/templates/advanced/Views & Reports/Add_Text_on_Dashboard_Sheet.md index cdb46e20..dbb79ab2 100644 --- a/sample-data/templates/advanced/Views & Reports/Add_Text_on_Dashboard_Sheet.md +++ b/sample-data/templates/advanced/Views & Reports/Add_Text_on_Dashboard_Sheet.md @@ -1,14 +1,14 @@ ___ ## Add 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. A local pyegeria Placement record, not an Egeria element or relationship — no upsert. The target Dashboard Sheet must already exist (Create Dashboard Sheet). +> Places literal markdown text (a section header, explanation, or caption) into a Dashboard Sheet as an ordered placement, alongside Report placements. In Egeria the placement is a DisplayDataField of the sheet that holds the text. Re-running it with the same Placement Name updates it in place. The Dashboard Sheet must already exist (Create Dashboard Sheet). The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so. ### Dashboard Sheet Name > **Input Required**: True > **Attribute Type**: Simple -> **Description**: The unique name of a Dashboard Sheet — a local pyegeria-managed record (planned to become a Collection subtype in Egeria; see Container/ContainerDict in pyegeria.view._output_container_models for the current pre-Egeria model). Used both to define a new Dashboard Sheet's identity (Create Dashboard Sheet) and to reference an existing one (Link Report to Dashboard Sheet). +> **Description**: The unique name of a Dashboard Sheet, held in Egeria as a Dashboard with its layout (a DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement). Used both to name a new Dashboard Sheet (Create Dashboard Sheet) and to refer to an existing one (Link Report to Dashboard Sheet, Add Text on Dashboard Sheet). ### MD Content @@ -16,7 +16,7 @@ ___ > **Attribute Type**: Simple -> **Description**: Markdown text to display at this placement — section headers, explanations, captions. Rendered as-is (mermaid fences supported), no Egeria element involved. +> **Description**: Markdown text to display at this placement -- section headers, explanations, captions. Rendered as-is (mermaid fences supported). Held in Egeria as the placement's markdownContent. ### Placement Name diff --git a/sample-data/templates/advanced/Views & Reports/Create_Dashboard_Sheet.md b/sample-data/templates/advanced/Views & Reports/Create_Dashboard_Sheet.md index ac1e1c10..4a388eab 100644 --- a/sample-data/templates/advanced/Views & Reports/Create_Dashboard_Sheet.md +++ b/sample-data/templates/advanced/Views & Reports/Create_Dashboard_Sheet.md @@ -1,6 +1,7 @@ ___ ## Create Dashboard Sheet +> Creates or updates a Dashboard Sheet: a named, ordered layout of report and text placements, held in Egeria as a Dashboard with its layout (a DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement). Re-running it updates the sheet in place. The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so. > > **Alternative Names**: Sheet @@ -420,6 +421,14 @@ ___ > **Description**: A user defined content status = only valid if content status is OTHER. +### Dashboard Owner +> **Input Required**: False + +> **Attribute Type**: Simple + +> **Description**: The userId that owns the sheet's Dashboard (its Ownership classification, owner type UserIdentity). Leave it empty for the user the command runs as (in the Portal, by default, its service user). Set once: a Dashboard that already has an owner keeps it. Not written to Egeria with --local-only or with no Egeria connection. + + ### User Defined Status > **Input Required**: False diff --git a/sample-data/templates/advanced/Views & Reports/Link_Report_to_Dashboard_Sheet.md b/sample-data/templates/advanced/Views & Reports/Link_Report_to_Dashboard_Sheet.md index 17c64f2d..4dc57507 100644 --- a/sample-data/templates/advanced/Views & Reports/Link_Report_to_Dashboard_Sheet.md +++ b/sample-data/templates/advanced/Views & Reports/Link_Report_to_Dashboard_Sheet.md @@ -1,13 +1,14 @@ ___ ## Link Report to Dashboard Sheet +> Places a Report into a Dashboard Sheet as an ordered placement, with layout hints (span and emphasis). In Egeria the placement is a DisplayDataField of the sheet, and the Report is linked from the Dashboard (DataSetContent). Re-running it with the same Report Name updates the placement in place. The Dashboard Sheet must already exist (Create Dashboard Sheet). The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so. ### Dashboard Sheet Name > **Input Required**: True > **Attribute Type**: Simple -> **Description**: The unique name of a Dashboard Sheet — a local pyegeria-managed record (planned to become a Collection subtype in Egeria; see Container/ContainerDict in pyegeria.view._output_container_models for the current pre-Egeria model). Used both to define a new Dashboard Sheet's identity (Create Dashboard Sheet) and to reference an existing one (Link Report to Dashboard Sheet). +> **Description**: The unique name of a Dashboard Sheet, held in Egeria as a Dashboard with its layout (a DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement). Used both to name a new Dashboard Sheet (Create Dashboard Sheet) and to refer to an existing one (Link Report to Dashboard Sheet, Add Text on Dashboard Sheet). ### Report Name diff --git a/sample-data/templates/basic/Views & Reports/Add_Text_on_Dashboard_Sheet.md b/sample-data/templates/basic/Views & Reports/Add_Text_on_Dashboard_Sheet.md index cdb46e20..dbb79ab2 100644 --- a/sample-data/templates/basic/Views & Reports/Add_Text_on_Dashboard_Sheet.md +++ b/sample-data/templates/basic/Views & Reports/Add_Text_on_Dashboard_Sheet.md @@ -1,14 +1,14 @@ ___ ## Add 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. A local pyegeria Placement record, not an Egeria element or relationship — no upsert. The target Dashboard Sheet must already exist (Create Dashboard Sheet). +> Places literal markdown text (a section header, explanation, or caption) into a Dashboard Sheet as an ordered placement, alongside Report placements. In Egeria the placement is a DisplayDataField of the sheet that holds the text. Re-running it with the same Placement Name updates it in place. The Dashboard Sheet must already exist (Create Dashboard Sheet). The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so. ### Dashboard Sheet Name > **Input Required**: True > **Attribute Type**: Simple -> **Description**: The unique name of a Dashboard Sheet — a local pyegeria-managed record (planned to become a Collection subtype in Egeria; see Container/ContainerDict in pyegeria.view._output_container_models for the current pre-Egeria model). Used both to define a new Dashboard Sheet's identity (Create Dashboard Sheet) and to reference an existing one (Link Report to Dashboard Sheet). +> **Description**: The unique name of a Dashboard Sheet, held in Egeria as a Dashboard with its layout (a DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement). Used both to name a new Dashboard Sheet (Create Dashboard Sheet) and to refer to an existing one (Link Report to Dashboard Sheet, Add Text on Dashboard Sheet). ### MD Content @@ -16,7 +16,7 @@ ___ > **Attribute Type**: Simple -> **Description**: Markdown text to display at this placement — section headers, explanations, captions. Rendered as-is (mermaid fences supported), no Egeria element involved. +> **Description**: Markdown text to display at this placement -- section headers, explanations, captions. Rendered as-is (mermaid fences supported). Held in Egeria as the placement's markdownContent. ### Placement Name diff --git a/sample-data/templates/basic/Views & Reports/Create_Dashboard_Sheet.md b/sample-data/templates/basic/Views & Reports/Create_Dashboard_Sheet.md index 08a18d05..c559bf91 100644 --- a/sample-data/templates/basic/Views & Reports/Create_Dashboard_Sheet.md +++ b/sample-data/templates/basic/Views & Reports/Create_Dashboard_Sheet.md @@ -1,6 +1,7 @@ ___ ## Create Dashboard Sheet +> Creates or updates a Dashboard Sheet: a named, ordered layout of report and text placements, held in Egeria as a Dashboard with its layout (a DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement). Re-running it updates the sheet in place. The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so. > > **Alternative Names**: Sheet diff --git a/sample-data/templates/basic/Views & Reports/Link_Report_to_Dashboard_Sheet.md b/sample-data/templates/basic/Views & Reports/Link_Report_to_Dashboard_Sheet.md index 276dafba..b33d610a 100644 --- a/sample-data/templates/basic/Views & Reports/Link_Report_to_Dashboard_Sheet.md +++ b/sample-data/templates/basic/Views & Reports/Link_Report_to_Dashboard_Sheet.md @@ -1,13 +1,14 @@ ___ ## Link Report to Dashboard Sheet +> Places a Report into a Dashboard Sheet as an ordered placement, with layout hints (span and emphasis). In Egeria the placement is a DisplayDataField of the sheet, and the Report is linked from the Dashboard (DataSetContent). Re-running it with the same Report Name updates the placement in place. The Dashboard Sheet must already exist (Create Dashboard Sheet). The local JSON store (PYEGERIA_DASHBOARD_SHEETS_STORE) is a fallback: with --local-only or no Egeria connection, only the store is written, and the command output says so. ### Dashboard Sheet Name > **Input Required**: True > **Attribute Type**: Simple -> **Description**: The unique name of a Dashboard Sheet — a local pyegeria-managed record (planned to become a Collection subtype in Egeria; see Container/ContainerDict in pyegeria.view._output_container_models for the current pre-Egeria model). Used both to define a new Dashboard Sheet's identity (Create Dashboard Sheet) and to reference an existing one (Link Report to Dashboard Sheet). +> **Description**: The unique name of a Dashboard Sheet, held in Egeria as a Dashboard with its layout (a DisplayDataSchemaType, the sheet's DisplayDataContainer, and one DisplayDataField per placement). Used both to name a new Dashboard Sheet (Create Dashboard Sheet) and to refer to an existing one (Link Report to Dashboard Sheet, Add Text on Dashboard Sheet). ### Report Name diff --git a/tests/micro-tests/data/semantic_assignment_live_ends_2026_11_11.json b/tests/micro-tests/data/semantic_assignment_live_ends_2026_11_11.json new file mode 100644 index 00000000..ccb24f54 --- /dev/null +++ b/tests/micro-tests/data/semantic_assignment_live_ends_2026_11_11.json @@ -0,0 +1,453 @@ +{ + "_source": "Two SemanticAssignment relationships read live (read-only) from the quickstart, 2026-11-11, as erinoverview, page 1 of 25: a TabularColumn anchored to an Asset, and a SubscribingActionProcess anchored to a DigitalProduct (domain AuthoredReferenceable). The anchor is an ElementClassification: its fields are under classificationProperties.", + "relationships": [ + { + "relationshipHeader": { + "guid": "45ab2119-d3ad-4bc8-8f41-e7765d8c3cfc" + }, + "end1": { + "class": "ElementStub", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "d81a0425-4e9b-4f31-bc1c-e18c3566da10", + "typeName": "TabularColumn", + "superTypeNames": [ + "SchemaAttribute", + "SchemaElement", + "AuthoredReferenceable", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "A column attribute for a table oriented data structure.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "filegovernanceengine", + "updatedBy": "filegovernanceengine", + "maintainedBy": [ + "filegovernanceengine" + ], + "createTime": "2026-11-07T23:16:36.969+00:00", + "updateTime": "2026-11-07T23:16:36.969+00:00", + "version": 1, + "lastRequestId": "c1a96807-891a-402b-a808-465e0b9476c1", + "lastOperationId": "2c3391c6-29a8-4e1a-885c-cd46211953c1" + }, + "guid": "a3fd9433-a1a8-4534-837e-cde5e2073d25", + "anchor": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "aa44f302-2e43-4669-a1e7-edaae414fc6e", + "typeName": "Anchors", + "typeVersion": 1, + "typeDescription": "Identifies the anchor entity for an element that is part of a large composite object such as an asset.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "filegovernanceengine", + "updatedBy": "filegovernanceengine", + "maintainedBy": [ + "filegovernanceengine" + ], + "createTime": "2026-11-07T23:16:36.966+00:00", + "updateTime": "2026-11-07T23:16:36.966+00:00", + "version": 1, + "lastRequestId": "c1a96807-891a-402b-a808-465e0b9476c1", + "lastOperationId": "2c3391c6-29a8-4e1a-885c-cd46211953c1" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "709f2262-b95d-4eb9-a706-0d7fab098ae2", + "anchorTypeName": "CSVFile", + "anchorDomainName": "Asset", + "zoneMembership": [ + "quarantine", + "PROJ-CT-TBDF" + ] + } + }, + "schemaType": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "e2bb76bb-774a-43ff-9045-3a05f663d5d9", + "typeName": "TypeEmbeddedAttribute", + "typeVersion": 2, + "typeDescription": "Type information embedded within an attribute.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "filegovernanceengine", + "updatedBy": "filesurveyengine", + "maintainedBy": [ + "filegovernanceengine", + "filesurveyengine" + ], + "createTime": "2026-11-07T23:16:36.966+00:00", + "updateTime": "2026-11-07T23:33:23.805+00:00", + "version": 2, + "lastRequestId": "7e30e4e4-01d9-4427-b547-a82c8383ab6f" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "TypeEmbeddedAttribute", + "classificationProperties": { + "class": "TypeEmbeddedAttributeProperties", + "typeName": "TypeEmbeddedAttribute", + "schemaTypeName": "PrimitiveSchemaType", + "dataType": "string" + } + }, + "uniqueName": "DataLake::PROJ-CT-TBDF::WeeklyMeasurements::Oak Dene Hospital::PROJ-CT-TBDF_000029.csv_angleLeft_column" + }, + "end2": { + "class": "ElementStub", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "0db3e6ec-f5ef-4d75-ae38-b7ee6fd6ec0a", + "typeName": "GlossaryTerm", + "superTypeNames": [ + "AuthoredReferenceable", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "A semantic description of something, such as a concept, object, asset, technology, role or group.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "CONTENT_PACK", + "homeMetadataCollectionId": "655b1965-4c29-4a0e-8a5d-3f55a37b3799", + "homeMetadataCollectionName": "Coco Pharmaceuticals Combination", + "license": "Apache 2.0" + }, + "versions": { + "createdBy": "Egeria Project", + "updatedBy": "Egeria Project", + "maintainedBy": [ + "Egeria Project" + ], + "createTime": "2021-12-20T07:20:40.038+00:00", + "updateTime": "2021-12-20T07:20:40.038+00:00", + "version": 1791274688680 + }, + "guid": "e84999d8-ccc4-405e-9eb4-72f9a5ef5429", + "anchor": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "aa44f302-2e43-4669-a1e7-edaae414fc6e", + "typeName": "Anchors", + "typeVersion": 1, + "typeDescription": "Identifies the anchor entity for an element that is part of a large composite object such as an asset.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "CONTENT_PACK", + "homeMetadataCollectionId": "655b1965-4c29-4a0e-8a5d-3f55a37b3799", + "homeMetadataCollectionName": "Coco Pharmaceuticals Combination" + }, + "versions": { + "createdBy": "Egeria Project", + "updatedBy": "Egeria Project", + "maintainedBy": [ + "Egeria Project" + ], + "createTime": "2021-12-20T07:20:40.038+00:00", + "updateTime": "2021-12-20T07:20:40.038+00:00", + "version": 1791274688680 + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorTypeName": "GlossaryTerm", + "anchorDomainName": "AuthoredReferenceable", + "anchorScopeGUIDs": [ + "0f2c1abc-2aa2-4db8-9fb6-09c97998d78f" + ] + } + }, + "usageActivity": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "cfae23a1-8020-431f-a603-1f1bb0e01cb3", + "typeName": "UsageActivity", + "typeVersion": 1, + "typeDescription": "Describes the usage activity around an anchor element and its anchored elements: how often it is explicitly retrieved, found through searches, has its properties updated, and has its attachments and feedback updated or deleted.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842" + }, + "versions": { + "createdBy": "pepysnpa", + "updatedBy": "pepysnpa", + "maintainedBy": [ + "pepysnpa" + ], + "createTime": "2026-11-07T16:19:02.062+00:00", + "updateTime": "2026-11-09T22:53:30.416+00:00", + "version": 12, + "lastRequestId": "9cb9e734-9c44-49fb-9f9f-7810807c2fa5" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "UsageActivity", + "classificationProperties": { + "class": "UsageActivityProperties", + "typeName": "UsageActivity", + "explicitGetCount": 8, + "findCount": 74, + "updatePropertyCount": 0, + "updateAttachmentCount": 0, + "updateFeedbackCount": 0, + "deleteAttachmentCount": 0, + "deleteFeedbackCount": 0 + } + }, + "uniqueName": "GlossaryTerm::ClinicalTrialTerminology::AngleLeft" + } + }, + { + "relationshipHeader": { + "guid": "f40056a5-f572-49fd-bc42-ba959e79fb99" + }, + "end1": { + "class": "ElementStub", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "d3847402-c3ad-493e-946a-506205b765f8", + "typeName": "SubscribingActionProcess", + "superTypeNames": [ + "GovernanceActionProcess", + "GovernanceAction", + "GovernanceControl", + "GovernanceDefinition", + "AuthoredReferenceable", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "A governance action process that is used to create a subscription to a digital resource.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "jacquardnpa", + "updatedBy": "jacquardnpa", + "maintainedBy": [ + "jacquardnpa" + ], + "createTime": "2026-11-07T23:17:20.894+00:00", + "updateTime": "2026-11-07T23:17:20.894+00:00", + "version": 1, + "lastRequestId": "61b3b15c-4b0e-490f-bfd0-896fc4789494" + }, + "guid": "049c6ce2-193d-4509-af86-f9c41e527b5c", + "anchor": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "aa44f302-2e43-4669-a1e7-edaae414fc6e", + "typeName": "Anchors", + "typeVersion": 1, + "typeDescription": "Identifies the anchor entity for an element that is part of a large composite object such as an asset.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "jacquardnpa", + "updatedBy": "jacquardnpa", + "maintainedBy": [ + "jacquardnpa" + ], + "createTime": "2026-11-07T23:17:20.892+00:00", + "updateTime": "2026-11-07T23:17:20.892+00:00", + "version": 1, + "lastRequestId": "61b3b15c-4b0e-490f-bfd0-896fc4789494" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "091f7840-07cc-401c-afdf-e8ef43c982e5", + "anchorTypeName": "DigitalProduct", + "anchorDomainName": "AuthoredReferenceable", + "anchorScopeGUIDs": [ + "091f7840-07cc-401c-afdf-e8ef43c982e5" + ], + "zoneMembership": [ + "digital-products" + ] + } + }, + "uniqueName": "ProvisioningActionProcess::Valid Metadata Value Set: span::Create Subscription::ONGOING-UPDATE-SUBSCRIPTION" + }, + "end2": { + "class": "ElementStub", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "0db3e6ec-f5ef-4d75-ae38-b7ee6fd6ec0a", + "typeName": "GlossaryTerm", + "superTypeNames": [ + "AuthoredReferenceable", + "Referenceable", + "OpenMetadataRoot" + ], + "typeVersion": 1, + "typeDescription": "A semantic description of something, such as a concept, object, asset, technology, role or group.", + "typeCategory": "ENTITY_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "jacquardnpa", + "updatedBy": "jacquardnpa", + "maintainedBy": [ + "jacquardnpa" + ], + "createTime": "2026-11-07T15:10:10.424+00:00", + "updateTime": "2026-11-07T15:10:10.424+00:00", + "version": 1, + "lastRequestId": "422c5b52-2654-40ec-9701-1bbf1e5ade0e" + }, + "guid": "29877c5d-4696-49bf-86d4-4ddd58b3cbd4", + "anchor": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "aa44f302-2e43-4669-a1e7-edaae414fc6e", + "typeName": "Anchors", + "typeVersion": 1, + "typeDescription": "Identifies the anchor entity for an element that is part of a large composite object such as an asset.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842", + "homeMetadataCollectionName": "qs-metadata-store" + }, + "versions": { + "createdBy": "jacquardnpa", + "updatedBy": "jacquardnpa", + "maintainedBy": [ + "jacquardnpa" + ], + "createTime": "2026-11-07T15:10:10.422+00:00", + "updateTime": "2026-11-07T15:10:10.422+00:00", + "version": 1, + "lastRequestId": "422c5b52-2654-40ec-9701-1bbf1e5ade0e" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "Anchors", + "classificationProperties": { + "class": "AnchorsProperties", + "typeName": "Anchors", + "anchorGUID": "f7d8f943-e9c5-42f7-9b7a-63a72d18d13b", + "anchorTypeName": "CollectionFolder", + "anchorDomainName": "AuthoredReferenceable", + "anchorScopeGUIDs": [ + "cf98ae54-b68b-415d-a28f-15ac33f9611b" + ] + } + }, + "usageActivity": { + "class": "ElementClassification", + "headerVersion": 0, + "status": "ACTIVE", + "type": { + "typeId": "cfae23a1-8020-431f-a603-1f1bb0e01cb3", + "typeName": "UsageActivity", + "typeVersion": 1, + "typeDescription": "Describes the usage activity around an anchor element and its anchored elements: how often it is explicitly retrieved, found through searches, has its properties updated, and has its attachments and feedback updated or deleted.", + "typeCategory": "CLASSIFICATION_DEF" + }, + "origin": { + "sourceServer": "qs-metadata-store", + "originCategory": "LOCAL_COHORT", + "homeMetadataCollectionId": "9905c3cb-94c5-4494-9229-0d6f69c0b842" + }, + "versions": { + "createdBy": "pepysnpa", + "updatedBy": "pepysnpa", + "maintainedBy": [ + "pepysnpa" + ], + "createTime": "2026-11-07T16:18:42.014+00:00", + "updateTime": "2026-11-09T22:54:06.207+00:00", + "version": 12, + "lastRequestId": "9cb9e734-9c44-49fb-9f9f-7810807c2fa5" + }, + "classificationOrigin": "ASSIGNED", + "classificationName": "UsageActivity", + "classificationProperties": { + "class": "UsageActivityProperties", + "typeName": "UsageActivity", + "explicitGetCount": 2, + "findCount": 88, + "updatePropertyCount": 0, + "updateAttachmentCount": 0, + "updateFeedbackCount": 0, + "deleteAttachmentCount": 0, + "deleteFeedbackCount": 0 + } + }, + "uniqueName": "GlossaryTerm::Jacquard::Ongoing Update Subscription" + } + } + ] +} \ No newline at end of file diff --git a/tests/micro-tests/test_capped_count_not_measured.py b/tests/micro-tests/test_capped_count_not_measured.py index 14285dfc..1acc314b 100644 --- a/tests/micro-tests/test_capped_count_not_measured.py +++ b/tests/micro-tests/test_capped_count_not_measured.py @@ -182,8 +182,11 @@ def test_semantic_grounding_no_longer_reports_500_links_100_percent(): ce = MagicMock() ce.get_relationships.return_value = [{"guid": f"r{i}"} for i in range(CAP)] with om.recording_unmeasured() as notes: - assert om.semantic_grounding(mgr, ce) == {"groundingLinks": None, "groundingPct": None} - assert {n["count"] for n in notes} == {"Asset", "SemanticAssignment"} + r = om.semantic_grounding(mgr, ce) + assert r.pop("groundedAssetNote").startswith("Grounded Assets were not measured") + assert r == {"groundedAssets": None, "groundedAssetTotal": None, "groundedAssetPct": None, "groundingLinksScanned": None, "groundingLinksNotOnAsset": None, "groundingLinks": None, "groundingPct": None} + # the native link count and Asset counts, and the distinct-Asset scan (which saw one page again) + assert {n["count"] for n in notes} == {"Asset", "SemanticAssignment", "SemanticAssignment relationships"} def test_counts_by_type_and_its_sum_never_add_a_lower_bound_into_a_total(): @@ -298,8 +301,10 @@ def test_no_chart_is_drawn_over_an_unmeasured_count(fmt): def test_semantic_grounding_spec_reports_nulls_and_why(): out = _exec("Analytic Demo - Semantic Grounding") - assert out["data"] == {"groundingLinks": None, "groundingPct": None} - assert {n["count"] for n in out["unmeasured"]} == {"Asset", "SemanticAssignment"} + assert out["data"].pop("groundedAssetNote").startswith("Grounded Assets were not measured") + assert out["data"] == {"groundedAssets": None, "groundedAssetTotal": None, "groundedAssetPct": None, "groundingLinksScanned": None, "groundingLinksNotOnAsset": None, "groundingLinks": None, "groundingPct": None} + assert {n["count"] for n in out["unmeasured"]} == {"Asset", "SemanticAssignment", + "SemanticAssignment relationships"} rel = next(n for n in out["unmeasured"] if n["count"] == "SemanticAssignment") assert rel["reason"].startswith("no native relationship count is available") diff --git a/tests/micro-tests/test_dashboard_sheets_in_egeria.py b/tests/micro-tests/test_dashboard_sheets_in_egeria.py index de6f26b7..94379211 100644 --- a/tests/micro-tests/test_dashboard_sheets_in_egeria.py +++ b/tests/micro-tests/test_dashboard_sheets_in_egeria.py @@ -502,3 +502,68 @@ async def test_local_only_sheet_without_zones_reports_nothing_about_zones(egeria monkeypatch.setenv(LOCAL_ONLY_ENV, "1") result = await _run(egeria, "Create", "Dashboard Sheet", CREATE) assert "Zone Membership" not in result["output"] and "Zone Membership" not in result["message"] + + +# ---------------------------------------------------------------------------- ownership (DB-3, as migrate) + +def _owners(fake): + return [w for w in fake.writes if w[0] == "add_ownership"] + + +@pytest.mark.asyncio +async def test_create_sets_ownership_for_the_signed_in_user_once(egeria): + egeria.user_id = "garygeeke" + first = await _run(egeria, "Create", "Dashboard Sheet", CREATE) + writes = list(egeria.writes) + second = await _run(egeria, "Create", "Dashboard Sheet", CREATE) + + dashboard = egeria.by_qn(f"Dashboard::{SHEET}") + assert _owners(egeria) == [("add_ownership", dashboard, "garygeeke")] + assert egeria.writes == writes # the re-run writes nothing + assert "**Ownership**: garygeeke" in first["output"] + assert "**Ownership**: unchanged (already owned)" in second["output"] + assert "no change: already as written" in second["output"] + + +@pytest.mark.asyncio +async def test_dashboard_owner_names_another_user(egeria): + egeria.user_id = "garygeeke" + await _run(egeria, "Create", "Dashboard Sheet", {**CREATE, "Dashboard Owner": "peterprofile"}) + assert _owners(egeria) == [("add_ownership", egeria.by_qn(f"Dashboard::{SHEET}"), "peterprofile")] + + +@pytest.mark.asyncio +async def test_an_owned_dashboard_keeps_its_owner_and_says_so(egeria): + egeria.user_id = "garygeeke" + await _run(egeria, "Create", "Dashboard Sheet", CREATE) + result = await _run(egeria, "Create", "Dashboard Sheet", {**CREATE, "Dashboard Owner": "peterprofile"}) + assert [w[2] for w in _owners(egeria)] == ["garygeeke"] + assert "already owned by 'garygeeke'" in result["output"] + + +@pytest.mark.asyncio +async def test_no_known_user_and_no_owner_sets_no_ownership(egeria): + result = await _run(egeria, "Create", "Dashboard Sheet", CREATE) # the fake has no user_id + assert _owners(egeria) == [] and "Ownership" not in result["output"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("no_client", [False, True], ids=["local-only-env", "no-egeria-connection"]) +async def test_local_only_sets_no_ownership(egeria, monkeypatch, no_client): + egeria.user_id = "garygeeke" + if no_client: + client = None + else: + monkeypatch.setenv(LOCAL_ONLY_ENV, "1") + client = egeria + result = await _run(client, "Create", "Dashboard Sheet", {**CREATE, "Dashboard Owner": "peterprofile"}) + assert egeria.writes == [] + assert "**Ownership**: not written (local only)" in result["output"] + + +def test_dashboard_owner_says_the_default_is_the_user_the_command_runs_as(): + import json as _json + spec = _json.loads((_pl.Path(__file__).resolve().parents[2] / "md_processing" / "data" / "compact_commands" + / "commands_report_compact.json").read_text()) + text = spec["attribute_definitions"]["Dashboard Owner"]["description"] + assert "the user the command runs as" in text and "signed-in" not in text diff --git a/tests/micro-tests/test_overview_metric_definitions.py b/tests/micro-tests/test_overview_metric_definitions.py new file mode 100644 index 00000000..8298497e --- /dev/null +++ b/tests/micro-tests/test_overview_metric_definitions.py @@ -0,0 +1,42 @@ +"""What two Overview metrics count, as their specs and registry entries say (6.2.31). + +governed_coverage counts elements of any type the caller can see -- not a share of Assets (the +Portal's Governed tile is an Asset share across the repository, so the two differ by definition). +""" +from __future__ import annotations + +import pytest + +from pyegeria.view.analytic_registry import get_analytic_registry +from pyegeria.view.base_report_formats import get_report_registry + +pytestmark = pytest.mark.unit + + +def _spec_description(label: str) -> str: + spec = get_report_registry()[label] + return spec.description if hasattr(spec, "description") else spec["description"] + + +def test_governance_coverage_spec_says_any_type_not_a_share_of_assets(): + text = _spec_description("Analytic Demo - Governance Coverage") + assert "ANY type that you can see" in text + assert "not a share of Assets" in text + assert "Governed tile" in text # says why the Overview tile differs + + +def test_governed_coverage_registry_entry_is_not_a_share_of_assets(): + text = get_analytic_registry()["governed_coverage"].description + assert "Share of assets" not in text + assert "any type" in text and "not a share of Assets" in text + + +def test_semantic_grounding_spec_names_distinct_assets_and_keeps_links_apart(): + text = _spec_description("Analytic Demo - Semantic Grounding") + assert "DISTINCT Assets" in text and "groundedAssetPct" in text and "groundedAssetNote" in text + assert "on it or on any of its parts (tables, columns)" in text # owner's definition + assert "links, not Assets" in text + returns = get_analytic_registry()["semantic_grounding"].returns + for field in ("groundedAssets", "groundedAssetTotal", "groundedAssetPct", "groundedAssetNote", "groundingLinksScanned", "groundingLinksNotOnAsset", + "groundingLinks", "groundingPct"): + assert field in returns diff --git a/tests/micro-tests/test_overview_metrics.py b/tests/micro-tests/test_overview_metrics.py index 037b2758..79155f49 100644 --- a/tests/micro-tests/test_overview_metrics.py +++ b/tests/micro-tests/test_overview_metrics.py @@ -269,17 +269,129 @@ def test_certifications_summary_degrades_on_failure(): # ── semantic_grounding ──────────────────────────────────────────────────── +def _assignment(i, asset, end1_type=("CSVFile", ["DataFile", "Asset", "Referenceable"])): + type_name, supers = end1_type + return {"relationshipHeader": {"guid": f"r{i}"}, + "end1": {"guid": asset, "type": {"typeName": type_name, "superTypeNames": supers}}, + "end2": {"guid": f"t{i}", "type": {"typeName": "GlossaryTerm", "superTypeNames": ["Referenceable"]}}} + + def test_semantic_grounding_computes_percent(): mgr = _mgr(count_metadata_elements=MagicMock(return_value=100), count_relationships_between_elements=MagicMock(return_value=61)) ce = MagicMock() + ce.get_relationships.side_effect = _pages([]) result = om.semantic_grounding(mgr, ce) assert result["groundingLinks"] == 61 assert result["groundingPct"] == 61 - # both counts in the repository population; the relationship count goes through mgr (R4) - assert mgr.count_metadata_elements.call_args.kwargs == {"push_down": True} + # links: both native counts in the repository population; the relationship count goes through mgr (R4). + # grounded Assets: the Asset total in the viewer population (the scan's own population). + assert sorted(c.kwargs["push_down"] for c in mgr.count_metadata_elements.call_args_list) == [False, True] assert mgr.count_relationships_between_elements.call_args.kwargs == {"push_down": True} - ce.get_relationships.assert_not_called() + + +def test_semantic_grounding_counts_distinct_assets_not_links(): + # 6 links: asset a1 three times, a2 twice, and one link to a non-Asset (a glossary category) + rels = [_assignment(0, "a1"), _assignment(1, "a1"), _assignment(2, "a1"), _assignment(3, "a2"), + _assignment(4, "a2"), _assignment(5, "c1", ("GlossaryCategory", ["Referenceable"]))] + mgr = _mgr(count_metadata_elements=MagicMock(return_value=40), + count_relationships_between_elements=MagicMock(return_value=6)) + ce = MagicMock() + ce.get_relationships.side_effect = _pages(rels) + result = om.semantic_grounding(mgr, ce) + assert result["groundedAssets"] == 2 # distinct Assets, not 6 links + assert result["groundingLinksNotOnAsset"] == 1 # the glossary-category link + assert result["groundedAssetTotal"] == 40 # the viewer Asset total + assert result["groundedAssetPct"] == 5 # 2 / 40 + assert result["groundingLinks"] == 6 and result["groundingPct"] == 15 # links per hundred Assets + + +def _column_assignment(i, column, asset, memento=False): + end1 = {"guid": column, "type": {"typeName": "TabularColumn", + "superTypeNames": ["SchemaAttribute", "SchemaElement", "Referenceable"]}, + # as live: the anchor is an ElementClassification, its fields under classificationProperties + "anchor": {"class": "ElementClassification", "classificationName": "Anchors", + "classificationProperties": {"class": "AnchorsProperties", "anchorGUID": asset, + "anchorTypeName": "CSVFile", "anchorDomainName": "Asset"}}} + if memento: + end1["memento"] = {"classificationName": "Memento"} + return {"relationshipHeader": {"guid": f"r{i}"}, "end1": end1, + "end2": {"guid": f"t{i}", "type": {"typeName": "GlossaryTerm", "superTypeNames": ["Referenceable"]}}} + + +def test_semantic_grounding_counts_the_asset_a_columns_term_grounds(): + # As live: terms on Assets' columns, never on Assets. Columns c1, c2 of a1 and c3 of a2 ground 2 Assets; + # a deleted (memento) column of a3 grounds nothing; a process not anchored to an Asset counts for nothing. + process = {"relationshipHeader": {"guid": "rp"}, + "end1": {"guid": "p1", "type": {"typeName": "SubscribingActionProcess", "superTypeNames": ["Referenceable"]}, + "anchor": {"class": "ElementClassification", "classificationName": "Anchors", + "classificationProperties": {"anchorGUID": "p1", + "anchorTypeName": "SubscribingActionProcess", + "anchorDomainName": "Referenceable"}}}, + "end2": {"guid": "tp", "type": {"typeName": "GlossaryTerm"}}} + rels = [_column_assignment(0, "c1", "a1"), _column_assignment(1, "c2", "a1"), + _column_assignment(2, "c3", "a2"), _column_assignment(3, "c4", "a3", memento=True), process] + mgr = _mgr(count_metadata_elements=MagicMock(return_value=20), + count_relationships_between_elements=MagicMock(return_value=5)) + ce = MagicMock() + ce.get_relationships.side_effect = _pages(rels) + result = om.semantic_grounding(mgr, ce) + assert result["groundedAssets"] == 2 and result["groundedAssetPct"] == 10 + assert result["groundedAssetNote"] is None + assert result["groundingLinksNotOnAsset"] == 2 # the memento column and the process: shown, not dropped + + +def test_semantic_grounding_on_live_relationship_ends(): + import json + from pathlib import Path + live = json.loads((Path(__file__).parent / "data" / "semantic_assignment_live_ends_2026_11_11.json").read_text()) + rels = live["relationships"] + column, process = rels[0]["end1"], rels[1]["end1"] + assert column["type"]["typeName"] == "TabularColumn" and process["type"]["typeName"] == "SubscribingActionProcess" + asset = column["anchor"]["classificationProperties"]["anchorGUID"] + assert om._grounded_asset_guid(column) == asset # read from anchor.classificationProperties + assert om._grounded_asset_guid(process) is None # anchored to a DigitalProduct, not an Asset + mgr = _mgr(count_metadata_elements=MagicMock(return_value=50), + count_relationships_between_elements=MagicMock(return_value=2)) + ce = MagicMock() + ce.get_relationships.side_effect = _pages(rels) + result = om.semantic_grounding(mgr, ce) + assert result["groundedAssets"] == 1 and result["groundedAssetPct"] == 2 + assert result["groundingLinksNotOnAsset"] == 1 and result["groundingLinksScanned"] == 2 + + +def test_semantic_grounding_asset_itself_and_its_columns_count_once(): + # a term on the CSV file asset a1 itself, and on two columns of a1's table: one Asset + rels = [_assignment(0, "a1"), _column_assignment(1, "c1", "a1"), _column_assignment(2, "c2", "a1")] + mgr = _mgr(count_metadata_elements=MagicMock(return_value=10), + count_relationships_between_elements=MagicMock(return_value=3)) + ce = MagicMock() + ce.get_relationships.side_effect = _pages(rels) + result = om.semantic_grounding(mgr, ce) + assert result["groundedAssets"] == 1 and result["groundedAssetPct"] == 10 + assert result["groundingLinksNotOnAsset"] == 0 + + +def test_semantic_grounding_share_is_not_measured_when_the_viewer_asset_total_is_not(): + rels = [_assignment(0, "a1"), _assignment(1, "a2")] + + def count(body, push_down=None, **kw): + if push_down is False: + raise TimeoutError("viewer count timed out") + return 100 + + mgr = _mgr(count_metadata_elements=MagicMock(side_effect=count), + count_relationships_between_elements=MagicMock(return_value=2)) + mgr.find_metadata_elements.side_effect = lambda *a, **k: [{"elementHeader": {"guid": f"x{i}"}} for i in range(om.DEFAULT_CAP)] + ce = MagicMock() + ce.get_relationships.side_effect = _pages(rels) + with om.recording_unmeasured() as notes: + result = om.semantic_grounding(mgr, ce) + assert result["groundedAssets"] == 2 # the count always shows + assert result["groundedAssetTotal"] is None and result["groundedAssetPct"] is None # never mixed populations + assert result["groundedAssetNote"].startswith("The share of Assets grounded was not measured") + assert any(n["count"] == "Asset" for n in notes) + assert result["groundingLinks"] == 2 and result["groundingPct"] == 2 def test_semantic_grounding_handles_zero_cataloged(): diff --git a/tests/micro-tests/test_rs_w2_3_inputs_by_role.py b/tests/micro-tests/test_rs_w2_3_inputs_by_role.py index de457f9b..800b2cea 100644 --- a/tests/micro-tests/test_rs_w2_3_inputs_by_role.py +++ b/tests/micro-tests/test_rs_w2_3_inputs_by_role.py @@ -264,11 +264,14 @@ def spy(mgr, ce, **kw): result = _run("Analytic Demo - Semantic Grounding", token="caller-token") finally: om_spy.undo() - assert result["kind"] == "json" and set(result["data"]) == {"groundingLinks", "groundingPct"} + assert result["kind"] == "json" and set(result["data"]) == { + "groundedAssets", "groundedAssetTotal", "groundedAssetPct", "groundedAssetNote", "groundingLinksScanned", "groundingLinksNotOnAsset", + "groundingLinks", "groundingPct"} assert len(fake_tech) == 1 and fake_tech[0].tokens == ["caller-token"] and fake_tech[0].minted == 0 assert seen["mgr"] is seen["ce"] is fake_tech[0] - # both counts native in the repository population; the relationship count goes through mgr (R4) - assert {c[0] for c in fake_tech[0].calls} == {"count_metadata_elements", "count_relationships_between_elements"} + # native counts through mgr (R4), and the SemanticAssignment scan for distinct grounded Assets (6.2.31) + assert {c[0] for c in fake_tech[0].calls} == {"count_metadata_elements", "count_relationships_between_elements", + "get_relationships"} def test_end_to_end_an_environment_supply_is_asked_by_declared_class_in_order(fake_tech): diff --git a/uv.lock b/uv.lock index c2c79796..2b353396 100644 --- a/uv.lock +++ b/uv.lock @@ -2238,7 +2238,7 @@ sdist = { url = "https://files.pythonhosted.org/packages/f8/f6/8f49005d581cff883 [[package]] name = "pyegeria" -version = "6.2.30" +version = "6.2.31" source = { editable = "." } dependencies = [ { name = "altair" },