In this section
- Inverter Block electrical · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/inverter_block.py lines 1–321
- Kernel Authority transform · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/kernel_authority.py lines 1–134
- Persistence ingest · solar-electrical-topology-analysis-engine-text-based / src/solar_topology/persistence.py lines 1–136
Inverter Block
A Python module in Solar Electrical Topology Analysis Engine Text Based that works with solar, using SHA-256. It validates inverter block receipt (`validate_inverter_block_receipt`) and builds reference inverter block (`build_reference_inverter_block`).
electricalsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/inverter_block.py · lines 1–321 of 321 · Not reached from any entry point (candidate for review) · pattern _canonical_json (shared by 3 files)
- What it does
- It calculates solar. Defines 13 functions or classes, including InverterBlockEvidenceState, InverterBlockReceipt, _canonical_json, _hash_payload, _qualified_state. Uses libraries __future__, dataclasses, enum, hashlib, json.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'inverter'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
- Downstream impact
- Used directly by 1 file: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based).
- What it achieves
- Deterministic inverter-block aggregate over existing engineering receipts. Its code works with 352 kVA.
- Why it matters
- Imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology.
- Application
- solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
- Uses
- Solar Topology — Array (relative import), Equipment Profiles (relative import), __future__, dataclasses, enum, hashlib, json, typing
- Used by
- imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
- Produces
- InverterBlockEvidenceState, InverterBlockReceipt, inverter_block_payload, inverter_block_json, inverter_block_hash, build_inverter_block, validate_inverter_block_receipt, build_reference_inverter_block
- Defines here
- InverterBlockEvidenceState, InverterBlockReceipt, _canonical_json, _hash_payload, _qualified_state, _table_binding, inverter_block_payload, inverter_block_json, inverter_block_hash, _normalise_receipts, build_inverter_block, validate_inverter_block_receipt, build_reference_inverter_block
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 src/solar_topology/inverter_block.py:1-321 · blob 1f4044163ce6fc6f87103a78080c749980884d68 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Deterministic inverter-block aggregate over existing engineering receipts.
This module adds no geometry, routing, electrical calculations, standards logic or
browser behaviour. It binds the existing Build 025 receipt authority to the
separate generic equipment-evidence contract without treating routing-fixture MPPT
labels as manufacturer evidence.
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
import hashlib
import json
from typing import Iterable
from .array import (
Build025Receipt,
WiringStrategy,
reference_24_by_30_build,
)
from .equipment_profiles import (
GENERIC_REFERENCE_EQUIPMENT_CONTRACT,
ReferenceEquipmentContract,
reference_equipment_contract_hash,
reference_equipment_missing_evidence,
validate_reference_equipment_contract,
)
INVERTER_BLOCK_SCHEMA_VERSION = "globalgrid2050.solar-dc.inverter-block.v1"
REFERENCE_INVERTER_BLOCK_ID = "inverter_block_352kva_475_2kwp_001"
class InverterBlockEvidenceState(StrEnum):
COMPLETE = "complete"
INCOMPLETE_EVIDENCE = "incomplete_evidence"
@dataclass(frozen=True, slots=True)
class InverterBlockReceipt:
"""One inverter-centred aggregate retaining all child receipt identities."""
block_id: str
equipment_contract: ReferenceEquipmentContract
table_receipts: tuple[Build025Receipt, ...]
module_count: int
string_count: int
modules_per_string: int
allocated_physical_input_count: int
equipment_missing_evidence: tuple[str, ...]
evidence_state: InverterBlockEvidenceState
receipt_hash: str
schema_version: str = INVERTER_BLOCK_SCHEMA_VERSION
def _canonical_json(payload: object) -> str:
return json.dumps(
payload,
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
)
def _hash_payload(payload: object) -> str:
digest = hashlib.sha256(_canonical_json(payload).encode("utf-8")).hexdigest()
return f"sha256:{digest}"
def _qualified_state(value: object) -> str:
verification_state = getattr(value, "verification_state", None)
return str(verification_state) if verification_state is not None else "unknown"
def _table_binding(receipt: Build025Receipt) -> dict[str, object]:
return {
"table_id": receipt.geometry.table_id,
"strategy": str(receipt.topology.strategy),
"module_count": receipt.geometry.module_count,
"string_count": len(receipt.string_allocation.strings),
"geometry_hash": receipt.geometry.geometry_hash,
"assignment_hash": receipt.string_allocation.assignment_hash,
"topology_hash": receipt.topology.topology_hash,
"input_allocation_hash": receipt.input_allocation.allocation_hash,
"routing_hash": receipt.routing.routing_hash,
"installed_length_hash": receipt.installed_length.receipt_hash,
"build025_receipt_hash": receipt.receipt_hash,
"routing_fixture_equipment_profile_id": receipt.equipment_profile.profile_id,
"routing_fixture_inverter_id": receipt.equipment_profile.inverter_id,
}
def inverter_block_payload(receipt: InverterBlockReceipt) -> dict[str, object]:
"""Return the deterministic aggregate payload without runtime metadata."""
if not isinstance(receipt, InverterBlockReceipt):
raise TypeError("receipt must be an InverterBlockReceipt")
contract = receipt.equipment_contract
inverter = contract.inverter
return {
"schema_version": receipt.schema_version,
"block_id": receipt.block_id,
"receipt_hash": receipt.receipt_hash,
"equipment_contract": {
"contract_id": contract.contract_id,
"revision": contract.revision,
"contract_hash": reference_equipment_contract_hash(contract),
},
"product_boundary": {
"module_profile_id": contract.module.profile_id,
"inverter_profile_id": inverter.profile_id,
"module_technology": contract.module.technology.value,
"module_rated_power_wp": contract.module.rated_power_wp.value,
"modules_per_string": receipt.modules_per_string,
"string_count": receipt.string_count,
"module_count": receipt.module_count,
"string_rated_power_kwp": contract.string_rated_power_kwp,
"dc_nameplate_power_kwp": contract.dc_nameplate_power_kwp,
"inverter_apparent_power_kva": inverter.apparent_power_kva.value,
"dc_ac_nameplate_ratio": contract.dc_ac_nameplate_ratio,
},
"table_count": len(receipt.table_receipts),
"table_receipts": [
_table_binding(item)
for item in receipt.table_receipts
],
"input_authority": {
"physical_dc_input_count": inverter.physical_dc_input_count.value,
"allocated_physical_input_count": receipt.allocated_physical_input_count,
"mppt_count": inverter.mppt_count.value,
"mppt_count_verification_state": _qualified_state(inverter.mppt_count),
"mppt_mapping_verification_states": sorted(
{
_qualified_state(item.mppt_id)
for item in inverter.dc_inputs
}
),
"internal_dc_topology": inverter.internal_dc_topology.value,
"internal_dc_topology_verification_state": _qualified_state(
inverter.internal_dc_topology
),
"reverse_current_blocking": inverter.reverse_current_blocking.value,
"reverse_current_blocking_verification_state": _qualified_state(
inverter.reverse_current_blocking
),
"pce_backfeed_current_a": inverter.pce_backfeed_current_a.value,
"pce_backfeed_verification_state": _qualified_state(
inverter.pce_backfeed_current_a
),
"routing_fixture_mppt_labels_are_equipment_evidence": False,
},
"equipment_evidence": {
"state": str(receipt.evidence_state),
"missing_evidence_count": len(receipt.equipment_missing_evidence),
"missing_evidence": list(receipt.equipment_missing_evidence),
},
}
def inverter_block_json(receipt: InverterBlockReceipt) -> str:
"""Return canonical JSON for the inverter-block aggregate."""
return _canonical_json(inverter_block_payload(receipt))
def inverter_block_hash(receipt: InverterBlockReceipt) -> str:
"""Recompute the aggregate hash from all bound engineering authorities."""
payload = inverter_block_payload(receipt)
payload.pop("receipt_hash")
return _hash_payload(payload)
def _normalise_receipts(
table_receipts: Iterable[Build025Receipt],
) -> tuple[Build025Receipt, ...]:
receipts = tuple(table_receipts)
if not receipts:
raise ValueError("an inverter block requires at least one table receipt")
if any(not isinstance(item, Build025Receipt) for item in receipts):
raise TypeError("table_receipts must contain Build025Receipt objects")
table_ids = [item.geometry.table_id for item in receipts]
if len(table_ids) != len(set(table_ids)):
raise ValueError("inverter-block table identifiers must be unique")
return tuple(sorted(receipts, key=lambda item: item.geometry.table_id))
def build_inverter_block(
*,
block_id: str,
equipment_contract: ReferenceEquipmentContract,
table_receipts: Iterable[Build025Receipt],
) -> InverterBlockReceipt:
"""Bind existing table and equipment receipts into one deterministic block."""
if not isinstance(block_id, str) or not block_id.strip():
raise ValueError("block_id must be a non-empty string")
if not isinstance(equipment_contract, ReferenceEquipmentContract):
raise TypeError("equipment_contract must be a ReferenceEquipmentContract")
validate_reference_equipment_contract(equipment_contract)
receipts = _normalise_receipts(table_receipts)
module_count = sum(item.geometry.module_count for item in receipts)
string_count = sum(len(item.string_allocation.strings) for item in receipts)
modules_per_string_values = {
len(string_item.ordered_module_ids)
for item in receipts
for string_item in item.string_allocation.strings
}
if len(modules_per_string_values) != 1:
raise ValueError("inverter-block strings must have one modules-per-string value")
modules_per_string = modules_per_string_values.pop()
allocated_inputs = [
assignment.input_id
for item in receipts
for assignment in item.input_allocation.assignments
]
if len(allocated_inputs) != len(set(allocated_inputs)):
raise ValueError("physical input identifiers are duplicated across tables")
if module_count != equipment_contract.module_count:
raise ValueError(
"table receipts do not match equipment-contract module count: "
f"{module_count} != {equipment_contract.module_count}"
)
if string_count != equipment_contract.string_count:
raise ValueError(
"table receipts do not match equipment-contract string count: "
f"{string_count} != {equipment_contract.string_count}"
)
if modules_per_string != equipment_contract.modules_per_string:
raise ValueError(
"table receipts do not match equipment-contract modules per string: "
f"{modules_per_string} != {equipment_contract.modules_per_string}"
)
physical_input_count = equipment_contract.inverter.physical_dc_input_count.value
if not isinstance(physical_input_count, int):
raise ValueError("equipment physical DC input count is unresolved")
if len(allocated_inputs) != string_count:
raise ValueError("every block string must have one physical input allocation")
if len(allocated_inputs) > physical_input_count:
raise ValueError("allocated strings exceed equipment physical DC input count")
missing = reference_equipment_missing_evidence(equipment_contract)
evidence_state = (
InverterBlockEvidenceState.INCOMPLETE_EVIDENCE
if missing
else InverterBlockEvidenceState.COMPLETE
)
preliminary = InverterBlockReceipt(
block_id=block_id.strip(),
equipment_contract=equipment_contract,
table_receipts=receipts,
module_count=module_count,
string_count=string_count,
modules_per_string=modules_per_string,
allocated_physical_input_count=len(allocated_inputs),
equipment_missing_evidence=missing,
evidence_state=evidence_state,
receipt_hash="",
)
return InverterBlockReceipt(
block_id=preliminary.block_id,
equipment_contract=preliminary.equipment_contract,
table_receipts=preliminary.table_receipts,
module_count=preliminary.module_count,
string_count=preliminary.string_count,
modules_per_string=preliminary.modules_per_string,
allocated_physical_input_count=(
preliminary.allocated_physical_input_count
),
equipment_missing_evidence=preliminary.equipment_missing_evidence,
evidence_state=preliminary.evidence_state,
receipt_hash=inverter_block_hash(preliminary),
)
def validate_inverter_block_receipt(receipt: InverterBlockReceipt) -> None:
"""Reject tampering without rebuilding or changing child receipts."""
if not isinstance(receipt, InverterBlockReceipt):
raise TypeError("receipt must be an InverterBlockReceipt")
expected = inverter_block_hash(receipt)
if receipt.receipt_hash != expected:
raise ValueError("inverter-block receipt hash mismatch")
rebuilt = build_inverter_block(
block_id=receipt.block_id,
equipment_contract=receipt.equipment_contract,
table_receipts=receipt.table_receipts,
)
if rebuilt.receipt_hash != receipt.receipt_hash:
raise ValueError("inverter-block receipt content is inconsistent")
def build_reference_inverter_block(
*,
strategy: WiringStrategy | str = WiringStrategy.LEAPFROG,
) -> InverterBlockReceipt:
"""Build the first complete 352 kVA / 475.2 kWp product fixture."""
table_receipt = reference_24_by_30_build(strategy=strategy)
return build_inverter_block(
block_id=REFERENCE_INVERTER_BLOCK_ID,
equipment_contract=GENERIC_REFERENCE_EQUIPMENT_CONTRACT,
table_receipts=(table_receipt,),
)
__all__ = [
"INVERTER_BLOCK_SCHEMA_VERSION",
"REFERENCE_INVERTER_BLOCK_ID",
"InverterBlockEvidenceState",
"InverterBlockReceipt",
"build_inverter_block",
"build_reference_inverter_block",
"inverter_block_hash",
"inverter_block_json",
"inverter_block_payload",
"validate_inverter_block_receipt",
]Kernel Authority
A Python module in Solar Electrical Topology Analysis Engine Text Based that works with solar, using SHA-256.
transformsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/kernel_authority.py · lines 1–134 of 134 · Not reached from any entry point (candidate for review)
- What it does
- It calculates solar. Defines 6 functions or classes, including KernelAuthorityStatus, KernelAuthorityAssessment, authoritative, require_authoritative, _close. Uses libraries __future__, dataclasses, enum, math.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
- What it achieves
- It is built from the kernel authority status class (`KernelAuthorityStatus`), the kernel authority assessment class (`KernelAuthorityAssessment`) and the authoritative step (`authoritative`). Authority assessment for deterministic steady-state calculation receipts.
- Why it matters
- No other file in the estate was found to import it.
- Application
- solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
- Uses
- Calculation Receipts (relative import), __future__, dataclasses, enum, math
- Used by
- none found
- Produces
- KernelAuthorityStatus, KernelAuthorityAssessment, assess_steady_state_receipt
- Defines here
- KernelAuthorityStatus, KernelAuthorityAssessment, authoritative, require_authoritative, _close, assess_steady_state_receipt
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 src/solar_topology/kernel_authority.py:1-134 · blob dfb3b3b0163af9ceb3509023fca432d4b867689b · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Authority assessment for deterministic steady-state calculation receipts."""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
import math
from .calculation_receipts import (
CALCULATION_RECEIPT_SCHEMA_VERSION,
COMPLETE_CIRCUIT_METHOD_VERSION,
OrderedCircuitCalculationReceipt,
calculation_receipt_hash,
)
KERNEL_AUTHORITY_SCHEMA_VERSION = (
"globalgrid2050.solar-dc.kernel-authority.v10.2"
)
REQUIRED_STEADY_STATE_FORMULA_IDS = (
"V10-R-000:R20=resolved_evidence_bound_product_property",
"V10-R-001:Rconductor=R20*L*(1+alpha20*(T-20C))",
"V10-R-002:Rcontacts=N*R20contact*(1+alpha20*(T-20C))",
"V10-V-001:dV=I*R",
"V10-P-001:Ploss=I^2*R",
)
class KernelAuthorityStatus(StrEnum):
AUTHORITATIVE = "authoritative"
PROVISIONAL = "provisional"
REJECTED = "rejected"
@dataclass(frozen=True)
class KernelAuthorityAssessment:
status: KernelAuthorityStatus
receipt_hash: str | None
reasons: tuple[str, ...]
schema_version: str = KERNEL_AUTHORITY_SCHEMA_VERSION
@property
def authoritative(self) -> bool:
return self.status == KernelAuthorityStatus.AUTHORITATIVE
def require_authoritative(self) -> None:
if not self.authoritative:
raise ValueError(
"steady-state receipt is not authoritative: "
+ ", ".join(self.reasons)
)
def _close(first: float, second: float) -> bool:
return math.isclose(first, second, rel_tol=1e-12, abs_tol=1e-12)
def assess_steady_state_receipt(
receipt: OrderedCircuitCalculationReceipt,
) -> KernelAuthorityAssessment:
"""Independently assess whether a receipt may act as steady-state authority."""
if not isinstance(receipt, OrderedCircuitCalculationReceipt):
return KernelAuthorityAssessment(
KernelAuthorityStatus.REJECTED,
None,
("INVALID_RECEIPT_TYPE",),
)
reasons: list[str] = []
if receipt.schema_version != CALCULATION_RECEIPT_SCHEMA_VERSION:
reasons.append("UNSUPPORTED_RECEIPT_SCHEMA")
if receipt.method_version != COMPLETE_CIRCUIT_METHOD_VERSION:
reasons.append("UNSUPPORTED_METHOD_VERSION")
if tuple(receipt.formula_ids) != REQUIRED_STEADY_STATE_FORMULA_IDS:
reasons.append("FORMULA_CONTRACT_MISMATCH")
if not receipt.validated_circuit_hash.startswith("sha256:"):
reasons.append("MISSING_VALIDATED_CIRCUIT_HASH")
if not receipt.resistance_evidence_set_hash.startswith("sha256:"):
reasons.append("MISSING_RESISTANCE_EVIDENCE_SET_HASH")
if not receipt.ordered_segment_ids:
reasons.append("EMPTY_ORDERED_SEGMENT_SET")
if tuple(result.segment_id for result in receipt.segment_results) != tuple(
receipt.ordered_segment_ids
):
reasons.append("SEGMENT_ORDER_MISMATCH")
numeric_values = (
receipt.current_a,
receipt.total_conductor_length_m,
receipt.total_conductor_resistance_ohm,
receipt.total_connector_resistance_ohm,
receipt.total_resistance_ohm,
receipt.voltage_drop_v,
receipt.resistive_loss_w,
)
if any(not math.isfinite(float(value)) or value < 0 for value in numeric_values):
reasons.append("INVALID_NON_NEGATIVE_TOTAL")
conductor_sum = math.fsum(
result.conductor_resistance_ohm for result in receipt.segment_results
)
connector_sum = math.fsum(
result.connector_resistance_ohm for result in receipt.segment_results
)
length_sum = math.fsum(
result.conductor_length_m for result in receipt.segment_results
)
resistance_sum = conductor_sum + connector_sum
if not _close(length_sum, receipt.total_conductor_length_m):
reasons.append("CONDUCTOR_LENGTH_TOTAL_MISMATCH")
if not _close(conductor_sum, receipt.total_conductor_resistance_ohm):
reasons.append("CONDUCTOR_RESISTANCE_TOTAL_MISMATCH")
if not _close(connector_sum, receipt.total_connector_resistance_ohm):
reasons.append("CONNECTOR_RESISTANCE_TOTAL_MISMATCH")
if not _close(resistance_sum, receipt.total_resistance_ohm):
reasons.append("TOTAL_RESISTANCE_MISMATCH")
if not _close(receipt.current_a * resistance_sum, receipt.voltage_drop_v):
reasons.append("VOLTAGE_DROP_MISMATCH")
if not _close(receipt.current_a**2 * resistance_sum, receipt.resistive_loss_w):
reasons.append("RESISTIVE_LOSS_MISMATCH")
receipt_hash = calculation_receipt_hash(receipt)
status = (
KernelAuthorityStatus.AUTHORITATIVE
if not reasons
else KernelAuthorityStatus.REJECTED
)
return KernelAuthorityAssessment(
status,
receipt_hash,
tuple(sorted(set(reasons))),
)Persistence
A Python module in Solar Electrical Topology Analysis Engine Text Based that builds deterministic record store (`build_deterministic_record_store`) and reads back store (`read_back_store`), covering solar, using SHA-256.
ingestsolar-electrical-topology-analysis-engine-text-based / src/solar_topology/persistence.py · lines 1–136 of 136 · Not reached from any entry point (candidate for review) · pattern __post_init__ (shared by 16 files)
- What it does
- Defines 10 functions or classes, including PersistedRecord, __post_init__, DeterministicStore, canonical_payload_json, persist_record. Uses libraries __future__, dataclasses, hashlib, json, typing.
- Why it exists in the grid workflow
- Domain stage sub33kv_design (path word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary. Domain terms in the code: solar.
- Downstream impact
- Used directly by 1 file: Solar Electrical Topology Analysis Engine Text Based — Solar Topology (solar-electrical-topology-analysis-engine-text-based).
- What it achieves
- It is built from the persisted record class (`PersistedRecord`), the deterministic store class (`DeterministicStore`) and the canonical payload JSON helper (`canonical_payload_json`). Deterministic persistence envelopes and independent read-back verification.
- Why it matters
- Imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology.
- Application
- solar-electrical-topology-analysis-engine-text-based · src/solar_topology · Python module
- Uses
- __future__, dataclasses, hashlib, json, typing
- Used by
- imported by Solar Electrical Topology Analysis Engine Text Based — Solar Topology (relative import)
- Produces
- PersistedRecord, DeterministicStore, canonical_payload_json, persist_record, build_deterministic_record_store, deterministic_store_payload, deterministic_store_json, deterministic_store_hash, read_back_store
- Defines here
- PersistedRecord, __post_init__, DeterministicStore, canonical_payload_json, persist_record, build_deterministic_record_store, deterministic_store_payload, deterministic_store_json, deterministic_store_hash, read_back_store
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- solar-electrical-topology-analysis-engine-text-based@d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9 src/solar_topology/persistence.py:1-136 · blob bfe71190041b43efa8a717d80d8dbd70e236c748 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: unreached_review
"""Deterministic persistence envelopes and independent read-back verification."""
from __future__ import annotations
from dataclasses import dataclass
import hashlib
import json
from typing import Mapping
PERSISTENCE_SCHEMA_VERSION = "globalgrid2050.solar-dc.persistence.v10.1"
@dataclass(frozen=True)
class PersistedRecord:
record_id: str
record_type: str
source_schema_version: str
payload_json: str
payload_hash: str
def __post_init__(self) -> None:
for name, value in (
("record_id", self.record_id),
("record_type", self.record_type),
("source_schema_version", self.source_schema_version),
("payload_json", self.payload_json),
):
if not isinstance(value, str) or not value.strip():
raise ValueError(f"{name} must be non-empty text")
expected = "sha256:" + hashlib.sha256(self.payload_json.encode("utf-8")).hexdigest()
if self.payload_hash != expected:
raise ValueError("payload_hash does not match payload_json")
try:
decoded = json.loads(self.payload_json)
except json.JSONDecodeError as exc:
raise ValueError("payload_json must contain valid JSON") from exc
canonical = json.dumps(decoded, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
if canonical != self.payload_json:
raise ValueError("payload_json must be canonical JSON")
@dataclass(frozen=True)
class DeterministicStore:
records: tuple[PersistedRecord, ...]
schema_version: str = PERSISTENCE_SCHEMA_VERSION
def canonical_payload_json(payload: Mapping[str, object]) -> str:
if not isinstance(payload, Mapping):
raise TypeError("payload must be a mapping")
return json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
def persist_record(
record_id: str,
record_type: str,
source_schema_version: str,
payload: Mapping[str, object],
) -> PersistedRecord:
payload_json = canonical_payload_json(payload)
payload_hash = "sha256:" + hashlib.sha256(payload_json.encode("utf-8")).hexdigest()
return PersistedRecord(
record_id=record_id,
record_type=record_type,
source_schema_version=source_schema_version,
payload_json=payload_json,
payload_hash=payload_hash,
)
def build_deterministic_record_store(
records: tuple[PersistedRecord, ...] | list[PersistedRecord],
) -> DeterministicStore:
ordered = tuple(sorted(records, key=lambda item: item.record_id))
ids = [item.record_id for item in ordered]
if len(ids) != len(set(ids)):
raise ValueError("persisted record identifiers must be unique")
return DeterministicStore(records=ordered)
def deterministic_store_payload(store: DeterministicStore) -> dict[str, object]:
return {
"schema_version": store.schema_version,
"records": [
{
"record_id": item.record_id,
"record_type": item.record_type,
"source_schema_version": item.source_schema_version,
"payload": json.loads(item.payload_json),
"payload_hash": item.payload_hash,
}
for item in store.records
],
}
def deterministic_store_json(store: DeterministicStore) -> str:
return json.dumps(
deterministic_store_payload(store),
sort_keys=True,
separators=(",", ":"),
ensure_ascii=False,
)
def deterministic_store_hash(store: DeterministicStore) -> str:
digest = hashlib.sha256(deterministic_store_json(store).encode("utf-8")).hexdigest()
return f"sha256:{digest}"
def read_back_store(serialised: str) -> DeterministicStore:
if not isinstance(serialised, str) or not serialised:
raise ValueError("serialised store must be non-empty text")
try:
raw = json.loads(serialised)
except json.JSONDecodeError as exc:
raise ValueError("serialised store must be valid JSON") from exc
if raw.get("schema_version") != PERSISTENCE_SCHEMA_VERSION:
raise ValueError("unsupported persistence schema version")
records: list[PersistedRecord] = []
for item in raw.get("records", []):
payload_json = canonical_payload_json(item["payload"])
records.append(
PersistedRecord(
record_id=item["record_id"],
record_type=item["record_type"],
source_schema_version=item["source_schema_version"],
payload_json=payload_json,
payload_hash=item["payload_hash"],
)
)
store = build_deterministic_record_store(records)
if deterministic_store_json(store) != serialised:
raise ValueError("serialised store is not canonical or changed during read-back")
return store