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.
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.
Stable imports and package surface 01 · models
Typed contract and evidence objects 02 · contracts
Compile user-owned contract documents 03 · engine
Deterministic evidence evaluation 04 · semantics
State ranking and aggregation 05 · adapters
Normalize external records 06 · telemetry
JSON, JSONL and OTLP admission 07 · provenance
Canonical payloads and hashes 08 · auth
Signature and key-custody boundaries 09 · replay
Nonce, sequence and fencing state 10 · trusted_time
Time receipts, status and quorum 11 · audit
Hash-linked retention and checkpoints 12 · ledger
Small evidence replay ledger 13 · standards
Versioned packs and crosswalks 14 · standard_registry
Register and snapshot packs 15 · standard_context
Fail-closed applicability 16 · public_data
NVD and ATT&CK snapshots 17 · public_mapping
Explicit source-to-evidence mapping 18 · benchmark
Reference contracts and scenarios 19 · baselines
Comparison methods and metrics 20 · faults
Seeded failure injection 21 · experimental
Factorial evaluation utilities 22 · statistics
Uncertainty summaries
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)
23 · package entrypoint
__init__
The stable import surface. It re-exports the objects an application should use without depending on private file layout.
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.
Public symbols
DecisionStatePASS, FAIL, UNKNOWN, EXPIRED, CONFLICT, NOT_TESTED.
EvidenceKindRuntime, scheduled, test, document or human observation.
EvidenceIdentity, subject, assertion, value, time, validity, provenance, hash and metadata.
ControlRequirementDeclared assertion, expected value and criticality.
DependencyRequirementTyped binding between a dependency and an assertion.
BusinessObjectiveMetric, numeric target and comparator.
ControlObjectiveLinkTyped control-to-objective relation with provenance and scope.
ServiceContract / AuditDecisionCompiled 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.
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.
03 · decision kernel
engine
AssuranceEngine evaluates evidence against a contract deterministically and returns an AuditDecision with component states, evidence identities and reasons.
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.
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_ORDERConstant 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.
EvidenceAdapterProtocol boundary with read(records).
MappingEvidenceAdapterMaps 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.
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.
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.
08 · signature boundary
auth
Provides local and remote signature interfaces without embedding key custody into the library.
HMACKey / HMACKeyringDeterministic local signing and verification.
SignatureVerifierMinimal verifier protocol for adapters.
ProcessSignatureVerifierJSON-lines boundary to a separate key process.
HTTPSignatureSigner / HTTPSignatureVerifierKMS-compatible HTTPS contracts.
QuorumSignatureSigner / QuorumSignatureVerifierMatching responses from key-custody members.
FailoverSignatureVerifierCombines 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.
ReplayGuardDurable local state with locking and fail-closed corruption handling.
HTTPReplayGuardHTTPS client for an external coordinator.
FencingTokenOwner, epoch and expiry tuple.
LeaseStoreAcquire, 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.
TimeSample / TrustedTimeProviderCommon timestamp and provider contract.
StaticTrustedTimeProvider / SequenceTrustedTimeProviderDeterministic fixtures and tests.
SignedTimeReceiptProvider / HTTPSignedTimeReceiptProviderVerify and freshness-check signed receipts.
QuorumTrustedTimeProviderReject stale or disagreeing sources.
CertificateValidationPolicyDeterministic chain/OCSP/CRL policy.
AttestedTrustedTimeProviderBind a sample to provider identity attestation.
HTTPSCertificateStatusProvider / QuorumCertificateStatusProviderFetch and require matching status.
11 · retention
audit
AuditChain appends hash-linked events, verifies the chain and supports signed checkpoints.
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.
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.
StandardPackAuthority, identifier, status, effective date, URI and version metadata.
StandardStatusLifecycle state for a pack.
CrosswalkTyped relation with scope and provenance.
CrosswalkRelationExplicit 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.
add_pack / add_crosswalkRegister governed entries.
get / packs / crosswalksRead entries without silent mutation.
snapshotCapture 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.
StandardContextAdmissionRecords 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.
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 / AttackTechniqueTyped records with provenance.
PublicDataSchemaErrorRaised 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.
ExplicitEvidenceMappingDeclares subject, assertion, value, kind, validity and metadata.
map_public_record(record, mapping)Creates evidence without semantic guessing.
PublicEvidenceMappingErrorRaised 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)18 · reference workload
benchmark
Defines a bounded e-commerce checkout contract and scenarios so the evaluator can be compared under repeatable conditions.
ecommerce_contract()Returns the reference service contract.
scenarios(now)Returns named evidence scenarios.
run_benchmark(now)Runs the bounded comparison workload.
ScenarioNames 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.
manual_checklistHuman-style checklist approximation.
static_crosswalkStatic mapping without runtime validity.
risk_score / rule_matchScoring and exact-match comparisons.
naive_business_thresholdBusiness-aware baseline that ignores evidence validity.
proposed_engineRuns AssuranceEngine on the same fixture.
classification_metricsSummarizes 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.
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.
FaultScenarioNames 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.
ExperimentalCaseOne 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.
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.