: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(fleetio): sync expense, status and service line item tables (#107409)
Tom Owersad322ab4806a
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 9d98aff87efb..fe36e67dfda8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -3224,10 +3224,10 @@ Today (9): `contacts`, `fuel_entries`, `issues`, `meter_entries`, `parts`, `servDiffed against: <https://developer.fleetio.com/sitemap.xml>-- [ ] `expense_entries (and expense_entry_types)` — non-service vehicle costs; without them total cost of ownership cannot be computed from the synced tables (high)-- [ ] `service_entry_line_items (v2)` — line-item detail behind each synced service entry - labor, parts and cost breakdown (high)-- [ ] `work_order_statuses` — lookup resolving the status ID on every synced work_orders row (high)-- [ ] `vehicle_statuses` — lookup resolving the status ID on every synced vehicles row (high)+- [x] `expense_entries (and expense_entry_types)` — non-service vehicle costs; without them total cost of ownership cannot be computed from the synced tables (high)+- [x] `service_entry_line_items (v2)` — line-item detail behind each synced service entry - labor, parts and cost breakdown (high)+- [x] `work_order_statuses` — lookup resolving the status ID on every synced work_orders row (high)+- [x] `vehicle_statuses` — lookup resolving the status ID on every synced vehicles row (high)- [ ] `vehicle_types` — lookup resolving vehicle type IDs, the main breakdown dimension for fleet analysis (high)- [ ] `service_tasks` — lookup resolving the task IDs referenced by service entries, work orders and service reminders (high)- [ ] `vendors` — lookup resolving vendor IDs on service entries, fuel entries and purchase orders (high)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/canonical_descriptions.pyindex 9e8543ad5815..9d039cc44a71 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/canonical_descriptions.py@@ -152,4 +152,76 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"comments_count": "Number of comments on the assignment.",},},+ "expense_entries": {+ "description": "A non-service cost recorded against a vehicle in Fleetio, such as a toll, permit, or insurance charge.",+ "docs_url": "https://developer.fleetio.com/docs/api/expense-entries",+ "columns": {+ **_COMMON_COLUMNS,+ "total_amount_cents": "Total amount of the expense, in cents.",+ "notes": "Additional comments on the expense.",+ "expense_entry_type_id": "Identifier of the expense entry type.",+ "expense_entry_type_name": "Name of the expense entry type.",+ "occurred_at": "Date and time of the expense.",+ "vehicle_id": "Identifier of the associated vehicle.",+ "vendor_id": "Identifier of the associated vendor.",+ "custom_fields": "Values of the account's custom fields for this expense.",+ },+ },+ "expense_entry_types": {+ "description": "A category an expense entry can be filed under, such as Tolls or Insurance.",+ "docs_url": "https://developer.fleetio.com/docs/api/expense-entry-types",+ "columns": {+ **_COMMON_COLUMNS,+ "name": "The name of the expense entry type.",+ },+ },+ "vehicle_statuses": {+ "description": "A status a vehicle can be in, such as Active or Out of Service. Resolves the status identifier on each vehicle.",+ "docs_url": "https://developer.fleetio.com/docs/api/vehicle-statuses",+ "columns": {+ **_COMMON_COLUMNS,+ "account_id": "Identifier of the Fleetio account the status belongs to.",+ "name": "The name of the vehicle status.",+ "default": "Whether this is the default status for new vehicles.",+ "color": "The color of the status shown in the Fleetio UI.",+ "position": "The position of this status in the list of vehicle statuses.",+ },+ },+ "work_order_statuses": {+ "description": "A status a work order can be in, such as Open or Completed. Resolves the status identifier on each work order.",+ "docs_url": "https://developer.fleetio.com/docs/api/work-order-statuses",+ "columns": {+ **_COMMON_COLUMNS,+ "account_id": "Identifier of the Fleetio account the status belongs to.",+ "name": "The name of the work order status.",+ "description": "The description of the work order status.",+ "color": "The color of the status shown in the Fleetio UI.",+ "default": "Whether this is the default status applied to new work orders.",+ "completed": "Whether work orders moved to this status are marked completed.",+ "position": "The position of this status in the list of work order statuses.",+ "work_orders_count": "Number of work orders currently in this status.",+ },+ },+ "service_entry_line_items": {+ "description": "A single line of a service entry: the labor, part, tax, fee, or free-text charge that makes up its cost.",+ "docs_url": "https://developer.fleetio.com/docs/api/service-entry-line-items-index",+ "columns": {+ **_COMMON_COLUMNS,+ "service_entry_id": "Identifier of the service entry this line item belongs to.",+ "description": "A description of the service performed for this line item.",+ "type": "The kind of line item, such as labor, part, tax, fee, tire, or free text.",+ "service_entry_line_item_id": "Identifier of the parent line item, for nested line items.",+ "service_reminder_id": "Identifier of the service reminder this line item is linked to, if any.",+ "service_task": "The service task performed for this line item.",+ "issues": "Issues resolved by this line item.",+ "subtotal": "The pre-tax subtotal for this line item.",+ "parts_cost": "The parts cost for this line item.",+ "labor_cost": "The labor cost for this line item.",+ "vmrs_reason_for_repair": "VMRS reason for repair coded against this line item.",+ "vmrs_system_group": "VMRS system group coded against this line item.",+ "vmrs_system": "VMRS system coded against this line item.",+ "vmrs_assembly": "VMRS assembly coded against this line item.",+ "vmrs_component": "VMRS component coded against this line item.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.pyindex 2cddae114437..106abfcde811 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py@@ -1,6 +1,7 @@import dataclasses+from collections.abc import Callable, Iterablefrom datetime import UTC, date, datetime-from typing import Any, Optional+from typing import Any, Optional, castfrom requests import PreparedRequest@@ -10,14 +11,19 @@ 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.auth import AuthConfigBase+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (JSONResponseCursorPaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom 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_probe-from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.fleetio.settings import (FLEETIO_ENDPOINTS,+ PER_PAGE,FleetioEndpointConfig,)@@ -27,8 +33,9 @@ FLEETIO_API_HOST = "https://secure.fleetio.com"# `X-Api-Version` header overrides that lock per request. We pin a modern date version explicitly so# every index endpoint serves the same cursor-pagination + `filter`/`sort` contract regardless of the# key's locked version. Two labels are supported:-# "v1" -> the 2024-06-30 date version, served under the integer `/api/v1` path.-# "2025-05-05" -> the same pagination/filter contract, but Fleetio drops the integer path segment+# "v1" -> the 2024-06-30 date version, which carries each resource's API generation in the+# path (`/api/v1/vehicles`, `/api/v2/service_entries/{id}/service_entry_line_items`).+# "2025-05-05" -> the same pagination/filter contract, but Fleetio dropped the generation segment# from this version onward (resources move to `/api/{resource}`).# See https://developer.fleetio.com/docs/overview/versioning.FLEETIO_LEGACY_VERSION = "v1"@@ -42,26 +49,27 @@ DEFAULT_VERSION = SUPPORTED_VERSIONS[-1]# for that label). Referenced by tests as the header the "v1" pin sends.FLEETIO_API_VERSION = "2024-06-30"+# Shared by every supported version; the per-resource generation segment, where a version still uses+# one, is part of the resource path rather than the base.+FLEETIO_BASE_URL = f"{FLEETIO_API_HOST}/api"+@dataclasses.dataclass(frozen=True)class _VersionContract:- base_url: strversion_header: str+ uses_path_version_segment: bool# Maps every supported label to the wire contract it selects. Coverage is exhaustive by construction# (`_resolve_contract` raises on an unmapped pin) — never fall through to a default, which would send# no version header and silently track "latest", the drift versioning exists to prevent._VERSION_CONTRACTS: dict[str, _VersionContract] = {- FLEETIO_LEGACY_VERSION: _VersionContract(base_url=f"{FLEETIO_API_HOST}/api/v1", version_header=FLEETIO_API_VERSION),+ FLEETIO_LEGACY_VERSION: _VersionContract(version_header=FLEETIO_API_VERSION, uses_path_version_segment=True),FLEETIO_VERSION_2025_05_05: _VersionContract(- base_url=f"{FLEETIO_API_HOST}/api", version_header=FLEETIO_VERSION_2025_05_05+ version_header=FLEETIO_VERSION_2025_05_05, uses_path_version_segment=False),}-# Base URL of the legacy contract; retained as a module constant for readability at call sites.-FLEETIO_BASE_URL = _VERSION_CONTRACTS[FLEETIO_LEGACY_VERSION].base_url-PER_PAGE = 100DEFAULT_INCREMENTAL_FIELD = "updated_at"@@ -72,6 +80,12 @@ def _resolve_contract(api_version: str) -> _VersionContract:raise ValueError(f"Unsupported Fleetio API version pin: {api_version!r}")+def _resource_path(contract: _VersionContract, config: FleetioEndpointConfig) -> str:+ if contract.uses_path_version_segment:+ return f"/{config.path_version}{config.path}"+ return config.path++class FleetioAuth(AuthConfigBase):"""Fleetio authenticates with two separate headers, not one.@@ -145,10 +159,33 @@ def _build_base_params(return params+def _client_config(api_key: str, account_token: str, contract: _VersionContract) -> ClientConfig:+ return {+ "base_url": FLEETIO_BASE_URL,+ "headers": _non_secret_headers(contract.version_header),+ "auth": FleetioAuth(api_key, account_token),+ # Every index endpoint returns the cursor envelope ({"records": [...], "next_cursor": ...});+ # the cursor is carried forward as the `start_cursor` query param.+ "paginator": JSONResponseCursorPaginator(cursor_path="next_cursor", cursor_param="start_cursor"),+ # Pin every request — including the paginator's next-page cursor requests — to the Fleetio+ # host and refuse redirects, so a tampered/spoofed response can't exfiltrate the two+ # credential headers to another origin.+ "allowed_hosts": [],+ "allow_redirects": False,+ }++[email protected](frozen=True)class FleetioResumeConfig:- # The cursor to start the next page from. None means "start at the first page".+ # The cursor to start the next page from, for a top-level endpoint. None means "start at the+ # first page".start_cursor: str | None = None+ # Fan-out endpoints resume by parent: the parent paths already fully synced, the parent in+ # progress, and that parent's paginator state — see+ # `common.rest_source.__init__._make_paginate_dependent_resource`.+ completed: list[str] | None = None+ current: str | None = None+ child_state: dict[str, Any] | None = Nonedef validate_credentials(api_key: str, account_token: str, api_version: str) -> bool:@@ -160,51 +197,56 @@ def validate_credentials(api_key: str, account_token: str, api_version: str) ->contract = _resolve_contract(api_version)ok, _status = validate_via_probe(lambda: make_tracked_session(redact_values=(api_key, account_token)),- f"{contract.base_url}/vehicles?per_page=1",+ f"{FLEETIO_BASE_URL}{_resource_path(contract, FLEETIO_ENDPOINTS['vehicles'])}?per_page=1",headers=_non_secret_headers(contract.version_header),auth=FleetioAuth(api_key, account_token),)return ok-def fleetio_source(+def _make_source_response(+ config: FleetioEndpointConfig,+ items: Callable[[], Iterable[Any]],+ sort_mode: SortMode | None,+ column_hints: dict[str, Any] | None = None,+) -> SourceResponse:+ return SourceResponse(+ name=config.name,+ items=items,+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ sort_mode=sort_mode,+ column_hints=column_hints,+ )+++def _top_level_source(+ config: FleetioEndpointConfig,+ contract: _VersionContract,api_key: str,account_token: str,- endpoint: str,team_id: int,job_id: str,resumable_source_manager: ResumableSourceManager[FleetioResumeConfig],- api_version: str = DEFAULT_VERSION,- should_use_incremental_field: bool = False,- db_incremental_field_last_value: Optional[Any] = None,- incremental_field: str | None = None,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Optional[Any],+ incremental_field: str | None,) -> SourceResponse:- config = FLEETIO_ENDPOINTS[endpoint]- contract = _resolve_contract(api_version)-params = _build_base_params(config, should_use_incremental_field, db_incremental_field_last_value, incremental_field)rest_config: RESTAPIConfig = {- "client": {- "base_url": contract.base_url,- "headers": _non_secret_headers(contract.version_header),- "auth": FleetioAuth(api_key, account_token),- # Every index endpoint returns the cursor envelope ({"records": [...], "next_cursor": ...});- # the cursor is carried forward as the `start_cursor` query param.- "paginator": JSONResponseCursorPaginator(cursor_path="next_cursor", cursor_param="start_cursor"),- # Pin every request — including the paginator's next-page cursor requests — to the Fleetio- # host and refuse redirects, so a tampered/spoofed response can't exfiltrate the two- # credential headers to another origin.- "allowed_hosts": [],- "allow_redirects": False,- },+ "client": _client_config(api_key, account_token, contract),"resources": [{- "name": endpoint,+ "name": config.name,"endpoint": {- "path": config.path,+ "path": _resource_path(contract, config),"params": params,"data_selector": "records",# A 200 body without `records` (e.g. a bare list because the version pin was@@ -237,15 +279,109 @@ def fleetio_source(initial_paginator_state=initial_paginator_state,)- return SourceResponse(- name=endpoint,- items=lambda: resource,- primary_keys=config.primary_keys,- partition_count=1,- partition_size=1,- partition_mode="datetime" if config.partition_key else None,- partition_format="month" if config.partition_key else None,- partition_keys=[config.partition_key] if config.partition_key else None,- sort_mode="asc",- column_hints=resource.column_hints,+ return _make_source_response(config, lambda: resource, sort_mode="asc", column_hints=resource.column_hints)+++def _fanout_source(+ config: FleetioEndpointConfig,+ contract: _VersionContract,+ api_key: str,+ account_token: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[FleetioResumeConfig],+) -> SourceResponse:+ assert config.fanout is not None+ parent_config = FLEETIO_ENDPOINTS[config.fanout.parent_name]++ initial_state: Optional[dict[str, Any]] = None+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None and (resume.completed or resume.current):+ initial_state = {+ "completed": resume.completed or [],+ "current": resume.current,+ "child_state": resume.child_state,+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ if state is not None:+ resumable_source_manager.save_state(+ FleetioResumeConfig(+ completed=state.get("completed"),+ current=state.get("current"),+ child_state=state.get("child_state"),+ )+ )++ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=FLEETIO_ENDPOINTS,+ child_endpoint=config.name,+ fanout=config.fanout,+ client_config=_client_config(api_key, account_token, contract),+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ # The parent and child sit on different API generations, so each resource's path has to+ # carry its own version segment rather than share one from the client base URL.+ parent_endpoint_extra={+ "path": _resource_path(contract, parent_config),+ "data_selector": "records",+ "data_selector_required": True,+ },+ child_endpoint_extra={+ "path": _resource_path(contract, config),+ "data_selector": "records",+ "data_selector_required": True,+ },+ page_size_param="per_page",+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ ),+ )++ # Rows arrive grouped by parent service entry, so the partition key is not globally ascending.+ return _make_source_response(config, lambda: dependent_resource, sort_mode=None)+++def fleetio_source(+ api_key: str,+ account_token: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[FleetioResumeConfig],+ api_version: str = DEFAULT_VERSION,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = FLEETIO_ENDPOINTS[endpoint]+ contract = _resolve_contract(api_version)++ if config.fanout is not None:+ return _fanout_source(+ config,+ contract,+ api_key,+ account_token,+ team_id,+ job_id,+ resumable_source_manager,+ )++ return _top_level_source(+ config,+ contract,+ api_key,+ account_token,+ team_id,+ job_id,+ resumable_source_manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ incremental_field,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.pyindex d96d4cb22f4c..5ece34e2baa6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.py@@ -1,7 +1,13 @@from dataclasses import dataclass, field+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+# Every Fleetio index endpoint caps `per_page` at 100 (default 50), so always request the max.+PER_PAGE = 100+def _datetime_field(name: str) -> IncrementalField:return {@@ -18,30 +24,70 @@ def _datetime_field(name: str) -> IncrementalField:_DEFAULT_INCREMENTAL_FIELDS: list[IncrementalField] = [_datetime_field("updated_at"), _datetime_field("created_at")]-@dataclass+# Mutable by choice, not oversight: instances flow into `build_dependent_resource`'s+# `endpoint_configs: Mapping[str, FanoutEndpointLike]`, and mypy treats a frozen dataclass's+# fields as read-only, which is incompatible with that Protocol's plain (read-write) attributes.+@dataclass(frozen=False)class FleetioEndpointConfig:name: strpath: str+ # The resource's API generation, which versions up to 2024-06-30 carry as a path segment+ # (`/api/v1/vehicles`, `/api/v2/service_entries/...`). 2025-05-05 dropped those segments, so it+ # ignores this. Fleetio moved several resources to v2 over time, so this is per resource.+ path_version: str = "v1"incremental_fields: list[IncrementalField] = field(default_factory=lambda: list(_DEFAULT_INCREMENTAL_FIELDS))# Partition by a stable field (created_at), never updated_at, so partitions don't rewrite each sync.partition_key: str | None = "created_at"primary_keys: list[str] = field(default_factory=lambda: ["id"])should_sync_default: bool = True+ # Set for a resource Fleetio only lists under a parent record, never account-wide.+ fanout: DependentEndpointConfig | None = None+ # Cursor field the fan-out helper binds to a server-side filter. Only read for a fan-out child+ # that merges, so it stays None for a child whose list action has no time filter.+ default_incremental_field: str | None = None+ # Page size the fan-out helper requests for this resource's list action.+ page_size: int = PER_PAGE# Core data streams a Fleetio user will actually want, cross-referenced against the dltHub Fleetio-# source and the common Airbyte/Fivetran fleet-management stream list. All are top-level index-# endpoints under https://secure.fleetio.com/api/v1 with `id`, `created_at`, and `updated_at`.+# source and the common Airbyte/Fivetran fleet-management stream list. Every entry exposes `id`,+# `created_at` and `updated_at`. `path_version` records the generation the 2024-06-30 docs serve the+# resource under, since Fleetio removed the v1 paths of the resources it moved to v2.FLEETIO_ENDPOINTS: dict[str, FleetioEndpointConfig] = {"vehicles": FleetioEndpointConfig(name="vehicles", path="/vehicles"),- "contacts": FleetioEndpointConfig(name="contacts", path="/contacts"),+ "contacts": FleetioEndpointConfig(name="contacts", path="/contacts", path_version="v2"),"fuel_entries": FleetioEndpointConfig(name="fuel_entries", path="/fuel_entries"),"meter_entries": FleetioEndpointConfig(name="meter_entries", path="/meter_entries"),- "service_entries": FleetioEndpointConfig(name="service_entries", path="/service_entries"),- "work_orders": FleetioEndpointConfig(name="work_orders", path="/work_orders"),- "issues": FleetioEndpointConfig(name="issues", path="/issues"),+ "service_entries": FleetioEndpointConfig(name="service_entries", path="/service_entries", path_version="v2"),+ "work_orders": FleetioEndpointConfig(name="work_orders", path="/work_orders", path_version="v2"),+ "issues": FleetioEndpointConfig(name="issues", path="/issues", path_version="v2"),"parts": FleetioEndpointConfig(name="parts", path="/parts"),"vehicle_assignments": FleetioEndpointConfig(name="vehicle_assignments", path="/vehicle_assignments"),+ "expense_entries": FleetioEndpointConfig(name="expense_entries", path="/expense_entries"),+ "expense_entry_types": FleetioEndpointConfig(name="expense_entry_types", path="/expense_entry_types"),+ # Lookup tables resolving the status ids carried on every vehicle and work order row.+ "vehicle_statuses": FleetioEndpointConfig(name="vehicle_statuses", path="/vehicle_statuses"),+ "work_order_statuses": FleetioEndpointConfig(name="work_order_statuses", path="/work_order_statuses"),+ # Line items are only listed per service entry, so fan out over the service entries endpoint.+ # The list action takes no `filter` param — only `sort[id]` — so this is full refresh only.+ "service_entry_line_items": FleetioEndpointConfig(+ name="service_entry_line_items",+ path="/service_entries/{service_entry_id}/service_entry_line_items",+ path_version="v2",+ incremental_fields=[],+ primary_keys=["service_entry_id", "id"],+ fanout=DependentEndpointConfig(+ parent_name="service_entries",+ resolve_param="service_entry_id",+ resolve_field="id",+ # The line item carries `service_entry_id` itself, but the field is not required by the+ # schema, so take it from the parent row to keep the composite primary key populated.+ include_from_parent=["id"],+ parent_field_renames={"id": "service_entry_id"},+ parent_params={"sort[created_at]": "asc"},+ child_params={"sort[id]": "asc"},+ ),+ ),}ENDPOINTS = tuple(FLEETIO_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.pyindex fe05ed218c97..17a8920a3731 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/tests/test_fleetio.py@@ -288,3 +288,94 @@ class TestValidateCredentials:def test_network_error_is_not_valid(self, mock_session) -> None:mock_session.return_value.get.side_effect = Exception("boom")assert validate_credentials("k", "a", FLEETIO_VERSION_2025_05_05) is False+++class TestServiceEntryLineItemsFanout:+ """The only fan-out endpoint: line items are listed per service entry, never account-wide."""++ def _wire_fanout(self, session: mock.MagicMock, responses: list[Response]) -> list[str]:+ session.headers = {}+ urls: list[str] = []++ def _prepare(request: Any) -> mock.MagicMock:+ url = request.url+ for key, value in (request.params or {}).items():+ url = url.replace("{" + key + "}", str(value))+ urls.append(url)+ prepared = mock.MagicMock()+ prepared.url = url+ return prepared++ session.prepare_request.side_effect = _prepare+ session.send.side_effect = responses+ return urls++ def _line_items(self, manager: mock.MagicMock, **kwargs: Any):+ return fleetio_source(+ api_key="k",+ account_token="a",+ endpoint="service_entry_line_items",+ team_id=1,+ job_id="j",+ resumable_source_manager=manager,+ **kwargs,+ )++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_per_service_entry_and_stamps_the_parent_id(self, MockSession) -> None:+ # Without the parent id the composite primary key has a null column, so every line item+ # collides on merge. The API's own `service_entry_id` is optional, hence taking the+ # parent's.+ session = MockSession.return_value+ urls = self._wire_fanout(+ session,+ [+ _response([{"id": 11}, {"id": 22}], None),+ _response([{"id": 101, "description": "Oil"}], None),+ _response([{"id": 201}], "CUR2"),+ _response([{"id": 202}], None),+ ],+ )++ rows = _rows(self._line_items(_make_manager()))++ assert [(row["service_entry_id"], row["id"]) for row in rows] == [(11, 101), (22, 201), (22, 202)]+ assert urls[0].endswith("/api/service_entries")+ assert urls[1] == "https://secure.fleetio.com/api/service_entries/11/service_entry_line_items"+ assert urls[2] == "https://secure.fleetio.com/api/service_entries/22/service_entry_line_items"++ @parameterized.expand(+ [+ # Fleetio removed `/v1/service_entries` when it moved the resource to v2, so a legacy+ # pin that assumes one shared generation segment cannot list the fan-out's parents.+ (FLEETIO_LEGACY_VERSION, "/api/v2/service_entries", "/api/v2/service_entries/11/service_entry_line_items"),+ (FLEETIO_VERSION_2025_05_05, "/api/service_entries", "/api/service_entries/11/service_entry_line_items"),+ ]+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_parent_and_child_carry_their_own_version_segment(+ self, api_version: str, parent_path: str, child_path: str, MockSession+ ) -> None:+ session = MockSession.return_value+ urls = self._wire_fanout(session, [_response([{"id": 11}], None), _response([{"id": 101}], None)])++ _rows(self._line_items(_make_manager(), api_version=api_version))++ assert urls[0] == f"https://secure.fleetio.com{parent_path}"+ assert urls[1] == f"https://secure.fleetio.com{child_path}"++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_checkpoints_by_parent_and_resumes_past_completed_parents(self, MockSession) -> None:+ # Fan-out resume state is keyed by parent path, not by the top-level cursor — a checkpoint+ # written in the top-level shape would silently restart the whole fan-out on retry.+ session = MockSession.return_value+ self._wire_fanout(session, [_response([{"id": 11}, {"id": 22}], None), _response([{"id": 201}], None)])++ # The framework keys fan-out checkpoints by the child's endpoint path, not the full URL.+ completed = "/service_entries/11/service_entry_line_items"+ manager = _make_manager(FleetioResumeConfig(completed=[completed], current=None, child_state=None))+ rows = _rows(self._line_items(manager))++ assert [row["service_entry_id"] for row in rows] == [22]+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert any(state.completed is not None and completed in state.completed for state in saved)