Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions PYEGERIA_ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<name>` 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
Expand Down
20 changes: 12 additions & 8 deletions docs/output-formats-and-report-specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<Class>`, `reader:<name>`, `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:<name>` 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.

Expand Down Expand Up @@ -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).
Expand All @@ -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

Expand Down
35 changes: 30 additions & 5 deletions pyegeria/view/_output_format_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -247,18 +248,42 @@ 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)
optional_params: Optional[List[str]] = Field(default_factory=list)
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:<name>, viewer, subject, "
f"egeria_client:<Class>); 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
Expand Down
37 changes: 4 additions & 33 deletions pyegeria/view/format_set_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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():
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)


Expand Down
15 changes: 3 additions & 12 deletions pyegeria/view/spec_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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.
Expand Down
47 changes: 33 additions & 14 deletions tests/micro-tests/test_issue_138_140_149_analytic_envelope.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:<name>` 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`.
Expand Down Expand Up @@ -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
Expand Down
7 changes: 0 additions & 7 deletions tests/micro-tests/test_issue_169_analytic_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"}, {})
Loading
Loading