: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(configcat): sync audit logs, members, tags and stale flags (#103714)
Tom Owersd870e3defab2
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 c84173550889..1bcbe1cb69f9 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@@ -1944,7 +1944,7 @@ Note: Bundled OpenAPI 3.1 spec (redoc spec-url from api.doc.concordnow.com). Top## ConfigCat — gaps-Today (6): `configs`, `environments`, `organizations`, `products`, `setting_values`, `settings`+Today (12): `audit_logs`, `configs`, `environments`, `organization_members`, `organizations`, `product_members`, `products`, `setting_values`, `settings`, `stale_flags`, `tag_settings`, `tags`Diffed against: <https://api.configcat.com/docs/v1/swagger.json>@@ -1952,16 +1952,16 @@ Diffed against: <https://api.configcat.com/docs/v1/swagger.json>- [x] `GET /v1/products/{productId}/environments` — environment lookup table; flag values are per environment (high)- [x] `GET /v1/configs/{configId}/settings` — the feature flag / setting catalog - the product's headline object (high)- [x] `GET /v2/configs/{configId}/environments/{environmentId}/values` — flag values and targeting rules per environment; what is actually rolled out where (high)-- [ ] `GET /v2/products/{productId}/auditlogs and /v2/organizations/{organizationId}/auditlogs` — change history - who flipped which flag when (high)+- [x] `GET /v2/products/{productId}/auditlogs and /v2/organizations/{organizationId}/auditlogs` — change history - who flipped which flag when (high)- [ ] `GET /v1/products/{productId}/segments` — reusable targeting segments referenced by flag rules (medium)-- [ ] `GET /v1/products/{productId}/tags (and /v1/tags/{tagId}/settings)` — tag lookup plus the tag->setting junction (medium)-- [ ] `GET /v2/organizations/{organizationId}/members and /v1/products/{productId}/members` — user membership and product access (medium)-- [ ] `GET /v1/products/{productId}/staleflags` — stale-flag report - the standard cleanup/tech-debt query (medium)+- [x] `GET /v1/products/{productId}/tags (and /v1/tags/{tagId}/settings)` — tag lookup plus the tag->setting junction (medium)+- [x] `GET /v2/organizations/{organizationId}/members and /v1/products/{productId}/members` — user membership and product access (medium)+- [x] `GET /v1/products/{productId}/staleflags` — stale-flag report - the standard cleanup/tech-debt query (medium)- [ ] `GET /v1/products/{productId}/permissions` — permission group lookup resolving member role ids (low)- [ ] `GET /v1/settings/{settingId}/code-references` — where each flag is referenced in source, for removal analysis (low)- [ ] `GET /v1/configs/{configId}/deleted-settings` — deleted flags, needed to keep historical joins from dangling (low)-Note: Source exposes 6 static endpoints (settings.py CONFIGCAT_ENDPOINTS) with no dynamic discovery. The vendor spec has ~48 GET operations. The config/environment/setting model - i.e. what ConfigCat actually is - now syncs; the remaining gaps are audit logs, segments, tags, members and the cleanup reports. Note: I include feature-flag 'settings' despite the generic exclusion on feature flags, because here they are the vendor's core catalog object, not incidental plumbing.+Note: Source exposes 12 static endpoints (settings.py CONFIGCAT_ENDPOINTS) with no dynamic discovery. The vendor spec has ~48 GET operations. The config/environment/setting model - i.e. what ConfigCat actually is - now syncs, along with audit logs, stale flags, members and tags; the remaining gaps are segments, permissions and the code-reference reports. Audit logs sync from the organization endpoint only, which already covers every product in the organization (productId is one of its filters), so the per-product endpoint would only repeat those rows. Note: I include feature-flag 'settings' despite the generic exclusion on feature flags, because here they are the vendor's core catalog object, not incidental plumbing.## Confluence — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/canonical_descriptions.pyindex 5728fbd47d3c..7194cd742463 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/canonical_descriptions.py@@ -92,4 +92,89 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"changeRequestCount": "The number of open change requests for the feature flag or setting.",},},+ "audit_logs": {+ "description": "A ConfigCat audit log entry — one recorded change to a product, config, environment, feature flag or member, with who made it and why.",+ "docs_url": "https://api.configcat.com/docs",+ "columns": {+ "organizationId": "The unique identifier (GUID) of the organization the change was recorded under.",+ "auditLogId": "The identifier of the audit log entry.",+ "auditLogDateTime": "The time the change was made.",+ "auditLogType": "The kind of change that was made, such as settingValueChanged or configCreated.",+ "auditLogTypeEnum": "The kind of change that was made, as the API's enum value.",+ "userEmail": "The email of the user who made the change.",+ "userName": "The name of the user who made the change.",+ "where": "The product, config and environment the change was made in.",+ "why": "The reason the user gave for the change, where the product requires one.",+ "actionTarget": "The object the change was made to, such as the feature flag key.",+ "details": "A description of what changed.",+ "modelVersion": "The version of the audited object after the change.",+ "truncated": "Whether the details were shortened because the change was too large to record in full.",+ },+ },+ "organization_members": {+ "description": "A person's membership of a ConfigCat organization — one row per user per role, so a user who is both an admin and a billing manager appears twice.",+ "docs_url": "https://api.configcat.com/docs",+ "columns": {+ "organizationId": "The unique identifier (GUID) of the organization.",+ "userId": "The identifier of the member.",+ "memberType": "The role the row records: admin, billingManager or member.",+ "fullName": "The name of the member.",+ "email": "The email of the member.",+ "twoFactorEnabled": "Whether two-factor authentication is enabled for the member.",+ "permissions": "The member's per-product permission groups (only set for the member role).",+ },+ },+ "product_members": {+ "description": "A person's access to a ConfigCat product, with the permission group that decides what they can change.",+ "docs_url": "https://api.configcat.com/docs",+ "columns": {+ "productId": "The unique identifier (GUID) of the product the member has access to.",+ "userId": "The identifier of the member.",+ "permissionGroupId": "The identifier of the member's permission group.",+ "fullName": "The name of the member.",+ "email": "The email of the member.",+ },+ },+ "stale_flags": {+ "description": "A ConfigCat zombie (stale) flag — a feature flag nothing has changed for long enough that it is a candidate for removal, with its staleness in each environment.",+ "docs_url": "https://api.configcat.com/docs",+ "columns": {+ "productId": "The unique identifier (GUID) of the product the stale flag belongs to.",+ "configId": "The unique identifier (GUID) of the config the stale flag belongs to.",+ "configName": "The name of the config the stale flag belongs to.",+ "settingId": "The identifier of the feature flag or setting.",+ "key": "The key the SDKs read the feature flag or setting by.",+ "name": "The name of the feature flag or setting.",+ "hint": "The description of the feature flag or setting.",+ "hasCodeReferences": "Whether code references have been uploaded for the feature flag or setting.",+ "tags": "The tags attached to the feature flag or setting.",+ "settingValues": "Per-environment staleness: the environment, the time the flag was last updated there, and whether it counts as stale.",+ },+ },+ "tags": {+ "description": "A ConfigCat tag — a label attached to feature flags to group them, defined per product.",+ "docs_url": "https://api.configcat.com/docs",+ "columns": {+ "tagId": "The identifier of the tag.",+ "name": "The name of the tag.",+ "color": "The configured color of the tag on the ConfigCat dashboard.",+ "product": "The product that owns the tag (nested object with productId and name).",+ },+ },+ "tag_settings": {+ "description": "The tag to feature flag junction — one row per feature flag carrying a tag, with the flag's own details.",+ "docs_url": "https://api.configcat.com/docs",+ "columns": {+ "tagId": "The identifier of the tag attached to the feature flag or setting.",+ "settingId": "The identifier of the feature flag or setting.",+ "configId": "The unique identifier (GUID) of the config the feature flag or setting belongs to.",+ "configName": "The name of the config the feature flag or setting belongs to.",+ "key": "The key the SDKs read the feature flag or setting by.",+ "name": "The name of the feature flag or setting.",+ "hint": "The description of the feature flag or setting.",+ "settingType": "The value type of the feature flag or setting (boolean, string, int or double).",+ "createdAt": "The creation time of the feature flag or setting.",+ "tags": "Every tag attached to the feature flag or setting, not only the one this row is keyed on.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/configcat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/configcat.pyindex 1b54c6d60ca0..1955165410c8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/configcat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/configcat.py@@ -1,6 +1,8 @@import base64-from collections.abc import Iterator+from collections.abc import Callable, Iterator+from datetime import UTC, datetimefrom typing import Any, Optional+from urllib.parse import urlencodeimport requests@@ -26,6 +28,11 @@ REQUEST_TIMEOUT_SECONDS = 60# The v2 values response is an envelope describing one config/environment pair; the per-flag rows# sit under this key.SETTING_FORMULAS_SELECTOR = "settingFormulas"+# The audit log is the one paged endpoint; 100 is the maximum page size it accepts.+AUDIT_LOG_PAGE_SIZE = 100+# Each list in the organization members envelope, and the role it records. A user appears in more+# than one when they hold more than one role.+ORGANIZATION_MEMBER_GROUPS = (("admins", "admin"), ("billingManagers", "billingManager"), ("members", "member"))def _headers(username: str, password: str) -> dict[str, str]:@@ -65,6 +72,10 @@ def _product_ids(session: requests.Session) -> list[str]:return _ids(_get_list(session, CONFIGCAT_ENDPOINTS["products"].path), "productId")+def _organization_ids(session: requests.Session) -> list[str]:+ return _ids(_get_list(session, CONFIGCAT_ENDPOINTS["organizations"].path), "organizationId")++def _configs(session: requests.Session, product_id: str) -> list[dict[str, Any]]:path = CONFIGCAT_ENDPOINTS["configs"].path.format(productId=product_id)rows = _get_list(session, path)@@ -129,53 +140,236 @@ def _v1_setting_value_rows(body: Any, config_id: str, environment_id: str) -> lireturn rows+def _stale_flag_rows(body: Any, product_id: str) -> list[dict[str, Any]]:+ """Flatten the stale-flag report into one row per flag, keeping its per-environment detail."""+ if not isinstance(body, dict):+ raise ValueError(f"ConfigCat returned a non-object staleflags body for product {product_id}")+ configs = body.get("configs")+ if not isinstance(configs, list):+ raise ValueError(f"ConfigCat returned invalid staleflags configs for product {product_id}")++ rows: list[dict[str, Any]] = []+ for config in configs:+ if not isinstance(config, dict):+ raise ValueError(f"ConfigCat returned a non-object staleflags config for product {product_id}")+ config_id = _identifier(config, "configId")+ settings = config.get("settings")+ if not isinstance(settings, list):+ raise ValueError(f"ConfigCat returned invalid staleflags settings for config {config_id}")+ for setting in settings:+ if not isinstance(setting, dict):+ raise ValueError(f"ConfigCat returned a non-object stale flag for config {config_id}")+ rows.append(+ {+ **setting,+ "productId": product_id,+ "configId": config_id,+ "configName": config.get("name"),+ }+ )+ return rows+++def _organization_member_rows(body: Any, organization_id: str) -> list[dict[str, Any]]:+ """Flatten the members envelope into one row per user per role."""+ if not isinstance(body, dict):+ raise ValueError(f"ConfigCat returned a non-object members body for organization {organization_id}")++ rows: list[dict[str, Any]] = []+ for key, member_type in ORGANIZATION_MEMBER_GROUPS:+ members = body.get(key)+ if not isinstance(members, list):+ raise ValueError(f"ConfigCat returned invalid {key} for organization {organization_id}")+ for member in members:+ if not isinstance(member, dict):+ raise ValueError(f"ConfigCat returned a non-object {key} entry for organization {organization_id}")+ rows.append({**member, "organizationId": organization_id, "memberType": member_type})+ return rows+++# Endpoints whose body is an envelope rather than a bare array, keyed by schema name. Each builder+# reshapes one response into rows, given the parent id the envelope does not repeat on every item.+ENVELOPE_ROW_BUILDERS: dict[str, Callable[[Any, str], list[dict[str, Any]]]] = {+ "stale_flags": _stale_flag_rows,+ "organization_members": _organization_member_rows,+}+++def _to_configcat_datetime(value: Any) -> Optional[str]:+ """Coerce an incremental cursor value into the UTC ISO 8601 shape `fromUtcDateTime` takes."""+ if isinstance(value, str):+ try:+ value = datetime.fromisoformat(value)+ except ValueError:+ return None+ if not isinstance(value, datetime):+ return None+ normalized = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)+ return normalized.isoformat()+++def _audit_log_pages(+ session: requests.Session, organization_id: str, since: Optional[str]+) -> Iterator[list[dict[str, Any]]]:+ base_path = CONFIGCAT_ENDPOINTS["audit_logs"].path.format(organizationId=organization_id)+ page_number = 1+ while True:+ params: dict[str, Any] = {"pageNumber": page_number, "pageSize": AUDIT_LOG_PAGE_SIZE}+ if since is not None:+ params["fromUtcDateTime"] = since+ body = _get(session, f"{base_path}?{urlencode(params)}")+ if not isinstance(body, dict):+ raise ValueError(f"ConfigCat returned a non-object auditlogs body for organization {organization_id}")+ data = body.get("data")+ if not isinstance(data, list):+ raise ValueError(f"ConfigCat returned invalid auditlogs data for organization {organization_id}")+ rows: list[dict[str, Any]] = []+ for item in data:+ if not isinstance(item, dict):+ raise ValueError(f"ConfigCat returned a non-object audit log for organization {organization_id}")+ rows.append({**item, "organizationId": organization_id})+ paging = body.get("paging")+ # Losing `hasNext` would end the walk silently, and a run that stops early still commits+ # its watermark — so the rows behind the truncation would never be fetched again.+ if not isinstance(paging, dict) or not isinstance(paging.get("hasNext"), bool):+ raise ValueError(f"ConfigCat returned invalid auditlogs paging for organization {organization_id}")++ if rows:+ yield rows++ # An empty page also terminates: it is what a page past the end returns, so the walk stops+ # even if `hasNext` ever disagrees with the data.+ if not rows or not paging["hasNext"]:+ return+ page_number += 1++def _validate_primary_keys(rows: list[dict[str, Any]], primary_keys: list[str]) -> None:for row in rows:for field in primary_keys:_identifier(row, field)-def _fan_out_rows(session: requests.Session, config: ConfigCatEndpointConfig) -> Iterator[list[dict[str, Any]]]:- for product_id in _product_ids(session):- if config.parent == "product":- rows = _get_list(session, config.path.format(productId=product_id))- _validate_primary_keys(rows, config.primary_keys)+def _parent_scoped_rows(+ session: requests.Session, config: ConfigCatEndpointConfig, parent_id: str, path: str+) -> list[dict[str, Any]]:+ builder = ENVELOPE_ROW_BUILDERS.get(config.name)+ rows = builder(_get(session, path), parent_id) if builder is not None else _get_list(session, path)+ _validate_primary_keys(rows, config.primary_keys)+ return rows+++def _organization_rows(+ session: requests.Session, config: ConfigCatEndpointConfig, since: Optional[str]+) -> Iterator[list[dict[str, Any]]]:+ for organization_id in _organization_ids(session):+ if config.name == "audit_logs":+ for page in _audit_log_pages(session, organization_id, since):+ _validate_primary_keys(page, config.primary_keys)+ yield page+ continue++ rows = _parent_scoped_rows(session, config, organization_id, config.path.format(organizationId=organization_id))+ if rows:+ yield rows+++def _tag_setting_rows(+ session: requests.Session, config: ConfigCatEndpointConfig, product_id: str+) -> Iterator[list[dict[str, Any]]]:+ tags_path = CONFIGCAT_ENDPOINTS["tags"].path.format(productId=product_id)+ for tag in _get_list(session, tags_path):+ tag_id = _identifier(tag, "tagId")+ # Carry the tag's own value rather than the stringified id, so the junction column keeps the+ # integer type the `tags` table stores it under.+ rows = [{**row, "tagId": tag["tagId"]} for row in _get_list(session, config.path.format(tagId=tag_id))]+ _validate_primary_keys(rows, config.primary_keys)+ if rows:+ yield rows+++def _config_child_rows(+ session: requests.Session, config: ConfigCatEndpointConfig, configs: list[dict[str, Any]]+) -> Iterator[list[dict[str, Any]]]:+ for config_row in configs:+ config_id = _identifier(config_row, "configId")+ rows = _get_list(session, config.path.format(configId=config_id))+ _validate_primary_keys(rows, config.primary_keys)+ if rows:+ yield rows+++def _config_environment_rows(+ session: requests.Session,+ config: ConfigCatEndpointConfig,+ configs: list[dict[str, Any]],+ environment_ids: list[str],+) -> Iterator[list[dict[str, Any]]]:+ for config_row in configs:+ config_id = _identifier(config_row, "configId")+ evaluation_version = config_row.get("evaluationVersion")+ if evaluation_version not in ("v1", "v2"):+ raise ValueError(f"ConfigCat config {config_id} has an invalid evaluationVersion")+ for environment_id in environment_ids:+ if evaluation_version == "v1":+ path = f"/v1/configs/{config_id}/environments/{environment_id}/values"+ rows = _v1_setting_value_rows(_get(session, path), config_id, environment_id)+ else:+ path = config.path.format(configId=config_id, environmentId=environment_id)+ rows = _setting_value_rows(_get(session, path), config_id, environment_id)if rows:yield rows- continue- configs = _configs(session, product_id)- if config.parent == "config":- for config_row in configs:- config_id = _identifier(config_row, "configId")- rows = _get_list(session, config.path.format(configId=config_id))- _validate_primary_keys(rows, config.primary_keys)- if rows:- yield rows- continue+def _product_child_rows(+ session: requests.Session, config: ConfigCatEndpointConfig, product_id: str+) -> Iterator[list[dict[str, Any]]]:+ if config.parent == "product":+ rows = _parent_scoped_rows(session, config, product_id, config.path.format(productId=product_id))+ if rows:+ yield rows+ return++ if config.parent == "tag":+ yield from _tag_setting_rows(session, config, product_id)+ return++ configs = _configs(session, product_id)++ if config.parent == "config":+ yield from _config_child_rows(session, config, configs)+ return++ yield from _config_environment_rows(session, config, configs, _environment_ids(session, product_id))- environment_ids = _environment_ids(session, product_id)- for config_row in configs:- config_id = _identifier(config_row, "configId")- evaluation_version = config_row.get("evaluationVersion")- if evaluation_version not in ("v1", "v2"):- raise ValueError(f"ConfigCat config {config_id} has an invalid evaluationVersion")- for environment_id in environment_ids:- if evaluation_version == "v1":- path = f"/v1/configs/{config_id}/environments/{environment_id}/values"- rows = _v1_setting_value_rows(_get(session, path), config_id, environment_id)- else:- path = config.path.format(configId=config_id, environmentId=environment_id)- rows = _setting_value_rows(_get(session, path), config_id, environment_id)- if rows:- yield rows---def _fan_out_source(username: str, password: str, config: ConfigCatEndpointConfig) -> SourceResponse:++def _fan_out_rows(+ session: requests.Session, config: ConfigCatEndpointConfig, since: Optional[str]+) -> Iterator[list[dict[str, Any]]]:+ if config.parent == "organization":+ yield from _organization_rows(session, config, since)+ return++ for product_id in _product_ids(session):+ yield from _product_child_rows(session, config, product_id)+++def _partition_kwargs(config: ConfigCatEndpointConfig) -> dict[str, Any]:+ if config.partition_key is None:+ return {}+ return {+ "partition_mode": "datetime",+ "partition_format": "month",+ "partition_keys": [config.partition_key],+ }+++def _fan_out_source(+ username: str, password: str, config: ConfigCatEndpointConfig, since: Optional[str]+) -> SourceResponse:def items() -> Iterator[list[dict[str, Any]]]:session = make_tracked_session(headers=_headers(username, password), redact_values=(username, password))- yield from _fan_out_rows(session, config)+ yield from _fan_out_rows(session, config, since)return SourceResponse(name=config.name,@@ -183,6 +377,8 @@ def _fan_out_source(username: str, password: str, config: ConfigCatEndpointConfiprimary_keys=config.primary_keys,partition_count=1,partition_size=1,+ sort_mode=config.sort_mode,+ **_partition_kwargs(config),)@@ -192,11 +388,12 @@ def configcat_source(endpoint: str,team_id: int,job_id: str,+ db_incremental_field_last_value: Optional[Any] = None,) -> SourceResponse:config = CONFIGCAT_ENDPOINTS[endpoint]if config.parent is not None:- return _fan_out_source(username, password, config)+ return _fan_out_source(username, password, config, _to_configcat_datetime(db_incremental_field_last_value))rest_config: RESTAPIConfig = {"client": {@@ -230,6 +427,8 @@ def configcat_source(partition_count=1,partition_size=1,column_hints=resource.column_hints,+ sort_mode=config.sort_mode,+ **_partition_kwargs(config),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/settings.pyindex 84baba7ab471..9f7bc44a1110 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/settings.py@@ -2,12 +2,14 @@ from typing import Literalfrom posthog.dataclasses import frozen-from products.warehouse_sources.backend.types import IncrementalField+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortMode+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# Which parent a fan-out endpoint is queried once per. Everything below a product is addressed by# GUID only, so the deeper resources are reached by walking products first. `config_environment`-# is the config/environment pair the v2 values endpoint takes.-ConfigCatParent = Literal["product", "config", "config_environment"]+# is the config/environment pair the v2 values endpoint takes, and `tag` is reached by walking a+# product's tags.+ConfigCatParent = Literal["organization", "product", "config", "config_environment", "tag"]@frozen@@ -20,10 +22,13 @@ class ConfigCatEndpointConfig:primary_keys: list[str]# None for a top-level listing fetched in a single request.parent: ConfigCatParent | None = None+ # Stable creation timestamp to partition on, where the resource has one.+ partition_key: str | None = None+ sort_mode: SortMode = "asc"-# ConfigCat Public Management API endpoints. None of them accept a page, cursor or timestamp-# parameter — every response is the full collection — so sync is full refresh only.+# ConfigCat Public Management API endpoints. Only the audit log is paged and time-filtered; every+# other response is the full collection in one request, so those sync full refresh only.CONFIGCAT_ENDPOINTS: dict[str, ConfigCatEndpointConfig] = {"products": ConfigCatEndpointConfig(name="products", path="/v1/products", primary_keys=["productId"]),"organizations": ConfigCatEndpointConfig(@@ -56,8 +61,70 @@ CONFIGCAT_ENDPOINTS: dict[str, ConfigCatEndpointConfig] = {primary_keys=["configId", "environmentId", "settingId"],parent="config_environment",),+ # Change history. The organization endpoint already covers every product in the organization —+ # `productId` is one of its filters — so the per-product endpoint would only repeat these rows.+ "audit_logs": ConfigCatEndpointConfig(+ name="audit_logs",+ path="/v2/organizations/{organizationId}/auditlogs",+ primary_keys=["organizationId", "auditLogId"],+ parent="organization",+ partition_key="auditLogDateTime",+ # The API documents no ordering for the audit log and returns newest-first in practice. In+ # `desc` the pipeline only commits the watermark once the whole run finishes, which is+ # correct whichever order rows arrive in; `asc` would commit a too-high watermark after the+ # first page and skip everything behind it.+ sort_mode="desc",+ ),+ "organization_members": ConfigCatEndpointConfig(+ name="organization_members",+ path="/v2/organizations/{organizationId}/members",+ # One user can hold more than one role in an organization (an admin is often a billing+ # manager too), and the response lists each role separately, so the role is part of the key.+ primary_keys=["organizationId", "userId", "memberType"],+ parent="organization",+ ),+ "product_members": ConfigCatEndpointConfig(+ name="product_members",+ path="/v1/products/{productId}/members",+ primary_keys=["productId", "userId"],+ parent="product",+ ),+ # The stale ("zombie") flag report: flags nothing has changed for a while, per environment.+ "stale_flags": ConfigCatEndpointConfig(+ name="stale_flags",+ path="/v1/products/{productId}/staleflags",+ primary_keys=["productId", "configId", "settingId"],+ parent="product",+ ),+ # `tagId` is keyed on its own because ConfigCat addresses a tag by id alone (`/v1/tags/{tagId}`),+ # the same reasoning the config and environment tables key on their own GUID.+ "tags": ConfigCatEndpointConfig(+ name="tags",+ path="/v1/products/{productId}/tags",+ primary_keys=["tagId"],+ parent="product",+ ),+ # The tag -> feature flag junction. A flag carries several tags and a tag several flags, so the+ # tag is part of the key alongside the flag's own config-scoped identity.+ "tag_settings": ConfigCatEndpointConfig(+ name="tag_settings",+ path="/v1/tags/{tagId}/settings",+ primary_keys=["tagId", "configId", "settingId"],+ parent="tag",+ ),}ENDPOINTS = tuple(CONFIGCAT_ENDPOINTS.keys())-INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}+# Only the audit log takes a server-side time filter (`fromUtcDateTime`). Everything else returns+# its whole collection with no way to bound it, so a "cursor" there would cost a full sync anyway.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ "audit_logs": [+ {+ "label": "auditLogDateTime",+ "type": IncrementalFieldType.DateTime,+ "field": "auditLogDateTime",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/source.pyindex 2683ddceff32..04af64dd6078 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/source.py@@ -102,8 +102,8 @@ Create a Public API credential (a username and password pair) under **Public Manforce_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # Every endpoint is full refresh only — ConfigCat's list endpoints expose no pagination and- # no server-side timestamp filter, so there is no incremental cursor to advance.+ # Only the audit log is incremental — every other list endpoint returns its full+ # collection with no pagination and no server-side timestamp filter to advance a cursor on.return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)def validate_credentials(@@ -126,4 +126,7 @@ Create a Public API credential (a username and password pair) under **Public Manendpoint=inputs.schema_name,team_id=inputs.team_id,job_id=inputs.job_id,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value+ if inputs.should_use_incremental_field+ else None,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/tests/test_configcat.py b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/tests/test_configcat.pyindex a6ba925f43a7..589ae37fc322 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/tests/test_configcat.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/configcat/tests/test_configcat.py@@ -1,5 +1,6 @@import jsonimport base64+from datetime import UTC, datetime, timedelta, timezonefrom typing import Anyimport pytest@@ -256,6 +257,236 @@ class TestConfigCatFanOut:self._run(mock_make_session, {"/v1/products": {"error": "nope"}}, "configs")+def _audit_page(rows: list[dict[str, Any]], has_next: bool) -> dict[str, Any]:+ return {"data": rows, "paging": {"currentPage": 1, "totalPages": 1, "pageSize": 100, "hasNext": has_next}}+++class TestConfigCatAuditLogs:+ @staticmethod+ def _run(+ mock_make_session: MagicMock, bodies: dict[str, Any], **kwargs: Any+ ) -> tuple[list[dict[str, Any]], list[str]]:+ session = _FakeSession(bodies)+ mock_make_session.return_value = session+ rows = _rows(configcat_source("user", "pass", "audit_logs", team_id=1, job_id="j", **kwargs))+ return rows, session.paths++ @mock.patch.object(configcat, "make_tracked_session")+ def test_walks_every_page_until_the_api_stops_advertising_one(self, mock_make_session: MagicMock) -> None:+ bodies = {+ "/v1/organizations": [{"organizationId": "o1"}],+ "/v2/organizations/o1/auditlogs?pageNumber=1&pageSize=100": _audit_page([{"auditLogId": 2}], True),+ "/v2/organizations/o1/auditlogs?pageNumber=2&pageSize=100": _audit_page([{"auditLogId": 1}], False),+ }+ rows, paths = self._run(mock_make_session, bodies)++ # The organization is only on the request path, so it is lifted onto each row to complete+ # the primary key.+ assert rows == [+ {"auditLogId": 2, "organizationId": "o1"},+ {"auditLogId": 1, "organizationId": "o1"},+ ]+ assert paths[1:] == [+ "/v2/organizations/o1/auditlogs?pageNumber=1&pageSize=100",+ "/v2/organizations/o1/auditlogs?pageNumber=2&pageSize=100",+ ]++ @mock.patch.object(configcat, "make_tracked_session")+ def test_empty_page_stops_the_walk_even_when_has_next_stays_true(self, mock_make_session: MagicMock) -> None:+ # A page past the end comes back empty. Trusting `hasNext` alone would page forever.+ bodies = {+ "/v1/organizations": [{"organizationId": "o1"}],+ "/v2/organizations/o1/auditlogs?pageNumber=1&pageSize=100": _audit_page([{"auditLogId": 1}], True),+ "/v2/organizations/o1/auditlogs?pageNumber=2&pageSize=100": _audit_page([], True),+ }+ rows, paths = self._run(mock_make_session, bodies)++ assert rows == [{"auditLogId": 1, "organizationId": "o1"}]+ assert len(paths) == 3++ @mock.patch.object(configcat, "make_tracked_session")+ def test_incremental_run_bounds_the_request_with_the_watermark(self, mock_make_session: MagicMock) -> None:+ bodies = {+ "/v1/organizations": [{"organizationId": "o1"}],+ "/v2/organizations/o1/auditlogs"+ "?pageNumber=1&pageSize=100&fromUtcDateTime=2024-05-01T10%3A00%3A00%2B00%3A00": _audit_page([], False),+ }+ _, paths = self._run(+ mock_make_session,+ bodies,+ db_incremental_field_last_value=datetime(2024, 5, 1, 10, 0, tzinfo=UTC),+ )+ assert "fromUtcDateTime=2024-05-01T10%3A00%3A00%2B00%3A00" in paths[1]++ @mock.patch.object(configcat, "make_tracked_session")+ def test_full_refresh_run_omits_the_watermark(self, mock_make_session: MagicMock) -> None:+ bodies = {+ "/v1/organizations": [{"organizationId": "o1"}],+ "/v2/organizations/o1/auditlogs?pageNumber=1&pageSize=100": _audit_page([], False),+ }+ _, paths = self._run(mock_make_session, bodies)+ assert "fromUtcDateTime" not in paths[1]++ @parameterized.expand(+ [+ ("naive_datetime", datetime(2024, 5, 1, 10, 0), "2024-05-01T10:00:00+00:00"),+ (+ "other_timezone",+ datetime(2024, 5, 1, 12, 0, tzinfo=timezone(timedelta(hours=2))),+ "2024-05-01T10:00:00+00:00",+ ),+ ("iso_string", "2024-05-01T10:00:00+00:00", "2024-05-01T10:00:00+00:00"),+ ("unparseable_string", "not a date", None),+ ("no_watermark", None, None),+ ]+ )+ def test_watermark_is_coerced_to_utc(self, _name: str, value: Any, expected: str | None) -> None:+ # `fromUtcDateTime` is a UTC filter, so a naive or offset value has to be converted rather+ # than sent as written — a two-hour offset would otherwise skip two hours of history.+ assert configcat._to_configcat_datetime(value) == expected++ @parameterized.expand(+ [+ ("missing_data", {"paging": {"hasNext": False}}, "invalid auditlogs data"),+ ("missing_paging", {"data": []}, "invalid auditlogs paging"),+ ("non_boolean_has_next", {"data": [], "paging": {"hasNext": "yes"}}, "invalid auditlogs paging"),+ ]+ )+ @mock.patch.object(configcat, "make_tracked_session")+ def test_malformed_page_fails_loud(+ self, _name: str, page: dict[str, Any], error: str, mock_make_session: MagicMock+ ) -> None:+ # Losing `hasNext` would otherwise end the walk quietly, and the run would commit a+ # watermark past every row it never asked for.+ bodies = {+ "/v1/organizations": [{"organizationId": "o1"}],+ "/v2/organizations/o1/auditlogs?pageNumber=1&pageSize=100": page,+ }+ with pytest.raises(ValueError, match=error):+ self._run(mock_make_session, bodies)+++class TestConfigCatEnvelopeEndpoints:+ @staticmethod+ def _run(+ mock_make_session: MagicMock, bodies: dict[str, Any], endpoint: str+ ) -> tuple[list[dict[str, Any]], list[str]]:+ session = _FakeSession(bodies)+ mock_make_session.return_value = session+ rows = _rows(configcat_source("user", "pass", endpoint, team_id=1, job_id="j"))+ return rows, session.paths++ @mock.patch.object(configcat, "make_tracked_session")+ def test_stale_flags_flatten_to_one_row_per_flag(self, mock_make_session: MagicMock) -> None:+ bodies = {+ "/v1/products": [{"productId": "p1"}],+ "/v1/products/p1/staleflags": {+ "productId": "p1",+ "name": "Main",+ "environments": [{"environmentId": "e1", "name": "Production"}],+ "configs": [+ {+ "configId": "c1",+ "name": "Main config",+ "settings": [+ {+ "settingId": 1,+ "key": "old_flag",+ "settingValues": [{"environmentId": "e1", "isStale": True}],+ },+ {"settingId": 2, "key": "older_flag", "settingValues": []},+ ],+ }+ ],+ },+ }+ rows, _ = self._run(mock_make_session, bodies, "stale_flags")++ # The report nests flags under configs under one product, and repeats neither id on the+ # flag, so both are lifted onto each row to complete the primary key.+ assert [(row["productId"], row["configId"], row["settingId"]) for row in rows] == [+ ("p1", "c1", 1),+ ("p1", "c1", 2),+ ]+ assert rows[0]["configName"] == "Main config"+ assert rows[0]["settingValues"] == [{"environmentId": "e1", "isStale": True}]++ @mock.patch.object(configcat, "make_tracked_session")+ def test_organization_members_keep_one_row_per_role(self, mock_make_session: MagicMock) -> None:+ bodies = {+ "/v1/organizations": [{"organizationId": "o1"}],+ "/v2/organizations/o1/members": {+ "admins": [{"userId": "u1", "email": "[email protected]"}],+ "billingManagers": [{"userId": "u1", "email": "[email protected]"}],+ "members": [{"userId": "u2", "email": "[email protected]", "permissions": []}],+ },+ }+ rows, _ = self._run(mock_make_session, bodies, "organization_members")++ # u1 is both an admin and a billing manager, which is why the role is part of the key —+ # without it the two rows would collide and the merge would keep only one.+ assert [(row["organizationId"], row["userId"], row["memberType"]) for row in rows] == [+ ("o1", "u1", "admin"),+ ("o1", "u1", "billingManager"),+ ("o1", "u2", "member"),+ ]++ @parameterized.expand(+ [+ (+ "stale_flags",+ {"/v1/products": [{"productId": "p1"}], "/v1/products/p1/staleflags": []},+ "non-object staleflags body",+ ),+ (+ "organization_members",+ {"/v1/organizations": [{"organizationId": "o1"}], "/v2/organizations/o1/members": {"admins": []}},+ "invalid billingManagers",+ ),+ ]+ )+ @mock.patch.object(configcat, "make_tracked_session")+ def test_malformed_envelope_fails_loud(+ self, endpoint: str, bodies: dict[str, Any], error: str, mock_make_session: MagicMock+ ) -> None:+ with pytest.raises(ValueError, match=error):+ self._run(mock_make_session, bodies, endpoint)++ @parameterized.expand(+ [+ ("product_members", "/v1/products/{}/members", {"userId": "u1", "productId": "p1"}),+ ("tags", "/v1/products/{}/tags", {"tagId": 4, "name": "cleanup"}),+ ]+ )+ @mock.patch.object(configcat, "make_tracked_session")+ def test_product_listings_are_fetched_once_per_product(+ self, endpoint: str, child_path: str, row: dict[str, Any], mock_make_session: MagicMock+ ) -> None:+ bodies = {"/v1/products": [{"productId": "p1"}], child_path.format("p1"): [row]}+ rows, paths = self._run(mock_make_session, bodies, endpoint)++ assert rows == [row]+ assert paths == ["/v1/products", child_path.format("p1")]++ @mock.patch.object(configcat, "make_tracked_session")+ def test_tag_settings_walk_products_then_tags(self, mock_make_session: MagicMock) -> None:+ bodies = {+ "/v1/products": [{"productId": "p1"}],+ "/v1/products/p1/tags": [{"tagId": 4}, {"tagId": 5}],+ "/v1/tags/4/settings": [{"settingId": 1, "configId": "c1"}],+ "/v1/tags/5/settings": [{"settingId": 1, "configId": "c1"}],+ }+ rows, paths = self._run(mock_make_session, bodies, "tag_settings")++ # The same flag carries both tags, so the tag is part of the key and is lifted onto the row+ # as the integer the tags table stores it under.+ assert [(row["tagId"], row["configId"], row["settingId"]) for row in rows] == [+ (4, "c1", 1),+ (5, "c1", 1),+ ]+ assert paths[-2:] == ["/v1/tags/4/settings", "/v1/tags/5/settings"]++class TestCheckAccess:@staticmethoddef _session_for(response: Any) -> MagicMock:@@ -327,8 +558,10 @@ class TestConfigCatSourceResponse:response = configcat_source(username="user", password="pass", endpoint=endpoint, team_id=1, job_id="j")assert response.name == endpointassert response.primary_keys == CONFIGCAT_ENDPOINTS[endpoint].primary_keys- # The list endpoints expose no stable timestamp, so we don't partition.- assert response.partition_mode is None+ # Only an endpoint with a stable timestamp is partitioned on it; the rest expose none.+ partition_key = CONFIGCAT_ENDPOINTS[endpoint].partition_key+ assert response.partition_mode == ("datetime" if partition_key else None)+ assert response.partition_keys == ([partition_key] if partition_key else None)def test_primary_keys_are_per_endpoint(self) -> None:assert CONFIGCAT_ENDPOINTS["products"].primary_keys == ["productId"]@@ -340,6 +573,6 @@ class TestConfigCatSourceResponse:# A fan-out table aggregates rows from every parent, so a key missing a parent id seeds# duplicates that every later merge multi-matches.config = CONFIGCAT_ENDPOINTS[endpoint]- for placeholder in ("configId", "environmentId"):+ for placeholder in ("configId", "environmentId", "tagId", "organizationId"):if f"{{{placeholder}}}" in config.path:assert placeholder in config.primary_keys