Skip to Content

Reproducibility bundles

Package an audit, its evidence and its environment into one checksummed archive, and detect later corruption or careless edits. A bundle checks integrity only: it cannot prove the files are the originals or who made them.

A report is only as useful as your ability to say, months later, exactly which evidence produced it. A reproducibility bundle freezes that: one .lacuna file holding the audit, the evidence behind it, the configuration and the environment, with a SHA-256 digest for every member except the manifest.

A bundle makes a narrow claim, and the page is organized around it. Verification checks every member against digests stored inside the same archive, without running any of them. That detects accidental corruption, and edits made without rebuilding the manifest. It does not show that the files are the originals, because anyone who can change a file can change its digest too. It does not prove who wrote the archive, and the bundle does not contain the data or the code needed to recompute the result. Integrity versus authenticity spells out the difference.

Create a bundle

import json
import zipfile
from datetime import date, timedelta

import lacuna as lc
import numpy as np
import polars as pl

rng = np.random.default_rng(1)
n_sessions, n_instruments = 60, 20
calendar = (date(2024, 1, 1) + timedelta(days=k) for k in range(120))
sessions = [day for day in calendar if day.weekday() < 5][:n_sessions]
instruments = [f"S{i:02d}" for i in range(n_instruments)]

signal_values = rng.normal(size=(n_sessions, n_instruments))
returns = rng.normal(scale=0.02, size=(n_sessions, n_instruments))
returns[1:] += 0.004 * signal_values[:-1]
close = 100 * np.cumprod(1 + returns, axis=0)

rows = [
    (day, name, close[i, j], signal_values[i, j])
    for i, day in enumerate(sessions)
    for j, name in enumerate(instruments)
]
panel = pl.DataFrame(rows, schema=["time", "instrument", "close", "signal"], orient="row")
prices = panel.select("time", "instrument", "close")
signal = panel.select("time", "instrument", "signal")

study = lc.SignalStudy(
    signal=signal,
    prices=prices,
    horizons=("1D", "5D"),
    signal_observed_at="open",
    entry="current_close",
    price_adjustment="total_return_adjusted",
)
report = study.audit(bootstrap_resamples=200, seed=1)

context = dict(
    provenance={
        "data_source": "synthetic panel, seed 1",
        "export_url": "https://analyst:[email protected]/export?signature=dummy",
        "input_file": "/home/analyst/panel.parquet",
    },
    invocation={"command": "python study.py", "api_key": "dummy-key"},
)
path = report.bundle("study.lacuna", **context)
print(path)
study.lacuna

AuditReport.bundle writes the archive and returns its path. The path must end in .lacuna, and an existing file is never replaced unless you pass overwrite=True. create_bundle enforces the limits that verification checks: at most 256 members, 16 MiB per member and 64 MiB in total and for the archive. The provenance and invocation mappings here carry a URL with credentials, an absolute path and a credential-looking key on purpose, to show what happens to them in What is left out.

What is inside

A bundle is a ZIP archive, and each member has a role:

MemberRoleContents
manifest.jsonnone: it declares the restFormat, version, producer, report identity, a digest of the artifact list, and one entry per member.
report/audit.jsoncanonical_reportThe audit result in canonical JSON. This is the record; the other report files are views of it.
report/audit.mdrendered_reportThe Markdown rendering.
report/audit.htmlrendered_reportThe core HTML rendering.
evidence/<name>.jsonevidenceOne member per evidence result: every table, metric and finding.
metadata/configuration.jsonconfigurationThe configuration= mapping you pass; by default Lacuna’s runtime settings (cache_dir, log_level, memory_limit, seed, threads).
metadata/environment.jsonenvironmentVersions of Lacuna, NumPy and Polars, the Python implementation and version, the operating system and machine, and whether the native core is available.
metadata/provenance.jsonprovenanceOnly when you pass provenance=.
metadata/invocation.jsoninvocationOnly when you pass invocation=.
metadata/redactions.jsonredaction_logOnly when something was redacted.
verification = lc.verify_bundle(path)
for artifact in verification.manifest.artifacts:
    print(f"{artifact.role:<17} {artifact.path}")
evidence          evidence/bootstrap.json
evidence          evidence/decay.json
evidence          evidence/ic.json
evidence          evidence/labels.json
evidence          evidence/quantiles.json
evidence          evidence/turnover.json
configuration     metadata/configuration.json
environment       metadata/environment.json
invocation        metadata/invocation.json
provenance        metadata/provenance.json
redaction_log     metadata/redactions.json
rendered_report   report/audit.html
canonical_report  report/audit.json
rendered_report   report/audit.md

The evidence members come from the report. SignalStudy.audit retains its evidence (labels, IC, quantiles, turnover, decay, the bootstrap, and a split if you passed one), so it is bundled by default. A report from lc.audit or lc.standard_audit retains none, so pass them explicitly:

standard = lc.standard_audit(results=dict(report.evidence), scope="signal")
bare = standard.bundle("standard-bare.lacuna")
full = standard.bundle("standard.lacuna", evidence=dict(report.evidence))

def evidence_members(bundle_path):
    verified = lc.verify_bundle(bundle_path)
    return [a.path for a in verified.manifest.artifacts if a.role == "evidence"]

print(len(evidence_members(bare)), len(evidence_members(full)))
0 6

Evidence names must match [a-z][a-z0-9_-]{0,63} and become file names, so they cannot carry a path.

What is left out

Source data is not included. The prices, signals and label frames you analysed stay where they are: the manifest records source_data: not_included_automatically. What is included is the evidence results, which are derived summaries such as IC by period, quantile returns and attrition counts. Check any evidence you attach yourself. A table can carry identifiers if the method that produced it recorded them.

Code is not included either, and nothing in a bundle is executable. The manifest records executable_code: false and plugins_activated: false, and verification rejects any member with executable permissions. Lacuna never imports, unpickles or runs a bundle’s content.

Secrets are handled in two different ways, depending on where they appear.

The mappings you pass as configuration=, provenance= and invocation= are redacted. Lacuna cannot know what they hold, so it rewrites what looks dangerous and records each change:

FoundBecomesReason in the log
A key that looks like a credential: it equals or ends in _ plus access_key, api_key, authorization, cookie, credential, password, secret or token.The key <key>_redacted with the value <redacted>.credential_key
A string that is an http, https, ftp, ftps, gs or s3 URL with credentials, a query or a fragment.The same URL without them.url_credentials_or_query
A string that is an absolute POSIX or Windows path.<absolute-path>/ plus the file name.absolute_path
with zipfile.ZipFile(path) as archive:
    print(json.loads(archive.read("metadata/provenance.json")))
    print(json.loads(archive.read("metadata/invocation.json")))
    for entry in json.loads(archive.read("metadata/redactions.json"))["redactions"]:
        print(entry)
{'data_source': 'synthetic panel, seed 1', 'export_url': 'https://example.com/export', 'input_file': '<absolute-path>/panel.parquet'}
{'api_key_redacted': '<redacted>', 'command': 'python study.py'}
{'artifact': 'metadata/provenance.json', 'path': '$.export_url', 'reason': 'url_credentials_or_query'}
{'artifact': 'metadata/provenance.json', 'path': '$.input_file', 'reason': 'absolute_path'}
{'artifact': 'metadata/invocation.json', 'path': '$.api_key', 'reason': 'credential_key'}

Redaction looks only for the patterns in the table, and only in whole string values. These pass through unchanged: postgresql://user:pw@host/db (the scheme is not in the list), file:// URLs, ~/ paths, a command line that contains a path, a bare token such as sk-live-abc123, an absolute path used as a mapping key, and any secret embedded in a longer string. Keep credentials and private paths out of these mappings.

The canonical report and the evidence are not redacted. Rewriting them would make the record differ from what was computed, so a bundle refuses them instead. If any string in the report or in an evidence result is an absolute path or a URL (on the schemes above) with credentials, a query or a fragment, or if any key looks like a credential, create_bundle raises ReportError and writes nothing. That is the whole test. An ordinary secret value such as sk-live-abc123, a postgresql:// URL or a ~/ path is not detected and goes into the archive. Any string that starts with /, even an instrument named /ES, counts as an absolute path and is rejected:

leaky = lc.AnalysisResult(
    lc.ResultMetadata("custom.check", parameters={"source": "/home/analyst/panel.parquet"})
)
report.bundle("leaky.lacuna", evidence={"custom": leaky})
ReportError: canonical evidence at $.evidence.custom.metadata.parameters.source contains an absolute path; replace it with a portable identity before bundling

Replace the path with a portable identity, such as a file name or a fingerprint, and bundle again. You remain responsible for what else is in the evidence.

Verify a bundle

lc.verify_bundle(path) checks a bundle without extracting it, and returns a BundleVerification. It raises ReportError on the first problem it finds.

verification = lc.verify_bundle("study.lacuna")
print(verification.artifact_count, verification.manifest.report_method)
print(verification.to_dict()["integrity_verified"], verification.to_dict()["authenticity_verified"])
14 audit.v0_1
True False

It reads the archive into memory and checks, in order:

CheckRejects
Size and shapeAn archive over 64 MiB, a member over 16 MiB, more than 256 members, or a total over 64 MiB. An archive that is not a ZIP, has a comment, or has duplicate member names.
Member safetyAbsolute paths, .., backslashes, directories, compression, encryption, non-regular files and executable permissions.
ManifestA missing, non-canonical or duplicate-key manifest, extra or missing fields, any value that differs from the version-1 trust contract, or a member that the manifest does not declare.
DigestsA mismatch in the artifact-set digest, or in any member’s size or SHA-256.
JSON membersDuplicate keys, non-finite numbers, or JSON that is not in canonical form.
Report identityA canonical report whose schema version, method, method version or input fingerprint disagrees with the manifest.
EncodingAn archive whose bytes differ from the canonical re-encoding of its members.

A bundle that has been edited after it was written fails:

with zipfile.ZipFile("study.lacuna") as source:
    with zipfile.ZipFile("edited.lacuna", "w", compression=zipfile.ZIP_STORED) as target:
        for info in source.infolist():
            content = source.read(info)
            if info.filename == "report/audit.md":
                content = content.replace(b"PASS", b"FAIL")
            target.writestr(info, content)
lc.verify_bundle("edited.lacuna")
ReportError: bundle artifact SHA-256 mismatch: report/audit.md

BundleVerification holds the path, the parsed manifest, the archive_sha256, the total_size and an artifact_count. total_size is the sum of the member sizes, not the size of the file. to_dict() is a summary without the manifest: archive_sha256, artifact_count, bundle_version, format, path, reproducibility_level, total_size and the two flags discussed next. Verification does not check that report/audit.md and report/audit.html match report/audit.json, compares only four report identity fields (schema version, method, method version and input fingerprint) with the manifest, and does not rescan the contents for secrets or paths.

Integrity versus authenticity

verify_bundle establishes integrity: the members match the digests the manifest declares, and the archive is well-formed and safe to read. to_dict() therefore reports integrity_verified as True, and authenticity_verified as False always.

It cannot establish authenticity, because every digest lives inside the archive. Someone who can rewrite a member can also rewrite the manifest entries, the artifact-set digest and the ZIP, and the result verifies. manifest.json has no digest of its own in the archive; only the archive hash covers it. Verification detects corruption and edits made without rebuilding the manifest, as in the example above. It does not detect a deliberate replacement by someone who understands the format.

To get authenticity you need something outside the archive:

GoalApproach
Detect any replacement of the fileRecord verification.archive_sha256 through a channel the file’s writers cannot alter, such as a commit message, a CI log or a ticket. Compare it before trusting the archive.
Establish who produced itSign the .lacuna file with your organization’s signing tool and verify the signature separately.
Check that a manifest is well-formedBundleManifest.from_json(text) parses a standalone manifest strictly. It never reads the members, so it proves nothing about the archive.

The manifest also states what a bundle reproduces. reproducibility.level is identifiable, with the scope “artifact identity and archive integrity”. The bundle identifies the evidence; it does not recompute it. The source data and code are not inside it, so recomputing needs both from you. Put their fingerprints in provenance= (see Experiments and fingerprints) so the bundle names exactly what is needed.

Determinism

The archive format is canonical. Members are sorted, stored uncompressed with a fixed 1980 timestamp and mode 0600, and every JSON member is canonical JSON. The same report bundled twice in the same environment gives the same bytes. metadata/environment.json and metadata/configuration.json record the machine, package versions and settings, so another environment gives different bytes:

report.bundle("again.lacuna", **context)
with open("study.lacuna", "rb") as first, open("again.lacuna", "rb") as second:
    print(first.read() == second.read())
True

A new audit run does not. Every result carries metadata.created_at, and report/audit.json and every evidence member contain it, so two runs of the same code give two archives with different digests and different members. To ask whether two runs agree, remove metadata.created_at from the members before comparing them, or compare the metrics and tables. input_fingerprint is no help here: it is null for SignalStudy audits.

The manifest

manifest.json is canonical JSON with a fixed set of fields. BundleManifest is its parsed form and BundleArtifact is one entry:

BundleManifest fieldMeaning
format, bundle_version"lacuna.reproducibility-bundle" and 1. Also available as lc.BUNDLE_FORMAT and lc.BUNDLE_VERSION.
producer_versionThe Lacuna version that wrote the bundle.
report_schema_version, report_method, report_method_version, report_input_fingerprintThe identity of report/audit.json, which verification cross-checks.
artifact_set_sha256A digest of the canonical list of artifact entries.
artifactsThe BundleArtifact entries, sorted by path.
reproducibility_level"identifiable". The only level version 1 supports.
BundleArtifact fieldMeaning
pathThe member path inside the archive.
roleOne of canonical_report, configuration, environment, evidence, invocation, provenance, redaction_log, rendered_report.
media_typeThe member’s media type.
sha25664 lowercase hex digits.
sizeThe member’s size in bytes.

The version-1 manifest is described by the packaged lacuna-bundle-manifest-v1 schema; see Schemas.

From the command line

lacuna signal --bundle and lacuna audit --bundle write a bundle beside the report, and lacuna bundle verify checks one. The commands take files, so save the panel first:

signal.write_parquet("signal.parquet")
prices.write_parquet("prices.parquet")
lacuna signal \
  --signal signal.parquet --prices prices.parquet \
  --horizon 1D --horizon 5D \
  --signal-observed-at open --entry current_close \
  --price-adjustment total_return_adjusted \
  --seed 1 --bootstrap-resamples 200 \
  --out cli-report.md --bundle cli.lacuna 2>&1
lacuna bundle verify cli.lacuna | sed -E 's/^(Total bytes +).*/\1<n>/; s/^(SHA-256 +).*/\1<digest>/'
lacuna bundle verify cli.lacuna --json | python -c "import json, sys; d = json.load(sys.stdin); print(d['integrity_verified'], d['authenticity_verified'], d['artifact_count'])"
wrote Lacuna reproducibility bundle to cli.lacuna
wrote Lacuna audit to cli-report.md
Bundle       cli.lacuna
Format       lacuna.reproducibility-bundle v1
Artifacts    11
Total bytes  <n>
SHA-256      <digest>
Integrity    verified
Authenticity not verified (use signed release/provenance channels separately)
True False 11

lacuna bundle verify exits 0 when the bundle verifies and 1 when it does not, printing lacuna: error: ... to standard error. Its output states plainly that authenticity was not verified. The CLI reference lists every option.

Neither command can supply provenance, so a CLI bundle carries no data or code fingerprints. --out and --bundle must be different paths, and --overwrite governs both. The two commands bundle differently. lacuna signal --bundle bundles the study’s evidence with the default configuration. lacuna audit --bundle bundles the evidence files you passed with --evidence, a configuration naming the audit profile, and an invocation entry recording the command, scope and evidence names.

Parameters

ParameterDefaultMeaning
reportrequiredThe AuditReport to bundle.
pathrequiredThe destination. It must end in .lacuna, compared without regard to case. Missing parent directories are created.
configurationNoneA mapping stored as metadata/configuration.json and redacted. When omitted, Lacuna’s runtime settings are stored.
evidenceNoneNamed AnalysisResult values, stored as evidence/<name>.json. Rejected, not redacted, if they contain a credential-like key, a URL with credentials, a query or a fragment, or a string that starts with /. Other secrets are not detected.
provenanceNoneA mapping stored as metadata/provenance.json and redacted. Use it for data and code fingerprints, vendor and export identities.
invocationNoneA mapping stored as metadata/invocation.json and redacted. Use it for the command and arguments that produced the report.
overwriteFalseReplace an existing bundle. The replacement is written to a temporary file and moved into place, so a reader never sees a half-written archive. Without it, the archive is created in place with an exclusive open, so an existing file raises ReportError, and the write is not atomic.
ParameterDefaultMeaning
pathrequiredAs for create_bundle.
configurationNoneAs for create_bundle.
evidenceNoneWhen None, the evidence the report retained. Pass a mapping to bundle something else, or {} to bundle none.
provenanceNoneAs for create_bundle.
invocationNoneAs for create_bundle.
overwriteFalseAs for create_bundle.
ParameterDefaultMeaning
pathrequiredThe .lacuna file to verify. It is read, never extracted or executed.

The full signatures are in the lacuna.bundle API reference.