: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): add cisco meraki network clients and events tables (#118999)
Tom Owersbb0d62652678
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 56a53324eec3..a6da29435d47 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@@ -2552,12 +2552,12 @@ Note: All nine Insights tables map cleanly onto spec paths; the gap is the remai## Cisco Meraki — **thin**-Today (5): `assurance_alerts`, `devices`, `inventory_devices`, `networks`, `uplink_statuses`+Today (7): `assurance_alerts`, `devices`, `inventory_devices`, `network_clients`, `network_events`, `networks`, `uplink_statuses`Diffed against: <https://raw.githubusercontent.com/meraki/openapi/master/openapi/spec3.json>-- [ ] `Network clients (GET /api/v1/networks/{networkId}/clients)` — measure active clients and join client activity with imported networks and devices (high)-- [ ] `Network events (GET /api/v1/networks/{networkId}/events)` — analyze connectivity failures, authentication events, and operational history (high)+- [x] `Network clients (GET /api/v1/networks/{networkId}/clients)` — measure active clients and join client activity with imported networks and devices (high)+- [x] `Network events (GET /api/v1/networks/{networkId}/events)` — analyze connectivity failures, authentication events, and operational history (high)- [ ] `Client usage histories (GET /api/v1/networks/{networkId}/clients/usageHistories)` — measure bandwidth consumption by client over time (high)- [ ] `Uplink loss and latency history (GET /api/v1/devices/{serial}/lossAndLatencyHistory)` — measure packet loss and latency beyond the current uplink status (high)- [ ] `Device statuses (GET /api/v1/organizations/{organizationId}/devices/statuses)` — monitor device availability and last contact across the imported inventory (medium)@@ -2566,7 +2566,7 @@ Diffed against: <https://raw.githubusercontent.com/meraki/openapi/master/openapi- [ ] `Wireless client connection statistics (GET /api/v1/networks/{networkId}/wireless/clients/connectionStats)` — compare connection failures and wireless reliability across clients (medium)- [ ] `Organization security events (GET /api/v1/organizations/{organizationId}/appliance/security/events)` — measure security threats and affected networks over time (medium)-Note: Fetched the official Meraki OpenAPI specification and checked collection GET paths at organization, network, device, and client levels. The specification uses the /api/v1 server base; current network and device tables already supply parent IDs. Most additions need requests for each network or device, with time windows, pagination, and supported device types. Network configuration, credentials, webhook plumbing, and writes are excluded.+Note: Fetched the official Meraki OpenAPI specification and checked collection GET paths at organization, network, device, and client levels. The specification uses the /api/v1 server base; current network and device tables already supply parent IDs. Most additions need requests for each network or device, with time windows, pagination, and supported device types. Network configuration, credentials, webhook plumbing, and writes are excluded. Client usage histories stay open because the endpoint requires a list of client keys in each request, so a table needs a second fan-out through network clients in batches. Uplink loss and latency history stays open because each request requires a destination IP that no listed endpoint returns, and covers one device uplink.## Cisco ThousandEyes — **thin**diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/canonical_descriptions.pyindex 140f3a01aec7..7bdea351dd69 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/canonical_descriptions.py@@ -63,4 +63,41 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"scope": "Devices, applications, peers, and other items affected by the alert.",},},+ "network_clients": {+ "description": "Clients that used each network in the selected Meraki organization in the last 31 days.",+ "docs_url": "https://developer.cisco.com/meraki/api-v1/get-network-clients/",+ "columns": {+ "networkId": "Identifier of the network that the client used.",+ "id": "Identifier of the client. It is unique within the network.",+ "mac": "MAC address of the client.",+ "ip": "IP address of the client.",+ "description": "Short description of the client.",+ "firstSeen": "Time when the client was first seen in the network, as a Unix timestamp.",+ "lastSeen": "Time when the client was last seen in the network, as a Unix timestamp.",+ "manufacturer": "Manufacturer of the client.",+ "os": "Operating system of the client.",+ "status": "Connection status of the client: Online or Offline.",+ "usage": "Data that the client sent and received in the last 31 days, in kilobytes.",+ "recentDeviceSerial": "Serial number of the device that the client most recently connected to.",+ "recentDeviceConnection": "Type of the most recent connection: Wired or Wireless.",+ },+ },+ "network_events": {+ "description": "Event log entries for each network and product type in the selected Meraki organization.",+ "docs_url": "https://developer.cisco.com/meraki/api-v1/get-network-events/",+ "columns": {+ "id": "Identifier that the import derives from the event content. Meraki events have no identifier.",+ "occurredAt": "Time when the event occurred.",+ "networkId": "Identifier of the network.",+ "productType": "Product type of the event log, for example wireless, switch, or appliance.",+ "type": "Type of the event.",+ "description": "Description of the event.",+ "category": "Category of the event type.",+ "clientId": "Identifier of the client, such as its MAC or IP address.",+ "clientMac": "MAC address of the client.",+ "deviceSerial": "Serial number of the device.",+ "deviceName": "Name of the device.",+ "eventData": "Additional data about the event.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/cisco_meraki.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/cisco_meraki.pyindex f5b3292abe77..65b31e595bc4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/cisco_meraki.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/cisco_meraki.py@@ -1,6 +1,9 @@import re-from typing import TYPE_CHECKING, Any-from urllib.parse import urlsplit+import json+import hashlib+from datetime import datetime+from typing import TYPE_CHECKING, Any, cast+from urllib.parse import parse_qs, urlsplitfrom requests import HTTPError, PreparedRequest, Response, Session@@ -9,21 +12,30 @@ from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.cisco_meraki.settings import (AUTH_ERROR,ENDPOINTS,+ EVENT_LOG_FLOOR,+ EVENT_PRODUCT_TYPES,NOT_FOUND_ERROR,ORGANIZATION_ERROR,PERMISSION_ERROR,REGION_ERROR,REGION_HOSTS,+ MerakiEndpoint,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_valuefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_adapterfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth+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 (+ HeaderLinkPaginator,SinglePagePaginator,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClientfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfigfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource@@ -40,6 +52,11 @@ if TYPE_CHECKING:class CiscoMerakiResumeConfig:next_url: str | None = Nonecompleted: bool = False+ # Network-level tables resume by network: the child paths already synced, the one in progress, and its+ # paginator state. See `common.rest_source.__init__._make_paginate_dependent_resource`.+ completed_paths: list[str] | None = None+ current_path: str | None = None+ child_state: dict[str, Any] | None = Noneclass _MerakiSession(Session):@@ -73,7 +90,7 @@ def client_config(config: "CiscoMerakiSourceConfig", api_version: str) -> Clientallowed_domain = host.removeprefix("api.")return {- "base_url": f"https://{host}/api/{api_version}/organizations/{config.organization_id}/",+ "base_url": f"https://{host}/api/{api_version}/",# Meraki supports this header across shard redirects, where requests removes bearer authentication."auth": {"type": "api_key", "name": "X-Cisco-Meraki-API-Key", "api_key": config.api_key, "location": "header"},"paginator": "header_link",@@ -82,6 +99,10 @@ def client_config(config: "CiscoMerakiSourceConfig", api_version: str) -> Client}+def _organization_path(path: str, config: "CiscoMerakiSourceConfig") -> str:+ return path.replace("{organization_id}", config.organization_id)++def validate_credentials(config: "CiscoMerakiSourceConfig", api_version: str, schema_name: str | None = None) -> tuple[bool, str | None]:@@ -91,6 +112,9 @@ def validate_credentials(return False, str(error)endpoint = schema_for_resource(ENDPOINTS, schema_name) if schema_name is not None else None+ if endpoint is not None and endpoint.fanout is not None:+ # Network-level tables need the same read access as the networks they fan out over.+ endpoint = ENDPOINTS[endpoint.fanout.parent_name]client = RESTClient(base_url=settings["base_url"],auth=APIKeyAuth(api_key=config.api_key, name="X-Cisco-Meraki-API-Key"),@@ -101,7 +125,7 @@ def validate_credentials(try:next(client.paginate(- path=endpoint.path if endpoint else settings["base_url"].rstrip("/"),+ path=_organization_path(endpoint.path if endpoint else "organizations/{organization_id}", config),params={"perPage": 4} if endpoint else {},))@@ -117,6 +141,132 @@ def validate_credentials(return True, None+class _EventLogPaginator(HeaderLinkPaginator):+ """Walks a network event log from the newest page to older pages, which is the order Meraki pages it in.++ Meraki pages the log by time window, so an empty page can still link to older events. The walk stops when a+ page reaches past the watermark, or when the older page starts before the watermark or the log floor.+ """++ def __init__(self, stop_before: datetime | None) -> None:+ super().__init__(links_next_key="prev")+ self._stop_before = stop_before or EVENT_LOG_FLOOR++ def update_state(self, response: Response, data: list[Any] | None = None) -> None:+ if data and self._reaches_watermark(data):+ self._has_next_page = False+ return+ prev_link = response.links.get("prev")+ ending_before = _ending_before(prev_link.get("url")) if prev_link else None+ if ending_before is None and not data:+ # An empty page whose older link carries no time cannot show that the walk moves toward the floor.+ self._has_next_page = False+ return+ if ending_before is not None and ending_before < self._stop_before:+ self._has_next_page = False+ return+ super().update_state(response, data)++ def _reaches_watermark(self, events: list[Any]) -> bool:+ for event in events:+ occurred_at = parse_datetime_value(event.get("occurredAt")) if isinstance(event, dict) else None+ if occurred_at is not None and occurred_at < self._stop_before:+ return True+ return False+++def _ending_before(url: str | None) -> datetime | None:+ values = parse_qs(urlsplit(url).query).get("endingBefore") if url else None+ return parse_datetime_value(values[0]) if values else None+++def _network_product_types(network: dict[str, Any]) -> list[dict[str, Any]]:+ product_types = network.get("productTypes") or []+ return [+ {**network, "productType": product_type}+ for product_type in product_types+ if product_type in EVENT_PRODUCT_TYPES+ ]+++def _with_event_id(event: dict[str, Any]) -> dict[str, Any]:+ content = json.dumps(event, sort_keys=True, separators=(",", ":"), default=str)+ return {"id": hashlib.sha256(content.encode()).hexdigest(), **event}+++def _network_source(+ config: "CiscoMerakiSourceConfig",+ endpoint: MerakiEndpoint,+ api_version: str,+ team_id: int,+ job_id: str,+ manager: "ResumableSourceManager[CiscoMerakiResumeConfig]",+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> SourceResponse:+ assert endpoint.fanout is not None+ resume = manager.load_state() if manager.can_resume() else None+ initial_state = (+ {"completed": resume.completed_paths or [], "current": resume.current_path, "child_state": resume.child_state}+ if resume is not None and (resume.completed_paths or resume.current_path)+ else None+ )++ def save_checkpoint(state: dict[str, Any] | None) -> None:+ if state is not None:+ manager.save_state(+ CiscoMerakiResumeConfig(+ completed_paths=state.get("completed"),+ current_path=state.get("current"),+ child_state=state.get("child_state"),+ )+ )++ is_event_log = endpoint.name == "network_events"+ incremental = is_event_log and should_use_incremental_field+ stop_before = parse_datetime_value(db_incremental_field_last_value) if incremental else None+ child_endpoint_extra: dict[str, Any] = {"data_selector": endpoint.data_selector}+ if is_event_log:+ child_endpoint_extra["paginator"] = _EventLogPaginator(stop_before)++ resource = cast(+ Resource,+ build_dependent_resource(+ endpoint_configs=ENDPOINTS,+ child_endpoint=endpoint.name,+ fanout=endpoint.fanout,+ client_config=client_config(config, api_version),+ path_format_values={"organization_id": config.organization_id},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ should_use_incremental_field=incremental,+ # The event log has no time filter, so the paginator bounds an incremental read instead.+ incremental_config_factory=lambda _field: None,+ parent_endpoint_extra={"data_selector": "$"},+ child_endpoint_extra=cast(Any, child_endpoint_extra),+ parent_data_map=_network_product_types if is_event_log else None,+ page_size_param="perPage",+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_state,+ ),+ )+ if is_event_log:+ resource = resource.add_map(_with_event_id)++ return SourceResponse(+ name=endpoint.name,+ items=lambda: resource,+ primary_keys=list(endpoint.primary_keys),+ on_complete=manager.clear_state,+ # Each network's event log arrives newest first, so the watermark advances only when the sync completes.+ sort_mode="desc" if is_event_log else "asc",+ partition_mode="datetime" if is_event_log else None,+ partition_format="month" if is_event_log else None,+ partition_keys=["occurredAt"] if is_event_log else None,+ )++def cisco_meraki_source(config: "CiscoMerakiSourceConfig",endpoint_name: str,@@ -124,14 +274,32 @@ def cisco_meraki_source(team_id: int,job_id: str,manager: "ResumableSourceManager[CiscoMerakiResumeConfig]",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,) -> SourceResponse:endpoint = schema_for_resource(ENDPOINTS, endpoint_name)+ if endpoint.fanout is not None:+ return _network_source(+ config,+ endpoint,+ api_version,+ team_id,+ job_id,+ manager,+ should_use_incremental_field,+ db_incremental_field_last_value,+ )+rest_config: RESTAPIConfig = {"client": client_config(config, api_version),"resources": [{"name": endpoint_name,- "endpoint": {"path": endpoint.path, "data_selector": "$", "params": {"perPage": endpoint.page_size}},+ "endpoint": {+ "path": _organization_path(endpoint.path, config),+ "data_selector": "$",+ "params": {"perPage": endpoint.page_size},+ },}],}@@ -140,7 +308,7 @@ def cisco_meraki_source(return SourceResponse(name=endpoint_name,items=lambda: iter(()),- primary_keys=[endpoint.primary_key],+ primary_keys=list(endpoint.primary_keys),on_complete=manager.clear_state,)@@ -162,6 +330,6 @@ def cisco_meraki_source(return SourceResponse(name=endpoint_name,items=lambda: resource,- primary_keys=[endpoint.primary_key],+ primary_keys=list(endpoint.primary_keys),on_complete=manager.clear_state,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/settings.pyindex 10b91c061921..6a5000cfc0ca 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/settings.py@@ -1,5 +1,13 @@+from dataclasses import field+from datetime import UTC, datetime+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+REGION_HOSTS = {"global": "api.meraki.com","canada": "api.meraki.ca",@@ -8,20 +16,110 @@ REGION_HOSTS = {"us_government": "api.gov-meraki.com",}+# The maximum lookback that the network clients endpoint accepts (31 days).+CLIENTS_TIMESPAN_SECONDS = 31 * 24 * 60 * 60++# Product types that the network events endpoint accepts. A network can contain others, such as sensor.+EVENT_PRODUCT_TYPES = frozenset(+ {+ "appliance",+ "camera",+ "campusGateway",+ "cellularGateway",+ "secureConnect",+ "switch",+ "systemsManager",+ "wireless",+ "wirelessController",+ }+)++# The official Meraki SDK stops an event log walk at this date, which is older than any Meraki event.+EVENT_LOG_FLOOR = datetime(2014, 1, 1, tzinfo=UTC)++# Devices can upload events after the previous sync read past them.+EVENTS_LOOKBACK_SECONDS = 60 * 60+@frozenclass MerakiEndpoint:+ name: strpath: str- primary_key: str+ primary_keys: tuple[str, ...]page_size: int = 1000+ data_selector: str = "$"+ fanout: DependentEndpointConfig | None = None+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None++_NETWORK_FANOUT_PARENT = "networks"ENDPOINTS = {- "networks": MerakiEndpoint(path="networks", primary_key="id"),- "devices": MerakiEndpoint(path="devices", primary_key="serial"),- "inventory_devices": MerakiEndpoint(path="inventory/devices", primary_key="serial"),- "uplink_statuses": MerakiEndpoint(path="uplinks/statuses", primary_key="serial"),- "assurance_alerts": MerakiEndpoint(path="assurance/alerts", primary_key="id", page_size=300),+ endpoint.name: endpoint+ for endpoint in (+ MerakiEndpoint(name="networks", path="organizations/{organization_id}/networks", primary_keys=("id",)),+ MerakiEndpoint(name="devices", path="organizations/{organization_id}/devices", primary_keys=("serial",)),+ MerakiEndpoint(+ name="inventory_devices",+ path="organizations/{organization_id}/inventory/devices",+ primary_keys=("serial",),+ ),+ MerakiEndpoint(+ name="uplink_statuses", path="organizations/{organization_id}/uplinks/statuses", primary_keys=("serial",)+ ),+ MerakiEndpoint(+ name="assurance_alerts",+ path="organizations/{organization_id}/assurance/alerts",+ primary_keys=("id",),+ page_size=300,+ ),+ MerakiEndpoint(+ name="network_clients",+ path="networks/{networkId}/clients",+ # Client ids are unique within a network only.+ primary_keys=("networkId", "id"),+ fanout=DependentEndpointConfig(+ parent_name=_NETWORK_FANOUT_PARENT,+ resolve_param="networkId",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "networkId"},+ child_params={"timespan": CLIENTS_TIMESPAN_SECONDS},+ ),+ ),+ MerakiEndpoint(+ name="network_events",+ # Networks with more than one product type reject event requests that omit the product type.+ path="networks/{networkId}/events?productType={productType}",+ # Events carry no identifier, so the source derives `id` from the event content.+ primary_keys=("id",),+ data_selector="events",+ fanout=DependentEndpointConfig(+ parent_name=_NETWORK_FANOUT_PARENT,+ resolve_param="networkId",+ resolve_field="id",+ include_from_parent=["productType"],+ parent_field_renames={"productType": "productType"},+ child_params={+ "productType": {"type": "resolve", "resource": _NETWORK_FANOUT_PARENT, "field": "productType"}+ },+ ),+ incremental_fields=[+ {+ "label": "occurredAt",+ "type": IncrementalFieldType.DateTime,+ "field": "occurredAt",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ default_incremental_field="occurredAt",+ ),+ )+}++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: endpoint.incremental_fields for name, endpoint in ENDPOINTS.items() if endpoint.incremental_fields}AUTH_ERROR = "Cisco Meraki rejected your API key. Check the key and selected region."diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/source.pyindex 456a33e3f204..d8fc39f11907 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/source.py@@ -21,6 +21,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cisco_merafrom products.warehouse_sources.backend.temporal.data_imports.sources.cisco_meraki.settings import (AUTH_ERROR,ENDPOINTS,+ EVENTS_LOOKBACK_SECONDS,+ INCREMENTAL_FIELDS,NOT_FOUND_ERROR,ORGANIZATION_ERROR,PERMISSION_ERROR,@@ -86,7 +88,13 @@ class CiscoMerakiSource(ResumableSource[CiscoMerakiSourceConfig, CiscoMerakiResuforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, {}, names)+ return build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names,+ merge_only=INCREMENTAL_FIELDS.keys(),+ default_incremental_lookback_seconds={"network_events": EVENTS_LOOKBACK_SECONDS},+ )def validate_credentials(self,@@ -113,6 +121,8 @@ class CiscoMerakiSource(ResumableSource[CiscoMerakiSourceConfig, CiscoMerakiResuinputs.team_id,inputs.job_id,resumable_source_manager,+ inputs.should_use_incremental_field,+ inputs.db_incremental_field_last_value,)@property@@ -126,7 +136,8 @@ class CiscoMerakiSource(ResumableSource[CiscoMerakiSourceConfig, CiscoMerakiResucaption=("In Meraki Dashboard, open **Organization > API & Webhooks > API keys and access**. Create an API key. ""Enable API access for your organization. Use an administrator account with read access to the selected tables. "- "Each connection imports one organization. Tables use full refresh. Health alerts include active alerts only."+ "Each connection imports one organization. Network events support incremental sync, and other tables use full refresh. "+ "Network clients include clients seen in the last 31 days. Health alerts include active alerts only."),fields=cast(list[FieldType],diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/tests/test_cisco_meraki.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/tests/test_cisco_meraki.pyindex a45e2e0c4ccd..534c1a492062 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/tests/test_cisco_meraki.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cisco_meraki/tests/test_cisco_meraki.py@@ -1,4 +1,5 @@from collections.abc import Iterable+from datetime import UTC, datetimefrom typing import Any, castfrom urllib.parse import parse_qs, urlsplit@@ -27,6 +28,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceErrorfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.testing import (+ RecordedRequest,ScriptedResponse,SourceDriver,always,@@ -37,7 +39,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_CiscoMerakiSourceConfig,)-BASE_URL = "https://api.meraki.com/api/v1/organizations/123456"+API_URL = "https://api.meraki.com/api/v1"+BASE_URL = f"{API_URL}/organizations/123456"def make_config(**overrides: str) -> CiscoMerakiSourceConfig:@@ -215,6 +218,7 @@ def test_resume_rejects_unapproved_destination() -> None:(401, None, (False, AUTH_ERROR)),(403, None, (True, None)),(403, "networks", (False, PERMISSION_ERROR)),+ (403, "network_events", (False, PERMISSION_ERROR)),(404, None, (False, NOT_FOUND_ERROR)),],)@@ -290,3 +294,102 @@ def test_unknown_table_fails_before_network_access() -> None:assert isinstance(result.raised, UnknownResourceError)assert result.requests == []assert network.requests_log == []+++def network_api(routes: dict[tuple[str, str | None], ScriptedResponse]) -> Any:+ def answer(request: RecordedRequest) -> ScriptedResponse:+ path = request.path+ if product_type := request.param("productType"):+ path = f"{path}?productType={product_type}"+ return routes[(path, request.param("endingBefore") or request.param("startingAfter"))]++ return answer+++def test_network_clients_fan_out_over_every_network_page() -> None:+ next_clients = f"{API_URL}/networks/N_1/clients?perPage=1000×pan=2678400&startingAfter=k2"+ result = make_driver().run(+ "network_clients",+ network_api(+ {+ ("/api/v1/organizations/123456/networks", None): ScriptedResponse(json=[{"id": "N_1"}, {"id": "N_2"}]),+ ("/api/v1/networks/N_1/clients", None): ScriptedResponse(+ json=[{"id": "k1"}], headers={"Link": f'<{next_clients}>; rel="next"'}+ ),+ ("/api/v1/networks/N_1/clients", "k2"): ScriptedResponse(json=[{"id": "k2"}]),+ ("/api/v1/networks/N_2/clients", None): ScriptedResponse(json=[{"id": "k1"}]),+ }+ ),+ )++ assert result.raised is None+ assert [(row["networkId"], row["id"]) for row in result.rows] == [("N_1", "k1"), ("N_1", "k2"), ("N_2", "k1")]+ assert [request.param("timespan") for request in result.requests[1:]] == ["2678400"] * 3+++def test_network_clients_resume_skips_completed_networks() -> None:+ result = make_driver().run(+ "network_clients",+ network_api(+ {+ ("/api/v1/organizations/123456/networks", None): ScriptedResponse(json=[{"id": "N_1"}, {"id": "N_2"}]),+ ("/api/v1/networks/N_2/clients", None): ScriptedResponse(json=[{"id": "k9"}]),+ }+ ),+ resume_state=CiscoMerakiResumeConfig(completed_paths=["networks/N_1/clients"]),+ )++ assert result.raised is None+ assert result.rows == [{"id": "k9", "networkId": "N_2"}]+ assert result.final_state == CiscoMerakiResumeConfig(+ completed_paths=["networks/N_1/clients", "networks/N_2/clients"]+ )+++def _event(occurred_at: str) -> dict[str, Any]:+ return {"occurredAt": occurred_at, "networkId": "N_1", "type": "association"}+++ ("watermark", "expected_pages"),+ [+ (None, [None, "2026-01-02T00:00:00Z", "2026-01-01T06:00:00Z", "2025-12-31T00:00:00Z"]),+ (datetime(2026, 1, 1, tzinfo=UTC), [None, "2026-01-02T00:00:00Z", "2026-01-01T06:00:00Z"]),+ ],+)+def test_network_events_walk_back_per_product_type(+ watermark: datetime | None, expected_pages: list[str | None]+) -> None:+ def page(events: list[dict[str, Any]], older_than: str) -> ScriptedResponse:+ prev_url = f"{API_URL}/networks/N_1/events?productType=appliance&perPage=1000&endingBefore={older_than}"+ return ScriptedResponse(json={"events": events}, headers={"Link": f'<{prev_url}>; rel="prev"'})++ appliance_path = "/api/v1/networks/N_1/events?productType=appliance"+ result = make_driver().run(+ "network_events",+ network_api(+ {+ ("/api/v1/organizations/123456/networks", None): ScriptedResponse(+ json=[{"id": "N_1", "productTypes": ["appliance", "sensor", "wireless"]}]+ ),+ ("/api/v1/networks/N_1/events?productType=wireless", None): ScriptedResponse(json={"events": []}),+ (appliance_path, None): page(+ [_event("2026-01-03T00:00:00Z"), _event("2026-01-02T00:00:00Z")], "2026-01-02T00:00:00Z"+ ),+ (appliance_path, "2026-01-02T00:00:00Z"): page([], "2026-01-01T06:00:00Z"),+ (appliance_path, "2026-01-01T06:00:00Z"): page(+ [_event("2026-01-01T05:00:00Z"), _event("2025-12-31T00:00:00Z")], "2025-12-31T00:00:00Z"+ ),+ (appliance_path, "2025-12-31T00:00:00Z"): page([], "2013-12-31T00:00:00Z"),+ }+ ),+ incremental_field="occurredAt" if watermark else None,+ db_incremental_field_last_value=watermark,+ )++ appliance = [request for request in result.requests if request.param("productType") == "appliance"]+ assert result.raised is None+ assert [request.param("endingBefore") for request in appliance] == expected_pages+ assert {request.param("productType") for request in result.requests[1:]} == {"appliance", "wireless"}+ assert {row["productType"] for row in result.rows} == {"appliance"}+ assert len({row["id"] for row in result.rows}) == len(result.rows) == 4