Errors
Lacuna's exception hierarchy, what raises each exception, the messages you will see, and how errors differ from findings.
Lacuna raises an exception when an input or a setting makes a result impossible, and returns a finding when the result is possible but weak. The first case needs you to change your input. The second case needs you to read the result. Keeping the two apart means a result that was returned was computed on input that passed the method’s contract.
All of Lacuna’s own exceptions derive from LacunaError and are exported from the top-level package.
Exception
└── LacunaError
├── ConfigurationError (also a ValueError)
├── DataContractError (also a ValueError)
├── MethodContractError (also a ValueError)
├── NativeExtensionError (also a RuntimeError)
├── ReportError (also a RuntimeError)
└── PluginError (also a RuntimeError) The tree is checked here rather than asserted:
import lacuna as lc
import numpy as np
import polars as pl
for cls in (
lc.ConfigurationError,
lc.DataContractError,
lc.MethodContractError,
lc.NativeExtensionError,
lc.ReportError,
lc.PluginError,
):
print(f"{cls.__name__:<22}", [base.__name__ for base in cls.__bases__]) ConfigurationError ['LacunaError', 'ValueError']
DataContractError ['LacunaError', 'ValueError']
MethodContractError ['LacunaError', 'ValueError']
NativeExtensionError ['LacunaError', 'RuntimeError']
ReportError ['LacunaError', 'RuntimeError']
PluginError ['LacunaError', 'RuntimeError'] Because the first three are also ValueError, except ValueError catches them. The last three are also RuntimeError, but that is not a sign that they only report environment problems. ReportError and PluginError are raised for bad arguments too: an unsupported report format, a reserved evidence name, a bundle path without the .lacuna suffix, an unknown plugin name. except ValueError does not catch those, so catch lc.LacunaError or the specific class.
Catching errors
except lc.LacunaError handles what Lacuna raises on purpose. It does not cover everything that bad input can cause: a wrong-typed argument or an input Polars cannot process raises a plain Python or Polars exception, as below describes. Catch the specific class when you handle a specific cause, and let the rest propagate:
rng = np.random.default_rng(3)
sessions = [f"2025-03-{d:02d}" for d in range(3, 9)]
instruments = ["A", "B", "C", "D"]
rows = [(s, i) for s in sessions for i in instruments]
prices = pl.DataFrame(
{
"time": [s for s, _ in rows],
"instrument": [i for _, i in rows],
"close": 100.0 * np.exp(np.cumsum(rng.normal(0.0, 0.01, (6, 4)), axis=0)).ravel(),
}
).with_columns(pl.col("time").str.to_date())
signal = prices.select("time", "instrument").with_columns(signal=pl.Series(rng.normal(size=24)))
labels = lc.labels.forward_returns(prices, horizon="1D")
try:
lc.signal.ic(pl.concat([signal, signal.head(1)]), labels)
except lc.DataContractError as error:
print("fix the data:", error) fix the data: signal contains 2 duplicate rows for logical key (time, instrument) Do not catch an error in order to continue with a result of your own. A DataContractError means the data cannot support the method as asked, and a fallback that proceeds anyway hides the thing Lacuna stopped you from doing.
DataContractError
The data you passed does not satisfy the contract of the method. It is raised before computation in most cases, and later for conditions that only show up during it, such as a non-finite bootstrap replicate or a zero-variance Sharpe sample. Its message names the column or the count. It covers the rules in Time and data: missing columns, key dtypes and their agreement, null keys, duplicate keys, infinite values, nulls under a "raise" policy, label intervals, availability times later than the rows they serve, and groups too small to estimate.
lc.signal.ic(pl.concat([signal, signal.head(1)]), labels) DataContractError: signal contains 2 duplicate rows for logical key (time, instrument) lc.signal.ic(signal.rename({"instrument": "ticker"}), labels) DataContractError: missing required columns: instrument lc.signal.ic(signal.with_columns(pl.col("signal").cast(pl.Float64) * float("inf")), labels) DataContractError: signal input contains 24 rows with positive or negative infinity lc.signal.ic(signal.with_columns(pl.col("time").cast(pl.Datetime("ns"))), labels) DataContractError: aligned semantic keys must use matching dtypes: time=Datetime(time_unit='ns', time_zone=None) vs observation_time=Date Other messages follow the same pattern, so the table gives only the shape of what you will meet.
| Message contains | Cause |
|---|---|
missing required columns | A column named by a parameter is not in the table. |
must use matching dtypes | Two tables or columns that must align have different types. |
contains null semantic keys | A null in a time, instrument or availability column. |
duplicate rows for logical key | Two rows share a key that must be unique. |
positive or negative infinity | An infinite value in a numeric input, under any missing-value policy. |
null or NaN values | A null or NaN under null_policy="raise" (or missing="raise"). |
available after observation time | A group or exposure timestamp later than the row it applies to. |
no aligned finite signal/label observations remain | Nothing is left after alignment and the missing-value policy. |
no groups contain the required | Every cross-section is smaller than min_observations. |
The experiment registry and fingerprinting also use DataContractError, for parameters they cannot record without ambiguity: a timezone-naive datetime, a NaN or infinity, a set, a callable, a mapping with a non-string key, or a mapping key that looks like a credential. The credential-looking keys are access_key, api_key, authorization, cookie, credential, password, secret and token, and any key ending in an underscore followed by one of these.
lc.experiment.fingerprint({"api_key": 1}, namespace="example") DataContractError: $.api_key looks credential-bearing and is not recorded MethodContractError
The method, or the way you configured it, is undefined: an unsupported option, a combination that does not make sense, or a number outside its range. The data may be perfectly valid.
lc.labels.forward_returns(prices, horizon="1W") MethodContractError: unsupported horizon '1W'; v0.1 uses trading-observation strings such as '5D' lc.labels.forward_returns(prices, horizon="1D", signal_time="close", entry="current_close") MethodContractError: a close-observed signal cannot use the same close; use entry='next_open' or entry='next_close' (horizons of at least 2D), or explicitly set allow_same_close=True lc.validation.bootstrap(np.arange(10.0), resamples=10) MethodContractError: resamples must be at least 100 for inferential output PurgedKFold and CombinatorialPurgedKFold check the types of their integer settings at construction, so a string, float, bool or NumPy integer is rejected here rather than failing later on a comparison:
lc.cv.PurgedKFold(n_splits="3") MethodContractError: PurgedKFold integer parameters have invalid types: n_splits The same exception covers a policy argument outside its allowed values (null_policy must be 'drop' or 'raise'), a negative seed passed to a method, conflicting parameters (pass either horizon or horizons, not both), and an unknown plugin group.
The distinction between this and DataContractError is whether the fix is in the data or in the call. If you are unsure which applies, the message tells you.
ConfigurationError
A runtime setting is invalid. Settings are the ones you set with lc.configure and lc.config, or with the LACUNA_NUM_THREADS and LACUNA_MEMORY_LIMIT environment variables.
Validation happens at different times. lc.configure and lc.config check only threads, seed and log_level when you call them. The memory_limit format, and whether the limit is large enough, are checked only when a method resolves its memory budget. Environment variables are read lazily, the first time the configuration is needed, so a bad LACUNA_NUM_THREADS surfaces then and not at import. Keys that are not settings are silently ignored.
lc.configure(threads=0) ConfigurationError: threads must be 'auto' or a positive integer with lc.config(memory_limit="100B"):
lc.validation.bootstrap(np.arange(50.0), seed=1, resamples=500) ConfigurationError: memory_limit cannot fit the required fixed output allocation (4000 bytes required, 100 bytes configured) A memory_limit that is not a valid size is accepted when you set it and rejected when a method first uses it:
with lc.config(memory_limit="abc") as cfg:
print(cfg.memory_limit) abc with lc.config(memory_limit="abc"):
lc.validation.bootstrap(np.arange(50.0), seed=1, resamples=500) ConfigurationError: memory_limit must be bytes or use B, KB, MB, GB, TB, KiB, MiB, GiB, or TiB A failed lc.configure leaves the current configuration as it was.
ReportError
Writing, rendering, reading or verifying a report or a reproducibility bundle failed. It is a RuntimeError, not a ValueError; most of its causes involve a file or an archive. It is raised for an unsupported format, a destination that already exists, an evidence name that is reserved, and every way a bundle can fail verification.
mine = lc.AnalysisResult(metadata=lc.ResultMetadata(method="custom.example"))
report = lc.AuditReport(result=mine)
path = report.write("report.json")
try:
report.write("report.json")
except lc.ReportError as error:
print(str(error).split(":")[0]) refusing to overwrite existing report report.write("report.pdf") ReportError: report format must be json, md/markdown, or html Files are never replaced silently; pass overwrite=True when you mean to. Reading a bundle is defensive: lc.verify_bundle raises ReportError for a file that is not a valid archive, for an unsafe or non-canonical member path, for a digest or size that does not match the manifest, and for a manifest that departs from the version-1 contract. Reproducibility bundles covers the contract.
lc.verify_bundle("missing.lacuna") ReportError: cannot read bundle: missing.lacuna PluginError
Selecting or activating a plugin failed. Discovery imports nothing, so lc.plugins.discover_plugins does not raise this. select_plugin raises it when no installed plugin has the name, or when more than one does and you did not name a distribution. activate_plugin raises it when the entry point cannot be imported or is not callable, when the factory raises, when the activated object has no valid descriptor, when the descriptor’s identifier does not match the entry-point name, when the protocol major version is incompatible, and when a required capability is missing.
lc.plugins.select_plugin("nope", group="methods") PluginError: plugin 'nope' is not installed in group 'methods' Activation executes the plugin’s code in your process, and its exceptions are chained under PluginError, so error.__cause__ holds the original.
Missing optional dependencies
The core install needs only NumPy and Polars. These two features raise a Lacuna error that names the extra to install, and the class depends on the feature.
| Feature | Needs | Raises |
|---|---|---|
lc.signal.fit_decay | SciPy, from lacuna-quant[statistics] | MethodContractError |
The Plotly HTML renderer (renderer="plotly") | Jinja2 and Plotly, from lacuna-quant[report] | ReportError |
NativeExtensionError
Reserved for a required native capability that is unavailable. The class is defined and exported, but in this release no Lacuna function raises it. The methods that take use_native fall back to a Python implementation when the compiled extension cannot be imported, and record which backend ran in the result’s parameters, so you are unlikely to meet it in normal use.
Exceptions that are not LacunaError
Some failures are ordinary Python exceptions, and it is worth knowing which.
| Exception | Raised by |
|---|---|
ValueError, TypeError | The constructors and parsers of value objects: AnalysisResult, ResultMetadata, Finding, from_json and from_dict, audit profiles and rules, installation diagnostics. These reject a malformed object, not a bad analysis input. Bundle manifests are the exception to the pattern: invalid content raises ReportError, and TypeError is for wrong argument types only. |
TypeError, AttributeError | Wrong-typed scalar arguments that a method does not validate first (PurgedKFold and CombinatorialPurgedKFold do, and raise MethodContractError). min_observations="a" or resamples="x" fail on a comparison ('<' not supported between instances of 'str' and 'int'), lc.configure(threads="four") and seed="a" the same way, a float seed passed to bootstrap fails with seed must be integer from NumPy, and lc.configure(log_level=5) raises AttributeError. |
| Polars exceptions | Input that Polars cannot process and Lacuna’s own checks do not reject first, for example a Decimal price column in forward_returns (InvalidOperationError) or a dictionary of unequal-length columns (ShapeError). Both are subclasses of polars.exceptions.PolarsError. |
sqlite3.DatabaseError | ExperimentRegistry opened on a file that is not a SQLite database. |
KeyError | AnalysisResult.table(name) for a table that does not exist. |
TypeError | Python itself, for a missing or unexpected argument. |
RuntimeError | Internal consistency checks, such as a corrupt experiment-registry payload. These indicate a bug or a damaged store, not something to handle. |
lc.Finding(code="", title="t", message="m", state=lc.FindingState.PASS) ValueError: code, title, and message must not be empty lc.ResultMetadata(method="custom.example", seed=-1) ValueError: seed must be non-negative An exception raised inside your own code is not wrapped. For example, one raised by a rule you pass to an audit propagates as it is and does not become a FAIL finding.
Note the three different ways a negative seed can be rejected: ValueError in a ResultMetadata, ConfigurationError in lc.configure(seed=-1), and MethodContractError when passed to a method. They fail at different layers, and the class says which.
Exceptions from your own functions
Some methods call a function you supply once per parameter setting, window or scenario: lc.validation.parameter_surface, lc.robustness.continuous_perturbation, subperiod_analysis and universe_perturbation. With the default failure_policy="record", an exception from your function is not raised. The point is recorded as failed, with the exception’s class name in error_category, and the analysis continues. Only KeyboardInterrupt and SystemExit propagate.
def evaluate(params):
if params["a"] == 2:
raise RuntimeError("boom")
metadata = lc.ResultMetadata(method="custom.evaluate")
return lc.AnalysisResult(metadata=metadata, metrics={"score": float(params["a"])})
surface = lc.validation.parameter_surface(
evaluate, grid={"a": [1, 2, 3]}, objective="score", evaluator_name="evaluate", sample_id="s", code_id="c"
)
print([(row["a"], row["status"], row["error_category"]) for row in surface.table("parameter_surface")]) [(1, 'completed', None), (2, 'failed', 'RuntimeError'), (3, 'completed', None)] Pass failure_policy="raise" to stop at the first failure instead. The exception is then your function’s own:
lc.validation.parameter_surface(
evaluate,
grid={"a": [1, 2, 3]},
objective="score",
evaluator_name="evaluate",
sample_id="s",
code_id="c",
failure_policy="raise",
) RuntimeError: boom On the command line
The lacuna command catches LacunaError and OSError from its subcommands, and Polars errors from signal and bench. It prints lacuna: error: <message> to standard error and exits with code 1. Exit code 3 is reserved for --fail-on (see the CLI reference).
Errors and findings
An exception means no result. A finding means a result, with a statement about how far to trust it. A method chooses between them by one test: can the question be answered on this input at all?
| Situation | Outcome |
|---|---|
Duplicate (time, instrument) rows | DataContractError. No cross-section is defined. |
| Few cross-sections behind an IC summary | WARN finding (IC_PERIOD_SUPPORT_LOW). The estimate exists and is thin. |
| A bootstrap given fewer than two finite values | DataContractError. There is nothing to resample. |
price_adjustment left undeclared | UNKNOWN finding. The labels exist; their basis is unproven. |
| A group timestamp later than its row | DataContractError in lc.signal.ic. In lc.regime.regime_analysis, a FAIL finding. |
| An unsupported option value | MethodContractError. |
| Evidence that does not apply to the study | NOT_APPLICABLE finding. |
A few methods let you choose. Their policy parameters (null_policy, small_group_policy, unmatched, overlap_policy, failure_policy) switch a condition between raising and being recorded or dropped, and the choice is stored in the result. Time and data lists them, and Results explains the states.
The audit adds a third outcome. An audit rule whose required evidence is not present reports UNKNOWN (or NOT_APPLICABLE when the rule does not apply), which is a finding rather than an exception. Audits and reports shows how to supply the evidence.
The exception classes have generated entries in the lacuna API reference.