Plugins
Discover installed Lacuna plugins without running them, then activate one on purpose, and know exactly what that does and does not guarantee.
A plugin is a Python package meant to offer something to Lacuna: an adapter, an audit rule, a cost model, a method or a report section. In 0.14.3 Lacuna defines how plugins are found and activated, but wires nothing in; what an activated plugin does is up to you. Python’s packaging system lets such a package announce itself through an entry point, and Lacuna reads those announcements. The hard part is trust. An entry point names code, and loading it runs that code, with your permissions, inside your process.
Lacuna therefore splits the work in two. Discovery reads installed package metadata and imports nothing. Activation is a separate call that you make for one named plugin, and it records what it ran. That record can say which plugin, which declared version and which configuration a result depended on, within the limits described under Recording the activation. Nothing in Lacuna discovers or activates a plugin on its own.
Discovering plugins
lc.plugins.discover_plugins lists the entry points installed in the current environment. With no third-party plugin installed, it returns an empty tuple:
import lacuna as lc
print(lc.plugins.discover_plugins()) () An empty result is the normal state of a fresh environment, not an error. Plugins are looked up in five entry-point groups, one per kind of extension. lc.plugins.ENTRY_POINT_GROUPS maps the short group name you pass to Lacuna to the entry-point group a package declares:
for name, group in lc.plugins.ENTRY_POINT_GROUPS.items():
print(f"{name}: {group!r}") adapters: 'lacuna.adapters.v1'
audit_rules: 'lacuna.audit_rules.v1'
cost_models: 'lacuna.cost_models.v1'
methods: 'lacuna.methods.v1'
report_sections: 'lacuna.report_sections.v1' The version suffix is part of the group name, so a future incompatible protocol can live beside this one.
| Parameter | Meaning |
|---|---|
group | One of adapters, audit_rules, cost_models, methods or report_sections. Omit it to search all five. Any other value raises MethodContractError. |
Each result is a PluginCandidate: the entry-point name, its group and value (the module:attribute string it points to), and the distribution name and distribution_version of the package that installed it. A candidate is only metadata. The module it points to has not been imported. Candidates come back sorted by group, name, distribution and value, so the order does not depend on how the environment was built.
A plugin, end to end
To show the whole flow without installing anything, the next block writes a small package and its packaging metadata into the working directory and puts that directory on sys.path. It stands in for pip install acme-costs. A real plugin ships the same two things in its wheel: a module and an entry_points.txt.
import sys
import textwrap
from pathlib import Path
workdir = Path.cwd()
(workdir / "acme_flat_costs.py").write_text(
textwrap.dedent(
'''
print("acme_flat_costs imported")
from lacuna.plugins import PluginDescriptor
class FlatCost:
def __init__(self, config):
self.bps = float(config.get("bps", 3.0))
self.descriptor = PluginDescriptor(
plugin_id="acme_flat",
protocol_version="1.0",
capabilities=("cost_model.flat",),
method_versions={"acme_flat": 1},
required_dependencies=("numpy",),
)
def create(config):
return FlatCost(config)
'''
)
)
def install_stand_in(distribution: str, version: str, entry_points: str) -> None:
dist_info = workdir / f"{distribution.replace('-', '_')}-{version}.dist-info"
dist_info.mkdir()
(dist_info / "METADATA").write_text(
f"Metadata-Version: 2.1\nName: {distribution}\nVersion: {version}\n"
)
(dist_info / "entry_points.txt").write_text(entry_points)
cost_group = lc.plugins.ENTRY_POINT_GROUPS["cost_models"]
install_stand_in("acme-costs", "0.3.0", f"[{cost_group}]\nacme_flat = acme_flat_costs:create\n")
sys.path.insert(0, str(workdir))
for candidate in lc.plugins.discover_plugins():
print(
(
candidate.name,
candidate.group,
candidate.value,
candidate.distribution,
candidate.distribution_version,
)
)
print("module imported by discovery:", "acme_flat_costs" in sys.modules) ('acme_flat', 'lacuna.cost_models.v1', 'acme_flat_costs:create', 'acme-costs', '0.3.0')
module imported by discovery: False Discovery found the plugin and its package version, and the module was not imported: the print at the top of the module has not run. That is the guarantee discovery makes. You can inspect what is installed, in CI or on a machine you do not trust yet, without executing any of it.
Selecting one plugin
lc.plugins.select_plugin resolves a single candidate by name within a group:
candidate = lc.plugins.select_plugin("acme_flat", group="cost_models")
print(candidate.name, candidate.distribution, candidate.distribution_version) acme_flat acme-costs 0.3.0 It raises PluginError when nothing matches, and when more than one installed package provides the same name. In that case you choose the provider with distribution:
install_stand_in("other-costs", "1.0.0", f"[{cost_group}]\nacme_flat = other_costs:create\n")
try:
lc.plugins.select_plugin("acme_flat", group="cost_models")
except lc.PluginError as error:
print(error)
chosen = lc.plugins.select_plugin("acme_flat", group="cost_models", distribution="acme-costs")
print(chosen.distribution, chosen.value) plugin name 'acme_flat' is ambiguous in group 'cost_models'; choose a distribution: acme-costs, other-costs
acme-costs acme_flat_costs:create The second package points at a module that does not exist, and nothing went wrong, because nothing was loaded. Name collisions are resolved by you, in code, rather than by whichever package was installed last.
| Parameter | Meaning |
|---|---|
name | The entry-point name. Must not be empty. |
group | The group to search, as in discover_plugins. Keyword-only and required. |
distribution | The installed package to take the plugin from, matched exactly against the package’s metadata name: no case folding, and - and _ are not interchangeable. Required only when two packages use the same name. |
Activating a plugin
lc.plugins.activate_plugin is the one place Lacuna runs plugin code. Everything it does happens in this order:
- It checks your arguments and that
configcan be recorded as JSON. - It imports the module the entry point names. Import-time code runs here.
- It checks the loaded object is callable and calls it with one argument, your configuration mapping. This is the plugin’s factory.
- It checks that the returned object has a
descriptorattribute that is aPluginDescriptor. - It checks the descriptor’s
plugin_idequals the entry-point name, its protocol major version equalsprotocol_major, and, when you passed one, thatrequired_capabilityis among its capabilities.
Steps 3 to 5 run after the plugin’s code has already executed. They are compatibility checks on what came back, not a gate that keeps the code from running; only step 1 happens before any plugin code. A failure in steps 2 to 5 raises PluginError, with the original exception attached as the cause when the plugin’s own code failed. Bad arguments or an unrecordable config (step 1) raise MethodContractError before any plugin code runs.
activated = lc.plugins.activate_plugin(
chosen,
config={"bps": 4.5},
required_capability="cost_model.flat",
)
print("module imported after activation:", "acme_flat_costs" in sys.modules)
print(activated.descriptor.plugin_id, activated.descriptor.capabilities)
print(activated.implementation.bps) acme_flat_costs imported
module imported after activation: True
acme_flat ('cost_model.flat',)
4.5 The print in the module ran during activation, which is the first and only time the plugin’s code ran. The result is an ActivatedPlugin with four fields: the candidate you activated, the validated descriptor, the implementation object the factory returned, and evidence, an AnalysisResult that records the activation.
| Parameter | Meaning |
|---|---|
candidate | A PluginCandidate from discover_plugins or select_plugin. Anything else raises MethodContractError. |
config | A mapping recorded in the evidence and passed to the plugin’s factory. Every value must be JSON-compatible. The factory receives a read-only, JSON-normalized copy (a mappingproxy in which lists have become tuples), not your own object. Defaults to an empty mapping. |
required_capability | A capability name the descriptor must list. Set it whenever you are going to depend on a particular feature. |
protocol_major | The major protocol version you expect, default 1. A descriptor whose protocol_version has a different major version is rejected. |
The checks fail loudly. A plugin that does not offer the capability you need, or that speaks a different protocol, is rejected and you never receive it, although its module and factory have already run by then:
lc.plugins.activate_plugin(chosen, required_capability="cost_model.tiered") PluginError: plugin 'acme_flat' does not provide capability 'cost_model.tiered' lc.plugins.activate_plugin(chosen, protocol_major=2) PluginError: plugin protocol major 1 is incompatible with required major 2 Configuration is checked before any plugin code runs, so a value that cannot be recorded stops the call before the import:
lc.plugins.activate_plugin(chosen, config={"table": object()}) MethodContractError: config must be a JSON-compatible mapping The descriptor
Every plugin describes itself with a PluginDescriptor. Lacuna validates its shape when it is built.
| Field | Meaning |
|---|---|
plugin_id | The plugin’s identifier. Must equal the entry-point name. |
protocol_version | A string of the form major.minor, such as "1.0". The major part is compared with protocol_major; the minor part is recorded. |
capabilities | A non-empty tuple of unique capability names. These are what required_capability is checked against. |
config_schema | A JSON-compatible mapping describing the plugin’s configuration. It stays on the descriptor and is not copied into the activation evidence. Lacuna does not validate config against it. |
method_versions | A mapping from method name to a positive integer version, so a result can name the exact method version used. |
required_dependencies | A tuple of unique package names the plugin needs. Recorded in the activation evidence; Lacuna does not check that they are installed. |
Recording the activation
The evidence of an activation names the plugin, where it came from, what it offers and how it was configured:
parameters = activated.evidence.metadata.parameters
print(parameters["plugin_id"], parameters["distribution"], parameters["distribution_version"])
print(parameters["protocol_version"], parameters["capabilities"])
print(parameters["config"])
print(parameters["trusted_in_process_code"])
print(activated.evidence.metadata.method) acme_flat acme-costs 0.3.0
1.0 ('cost_model.flat',)
{'bps': 4.5}
True
plugins.activate trusted_in_process_code is always True: it states that this evidence came from code that ran in your process. When a result depends on a plugin, keep this evidence with it. The standard audit recognises it, by its plugins.activate method name, as the optional plugin_provenance capability:
report = lc.standard_audit(results={"cost_plugin": activated.evidence}, scope="strategy")
for finding in report.findings:
if finding.code == "EVIDENCE_PLUGIN_PROVENANCE":
print(finding.state.value, finding.evidence["coverage_only"]) PASS True The PASS is coverage only: evidence of that kind was supplied. It does not review the plugin. The capability is optional in every audit scope, so leaving the evidence out gives NOT_APPLICABLE, not a failure. See Audits and reports for how evidence reaches an audit.
The evidence has limits you should know before you lean on it:
- It is an in-memory
AnalysisResult. Nothing stores it for you; you carry it, for example into an audit or a bundle. - The version is whatever the package’s metadata declares. Lacuna does not hash or inspect the plugin’s code, so the same version string can hide different code.
distributionanddistribution_versioncan beNonewhen the entry point comes from metadata that does not name a package.- It records one activation. Each call to
activate_pluginruns the factory again and returns a new implementation, with its own evidence.
What a plugin package declares
A plugin package needs a module with a factory, and an entry point in its pyproject.toml that names the factory, in the group for the kind of extension it offers:
[project]
name = "acme-costs"
version = "0.3.0"
dependencies = ["lacuna-quant>=0.14,<0.15"]
[project.entry-points."lacuna.cost_models.v1"]
acme_flat = "acme_flat_costs:create" The contract Lacuna checks is short:
| Piece | Requirement |
|---|---|
| Entry-point name | The plugin’s identity. Unique within the group, or callers must pass distribution. |
| Entry-point value | A module:attribute path resolving to a callable that takes one configuration mapping. |
| Return value | An object with a descriptor attribute that is a PluginDescriptor. |
descriptor.plugin_id | Equal to the entry-point name. |
descriptor.protocol_version | A major.minor string whose major matches what callers ask for. |
Pin the range of Lacuna versions you support in the package’s dependencies. The group names carry a protocol version, but the objects your implementation returns are Python code, and they are only as compatible as the Lacuna release they were written against.
The five groups, and what a plugin in each is meant to offer. The names state intent. Lacuna 0.14.3 attaches no behaviour to them beyond using them to look entry points up:
| Short name | Offers |
|---|---|
adapters | Readers for a data source or file format. |
audit_rules | Additional audit rules. |
cost_models | Trading-cost models. |
methods | Analytical methods. |
report_sections | Sections for rendered reports. |
Lacuna 0.14.3 defines the groups and the activation handshake above. It does not call anything on the implementation object itself. Nothing in the library takes an activated plugin and wires it into an audit, a cost study or a report. You receive the implementation and use it where it belongs, and Lacuna’s part is the discovery, the checks and the evidence.
The trust model
Activating a plugin runs its code with your permissions. activate_plugin is not a sandbox and does not isolate the plugin from your data, files, network or credentials.
| Stage | What Lacuna does |
|---|---|
| Discovery | Reads installed package metadata. Imports no plugin module and runs no plugin code. Safe to run anywhere. |
| Selection | Discovery plus a name match. Still imports nothing. |
| Activation | Imports the module and calls the factory, in your process. Records the result as evidence. |
| Everything else | Never. Lacuna does not discover or activate plugins on its own. Creating or verifying a reproducibility bundle does not activate any, and records plugins_activated as false. Neither does the installation diagnostic. |
Only Exception from the plugin’s import or factory is caught and wrapped. A SystemExit or KeyboardInterrupt raised by plugin code escapes unwrapped. Lacuna does not check what a plugin does after it returns. It does not validate config against config_schema, does not confirm that required_dependencies are installed, and does not look inside the implementation. The checks that run are the ones listed under activation. A plugin from a package you have not reviewed has the same power as any other code you import. Install plugins from sources you trust, pin their versions, and read the evidence.
To leave the environment as it was, remove the stand-in:
sys.path.remove(str(workdir))
sys.modules.pop("acme_flat_costs", None)
print(lc.plugins.discover_plugins()) () For every signature, see the lacuna.plugins API reference.