Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add Companies House source (#77144)

Tom Owersf0e31a09ad03
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index ea109067ec8d..07677acb7cb7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -628,6 +628,7 @@ the row lists both.
| tyntec_sms | HTTP | requests + `rest_source.RESTClient` | ✅ |
| typeform | HTTP | requests + `rest_source.RESTClient` | ✅ |
| ubidots | HTTP | requests | ✅ |
+| uk_companies_house | HTTP | requests + `rest_source.RESTClient` | ✅ |
| unleash | HTTP | requests | ✅ |
| unstructured | HTTP | requests | ✅ |
| upstash | HTTP | requests | ✅ |
@@ -1380,7 +1381,6 @@ doesn't conflict with concurrent PRs.
- two_c2p
- tyntec_sms
- typesense
-- uk_companies_house
- uk_ons
- umami
- un_comtrade
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ukcompanieshouse.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ukcompanieshouse.py
index 219f7a48ae52..0086159476ad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ukcompanieshouse.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/ukcompanieshouse.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class UkCompaniesHouseSourceConfig(config.Config):
- pass
+ api_key: str
+ company_numbers: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/canonical_descriptions.py
new file mode 100644
index 000000000000..4b3807e7bce3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/canonical_descriptions.py
@@ -0,0 +1,219 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.settings import (
+ CHARGES,
+ COMPANIES,
+ EXEMPTIONS,
+ FILING_HISTORY,
+ INSOLVENCY,
+ OFFICERS,
+ PERSONS_WITH_SIGNIFICANT_CONTROL,
+ PSC_STATEMENTS,
+ REGISTERS,
+ UK_ESTABLISHMENTS,
+)
+
+_REFERENCE_URL = "https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/reference"
+_RESOURCES_URL = "https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/resources"
+
+_COMPANY_NUMBER = "The company number the row was fetched for."
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ COMPANIES: {
+ "description": "The Companies House profile of a registered company: name, status, type, incorporation date, registered office and SIC codes.",
+ "docs_url": f"{_RESOURCES_URL}/companyprofile?v=latest",
+ "columns": {
+ "company_number": "The number allocated to the company by Companies House.",
+ "company_name": "The name of the company as registered.",
+ "company_status": "The status of the company, for example active, dissolved or liquidation.",
+ "company_status_detail": "Extra context on the company status.",
+ "type": "The legal form of the company, for example ltd, plc or llp.",
+ "subtype": "The subtype of the company, for example community interest company.",
+ "date_of_creation": "The date the company was incorporated.",
+ "date_of_cessation": "The date the company was dissolved, converted or closed.",
+ "jurisdiction": "The political body responsible for the company.",
+ "sic_codes": "The SIC codes describing what the company does.",
+ "registered_office_address": "The address the company's legal correspondence is sent to.",
+ "registered_office_is_in_dispute": "Whether the registered office address is disputed.",
+ "undeliverable_registered_office_address": "Whether post to the registered office is undeliverable.",
+ "service_address": "The correspondence address, for registered overseas entities.",
+ "accounts": "Accounting reference dates and the last and next accounts filed.",
+ "annual_return": "Annual return dates, superseded by confirmation statements.",
+ "confirmation_statement": "The last and next confirmation statement dates.",
+ "previous_company_names": "Names the company traded under previously, with the dates they applied.",
+ "branch_company_details": "Details of the UK branch of an overseas company.",
+ "foreign_company_details": "Details of a company incorporated outside the UK.",
+ "links": "Links to the company's other Companies House resources.",
+ "can_file": "Whether the company is allowed to file.",
+ "has_charges": "Deprecated by Companies House; check the charges link instead.",
+ "has_insolvency_history": "Deprecated by Companies House; check the insolvency link instead.",
+ "last_full_members_list_date": "The date of the last full members list filed.",
+ "partial_data_available": "Set when Companies House is not the primary source of the data.",
+ "super_secure_managing_officer_count": "The number of protected officers, for overseas entities.",
+ "external_registration_number": "The company's identifier at an external registry.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+ OFFICERS: {
+ "description": "Officers appointed to a company, both current and resigned.",
+ "docs_url": f"{_RESOURCES_URL}/officerlist?v=latest",
+ "columns": {
+ "company_number": _COMPANY_NUMBER,
+ "appointment_id": "The appointment identifier taken from the last segment of `links.self`.",
+ "name": "The name of the officer.",
+ "person_number": "The Companies House identifier for the person.",
+ "officer_role": "The role the officer holds, for example director or secretary.",
+ "appointed_on": "The date the officer was appointed.",
+ "resigned_on": "The date the officer resigned.",
+ "nationality": "The nationality of the officer.",
+ "country_of_residence": "The country the officer usually lives in.",
+ "occupation": "The occupation of the officer.",
+ "date_of_birth": "The month and year the officer was born.",
+ "former_names": "Names the officer was previously known by.",
+ "address": "The correspondence address of the officer.",
+ "principal_office_address": "The principal office address of a corporate managing officer.",
+ "identification": "Identity type and registration details for a corporate officer.",
+ "contact_details": "Contact details recorded for the officer.",
+ "identity_verification_details": "Identity verification status and dates for the officer.",
+ "responsibilities": "The responsibilities of a managing officer.",
+ "is_pre_1992_appointment": "Whether the appointment predates 1992.",
+ "links": "Links to the appointment and to the officer's other appointments.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+ PERSONS_WITH_SIGNIFICANT_CONTROL: {
+ "description": "People and entities with significant control over a company, excluding statements filed in place of a person.",
+ "docs_url": f"{_REFERENCE_URL}/persons-with-significant-control/list",
+ "columns": {
+ "company_number": _COMPANY_NUMBER,
+ "psc_id": "The notification identifier taken from the last segment of `links.self`.",
+ "name": "The full name of the person or entity with significant control.",
+ "name_elements": "The name broken into title, forename, middle name and surname.",
+ "kind": "The kind of person with significant control, for example individual or corporate entity.",
+ "natures_of_control": "The ways in which control is held over the company.",
+ "notified_on": "The date Companies House was notified of the person with significant control.",
+ "ceased": "Whether the person has ceased to have significant control.",
+ "ceased_on": "The date Companies House was notified that control ceased.",
+ "date_of_birth": "The month and year the person was born.",
+ "nationality": "The nationality of the person.",
+ "country_of_residence": "The country the person usually lives in.",
+ "address": "The service address of the person or entity.",
+ "principal_office_address": "The principal office address of a corporate or legal entity.",
+ "identification": "Registration details of a corporate or legal entity.",
+ "is_sanctioned": "Whether the person appears on a sanctions list.",
+ "identity_verification_details": "Identity verification status and dates.",
+ "links": "Links to this notification and its statements.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+ PSC_STATEMENTS: {
+ "description": "Statements a company filed instead of person with significant control details, for example that no person has been identified.",
+ "docs_url": f"{_RESOURCES_URL}/statementlist?v=latest",
+ "columns": {
+ "company_number": _COMPANY_NUMBER,
+ "statement_id": "The statement identifier taken from the last segment of `links.self`.",
+ "statement": "The statement filed by the company.",
+ "kind": "The resource kind, always persons-with-significant-control-statement.",
+ "notified_on": "The date Companies House processed the statement.",
+ "ceased_on": "The date Companies House was notified that the statement ceased.",
+ "linked_psc_name": "The name of the person with significant control the statement refers to.",
+ "restrictions_notice_withdrawal_reason": "Why a restrictions notice was withdrawn.",
+ "links": "Links to the statement and any linked person with significant control.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+ FILING_HISTORY: {
+ "description": "Documents filed at Companies House for a company, such as accounts, confirmation statements and officer changes.",
+ "docs_url": f"{_RESOURCES_URL}/filinghistorylist?v=latest",
+ "columns": {
+ "company_number": _COMPANY_NUMBER,
+ "transaction_id": "The identifier of the filing.",
+ "date": "The date the filing was processed.",
+ "category": "The category of the filing, for example accounts, officers or mortgage.",
+ "subcategory": "A finer classification of the filing.",
+ "type": "The filing type code.",
+ "description": "A description of the filing.",
+ "description_values": "Values used to expand the filing description template.",
+ "barcode": "The barcode of the filed document.",
+ "pages": "The number of pages in the filed document.",
+ "paper_filed": "Whether the document was filed on paper.",
+ "action_date": "The date the filing action took effect.",
+ "annotations": "Annotations Companies House added to the filing.",
+ "associated_filings": "Filings submitted alongside this one.",
+ "resolutions": "Resolutions attached to the filing.",
+ "links": "Links to the filing and its document metadata.",
+ },
+ },
+ CHARGES: {
+ "description": "Mortgages and charges registered against a company.",
+ "docs_url": f"{_RESOURCES_URL}/chargelist?v=latest",
+ "columns": {
+ "company_number": _COMPANY_NUMBER,
+ "id": "The identifier of the charge.",
+ "charge_code": "The charge code allocated by Companies House.",
+ "charge_number": "The number of the charge within the company's charge list.",
+ "status": "The status of the charge, for example outstanding or fully-satisfied.",
+ "classification": "The classification of the charge.",
+ "particulars": "The particulars of the charge, including the property secured.",
+ "persons_entitled": "The parties entitled to the charge.",
+ "secured_details": "What the charge secures.",
+ "transactions": "The filings that created or amended the charge.",
+ "insolvency_cases": "Insolvency cases linked to the charge.",
+ "scottish_alterations": "Alteration flags that apply to Scottish charges.",
+ "created_on": "The date the charge was created.",
+ "delivered_on": "The date the charge was delivered to Companies House.",
+ "acquired_on": "The date the property subject to the charge was acquired.",
+ "satisfied_on": "The date the charge was satisfied.",
+ "resolved_on": "The date the charge was resolved.",
+ "links": "Links to the charge resource.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+ INSOLVENCY: {
+ "description": "Insolvency status and cases for a company. One row per company, with the cases nested.",
+ "docs_url": f"{_RESOURCES_URL}/companyinsolvency?v=latest",
+ "columns": {
+ "company_number": _COMPANY_NUMBER,
+ "status": "The insolvency status of the company, for example liquidation or in-administration.",
+ "cases": "The insolvency cases recorded against the company, each with its type, dates, notes and practitioners.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+ REGISTERS: {
+ "description": "Which statutory registers a company keeps at Companies House rather than at its own registered office. One row per company.",
+ "docs_url": _REFERENCE_URL,
+ "columns": {
+ "company_number": _COMPANY_NUMBER,
+ "registers": "The registers held, keyed by register type, each with its register entries and moved-on dates.",
+ "kind": "The resource kind, always registers.",
+ "links": "Links to the company and its register resources.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+ EXEMPTIONS: {
+ "description": "Exemptions a company holds from filing person with significant control information. One row per company.",
+ "docs_url": _REFERENCE_URL,
+ "columns": {
+ "company_number": _COMPANY_NUMBER,
+ "exemptions": "The exemptions held, each with the periods it applied for.",
+ "kind": "The resource kind, always exemptions.",
+ "links": "Links to the company resource.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+ UK_ESTABLISHMENTS: {
+ "description": "UK establishments registered by an overseas company.",
+ "docs_url": _REFERENCE_URL,
+ "columns": {
+ "parent_company_number": "The company number of the overseas company the establishment belongs to.",
+ "company_number": "The company number of the UK establishment.",
+ "company_name": "The name of the UK establishment.",
+ "company_status": "The status of the UK establishment.",
+ "locality": "The locality of the UK establishment.",
+ "kind": "The resource kind, always uk-establishment.",
+ "links": "Links to the establishment's company resource.",
+ "etag": "The ETag of the resource at Companies House.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/settings.py
new file mode 100644
index 000000000000..f3c8f561f1e9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/settings.py
@@ -0,0 +1,125 @@
+import dataclasses
+from typing import Optional
+
+BASE_URL = "https://api.company-information.service.gov.uk"
+
+# Companies House allows 600 requests per five minutes and answers 429 once that is used up.
+# The shared REST client already backs off on 429, so the only tuning here is page size.
+ITEMS_PER_PAGE = 100
+
+# Connect and read timeouts, so a stalled request cannot hold an import worker open forever.
+REQUEST_TIMEOUT = (10.0, 60.0)
+
+COMPANIES = "Companies"
+OFFICERS = "Officers"
+PERSONS_WITH_SIGNIFICANT_CONTROL = "PersonsWithSignificantControl"
+PSC_STATEMENTS = "PersonsWithSignificantControlStatements"
+FILING_HISTORY = "FilingHistory"
+CHARGES = "Charges"
+INSOLVENCY = "Insolvency"
+REGISTERS = "Registers"
+EXEMPTIONS = "Exemptions"
+UK_ESTABLISHMENTS = "UkEstablishments"
+
+
[email protected](frozen=True)
+class EndpointSpec:
+ """One Companies House resource, fetched once per configured company number.
+
+ ``path`` is formatted with the company number. ``data_selector`` names the array of rows in
+ the response body; when it is ``None`` the whole body is a single row. ``total_key`` names the
+ body field carrying the grand total, which is what drives offset pagination - endpoints
+ without one are fetched as a single page because Companies House does not document
+ ``start_index`` for them.
+ """
+
+ path: str
+ primary_key: list[str]
+ data_selector: Optional[str] = None
+ total_key: Optional[str] = None
+ # Field the company number is written onto for the rows of this endpoint. `None` means the
+ # response already carries it (the company profile).
+ parent_field: Optional[str] = "company_number"
+ # Field to populate from the last path segment of the row's `links.self`, for resources whose
+ # identifier is only exposed through that link.
+ id_from_self_link: Optional[str] = None
+
+
+ENDPOINT_SPECS: dict[str, EndpointSpec] = {
+ COMPANIES: EndpointSpec(
+ path="/company/{company_number}",
+ primary_key=["company_number"],
+ parent_field=None,
+ ),
+ OFFICERS: EndpointSpec(
+ path="/company/{company_number}/officers",
+ primary_key=["company_number", "appointment_id"],
+ data_selector="items",
+ total_key="total_results",
+ id_from_self_link="appointment_id",
+ ),
+ PERSONS_WITH_SIGNIFICANT_CONTROL: EndpointSpec(
+ path="/company/{company_number}/persons-with-significant-control",
+ primary_key=["company_number", "psc_id"],
+ data_selector="items",
+ total_key="total_results",
+ id_from_self_link="psc_id",
+ ),
+ PSC_STATEMENTS: EndpointSpec(
+ path="/company/{company_number}/persons-with-significant-control-statements",
+ primary_key=["company_number", "statement_id"],
+ data_selector="items",
+ total_key="total_results",
+ id_from_self_link="statement_id",
+ ),
+ FILING_HISTORY: EndpointSpec(
+ path="/company/{company_number}/filing-history",
+ primary_key=["company_number", "transaction_id"],
+ data_selector="items",
+ total_key="total_count",
+ ),
+ CHARGES: EndpointSpec(
+ path="/company/{company_number}/charges",
+ primary_key=["company_number", "id"],
+ data_selector="items",
+ ),
+ INSOLVENCY: EndpointSpec(
+ path="/company/{company_number}/insolvency",
+ primary_key=["company_number"],
+ ),
+ REGISTERS: EndpointSpec(
+ path="/company/{company_number}/registers",
+ primary_key=["company_number"],
+ ),
+ EXEMPTIONS: EndpointSpec(
+ path="/company/{company_number}/exemptions",
+ primary_key=["company_number"],
+ ),
+ UK_ESTABLISHMENTS: EndpointSpec(
+ path="/company/{company_number}/uk-establishments",
+ # Establishment rows carry their own `company_number`, so the parent lands on a
+ # separate field to avoid overwriting it.
+ primary_key=["parent_company_number", "company_number"],
+ data_selector="items",
+ parent_field="parent_company_number",
+ ),
+}
+
+ENDPOINTS = tuple(ENDPOINT_SPECS.keys())
+
+# Every table is full refresh: none of the Public Data API list endpoints accept an
+# updated-since filter, so there is nothing to build a server-side incremental sync on.
+INCREMENTAL_FIELDS: dict[str, list] = {}
+
+DESCRIPTIONS: dict[str, str] = {
+ COMPANIES: "Company profile for each company number you sync.",
+ OFFICERS: "Current and resigned officers appointed to each company.",
+ PERSONS_WITH_SIGNIFICANT_CONTROL: "People and entities with significant control over each company.",
+ PSC_STATEMENTS: "Statements filed in place of a person with significant control.",
+ FILING_HISTORY: "Documents filed at Companies House for each company.",
+ CHARGES: "Mortgages and charges registered against each company.",
+ INSOLVENCY: "Insolvency status and cases for each company.",
+ REGISTERS: "Which statutory registers each company keeps at Companies House.",
+ EXEMPTIONS: "Exemptions from filing person with significant control information.",
+ UK_ESTABLISHMENTS: "UK establishments of each overseas company.",
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/source.py
index a47d792ddbb0..7564ca3835f5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/source.py
@@ -1,32 +1,183 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ukcompanieshouse import (
UkCompaniesHouseSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.settings import (
+ DESCRIPTIONS,
+ ENDPOINT_SPECS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.uk_companies_house import (
+ UkCompaniesHouseResumeConfig,
+ invalid_company_numbers,
+ parse_company_numbers,
+ uk_companies_house_source,
+ validate_credentials as validate_companies_house_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+NO_COMPANY_NUMBERS_ERROR = "Add at least one company number to sync from Companies House."
+
+
+def _invalid_company_numbers_error(invalid: list[str]) -> str:
+ shown = ", ".join(invalid[:5])
+ suffix = " and others" if len(invalid) > 5 else ""
+ return (
+ f"These are not valid Companies House company numbers: {shown}{suffix}. "
+ "Company numbers are eight characters, so pad shorter numbers with leading zeros."
+ )
+
@SourceRegistry.register
-class UkCompaniesHouseSource(SimpleSource[UkCompaniesHouseSourceConfig]):
+class UkCompaniesHouseSource(ResumableSource[UkCompaniesHouseSourceConfig, UkCompaniesHouseResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # The Public Data API has no version segment, header or param to pin, so the framework
+ # default (unversioned) applies.
+ api_docs_url = (
+ "https://developer-specs.company-information.service.gov.uk/companies-house-public-data-api/reference"
+ )
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.UKCOMPANIESHOUSE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url": "Companies House rejected the API key. Check that it is a live Public Data API key.",
+ "403 Client Error: Forbidden for url": "This Companies House API key cannot read the Public Data API. Check the application type in the developer hub.",
+ NO_COMPANY_NUMBERS_ERROR: NO_COMPANY_NUMBERS_ERROR,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: UkCompaniesHouseSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, descriptions=DESCRIPTIONS)
+
+ def validate_credentials(
+ self,
+ config: UkCompaniesHouseSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ company_numbers = parse_company_numbers(config.company_numbers)
+ if not company_numbers:
+ return False, NO_COMPANY_NUMBERS_ERROR
+
+ invalid = invalid_company_numbers(company_numbers)
+ if invalid:
+ return False, _invalid_company_numbers_error(invalid)
+
+ # One profile lookup proves the key works and that the first company number resolves,
+ # which is the typo most likely to turn a whole sync into 404s.
+ return validate_companies_house_credentials(config.api_key, company_numbers[0])
+
+ def get_resumable_source_manager(
+ self, inputs: SourceInputs
+ ) -> ResumableSourceManager[UkCompaniesHouseResumeConfig]:
+ return ResumableSourceManager[UkCompaniesHouseResumeConfig](inputs, UkCompaniesHouseResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: UkCompaniesHouseSourceConfig,
+ resumable_source_manager: ResumableSourceManager[UkCompaniesHouseResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ endpoint = inputs.schema_name
+ if endpoint not in ENDPOINT_SPECS:
+ raise ValueError(f"Unknown Companies House endpoint: {endpoint}")
+
+ company_numbers = parse_company_numbers(config.company_numbers)
+ if not company_numbers:
+ raise ValueError(NO_COMPANY_NUMBERS_ERROR)
+
+ items = uk_companies_house_source(
+ api_key=config.api_key,
+ endpoint=endpoint,
+ company_numbers=company_numbers,
+ resumable_source_manager=resumable_source_manager,
+ logger=inputs.logger,
+ )
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: items,
+ primary_keys=ENDPOINT_SPECS[endpoint].primary_key,
+ # Companies House documents no ordering for its list endpoints, and rows arrive
+ # grouped by the configured company numbers rather than by time.
+ sort_mode=None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.UK_COMPANIES_HOUSE,
category=DataWarehouseSourceCategory.CRM,
label="Companies House (UK government)",
+ caption="""Sync UK company registry data for the companies you care about, keyed by company number.
+
+Get a free API key by registering an application on the [Companies House developer hub](https://developer.company-information.service.gov.uk/), then create a live key for the Public Data API.
+
+Every table is fetched per company number, so start with the companies you want to enrich rather than the whole register. Companies House allows 600 requests every five minutes.""",
+ docsUrl="https://posthog.com/docs/cdp/sources/uk-companies-house",
iconPath="/static/services/uk_companies_house.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ keywords=["kyb", "firmographics", "uk company registry"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="company_numbers",
+ label="Company numbers",
+ type=SourceFieldInputConfigType.TEXTAREA,
+ required=True,
+ placeholder="00006400, SC123456",
+ secret=False,
+ caption="One company number per line, or separated by commas. Numbers shorter than eight digits are padded with leading zeros.",
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/tests/test_uk_companies_house.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/tests/test_uk_companies_house.py
new file mode 100644
index 000000000000..aa1c6fb6301b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/tests/test_uk_companies_house.py
@@ -0,0 +1,353 @@
+import json
+from typing import Any, Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+from requests import Request, RequestException, Response
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.settings import (
+ CHARGES,
+ COMPANIES,
+ FILING_HISTORY,
+ INSOLVENCY,
+ ITEMS_PER_PAGE,
+ OFFICERS,
+ PERSONS_WITH_SIGNIFICANT_CONTROL,
+ PSC_STATEMENTS,
+ UK_ESTABLISHMENTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.uk_companies_house import (
+ CompaniesHouseOffsetPaginator,
+ UkCompaniesHouseResumeConfig,
+ invalid_company_numbers,
+ parse_company_numbers,
+ uk_companies_house_source,
+ validate_credentials,
+)
+
+SESSION_TARGET = "products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.uk_companies_house.make_tracked_session"
+
+
+def _response(body: Any, status_code: int = 200) -> Response:
+ response = Response()
+ response.status_code = status_code
+ response.url = "https://api.company-information.service.gov.uk/company/00006400"
+ response._content = json.dumps(body).encode()
+ response.headers["Content-Type"] = "application/json"
+ return response
+
+
+def _drive_session(responses: list[Response]) -> tuple[Any, list[tuple[str, dict[str, Any]]]]:
+ """Patch the tracked session so `RESTClient.paginate` runs against canned responses.
+
+ Returns the patcher and the (url, params) actually sent, captured at send time because the
+ paginator mutates one `Request` in place across pages.
+ """
+ sent: list[tuple[str, dict[str, Any]]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent.append((request.url, dict(request.params or {})))
+ return next(response_iter)
+
+ patcher = patch(SESSION_TARGET)
+ mock_make_session = patcher.start()
+ mock_session = mock_make_session.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+ return patcher, sent
+
+
+def _manager(resume: Optional[UkCompaniesHouseResumeConfig] = None) -> MagicMock:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = resume is not None
+ manager.load_state.return_value = resume
+ return manager
+
+
+def _run(endpoint: str, company_numbers: list[str], responses: list[Response], resume=None):
+ patcher, sent = _drive_session(responses)
+ manager = _manager(resume)
+ try:
+ pages = list(
+ uk_companies_house_source(
+ api_key="key",
+ endpoint=endpoint,
+ company_numbers=company_numbers,
+ resumable_source_manager=manager,
+ logger=MagicMock(),
+ )
+ )
+ finally:
+ patcher.stop()
+ return pages, sent, manager
+
+
+class TestParseCompanyNumbers:
+ @parameterized.expand(
+ [
+ ("newlines", "00006400\nSC123456", ["00006400", "SC123456"]),
+ ("commas_and_spaces", "00006400, sc123456 ;OC301365", ["00006400", "SC123456", "OC301365"]),
+ ("zero_pads_short_numeric", "6400", ["00006400"]),
+ ("keeps_alphanumeric_as_typed", "br000123", ["BR000123"]),
+ ("dedupes_preserving_order", "00006400\n6400\nSC123456", ["00006400", "SC123456"]),
+ ("blank", " \n , ", []),
+ ("none", None, []),
+ ]
+ )
+ def test_parse(self, _label: str, raw: Optional[str], expected: list[str]) -> None:
+ assert parse_company_numbers(raw) == expected
+
+ @parameterized.expand(
+ [
+ ("valid_numeric", ["00006400"], []),
+ ("valid_prefixed", ["SC123456", "OC301365", "NI123456"], []),
+ ("too_short", ["ABC123"], ["ABC123"]),
+ ("too_long", ["000064000"], ["000064000"]),
+ ("punctuation", ["0000-640"], ["0000-640"]),
+ ]
+ )
+ def test_invalid_company_numbers(self, _label: str, numbers: list[str], expected: list[str]) -> None:
+ assert invalid_company_numbers(numbers) == expected
+
+
+class TestCompaniesHouseOffsetPaginator:
+ def test_init_request_seeds_offset_params(self) -> None:
+ paginator = CompaniesHouseOffsetPaginator(total_key="total_results", start_index=40)
+ request = Request(method="GET", url="https://api.company-information.service.gov.uk/company/1/officers")
+ paginator.init_request(request)
+
+ assert request.params == {"start_index": 40, "items_per_page": ITEMS_PER_PAGE}
+
+ def test_advances_by_rows_returned_not_requested_page_size(self) -> None:
+ # Companies House caps items_per_page per endpoint and silently returns fewer rows;
+ # striding by the requested size would skip everything it did not send.
+ paginator = CompaniesHouseOffsetPaginator(total_key="total_results", items_per_page=100)
+ rows = [{"n": i} for i in range(35)]
+ paginator.update_state(_response({"total_results": 70, "items": rows}), rows)
+
+ assert paginator.start_index == 35
+ assert paginator.has_next_page is True
+
+ @parameterized.expand(
+ [
+ ("stops_at_total", {"total_results": 2}, [{"n": 1}, {"n": 2}], 2, False),
+ ("continues_below_total", {"total_results": 9}, [{"n": 1}, {"n": 2}], 2, True),
+ ("stops_on_empty_page", {"total_results": 9}, [], 0, False),
+ ("stops_on_short_page_without_total", {}, [{"n": 1}], 1, False),
+ ("continues_on_full_page_without_total", {}, [{"n": 1}, {"n": 2}], 2, True),
+ ("ignores_non_integer_total", {"total_results": "many"}, [{"n": 1}], 1, False),
+ ]
+ )
+ def test_update_state(
+ self,
+ _label: str,
+ body: dict[str, Any],
+ rows: list[dict[str, Any]],
+ expected_start_index: int,
+ expected_has_next: bool,
+ ) -> None:
+ paginator = CompaniesHouseOffsetPaginator(total_key="total_results", items_per_page=2)
+ paginator.update_state(_response(body), rows)
+
+ assert paginator.start_index == expected_start_index
+ assert paginator.has_next_page is expected_has_next
+
+ def test_resume_state_round_trip(self) -> None:
+ paginator = CompaniesHouseOffsetPaginator(total_key="total_results", items_per_page=2)
+ paginator.update_state(_response({"total_results": 9}), [{"n": 1}, {"n": 2}])
+ state = paginator.get_resume_state()
+ assert state == {"start_index": 2}
+
+ resumed = CompaniesHouseOffsetPaginator(total_key="total_results", items_per_page=2)
+ resumed.set_resume_state(state or {})
+ assert resumed.start_index == 2
+ assert resumed.has_next_page is True
+
+ def test_no_resume_state_once_exhausted(self) -> None:
+ paginator = CompaniesHouseOffsetPaginator(total_key="total_results", items_per_page=2)
+ paginator.update_state(_response({"total_results": 1}), [{"n": 1}])
+
+ assert paginator.get_resume_state() is None
+
+
+class TestUkCompaniesHouseSource:
+ @parameterized.expand(
+ [
+ (
+ "profile_is_one_row_untouched",
+ COMPANIES,
+ {"company_number": "00006400", "company_name": "Acme"},
+ [{"company_number": "00006400", "company_name": "Acme"}],
+ ),
+ (
+ "single_object_endpoint_gets_company_number",
+ INSOLVENCY,
+ {"status": "liquidation", "cases": [{"type": "compulsory-liquidation"}]},
+ [
+ {
+ "status": "liquidation",
+ "cases": [{"type": "compulsory-liquidation"}],
+ "company_number": "00006400",
+ }
+ ],
+ ),
+ (
+ "officers_get_appointment_id_from_self_link",
+ OFFICERS,
+ {
+ "total_results": 1,
+ "items": [{"name": "A Person", "links": {"self": "/company/00006400/appointments/xyz"}}],
+ },
+ [
+ {
+ "name": "A Person",
+ "links": {"self": "/company/00006400/appointments/xyz"},
+ "company_number": "00006400",
+ "appointment_id": "xyz",
+ }
+ ],
+ ),
+ (
+ "officers_without_self_link_get_no_id",
+ OFFICERS,
+ {"total_results": 1, "items": [{"name": "A Person"}]},
+ [{"name": "A Person", "company_number": "00006400", "appointment_id": None}],
+ ),
+ (
+ "establishments_keep_their_own_company_number",
+ UK_ESTABLISHMENTS,
+ {"items": [{"company_number": "BR000123", "company_name": "Branch"}]},
+ [
+ {
+ "company_number": "BR000123",
+ "company_name": "Branch",
+ "parent_company_number": "00006400",
+ }
+ ],
+ ),
+ ]
+ )
+ def test_row_normalization_per_endpoint(
+ self, _label: str, endpoint: str, body: dict[str, Any], expected: list[dict[str, Any]]
+ ) -> None:
+ pages, _sent, _manager_mock = _run(endpoint, ["00006400"], [_response(body)])
+
+ assert pages == [expected]
+
+ def test_fans_out_over_every_company_number(self) -> None:
+ pages, sent, manager = _run(
+ OFFICERS,
+ ["00006400", "SC123456"],
+ [
+ _response({"total_results": 1, "items": [{"name": "First"}]}),
+ _response({"total_results": 1, "items": [{"name": "Second"}]}),
+ ],
+ )
+
+ assert [url for url, _params in sent] == [
+ "https://api.company-information.service.gov.uk/company/00006400/officers",
+ "https://api.company-information.service.gov.uk/company/SC123456/officers",
+ ]
+ assert [row["company_number"] for page in pages for row in page] == ["00006400", "SC123456"]
+ manager.clear_state.assert_called_once()
+
+ def test_paginates_one_company_until_the_total_is_reached(self) -> None:
+ pages, sent, _manager_mock = _run(
+ FILING_HISTORY,
+ ["00006400"],
+ [
+ _response({"total_count": 3, "items": [{"transaction_id": "a"}, {"transaction_id": "b"}]}),
+ _response({"total_count": 3, "items": [{"transaction_id": "c"}]}),
+ ],
+ )
+
+ assert [params["start_index"] for _url, params in sent] == [0, 2]
+ assert [row["transaction_id"] for page in pages for row in page] == ["a", "b", "c"]
+
+ @parameterized.expand([(CHARGES,), (PERSONS_WITH_SIGNIFICANT_CONTROL,), (PSC_STATEMENTS,)])
+ def test_missing_resource_does_not_fail_the_table(self, endpoint: str) -> None:
+ # Companies House 404s both for "this company has nothing filed" and for an unknown
+ # company number, and most companies have nothing filed for these resources.
+ pages, sent, _manager_mock = _run(
+ endpoint,
+ ["00006400", "SC123456"],
+ [_response({}, status_code=404), _response({"total_results": 1, "items": [{"id": "1"}]})],
+ )
+
+ assert len(sent) == 2
+ assert [row["company_number"] for page in pages for row in page] == ["SC123456"]
+
+ def test_auth_failure_is_not_swallowed(self) -> None:
+ try:
+ _run(OFFICERS, ["00006400"], [_response({}, status_code=401)])
+ except HTTPError as e:
+ assert e.response is not None
+ assert e.response.status_code == 401
+ else:
+ raise AssertionError("expected the 401 to propagate")
+
+ def test_resume_skips_completed_companies_and_seeds_the_offset(self) -> None:
+ _pages, sent, _manager_mock = _run(
+ OFFICERS,
+ ["00006400", "SC123456", "OC301365"],
+ [
+ _response({"total_results": 101, "items": [{"name": "Resumed"}]}),
+ _response({"total_results": 1, "items": [{"name": "Third"}]}),
+ ],
+ resume=UkCompaniesHouseResumeConfig(company_index=1, start_index=100),
+ )
+
+ assert [(url.rsplit("/company/", 1)[1], params["start_index"]) for url, params in sent] == [
+ ("SC123456/officers", 100),
+ ("OC301365/officers", 0),
+ ]
+
+ def test_saves_progress_after_each_page_and_each_company(self) -> None:
+ _pages, _sent, manager = _run(
+ OFFICERS,
+ ["00006400", "SC123456"],
+ [
+ _response({"total_results": 3, "items": [{"name": "a"}, {"name": "b"}]}),
+ _response({"total_results": 3, "items": [{"name": "c"}]}),
+ _response({"total_results": 1, "items": [{"name": "d"}]}),
+ ],
+ )
+
+ assert [call.args[0] for call in manager.save_state.call_args_list] == [
+ UkCompaniesHouseResumeConfig(company_index=0, start_index=2),
+ UkCompaniesHouseResumeConfig(company_index=1, start_index=0),
+ UkCompaniesHouseResumeConfig(company_index=2, start_index=0),
+ ]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (404, False),
+ (429, False),
+ (500, False),
+ ]
+ )
+ def test_status_mapping(self, status_code: int, expected_ok: bool) -> None:
+ with patch(SESSION_TARGET) as mock_make_session:
+ mock_make_session.return_value.get.return_value = _response({}, status_code=status_code)
+ ok, error = validate_credentials("key", "00006400")
+
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_unreachable_api_is_reported_not_raised(self) -> None:
+ with patch(SESSION_TARGET) as mock_make_session:
+ mock_make_session.return_value.get.side_effect = RequestException("boom")
+ ok, error = validate_credentials("key", "00006400")
+
+ assert ok is False
+ assert error is not None and "Could not reach" in error
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/tests/test_uk_companies_house_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/tests/test_uk_companies_house_source.py
new file mode 100644
index 000000000000..fe4ed90067b2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/tests/test_uk_companies_house_source.py
@@ -0,0 +1,189 @@
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ukcompanieshouse import (
+ UkCompaniesHouseSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.settings import (
+ COMPANIES,
+ ENDPOINT_SPECS,
+ ENDPOINTS,
+ OFFICERS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.source import (
+ NO_COMPANY_NUMBERS_ERROR,
+ UkCompaniesHouseSource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.uk_companies_house import (
+ UkCompaniesHouseResumeConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+VALIDATE_TARGET = "products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.source.validate_companies_house_credentials"
+TRANSPORT_TARGET = "products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.source.uk_companies_house_source"
+
+
+def _make_inputs(schema_name: str, **overrides: Any) -> SourceInputs:
+ defaults: dict = {
+ "schema_name": schema_name,
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestUkCompaniesHouseSource:
+ def setup_method(self) -> None:
+ self.source = UkCompaniesHouseSource()
+ self.config = UkCompaniesHouseSourceConfig(api_key="test-key", company_numbers="6400\nSC123456")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.UKCOMPANIESHOUSE
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static endpoint catalog with no I/O, so it is safe for public docs.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_source_config_is_released(self) -> None:
+ config = self.source.get_source_config
+ assert getattr(config, "unreleasedSource", None) is not True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_source_config_fields(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert [f.name for f in fields] == ["api_key", "company_numbers"]
+
+ api_key = fields[0]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.secret is True
+ assert api_key.required is True
+
+ company_numbers = fields[1]
+ assert isinstance(company_numbers, SourceFieldInputConfig)
+ assert company_numbers.secret is False
+ assert company_numbers.required is True
+
+ def test_get_schemas_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=123)
+
+ assert [schema.name for schema in schemas] == list(ENDPOINTS)
+ # No Companies House list endpoint takes an updated-since filter, so nothing may claim
+ # incremental support.
+ assert all(schema.supports_incremental is False for schema in schemas)
+ assert all(schema.supports_append is False for schema in schemas)
+ assert all(schema.description for schema in schemas)
+
+ def test_get_schemas_honors_the_names_filter(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=123, names=[OFFICERS])
+
+ assert [schema.name for schema in schemas] == [OFFICERS]
+
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_primary_keys_are_unique_table_wide(self, endpoint: str) -> None:
+ # Every child table aggregates rows from every configured company, so the company the row
+ # was fetched for has to be part of the key.
+ spec = ENDPOINT_SPECS[endpoint]
+ if spec.parent_field is None:
+ assert spec.primary_key == ["company_number"]
+ else:
+ assert spec.parent_field in spec.primary_key
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(CANONICAL_DESCRIPTIONS.keys()) == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("blank", "", NO_COMPANY_NUMBERS_ERROR),
+ ("separators_only", " , \n ", NO_COMPANY_NUMBERS_ERROR),
+ ("malformed_number", "not-a-number", "not valid Companies House company numbers: NOT-A-NUMBER"),
+ ]
+ )
+ def test_validate_credentials_rejects_bad_company_numbers_without_calling_the_api(
+ self, _label: str, company_numbers: str, expected_fragment: str
+ ) -> None:
+ config = UkCompaniesHouseSourceConfig(api_key="test-key", company_numbers=company_numbers)
+
+ with patch(VALIDATE_TARGET) as mock_validate:
+ ok, error = self.source.validate_credentials(config, team_id=123)
+
+ assert ok is False
+ assert error is not None and expected_fragment in error
+ mock_validate.assert_not_called()
+
+ def test_validate_credentials_probes_the_first_normalized_company_number(self) -> None:
+ with patch(VALIDATE_TARGET, return_value=(True, None)) as mock_validate:
+ ok, error = self.source.validate_credentials(self.config, team_id=123)
+
+ assert (ok, error) == (True, None)
+ mock_validate.assert_called_once_with("test-key", "00006400")
+
+ def test_get_resumable_source_manager_is_bound_to_the_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs(OFFICERS))
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is UkCompaniesHouseResumeConfig
+
+ def test_source_for_pipeline_passes_parsed_company_numbers(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ inputs = _make_inputs(OFFICERS)
+
+ with patch(TRANSPORT_TARGET, return_value=iter([[{"name": "A"}]])) as mock_transport:
+ response = self.source.source_for_pipeline(self.config, manager, inputs)
+ rows = list(cast("Iterable[Any]", response.items()))
+
+ assert rows == [[{"name": "A"}]]
+ assert mock_transport.call_args.kwargs["company_numbers"] == ["00006400", "SC123456"]
+ assert mock_transport.call_args.kwargs["endpoint"] == OFFICERS
+
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_source_for_pipeline_response_shape(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+
+ with patch(TRANSPORT_TARGET, return_value=iter([])):
+ response = self.source.source_for_pipeline(self.config, manager, _make_inputs(endpoint))
+
+ assert response.name == endpoint
+ assert response.primary_keys == ENDPOINT_SPECS[endpoint].primary_key
+ # Companies House documents no ordering, so the watermark must not be told rows arrive sorted.
+ assert response.sort_mode is None
+
+ def test_source_for_pipeline_rejects_an_unknown_endpoint(self) -> None:
+ with pytest.raises(ValueError, match="Unknown Companies House endpoint"):
+ self.source.source_for_pipeline(
+ self.config, MagicMock(spec=ResumableSourceManager), _make_inputs("NotATable")
+ )
+
+ def test_source_for_pipeline_rejects_an_empty_company_list(self) -> None:
+ config = UkCompaniesHouseSourceConfig(api_key="test-key", company_numbers="")
+
+ with pytest.raises(ValueError, match=NO_COMPANY_NUMBERS_ERROR):
+ self.source.source_for_pipeline(config, MagicMock(spec=ResumableSourceManager), _make_inputs(COMPANIES))
+
+ def test_non_retryable_errors_cover_auth_failures(self) -> None:
+ errors = self.source.get_non_retryable_errors()
+
+ assert any("401" in key for key in errors)
+ assert any("403" in key for key in errors)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/uk_companies_house.py b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/uk_companies_house.py
new file mode 100644
index 000000000000..4187c0a3cd58
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/uk_companies_house/uk_companies_house.py
@@ -0,0 +1,272 @@
+import re
+import dataclasses
+from collections.abc import Callable, Iterator
+from typing import Any, Optional
+
+from requests import Request, RequestException, Response
+from requests.exceptions import HTTPError
+from structlog.types import FilteringBoundLogger
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import HttpBasicAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.uk_companies_house.settings import (
+ BASE_URL,
+ ENDPOINT_SPECS,
+ ITEMS_PER_PAGE,
+ REQUEST_TIMEOUT,
+ EndpointSpec,
+)
+
+# Company numbers are eight characters at Companies House: digits, or a two letter registrar
+# prefix (SC, NI, OC, OE, BR) followed by six characters.
+COMPANY_NUMBER_PATTERN = re.compile(r"^[A-Z0-9]{8}$")
+
+_SEPARATORS = re.compile(r"[\s,;]+")
+
+
+class UkCompaniesHouseResumeConfig:
+ """Where a sync got to across the configured company numbers.
+
+ ``company_index`` is the position in the configured company number list, so resume relies on
+ that list being the same one the job started with. It is, because resume state is keyed by
+ job id and a job runs against a single snapshot of the source config.
+ """
+
+ company_index: int = 0
+ start_index: int = 0
+
+
+class CompaniesHouseOffsetPaginator(BasePaginator):
+ """Offset pagination over ``start_index`` / ``items_per_page``.
+
+ Advances by the number of rows actually returned rather than by the requested page size:
+ Companies House caps ``items_per_page`` per endpoint and quietly returns fewer rows than
+ asked for, so a fixed stride would step over the rows it did not send.
+ """
+
+ def __init__(
+ self,
+ total_key: str,
+ items_per_page: int = ITEMS_PER_PAGE,
+ start_index: int = 0,
+ ) -> None:
+ super().__init__()
+ self.total_key = total_key
+ self.items_per_page = items_per_page
+ self.start_index = start_index
+
+ def init_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def update_request(self, request: Request) -> None:
+ self._apply(request)
+
+ def _apply(self, request: Request) -> None:
+ if request.params is None:
+ request.params = {}
+ request.params["start_index"] = self.start_index
+ request.params["items_per_page"] = self.items_per_page
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ if not data:
+ self._has_next_page = False
+ return
+
+ self.start_index += len(data)
+
+ try:
+ body = response.json()
+ except Exception:
+ body = None
+
+ total = body.get(self.total_key) if isinstance(body, dict) else None
+ if isinstance(total, int) and not isinstance(total, bool):
+ self._has_next_page = self.start_index < total
+ return
+
+ # No usable total in the body, so a short page is the only end-of-results signal left.
+ self._has_next_page = len(data) >= self.items_per_page
+
+ def get_resume_state(self) -> Optional[dict[str, Any]]:
+ return {"start_index": self.start_index} if self._has_next_page else None
+
+ def set_resume_state(self, state: dict[str, Any]) -> None:
+ start_index = state.get("start_index")
+ if start_index:
+ self.start_index = int(start_index)
+ self._has_next_page = True
+
+ def __str__(self) -> str:
+ return f"CompaniesHouseOffsetPaginator(start_index={self.start_index}, items_per_page={self.items_per_page})"
+
+
+def parse_company_numbers(raw: Optional[str]) -> list[str]:
+ """Split the configured company numbers and normalize them to the registry's eight character
+ form. Purely numeric input is zero padded, which is how Companies House writes short numbers:
+ company 6400 is 00006400."""
+ numbers: list[str] = []
+ seen: set[str] = set()
+ for token in _SEPARATORS.split(raw or ""):
+ candidate = token.strip().upper()
+ if not candidate:
+ continue
+ if candidate.isdigit():
+ candidate = candidate.zfill(8)
+ if candidate in seen:
+ continue
+ seen.add(candidate)
+ numbers.append(candidate)
+ return numbers
+
+
+def invalid_company_numbers(company_numbers: list[str]) -> list[str]:
+ return [number for number in company_numbers if not COMPANY_NUMBER_PATTERN.match(number)]
+
+
+def _client(api_key: str) -> RESTClient:
+ # The key is the HTTP Basic username with a blank password, so `HttpBasicAuth.secret_values`
+ # (which only reports the password) would not redact it. Pass a session that masks it directly.
+ return RESTClient(
+ base_url=BASE_URL,
+ auth=HttpBasicAuth(username=api_key, password=""),
+ session=make_tracked_session(redact_values=(api_key,), allow_redirects=False),
+ allowed_hosts=[],
+ allow_redirects=False,
+ request_timeout=REQUEST_TIMEOUT,
+ )
+
+
+def _id_from_self_link(row: dict[str, Any]) -> Optional[str]:
+ links = row.get("links")
+ self_link = links.get("self") if isinstance(links, dict) else None
+ if not isinstance(self_link, str):
+ return None
+ return self_link.rstrip("/").rsplit("/", 1)[-1] or None
+
+
+def _normalize(row: dict[str, Any], spec: EndpointSpec, company_number: str) -> dict[str, Any]:
+ normalized = dict(row)
+ if spec.parent_field:
+ normalized[spec.parent_field] = company_number
+ if spec.id_from_self_link:
+ normalized[spec.id_from_self_link] = _id_from_self_link(row)
+ return normalized
+
+
+def _rows_for_company(
+ client: RESTClient,
+ spec: EndpointSpec,
+ company_number: str,
+ logger: FilteringBoundLogger,
+ resume_hook: Callable[[Optional[dict[str, Any]]], None],
+ initial_paginator_state: Optional[dict[str, Any]],
+) -> Iterator[list[dict[str, Any]]]:
+ paginator: BasePaginator = (
+ CompaniesHouseOffsetPaginator(total_key=spec.total_key) if spec.total_key else SinglePagePaginator()
+ )
+
+ pages = client.paginate(
+ path=spec.path.format(company_number=company_number),
+ paginator=paginator,
+ data_selector=spec.data_selector,
+ resume_hook=resume_hook,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ try:
+ for page in pages:
+ rows = [_normalize(row, spec, company_number) for row in page if isinstance(row, dict)]
+ if rows:
+ yield rows
+ except HTTPError as e:
+ status_code = e.response.status_code if e.response is not None else None
+ if status_code == 404:
+ # Companies House answers 404 both for a company that has nothing filed for this
+ # resource (most companies have no charges, insolvency or exemptions) and for a
+ # company number that does not exist. Neither should fail the whole table.
+ logger.info(
+ "Companies House returned no data for a company",
+ company_number=company_number,
+ path=spec.path,
+ )
+ return
+ raise
+
+
+def uk_companies_house_source(
+ api_key: str,
+ endpoint: str,
+ company_numbers: list[str],
+ resumable_source_manager: ResumableSourceManager[UkCompaniesHouseResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ spec = ENDPOINT_SPECS[endpoint]
+ client = _client(api_key)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ first_index = resume.company_index if resume else 0
+ seeded_start_index = resume.start_index if resume else 0
+
+ for index, company_number in enumerate(company_numbers):
+ if index < first_index:
+ continue
+
+ initial_paginator_state = (
+ {"start_index": seeded_start_index} if (index == first_index and seeded_start_index) else None
+ )
+
+ def checkpoint(state: Optional[dict[str, Any]], _index: int = index) -> None:
+ # `RESTClient.paginate` deep copies the paginator, so this hook is the only view onto
+ # the copy's progress. Saving after each yielded page means a crash re-yields the last
+ # page rather than skipping it.
+ if state and state.get("start_index"):
+ resumable_source_manager.save_state(
+ UkCompaniesHouseResumeConfig(company_index=_index, start_index=int(state["start_index"]))
+ )
+
+ yield from _rows_for_company(
+ client,
+ spec,
+ company_number,
+ logger,
+ resume_hook=checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ resumable_source_manager.save_state(UkCompaniesHouseResumeConfig(company_index=index + 1, start_index=0))
+
+ resumable_source_manager.clear_state()
+
+
+def validate_credentials(api_key: str, company_number: str) -> tuple[bool, str | None]:
+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+ try:
+ response = session.get(
+ f"{BASE_URL}/company/{company_number}",
+ auth=(api_key, ""),
+ timeout=REQUEST_TIMEOUT,
+ )
+ except RequestException as e:
+ return False, f"Could not reach the Companies House API: {e}"
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Companies House rejected the API key. Check that it is a live Public Data API key."
+ if response.status_code == 403:
+ return (
+ False,
+ "This Companies House API key cannot read the Public Data API. Check the application type in the developer hub.",
+ )
+ if response.status_code == 404:
+ return False, f"Companies House has no company with number {company_number}."
+ if response.status_code == 429:
+ return False, "Companies House rate limited the request. Wait a few minutes and try again."
+ return False, f"Companies House API returned HTTP {response.status_code}."