Deep module reference

AssuranceLab is an explicit evidence-to-decision pipeline, not a set of opaque helpers. This page explains the 22 runtime modules plus the public package entrypoint: what each owns, how data moves through it, how to use it, and which responsibility stays outside the wheel.

How to read this page. Start with the workflow, then follow the modules in the order that an observation crosses them. Every section separates public symbols, practical use, failure semantics and the external boundary an operator must own.

The 23-module map

The package contains 23 Python module files: __init__ is the stable import surface and the other 22 modules provide domain, trust, governance, retention and validation layers.

The complete path from observation to decision

A normal run is visible and reviewable: a collector creates a record, admission validates its shape, an adapter creates immutable evidence, the engine evaluates the contract, and retention stores the evidence and decision references.

from assurance_lab import (
    AssuranceEngine, MappingEvidenceAdapter, compile_service_contract,
    ingest_json_envelope, EvidenceLedger,
)
contract = compile_service_contract(contract_spec)
batch = ingest_json_envelope(envelope, MappingEvidenceAdapter())
decision = AssuranceEngine(
    require_integrity=True, require_provenance=True,
).evaluate(contract, batch.evidence, now=evaluation_time)
ledger = EvidenceLedger()
for item in batch.evidence:
    ledger.append(item)
print(decision.state.value, decision.evidence_ids, decision.reasons)
The wheel has no third-party runtime dependency. Remote signature, replay, certificate-status and trusted-time classes are transport/adaptor boundaries; they do not create an enterprise KMS, SIEM, HSM or high-availability service.

23 · package entrypoint

__init__

The stable import surface. It re-exports the objects an application should use without depending on private file layout.

ConsumesNothing at import time
ProducesTyped public classes and functions
Use inApplication code and integrations

How to use it

from assurance_lab import AssuranceEngine, Evidence, ServiceContract

Use top-level imports for stable code. The entrypoint does not configure a collector or make a network connection. Configuration remains explicit in the caller.

01 · domain model

models

Defines the typed vocabulary of an assurance decision: evidence, controls, dependencies, business objectives, links, contracts and decisions.

ConsumesStrings, values, UTC datetimes and mappings
ProducesFrozen dataclasses and enums
Use inEvery contract and evaluation

Public symbols

DecisionState

PASS, FAIL, UNKNOWN, EXPIRED, CONFLICT, NOT_TESTED.

EvidenceKind

Runtime, scheduled, test, document or human observation.

Evidence

Identity, subject, assertion, value, time, validity, provenance, hash and metadata.

ControlRequirement

Declared assertion, expected value and criticality.

DependencyRequirement

Typed binding between a dependency and an assertion.

BusinessObjective

Metric, numeric target and comparator.

ControlObjectiveLink

Typed control-to-objective relation with provenance and scope.

ServiceContract / AuditDecision

Compiled service boundary and explainable result.

requirement = ControlRequirement(
    control_id="backup", title="Fresh backup",
    assertion="backup_fresh", expected_value=True,
)
observation = Evidence(
    evidence_id="backup-001", subject="checkout",
    assertion="backup_fresh", value=True,
    observed_at=now, expires_at=None, kind=EvidenceKind.RUNTIME,
    provenance="backup-monitor", integrity_hash="...",
)

Validation rejects duplicate or unbound dependency requirements and invalid control-objective links. The model does not infer meaning from similar words; the organization owns assertion semantics and targets.

02 · contract compiler

contracts

compile_service_contract turns a user-owned mapping into a typed ServiceContract without silently importing standard text or inventing missing targets.

ConsumesMapping with service, controls and objectives
ProducesValidated ServiceContract
Use inConfiguration loading and CI checks

Required shape

{
  "service_id": "checkout", "name": "Payment checkout",
  "controls": [{"control_id": "backup", "title": "Fresh backup", "assertion": "backup_fresh"}],
  "objectives": [{"objective_id": "rto", "metric": "rto_minutes", "target": 60, "comparator": "<="}]
}

Compilation is the boundary where business language becomes machine-checkable semantics. Missing fields, malformed sequences, invalid comparators, undeclared dependencies and invalid links raise an error before evaluation.

A contract is a declared scope and set of checks. It is not an ISO certificate or a replacement for an audit opinion.

03 · decision kernel

engine

AssuranceEngine evaluates evidence against a contract deterministically and returns an AuditDecision with component states, evidence identities and reasons.

ConsumesContract, Evidence iterable and explicit UTC now
ProducesAuditDecision and reasons
Use inScheduled, event-driven or batch checks

Strictness options

Enable only what the deployment can support: require_integrity, require_signature, require_replay, require_independence, require_provenance, subject binding, future-clock skew, dependency binding, business oracle and business linkage.

engine = AssuranceEngine(
    rule_version="checkout-policy-2026-01",
    require_integrity=True, require_signature=True,
    require_replay=True, require_dependency_binding=True,
)
decision = engine.evaluate(contract, evidence, now=now)

Missing evidence is UNKNOWN; contradictory valid values are CONFLICT; stale evidence is EXPIRED; a false value is FAIL; no evidence at all is NOT_TESTED. Subject binding prevents evidence for another service from satisfying this contract.

04 · decision algebra

semantics

Provides the public ordering and join operation used to combine component states into a top-level state.

ConsumesDecisionState values
ProducesRank, order and aggregate state
Use inReports, tests and independent oracles
state_rank(state)

Severity rank used for aggregation.

aggregate_states(states)

Conservative join of non-empty states.

state_order()

Immutable public order for reproducible reports.

AGGREGATION_ORDER

Constant for consumers that display policy.

Keeping precedence in one module avoids each integration inventing a different meaning for “overall result”.

05 · admission boundary

adapters

Adapts external records into immutable evidence. An adapter validates and annotates; it never decides whether a service passes.

ConsumesNormalized mappings or record iterables
ProducesEvidence with trust metadata
Use inCollectors, telemetry bridges and tests
EvidenceAdapter

Protocol boundary with read(records).

MappingEvidenceAdapter

Maps records, optionally checking signatures and replay guards.

adapter = MappingEvidenceAdapter(
    keyring=keyring, require_signature=True,
    replay_guard=ReplayGuard("state/replay.json"), require_replay=True,
)
evidence = adapter.read(payload["records"])

Signature and replay results are attached as evidence metadata for strict engine gates. The adapter does not know whether an assertion is a business control.

06 · ingestion

telemetry

Admits bounded telemetry envelopes through one schema path, including JSON, JSONL and an explicit OTLP/HTTP JSON profile.

ConsumesVersioned JSON, JSONL or OTLP JSON
ProducesTelemetryBatch and typed evidence
Use inCollectors, webhooks and jobs
ingest_json_envelope(payload, adapter)

Validates schema version and records.

ingest_jsonl(payload, adapter)

Uses the same strict envelope path for lines.

ingest_otlp_json(payload, adapter)

Maps the bounded assurance OTLP log shape.

fetch_otlp_json(url, adapter, ...)

HTTPS fetch through a caller-provided context.

Malformed, unversioned or oversized input raises TelemetrySchemaError. The parser does not fetch public intelligence or guess business semantics.

07 · integrity primitives

provenance

Defines canonical JSON and SHA-256 digests so records can be compared, signed and retained reproducibly.

ConsumesJSON-compatible values or Evidence
ProducesCanonical bytes and hexadecimal hashes
Use inAdapters, signatures and retention
canonical_json(value)

Stable serialization used as a signature input.

sha256_record(value)

Digest of a canonical record.

evidence_payload(evidence)

Metadata-independent evidence payload.

evidence_hash(evidence)

Digest used by integrity checks.

A hash proves canonical content changed or did not change. It does not prove a source was honest, a clock was trustworthy or a control was correctly chosen.

08 · signature boundary

auth

Provides local and remote signature interfaces without embedding key custody into the library.

ConsumesCanonical payload, key id and signature
ProducesBoolean verification or signature bytes
Use inFixtures, KMS gateways and quorum checks
HMACKey / HMACKeyring

Deterministic local signing and verification.

SignatureVerifier

Minimal verifier protocol for adapters.

ProcessSignatureVerifier

JSON-lines boundary to a separate key process.

HTTPSignatureSigner / HTTPSignatureVerifier

KMS-compatible HTTPS contracts.

QuorumSignatureSigner / QuorumSignatureVerifier

Matching responses from key-custody members.

FailoverSignatureVerifier

Combines trusted verifiers without stale bypass.

Production still requires TLS/mTLS, authorization, rotation, HSM/KMS policy and audit logs outside this package.

09 · freshness and fencing

replay

Rejects reused nonces and non-monotonic sequences, and provides durable leases/fencing for a shared coordinator.

ConsumesProducer id, nonce, sequence and lease time
ProducesAccept/reject plus fencing tokens
Use inWebhooks, collectors and failover workers
ReplayGuard

Durable local state with locking and fail-closed corruption handling.

HTTPReplayGuard

HTTPS client for an external coordinator.

FencingToken

Owner, epoch and expiry tuple.

LeaseStore

Acquire, renew and validate monotonic epoch leases.

guard = ReplayGuard("state/replay.json")
accepted = guard.observe("collector-a", "nonce-7", 7)
# duplicate nonce or sequence <= previous returns False

Coordinator outages return rejection so the adapter can resolve evidence to UNKNOWN. The library does not provide a distributed database.

10 · time authority

trusted_time

Models time samples and freshness authority for leases, signed receipts and certificate-status decisions.

ConsumesProvider samples, receipts and status responses
ProducesTimeSample or explicit unavailability
Use inReplay, validity windows and high assurance
TimeSample / TrustedTimeProvider

Common timestamp and provider contract.

StaticTrustedTimeProvider / SequenceTrustedTimeProvider

Deterministic fixtures and tests.

SignedTimeReceiptProvider / HTTPSignedTimeReceiptProvider

Verify and freshness-check signed receipts.

QuorumTrustedTimeProvider

Reject stale or disagreeing sources.

CertificateValidationPolicy

Deterministic chain/OCSP/CRL policy.

AttestedTrustedTimeProvider

Bind a sample to provider identity attestation.

HTTPSCertificateStatusProvider / QuorumCertificateStatusProvider

Fetch and require matching status.

A time provider is an authority boundary, not a magic clock. Document source identity, trust anchors, freshness limits and outage behavior.

11 · retention

audit

AuditChain appends hash-linked events, verifies the chain and supports signed checkpoints.

ConsumesJSON-compatible event mappings
ProducesVerification result and checkpoint record
Use inEvidence retention and review bundles
AuditChain(path, genesis_hash=...)

Opens an append-only JSONL chain.

append(event)

Links a new event to the previous hash.

verify()

Checks sequence, predecessor and digest.

create_checkpoint(signer, key_id)

Signs the current head.

verify_checkpoint(checkpoint, verifier)

Checks signature and head binding.

Hash chaining is tamper evidence, not an immutable external archive by itself. Keep chain and signer custody separate when required.

12 · replay harness

ledger

Offers a small append-only EvidenceLedger for local fixtures, replay experiments and JSONL export.

ConsumesEvidence objects
ProducesOrdered entries and JSONL
Use inDocker smoke tests and notebooks
ledger = EvidenceLedger()
ledger.append(evidence_item)
ledger.export_jsonl("artifacts/evidence.jsonl")
for entry in ledger.entries():
    print(entry.evidence_id)

The ledger is not a database, object store, legal hold or retention service. It is useful because a small deterministic fixture is easy to inspect and reproduce.

13 · governance vocabulary

standards

Represents standards as versioned metadata and explicit crosswalk relations instead of keyword rules.

ConsumesPack metadata and relation endpoints
ProducesStandardPack and Crosswalk
Use inScope, applicability and audit context
StandardPack

Authority, identifier, status, effective date, URI and version metadata.

StandardStatus

Lifecycle state for a pack.

Crosswalk

Typed relation with scope and provenance.

CrosswalkRelation

Explicit relation vocabulary.

Use a pack to record which version and scope an evaluation relied on. This module does not copy normative text or declare conformity.

14 · governed registry

standard_registry

Stores standard packs and crosswalks with duplicate/conflict checks and produces an auditable snapshot.

ConsumesStandardPack and Crosswalk
ProducesRegistrySnapshot and immutable views
Use inConfiguration review and reproducible runs
add_pack / add_crosswalk

Register governed entries.

get / packs / crosswalks

Read entries without silent mutation.

snapshot

Capture versions and relations used.

baseline_registry()

Metadata-only baseline with official source provenance.

Keep organization-specific applicability and approval outside the default registry. A snapshot is context evidence, not proof of compliance.

15 · applicability gate

standard_context

Admits registered standard versions before evaluation and fails closed when the requested context is missing or unproven.

ConsumesRegistry and requested version tuple
ProducesAdmission result or explicit failure
Use inRelease pipelines and audit reports
StandardContextAdmission

Records admitted versions and reasons.

admit_standard_context(registry, versions)

Checks every requested version exists.

evaluate_with_standard_context(...)

Combines admission with engine evaluation.

admission = admit_standard_context(registry, ("iso-27001:2022",))
if not admission.accepted:
    raise RuntimeError(admission.reasons)

This gate prevents a report from claiming it used a standard version that was never registered or scoped.

16 · public intelligence

public_data

Parses bounded NVD JSON 2.0 and MITRE ATT&CK STIX snapshots while preserving source provenance and avoiding business inference.

ConsumesOfficial snapshot JSON objects
ProducesNvdSnapshot and AttackStixSnapshot
Use inEnrichment before explicit mapping
parse_nvd_snapshot(payload)

Retains vulnerability identifiers, descriptions, metrics and source digest.

parse_attack_stix_snapshot(payload)

Retains attack-pattern objects and source digest.

NvdVulnerability / AttackTechnique

Typed records with provenance.

PublicDataSchemaError

Raised when a snapshot cannot be admitted safely.

Parsing says what the public source reported. It does not say that a vulnerability affects a business process or is a control failure.

17 · explicit interpretation

public_mapping

Maps a public record to evidence only when the organization supplies the target subject, assertion, value and provenance explicitly.

ConsumesPublic record and mapping declaration
ProducesEvidence with source identity
Use inThreat-informed assurance
ExplicitEvidenceMapping

Declares subject, assertion, value, kind, validity and metadata.

map_public_record(record, mapping)

Creates evidence without semantic guessing.

PublicEvidenceMappingError

Raised for incomplete or ambiguous mapping.

mapping = ExplicitEvidenceMapping(
    subject="checkout", assertion="cve_reviewed",
    value=True, mapping_provenance="mapping://security/public-records",
    mapping_version="checkout-cve-review-v1",
    justification="Reviewed by the service owner", observed_at=now,
)
evidence = map_public_record(vulnerability, mapping)
Never auto-convert a CVE, ATT&CK technique or scanner label into a business pass/fail state without a reviewed mapping.

18 · reference workload

benchmark

Defines a bounded e-commerce checkout contract and scenarios so the evaluator can be compared under repeatable conditions.

ConsumesUTC reference time
ProducesScenario objects and benchmark output
Use inSmoke tests and research artifacts
ecommerce_contract()

Returns the reference service contract.

scenarios(now)

Returns named evidence scenarios.

run_benchmark(now)

Runs the bounded comparison workload.

Scenario

Names inputs and expected behavior.

This is a reproducible reference workload, not a claim that every enterprise checkout has the same controls or objectives.

19 · comparison methods

baselines

Provides interpretable comparison methods: manual checklist, static crosswalk, risk score, rule match, naive business threshold and the proposed engine.

ConsumesSame contract and evidence fixture
ProducesBaselineOutput and metrics
Use inClaim-driven evaluation
manual_checklist

Human-style checklist approximation.

static_crosswalk

Static mapping without runtime validity.

risk_score / rule_match

Scoring and exact-match comparisons.

naive_business_threshold

Business-aware baseline that ignores evidence validity.

proposed_engine

Runs AssuranceEngine on the same fixture.

classification_metrics

Summarizes predictions against an oracle.

Use matched fixtures and report negative cases. A score caused by extra information, data or compute is not a method contribution.

20 · fault injection

faults

Generates deterministic stale, conflicting, missing, tampered or unbound evidence to test fail-closed behavior.

ConsumesSeed and optional scenario id
ProducesFaultScenario, evidence and replay result
Use inRegression tests and Docker runs
generate_fault_scenario(seed, scenario_id)

Creates a reproducible fault.

scenario_evidence(scenario, now)

Materializes evidence for it.

replay_scenario(seed, now)

Runs the scenario deterministically.

FaultScenario

Names injected fault and expected boundary.

Fault tests are not penetration tests. They test decision and evidence handling; network, identity and host security need separate tests.

21 · controlled experiment

experimental

Supports bounded factorial experiments and an independent business oracle without calling the engine from the oracle.

ConsumesReplicate count, UTC time and factor levels
ProducesExperimentalCase and aggregate results
Use inResearch validation and ablations
ExperimentalCase

One combination of capacity, RTO, RPO, payment and review status.

independent_oracle(...)

Reference business outcome computed independently.

generate_factorial_cases(replicates, now)

Creates balanced cases.

evaluate_factorial(cases, now)

Compares engine outcomes with the oracle.

Keep factors, replicates, seed and failure criteria in the experiment record. An oracle that repeats the engine cannot falsify it.

22 · uncertainty

statistics

Reports binary outcomes with a Wilson interval so small experiments do not present a point estimate as certainty.

ConsumesSuccess/trial counts or binary values
ProducesInterval and summary mapping
Use inBenchmark reports and appendices
wilson_interval(successes, trials, z)

Returns a conservative proportion interval.

binary_summary(values)

Summarizes binary observations with counts and uncertainty.

These utilities do not choose a hypothesis test or establish external validity. Study design and interpretation remain the researcher's responsibility.

Recommended reading order

Operational reading rule. If a page says “provider”, “coordinator”, “registry” or “oracle”, that component is an explicit boundary. Deployments must document its owner, authentication, availability, retention and failure response rather than treating the Python class as the complete service.