: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse_sources): support EZOfficeInventory API version v2 (#80105)
Tom Owersac711b0f7559
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.mdindex 53eed4081bbd..0e9cdc017b68 100644--- a/.agents/skills/warehouse-source-new-version/SKILL.md+++ b/.agents/skills/warehouse-source-new-version/SKILL.md@@ -86,6 +86,7 @@ Add it when any of these hold:- When a versioned source starts consuming the discovery `api_version` parameter, add the vendor's version-rejection error signature to `get_non_retryable_errors` — otherwise a retired pin turns the ~6h discovery cadence into a permanent retry/error loop with no user-facing surface.- A version bump can change the auth scheme, not just the wire format. Then the source config needs both credential shapes as optional fields, auth construction dispatches on the resolved version, and `validate_credentials` enforces the pair that version needs — form-level `required` can't express "depends on the pin".- When the vendor renames a collection between versions, keep the schema/table name set identical across versions and put the rename in a per-version path on the endpoint config — otherwise discovery diffs orphan the table on repin.+- When the new version has no equivalent for an old endpoint (a dropped collection, not a rename), keep that table only on the versions that serve it and let the table set differ by version — never map it to a guessed path just to keep the sets equal, since docs are the sole source of truth and an unverified path makes a new source surface a table that 404s at sync time.## Self-improvementdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.com.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.com.mdxindex efc4f8dea778..a8853b6505ff 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.com.mdx+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.com.mdx@@ -31,8 +31,8 @@ Before connecting, you need:- An EZOfficeInventory account with **API access enabled**. API access is off by default — the accountowner enables it in **Settings → Integrations → API Integration**.-- A company **access token**, generated on that same settings page. The token is sent in the `token`- HTTP header over HTTPS on every request, so keep it secret and regenerate it if it is compromised.+- A company **access token**, generated on that same settings page. The token is sent over HTTPS on+ every request, so keep it secret and regenerate it if it is compromised.- Your account **subdomain** — the `<subdomain>` in `https://<subdomain>.ezofficeinventory.com`.## Adding a data sourcediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.pyindex 2a950861c152..8a7cf1f4ed45 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/ezofficeinventory.py@@ -13,14 +13,22 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ BasePaginator,+ JSONResponsePaginator,PageNumberPaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ApiKeyAuthConfig,+ AuthConfig,+ BearerTokenAuthConfig,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinventory.settings import (- EZOFFICEINVENTORY_ENDPOINTS,+ EZOFFICEINVENTORY_API_VERSION_V2,EZOfficeInventoryEndpointConfig,+ endpoints_for_version,)# EZOfficeInventory enforces a per-account hostname, so only the subdomain label is user-supplied.@@ -30,14 +38,35 @@ SUBDOMAIN_REGEX = re.compile(r"^[a-zA-Z0-9-]+$")@dataclasses.dataclassclass EZOfficeInventoryResumeConfig:- # Next page (1-indexed) to fetch when resuming an interrupted sync.- next_page: int+ # v1 page-number paginator: next page (1-indexed) to fetch when resuming an interrupted sync.+ next_page: Optional[int] = None+ # v2 next-URL paginator: absolute URL of the next page to fetch when resuming.+ next_url: Optional[str] = Nonedef base_url(subdomain: str) -> str:return f"https://{subdomain}.ezofficeinventory.com"+def _auth_config(api_version: str, api_key: str) -> AuthConfig:+ # v2 authenticates with `Authorization: Bearer <token>`; v1 sends the token in a `token`+ # header. Either way the value is supplied via the framework auth config so it's redacted+ # from logs and raised error messages.+ if api_version == EZOFFICEINVENTORY_API_VERSION_V2:+ return BearerTokenAuthConfig(type="bearer", token=api_key)+ return ApiKeyAuthConfig(type="api_key", api_key=api_key, name="token", location="header")+++def _paginator(api_version: str) -> BasePaginator:+ if api_version == EZOFFICEINVENTORY_API_VERSION_V2:+ # v2 returns a self-contained absolute URL for the next page under `metadata.next_page`+ # (null on the last page); follow it. `allowed_hosts=[]` still pins it to the subdomain.+ return JSONResponsePaginator(next_url_path="metadata.next_page")+ # `total_pages` is the total number of PAGES; the paginator stops after it. When the API+ # omits it, an empty page terminates instead (stop_after_empty_page).+ return PageNumberPaginator(base_page=1, page=1, page_param="page", total_path="total_pages")++def _make_unwrap_map(unwrap_key: str) -> Callable[[dict[str, Any]], dict[str, Any]]:"""Some list endpoints wrap each record in a single-key object (e.g. groups returns`{"groups": [{"group": {...}}]}`); unwrap it, falling back to the row untouched when the@@ -51,14 +80,14 @@ def _make_unwrap_map(unwrap_key: str) -> Callable[[dict[str, Any]], dict[str, Anreturn _unwrap-def _rest_config(subdomain: str, api_key: str, config: EZOfficeInventoryEndpointConfig) -> RESTAPIConfig:+def _rest_config(+ subdomain: str, api_key: str, config: EZOfficeInventoryEndpointConfig, api_version: str+) -> RESTAPIConfig:endpoint: Endpoint = {"path": config.path,"params": dict(config.extra_params),"data_selector": config.data_selector,- # `total_pages` is the total number of PAGES; the paginator stops after it. When the API- # omits it, an empty page terminates instead (stop_after_empty_page).- "paginator": PageNumberPaginator(base_page=1, page=1, page_param="page", total_path="total_pages"),+ "paginator": _paginator(api_version),}resource: EndpointResource = {"name": config.name, "endpoint": endpoint}if config.unwrap_key:@@ -67,10 +96,9 @@ def _rest_config(subdomain: str, api_key: str, config: EZOfficeInventoryEndpointreturn {"client": {"base_url": base_url(subdomain),- # Auth (token header) is supplied via the framework auth config so its value is redacted- # from logs and raised error messages; only the non-secret Accept header is set here.+ # Only the non-secret Accept header is set here; the token goes through the auth config."headers": {"Accept": "application/json"},- "auth": {"type": "api_key", "api_key": api_key, "name": "token", "location": "header"},+ "auth": _auth_config(api_version, api_key),# Pin every request (including paginator/resume URLs) to the subdomain host and reject# cross-host redirects — the user-supplied token must not be replayable off-host# (SSRF / credential-exfiltration defense-in-depth). `allowed_hosts=[]` means@@ -89,24 +117,33 @@ def ezofficeinventory_source(team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[EZOfficeInventoryResumeConfig],+ api_version: str,db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:- config = EZOFFICEINVENTORY_ENDPOINTS[endpoint]+ config = endpoints_for_version(api_version)[endpoint]initial_paginator_state: Optional[dict[str, Any]] = Noneif resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()if resume is not None:- initial_paginator_state = {"page": resume.next_page}+ if resume.next_url is not None:+ initial_paginator_state = {"next_url": resume.next_url}+ elif resume.next_page is not None:+ initial_paginator_state = {"page": resume.next_page}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:# Persist only when a next page remains; save AFTER a page is yielded so a crash re-fetches- # the page we just emitted rather than skipping it — merge dedupes the re-yielded rows.- if state and state.get("page") is not None:+ # the page we just emitted rather than skipping it — merge dedupes the re-yielded rows. The+ # paginator dictates the checkpoint shape: v2 carries a next-URL, v1 a page number.+ if not state:+ return+ if state.get("next_url"):+ resumable_source_manager.save_state(EZOfficeInventoryResumeConfig(next_url=str(state["next_url"])))+ elif state.get("page") is not None:resumable_source_manager.save_state(EZOfficeInventoryResumeConfig(next_page=int(state["page"])))resource = rest_api_resource(- _rest_config(subdomain, api_key, config),+ _rest_config(subdomain, api_key, config, api_version),team_id,job_id,db_incremental_field_last_value,@@ -125,19 +162,28 @@ def ezofficeinventory_source()-def validate_credentials(api_key: str, subdomain: str) -> tuple[bool, str | None]:+def validate_credentials(api_key: str, subdomain: str, api_version: str) -> tuple[bool, str | None]:"""Return (is_valid, error_message). A non-None message overrides the generic"invalid credentials" error so transient failures (e.g. rate limiting) aren'tmisreported as bad credentials."""if not SUBDOMAIN_REGEX.match(subdomain):return False, None+ # Probe the assets list under the resolved version so a passing probe reflects the same+ # base path and auth scheme the sync will use, not just that the token is well-formed.+ if api_version == EZOFFICEINVENTORY_API_VERSION_V2:+ probe_url = f"{base_url(subdomain)}/api/v2/assets"+ headers = {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}+ else:+ probe_url = f"{base_url(subdomain)}/assets.api?page=1"+ headers = {"token": api_key, "Accept": "application/json"}+ok, status = validate_via_probe(# Redirects pinned off and urllib3 retries disabled so the token can't be replayed to a# cross-host redirect target during a single-shot probe.lambda: make_tracked_session(redact_values=(api_key,), allow_redirects=False, retry=Retry(total=0)),- f"{base_url(subdomain)}/assets.api?page=1",- headers={"token": api_key, "Accept": "application/json"},+ probe_url,+ headers=headers,)if ok:return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/settings.pyindex 59cb0ff38f92..0c752da3fa45 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/settings.py@@ -3,6 +3,11 @@ from typing import Optionalfrom products.warehouse_sources.backend.types import IncrementalField+# Vendor API version labels. v1 is the legacy `*.api` interface (token header, page-number+# pagination); v2 is the GA `/api/v2/` REST interface (bearer token, next-URL pagination).+EZOFFICEINVENTORY_API_VERSION_V1 = "v1"+EZOFFICEINVENTORY_API_VERSION_V2 = "v2"+@dataclassclass EZOfficeInventoryEndpointConfig:@@ -117,5 +122,78 @@ EZOFFICEINVENTORY_ENDPOINTS: dict[str, EZOfficeInventoryEndpointConfig] = {ENDPOINTS = tuple(EZOFFICEINVENTORY_ENDPOINTS.keys())+# v2 (`/api/v2/`) serves the core inventory resources as flat REST list endpoints. Paths and+# response envelopes differ from v1: records are no longer wrapped per row (no `unwrap_key`), the+# list key is renamed for some resources (inventory, stock assets), and vendors expose no+# `created_at`, so that table can't be datetime-partitioned under v2. The v1-only endpoints+# (`checked_out_assets`, `subgroups`, `labels`, `custom_fields`) have no flat v2 list equivalent+# and stay v1-only — pinned v1 sources keep serving them.+EZOFFICEINVENTORY_V2_ENDPOINTS: dict[str, EZOfficeInventoryEndpointConfig] = {+ "assets": EZOfficeInventoryEndpointConfig(+ name="assets",+ path="api/v2/assets",+ data_selector="assets",+ primary_keys=["identifier"],+ partition_key="created_at",+ ),+ "inventories": EZOfficeInventoryEndpointConfig(+ name="inventories",+ path="api/v2/inventory",+ data_selector="inventory",+ primary_keys=["identifier"],+ partition_key="created_at",+ ),+ "asset_stocks": EZOfficeInventoryEndpointConfig(+ name="asset_stocks",+ path="api/v2/stock_assets",+ data_selector="asset_stock",+ primary_keys=["identifier"],+ partition_key="created_at",+ ),+ "members": EZOfficeInventoryEndpointConfig(+ name="members",+ path="api/v2/members",+ data_selector="members",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "locations": EZOfficeInventoryEndpointConfig(+ name="locations",+ path="api/v2/locations",+ data_selector="locations",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "groups": EZOfficeInventoryEndpointConfig(+ name="groups",+ path="api/v2/groups",+ data_selector="groups",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "vendors": EZOfficeInventoryEndpointConfig(+ name="vendors",+ path="api/v2/vendors",+ data_selector="vendors",+ primary_keys=["id"],+ ),+ "purchase_orders": EZOfficeInventoryEndpointConfig(+ name="purchase_orders",+ path="api/v2/purchase_orders",+ data_selector="purchase_orders",+ primary_keys=["id"],+ partition_key="created_at",+ ),+}++V2_ENDPOINTS = tuple(EZOFFICEINVENTORY_V2_ENDPOINTS.keys())+++def endpoints_for_version(api_version: str) -> dict[str, EZOfficeInventoryEndpointConfig]:+ if api_version == EZOFFICEINVENTORY_API_VERSION_V2:+ return EZOFFICEINVENTORY_V2_ENDPOINTS+ return EZOFFICEINVENTORY_ENDPOINTS++# Every endpoint is full refresh — no server-side timestamp filter is available.INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/source.pyindex ae068ef8055f..956c4e0851bd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/source.py@@ -23,9 +23,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinvalidate_credentials as validate_ezofficeinventory_credentials,)from products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinventory.settings import (- ENDPOINTS,- EZOFFICEINVENTORY_ENDPOINTS,+ EZOFFICEINVENTORY_API_VERSION_V1,+ EZOFFICEINVENTORY_API_VERSION_V2,INCREMENTAL_FIELDS,+ endpoints_for_version,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.ezofficeinventory import (EZOfficeInventorySourceConfig,@@ -40,6 +41,11 @@ class EZOfficeInventorySource(ResumableSource[EZOfficeInventorySourceConfig, EZOlists_tables_without_credentials = Trueapi_docs_url = "https://ezo.io/ezofficeinventory/developers/"+ # Declare oldest→newest; the default is always the last entry. New sources start on v2 (the+ # GA `/api/v2/` REST API); existing v1 pins keep serving the legacy `*.api` interface.+ supported_versions = (EZOFFICEINVENTORY_API_VERSION_V1, EZOFFICEINVENTORY_API_VERSION_V2)+ default_version = EZOFFICEINVENTORY_API_VERSION_V2+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.EZOFFICEINVENTORY@@ -73,16 +79,17 @@ class EZOfficeInventorySource(ResumableSource[EZOfficeInventorySourceConfig, EZOforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:+ endpoints = endpoints_for_version(self.resolve_api_version(api_version))schemas = [SourceSchema(name=endpoint,supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,supports_append=INCREMENTAL_FIELDS.get(endpoint) is not None,incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),- detected_primary_keys=EZOFFICEINVENTORY_ENDPOINTS[endpoint].primary_keys,- should_sync_default=EZOFFICEINVENTORY_ENDPOINTS[endpoint].should_sync_default,+ detected_primary_keys=config.primary_keys,+ should_sync_default=config.should_sync_default,)- for endpoint in list(ENDPOINTS)+ for endpoint, config in endpoints.items()]if names is not None:@@ -98,7 +105,9 @@ class EZOfficeInventorySource(ResumableSource[EZOfficeInventorySourceConfig, EZOschema_name: Optional[str] = None,api_version: str | None = None,) -> tuple[bool, str | None]:- is_valid, error_message = validate_ezofficeinventory_credentials(config.api_key, config.subdomain)+ is_valid, error_message = validate_ezofficeinventory_credentials(+ config.api_key, config.subdomain, self.resolve_api_version(api_version)+ )if is_valid:return True, None@@ -126,6 +135,7 @@ class EZOfficeInventorySource(ResumableSource[EZOfficeInventorySourceConfig, EZOteam_id=inputs.team_id,job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,+ api_version=self.resolve_api_version(inputs.api_version),db_incremental_field_last_value=None, # every EZOfficeInventory endpoint is full refresh)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory.pyindex e4114db2d841..5ef1620c7304 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory.py@@ -1,17 +1,31 @@import json-from typing import Any+from typing import Any, castimport pytestfrom unittest import mockfrom requests import Response+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ JSONResponsePaginator,+ PageNumberPaginator,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClientfrom products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinventory.ezofficeinventory import (EZOfficeInventoryResumeConfig,+ _rest_config,ezofficeinventory_source,validate_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinventory.settings import (+ EZOFFICEINVENTORY_API_VERSION_V1,+ EZOFFICEINVENTORY_API_VERSION_V2,+ endpoints_for_version,+)# RESTClient builds its session via make_tracked_session in the rest_client module.CLIENT_SESSION_PATCH = "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"@@ -62,7 +76,7 @@ def _rows(source_response) -> list[dict[str, Any]]:return [row for page in source_response.items() for row in page]-def _source(endpoint: str, manager: mock.MagicMock):+def _source(endpoint: str, manager: mock.MagicMock, api_version: str = EZOFFICEINVENTORY_API_VERSION_V1):return ezofficeinventory_source(api_key="tok",subdomain="acme",@@ -70,6 +84,7 @@ def _source(endpoint: str, manager: mock.MagicMock):team_id=1,job_id="job",resumable_source_manager=manager,+ api_version=api_version,)@@ -226,7 +241,7 @@ class TestValidateCredentials:@pytest.mark.parametrize("bad_subdomain", ["", "has space", "bad/slash", "a.b", "http://x"])def test_rejects_unsafe_subdomain_without_network(self, bad_subdomain: str) -> None:with mock.patch(EZO_SESSION_PATCH) as mocked:- assert validate_credentials("tok", bad_subdomain) == (False, None)+ assert validate_credentials("tok", bad_subdomain, EZOFFICEINVENTORY_API_VERSION_V1) == (False, None)mocked.assert_not_called()@pytest.mark.parametrize(@@ -237,14 +252,43 @@ class TestValidateCredentials:session = mock.MagicMock()session.get.return_value = _response({}, status_code=status_code)with mock.patch(EZO_SESSION_PATCH, return_value=session):- is_valid, _ = validate_credentials("tok", "acme")+ is_valid, _ = validate_credentials("tok", "acme", EZOFFICEINVENTORY_API_VERSION_V1)assert is_valid is expected+ @pytest.mark.parametrize(+ ("api_version", "expected_url", "expected_header"),+ [+ (+ EZOFFICEINVENTORY_API_VERSION_V1,+ "https://acme.ezofficeinventory.com/assets.api?page=1",+ ("token", "tok"),+ ),+ (+ EZOFFICEINVENTORY_API_VERSION_V2,+ "https://acme.ezofficeinventory.com/api/v2/assets",+ ("Authorization", "Bearer tok"),+ ),+ ],+ )+ def test_probes_versioned_path_and_auth(+ self, api_version: str, expected_url: str, expected_header: tuple[str, str]+ ) -> None:+ # A passing probe must exercise the same base path and auth scheme the sync will use for+ # that version — otherwise the probe validates a path the pinned sync never calls.+ session = mock.MagicMock()+ session.get.return_value = _response({}, status_code=200)+ with mock.patch(EZO_SESSION_PATCH, return_value=session):+ is_valid, _ = validate_credentials("tok", "acme", api_version)+ assert is_valid is True+ assert session.get.call_args.args[0] == expected_url+ header_name, header_value = expected_header+ assert session.get.call_args.kwargs["headers"][header_name] == header_value+def test_rate_limit_returns_specific_message(self) -> None:session = mock.MagicMock()session.get.return_value = _response({}, status_code=429)with mock.patch(EZO_SESSION_PATCH, return_value=session):- is_valid, error = validate_credentials("tok", "acme")+ is_valid, error = validate_credentials("tok", "acme", EZOFFICEINVENTORY_API_VERSION_V1)assert is_valid is Falseassert error is not Noneassert "rate limit" in error.lower()@@ -253,7 +297,7 @@ class TestValidateCredentials:session = mock.MagicMock()session.get.return_value = _response({}, status_code=200)with mock.patch(EZO_SESSION_PATCH, return_value=session) as mocked:- validate_credentials("tok", "acme")+ validate_credentials("tok", "acme", EZOFFICEINVENTORY_API_VERSION_V1)assert mocked.call_args.kwargs["allow_redirects"] is False# Single-shot validation handles status codes itself; urllib3 retries stay off.assert mocked.call_args.kwargs["retry"].total == 0@@ -262,4 +306,84 @@ class TestValidateCredentials:session = mock.MagicMock()session.get.side_effect = Exception("boom")with mock.patch(EZO_SESSION_PATCH, return_value=session):- assert validate_credentials("tok", "acme") == (False, None)+ assert validate_credentials("tok", "acme", EZOFFICEINVENTORY_API_VERSION_V1) == (False, None)+++class TestVersionedRequestConfig:+ @pytest.mark.parametrize(+ ("api_version", "expected_path", "expected_auth", "paginator_cls"),+ [+ (+ EZOFFICEINVENTORY_API_VERSION_V1,+ "assets.api",+ {"type": "api_key", "api_key": "tok", "name": "token", "location": "header"},+ PageNumberPaginator,+ ),+ (+ EZOFFICEINVENTORY_API_VERSION_V2,+ "api/v2/assets",+ {"type": "bearer", "token": "tok"},+ JSONResponsePaginator,+ ),+ ],+ )+ def test_builds_versioned_client(+ self, api_version: str, expected_path: str, expected_auth: dict, paginator_cls: type+ ) -> None:+ config = endpoints_for_version(api_version)["assets"]+ rest_config = _rest_config("acme", "tok", config, api_version)++ resource = cast(EndpointResource, rest_config["resources"][0])+ endpoint = cast(Endpoint, resource["endpoint"])+ assert endpoint["path"] == expected_path+ assert rest_config["client"]["auth"] == expected_auth+ assert isinstance(endpoint["paginator"], paginator_cls)+ # The host pin and redirect lock-down must hold on every version.+ assert rest_config["client"]["allowed_hosts"] == []+ assert rest_config["client"]["allow_redirects"] is False+++class TestV2Pagination:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_follows_metadata_next_page_and_saves_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ next_url = "https://acme.ezofficeinventory.com/api/v2/assets?page=2"+ _wire(+ session,+ [+ _response({"assets": [{"identifier": 1}], "metadata": {"next_page": next_url}}),+ _response({"assets": [{"identifier": 2}], "metadata": {"next_page": None}}),+ ],+ )++ manager = _make_manager()+ rows = _rows(_source("assets", manager, api_version=EZOFFICEINVENTORY_API_VERSION_V2))++ assert rows == [{"identifier": 1}, {"identifier": 2}]+ assert session.send.call_count == 2+ # Checkpoint carries the next-page URL, not a page number — the v2 resume shape.+ manager.save_state.assert_called_once_with(EZOfficeInventoryResumeConfig(next_url=next_url))++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_from_saved_cursor(self, MockSession) -> None:+ session = MockSession.return_value+ next_url = "https://acme.ezofficeinventory.com/api/v2/assets?page=2"+ _wire(session, [_response({"assets": [{"identifier": 2}], "metadata": {"next_page": None}})])++ manager = _make_manager(EZOfficeInventoryResumeConfig(next_url=next_url))+ rows = _rows(_source("assets", manager, api_version=EZOFFICEINVENTORY_API_VERSION_V2))++ assert rows == [{"identifier": 2}]+ # One request only: the saved cursor is the starting point, not page 1 followed by it.+ assert session.send.call_count == 1+ manager.save_state.assert_not_called()++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_uses_renamed_v2_selector(self, MockSession) -> None:+ # v2 renamed the inventory list key from `volatile_assets` to `inventory`; a wrong selector+ # would silently yield zero rows.+ session = MockSession.return_value+ _wire(session, [_response({"inventory": [{"identifier": 7}], "metadata": {"next_page": None}})])++ rows = _rows(_source("inventories", _make_manager(), api_version=EZOFFICEINVENTORY_API_VERSION_V2))+ assert rows == [{"identifier": 7}]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory_source.pyindex c31cc7a08b0e..de9819fb1618 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/ezofficeinventory/tests/test_ezofficeinventory_source.py@@ -8,7 +8,12 @@ from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFiefrom products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinventory.ezofficeinventory import (EZOfficeInventoryResumeConfig,)-from products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinventory.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinventory.settings import (+ ENDPOINTS,+ EZOFFICEINVENTORY_API_VERSION_V1,+ EZOFFICEINVENTORY_API_VERSION_V2,+ V2_ENDPOINTS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.ezofficeinventory.source import (EZOfficeInventorySource,)@@ -49,14 +54,36 @@ class TestSourceConfig:assert EZOfficeInventorySource().connection_host_fields == ["subdomain"]+class TestSourceVersions:+ def test_v2_is_the_default(self) -> None:+ # New sources are stamped with default_version; the whole point of this bump is that they+ # land on v2 while existing v1 pins are untouched.+ source = EZOfficeInventorySource()+ assert source.default_version == EZOFFICEINVENTORY_API_VERSION_V2+ assert source.supported_versions == (EZOFFICEINVENTORY_API_VERSION_V1, EZOFFICEINVENTORY_API_VERSION_V2)++class TestGetSchemas:- def test_returns_all_endpoints_full_refresh(self) -> None:- schemas = EZOfficeInventorySource().get_schemas(_config(), team_id=1)- assert {s.name for s in schemas} == set(ENDPOINTS)+ @pytest.mark.parametrize(+ ("api_version", "expected_names"),+ [+ (EZOFFICEINVENTORY_API_VERSION_V1, set(ENDPOINTS)),+ (EZOFFICEINVENTORY_API_VERSION_V2, set(V2_ENDPOINTS)),+ ],+ )+ def test_returns_version_specific_endpoints_full_refresh(self, api_version: str, expected_names: set) -> None:+ schemas = EZOfficeInventorySource().get_schemas(_config(), team_id=1, api_version=api_version)+ assert {s.name for s in schemas} == expected_names# EZOfficeInventory exposes no server-side cursor — every table is full refresh.assert all(not s.supports_incremental for s in schemas)assert all(not s.supports_append for s in schemas)+ def test_defaults_to_v2_endpoints(self) -> None:+ # No pin resolves to default_version (v2), so a v1-only table must not appear.+ schemas = {s.name for s in EZOfficeInventorySource().get_schemas(_config(), team_id=1)}+ assert schemas == set(V2_ENDPOINTS)+ assert "labels" not in schemas+def test_primary_keys_are_endpoint_specific(self) -> None:schemas = {s.name: s for s in EZOfficeInventorySource().get_schemas(_config(), team_id=1)}assert schemas["assets"].detected_primary_keys == ["identifier"]@@ -70,7 +97,8 @@ class TestGetSchemas:source = EZOfficeInventorySource()assert source.lists_tables_without_credentials is Truetables = source.get_documented_tables()- assert {t["name"] for t in tables} == set(ENDPOINTS)+ # Public docs render the default version's catalog.+ assert {t["name"] for t in tables} == set(V2_ENDPOINTS)# Curated descriptions flow through from canonical_descriptions.py.assets = next(t for t in tables if t["name"] == "assets")assert assets["description"]@@ -85,7 +113,8 @@ class TestValidateCredentials:def test_delegates_to_transport(self, transport_result: tuple[bool, str | None], expected_ok: bool) -> None:with patch(f"{_MODULE}.validate_ezofficeinventory_credentials", return_value=transport_result) as mocked:ok, error = EZOfficeInventorySource().validate_credentials(_config(), team_id=1)- mocked.assert_called_once_with("tok", "acme")+ # No pin resolves to the default version, so the probe runs under v2.+ mocked.assert_called_once_with("tok", "acme", EZOFFICEINVENTORY_API_VERSION_V2)assert ok is expected_okassert (error is None) is expected_ok@@ -113,11 +142,20 @@ class TestResumableWiring:manager = EZOfficeInventorySource().get_resumable_source_manager(inputs)assert manager._data_class is EZOfficeInventoryResumeConfig- def test_source_for_pipeline_plumbs_arguments(self) -> None:+ @pytest.mark.parametrize(+ ("pin", "expected_version"),+ [+ (None, EZOFFICEINVENTORY_API_VERSION_V2), # NULL pin → default (v2)+ ("v1", "v1"), # an existing v1 pin still reaches the request layer as v1+ ("v2", "v2"),+ ],+ )+ def test_source_for_pipeline_plumbs_resolved_version(self, pin: str | None, expected_version: str) -> None:inputs = MagicMock()inputs.schema_name = "members"inputs.team_id = 7inputs.job_id = "job-1"+ inputs.api_version = pinmanager = MagicMock()with patch(f"{_MODULE}.ezofficeinventory_source") as mocked:@@ -130,5 +168,6 @@ class TestResumableWiring:team_id=7,job_id="job-1",resumable_source_manager=manager,+ api_version=expected_version,db_incremental_field_last_value=None,)