Experiments and fingerprints
Record every attempt, including failures and retries, keep selections tied to the full set of candidates, and fingerprint data, code and parameters so a result can be identified later.
A backtest that survives was usually picked from many that did not. If only the winner is written down, every statistic computed on it is optimistic, and nothing in the result says by how much. The size of the family it was chosen from is what a multiple-testing correction needs, and the discarded variants are what a reviewer asks about first.
ExperimentRegistry is a local, append-only record of that history. It stores each attempt, including the ones that failed, and each selection decision with the full set of candidates it was made from. It computes no statistics itself. It supplies the trial list that the inference functions and the audit need, and it records identity with fingerprints so two results can be told apart.
A first registry
A registry belongs to one named experiment. Give it a path and it persists in a SQLite file; leave path out and it lives in memory and disappears when the registry closes.
import lacuna as lc
import numpy as np
import polars as pl
from lacuna.experiment import ExperimentRegistry, canonical_json, fingerprint
prices = pl.DataFrame({"time": [1, 2, 3], "instrument": ["A", "A", "A"], "close": [10.0, 10.5, 10.2]})
data_id = fingerprint(prices, namespace="prices")
code_id = fingerprint({"git_commit": "3f2c9ab", "module": "momentum"}, namespace="code")
registry = ExperimentRegistry("momentum", path="experiments.db")
rng = np.random.default_rng(3)
def record_trial(lookback, p_value):
return registry.record(
parameters={"lookback": lookback},
metric=p_value,
metric_name="p_value",
method="momentum.ic_test",
data_fingerprint=data_id,
code_fingerprint=code_id,
)
for lookback in (5, 10, 20, 40, 60):
record_trial(lookback, float(rng.uniform(0.001, 0.2)))
failed = registry.record(
parameters={"lookback": 90},
status="failed",
error_category="ValueError",
method="momentum.ic_test",
data_fingerprint=data_id,
code_fingerprint=code_id,
)
retry = record_trial(90, 0.4)
print(
pl.DataFrame(
[
{
"sequence": a.sequence,
"status": a.status.value,
"lookback": a.parameters["lookback"],
"p_value": a.metric_value,
}
for a in registry.attempts()
]
)
)
print(failed.trial_id == retry.trial_id) shape: (7, 4)
┌──────────┬───────────┬──────────┬──────────┐
│ sequence ┆ status ┆ lookback ┆ p_value │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ str ┆ i64 ┆ f64 │
╞══════════╪═══════════╪══════════╪══════════╡
│ 1 ┆ completed ┆ 5 ┆ 0.018044 │
│ 2 ┆ completed ┆ 10 ┆ 0.048125 │
│ 3 ┆ completed ┆ 20 ┆ 0.160454 │
│ 4 ┆ completed ┆ 40 ┆ 0.11685 │
│ 5 ┆ completed ┆ 60 ┆ 0.019732 │
│ 6 ┆ failed ┆ 90 ┆ null │
│ 7 ┆ completed ┆ 90 ┆ 0.4 │
└──────────┴───────────┴──────────┴──────────┘
True Seven attempts, six trials. The failed attempt for lookback 90 and its retry share one trial, because a trial is identified by what it evaluates and not by how many times you tried. The failure stays in the history. Retrying does not erase it.
Attempts and trials
An attempt is one execution with a terminal status. A trial is the thing being evaluated: a parameter set, with a method, a method version, and the data and code identities. Every attempt belongs to the trial whose identity it matches.
The trial identifier is derived, not assigned: trial_ followed by the first 32 hex digits of a fingerprint over the registry’s family and name, the canonical parameters, the method, the method version and both fingerprints. The same inputs give the same identifier on every machine. Change the data fingerprint, the code fingerprint or any parameter and it is a different trial. Identical records are not merged: recording the same trial twice gives two attempts and one trial.
| Status | Meaning | Constraints |
|---|---|---|
completed | The evaluation finished and may carry a metric. | error_category must be unset. |
failed | The evaluation raised or was rejected. | error_category is required. No metric. |
cancelled | The evaluation was abandoned. | No metric. |
record returns an immutable AttemptRecord with the fields below. parameters and metadata are frozen, and anything credential-like in them is refused (see canonical JSON).
| Field | Meaning |
|---|---|
sequence | A strictly increasing integer assigned by the registry. This, not the timestamp, orders attempts. |
attempt_id | Unique per attempt. attempt_ plus a random UUID unless you supply one. |
trial_id, family, experiment | The trial identity, the registry’s family and the registry’s name. |
created_at | A timezone-aware UTC time. Now, unless you supply one. |
status, error_category | The terminal status and, for failures, a category such as an exception name. Store a category, not a message or traceback. |
parameters | The canonical parameter mapping. |
metric_name, metric_value | One finite float and its name, for completed attempts. Both are None when no metric was given, whatever metric_name you passed. |
method, method_version | What was evaluated. user.evaluation and 1 by default. |
data_fingerprint, code_fingerprint, result_fingerprint | Identities you supply. Optional. |
supersedes_attempt_id, supersedes_reason | Set together when this attempt corrects an earlier one. |
metadata | A canonical mapping for anything else worth keeping. |
Corrections
Completed attempts are never edited. To correct a mistake, record a new attempt for the same trial that names the attempt it supersedes and why. Both stay in the history:
first = registry.attempts()[0]
corrected = registry.record(
parameters=dict(first.parameters),
metric=0.21,
metric_name="p_value",
method="momentum.ic_test",
data_fingerprint=data_id,
code_fingerprint=code_id,
supersedes_attempt_id=first.attempt_id,
supersedes_reason="p-value recomputed after fixing the purge window",
)
print(len(registry.attempts()), corrected.supersedes_attempt_id == first.attempt_id) 8 True A correction must reference an existing attempt of the same trial. The link is informational. Superseded attempts still count in attempt_count and in the completed and failed counts, an attempt can be superseded more than once, and consumers that need one value per trial, such as multiple testing below, take the latest attempt by sequence, whether or not it is marked as a correction. Recording the same trial again with a different metric overrides the earlier value in the same way.
Identity
Lacuna cannot see your data or your code, so data_fingerprint and code_fingerprint are strings you provide. Use fingerprint() on a frame or on a mapping that names the code version, as above, or any stable identifier you trust. An attempt lacking either one is counted in identity_incomplete_attempts and raises EXPERIMENT_IDENTITY_INCOMPLETE in the snapshot: without both, two attempts that look identical may not have run on the same data.
Selection
Choosing a winner is a decision, and the decision is evidence. record_selection stores it with the complete set of trials that were eligible, so the winner is always read against its competitors:
trial_ids = sorted({a.trial_id for a in registry.attempts()})
latest = {a.trial_id: a for a in registry.attempts() if a.metric_value is not None}
best = min(latest.values(), key=lambda a: a.metric_value)
selection = registry.record_selection(
eligible_trial_ids=trial_ids,
selected_trial_ids=[best.trial_id],
metric="p_value",
direction="minimize",
tie_breaking="lowest trial_id",
used_holdout=False,
actor="research-lead",
)
print(selection.metric, selection.direction, len(selection.eligible_trial_ids), len(selection.selected_trial_ids)) p_value minimize 6 1 The registry checks that the eligible set is non-empty and unique, that every eligible trial has at least one recorded attempt, that selected trials are a subset of the eligible ones, and that any exclusion_reasons name eligible but unselected trials. It does not check that the eligible set covers every recorded trial, so a subset is accepted, and it accepts a selected trial whose attempts all failed. It does not check that the selection followed the criterion: metric, direction, tie_breaking and used_holdout are your declaration of how the choice was made, recorded as given.
registry.record_selection(
eligible_trial_ids=[best.trial_id],
selected_trial_ids=["trial_that_was_never_recorded"],
metric="p_value",
) MethodContractError: selected trials must belong to the eligible set used_holdout=True is how you record that a holdout sample informed the choice, which a reviewer will want to know. Nothing computes from a selection: multiple_testing and the audit ignore it, and only the snapshot’s selection_count and the EXPERIMENT_SELECTION_MISSING finding read it.
Storage
With path=None the registry is an in-memory SQLite database. With a path it is a file. The parent directory must already exist, and the file is created on first use. The file is opened in write-ahead-log mode, so SQLite keeps -wal and -shm files beside it while a registry is open. Writes run in transactions with a five-second busy timeout, and each call holds an internal lock, so one registry object can be shared by threads. In testing, several threads and several processes writing to one file all succeeded, but heavy contention can outlast the busy timeout and raise sqlite3.OperationalError.
The registry stamps its schema version, name and family into the file. Reopening a file with a different name or family is an error, which stops two experiments from writing into one history by accident.
registry.close()
registry = ExperimentRegistry("momentum", path="experiments.db")
print(len(registry.attempts()), len(registry.selections())) 8 1 ExperimentRegistry("reversal", path="experiments.db") DataContractError: registry metadata mismatch for name: expected 'reversal' close() releases the connection and is safe to call twice. A registry also works as a context manager. Using a closed registry raises sqlite3.ProgrammingError.
Append-only is a property of the Python API: there is no method that updates or deletes a row. The SQLite file itself is an ordinary database, and anyone with write access can edit it with any SQLite client. The registry does not detect that. To make later edits visible, store the snapshot’s input_fingerprint (see below) somewhere the file’s writers cannot reach, such as a commit message or a CI log.
Snapshots
registry.to_result() returns an immutable AnalysisResult with method experiment.registry_snapshot. It is what the audit tools consume and what a bundle stores.
snapshot = registry.to_result()
print(snapshot.metrics)
for finding in snapshot.findings:
print(finding.state.value, finding.code)
print(snapshot.warnings[0])
print(len(snapshot.table("attempts")), len(snapshot.table("selections"))) {'attempt_count': 8, 'trial_count': 6, 'completed_attempts': 7, 'failed_attempts': 1, 'cancelled_attempts': 0, 'selection_count': 1, 'identity_incomplete_attempts': 0}
WARN EXPERIMENT_FAILED_ATTEMPTS
A local registry cannot prove that unrecorded external trials do not exist.
8 1 The metrics count attempts, trials (distinct trial identifiers), completed, failed and cancelled attempts, selections and attempts with incomplete identity. The tables attempts and selections hold every record in sequence order, and metadata.input_fingerprint is a fingerprint of both. The same history always gives the same fingerprint.
A snapshot raises up to three findings:
| Code | State | Raised when |
|---|---|---|
EXPERIMENT_FAILED_ATTEMPTS | WARN | Any attempt failed. It stays, even after a successful retry, because failures are part of the search. |
EXPERIMENT_IDENTITY_INCOMPLETE | UNKNOWN | Any attempt lacks a data or code fingerprint. |
EXPERIMENT_SELECTION_MISSING | UNKNOWN | Attempts exist and no selection was recorded. |
The snapshot always carries the warning that a local registry cannot prove that trials you never recorded do not exist. Nothing can: the registry records what you tell it. Record every attempt, including the ones you expect to discard, and from the start, because a history reconstructed afterward is a different claim.
Using the registry elsewhere
Multiple testing
lc.validation.multiple_testing accepts a registry directly. It reads the p-value of each trial, taking the latest attempt per trial by sequence, and adjusts the whole family, so the correction sees every trial you ran instead of the ones you remember.
adjusted = lc.validation.multiple_testing(registry, method="holm", alpha=0.05)
print(adjusted.metrics["trial_count"], adjusted.metrics["rejected_count"])
print(pl.DataFrame(adjusted.table("adjusted_p_values")).select("rank", "p_value", "adjusted_p_value", "rejected").head(3)) 6 0
shape: (3, 4)
┌──────┬──────────┬──────────────────┬──────────┐
│ rank ┆ p_value ┆ adjusted_p_value ┆ rejected │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ f64 ┆ f64 ┆ bool │
╞══════╪══════════╪══════════════════╪══════════╡
│ 6 ┆ 0.4 ┆ 0.481361 ┆ false │
│ 5 ┆ 0.21 ┆ 0.481361 ┆ false │
│ 4 ┆ 0.160454 ┆ 0.481361 ┆ false │
└──────┴──────────┴──────────────────┴──────────┘ Every trial must have a latest attempt that completed with a metric named p_value (or whatever you pass as p_value=). A trial whose latest attempt failed, was cancelled, or has a different or missing metric raises DataContractError instead of being skipped. Silently dropping failures would shrink the family, which is the bias this function exists to prevent:
registry.record(
parameters={"lookback": 120},
status="failed",
error_category="ValueError",
method="momentum.ic_test",
data_fingerprint=data_id,
code_fingerprint=code_id,
)
lc.validation.multiple_testing(registry) DataContractError: registry has 1 trials without a current completed 'p_value' metric Retry the trial and the family is complete again, now with the extra trial in it:
record_trial(120, 0.35)
adjusted = lc.validation.multiple_testing(registry, method="holm")
print(adjusted.metrics["trial_count"]) 7 The metric is also validated as a p-value. A recorded value outside [0, 1] raises, exactly as it does for array input, and null_policy is checked the same way (a registry cannot hold a non-finite metric, so it has nothing to drop):
misrecorded = ExperimentRegistry("range-check")
misrecorded.record(parameters={"lookback": 5}, metric=1.5, metric_name="p_value")
lc.validation.multiple_testing(misrecorded) DataContractError: multiple testing contains 1 p-values outside [0, 1] Inference covers choosing among the corrections.
Search functions
lc.validation.parameter_surface, lc.robustness.continuous_perturbation, lc.robustness.subperiod_analysis and lc.robustness.universe_perturbation take an optional registry=. Each evaluation they run is recorded as an attempt, so a sweep leaves its trial history behind without extra code. Failures are recorded only under the default failure_policy="record": with "raise" the exception propagates before anything is recorded. Draws that continuous_perturbation rejects for bounds or a constraint are never evaluated, so they are not recorded either.
The audit
The audit’s TRIAL_HISTORY_AVAILABLE check does not read the registry. It reads one declared policy, trial_history_available, and nothing connects the two: a registry snapshot passed as evidence leaves the finding UNKNOWN, and the policy alone passes it. Setting the policy is your assertion that the history is complete, and any value other than True warns. On the command line it is lacuna signal --trial-history-available or --no-trial-history-available, the same assertion. Attach the snapshot so a reviewer can see what the assertion rests on.
snapshot = registry.to_result()
state = lambda report: next(f.state.value for f in report.findings if f.code == "TRIAL_HISTORY_AVAILABLE")
evidence_only = lc.audit(results={"experiments": snapshot})
declared = lc.audit(results={"experiments": snapshot}, policies={"trial_history_available": True})
print(state(evidence_only), state(declared)) UNKNOWN PASS The standardized audit does read the snapshot, by method. A result whose method starts with experiment. satisfies the experiment_lineage capability, and a validation.multiple_testing.* result satisfies multiple_testing:
standard = lc.standard_audit(
results={"experiments": snapshot, "multiple_testing": adjusted}, scope="signal"
)
present = [row["capability"] for row in standard.table("evidence_requirements") if row["present"]]
print(present) ['experiment_lineage', 'multiple_testing'] For SignalStudy.audit, pass the same policy in policies= and the snapshot in additional_evidence=. See Supplying evidence.
Canonical JSON and fingerprints
Identity is only useful if the same value always produces the same bytes. canonical_json defines those bytes, and fingerprint hashes them.
print(canonical_json({"b": [1, 2.0, -0.0], "a": None, "name": "naïve"}))
print(fingerprint({"lookback": 20}, namespace="demo"))
print(fingerprint({"lookback": 20}, namespace="other")) {"a":null,"b":[1,2.0,0.0],"name":"naïve"}
sha256:c14n-v1:a6afbc7b02acc4898ee87f3a17135e482d00d1b505a7b002b9bbdb32bb86a11b
sha256:c14n-v1:28de6e7a1d0a92b10fbc94d7bcd422c57f494cb5ac81d3eeedb9f5511eb3a04f The canonical form is compact UTF-8 JSON with sorted keys. It is strict, and refuses what could not be reproduced:
| Input | Canonical behaviour |
|---|---|
| Mapping keys | Must be strings. Sorted by code point. |
| Floats | Finite only. -0.0 becomes 0.0. Integers stay integers: 1 and 1.0 are different. |
NaN, infinities | Rejected with DataContractError. |
| Datetimes | Must be timezone-aware. Written in UTC with a Z suffix. A naive datetime is rejected. |
| Dates | ISO 8601 text. |
| Enums | Their value. |
| Lists, tuples | Arrays. The two are not distinguished. |
| Sets, callables, other objects | Rejected: a set has no order, and a callable has no reproducible content. |
| Keys that look like credentials | Rejected, so secrets cannot enter the history by accident. |
A key looks like a credential when, compared case-insensitively with hyphens read as underscores, it equals or ends in _ plus one of access_key, api_key, authorization, cookie, credential, password, secret or token. Only keys are checked, not values.
canonical_json({"broker": "paper", "api_key": "not-a-real-key"}) DataContractError: $.api_key looks credential-bearing and is not recorded fingerprint(value, namespace=...) returns sha256:c14n-v1: followed by 64 hex digits. The digest covers a header with the canonicalization version and the namespace, then the canonical JSON. The namespace is mandatory, a non-empty string without surrounding whitespace, so the same value fingerprinted for two purposes, such as "prices" and "code", cannot collide.
fingerprint also accepts what canonical_json does not: NumPy arrays, Polars Series and DataFrames, which are hashed in bounded batches instead of being materialized as one string. The digest equals that of the equivalent nested lists, so an array and the list it holds have the same fingerprint. A frame is read as a list of row records, which has two consequences: column order does not matter, and row order does. The same checks apply to what a frame holds: non-finite values raise, and so do credential-like column names and naive datetime columns.
frame = pl.DataFrame({"a": [1, 2], "b": [3.0, 4.0]})
print(fingerprint(frame, namespace="x") == fingerprint(frame.select("b", "a"), namespace="x"))
print(fingerprint(frame, namespace="x") == fingerprint(frame.reverse(), namespace="x"))
print(fingerprint(np.array([1.0, 2.0]), namespace="x") == fingerprint([1.0, 2.0], namespace="x")) True
False
True A fingerprint identifies content. It does not authenticate who produced it, and it is only as informative as what you feed it. A hash of a frame says nothing about the query that built the frame.
Versions
Versions say which rules produced an identity. Where they are recorded differs:
| Constant | Value | Identifies |
|---|---|---|
lacuna.experiment.CANONICALIZATION_VERSION | 1 | The canonical JSON and fingerprint rules. Every fingerprint() result carries it as the c14n-v1 prefix, and snapshots record it in their parameters. Trial ids keep only a truncated digest without the prefix, and attempt and selection ids are random. |
lacuna.experiment.REGISTRY_SCHEMA_VERSION | 1 | The registry’s SQLite layout. It is the only version the file itself records (with the name and family). |
lacuna.BUNDLE_VERSION | 1 | The bundle format. |
print(lc.experiment.CANONICALIZATION_VERSION, lc.experiment.REGISTRY_SCHEMA_VERSION, lc.BUNDLE_VERSION)
print(snapshot.metadata.parameters["canonicalization_version"], snapshot.metadata.parameters["schema_version"]) 1 1 1
1 1 A change to the canonical form would be a new version with a new prefix, so fingerprints made today stay comparable only with other c14n-v1 fingerprints, including the ones you pass in as data_fingerprint and code_fingerprint. Each snapshot records the versions it used.
Parameters
| Parameter | Default | Meaning |
|---|---|---|
name | required | The experiment’s name. Non-empty, no surrounding whitespace. Part of every trial identity, and checked when a file is reopened. |
path | None | A SQLite file. None keeps the registry in memory. The parent directory must exist. |
family | None | The group of related experiments that a multiple-testing correction should treat as one set. Defaults to name. Also part of every trial identity. |
| Parameter | Default | Meaning |
|---|---|---|
parameters | required | The trial’s parameter mapping. Canonicalized, so non-finite numbers, sets, callables and credential-like keys are rejected. |
metric | None | A finite float for a completed attempt. Not allowed for failed or cancelled attempts. |
metric_name | "objective" | The metric’s name. Set it to "p_value" for multiple_testing. |
status | "completed" | "completed", "failed" or "cancelled". |
method | "user.evaluation" | The evaluator’s name. Part of the trial identity. |
method_version | 1 | Bump it when the evaluator’s logic changes, so old attempts are not conflated with new ones. |
data_fingerprint | None | The data’s identity. Part of the trial identity. |
code_fingerprint | None | The code’s identity. Part of the trial identity. |
result_fingerprint | None | The result’s identity, for example its input_fingerprint. |
error_category | None | Required for "failed", forbidden for "completed". |
supersedes_attempt_id | None | The earlier attempt this one corrects. Pass with supersedes_reason. |
supersedes_reason | None | Why the earlier attempt is superseded. Non-empty. |
metadata | None | Extra canonical context. Not part of the trial identity. |
created_at | None | A timezone-aware time. Defaults to now in UTC. |
attempt_id | None | A unique identifier. Generated when omitted. A duplicate raises DataContractError. |
| Parameter | Default | Meaning |
|---|---|---|
eligible_trial_ids | required | Every trial that was a candidate. Non-empty, unique, each with a recorded attempt. |
selected_trial_ids | required | The chosen trials. A non-empty subset of the eligible ones. |
metric | required | The criterion the choice used, as a name. |
direction | "maximize" | "maximize" or "minimize". |
tie_breaking | "trial_id" | How ties were resolved, as a description. |
used_holdout | False | Whether a holdout sample informed the choice. |
actor | None | Who or what made the decision. |
exclusion_reasons | None | A mapping from eligible, unselected trials to the reason each was excluded. |
created_at | None | A timezone-aware time. Defaults to now in UTC. |
selection_id | None | A unique identifier. Generated when omitted. |
| Parameter | Default | Meaning |
|---|---|---|
value | required | Anything canonical_json accepts, or a NumPy array, Polars Series or DataFrame. |
namespace | required | What the fingerprint is for. Mixed into the digest. |
| Parameter | Default | Meaning |
|---|---|---|
value | required | A JSON-compatible value, with the restrictions above. Returns the canonical text. |
The full signatures are in the lacuna.experiment API reference.