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(warehouse_sources): add Algolia analytics and A/B test tables (#98107)

Tom Owers9ba63b955ebb
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.md
index fc7baad906a7..51e0bff5a0f3 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
@@ -196,14 +196,14 @@ Note: Static schema list (no dynamic discovery). Coverage of the org/billing obj
## Algolia — gaps
-Today (4): `indices`, `records`, `rules`, `synonyms`
+Today (9): `ab_tests`, `indices`, `records`, `rules`, `searches_no_clicks`, `searches_no_results`, `synonyms`, `top_hits`, `top_searches`
Diffed against: <https://raw.githubusercontent.com/algolia/api-clients-automation/main/specs/bundled/analytics.yml>
-- [ ] `GET /2/searches (Analytics API)` — top search terms with counts - the vendor's headline search metric (high)
-- [ ] `GET /2/hits (Analytics API)` — top results per query with click and conversion counts, the record-level performance table (high)
-- [ ] `GET /2/searches/noResults and /2/searches/noClicks` — zero-result and zero-click queries, the core relevance-debugging tables (high)
-- [ ] `GET /2/abtests (A/B Testing API)` — A/B test definitions and per-variant results (high)
+- [x] `GET /2/searches (Analytics API)` — top search terms with counts - the vendor's headline search metric (high) → `top_searches`
+- [x] `GET /2/hits (Analytics API)` — top results per query with click and conversion counts, the record-level performance table (high) → `top_hits`
+- [x] `GET /2/searches/noResults and /2/searches/noClicks` — zero-result and zero-click queries, the core relevance-debugging tables (high) → `searches_no_results`, `searches_no_clicks`
+- [x] `GET /2/abtests (A/B Testing API)` — A/B test definitions and per-variant results (high) → `ab_tests` (implemented against the GA `GET /3/abtests`; the audited `/2/abtests` listing is deprecated in favour of v3)
- [ ] `GET /2/conversions/conversionRate, /2/conversions/revenue, /2/conversions/addToCartRate, /2/conversions/purchaseRate` — conversion and revenue time series per index (high)
- [ ] `GET /2/clicks/clickThroughRate, /2/clicks/averageClickPosition, /2/clicks/positions` — click-through and click-position time series (medium)
- [ ] `GET /2/filters and /2/filters/{attribute}` — facet/filter usage breakdown dimension (medium)
@@ -213,7 +213,7 @@ Diffed against: <https://raw.githubusercontent.com/algolia/api-clients-automatio
- [ ] `GET /1/incidents, /1/latency/{clusters}, /1/indexing/{clusters} (Monitoring API)` — cluster latency, indexing time and incident history (low)
- [ ] `GET /1/logs/{indexName} (Query Suggestions API)` — query-suggestions build logs per index (low)
-Note: Static schema list, no dynamic index discovery. Every synced table comes from the Search API (content objects only); the Analytics, A/B testing, Ingestion and Monitoring APIs are entirely absent, which is the part a warehouse user actually wants. Also diffed against the bundled abtesting.yml, insights.yml, monitoring.yml, ingestion.yml and search.yml specs in the same repo.
+Note: Static schema list, no dynamic index discovery. The headline Analytics tables (top searches, top hits, zero-result and zero-click searches) and A/B tests (via the GA `/3/abtests`) are now covered; the remaining Analytics time-series (conversions, clicks, filters, countries) and the Ingestion, Monitoring, and raw-log APIs are still absent. Also diffed against the bundled abtesting.yml, insights.yml, monitoring.yml, ingestion.yml and search.yml specs in the same repo.
## Alguna — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/algolia.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/algolia.py
index 3cceb67a7be8..9ce1dea0027c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/algolia.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/algolia.py
@@ -1,13 +1,15 @@
import re
-import dataclasses
from typing import Any, Optional, cast
from urllib.parse import quote
import requests
from requests import Response
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.settings import (
ALGOLIA_ENDPOINTS,
+ AlgoliaApi,
AlgoliaEndpointConfig,
PaginationStyle,
)
@@ -19,6 +21,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
JSONResponseCursorPaginator,
+ OffsetPaginator,
PageNumberPaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
@@ -28,11 +31,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
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 SourceResponse
-# Algolia's REST API is served per-application. The main host handles both reads and the
+# Algolia's Search API is served per-application. The main host handles both reads and the
# admin/list operations we use; the `-dsn` replica is only a latency optimisation for search,
# which doesn't matter for a batch import.
ALGOLIA_HOST_TEMPLATE = "https://{application_id}.algolia.net"
+# The Analytics and A/B Testing APIs live on a separate, region-specific host. The application ID
+# rides in a header here (never the host), so these are fixed Algolia hostnames with no injection
+# surface — only the two documented regions are reachable.
+ALGOLIA_ANALYTICS_HOSTS = {
+ "us": "https://analytics.algolia.com",
+ "de": "https://analytics.de.algolia.com",
+}
+
# Both 401 and 403 carry this exact message when the application ID / API key pair is wrong.
# A genuine key that merely lacks the ACL for an endpoint returns a different 403 message
# ("Method not allowed with this API key"), which lets us tell "bad credentials" apart from
@@ -49,12 +60,14 @@ class InvalidApplicationIdError(ValueError):
pass
+@frozen
class AlgoliaResumeConfig:
# Browse cursor token to continue an index scan from. None on the first page.
cursor: str | None = None
# 0-based page number for the page-paginated endpoints (synonyms, rules, indices).
page: int | None = None
+ # Row offset for the offset-paginated analytics / A-B testing endpoints.
+ offset: int | None = None
def _base_url(application_id: str) -> str:
@@ -63,6 +76,18 @@ def _base_url(application_id: str) -> str:
return ALGOLIA_HOST_TEMPLATE.format(application_id=application_id)
+def _analytics_base_url(region: str) -> str:
+ # An unknown region falls back to the US host rather than failing; the select field only ever
+ # supplies a documented region.
+ return ALGOLIA_ANALYTICS_HOSTS.get(region, ALGOLIA_ANALYTICS_HOSTS["us"])
+
+
+def _base_url_for(config: AlgoliaEndpointConfig, application_id: str, region: str) -> str:
+ if config.api == AlgoliaApi.ANALYTICS:
+ return _analytics_base_url(region)
+ return _base_url(application_id)
+
+
def _get_headers(application_id: str, api_key: str) -> dict[str, str]:
return {
"X-Algolia-Application-Id": application_id,
@@ -77,12 +102,20 @@ def _endpoint_path(config: AlgoliaEndpointConfig, index_name: str | None) -> str
if config.requires_index:
if not index_name:
raise ValueError(f"Algolia endpoint '{config.name}' requires an index name")
- path = path.format(index=quote(index_name, safe=""))
+ # Search endpoints carry the index in the path; analytics endpoints carry it as a query
+ # param (added by the caller), so only substitute when the placeholder is present.
+ if "{index}" in path:
+ path = path.format(index=quote(index_name, safe=""))
return path
-def _endpoint_url(application_id: str, config: AlgoliaEndpointConfig, index_name: str | None) -> str:
- return f"{_base_url(application_id)}{_endpoint_path(config, index_name)}"
+def _endpoint_url(
+ application_id: str,
+ config: AlgoliaEndpointConfig,
+ index_name: str | None,
+ region: str = "us",
+) -> str:
+ return f"{_base_url_for(config, application_id, region)}{_endpoint_path(config, index_name)}"
class AlgoliaPageNumberPaginator(PageNumberPaginator):
@@ -115,6 +148,15 @@ def _build_paginator(config: AlgoliaEndpointConfig) -> BasePaginator:
# Browse pages via an opaque cursor carried in the POST body; a missing cursor in the
# response signals end of index.
return JSONResponseCursorPaginator(cursor_path="cursor", cursor_param="cursor", param_location="json")
+ if config.pagination == PaginationStyle.OFFSET:
+ # Analytics / A-B endpoints page via `offset`/`limit` query params. `abtests` reports a
+ # `total`; the top-searches/hits tables don't, so a short final page ends the walk.
+ return OffsetPaginator(
+ limit=config.page_size,
+ offset_param="offset",
+ limit_param="limit",
+ param_location="query",
+ )
# Search endpoints (synonyms/rules) page via a 0-based `page` in the POST body; the indices
# listing pages via `page` in the query string.
return AlgoliaPageNumberPaginator(
@@ -133,6 +175,7 @@ def algolia_source(
team_id: int,
job_id: str,
manager: ResumableSourceManager[AlgoliaResumeConfig],
+ region: str = "us",
) -> SourceResponse:
config = ALGOLIA_ENDPOINTS[endpoint]
is_cursor = config.pagination == PaginationStyle.CURSOR
@@ -143,16 +186,25 @@ def algolia_source(
"data_selector": config.data_selector,
"paginator": _build_paginator(config),
}
- # Rows requested per page (`hitsPerPage`) travel where the page token does: in the POST body
- # for browse/search, in the query string for the GET indices listing.
- if config.method == "POST":
+ if config.api == AlgoliaApi.ANALYTICS:
+ # The paginator supplies `offset`/`limit`; the index (when the endpoint is index-scoped)
+ # and the click-analytics toggle travel as static query params alongside it.
+ params: dict[str, Any] = {}
+ if config.requires_index and index_name:
+ params["index"] = index_name
+ if config.click_analytics:
+ params["clickAnalytics"] = "true"
+ endpoint_config["params"] = params
+ elif config.method == "POST":
+ # Rows requested per page (`hitsPerPage`) travel where the page token does: in the POST body
+ # for browse/search, in the query string for the GET indices listing.
endpoint_config["json"] = {"hitsPerPage": config.page_size}
else:
endpoint_config["params"] = {"hitsPerPage": config.page_size}
rest_config: RESTAPIConfig = {
"client": {
- "base_url": _base_url(application_id),
+ "base_url": _base_url_for(config, application_id, region),
# The API key is supplied via the framework auth config so its value is redacted from
# logs; only the non-secret application ID / content headers are set here.
"headers": {
@@ -172,7 +224,9 @@ def algolia_source(
if resume is not None:
if is_cursor and resume.cursor is not None:
initial_paginator_state = {"cursor": resume.cursor}
- elif not is_cursor and resume.page is not None:
+ elif config.pagination == PaginationStyle.OFFSET and resume.offset is not None:
+ initial_paginator_state = {"offset": resume.offset}
+ elif config.pagination == PaginationStyle.PAGE and resume.page is not None:
initial_paginator_state = {"page": resume.page}
def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
@@ -183,6 +237,9 @@ def algolia_source(
if is_cursor:
if state.get("cursor") is not None:
manager.save_state(AlgoliaResumeConfig(cursor=state["cursor"]))
+ elif config.pagination == PaginationStyle.OFFSET:
+ if state.get("offset") is not None:
+ manager.save_state(AlgoliaResumeConfig(offset=int(state["offset"])))
elif state.get("page") is not None:
manager.save_state(AlgoliaResumeConfig(page=int(state["page"])))
@@ -210,6 +267,7 @@ def validate_credentials(
api_key: str,
index_name: str | None = None,
schema_name: str | None = None,
+ region: str = "us",
) -> tuple[bool, str | None]:
"""Confirm the application ID / API key pair is genuine.
@@ -230,13 +288,19 @@ def validate_credentials(
headers = _get_headers(application_id, api_key)
try:
- url = _endpoint_url(application_id, config, index_name)
+ url = _endpoint_url(application_id, config, index_name, region)
except InvalidApplicationIdError as exc:
return False, str(exc)
session = make_tracked_session(redact_values=(api_key,))
try:
- if config.method == "POST":
+ if config.api == AlgoliaApi.ANALYTICS:
+ # Confirm the `analytics` ACL with a one-row read against the analytics host.
+ params: dict[str, Any] = {"limit": 1}
+ if config.requires_index and index_name:
+ params["index"] = index_name
+ response = session.get(url, headers=headers, params=params, timeout=10)
+ elif config.method == "POST":
response = session.post(url, headers=headers, json={"hitsPerPage": 0}, timeout=10)
else:
response = session.get(url, headers=headers, timeout=10)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/canonical_descriptions.py
index ba1eb50315f7..2d3fd49f116b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/canonical_descriptions.py
@@ -45,4 +45,68 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"primary": "Name of the primary index, set on replica indices.",
},
},
+ "top_searches": {
+ "description": "Most popular searches on the index over the recent period, with search volume and, "
+ "when click analytics is enabled, click and conversion metrics.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/analytics/#tag/searches/operation/getTopSearches",
+ "columns": {
+ "search": "Search query term.",
+ "count": "Number of searches for this term.",
+ "nbHits": "Average number of search results (hits) returned for this term.",
+ "trackedSearchCount": "Number of tracked searches (requests with click analytics enabled).",
+ "clickCount": "Number of clicks on results for this term.",
+ "clickThroughRate": "Click-through rate: clicks divided by tracked searches.",
+ "averageClickPosition": "Average position of the clicked result.",
+ "conversionCount": "Number of conversions attributed to this term.",
+ "conversionRate": "Conversion rate: conversions divided by tracked searches.",
+ },
+ },
+ "top_hits": {
+ "description": "Most frequent search results (records) shown on the index over the recent period, with "
+ "display volume and, when click analytics is enabled, click and conversion metrics.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/analytics/#tag/hits/operation/getTopHits",
+ "columns": {
+ "hit": "Object ID of the record returned as a search result.",
+ "count": "Number of times this record appeared in search results.",
+ "trackedHitCount": "Number of tracked searches that returned this record.",
+ "clickCount": "Number of clicks on this record.",
+ "clickThroughRate": "Click-through rate for this record.",
+ "conversionCount": "Number of conversions attributed to this record.",
+ "conversionRate": "Conversion rate for this record.",
+ },
+ },
+ "searches_no_results": {
+ "description": "Most frequent searches on the index that returned zero results over the recent period.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/analytics/#tag/searches/operation/getSearchesNoResults",
+ "columns": {
+ "search": "Search query term that returned no results.",
+ "count": "Number of searches for this term.",
+ "withFilterCount": "Number of those searches that had filters applied.",
+ },
+ },
+ "searches_no_clicks": {
+ "description": "Most popular searches on the index that led to no clicks over the recent period.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/analytics/#tag/searches/operation/getSearchesNoClicks",
+ "columns": {
+ "search": "Search query term that received no clicks.",
+ "count": "Number of tracked searches for this term.",
+ "nbHits": "Average number of search results shown that remained unclicked.",
+ },
+ },
+ "ab_tests": {
+ "description": "A/B tests configured on the application, each with its variants and per-variant results.",
+ "docs_url": "https://www.algolia.com/doc/rest-api/abtesting/#tag/abtest/operation/listABTests",
+ "columns": {
+ "abTestID": "Unique identifier of the A/B test.",
+ "name": "Name of the A/B test.",
+ "status": "Current status of the A/B test (e.g. active, stopped, expired).",
+ "variants": "List of variants with their index, traffic share, and per-variant results.",
+ "createdAt": "Date the A/B test was created (ISO 8601).",
+ "updatedAt": "Date the A/B test was last updated (ISO 8601).",
+ "endAt": "Scheduled end date of the A/B test (ISO 8601).",
+ "stoppedAt": "Date the A/B test was stopped, if it was stopped early (ISO 8601).",
+ "configuration": "A/B test configuration, such as outlier and empty-search handling.",
+ "decision": "Automatic decision on the test outcome, when available.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/settings.py
index 596d347893d6..369a2e7c4857 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/settings.py
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from enum import Enum
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField
@@ -9,24 +11,38 @@ class PaginationStyle(Enum):
CURSOR = "cursor"
# Search endpoints (synonyms/rules) and `GET /1/indexes` use 0-based `page` numbers.
PAGE = "page"
+ # Analytics and A/B testing endpoints page via `offset`/`limit`.
+ OFFSET = "offset"
+
+
+class AlgoliaApi(Enum):
+ # Search API, served per-application at `{application_id}.algolia.net`.
+ SEARCH = "search"
+ # Analytics and A/B Testing APIs, served at `analytics.{region}.algolia.com`.
+ ANALYTICS = "analytics"
-@dataclass
+@frozen
class AlgoliaEndpointConfig:
name: str
- # Path on the Algolia REST API. `{index}` is substituted with the configured index name.
+ # Path on the Algolia REST API. `{index}` is substituted with the configured index name; for
+ # analytics endpoints the index travels as an `index` query param instead (no `{index}` in path).
path: str
method: str
pagination: PaginationStyle
- # Key in the JSON response that holds the list of rows (`hits`, `items`).
+ # Key in the JSON response that holds the list of rows (`hits`, `items`, `searches`, `abtests`).
data_selector: str
primary_keys: list[str] = field(default_factory=lambda: ["objectID"])
# Whether the endpoint targets a specific index (so it needs the `index_name` field).
requires_index: bool = True
should_sync_default: bool = True
- # Rows requested per page (`hitsPerPage`). Algolia caps browse/search at 1000.
+ # Rows requested per page (`hitsPerPage` for search, `limit` for analytics). Algolia caps both at 1000.
page_size: int = 1000
incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Which Algolia API (and therefore which host) serves this endpoint.
+ api: AlgoliaApi = AlgoliaApi.SEARCH
+ # Request click/conversion metrics alongside the base analytics table (analytics endpoints only).
+ click_analytics: bool = False
# All Algolia endpoints below are full-refresh: the index browse endpoint and the
@@ -71,6 +87,63 @@ ALGOLIA_ENDPOINTS: dict[str, AlgoliaEndpointConfig] = {
requires_index=False,
should_sync_default=False,
),
+ # Analytics API — aggregate metrics for the configured index over Algolia's default recent
+ # window (no server-side "updated since" filter, so each sync replaces the snapshot).
+ "top_searches": AlgoliaEndpointConfig(
+ name="top_searches",
+ path="/2/searches",
+ method="GET",
+ pagination=PaginationStyle.OFFSET,
+ data_selector="searches",
+ primary_keys=["search"],
+ should_sync_default=False,
+ api=AlgoliaApi.ANALYTICS,
+ click_analytics=True,
+ ),
+ "top_hits": AlgoliaEndpointConfig(
+ name="top_hits",
+ path="/2/hits",
+ method="GET",
+ pagination=PaginationStyle.OFFSET,
+ data_selector="hits",
+ primary_keys=["hit"],
+ should_sync_default=False,
+ api=AlgoliaApi.ANALYTICS,
+ click_analytics=True,
+ ),
+ "searches_no_results": AlgoliaEndpointConfig(
+ name="searches_no_results",
+ path="/2/searches/noResults",
+ method="GET",
+ pagination=PaginationStyle.OFFSET,
+ data_selector="searches",
+ primary_keys=["search"],
+ should_sync_default=False,
+ api=AlgoliaApi.ANALYTICS,
+ ),
+ "searches_no_clicks": AlgoliaEndpointConfig(
+ name="searches_no_clicks",
+ path="/2/searches/noClicks",
+ method="GET",
+ pagination=PaginationStyle.OFFSET,
+ data_selector="searches",
+ primary_keys=["search"],
+ should_sync_default=False,
+ api=AlgoliaApi.ANALYTICS,
+ ),
+ # A/B Testing API v3 (`/3/abtests`). The v2 `/2/abtests` listing is deprecated in favour of this;
+ # each row carries the test definition and its per-variant results. Application-level (no index).
+ "ab_tests": AlgoliaEndpointConfig(
+ name="ab_tests",
+ path="/3/abtests",
+ method="GET",
+ pagination=PaginationStyle.OFFSET,
+ data_selector="abtests",
+ primary_keys=["abTestID"],
+ requires_index=False,
+ should_sync_default=False,
+ api=AlgoliaApi.ANALYTICS,
+ ),
}
ENDPOINTS = tuple(ALGOLIA_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/source.py
index 6925d05f5c38..170853f2a13b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/source.py
@@ -7,6 +7,8 @@ from posthog.schema import (
SourceConfig,
SourceFieldInputConfig,
SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.algolia.algolia import (
@@ -39,6 +41,11 @@ _ENDPOINT_DESCRIPTIONS: dict[str, str] = {
"synonyms": "Synonyms configured on the index. Full refresh only.",
"rules": "Query rules configured on the index. Full refresh only.",
"indices": "Every index on the application. Full refresh only.",
+ "top_searches": "Most popular searches on the index with search and click/conversion counts. Full refresh only.",
+ "top_hits": "Most frequent search results on the index with click and conversion counts. Full refresh only.",
+ "searches_no_results": "Most frequent searches on the index that returned zero results. Full refresh only.",
+ "searches_no_clicks": "Most frequent searches on the index that received no clicks. Full refresh only.",
+ "ab_tests": "A/B tests configured on the application, with per-variant results. Full refresh only.",
}
@@ -65,6 +72,9 @@ The API key needs the ACLs for the data you want to sync:
- `browse` — index records
- `settings` — synonyms and query rules
- `listIndexes` — the list of indices
+- `analytics` — top searches, top hits, zero-result/zero-click searches, and A/B tests
+
+Set the region to match where your Algolia application is hosted. It selects the analytics host used for the analytics and A/B test tables.
""",
iconPath="/static/services/algolia.png",
docsUrl="https://posthog.com/docs/cdp/sources/algolia",
@@ -95,6 +105,16 @@ The API key needs the ACLs for the data you want to sync:
placeholder="your_index",
secret=False,
),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (analytics.algolia.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (analytics.de.algolia.com)", value="de"),
+ ],
+ ),
],
),
)
@@ -146,6 +166,7 @@ The API key needs the ACLs for the data you want to sync:
api_key=config.api_key,
index_name=config.index_name,
schema_name=schema_name,
+ region=config.region,
)
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AlgoliaResumeConfig]:
@@ -165,6 +186,7 @@ The API key needs the ACLs for the data you want to sync:
team_id=inputs.team_id,
job_id=inputs.job_id,
manager=resumable_source_manager,
+ region=config.region,
)
def get_canonical_descriptions(self) -> CanonicalDescriptions:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py
index b555ba39554c..bdfb8f1f5559 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/algolia/tests/test_algolia.py
@@ -1,4 +1,5 @@
import json
+import dataclasses
from typing import Any
import pytest
@@ -66,7 +67,7 @@ def _wire(session: mock.MagicMock, responses: list[Response]) -> list[dict[str,
return snapshots
-def _build(endpoint: str, manager: mock.MagicMock, index_name: str | None = "idx") -> Any:
+def _build(endpoint: str, manager: mock.MagicMock, index_name: str | None = "idx", region: str = "us") -> Any:
return algolia_source(
endpoint=endpoint,
application_id="APP",
@@ -75,6 +76,7 @@ def _build(endpoint: str, manager: mock.MagicMock, index_name: str | None = "idx
team_id=1,
job_id="job",
manager=manager,
+ region=region,
)
@@ -110,6 +112,23 @@ class TestEndpointUrl:
def test_app_level_endpoint_ignores_index(self) -> None:
assert _endpoint_url("APP", ALGOLIA_ENDPOINTS["indices"], None) == "https://APP.algolia.net/1/indexes"
+ def test_analytics_endpoint_uses_regional_analytics_host(self) -> None:
+ # Analytics endpoints live on the region-specific analytics host, not the per-application
+ # search host, and keep the index out of the path (it rides as a query param instead).
+ assert (
+ _endpoint_url("APP", ALGOLIA_ENDPOINTS["top_searches"], "idx", "us")
+ == "https://analytics.algolia.com/2/searches"
+ )
+ assert (
+ _endpoint_url("APP", ALGOLIA_ENDPOINTS["top_searches"], "idx", "de")
+ == "https://analytics.de.algolia.com/2/searches"
+ )
+
+ def test_abtests_endpoint_is_application_level_on_analytics_host(self) -> None:
+ assert (
+ _endpoint_url("APP", ALGOLIA_ENDPOINTS["ab_tests"], None, "us") == "https://analytics.algolia.com/3/abtests"
+ )
+
class TestCursorPagination:
@mock.patch(CLIENT_SESSION_PATCH)
@@ -193,7 +212,9 @@ class TestPagePagination:
) -> None:
session = MockSession.return_value
manager = _make_manager()
- monkeypatch.setattr(ALGOLIA_ENDPOINTS["synonyms"], "page_size", 2)
+ monkeypatch.setitem(
+ ALGOLIA_ENDPOINTS, "synonyms", dataclasses.replace(ALGOLIA_ENDPOINTS["synonyms"], page_size=2)
+ )
calls = _wire(
session,
[
@@ -244,6 +265,71 @@ class TestPagePagination:
assert calls[0]["params"]["page"] == 3
+class TestOffsetPagination:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_analytics_endpoint_stops_on_short_page(
+ self, MockSession: mock.MagicMock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ session = MockSession.return_value
+ manager = _make_manager()
+ monkeypatch.setitem(
+ ALGOLIA_ENDPOINTS, "top_searches", dataclasses.replace(ALGOLIA_ENDPOINTS["top_searches"], page_size=2)
+ )
+ calls = _wire(
+ session,
+ [
+ _response({"searches": [{"search": "a"}, {"search": "b"}]}),
+ _response({"searches": [{"search": "c"}]}),
+ ],
+ )
+
+ rows = _rows(_build("top_searches", manager))
+
+ assert [r["search"] for r in rows] == ["a", "b", "c"]
+ # The index and click-analytics flag ride as static query params; the paginator supplies
+ # offset/limit. A short final page (fewer rows than the limit) ends the walk.
+ assert [c["method"] for c in calls] == ["GET", "GET"]
+ assert calls[0]["url"] == "https://analytics.algolia.com/2/searches"
+ assert calls[0]["params"] == {"index": "idx", "clickAnalytics": "true", "offset": 0, "limit": 2}
+ assert calls[1]["params"]["offset"] == 2
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [AlgoliaResumeConfig(offset=2)]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_abtests_terminates_on_total_and_omits_index(
+ self, MockSession: mock.MagicMock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ session = MockSession.return_value
+ manager = _make_manager()
+ monkeypatch.setitem(
+ ALGOLIA_ENDPOINTS, "ab_tests", dataclasses.replace(ALGOLIA_ENDPOINTS["ab_tests"], page_size=1)
+ )
+ calls = _wire(
+ session,
+ [
+ _response({"abtests": [{"abTestID": 1}], "total": 2}),
+ _response({"abtests": [{"abTestID": 2}], "total": 2}),
+ ],
+ )
+
+ rows = _rows(_build("ab_tests", manager, index_name=None))
+
+ assert [r["abTestID"] for r in rows] == [1, 2]
+ # A/B tests are application-level, so no index param is sent; the `total` field stops paging.
+ assert "index" not in calls[0]["params"]
+ assert [c["params"]["offset"] for c in calls] == [0, 1]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_resume_seeds_offset(self, MockSession: mock.MagicMock) -> None:
+ session = MockSession.return_value
+ manager = _make_manager(AlgoliaResumeConfig(offset=5))
+ calls = _wire(session, [_response({"searches": []})])
+
+ _rows(_build("top_searches", manager))
+
+ assert calls[0]["params"]["offset"] == 5
+
+
class TestAlgoliaSourceResponse:
@pytest.mark.parametrize("endpoint", list(ALGOLIA_ENDPOINTS.keys()))
@mock.patch(CLIENT_SESSION_PATCH)
@@ -304,6 +390,24 @@ class TestValidateCredentials:
assert valid is False
assert error is not None
+ def test_analytics_schema_probe_hits_regional_analytics_host(self) -> None:
+ # Probing an analytics schema must target the region's analytics host (not the search host)
+ # with the configured index, so the `analytics` ACL is what actually gets checked.
+ with mock.patch(ALGOLIA_SESSION_PATCH) as factory:
+ session = factory.return_value
+ session.get.return_value = _response({}, status_code=200)
+ valid, error = validate_credentials(
+ application_id="APP",
+ api_key="key",
+ index_name="idx",
+ schema_name="top_searches",
+ region="de",
+ )
+ assert valid is True and error is None
+ args, kwargs = session.get.call_args
+ assert args[0] == "https://analytics.de.algolia.com/2/searches"
+ assert kwargs["params"]["index"] == "idx"
+
def test_invalid_application_id_rejected_before_request(self) -> None:
with mock.patch(ALGOLIA_SESSION_PATCH) as factory:
valid, error = validate_credentials(application_id="evil.com/", api_key="key", index_name="idx")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/algolia.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/algolia.py
index 7bc2c987da78..0ced6ce205ec 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/algolia.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/algolia.py
@@ -1,6 +1,8 @@
# This file is automatically generated from `SourceRegistry.get_all_sources()`
# Do not edit manually - run `pnpm generate:source-configs` to regenerate.
+from typing import Literal
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common import config
@@ -9,3 +11,4 @@ class AlgoliaSourceConfig(config.Config):
application_id: str
api_key: str
index_name: str
+ region: Literal["us", "de"] = config.value(default="us")