GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Solar and storage design / solar-electrical-topology-analysis-engine-text-based / tests

Test Inverter Block and 5 more files

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based that uses SHA-256.

658 lines of Python from solar-electrical-topology-analysis-engine-text-based, in 6 files. Topic: Solar and storage design. Section 241 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Test Inverter Block test · solar-electrical-topology-analysis-engine-text-based / tests/test_inverter_block.py lines 1–153
  2. Test Inverter Block Public API test · solar-electrical-topology-analysis-engine-text-based / tests/test_inverter_block_public_api.py lines 1–60
  3. Test Legacy Resistance Boundaries test · solar-electrical-topology-analysis-engine-text-based / tests/test_legacy_resistance_boundaries.py lines 1–57
  4. Test Local Authority Bridge test · solar-electrical-topology-analysis-engine-text-based / tests/test_local_authority_bridge.py lines 1–125
  5. Test Microbuild Advancement test · solar-electrical-topology-analysis-engine-text-based / tests/test_microbuild_advancement.py lines 1–147
  6. Test Microbuild Evidence test · solar-electrical-topology-analysis-engine-text-based / tests/test_microbuild_evidence.py lines 1–116

Test Inverter Block

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based that uses SHA-256.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_inverter_block.py · lines 1–153 of 153 · Entry point

What it does
It tests its inputs. Defines 7 functions or classes, including test_reference_inverter_block_binds_exact_product_boundary, test_inverter_block_payload_binds_existing_authority_hashes, test_inverter_block_preserves_unresolved_input_evidence, test_inverter_block_serialisation_and_hash_are_deterministic, test_wiring_strategy_changes_block_hash_without_changing_product_boundary. Uses libraries __future__, dataclasses, json, math, pytest.
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.
Downstream impact
Used directly by 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_reference_inverter_block_binds_exact_product_boundary`, `test_inverter_block_payload_binds_existing_authority_hashes`, `test_inverter_block_preserves_unresolved_input_evidence` and 4 more.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
__future__, dataclasses, json, math, pytest, solar_topology.array, solar_topology.equipment_profiles, solar_topology.inverter_block
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_reference_inverter_block_binds_exact_product_boundary, test_inverter_block_payload_binds_existing_authority_hashes, test_inverter_block_preserves_unresolved_input_evidence, test_inverter_block_serialisation_and_hash_are_deterministic, test_wiring_strategy_changes_block_hash_without_changing_product_boundary, test_duplicate_table_bindings_and_tampered_hash_are_rejected, test_inverter_block_payload_contains_no_identity_or_standards_claims
Defines here
test_reference_inverter_block_binds_exact_product_boundary, test_inverter_block_payload_binds_existing_authority_hashes, test_inverter_block_preserves_unresolved_input_evidence, test_inverter_block_serialisation_and_hash_are_deterministic, test_wiring_strategy_changes_block_hash_without_changing_product_boundary, test_duplicate_table_bindings_and_tampered_hash_are_rejected, test_inverter_block_payload_contains_no_identity_or_standards_claims
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 tests/test_inverter_block.py:1-153 · blob b99e0879fd19ef69c00d035464bc10a249a79227 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from __future__ import annotations

from dataclasses import replace
import json
import math

import pytest

from solar_topology.array import WiringStrategy, reference_24_by_30_build
from solar_topology.equipment_profiles import (
    GENERIC_REFERENCE_EQUIPMENT_CONTRACT,
    reference_equipment_contract_hash,
)
from solar_topology.inverter_block import (
    INVERTER_BLOCK_SCHEMA_VERSION,
    REFERENCE_INVERTER_BLOCK_ID,
    InverterBlockEvidenceState,
    build_inverter_block,
    build_reference_inverter_block,
    inverter_block_hash,
    inverter_block_json,
    inverter_block_payload,
    validate_inverter_block_receipt,
)


def test_reference_inverter_block_binds_exact_product_boundary() -> None:
    receipt = build_reference_inverter_block()

    assert receipt.schema_version == INVERTER_BLOCK_SCHEMA_VERSION
    assert receipt.block_id == REFERENCE_INVERTER_BLOCK_ID
    assert receipt.module_count == 720
    assert receipt.string_count == 24
    assert receipt.modules_per_string == 30
    assert receipt.allocated_physical_input_count == 24
    assert len(receipt.table_receipts) == 1
    assert receipt.table_receipts[0].geometry.module_count == 720
    assert len(receipt.table_receipts[0].string_allocation.strings) == 24
    assert receipt.evidence_state is InverterBlockEvidenceState.INCOMPLETE_EVIDENCE
    assert len(receipt.equipment_missing_evidence) == 47
    assert receipt.receipt_hash.startswith("sha256:")
    assert len(receipt.receipt_hash) == 71

    contract = receipt.equipment_contract
    assert contract.module.rated_power_wp.value == 660.0
    assert math.isclose(contract.string_rated_power_kwp, 19.8, abs_tol=0.0)
    assert math.isclose(contract.dc_nameplate_power_kwp, 475.2, abs_tol=0.0)
    assert contract.inverter.apparent_power_kva.value == 352.0
    assert math.isclose(contract.dc_ac_nameplate_ratio, 1.35, abs_tol=0.0)


def test_inverter_block_payload_binds_existing_authority_hashes() -> None:
    table = reference_24_by_30_build()
    receipt = build_inverter_block(
        block_id=REFERENCE_INVERTER_BLOCK_ID,
        equipment_contract=GENERIC_REFERENCE_EQUIPMENT_CONTRACT,
        table_receipts=(table,),
    )
    payload = inverter_block_payload(receipt)
    binding = payload["table_receipts"][0]

    assert payload["equipment_contract"]["contract_hash"] == (
        reference_equipment_contract_hash(GENERIC_REFERENCE_EQUIPMENT_CONTRACT)
    )
    assert binding["build025_receipt_hash"] == table.receipt_hash
    assert binding["geometry_hash"] == table.geometry.geometry_hash
    assert binding["assignment_hash"] == table.string_allocation.assignment_hash
    assert binding["topology_hash"] == table.topology.topology_hash
    assert binding["input_allocation_hash"] == table.input_allocation.allocation_hash
    assert binding["routing_hash"] == table.routing.routing_hash
    assert binding["installed_length_hash"] == table.installed_length.receipt_hash


def test_inverter_block_preserves_unresolved_input_evidence() -> None:
    payload = inverter_block_payload(build_reference_inverter_block())
    authority = payload["input_authority"]
    evidence = payload["equipment_evidence"]

    assert authority["physical_dc_input_count"] == 24
    assert authority["allocated_physical_input_count"] == 24
    assert authority["mppt_count"] is None
    assert authority["mppt_count_verification_state"] == "unknown"
    assert authority["mppt_mapping_verification_states"] == ["unknown"]
    assert authority["internal_dc_topology"] == "unknown"
    assert authority["internal_dc_topology_verification_state"] == "unknown"
    assert authority["reverse_current_blocking"] == "unknown"
    assert authority["reverse_current_blocking_verification_state"] == "unknown"
    assert authority["pce_backfeed_current_a"] is None
    assert authority["pce_backfeed_verification_state"] == "unknown"
    assert authority["routing_fixture_mppt_labels_are_equipment_evidence"] is False
    assert evidence["state"] == "incomplete_evidence"
    assert evidence["missing_evidence_count"] == 47
    assert "inverter.internal_dc_topology" in evidence["missing_evidence"]
    assert "inverter.dc_inputs.dc_input_01.mppt_id" in evidence["missing_evidence"]


def test_inverter_block_serialisation_and_hash_are_deterministic() -> None:
    first = build_reference_inverter_block()
    second = build_reference_inverter_block()

    assert inverter_block_payload(first) == inverter_block_payload(second)
    assert inverter_block_json(first) == inverter_block_json(second)
    assert first.receipt_hash == second.receipt_hash
    assert inverter_block_hash(first) == first.receipt_hash
    assert json.loads(inverter_block_json(first)) == inverter_block_payload(first)
    validate_inverter_block_receipt(first)


def test_wiring_strategy_changes_block_hash_without_changing_product_boundary() -> None:
    sequential = build_reference_inverter_block(strategy=WiringStrategy.SEQUENTIAL)
    leapfrog = build_reference_inverter_block(strategy=WiringStrategy.LEAPFROG)

    assert sequential.receipt_hash != leapfrog.receipt_hash
    assert sequential.module_count == leapfrog.module_count == 720
    assert sequential.string_count == leapfrog.string_count == 24
    assert sequential.equipment_contract == leapfrog.equipment_contract
    assert (
        sequential.table_receipts[0].geometry.geometry_hash
        == leapfrog.table_receipts[0].geometry.geometry_hash
    )
    assert (
        sequential.table_receipts[0].string_allocation.assignment_hash
        == leapfrog.table_receipts[0].string_allocation.assignment_hash
    )


def test_duplicate_table_bindings_and_tampered_hash_are_rejected() -> None:
    table = reference_24_by_30_build()
    with pytest.raises(ValueError, match="table identifiers must be unique"):
        build_inverter_block(
            block_id=REFERENCE_INVERTER_BLOCK_ID,
            equipment_contract=GENERIC_REFERENCE_EQUIPMENT_CONTRACT,
            table_receipts=(table, table),
        )

    valid = build_reference_inverter_block()
    tampered = replace(valid, receipt_hash="sha256:" + "0" * 64)
    with pytest.raises(ValueError, match="hash mismatch"):
        validate_inverter_block_receipt(tampered)


def test_inverter_block_payload_contains_no_identity_or_standards_claims() -> None:
    serialised = inverter_block_json(build_reference_inverter_block()).lower()

    for prohibited in (
        "manufacturer_name",
        "project_name",
        "client_name",
        "site_name",
        "compliance_pass",
        "standards_compliant",
    ):
        assert prohibited not in serialised

Test Inverter Block Public API

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_inverter_block_public_api.py · lines 1–60 of 60 · Entry point

What it does
It tests its inputs. Defines test_inverter_block_contract_is_exposed_by_supported_package_api, test_inverter_block_exports_are_explicitly_provisional, test_top_level_inverter_block_reproduces_authority_payload_and_hash. Uses libraries __future__, solar_topology, solar_topology.inverter_block.
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.
Downstream impact
Used directly by 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_inverter_block_contract_is_exposed_by_supported_package_api`, `test_inverter_block_exports_are_explicitly_provisional` and `test_top_level_inverter_block_reproduces_authority_payload_and_hash`.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
__future__, solar_topology, solar_topology.inverter_block
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_inverter_block_contract_is_exposed_by_supported_package_api, test_inverter_block_exports_are_explicitly_provisional, test_top_level_inverter_block_reproduces_authority_payload_and_hash
Defines here
test_inverter_block_contract_is_exposed_by_supported_package_api, test_inverter_block_exports_are_explicitly_provisional, test_top_level_inverter_block_reproduces_authority_payload_and_hash
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 tests/test_inverter_block_public_api.py:1-60 · blob 165113497b95e785b35976555ee4a27ebc07b32a · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from __future__ import annotations

import solar_topology as api
import solar_topology.inverter_block as authority


PUBLIC_NAMES = (
    "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",
)

IDENTITY_NAMES = (
    "InverterBlockEvidenceState",
    "InverterBlockReceipt",
    "build_inverter_block",
    "build_reference_inverter_block",
    "inverter_block_hash",
    "inverter_block_json",
    "inverter_block_payload",
    "validate_inverter_block_receipt",
)


def test_inverter_block_contract_is_exposed_by_supported_package_api() -> None:
    assert api.INVERTER_BLOCK_SCHEMA_VERSION == authority.INVERTER_BLOCK_SCHEMA_VERSION
    assert api.REFERENCE_INVERTER_BLOCK_ID == authority.REFERENCE_INVERTER_BLOCK_ID
    for name in IDENTITY_NAMES:
        assert getattr(api, name) is getattr(authority, name)
    assert all(name in api.__all__ for name in PUBLIC_NAMES)


def test_inverter_block_exports_are_explicitly_provisional() -> None:
    classified = api.explicitly_classified_public_names()
    for name in PUBLIC_NAMES:
        assert api.public_api_status(name) is api.ApiStatus.PROVISIONAL
        assert name in classified


def test_top_level_inverter_block_reproduces_authority_payload_and_hash() -> None:
    public_receipt = api.build_reference_inverter_block()
    authority_receipt = authority.build_reference_inverter_block()

    assert public_receipt == authority_receipt
    assert api.inverter_block_payload(public_receipt) == (
        authority.inverter_block_payload(authority_receipt)
    )
    assert api.inverter_block_json(public_receipt) == (
        authority.inverter_block_json(authority_receipt)
    )
    assert api.inverter_block_hash(public_receipt) == (
        authority.inverter_block_hash(authority_receipt)
    )

Test Legacy Resistance Boundaries

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based that uses IEC 60228.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_legacy_resistance_boundaries.py · lines 1–57 of 57 · Entry point

What it does
It tests its inputs. Defines test_v6_exposes_machine_readable_lower_bound_resistance_model, test_v6_injects_visible_resistance_authority_warning, test_v9_displays_and_exports_lower_bound_resistance_model, test_legacy_warnings_do_not_claim_v10_authority. Uses libraries __future__, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'legacy'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Downstream impact
Used directly by 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_v6_exposes_machine_readable_lower_bound_resistance_model`, `test_v6_injects_visible_resistance_authority_warning`, `test_v9_displays_and_exports_lower_bound_resistance_model` and 1 more.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
__future__, pathlib
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_v6_exposes_machine_readable_lower_bound_resistance_model, test_v6_injects_visible_resistance_authority_warning, test_v9_displays_and_exports_lower_bound_resistance_model, test_legacy_warnings_do_not_claim_v10_authority
Defines here
test_v6_exposes_machine_readable_lower_bound_resistance_model, test_v6_injects_visible_resistance_authority_warning, test_v9_displays_and_exports_lower_bound_resistance_model, test_legacy_warnings_do_not_claim_v10_authority
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 tests/test_legacy_resistance_boundaries.py:1-57 · blob c7da90fecc8a2d55cfa0c342cae6b813ed069f20 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: production_core
from __future__ import annotations

from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
WARNING = (
    "Ideal bulk-copper screening calculation using nominal metallic area. "
    "Not a finished-cable declared resistance and not an IEC 60228 "
    "maximum-resistance calculation."
)


def test_v6_exposes_machine_readable_lower_bound_resistance_model() -> None:
    physics = (ROOT / "physics.generated.js").read_text(encoding="utf-8")

    assert "basis: 'ideal_bulk_estimate'" in physics
    assert "valueKind: 'lower_bound_estimate'" in physics
    assert "resistanceModel:RESISTANCE_MODEL" in physics
    assert WARNING in physics
    assert "RHO_CU20 = 1.724e-8" in physics


def test_v6_injects_visible_resistance_authority_warning() -> None:
    physics = (ROOT / "physics.generated.js").read_text(encoding="utf-8")
    index = (ROOT / "index.html").read_text(encoding="utf-8")

    assert "legacyResistanceAuthority" in physics
    assert "RESISTANCE AUTHORITY · HISTORICAL LOWER-BOUND SCREEN" in physics
    assert "./physics.generated.js" in index


def test_v9_displays_and_exports_lower_bound_resistance_model() -> None:
    page = (ROOT / "v9-sandbox" / "index.html").read_text(
        encoding="utf-8"
    )
    app = (ROOT / "v9-sandbox" / "app.js").read_text(encoding="utf-8")
    engine = (
        ROOT / "v9-sandbox" / "debug" / "engine.js"
    ).read_text(encoding="utf-8")

    assert "RESISTANCE AUTHORITY · HISTORICAL LOWER-BOUND SCREEN" in page
    assert "ideal_bulk_estimate" in page
    assert "basis: \"ideal_bulk_estimate\"" in app
    assert "valueKind: \"lower_bound_estimate\"" in app
    assert "resistanceModel: project.resistanceModel" in app
    assert "RESISTANCE_MODEL_LOWER_BOUND" in app
    assert WARNING in app
    assert "COPPER_RESISTIVITY_20C_OHM_MM2_PER_M = 0.017241" in engine


def test_legacy_warnings_do_not_claim_v10_authority() -> None:
    v6 = (ROOT / "physics.generated.js").read_text(encoding="utf-8")
    v9 = (ROOT / "v9-sandbox" / "app.js").read_text(encoding="utf-8")

    assert "authorityStatus: 'historical_reference'" in v6
    assert "authorityStatus: \"historical_reference\"" in v9

Test Local Authority Bridge

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based that checks Build Authority Bundle and Local Authority Bridge.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_local_authority_bridge.py · lines 1–125 of 125 · Entry point · pattern running_bridge (shared by 2 files)

What it does
It tests its inputs. Defines 8 functions or classes, including running_bridge, fetch, test_bridge_serves_exact_python_authority_response, test_bridge_serves_existing_studio_without_browser_recalculation_fork, test_root_redirect_and_health_contract. Uses libraries __future__, contextlib, json, pathlib, threading. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 2 files: Run Microbuild (solar-electrical-topology-analysis-engine-text-based); Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based). Reached from 4 other entry points, including Microbuild Worker Workflow (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Runner (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `running_bridge`, `fetch`, `test_bridge_serves_exact_python_authority_response` and 5 more.
Why it matters
Run by Run Microbuild and Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
Build Authority Bundle (import), Local Authority Bridge (import), __future__, contextlib, json, pathlib, threading, typing, urllib.error, urllib.request
Used by
run by Run Microbuild (script call), run by Build 025 Small Gates Workflow (workflow run)
Produces
running_bridge, fetch, test_bridge_serves_exact_python_authority_response, test_bridge_serves_existing_studio_without_browser_recalculation_fork, test_root_redirect_and_health_contract, test_head_returns_headers_without_body, test_unknown_route_is_rejected, test_bridge_rejects_invalid_strategy_and_port
Defines here
running_bridge, fetch, test_bridge_serves_exact_python_authority_response, test_bridge_serves_existing_studio_without_browser_recalculation_fork, test_root_redirect_and_health_contract, test_head_returns_headers_without_body, test_unknown_route_is_rejected, test_bridge_rejects_invalid_strategy_and_port
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 tests/test_local_authority_bridge.py:1-125 · blob ebd325c7ede09410136b2dea8e473f3a23c045ea · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from __future__ import annotations

from contextlib import contextmanager
import json
from pathlib import Path
from threading import Thread
from typing import Iterator
from urllib.error import HTTPError
from urllib.request import Request, urlopen

import pytest

from scripts.build_authority_bundle import (
    AUTHORITY_BUNDLE_PATH,
    authority_response_json,
)
from scripts.local_authority_bridge import (
    AUTHORITY_BUNDLE_ROUTE,
    HEALTH_ROUTE,
    LOCAL_AUTHORITY_BRIDGE_VERSION,
    STUDIO_ROUTE,
    create_server,
)


ROOT = Path(__file__).resolve().parents[1]


@contextmanager
def running_bridge(*, strategy: str = "leapfrog") -> Iterator[str]:
    server = create_server(host="127.0.0.1", port=0, strategy=strategy)
    thread = Thread(target=server.serve_forever, daemon=True)
    thread.start()
    host, port = server.server_address[:2]
    try:
        yield f"http://{host}:{port}"
    finally:
        server.shutdown()
        thread.join(timeout=5)
        server.server_close()


def fetch(url: str, *, method: str = "GET") -> tuple[bytes, object]:
    request = Request(url, method=method)
    with urlopen(request, timeout=10) as response:
        return response.read(), response.headers


def test_bridge_serves_exact_python_authority_response() -> None:
    expected = (authority_response_json("leapfrog") + "\n").encode("utf-8")
    committed = AUTHORITY_BUNDLE_PATH.read_bytes()

    with running_bridge() as base:
        body, headers = fetch(base + AUTHORITY_BUNDLE_ROUTE)

    payload = json.loads(body)
    assert body == expected == committed
    assert headers["Content-Type"] == "application/json; charset=utf-8"
    assert headers["Cache-Control"] == "no-store"
    assert headers["X-Authority-Response-Hash"] == payload["response_hash"]
    assert headers["X-Authority-Strategy"] == "leapfrog"


def test_bridge_serves_existing_studio_without_browser_recalculation_fork() -> None:
    with running_bridge() as base:
        index, _ = fetch(base + STUDIO_ROUTE)
        authority_view, _ = fetch(
            base + "/v10-development/authority/authority-view.js"
        )
        authority_evidence, _ = fetch(
            base + "/v10-development/authority/authority-evidence.js"
        )
        playground, _ = fetch(base + "/v10-development/topology-studio.html")

    assert index == (
        ROOT / "v10-development" / "authority" / "index.html"
    ).read_bytes()
    assert authority_view == (
        ROOT / "v10-development" / "authority" / "authority-view.js"
    ).read_bytes()
    assert authority_evidence == (
        ROOT / "v10-development" / "authority" / "authority-evidence.js"
    ).read_bytes()
    assert playground == (
        ROOT / "v10-development" / "topology-studio.html"
    ).read_bytes()


def test_root_redirect_and_health_contract() -> None:
    with running_bridge(strategy="sequential") as base:
        redirected, _ = fetch(base + "/")
        health, _ = fetch(base + HEALTH_ROUTE)

    assert b"SOLAR DC TOPOLOGY STUDIO" in redirected
    assert json.loads(health) == {
        "authority_bundle_route": AUTHORITY_BUNDLE_ROUTE,
        "bridge_version": LOCAL_AUTHORITY_BRIDGE_VERSION,
        "status": "ready",
        "strategy": "sequential",
        "studio_route": STUDIO_ROUTE,
    }


def test_head_returns_headers_without_body() -> None:
    with running_bridge() as base:
        body, headers = fetch(base + AUTHORITY_BUNDLE_ROUTE, method="HEAD")

    assert body == b""
    assert int(headers["Content-Length"]) > 1000
    assert headers["X-Authority-Strategy"] == "leapfrog"


def test_unknown_route_is_rejected() -> None:
    with running_bridge() as base:
        with pytest.raises(HTTPError) as caught:
            fetch(base + "/not-an-authority-path")

    assert caught.value.code == 404


def test_bridge_rejects_invalid_strategy_and_port() -> None:
    with pytest.raises(ValueError, match="unsupported authority strategy"):
        create_server(strategy="invented")
    with pytest.raises(ValueError, match="port must be between"):
        create_server(port=70000)

Test Microbuild Advancement

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based that checks Advance Microbuild and Check Microbuild Plan, using SHA-256.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_microbuild_advancement.py · lines 1–147 of 147 · Entry point · pattern _current_evidence (shared by 3 files)

What it does
It tests its inputs. Defines 9 functions or classes, including _active_plan, _current_evidence, test_preview_advancement_changes_only_current_next_and_evidence, test_final_advancement_closes_the_programme, test_preview_never_writes_the_source_manifest. Uses libraries __future__, copy, pytest.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Downstream impact
Used directly by 2 files: Run Microbuild (solar-electrical-topology-analysis-engine-text-based); Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based). Reached from 4 other entry points, including Microbuild Worker Workflow (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Runner (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_preview_advancement_changes_only_current_next_and_evidence`, `test_final_advancement_closes_the_programme`, `test_preview_never_writes_the_source_manifest` and 4 more.
Why it matters
Run by Run Microbuild and Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
Advance Microbuild (import), Check Microbuild Plan (import), Microbuild Evidence (import), __future__, copy, pytest
Used by
run by Run Microbuild (script call), run by Build 025 Small Gates Workflow (workflow run)
Produces
test_preview_advancement_changes_only_current_next_and_evidence, test_final_advancement_closes_the_programme, test_preview_never_writes_the_source_manifest, test_refusal_rejects_failed_stale_mismatched_or_incomplete_evidence, test_refusal_rejects_tampered_evidence_hash, test_refusal_rejects_skipped_step_even_with_plausible_evidence, test_completed_programme_cannot_advance_again
Defines here
_active_plan, _current_evidence, test_preview_advancement_changes_only_current_next_and_evidence, test_final_advancement_closes_the_programme, test_preview_never_writes_the_source_manifest, test_refusal_rejects_failed_stale_mismatched_or_incomplete_evidence, test_refusal_rejects_tampered_evidence_hash, test_refusal_rejects_skipped_step_even_with_plausible_evidence, test_completed_programme_cannot_advance_again
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 tests/test_microbuild_advancement.py:1-147 · blob ed7ed3e1d421e39d530a5f8edee81c9327237a79 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from __future__ import annotations

from copy import deepcopy

import pytest

from scripts.advance_microbuild import AdvancementError, preview_advancement
from scripts.check_microbuild_plan import DEFAULT_PLAN_PATH, load_plan, validate_plan
from scripts.microbuild_evidence import microbuild_evidence_payload


def _active_plan(step_index: int) -> dict[str, object]:
    plan = deepcopy(load_plan())
    assert step_index in {18, 19}
    for index, step in enumerate(plan["steps"]):
        if index < step_index:
            step["status"] = "passed"
        elif index == step_index:
            step["status"] = "active"
            step["evidence"] = None
        else:
            step["status"] = "planned"
            step["evidence"] = None
    plan["manifest_revision"] = step_index + 1
    plan["active_step"] = plan["steps"][step_index]["id"]
    plan["next_step"] = (
        plan["steps"][step_index + 1]["id"] if step_index < 19 else None
    )
    validate_plan(plan)
    return plan


def _current_evidence(
    plan: dict[str, object],
    **overrides: object,
) -> dict[str, object]:
    current = next(
        item for item in plan["steps"] if item["status"] in {"active", "blocked"}
    )
    values: dict[str, object] = {
        "step_id": current["id"],
        "manifest_revision": plan["manifest_revision"],
        "tested_commit": "d" * 40,
        "test_id": current["test_id"],
        "result": "pass",
        "workflow_run_id": 6000 + current["ordinal"],
        "artifact_id": 7000 + current["ordinal"],
    }
    values.update(overrides)
    return microbuild_evidence_payload(**values)


def test_preview_advancement_changes_only_current_next_and_evidence() -> None:
    source = _active_plan(18)
    original = deepcopy(source)
    preview = preview_advancement(source, _current_evidence(source))

    assert source == original
    assert preview["manifest_revision"] == 20
    assert preview["active_step"] == "MB-20"
    assert preview["next_step"] is None
    assert preview["steps"][18]["status"] == "passed"
    assert preview["steps"][18]["evidence"]["step_id"] == "MB-19"
    assert preview["steps"][19]["status"] == "active"
    assert validate_plan(preview)["programme_status"] == "active"


def test_final_advancement_closes_the_programme() -> None:
    source = _active_plan(19)
    preview = preview_advancement(source, _current_evidence(source))
    summary = validate_plan(preview)

    assert preview["manifest_revision"] == 21
    assert preview["active_step"] is None
    assert preview["next_step"] is None
    assert preview["steps"][19]["status"] == "passed"
    assert preview["steps"][19]["evidence"]["step_id"] == "MB-20"
    assert summary["programme_status"] == "completed"
    assert summary["passed_steps"] == 20


def test_preview_never_writes_the_source_manifest() -> None:
    before = DEFAULT_PLAN_PATH.read_bytes()
    source = _active_plan(19)
    preview_advancement(source, _current_evidence(source))
    after = DEFAULT_PLAN_PATH.read_bytes()

    assert after == before


@pytest.mark.parametrize(
    ("overrides", "message"),
    (
        ({"result": "fail"}, "only passing evidence"),
        ({"manifest_revision": 1}, "manifest revision"),
        ({"step_id": "MB-06"}, "evidence step"),
        ({"test_id": "advancement_preview"}, "evidence test"),
        ({"workflow_run_id": None}, "workflow_run_id is required"),
        ({"artifact_id": None}, "artifact_id is required"),
    ),
)
def test_refusal_rejects_failed_stale_mismatched_or_incomplete_evidence(
    overrides: dict[str, object],
    message: str,
) -> None:
    source = _active_plan(19)
    original = deepcopy(source)
    before = DEFAULT_PLAN_PATH.read_bytes()

    with pytest.raises(AdvancementError, match=message):
        preview_advancement(source, _current_evidence(source, **overrides))

    assert source == original
    assert DEFAULT_PLAN_PATH.read_bytes() == before


def test_refusal_rejects_tampered_evidence_hash() -> None:
    source = _active_plan(19)
    original = deepcopy(source)
    evidence = _current_evidence(source)
    evidence["evidence_hash"] = "sha256:" + "0" * 64

    with pytest.raises(AdvancementError, match="evidence hash mismatch"):
        preview_advancement(source, evidence)

    assert source == original


def test_refusal_rejects_skipped_step_even_with_plausible_evidence() -> None:
    source = _active_plan(18)
    skipped = source["steps"][19]
    evidence = _current_evidence(
        source,
        step_id=skipped["id"],
        test_id=skipped["test_id"],
    )

    with pytest.raises(AdvancementError, match="evidence step"):
        preview_advancement(source, evidence)


def test_completed_programme_cannot_advance_again() -> None:
    completed = load_plan()
    active = _active_plan(19)

    with pytest.raises(AdvancementError, match="completed programme cannot advance"):
        preview_advancement(completed, _current_evidence(active))

Test Microbuild Evidence

A test in the tests folder of Solar Electrical Topology Analysis Engine Text Based that checks Check Microbuild Plan and Microbuild Evidence.

testsolar-electrical-topology-analysis-engine-text-based / tests/test_microbuild_evidence.py · lines 1–116 of 116 · Entry point

What it does
It tests its inputs. Defines 8 functions or classes, including _base, _active_final_plan, test_evidence_hash_is_deterministic_and_excludes_runtime_metadata, test_engineering_core_changes_evidence_hash, test_active_plan_evidence_uses_current_step_and_test. Uses libraries __future__, copy, json, pathlib, pytest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage sub33kv_design (repository name word 'solar'): inside-the-fence electrical and civil design below 33kV, which Ventus Ltd states is within its commercial execution boundary.
Inputs & outputs
In: JSON file active-plan.json.
Downstream impact
Used directly by 2 files: Run Microbuild (solar-electrical-topology-analysis-engine-text-based); Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based). Reached from 4 other entry points, including Microbuild Worker Workflow (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Runner (solar-electrical-topology-analysis-engine-text-based); Test Microbuild Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_evidence_hash_is_deterministic_and_excludes_runtime_metadata`, `test_engineering_core_changes_evidence_hash`, `test_active_plan_evidence_uses_current_step_and_test` and 3 more.
Why it matters
Run by Run Microbuild and Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
Check Microbuild Plan (import), Microbuild Evidence (import), __future__, copy, json, pathlib, pytest
Used by
run by Run Microbuild (script call), run by Build 025 Small Gates Workflow (workflow run)
Produces
test_evidence_hash_is_deterministic_and_excludes_runtime_metadata, test_engineering_core_changes_evidence_hash, test_active_plan_evidence_uses_current_step_and_test, test_completed_plan_refuses_a_new_evidence_record, test_invalid_core_and_runtime_values_are_rejected, test_worker_uses_canonical_evidence_writer_only_while_active
Defines here
_base, _active_final_plan, test_evidence_hash_is_deterministic_and_excludes_runtime_metadata, test_engineering_core_changes_evidence_hash, test_active_plan_evidence_uses_current_step_and_test, test_completed_plan_refuses_a_new_evidence_record, test_invalid_core_and_runtime_values_are_rejected, test_worker_uses_canonical_evidence_writer_only_while_active
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 tests/test_microbuild_evidence.py:1-116 · blob 26dfaa7d30304ca4ca49847a814dade12d07d8a2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
from __future__ import annotations

from copy import deepcopy
import json
from pathlib import Path

import pytest

from scripts.check_microbuild_plan import load_plan, validate_plan
from scripts.microbuild_evidence import (
    EvidenceValidationError,
    canonical_json,
    evidence_from_active_plan,
    microbuild_evidence_hash,
    microbuild_evidence_payload,
)


ROOT = Path(__file__).resolve().parents[1]


def _base(**overrides: object) -> dict[str, object]:
    values: dict[str, object] = {
        "step_id": "MB-05",
        "manifest_revision": 5,
        "tested_commit": "a" * 40,
        "test_id": "microbuild_evidence",
        "result": "pass",
        "workflow_run_id": 123,
        "artifact_id": 456,
    }
    values.update(overrides)
    return values


def _active_final_plan(path: Path) -> Path:
    plan = deepcopy(load_plan())
    plan["manifest_revision"] = 20
    plan["active_step"] = "MB-20"
    plan["next_step"] = None
    plan["steps"][-1]["status"] = "active"
    plan["steps"][-1]["evidence"] = None
    path.write_text(canonical_json(plan) + "\n", encoding="utf-8")
    return path


def test_evidence_hash_is_deterministic_and_excludes_runtime_metadata() -> None:
    first = microbuild_evidence_payload(**_base())
    second = microbuild_evidence_payload(
        **_base(workflow_run_id=999, artifact_id=1000)
    )

    assert first["core"] == second["core"]
    assert first["evidence_hash"] == second["evidence_hash"]
    assert first["runtime"] != second["runtime"]
    assert canonical_json(first) == canonical_json(
        microbuild_evidence_payload(**_base())
    )
    assert first["evidence_hash"] == microbuild_evidence_hash(first["core"])


def test_engineering_core_changes_evidence_hash() -> None:
    first = microbuild_evidence_payload(**_base())
    changed = microbuild_evidence_payload(**_base(tested_commit="b" * 40))

    assert first["evidence_hash"] != changed["evidence_hash"]


def test_active_plan_evidence_uses_current_step_and_test(tmp_path: Path) -> None:
    plan_path = _active_final_plan(tmp_path / "active-plan.json")
    summary = validate_plan(load_plan(plan_path))
    payload = evidence_from_active_plan(
        tested_commit="c" * 40,
        result="pass",
        workflow_run_id=12,
        plan_path=plan_path,
    )

    assert payload["core"]["step_id"] == summary["active_step"]
    assert payload["core"]["manifest_revision"] == summary["manifest_revision"]
    assert payload["core"]["test_id"] == summary["active_test_id"]
    assert payload["runtime"]["workflow_run_id"] == 12
    assert payload["runtime"]["artifact_id"] is None


def test_completed_plan_refuses_a_new_evidence_record() -> None:
    with pytest.raises(
        EvidenceValidationError,
        match="completed programme has no active step",
    ):
        evidence_from_active_plan(
            tested_commit="c" * 40,
            result="pass",
            workflow_run_id=12,
        )


def test_invalid_core_and_runtime_values_are_rejected() -> None:
    with pytest.raises(EvidenceValidationError, match="invalid tested_commit"):
        microbuild_evidence_payload(**_base(tested_commit="not-a-sha"))
    with pytest.raises(EvidenceValidationError, match="result must be pass or fail"):
        microbuild_evidence_payload(**_base(result="maybe"))
    with pytest.raises(EvidenceValidationError, match="artifact_id must be positive"):
        microbuild_evidence_payload(**_base(artifact_id=0))


def test_worker_uses_canonical_evidence_writer_only_while_active() -> None:
    workflow = (ROOT / ".github/workflows/microbuild-worker.yml").read_text(
        encoding="utf-8"
    )

    assert "python scripts/microbuild_evidence.py" in workflow
    assert '--tested-commit "$GITHUB_SHA"' in workflow
    assert '--workflow-run-id "$GITHUB_RUN_ID"' in workflow
    assert "programme_status != 'completed'" in workflow
    assert "Path(\".microbuild/evidence/latest.json\")" not in workflow