diff --git a/PYEGERIA_ISSUES.md b/PYEGERIA_ISSUES.md index ed18b723..77448bad 100644 --- a/PYEGERIA_ISSUES.md +++ b/PYEGERIA_ISSUES.md @@ -1292,6 +1292,8 @@ constructed from params. **Fixed 2026-10-13:** `ActionParameter.analytic_binders` maps a parameter name to a factory's dotted path (`pkg.mod.Factory` or `pkg.mod:Factory`). `_apply_analytic_binders` (format_set_executor.py) calls the factory with the call params its signature names, consuming them unless the routine also takes them, and passes the result to the routine by name. trellis can then name `trellis_analytics.routines.curation_coverage` directly, with `analytic_binders={"ods": "trellis_analytics.readers.ods.OdsReader"}` and the caller passing `url`. Tests: `tests/micro-tests/test_issue_138_140_149_analytic_envelope.py`. Documented in `docs/output-formats-and-report-specs.md`. +**Superseded 2026-11-08 (RS-W2-3 PR-B):** `analytic_binders` and `_apply_analytic_binders` are removed. A reader is now a declared `reader:` input that the environment's role supply provides (RS-W2-3 PR-A). For one release `ActionParameter` accepts the key and ignores it, with a `DeprecationWarning` when it is non-empty. No built-in, demo or library 0.4.0 spec set it. + --- ### ISSUE-151: `AutomatedCuration.get_engine_actions()` calls `automated-curation/engine-actions`, which the View Server doesn't have (404, reported as "unable to connect"); `find_engine_actions("*")` is the working list-all diff --git a/docs/output-formats-and-report-specs.md b/docs/output-formats-and-report-specs.md index 97aa6bf1..1ee463a7 100644 --- a/docs/output-formats-and-report-specs.md +++ b/docs/output-formats-and-report-specs.md @@ -982,17 +982,21 @@ The `absence` states are the four of trellis-analytics: `not_measured`, `not_per A result without an envelope is returned exactly as before. A result that is a pydantic model is returned as plain data (`model_dump`). See ISSUE-139/140/171. -**Building non-JSON arguments (`analytic_binders`).** Report-spec params are JSON, and only leading parameters named `mgr`/`ce`/`expert`/`client` get an Egeria client. To name a routine that takes some other object (e.g. a reader) by its own dotted path, map the parameter to a factory: +**Non-JSON arguments are declared `inputs` (RS-W2-3).** Report-spec params are JSON. A routine's other arguments (Egeria clients, readers, the viewer, the subject in view) are its registry entry's `inputs`, one role word per leading positional argument, in order: ```python -ActionParameter( - analytic_function="trellis_analytics.routines.curation_coverage", - analytic_binders={"ods": "trellis_analytics.readers.ods.OdsReader"}, - analytic_spec_params={"resource_type": "database"}, +AnalyticFunctionSpec( + name="semantic_grounding", + function="pyegeria.view.overview_metrics.semantic_grounding", + inputs=["egeria_client:MetadataExpert", "egeria_client:ClassificationExplorer"], ) ``` -Here `OdsReader(url)` takes `url`, so the caller passes `url` and the routine receives the built reader as `ods`. The factory is called with the call params its own signature names, and those params are consumed unless the routine also takes them. A routine with no client parameter still connects to nothing (ISSUE-137, ISSUE-138). +The role words are `egeria_client:`, `reader:`, `viewer` and `subject`. The executor asks a role supply for each input before the routine runs and passes them positionally; declared params follow by name. No parameter name is read to decide what to pass. `exec_report_spec(..., supply=...)` takes an environment's own supply (`pyegeria.view.role_supply.RoleSupply`). Without one, `PlainSupply` hands the caller's single `EgeriaTech` to every `egeria_client` input whose class it serves, and refuses readers, the viewer and the subject. A role the supply cannot provide raises `RoleRefused` with the supply's words before any stage runs. A routine that declares no `egeria_client` input still connects to nothing (ISSUE-137). + +Check 5 refuses, at load and at run with the same words, a routine whose binding takes leading `mgr`/`ce`/`expert`/`client` arguments that its `inputs` do not declare. The fix is to declare them. + +`analytic_binders` (ISSUE-138's factories) was removed in RS-W2-3 PR-B. For one release a spec that still carries the key loads, and the key is ignored: silently when empty, with a `DeprecationWarning` and a logged warning when not. Declare a reader as a `reader:` input instead, and have the environment's supply provide it. **`analytic_spec_params` are defaults, not pins.** Unlike the find path's `spec_params` (always fixed — a caller-supplied value for the same key is silently overridden), `analytic_spec_params` set a *default* that a caller-supplied value for the same key overrides. This is what lets a report spec like the demo "Element Count by Type" (which pins `type_name: "GlossaryTerm"` as its default) actually be re-pointed at a different type at run time instead of being permanently locked to the demo's own default. @@ -1020,7 +1024,7 @@ A name defined twice raises `AnalyticRegistryCollision`, except that an installe #### Which functions a report spec may name -A report spec is data: it can come from a user's report-spec directory or a config file. So `exec_report_spec` does not import whatever it names (ISSUE-169). `analytic_function`, an action's `fetch`/`analytic` steps and `analytic_binders` factories are resolved in this order: +A report spec is data: it can come from a user's report-spec directory or a config file. So `exec_report_spec` does not import whatever it names (ISSUE-169). `analytic_function` and an action's `fetch`/`analytic` steps are resolved in this order: 1. **A registered name** resolves to that entry's `function`. This is the form report specs use. 2. **A dotted path that a registered entry declares** is trusted, but not in a report spec (below). @@ -1029,7 +1033,7 @@ A report spec is data: it can come from a user's report-spec directory or a conf To use a function from your own package, register it (any tier above, usually an entry point), or add your package to `PYEGERIA_ANALYTIC_MODULE_PREFIXES`. Registering is better: the function then appears in the registry for authoring tools, and it can carry a declaration. -**Report specs name functions by registered name (ISSUE-173).** A report spec's `analytic_function`, or a function-valued parameter such as `metric_trend`'s `metric_path`, must be a registered name. From 6.2.19 anything else, including a dotted path that steps 2 and 3 would accept, raises `AnalyticFunctionRefused` before any import. The message names the registered name to use or, if there is none, says to register the function. (6.2.18 still resolved dotted paths with a `DeprecationWarning`.) Steps 2 and 3 still apply to code rather than report-spec data: registry entries themselves (`AnalyticFunctionSpec.function`, an action's `fetch`/`analytic`) and `analytic_binders` factories keep their dotted paths. +**Report specs name functions by registered name (ISSUE-173).** A report spec's `analytic_function`, or a function-valued parameter such as `metric_trend`'s `metric_path`, must be a registered name. From 6.2.19 anything else, including a dotted path that steps 2 and 3 would accept, raises `AnalyticFunctionRefused` before any import. The message names the registered name to use or, if there is none, says to register the function. (6.2.18 still resolved dotted paths with a `DeprecationWarning`.) Steps 2 and 3 still apply to code rather than report-spec data: registry entries themselves (`AnalyticFunctionSpec.function`, an action's `fetch`/`analytic`) keep their dotted paths. #### Declaring what results mean diff --git a/pyegeria/view/_output_format_models.py b/pyegeria/view/_output_format_models.py index ab3deb51..ee861a09 100644 --- a/pyegeria/view/_output_format_models.py +++ b/pyegeria/view/_output_format_models.py @@ -66,6 +66,7 @@ import json import os +import warnings from pathlib import Path from typing import Dict, List, Optional, Union, Any from pydantic import BaseModel, Field, field_validator, model_validator @@ -247,10 +248,12 @@ class ActionParameter(BaseModel): analytic_spec_params: Parameters fixed for this action, for `analytic_function` (from `extra_constraints`) -- layered under whatever arbitrary parameters the caller supplies at execution time. - analytic_binders: Parameter name -> dotted path of a factory that builds that - argument (e.g. a reader object) for `analytic_function` (ISSUE-138). The - factory's own parameters are filled from the call params by name, so a - routine that takes a non-JSON object can be named by its own dotted path. + + RS-W2-3 PR-B: the former `analytic_binders` field is gone. A routine's non-JSON + arguments (clients, readers, viewer, subject) are its declared `inputs`, which the + executor's role supply provides. For one release a spec that still carries the key is + accepted and the key ignored, with a DeprecationWarning when it is non-empty + (`_drop_deprecated_binders`). """ function: Optional[str] = None required_params: List[str] = Field(default_factory=list) @@ -258,7 +261,29 @@ class ActionParameter(BaseModel): spec_params: Dict[str, Any] = Field(default_factory=dict) analytic_function: Optional[str] = None analytic_spec_params: Dict[str, Any] = Field(default_factory=dict) - analytic_binders: Dict[str, str] = Field(default_factory=dict) + + @model_validator(mode="before") + @classmethod + def _drop_deprecated_binders(cls, values): + """Accept and ignore the removed `analytic_binders` key for one release (RS-W2-3 PR-B). + + An empty mapping (what older generated specs serialise) is dropped silently. A non-empty + one is dropped with a DeprecationWarning and a log warning naming the parameters: the + routine must declare them as `inputs` instead, or its call will lack them. + """ + if isinstance(values, dict) and "analytic_binders" in values: + values = dict(values) + binders = values.pop("analytic_binders") + if binders: + names = ", ".join(sorted(binders)) if isinstance(binders, dict) else repr(binders) + message = ( + f"analytic_binders is no longer supported and is ignored (binders for: {names}). " + f"Declare these arguments as the routine's inputs (reader:, viewer, subject, " + f"egeria_client:); the environment's role supply provides them. " + f"The key will be refused in a later release.") + warnings.warn(message, DeprecationWarning, stacklevel=2) + logger.warning(message) + return values @model_validator(mode="before") @classmethod diff --git a/pyegeria/view/format_set_executor.py b/pyegeria/view/format_set_executor.py index ac5e9ea0..3fa13daf 100644 --- a/pyegeria/view/format_set_executor.py +++ b/pyegeria/view/format_set_executor.py @@ -142,7 +142,7 @@ def _import_callable(func_decl: str): def _resolve_analytic_function(func_decl: str): """Return the callable a report spec's analytic_function (or an action's - fetch/analytic step, or a binder factory) names. + fetch/analytic step) names. Unlike `function` (find_method), `analytic_function` (extra_find) targets a plain module-level function, not a client class method -- overview_metrics.py's @@ -157,8 +157,8 @@ class to resolve here, just the function itself. 3. Any other dotted path must sit under an allowed module prefix (`python_binding_allowed`); anything else raises AnalyticFunctionRefused before any import happens. - Cases 2 and 3 are binding targets (an action's fetch/analytic step, a binder - factory): a report spec never reaches them, because + Cases 2 and 3 are binding targets (an action's fetch/analytic step): a report + spec never reaches them, because `resolve_report_spec_function` accepts registered names only (ISSUE-173). """ if not isinstance(func_decl, str) or not func_decl.strip(): @@ -254,34 +254,6 @@ def run_analytic_action( return analytic_func(raw_result, *fetch_args, **(analytic_kwargs or {})) -def _apply_analytic_binders(func, binders: Dict[str, str], call_params: Dict[str, Any]) -> Dict[str, Any]: - """Build non-JSON arguments for an analytic function from its call params (ISSUE-138). - - `binders` maps a parameter name of `func` to the dotted path of a factory - (e.g. `{"ods": "trellis_analytics.readers.ods.OdsReader"}`). Each factory is - called with the call params its own signature names; those params are - consumed unless `func` also takes them. A param the caller already supplied - under the bound name wins over the factory. - """ - if not binders: - return call_params - params = dict(call_params) - func_params = set(inspect.signature(func).parameters) - for target, factory_decl in binders.items(): - if target in params: - continue - factory = _resolve_analytic_function(factory_decl.replace(":", ".")) - factory_sig = inspect.signature(factory) - accepts_any = any(p.kind is inspect.Parameter.VAR_KEYWORD for p in factory_sig.parameters.values()) - names = set(params) if accepts_any else set(factory_sig.parameters) & set(params) - kwargs = {n: params[n] for n in names} - for n in names: - if n not in func_params: - params.pop(n) - params[target] = factory(**kwargs) - return params - - # Result-state envelope (ISSUE-139/140). A routine that reports how sure it is # carries one of these states; only an established answer (measured, or # nothing_found = a real zero) has numbers worth charting. @@ -443,12 +415,11 @@ def _run_analytic_function( func = resolve_report_spec_function(func_decl) from pyegeria.view.spec_resolver import declared_inputs # lazy: the resolver imports this module inputs = declared_inputs(func_decl, func) # check 5: the same function the resolver runs at load - call_params = _apply_analytic_binders(func, action.get("analytic_binders") or {}, call_params) if supply is None: supply = PlainSupply(client_factory=lambda: _plain_client(view_server, view_url, user, user_pass, token)) # Every role is obtained here, before the routine runs; a routine that declares no # egeria_client input never connects or mints a token (ISSUE-137). - args = supply_inputs(getattr(func_decl, "__name__", func_decl), inputs, supply) + args = supply_inputs(func_decl, inputs, supply) return func(*args, **call_params) diff --git a/pyegeria/view/spec_resolver.py b/pyegeria/view/spec_resolver.py index dbbb7d50..c7cc1bc5 100644 --- a/pyegeria/view/spec_resolver.py +++ b/pyegeria/view/spec_resolver.py @@ -14,7 +14,7 @@ (`action.analytic_function`). For them the §2c checks are: 1. names: the find method resolves on the client class the executor would use; the analytic - routine is a registered name with a python binding that imports; binder and function-valued + routine is a registered name with a python binding that imports; function-valued parameters name what they must. 2. parameters: every parameter the executor always sends (required params, spec_params, output_format, report_spec) is one the find method accepts; every analytic_spec_params key @@ -285,7 +285,7 @@ def _check_analytic(name: str, action: Dict[str, Any], fail, notes, warns, out: """Checks 1, 2, 5, 6 for the analytic stage. Returns the routine's declaration, or None.""" from pyegeria.view.analytic_registry import get_analytic_registry from pyegeria.view.format_set_executor import (AnalyticFunctionRefused, _import_callable, - _resolve_analytic_function, resolve_report_spec_function) + resolve_report_spec_function) from pyegeria.view.role_supply import RoleRefused func_decl = action["analytic_function"] @@ -313,19 +313,10 @@ def _check_analytic(name: str, action: Dict[str, Any], fail, notes, warns, out: notes.append(f"check 3: routine '{func_decl}' runs fetch {entry.action.fetch} then analytic " f"{entry.action.analytic}; neither step declares its shapes, so the hand-off is not checked") - for param, binder in (action.get("analytic_binders") or {}).items(): - try: - _resolve_analytic_function(binder) - except AnalyticFunctionRefused as exc: - fail(1, f"its binder for {param} is refused: {exc}") - except Exception as exc: # noqa: BLE001 - fail(1, f"its binder for {param} ('{binder}') cannot be imported: {exc}") - declared = [p.name for p in entry.params] out["params"].extend(p for p in declared if p not in out["params"]) spec_params = action.get("analytic_spec_params") or {} - binders = set((action.get("analytic_binders") or {}).keys()) - unknown = [k for k in spec_params if k not in declared and k not in binders] + unknown = [k for k in spec_params if k not in declared] if unknown and not declared: # A routine that declares no parameters at all is silent about them, not declaring none: # the spec runs today, so this is the declaration's gap, said as a warning. diff --git a/tests/micro-tests/test_issue_138_140_149_analytic_envelope.py b/tests/micro-tests/test_issue_138_140_149_analytic_envelope.py index 9cfc70f8..f19b34da 100644 --- a/tests/micro-tests/test_issue_138_140_149_analytic_envelope.py +++ b/tests/micro-tests/test_issue_138_140_149_analytic_envelope.py @@ -4,8 +4,9 @@ Regression tests for the analytic executor and registry changes requested by trellis-analytics (PYEGERIA_ISSUES.md): -- ISSUE-138: `analytic_binders` builds a non-JSON argument (e.g. a reader) from - the call params, so a routine can be named by its own dotted path. +- ISSUE-138: a routine that takes a non-JSON argument (e.g. a reader) gets it. + Since RS-W2-3 PR-B that is a declared `reader:` input, supplied by the + environment's role supply; the old `analytic_binders` factories are gone. - ISSUE-139: a result's state envelope is returned on every output and put on the chart as a subtitle. - ISSUE-140: no chart is drawn unless the state is `measured`. @@ -99,20 +100,38 @@ def _use_spec(monkeypatch, action: dict): monkeypatch.setattr(fse, "select_report_spec", lambda name, fmt_type: fmt) -# ISSUE-138 -def test_binder_builds_the_reader_from_params(monkeypatch): - _use_spec(monkeypatch, {"analytic_function": f"{MOD}.read_with", - "analytic_binders": {"ods": f"{MOD}.Reader"}}) - out = fse.exec_report_spec("tile", output_format="DICT", params={"slug": "db1", "url": "pg://x"}) - assert out["data"]["url"] == "pg://x" # the factory got url - assert out["data"]["slug"] == "db1" # the routine still got its own param +# ISSUE-138, as RS-W2-3 PR-B leaves it: the reader is a declared input the environment supplies. +class _ReaderSupply: + def __init__(self): + self.asked = [] + + def client(self, cls): + raise AssertionError("a routine that declares no client must not be given one") + + def viewer(self): + raise AssertionError("not declared") + + def reader(self, source): + self.asked.append(source) + return Reader(url=f"pg://{source}") + def subject(self): + return None -def test_binder_accepts_colon_form(monkeypatch): - _use_spec(monkeypatch, {"analytic_function": f"{MOD}.read_with", - "analytic_binders": {"ods": f"{MOD}:Reader"}}) - out = fse.exec_report_spec("tile", output_format="DICT", params={"slug": "db1"}) - assert out["data"]["url"] == "" + def refusal_words(self, kind): + return f"no {kind} here" + + +def test_a_declared_reader_input_is_supplied_by_the_environment(monkeypatch): + register_analytic_functions({"t138-reader": {"name": "t138-reader", "function": f"{MOD}.read_with", + "inputs": ["reader:ods"]}}) + fmt = {"target_type": None, "action": {"function": None, "analytic_function": "t138-reader"}} + monkeypatch.setattr(fse, "select_report_spec", lambda name, fmt_type: fmt) + supply = _ReaderSupply() + out = fse.exec_report_spec("tile", output_format="DICT", params={"slug": "db1"}, supply=supply) + assert supply.asked == ["ods"] + assert out["data"]["url"] == "pg://ods" # the supply built the reader, not a factory named in the spec + assert out["data"]["slug"] == "db1" # the routine still got its own param # ISSUE-139 / ISSUE-140 diff --git a/tests/micro-tests/test_issue_169_analytic_resolver.py b/tests/micro-tests/test_issue_169_analytic_resolver.py index 48093ba0..9aef3b3f 100644 --- a/tests/micro-tests/test_issue_169_analytic_resolver.py +++ b/tests/micro-tests/test_issue_169_analytic_resolver.py @@ -90,10 +90,3 @@ def test_env_var_overrides_the_allowlist(monkeypatch): assert fse._resolve_analytic_function("json.dumps") is json.dumps with pytest.raises(fse.AnalyticFunctionRefused): fse._resolve_analytic_function("pyegeria.core.utils.body_slimmer") - - -def test_binder_factories_go_through_the_same_check(): - def analytic(ods=None): - return ods - with pytest.raises(fse.AnalyticFunctionRefused): - fse._apply_analytic_binders(analytic, {"ods": "os:getcwd"}, {}) diff --git a/tests/micro-tests/test_rs_w2_2_spec_resolver.py b/tests/micro-tests/test_rs_w2_2_spec_resolver.py index 21b2f431..c374b564 100644 --- a/tests/micro-tests/test_rs_w2_2_spec_resolver.py +++ b/tests/micro-tests/test_rs_w2_2_spec_resolver.py @@ -84,7 +84,6 @@ def test_every_analytic_demo_spec_is_runnable(): (_analytic("pyegeria.view.overview_metrics.count_elements"), "use its registered name 'count_elements'"), (_analytic("metric_trend", analytic_spec_params={"metric_path": "nope"}), "its metric_path 'nope' is not a registered routine name"), - (_analytic("count_elements", analytic_binders={"type_name": "os.getcwd"}), "its binder for type_name is refused"), ]) def test_check_1_names(action, words): result = sr.resolve(_spec(action), "Probe") 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 84a5875d..1713d9a4 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 @@ -303,3 +303,41 @@ def test_every_demo_spec_lists_its_declared_inputs_at_load(): assert result.runnable, result.unrunnable_reason entry = BUILTIN_ANALYTIC_FUNCTIONS[spec.action.analytic_function] assert result.role_inputs == entry.inputs + + +# ── PR-B: the binder is gone; the key is accepted and ignored for one release ── + +def test_a_spec_still_carrying_analytic_binders_loads_with_a_deprecation_warning(): + with pytest.warns(DeprecationWarning, match=r"analytic_binders is no longer supported .*binders for: ods"): + action = ActionParameter(analytic_function="count_elements", + analytic_binders={"ods": "trellis_analytics.readers.ods.OdsReader"}) + assert "analytic_binders" not in action.model_dump() + + +def test_an_empty_analytic_binders_key_is_dropped_silently(): + import warnings + with warnings.catch_warnings(): + warnings.simplefilter("error") + action = ActionParameter.model_validate({"analytic_function": "count_elements", "analytic_binders": {}}) + assert "analytic_binders" not in action.model_dump() + + +def test_a_spec_with_a_binder_runs_on_declared_inputs_alone(monkeypatch, fake_tech): + """The ignored binder neither builds nor replaces anything: the routine gets its declared inputs.""" + seen = {} + + def probe(mgr, type_name="x"): + seen["args"] = (mgr, type_name) + return {"count": 1} + + _routine(monkeypatch, "binder_probe", probe, ["egeria_client:MetadataExpert"]) + with pytest.warns(DeprecationWarning): + action = ActionParameter(analytic_function="binder_probe", analytic_binders={"mgr": "os.getcwd"}) + brf.register_report_specs({"W23-Binder": FormatSet( + heading="W23-Binder", description="probe", target_type="Referenceable", action=action, + formats=[Format(types=["DICT"], attributes=[])])}, source="test") + assert sr.resolve(brf.get_report_registry()["W23-Binder"], "W23-Binder").runnable + result = _run("W23-Binder", params={"type_name": "Asset"}) + assert result == {"kind": "json", "data": {"count": 1}} + assert len(fake_tech) == 1 and seen["args"] == (fake_tech[0], "Asset") # the caller's client, not os.getcwd() + assert not hasattr(fse, "_apply_analytic_binders")