In this section
- Test Document Ceiling test · companies / tests/test_202608272016_document_ceiling.py lines 1–258
- Test Company Identity and Grains test · companies / tests/test_202608272120_company_identity_and_grains.py lines 1–442
Test Document Ceiling
A test in the tests folder of Companies that uses SHA-256. It is built from the load step (`load`), the rejected step (`rejected`) and the member step (`member`).
testcompanies / tests/test_202608272016_document_ceiling.py · lines 1–258 of 258 · version 2026-08-27 20:16 · Entry point · pattern member (shared by 2 files)
- What it does
- It tests its inputs. Defines 13 functions or classes, including load, rejected, member, counters, test_generation_boundary. Uses libraries __future__, hashlib, importlib.util, json, shutil. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file 202608272016-bounded-companies-house-candidate.json; Parquet file copied.parquet; DuckDB queries.
- Downstream impact
- Used directly by 1 file: Bounded Companies House Candidate (companies).
- What it achieves
- Deterministic boundary contract for the `iXBRL` ceiling repair.
- Why it matters
- Run by Bounded Companies House Candidate.
- Application
- companies · tests · test
- Uses
- __future__, hashlib, importlib.util, json, shutil, tempfile, zipfile, decimal
- Used by
- run by Bounded Companies House Candidate (workflow run)
- Produces
- load, rejected, member, counters, test_generation_boundary, test_source_manifest, test_document_ceiling, test_inherited_bomb_guards, analytical_record, analytical_fixture, test_analytical_contract, test_company_number_domain_and_rights_separation
- Defines here
- load, rejected, member, counters, test_generation_boundary, test_source_manifest, test_document_ceiling, test_inherited_bomb_guards, analytical_record, analytical_fixture, test_analytical_contract, test_company_number_domain_and_rights_separation, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- companies@1371da4d0166eef13f98fc3847c5bb1e38e8f571 tests/test_202608272016_document_ceiling.py:1-258 · blob e7b2fef4bb9c7743d361bbe8904efcc91e917a12 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""Deterministic boundary contract for the 202608272016 iXBRL ceiling repair."""
from __future__ import annotations
import hashlib
import importlib.util
import json
import shutil
import tempfile
import zipfile
from decimal import Decimal
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def load(name: str, relative: str):
spec = importlib.util.spec_from_file_location(name, ROOT / relative)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
spec.loader.exec_module(module)
return module
EXTRACT = load("companies_extract_202608272016", "build/python/202608272016-extract-bounded-accounts.py")
PLAN = load("companies_plan_202608272016", "build/python/202608272016-freeze-companies-house-plan.py")
DOWNLOAD = load("companies_download_202608272016", "build/python/202608272016-download-planned-archive.py")
VERIFY = load("companies_verify_202608272016", "build/python/202608272016-verify-companies-house-candidate.py")
def rejected(callable_, contains: str) -> None:
try:
callable_()
except RuntimeError as exc:
assert contains.lower() in str(exc).lower(), (contains, str(exc))
return
raise AssertionError(f"Expected RuntimeError containing {contains!r}")
def member(name: str, size: int, compressed: int | None = None) -> zipfile.ZipInfo:
info = zipfile.ZipInfo(name)
info.file_size = size
info.compress_size = size if compressed is None else compressed
return info
def counters(expanded: int = 0) -> dict:
return {"members": 0, "expanded_bytes": expanded}
def test_generation_boundary() -> None:
expected_parent = "cc61a74edea5321b9654a22af2e589a56c6dc19b"
assert PLAN.GENERATION == DOWNLOAD.GENERATION == VERIFY.GENERATION == "202608272016"
assert PLAN.BASE_COMMIT == DOWNLOAD.BASE_COMMIT == VERIFY.BASE_COMMIT == expected_parent
assert PLAN.PREVIOUS.GENERATION == DOWNLOAD.PREVIOUS.GENERATION == VERIFY.PREVIOUS.GENERATION == "202608272016"
assert PLAN.PREVIOUS.BASE_COMMIT == DOWNLOAD.PREVIOUS.BASE_COMMIT == VERIFY.PREVIOUS.BASE_COMMIT == expected_parent
assert VERIFY.PREVIOUS.FIXED_GENERATED_AT == "2026-08-27T19:16:00Z"
assert VERIFY.DUCKDB_VERSION == "1.3.2"
assert VERIFY.REFERENCE_REPOSITORY == "Ventusltd/data-gb-electricity"
assert VERIFY.REFERENCE_COMMIT == "7c492745c974f6b8610cb1209f996b1553abb498"
def test_source_manifest() -> None:
path = ROOT / "manifests/202608272016-bounded-companies-house-candidate.json"
manifest = json.loads(path.read_text())
assert manifest["generation"] == "202608272016"
assert manifest["base_commit"] == "cc61a74edea5321b9654a22af2e589a56c6dc19b"
assert manifest["deployment_state"] == "not-authorised"
assert manifest["limits"]["maximum_document_bytes"] == EXTRACT.MAX_DOCUMENT_BYTES
assert manifest["limits"]["maximum_other_member_bytes"] == EXTRACT.MAX_OTHER_MEMBER_BYTES
assert manifest["data_discipline"]["declared_key"] == ["company_number"]
assert manifest["data_discipline"]["engine"] == {"name": "duckdb", "version": "1.3.2", "threads": 1}
assert manifest["data_discipline"]["foreign_data_copied"] is False
assert manifest["discipline_references"]["data_repository"]["commit"] == VERIFY.REFERENCE_COMMIT
assert manifest["publication"]["stable_path_must_change"] is False
assert manifest["publication"]["promotion_eligible"] is False
assert len(manifest["source_files"]) == 7
for receipt in [*manifest["source_files"], *manifest["dependencies"]]:
source = ROOT / receipt["path"]
assert source.is_file(), receipt
if receipt["sha256"] != "SELF":
assert hashlib.sha256(source.read_bytes()).hexdigest() == receipt["sha256"], receipt
def test_document_ceiling() -> None:
assert EXTRACT.MAX_DOCUMENT_BYTES == 128_000_000
assert EXTRACT.MAX_OTHER_MEMBER_BYTES == 32_000_000
for suffix in (".xhtml", ".html", ".xml"):
EXTRACT.validate_member(member(f"Prod_01234567_T01{suffix}", EXTRACT.MAX_DOCUMENT_BYTES - 1), counters())
EXTRACT.validate_member(member(f"Prod_01234567_T01{suffix}", EXTRACT.MAX_DOCUMENT_BYTES), counters())
rejected(
lambda suffix=suffix: EXTRACT.validate_member(
member(f"Prod_01234567_T01{suffix}", EXTRACT.MAX_DOCUMENT_BYTES + 1), counters()
),
"per-document ceiling",
)
rejected(
lambda: EXTRACT.validate_member(member("opaque.bin", EXTRACT.MAX_OTHER_MEMBER_BYTES + 1), counters()),
"per-document ceiling",
)
assert EXTRACT.PREVIOUS.MAX_MEMBER_BYTES == EXTRACT.MAX_DOCUMENT_BYTES
def test_inherited_bomb_guards() -> None:
assert EXTRACT.MAX_TOTAL_EXPANDED_BYTES == 60_000_000_000
assert EXTRACT.MAX_COMPRESSION_RATIO == 250
assert EXTRACT.MAX_MEMBERS == 2_000_000
assert EXTRACT.MAX_NESTING == 1
EXTRACT.validate_member(member("Prod_01234567_T01.xhtml", 2_500, 10), counters())
rejected(
lambda: EXTRACT.validate_member(member("Prod_01234567_T01.xhtml", 2_501, 10), counters()),
"compression ratio",
)
EXTRACT.validate_member(
member("Prod_01234567_T01.xhtml", 1, 1),
counters(EXTRACT.MAX_TOTAL_EXPANDED_BYTES - 1),
)
rejected(
lambda: EXTRACT.validate_member(
member("Prod_01234567_T01.xhtml", 2, 2),
counters(EXTRACT.MAX_TOTAL_EXPANDED_BYTES - 1),
),
"expanded-byte ceiling",
)
rejected(
lambda: EXTRACT.validate_member(member("../escape.xhtml", 1, 1), counters()),
"unsafe",
)
def analytical_record(number: str) -> dict:
return {
"company_name": f"FIXTURE {number} LIMITED",
"company_number": number,
"company_status": "Active",
"sic_codes": ["35110 - Production of electricity"],
"accounts_date": "2025-12-31",
"total_assets": 15_000_000,
"net_assets": "8000000.25",
"turnover": None,
"cash": 500_000.5,
"assets_gte_10m": True,
"energy_relevant_large_company": True,
"btm_tags": ["INDUSTRIAL_SIC_B_TO_E"],
"repd_name_candidates": [],
"probable_project_spv": False,
"classification": "ENERGY_RELEVANT_LARGE_COMPANY",
"financial_currency": "GBP",
"news_identity_policy": "NEWS_MAY_ANNOTATE_BUT_NEVER_ESTABLISH_IDENTITY",
}
def analytical_fixture(root: Path, records: list[dict]) -> dict:
files = {}
for name in sorted(VERIFY.PREVIOUS.EXPECTED_CARTRIDGES):
path = root / f"{name}-v1.json"
path.write_text(
json.dumps(
{
"schema": "companies-house-cartridge-v1",
"snapshot_id": "202608272016",
"records": records,
},
sort_keys=True,
separators=(",", ":"),
)
+ "\n"
)
files[name] = {
"path": path.name,
"records": len(records),
"bytes": path.stat().st_size,
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
}
return {"files": files, "companies": len(records)}
def test_analytical_contract() -> str:
record = analytical_record("01234567")
row = VERIFY.analytical_row(record)
assert row[1] == "01234567"
assert row[6] == Decimal("15000000.00")
assert row[7] == Decimal("8000000.25")
assert row[8] is None
assert row[9] == Decimal("500000.50")
assert VERIFY.PARQUET_KEY == ("company_number",)
assert VERIFY.PARQUET_COLUMNS[6] == ("total_assets", "DECIMAL(38,2)", True)
rejected(lambda: VERIFY.money(True, "fixture"), "not a monetary")
malformed = dict(record)
malformed["assets_gte_10m"] = "true"
rejected(lambda: VERIFY.analytical_row(malformed), "is not boolean")
try:
VERIFY.load_duckdb()
except RuntimeError as exc:
if "is required" not in str(exc):
raise
return "SKIPPED_LOCAL_DUCKDB_UNAVAILABLE"
with tempfile.TemporaryDirectory() as temporary:
first = Path(temporary) / "first"
second = Path(temporary) / "second"
first.mkdir()
second.mkdir()
first_manifest = analytical_fixture(first, [record])
second_manifest = analytical_fixture(second, [record])
first_audit = VERIFY.write_analytical_parquet(first, first_manifest)
second_audit = VERIFY.write_analytical_parquet(second, second_manifest)
assert first_audit["rows"] == first_audit["distinct_keys"] == 1
assert first_audit["null_keys"] == first_audit["duplicate_key_groups"] == 0
assert (first / VERIFY.PARQUET_PATH).read_bytes() == (second / VERIFY.PARQUET_PATH).read_bytes()
comparable_first = json.loads((first / VERIFY.AUDIT_PATH).read_text())
comparable_second = json.loads((second / VERIFY.AUDIT_PATH).read_text())
assert comparable_first == comparable_second
copied = first / "copied.parquet"
shutil.copyfile(first / VERIFY.PARQUET_PATH, copied)
assert hashlib.sha256(copied.read_bytes()).hexdigest() == first_audit["parquet"]["sha256"]
return "PASS"
def test_company_number_domain_and_rights_separation() -> None:
accepted = ("00000006", "SC123456", "NI123456", "OC123456", "R0000001", "AB12CD34")
rejected_numbers = ("", "1234567", "123456789", "SC12345", "SC1234567", "AB-12345")
for number in accepted:
assert VERIFY.PREVIOUS.COMPANY_NUMBER.fullmatch(number), number
for number in rejected_numbers:
assert not VERIFY.PREVIOUS.COMPANY_NUMBER.fullmatch(number), number
source = (ROOT / "build/python/202608272016-verify-companies-house-candidate.py").read_text()
assert '"usage_context"] = "NON_COMMERCIAL_OPEN_SOURCE"' in source
assert '"source_licence"] = PREVIOUS.OGL' in source
assert '"source_rights_are_distinct_from_usage_context"] = True' in source
discipline = source.split('manifest["data_discipline"] = {', 1)[1].split("}", 1)[0]
assert "licensing_posture" not in discipline
def main() -> None:
test_generation_boundary()
test_source_manifest()
test_company_number_domain_and_rights_separation()
test_document_ceiling()
test_inherited_bomb_guards()
analytical_status = test_analytical_contract()
print(
json.dumps(
{
"status": "PASS",
"generation": "202608272016",
"document_ceiling_bytes": EXTRACT.MAX_DOCUMENT_BYTES,
"aggregate_ceiling_bytes": EXTRACT.MAX_TOTAL_EXPANDED_BYTES,
"compression_ratio_ceiling": EXTRACT.MAX_COMPRESSION_RATIO,
"analytical_contract": analytical_status,
"network_requests": 0,
},
sort_keys=True,
)
)
if __name__ == "__main__":
main()Test Company Identity and Grains
A test in the tests folder of Companies that uses SHA-256. It replaces Parquet (`replace_parquet`) and is built from the load step (`load`) and the rejected step (`rejected`).
testcompanies / tests/test_202608272120_company_identity_and_grains.py · lines 1–442 of 459 · version 2026-08-27 21:20 · Entry point · pattern successor_seal_fixture (shared by 2 files)
- What it does
- It tests its inputs. Defines 17 functions or classes, including load, rejected, test_generation_and_fixed_plan, drifted, ixbrl_payload. Uses libraries __future__, hashlib, importlib.util, json, shutil. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
- Inputs & outputs
- In: JSON file plan.json; JSON file rest-evidence.json; JSON file report.json; JSON file fixed-rest-evidence.json; JSON file manifest-v1.json; JSON file 202608272120-bounded-companies-house-candidate.json; JSON file 202608261927-build-manifest-v9-1.json; DuckDB queries. Out: Parquet file.
- Downstream impact
- Used directly by 1 file: Bounded Companies House Candidate (companies).
- What it achieves
- Source-only contracts for the Companies successor.
- Why it matters
- Run by Bounded Companies House Candidate.
- Application
- companies · tests · test
- Uses
- __future__, hashlib, importlib.util, json, shutil, tempfile, zipfile, pathlib
- Used by
- run by Bounded Companies House Candidate (workflow run)
- Produces
- load, rejected, test_generation_and_fixed_plan, ixbrl_payload, test_extractor_company_number_end_to_end, relationship, record, cartridge_fixture, test_relationship_key_law, replace_parquet, test_actual_landed_two_grain_readback, tree_bytes
- Defines here
- load, rejected, test_generation_and_fixed_plan, drifted, ixbrl_payload, test_extractor_company_number_end_to_end, relationship, record, cartridge_fixture, test_relationship_key_law, replace_parquet, test_actual_landed_two_grain_readback, tree_bytes, successor_seal_fixture, test_full_successor_seal_and_verify, test_source_manifest_and_workflow, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- companies@1371da4d0166eef13f98fc3847c5bb1e38e8f571 tests/test_202608272120_company_identity_and_grains.py:1-442 · blob ddd6d584755541183d8eb89af181030bebd027db · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unknown
#!/usr/bin/env python3
"""Source-only contracts for the 202608272120 Companies successor."""
from __future__ import annotations
import hashlib
import importlib.util
import json
import shutil
import tempfile
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def load(relative: str, name: str):
spec = importlib.util.spec_from_file_location(name, ROOT / relative)
if spec is None or spec.loader is None:
raise RuntimeError(f"Unable to load {relative}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
PLAN = load("build/python/202608272120-freeze-companies-house-plan.py", "companies_plan_2120_test")
DOWNLOAD = load("build/python/202608272120-download-planned-archive.py", "companies_download_2120_test")
EXTRACT = load("build/python/202608272120-extract-bounded-accounts.py", "companies_extract_2120_test")
VERIFY = load("build/python/202608272120-verify-companies-house-candidate.py", "companies_verify_2120_test")
BASE_FIXTURE = load("tests/test_202608271507_bounded_companies_house.py", "companies_1507_fixture_for_2120")
def rejected(callable_, contains: str) -> None:
try:
callable_()
except RuntimeError as exc:
assert contains.lower() in str(exc).lower(), (contains, str(exc))
return
raise AssertionError(f"Expected RuntimeError containing {contains!r}")
def test_generation_and_fixed_plan() -> None:
assert PLAN.GENERATION == DOWNLOAD.GENERATION == EXTRACT.GENERATION == VERIFY.GENERATION == "202608272120"
assert PLAN.BASE_COMMIT == DOWNLOAD.BASE_COMMIT == VERIFY.BASE_COMMIT == "cd870ff53d2693b734e5860947bb0fa96bde9cf3"
assert PLAN.FIXED_GENERATED_AT == DOWNLOAD.FIXED_GENERATED_AT == EXTRACT.FIXED_GENERATED_AT == VERIFY.FIXED_GENERATED_AT
assert PLAN.EXPECTED_FILES == DOWNLOAD.EXPECTED_FILES
assert PLAN.EXPECTED_TOTAL_BYTES == DOWNLOAD.EXPECTED_TOTAL_BYTES == 7_046_921_879
expected_by_url = {row["url"]: row for row in PLAN.EXPECTED_FILES}
plan = PLAN.fixed_plan(lambda request: dict(expected_by_url[request[1]]))
assert plan["planned_at"] == PLAN.FIXED_GENERATED_AT
assert plan["files"] == list(PLAN.EXPECTED_FILES)
assert [row["filename"] for row in plan["files"]] == [
"Accounts_Monthly_Data-May2026.zip",
"Accounts_Monthly_Data-June2026.zip",
"Accounts_Monthly_Data-July2026.zip",
"BasicCompanyDataAsOneFile-2026-08-01.zip",
]
encoded_plan = (json.dumps(plan, indent=2, sort_keys=True) + "\n").encode()
assert hashlib.sha256(encoded_plan).hexdigest() == VERIFY.EXPECTED_PLAN_SHA256
with tempfile.TemporaryDirectory(prefix="companies-2120-plan-") as temporary:
root = Path(temporary)
plan_path = root / "plan.json"
plan_path.write_bytes(encoded_plan)
loaded_plan, loaded_item = DOWNLOAD.load_item(plan_path, 0)
assert loaded_plan == plan
assert loaded_item == PLAN.EXPECTED_FILES[0]
rest_path = root / "rest-evidence.json"
rest = PLAN.fixed_rest_evidence(rest_path)
assert rest["generation"] == "202608272120"
assert hashlib.sha256(rest_path.read_bytes()).hexdigest() == VERIFY.EXPECTED_REST_EVIDENCE_SHA256
def drifted(request):
row = dict(expected_by_url[request[1]])
if row["filename"].endswith("May2026.zip"):
row["etag"] = '"drifted"'
return row
rejected(lambda: PLAN.fixed_plan(drifted), "closure drifted")
def ixbrl_payload(asset_value: int) -> bytes:
filler = "0123456789abcdef" * 160
return (
"<root>"
'<context id="current"><instant>2025-12-31</instant></context>'
f'<totalassets contextRef="current">{asset_value}</totalassets>'
f"<filler>{filler}</filler>"
"</root>"
).encode()
def test_extractor_company_number_end_to_end() -> None:
accepted = {
"00000006": "Prod224_2605_00000006_20260331.html",
"SC123456": "Prod101_2606_SC123456_20260430.xhtml",
"R0000001": "Prod999_2607_R0000001_20260531.xml",
"AB12CD34": "Prod000_2605_ab12cd34_20260331.HTML",
}
for number, member in accepted.items():
assert EXTRACT.COMPANY_NUMBER.fullmatch(number)
row, parser = EXTRACT.parse_document(member, ixbrl_payload(15_000_000))
assert parser == "xml"
assert row and row["company_number"] == number
assert row["source_file"] == member
for number in ("", "1234567", "123456789", "SC12345", "AB-12345"):
assert not EXTRACT.COMPANY_NUMBER.fullmatch(number)
# Every token around identity is closed. In particular, a valid company-like
# second or fourth token can never be reinterpreted as the company key.
for misleading_name in (
# invalid producer token / prefix and ASCII lookalikes
"Prod22_2605_00009872_20260331.html",
"Prod2244_2605_00009872_20260331.html",
"prefix_Prod224_2605_00009872_20260331.html",
"prod224_2605_00009872_20260331.html",
"Prød224_2605_00009872_20260331.html",
# invalid second YYMM token
"Prod224_265_00009872_20260331.html",
"Prod224_26050_00009872_20260331.html",
"Prod224_26O5_00009872_20260331.html",
"Prod224_R0000001_00009872_20260331.html",
# invalid third identity token
"Prod224_2605_0009872_20260331.html",
"Prod224_2605_000009872_20260331.html",
"Prod224_2605_AB-2CD34_20260331.html",
"Prod224_2605_ſC123456_20260331.html",
"Prod224_2605_ıC123456_20260331.html",
# invalid fourth date token, shifted identity bait, suffix or extension
"Prod224_2605_00009872_2026033.html",
"Prod224_2605_00009872_202603311.html",
"Prod224_2605_00009872_2026033O.html",
"Prod224_2605_00009872_R0000001.html",
"Prod224_2605_00009872_20260331_extra.html",
"Prod224_2605_00009872_20260331.htm",
"unrelated_2605_00009872_20260331.html",
):
row, parser = EXTRACT.parse_document(misleading_name, ixbrl_payload(15_000_000))
assert row is None and parser == "no-company-number"
# Directory placement is not identity: only the exact basename is parsed.
row, parser = EXTRACT.parse_document(
"nested/Prod224_2605_00009872_20260331.html", ixbrl_payload(15_000_000)
)
assert parser == "xml" and row and row["company_number"] == "00009872"
with tempfile.TemporaryDirectory(prefix="companies-2120-extract-") as temporary:
root = Path(temporary)
archive = root / "Accounts_Monthly_Data-Fixture2026.zip"
with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_STORED) as handle:
handle.writestr("Prod224_2605_R0000001_20260331.xhtml", ixbrl_payload(15_000_001))
handle.writestr("Prod224_2605_AB12CD34_20260331.xhtml", ixbrl_payload(15_000_002))
handle.writestr("Prod224_R0000001_00009872_20260331.xhtml", ixbrl_payload(99_999_999))
output = root / "accounts.ndjson"
report_path = root / "report.json"
report = EXTRACT.extract(archive, output, report_path)
rows = [json.loads(line) for line in output.read_text().splitlines()]
assert [row["company_number"] for row in rows] == ["AB12CD34", "R0000001"]
assert report["records"] == 2
assert report["completed_at"] == EXTRACT.FIXED_GENERATED_AT
assert json.loads(report_path.read_text()) == report
def relationship(ref: str, match_type: str = "EXACT_OPERATOR_NAME", **changes) -> dict:
value = {
"repd_ref": ref,
"match_type": match_type,
"gg_project_id": f"GG2050-REPD-{ref}",
"project": f"PROJECT {ref}",
"operator": "FIXTURE OPERATOR",
"technology": "solar",
"capacity_mw": "12.345678",
"status": "Operational",
"latitude": 52.1,
"longitude": -1.2,
"atlas_url": f"https://globalgrid2050.com/repd_grid_atlasv8/?repd_ref={ref}",
}
value.update(changes)
return value
def record(number: str = "R0000001", relationships: list[dict] | None = None) -> dict:
return {
"company_name": f"FIXTURE {number} LIMITED",
"company_number": number,
"company_status": "Active",
"sic_codes": ["35110 - Production of electricity"],
"accounts_date": "2025-12-31",
"total_assets": 15_000_000,
"net_assets": "8000000.25",
"turnover": None,
"cash": 500_000.5,
"assets_gte_10m": True,
"energy_relevant_large_company": True,
"btm_tags": ["INDUSTRIAL_SIC_B_TO_E"],
"repd_name_candidates": relationships if relationships is not None else [relationship("10001")],
"probable_project_spv": False,
"classification": "REPD_NAME_CANDIDATE",
"financial_currency": "GBP",
"news_identity_policy": "NEWS_MAY_ANNOTATE_BUT_NEVER_ESTABLISH_IDENTITY",
}
def cartridge_fixture(root: Path, records: list[dict]) -> dict:
files = {}
canonical = sorted(records, key=lambda row: row["company_number"])
for name in sorted(VERIFY.PARENT.PREVIOUS.EXPECTED_CARTRIDGES):
path = root / f"{name}-v1.json"
path.write_text(
json.dumps(
{"schema": "companies-house-cartridge-v1", "snapshot_id": VERIFY.GENERATION, "records": canonical},
sort_keys=True,
separators=(",", ":"),
)
+ "\n"
)
files[name] = {
"path": path.name,
"records": len(canonical),
"bytes": path.stat().st_size,
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
}
return {"files": files, "companies": len(canonical)}
def test_relationship_key_law() -> None:
one = record(relationships=[relationship("10001"), relationship("10002")])
rows = VERIFY.relationship_rows([one])
assert len(rows) == 2
assert str(rows[0][8]) == "12.345678"
assert [(row[1], row[2], row[3]) for row in rows] == [
("R0000001", "10001", "EXACT_OPERATOR_NAME"),
("R0000001", "10002", "EXACT_OPERATOR_NAME"),
]
distinct_match = record(
relationships=[relationship("10001", "EXACT_OPERATOR_NAME"), relationship("10001", "EXACT_PROJECT_NAME")]
)
assert len(VERIFY.relationship_rows([distinct_match])) == 2
repeated = relationship("10001")
rejected(lambda: VERIFY.relationship_rows([record(relationships=[repeated, dict(repeated)])]), "duplicate")
rejected(
lambda: VERIFY.relationship_rows(
[record(relationships=[relationship("10001"), relationship("10001", operator="DRIFT")])]
),
"drift",
)
rejected(lambda: VERIFY.relationship_rows([record(relationships=[relationship("")])]), "blank")
rejected(lambda: VERIFY.relationship_rows([record(relationships=[relationship("10001", match_type=None)])]), "null")
rejected(lambda: VERIFY.relationship_rows([record(relationships=[relationship(" 10001")])]), "whitespace")
def replace_parquet(source: Path, query: str, compression: str = "ZSTD") -> None:
duckdb = VERIFY.load_duckdb()
target = source.with_name(f"tampered-{source.name}")
connection = duckdb.connect(":memory:")
try:
connection.execute(
f"COPY ({query}) TO '{VERIFY.sql_path(target)}' (FORMAT PARQUET, COMPRESSION {compression})"
)
finally:
connection.close()
shutil.move(target, source)
def test_actual_landed_two_grain_readback() -> None:
fixture = record(relationships=[relationship("10001"), relationship("10002")])
with tempfile.TemporaryDirectory(prefix="companies-2120-parquet-") as temporary:
base = Path(temporary)
first = base / "first"
second = base / "second"
first.mkdir()
second.mkdir()
first_audit = VERIFY.build_analytical_datasets(first, cartridge_fixture(first, [fixture]))
second_audit = VERIFY.build_analytical_datasets(second, cartridge_fixture(second, [fixture]))
companies = first_audit["datasets"]["companies"]
relationships = first_audit["datasets"]["company_repd_candidates"]
assert companies["rows"] == companies["distinct_keys"] == 1
assert relationships["rows"] == relationships["distinct_keys"] == 2
assert companies["null_keys"] == relationships["null_keys"] == 0
assert companies["duplicate_key_groups"] == relationships["duplicate_key_groups"] == 0
assert companies["typed_column_mismatches"] == relationships["typed_column_mismatches"] == 0
assert companies["compression_codecs"] == relationships["compression_codecs"] == ["ZSTD"]
assert companies["declared_key"] == ["company_number"]
assert relationships["declared_key"] == ["company_number", "repd_ref", "match_type"]
for name in (VERIFY.COMPANY_PARQUET, VERIFY.RELATIONSHIP_PARQUET):
assert (first / name).read_bytes() == (second / name).read_bytes()
assert first_audit == second_audit
company_rows = VERIFY.company_rows([fixture])
relationship_rows = VERIFY.relationship_rows([fixture])
company_path = first / VERIFY.COMPANY_PARQUET
company_sql = f"SELECT * REPLACE ('WRONG NAME' AS company_name) FROM read_parquet('{VERIFY.sql_path(company_path)}')"
replace_parquet(company_path, company_sql)
rejected(
lambda: VERIFY.audit_parquet(
company_path,
VERIFY.COMPANY_COLUMNS,
("company_number",),
"record_json",
company_rows,
),
"readback",
)
relationship_path = first / VERIFY.RELATIONSHIP_PARQUET
relation_sql = f"SELECT * FROM read_parquet('{VERIFY.sql_path(relationship_path)}')"
replace_parquet(relationship_path, relation_sql, compression="SNAPPY")
rejected(
lambda: VERIFY.audit_parquet(
relationship_path,
VERIFY.RELATIONSHIP_COLUMNS,
("company_number", "repd_ref", "match_type"),
"relationship_json",
relationship_rows,
),
"compression",
)
def tree_bytes(root: Path) -> dict[str, bytes]:
return {
path.relative_to(root).as_posix(): path.read_bytes()
for path in sorted(root.rglob("*"))
if path.is_file()
}
def successor_seal_fixture(root: Path):
plan_path, evidence, repd, raw, basic, accounts, _old_rest, basic_report = BASE_FIXTURE.write_verifier_fixture(root)
plan = json.loads(plan_path.read_text())
plan["generation"] = VERIFY.GENERATION
plan["base_commit"] = VERIFY.BASE_COMMIT
plan["planned_at"] = VERIFY.FIXED_GENERATED_AT
plan_path.write_text(json.dumps(plan, indent=2, sort_keys=True) + "\n")
plan_sha = hashlib.sha256(plan_path.read_bytes()).hexdigest()
for path in sorted(evidence.glob("receipt-*.json")):
receipt = json.loads(path.read_text())
receipt["generation"] = VERIFY.GENERATION
receipt["base_commit"] = VERIFY.BASE_COMMIT
receipt["plan_sha256"] = plan_sha
receipt["retrieved_at"] = VERIFY.FIXED_GENERATED_AT
path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n")
for path in sorted(evidence.glob("extraction-*.json")):
report = json.loads(path.read_text())
report["generation"] = VERIFY.GENERATION
report["completed_at"] = VERIFY.FIXED_GENERATED_AT
path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
report = json.loads(basic_report.read_text())
report["generation"] = VERIFY.GENERATION
report["completed_at"] = VERIFY.FIXED_GENERATED_AT
basic_report.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n")
rest = root / "fixed-rest-evidence.json"
PLAN.fixed_rest_evidence(rest)
return plan_path, evidence, repd, raw, basic, accounts, rest, basic_report
def test_full_successor_seal_and_verify() -> None:
with tempfile.TemporaryDirectory(prefix="companies-2120-seal-") as temporary:
root = Path(temporary)
plan_path, evidence, repd, raw, basic, accounts, rest, basic_report = successor_seal_fixture(root)
original_plan_sha = VERIFY.EXPECTED_PLAN_SHA256
VERIFY.EXPECTED_PLAN_SHA256 = hashlib.sha256(plan_path.read_bytes()).hexdigest()
try:
first = root / "candidate-a"
second = root / "candidate-b"
for output in (first, second):
VERIFY.seal(
raw,
output,
plan_path,
evidence,
evidence,
repd,
basic,
accounts,
rest,
basic_report,
"a" * 40,
)
assert tree_bytes(first) == tree_bytes(second)
result = VERIFY.verify(first)
assert result["status"] == "PASS", result
manifest = json.loads((first / "manifest-v1.json").read_text())
assert manifest["analytical_dataset"]["rows"] == 1
assert manifest["relationship_dataset"]["rows"] == 1
assert manifest["data_discipline"] == VERIFY.DATA_DISCIPLINE
assert manifest["source_licences"] == VERIFY.MATERIALISED_SOURCES
finally:
VERIFY.EXPECTED_PLAN_SHA256 = original_plan_sha
def test_source_manifest_and_workflow() -> None:
source_path = ROOT / "manifests/202608272120-bounded-companies-house-candidate.json"
source = json.loads(source_path.read_text())
assert source["generation"] == "202608272120"
assert source["parent_generation"] == "202608272035"
assert source["base_commit"] == VERIFY.BASE_COMMIT
assert source["usage_context"] == "NON_COMMERCIAL_OPEN_SOURCE"
assert source["source_rights_are_distinct_from_usage_context"] is True
assert source["data_discipline"]["company_declared_key"] == ["company_number"]
assert source["data_discipline"]["relationship_declared_key"] == ["company_number", "repd_ref", "match_type"]
assert source["data_discipline"]["foreign_repository_files_committed"] is False
assert source["data_discipline"]["foreign_data_materialised"] is True
assert source["field_lineage"] == VERIFY.FIELD_LINEAGE
assert source["runtime_sources"]["repd"]["commit"] == VERIFY.PIPELINENEWS_COMMIT
assert source["source_licences"]["repd"]["source_page"] == VERIFY.REPD_RIGHTS["source_page"]
assert source["source_licences"]["repd"]["catalogue_url"] == VERIFY.REPD_RIGHTS["catalogue_url"]
assert source["source_licences"]["repd"]["catalogue_licence_id"] == "uk-ogl"
assert source["fixed_archive_plan"]["total_bytes"] == PLAN.EXPECTED_TOTAL_BYTES
assert source["fixed_archive_plan"]["plan_json_sha256"] == VERIFY.EXPECTED_PLAN_SHA256
assert source["fixed_archive_plan"]["rest_non_use_evidence_sha256"] == VERIFY.EXPECTED_REST_EVIDENCE_SHA256
assert source["company_number_domain"]["identity_token"] == 3
assert source["company_number_domain"]["monthly_member_example"] == "Prod224_2605_00009872_20260331.html"
assert source["company_number_domain"]["monthly_member_pattern"] == EXTRACT.COMPANY_NUMBER_IN_FILENAME.pattern
for receipt in [*source["source_files"], *source["dependencies"]]:
path = ROOT / receipt["path"]
assert path.is_file(), receipt
if receipt["sha256"] != "SELF":
assert hashlib.sha256(path.read_bytes()).hexdigest() == receipt["sha256"], receipt
workflow = (ROOT / ".github/workflows/202608272120-bounded-companies-house-candidate.yml").read_text()
assert "workflow_dispatch" not in workflow
assert "python tests/test_202608272035_company_identity_and_grains.py" in workflow
assert 'test "$GITHUB_EVENT_NAME" = push' in workflow
assert 'test "$GITHUB_REF" = refs/heads/main' in workflow
assert 'test "$(git rev-list --parents -n 1 HEAD | wc -w)" -eq 2' in workflow
assert 'test "$(git rev-parse HEAD^)" = "$BASE_COMMIT"' in workflow
assert '--force-with-lease="$candidate_ref:"' in workflow
assert 'HEAD:refs/heads/main' not in workflow
assert "sparse-checkout-cone-mode: false" in workflow
assert "/data/manifests/202608261927-build-manifest-v9-1.json" in workflow
assert "data/current" in workflow
assert "pages" in workflow and "releases" in workflow
def main() -> None:
test_generation_and_fixed_plan()
test_extractor_company_number_end_to_end()
test_relationship_key_law()
test_actual_landed_two_grain_readback()
test_full_successor_seal_and_verify()
test_source_manifest_and_workflow()
print(