GLOBALGRID2050 / EXPLORE CODE

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

Test Circuit Calculations and 3 more files

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

570 lines of Python from solar-electrical-topology-analysis-engine-text-based, in 4 files. Topic: Solar and storage design. Section 238 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 Circuit Calculations test · solar-electrical-topology-analysis-engine-text-based / tests/test_circuit_calculations.py lines 1–275
  2. Test Contradictions test · solar-electrical-topology-analysis-engine-text-based / tests/test_contradictions.py lines 1–95
  3. Test Diagnostic Public API test · solar-electrical-topology-analysis-engine-text-based / tests/test_diagnostic_public_api.py lines 1–20
  4. Test Diagnostics test · solar-electrical-topology-analysis-engine-text-based / tests/test_diagnostics.py lines 1–180

Test Circuit Calculations

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_circuit_calculations.py · lines 1–275 of 275 · Entry point · pattern _model_and_traversal (shared by 3 files)

What it does
It tests its inputs. Defines 9 functions or classes, including _rows, _model_and_traversal, _current_evidence, test_provenance_vocabularies_reconcile_without_silent_promotion, test_complete_circuit_known_answer_includes_all_series_elements. Uses libraries dataclasses, inspect, 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 steady_state_cross_language_v1.json.
Downstream impact
Used directly by 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_provenance_vocabularies_reconcile_without_silent_promotion`, `test_complete_circuit_known_answer_includes_all_series_elements`, `test_calculation_receipt_is_deterministic` and 3 more.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
dataclasses, inspect, json, pathlib, pytest, solar_topology.calculation_receipts, solar_topology.cartridges, solar_topology.circuit
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_provenance_vocabularies_reconcile_without_silent_promotion, test_complete_circuit_known_answer_includes_all_series_elements, test_calculation_receipt_is_deterministic, test_calculation_refuses_invalid_or_forged_traversal, test_calculation_api_has_no_free_total_length_input, test_python_matches_shared_javascript_formula_fixture
Defines here
_rows, _model_and_traversal, _current_evidence, test_provenance_vocabularies_reconcile_without_silent_promotion, test_complete_circuit_known_answer_includes_all_series_elements, test_calculation_receipt_is_deterministic, test_calculation_refuses_invalid_or_forged_traversal, test_calculation_api_has_no_free_total_length_input, test_python_matches_shared_javascript_formula_fixture
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_circuit_calculations.py:1-275 · blob 7cb2af605509233bd0d048753e1544561d703792 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: sub33kv_design · users: EPC_contractor, ICP_grid_engineer · canonical: production_core
import dataclasses
import inspect
import json
from pathlib import Path

import pytest

from solar_topology.calculation_receipts import (
    calculation_receipt_hash,
    calculation_receipt_json,
)
from solar_topology.cartridges import (
    LeapfrogCartridge,
    SequentialCartridge,
)
from solar_topology.circuit import EvidenceClass
from solar_topology.circuit_adapters import (
    adapt_segment_chain_to_circuit,
    circuit_boundary_terminal_ids,
    source_segment_ids,
)
from solar_topology.circuit_calculations import (
    calculate_complete_circuit,
)
from solar_topology.circuit_traversal import (
    TraversalIssue,
    verify_ordered_circuit,
)
from solar_topology.evidence import (
    VerificationState,
    canonical_evidence_descriptor,
    javascript_provenance_descriptor,
    segment_provenance_descriptor,
)
from solar_topology.segments import TopologyInputs, archetype_strings


FIXTURE_PATH = (
    Path(__file__).parents[1]
    / "v10-development"
    / "fixtures"
    / "steady_state_cross_language_v1.json"
)


def _rows(cartridge, *, modules=30):
    inputs = TopologyInputs(
        modules_per_string=modules,
        inverter_count=1,
        total_site_string_count=24,
        positive_factory_lead_m=1.4,
        negative_factory_lead_m=1.4,
    )
    definition = archetype_strings(inputs)[0]
    return cartridge.build_segments(inputs, definition)


def _model_and_traversal(rows):
    model = adapt_segment_chain_to_circuit(rows)
    start, end = circuit_boundary_terminal_ids(model)
    traversal = verify_ordered_circuit(
        model,
        start,
        end,
        expected_segment_ids=source_segment_ids(rows),
    )
    assert traversal.valid
    return model, traversal


def _current_evidence():
    return canonical_evidence_descriptor(
        EvidenceClass.MANUFACTURER_DECLARED,
        verification_state=VerificationState.CANDIDATE,
        source_reference="known_answer_current",
    )


def test_provenance_vocabularies_reconcile_without_silent_promotion():
    defaulted = segment_provenance_descriptor("defaulted")
    datasheet = javascript_provenance_descriptor("datasheet")
    standards = javascript_provenance_descriptor("standardsDerived")
    hypothesis = javascript_provenance_descriptor("researchHypothesis")

    assert defaulted.evidence_class == EvidenceClass.ASSUMED
    assert defaulted.source_value == "defaulted"
    assert datasheet.evidence_class == EvidenceClass.MANUFACTURER_DECLARED
    assert standards.evidence_class == EvidenceClass.DERIVED
    assert (
        standards.verification_state
        == VerificationState.STANDARDS_REVIEW_REQUIRED
    )
    assert hypothesis.evidence_class == EvidenceClass.ASSUMED
    assert (
        hypothesis.verification_state
        == VerificationState.RESEARCH_HYPOTHESIS
    )


@pytest.mark.parametrize(
    ("cartridge", "expected_resistance", "expected_drop", "expected_loss"),
    (
        (
            SequentialCartridge(),
            0.78836961445,
            13.6782128107075,
            237.316992265775,
        ),
        (
            LeapfrogCartridge(),
            0.627462739,
            10.88647852165,
            188.880402350628,
        ),
    ),
)
def test_complete_circuit_known_answer_includes_all_series_elements(
    cartridge,
    expected_resistance,
    expected_drop,
    expected_loss,
):
    rows = _rows(cartridge)
    model, traversal = _model_and_traversal(rows)

    receipt = calculate_complete_circuit(
        model,
        traversal,
        current_a=17.35,
        current_evidence=_current_evidence(),
    )

    assert receipt.ordered_segment_ids == tuple(
        row.segment_id for row in rows
    )
    assert receipt.total_conductor_length_m == pytest.approx(
        sum(row.conductor_length_m for row in rows)
    )
    assert receipt.total_resistance_ohm == pytest.approx(
        expected_resistance,
        rel=1e-12,
    )
    assert receipt.voltage_drop_v == pytest.approx(
        expected_drop,
        rel=1e-12,
    )
    assert receipt.resistive_loss_w == pytest.approx(
        expected_loss,
        rel=1e-12,
    )
    assert receipt.total_connector_resistance_ohm > 0
    assert receipt.input_evidence_floor == EvidenceClass.ASSUMED
    assert receipt.segment_results[0].segment_id == rows[0].segment_id
    assert receipt.segment_results[-1].segment_id == rows[-1].segment_id
    assert calculation_receipt_hash(receipt).startswith("sha256:")


def test_calculation_receipt_is_deterministic():
    rows = _rows(SequentialCartridge(), modules=6)
    first_model, first_traversal = _model_and_traversal(rows)
    second_model, second_traversal = _model_and_traversal(
        tuple(reversed(rows))
    )

    first = calculate_complete_circuit(
        first_model,
        first_traversal,
        current_a=10.0,
        current_evidence=_current_evidence(),
    )
    second = calculate_complete_circuit(
        second_model,
        second_traversal,
        current_a=10.0,
        current_evidence=_current_evidence(),
    )

    assert calculation_receipt_json(first) == calculation_receipt_json(
        second
    )
    assert calculation_receipt_hash(first) == calculation_receipt_hash(
        second
    )


def test_calculation_refuses_invalid_or_forged_traversal():
    rows = _rows(SequentialCartridge(), modules=6)
    model, traversal = _model_and_traversal(rows)
    invalid = dataclasses.replace(
        traversal,
        issues=(
            TraversalIssue(
                code="TEST_INVALID",
                message="test-invalid traversal",
            ),
        ),
    )

    with pytest.raises(
        ValueError,
        match="invalid ordered circuit traversal",
    ):
        calculate_complete_circuit(
            model,
            invalid,
            current_a=10.0,
            current_evidence=_current_evidence(),
        )

    forged = dataclasses.replace(
        traversal,
        ordered_connection_ids=tuple(
            reversed(traversal.ordered_connection_ids)
        ),
    )
    with pytest.raises(
        ValueError,
        match="differs from independently derived order",
    ):
        calculate_complete_circuit(
            model,
            forged,
            current_a=10.0,
            current_evidence=_current_evidence(),
        )


def test_calculation_api_has_no_free_total_length_input():
    parameters = inspect.signature(
        calculate_complete_circuit
    ).parameters
    assert "total_length" not in parameters
    assert "route_length" not in parameters
    assert "user_length" not in parameters


def test_python_matches_shared_javascript_formula_fixture():
    fixture = json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))

    for case in fixture["cases"]:
        rows = list(_rows(SequentialCartridge(), modules=1))
        source = rows[0]
        one_segment = dataclasses.replace(
            source,
            segment_index=1,
            segment_id=f"fixture:{case['id']}",
            from_node_id="fixture:start",
            to_node_id="fixture:end",
            conductor_length_m=case["length_m"],
            r20_ohm_per_m=case["resistance_ohm_per_m"],
            temperature_c=20.0,
            connector_count=0,
            connector_resistance_ohm_each=0.0,
            warnings="",
        )
        model, traversal = _model_and_traversal((one_segment,))
        receipt = calculate_complete_circuit(
            model,
            traversal,
            current_a=case["current_a"],
            current_evidence=_current_evidence(),
        )

        assert receipt.total_resistance_ohm == pytest.approx(
            case["expected"]["resistance_ohm"],
            rel=1e-12,
        )
        assert receipt.voltage_drop_v == pytest.approx(
            case["expected"]["voltage_drop_v"],
            rel=1e-12,
        )
        assert receipt.resistive_loss_w == pytest.approx(
            case["expected"]["resistive_loss_w"],
            rel=1e-12,
        )

Test Contradictions

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

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

What it does
It tests its inputs. Defines 7 functions or classes, including _subject, _claim, test_register_is_deterministic_under_input_reordering, test_equal_values_are_not_a_contradiction, test_closed_contradiction_requires_resolution_note. Uses libraries pytest, solar_topology.contradictions, solar_topology.identifiers.
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 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_register_is_deterministic_under_input_reordering`, `test_equal_values_are_not_a_contradiction`, `test_closed_contradiction_requires_resolution_note` and 2 more.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
pytest, solar_topology.contradictions, solar_topology.identifiers
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_register_is_deterministic_under_input_reordering, test_equal_values_are_not_a_contradiction, test_closed_contradiction_requires_resolution_note, test_duplicate_claim_pair_is_rejected_even_when_reversed, test_unresolved_filter_honours_severity_threshold
Defines here
_subject, _claim, test_register_is_deterministic_under_input_reordering, test_equal_values_are_not_a_contradiction, test_closed_contradiction_requires_resolution_note, test_duplicate_claim_pair_is_rejected_even_when_reversed, test_unresolved_filter_honours_severity_threshold
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_contradictions.py:1-95 · blob 603223c0ea4efaaee9ec08f6eff8f0c62e655067 · 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
import pytest

from solar_topology.contradictions import (
    Claim,
    Contradiction,
    ContradictionSeverity,
    ContradictionStatus,
    build_contradiction_register,
    contradiction_register_hash,
    contradiction_register_json,
    unresolved_contradictions,
)
from solar_topology.identifiers import EntityLevel, project_id


def _subject():
    project = project_id("public-study")
    site = project.child(EntityLevel.SITE, "site-01")
    return site.child(EntityLevel.SYSTEM, "dc-array")


def _claim(claim_id, value, source_id="public-source"):
    return Claim(
        claim_id=claim_id,
        subject_identifier=_subject(),
        predicate="string-count",
        value=value,
        unit="count",
        source_id=source_id,
    )


def test_register_is_deterministic_under_input_reordering():
    first = Contradiction(
        "ctr-002", _claim("claim-b", 24), _claim("claim-c", 32),
        ContradictionSeverity.MATERIAL,
    )
    second = Contradiction(
        "ctr-001", _claim("claim-a", 24), _claim("claim-d", 28),
        ContradictionSeverity.INFORMATIONAL,
    )
    a = build_contradiction_register([first, second])
    b = build_contradiction_register([second, first])
    assert contradiction_register_json(a) == contradiction_register_json(b)
    assert contradiction_register_hash(a) == contradiction_register_hash(b)


def test_equal_values_are_not_a_contradiction():
    with pytest.raises(ValueError, match="equal claim values"):
        Contradiction(
            "ctr-001", _claim("claim-a", 24), _claim("claim-b", 24),
            ContradictionSeverity.MATERIAL,
        )


def test_closed_contradiction_requires_resolution_note():
    with pytest.raises(ValueError, match="resolution_note"):
        Contradiction(
            "ctr-001", _claim("claim-a", 24), _claim("claim-b", 32),
            ContradictionSeverity.MATERIAL,
            status=ContradictionStatus.RESOLVED,
        )


def test_duplicate_claim_pair_is_rejected_even_when_reversed():
    left = _claim("claim-a", 24)
    right = _claim("claim-b", 32)
    with pytest.raises(ValueError, match="claim pair"):
        build_contradiction_register([
            Contradiction("ctr-001", left, right, ContradictionSeverity.MATERIAL),
            Contradiction("ctr-002", right, left, ContradictionSeverity.MATERIAL),
        ])


def test_unresolved_filter_honours_severity_threshold():
    register = build_contradiction_register([
        Contradiction(
            "ctr-info", _claim("claim-a", 24), _claim("claim-b", 25),
            ContradictionSeverity.INFORMATIONAL,
        ),
        Contradiction(
            "ctr-safety", _claim("claim-c", 24), _claim("claim-d", 32),
            ContradictionSeverity.SAFETY_CRITICAL,
        ),
        Contradiction(
            "ctr-resolved", _claim("claim-e", 24), _claim("claim-f", 30),
            ContradictionSeverity.MATERIAL,
            status=ContradictionStatus.RESOLVED,
            resolution_note="public survey superseded the earlier estimate",
        ),
    ])
    result = unresolved_contradictions(
        register, minimum_severity=ContradictionSeverity.MATERIAL
    )
    assert [item.contradiction_id for item in result] == ["ctr-safety"]

Test Diagnostic 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_diagnostic_public_api.py · lines 1–20 of 20 · Entry point

What it does
It tests its inputs. Defines test_diagnostic_and_applicability_public_api_is_exported. Uses libraries solar_topology.
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 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_diagnostic_and_applicability_public_api_is_exported`.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
solar_topology
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_diagnostic_and_applicability_public_api_is_exported
Defines here
test_diagnostic_and_applicability_public_api_is_exported
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_diagnostic_public_api.py:1-20 · blob f0d5f638faba00984c946e3790eb8dee5e2650d9 · 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
import solar_topology as api


def test_diagnostic_and_applicability_public_api_is_exported():
    required = {
        "Diagnostic",
        "DiagnosticReport",
        "DiagnosticSeverity",
        "StudyCoverage",
        "StudyState",
        "build_diagnostic_report",
        "circuit_validation_diagnostics",
        "AcceptanceCriterion",
        "StudyApplicability",
        "StudyKind",
        "build_study_applicability",
        "evaluate_criterion",
    }
    missing = sorted(name for name in required if not hasattr(api, name))
    assert not missing, missing

Test Diagnostics

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_diagnostics.py · lines 1–180 of 180 · Entry point · pattern test_public_payload_omits_internal_detail_and_is_deterministic (shared by 2 files)

What it does
It tests its inputs. Defines 9 functions or classes, including test_accumulates_sorts_and_counts_diagnostics, test_public_payload_omits_internal_detail_and_is_deterministic, test_not_checked_and_blocked_require_reasons, test_exception_bridge_does_not_publish_internal_exception_detail, test_circuit_validation_adapter_preserves_all_issues. Uses libraries json, pytest, solar_topology.circuit_validation, solar_topology.diagnostic_adapters, solar_topology.diagnostics.
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: Excel file source.xlsx.
Downstream impact
Used directly by 1 file: Build 025 Small Gates Workflow (solar-electrical-topology-analysis-engine-text-based).
What it achieves
Defines `test_accumulates_sorts_and_counts_diagnostics`, `test_public_payload_omits_internal_detail_and_is_deterministic`, `test_not_checked_and_blocked_require_reasons` and 5 more.
Why it matters
Run by Build 025 Small Gates Workflow.
Application
solar-electrical-topology-analysis-engine-text-based · tests · test
Uses
json, pytest, solar_topology.circuit_validation, solar_topology.diagnostic_adapters, solar_topology.diagnostics, solar_topology.study_applicability
Used by
run by Build 025 Small Gates Workflow (workflow run)
Produces
test_accumulates_sorts_and_counts_diagnostics, test_public_payload_omits_internal_detail_and_is_deterministic, test_not_checked_and_blocked_require_reasons, test_exception_bridge_does_not_publish_internal_exception_detail, test_circuit_validation_adapter_preserves_all_issues, test_applicability_distinguishes_missing_inputs_from_no_criterion, test_criterion_evaluation_is_unit_safe_and_source_declared, test_duplicate_diagnostics_and_coverage_are_rejected
Defines here
test_accumulates_sorts_and_counts_diagnostics, test_public_payload_omits_internal_detail_and_is_deterministic, test_not_checked_and_blocked_require_reasons, test_exception_bridge_does_not_publish_internal_exception_detail, test_circuit_validation_adapter_preserves_all_issues, _criterion, test_applicability_distinguishes_missing_inputs_from_no_criterion, test_criterion_evaluation_is_unit_safe_and_source_declared, test_duplicate_diagnostics_and_coverage_are_rejected
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_diagnostics.py:1-180 · blob 1ff21bad5a84715e3f6328ce004df3716f98836e · 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
import json

import pytest

from solar_topology.circuit_validation import (
    CircuitValidationResult,
    IssueSeverity,
    ValidationIssue,
)
from solar_topology.diagnostic_adapters import (
    circuit_validation_diagnostics,
    coverage_for_unperformed_studies,
)
from solar_topology.diagnostics import (
    Diagnostic,
    DiagnosticCategory,
    DiagnosticSeverity,
    StudyCoverage,
    StudyState,
    build_diagnostic_report,
    diagnostic_from_exception,
    diagnostic_report_hash,
    diagnostic_report_json,
    require_non_blocking,
)
from solar_topology.study_applicability import (
    AcceptanceCriterion,
    CriterionOperator,
    StudyKind,
    applicability_coverage,
    build_study_applicability,
    evaluate_criterion,
)


def test_accumulates_sorts_and_counts_diagnostics():
    report = build_diagnostic_report(
        [
            Diagnostic(
                code="Z.WARNING",
                severity=DiagnosticSeverity.WARNING,
                category=DiagnosticCategory.EVIDENCE,
                message="candidate evidence",
            ),
            Diagnostic(
                code="A.ERROR",
                severity=DiagnosticSeverity.ERROR,
                category=DiagnosticCategory.TOPOLOGY,
                message="broken topology",
            ),
        ]
    )
    assert [item.code for item in report.diagnostics] == ["A.ERROR", "Z.WARNING"]
    assert report.blocking
    assert report.error_count == 1
    assert report.warning_count == 1
    assert diagnostic_report_hash(report).startswith("sha256:")
    with pytest.raises(ValueError, match="A.ERROR"):
        require_non_blocking(report)


def test_public_payload_omits_internal_detail_and_is_deterministic():
    diagnostic = Diagnostic(
        code="PUBLIC.SAFE",
        severity=DiagnosticSeverity.INFO,
        category=DiagnosticCategory.PUBLICATION,
        message="public message",
        public_detail="safe detail",
        internal_detail="NDA source path must not escape",
    )
    first = build_diagnostic_report([diagnostic])
    second = build_diagnostic_report(reversed(first.diagnostics))
    public_payload = json.loads(diagnostic_report_json(first, public=True))
    assert "internal_detail" not in public_payload["diagnostics"][0]
    assert diagnostic_report_json(first) == diagnostic_report_json(second)


def test_not_checked_and_blocked_require_reasons():
    with pytest.raises(ValueError, match="require a reason"):
        StudyCoverage("ampacity", StudyState.NOT_CHECKED)
    entries = coverage_for_unperformed_studies(
        [("ampacity", "no current-carrying-capacity criterion supplied")]
    )
    assert entries[0].state is StudyState.NOT_CHECKED


def test_exception_bridge_does_not_publish_internal_exception_detail():
    item = diagnostic_from_exception(
        ValueError("private/path/source.xlsx"),
        code="LEGACY.FAIL",
        category=DiagnosticCategory.INTERNAL,
        public_message="legacy calculation failed",
    )
    report = build_diagnostic_report([item])
    public_json = diagnostic_report_json(report, public=True)
    assert "private/path" not in public_json
    assert "legacy calculation failed" in public_json


def test_circuit_validation_adapter_preserves_all_issues():
    result = CircuitValidationResult(
        (
            ValidationIssue("DUPLICATE_OBJECT_ID", "duplicate", object_id="o1"),
            ValidationIssue(
                "ASSUMED_GEOMETRY",
                "geometry is assumed",
                severity=IssueSeverity.WARNING,
                object_id="o2",
            ),
        )
    )
    report = circuit_validation_diagnostics(result, subject_id="model-1")
    assert len(report.diagnostics) == 2
    assert report.coverage[0].state is StudyState.CHECKED_FAIL
    assert report.blocking


def _criterion():
    return AcceptanceCriterion(
        criterion_id="criterion:string-voltage",
        study_kind=StudyKind.COLD_VOC,
        operator=CriterionOperator.MAXIMUM,
        threshold=1500.0,
        unit="V",
        source_id="public:system-voltage-basis",
        method_reference="cold-voc-method-v1",
        public_support=True,
    )


def test_applicability_distinguishes_missing_inputs_from_no_criterion():
    blocked = build_study_applicability(
        StudyKind.COLD_VOC,
        required_input_ids=("beta_voc", "cold_temperature", "module_voc"),
        available_input_ids=("module_voc",),
        criterion=_criterion(),
    )
    assert not blocked.executable
    assert applicability_coverage(blocked).state is StudyState.BLOCKED

    ready_without_verdict = build_study_applicability(
        StudyKind.LOOP_GEOMETRY,
        required_input_ids=("ordered_segments",),
        available_input_ids=("ordered_segments",),
    )
    assert ready_without_verdict.executable
    assert not ready_without_verdict.verdict_capable
    assert applicability_coverage(ready_without_verdict).state is StudyState.NOT_CHECKED


def test_criterion_evaluation_is_unit_safe_and_source_declared():
    criterion = _criterion()
    assert evaluate_criterion(1499.0, "V", criterion)
    assert not evaluate_criterion(1501.0, "V", criterion)
    with pytest.raises(ValueError, match="unit"):
        evaluate_criterion(1.5, "kV", criterion)
    with pytest.raises(ValueError, match="source_id"):
        AcceptanceCriterion(
            criterion_id="bad",
            study_kind=StudyKind.AMPACITY,
            operator=CriterionOperator.MINIMUM,
            threshold=20.0,
            unit="A",
            source_id="",
            method_reference="method",
        )


def test_duplicate_diagnostics_and_coverage_are_rejected():
    item = Diagnostic(
        code="DUP.TEST",
        severity=DiagnosticSeverity.WARNING,
        category=DiagnosticCategory.INPUT,
        message="same",
    )
    with pytest.raises(ValueError, match="duplicate diagnostics"):
        build_diagnostic_report([item, item])
    coverage = StudyCoverage("study", StudyState.CHECKED_PASS)
    with pytest.raises(ValueError, match="duplicate study coverage"):
        build_diagnostic_report(coverage=[coverage, coverage])