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(flagsmith): add tags, identities, traits and segment override tables (#107410)

Tom Owers81291c9aabee
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index f3c2dc895dbb..3d2ee15c888d 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -569,8 +569,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/fireworks_ai/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/first_promoter.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/first_promoter/settings.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/flagsmith.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/fleetio.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/fleetio/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/flexmail/flexmail.py
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 73216806f5a4..465ffadd2ea8 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
@@ -3202,12 +3202,12 @@ Today (8): `audit_logs`, `environments`, `feature_states`, `features`, `organisa
Diffed against: <https://api.flagsmith.com/api/v1/swagger.json>
-- [ ] `/api/v1/environments/{environment_api_key}/identities/` — the end users flags are evaluated against; without them feature_states cannot be attributed to anyone (high)
-- [ ] `/api/v1/environments/{environment_api_key}/identities/{identity_pk}/traits/` — identity traits, the attributes segments are defined on - the core targeting dimension (high)
-- [ ] `/api/v1/features/feature-segments/` — lookup/join table linking already-synced features to already-synced segments (the segment overrides) (high)
+- [x] `/api/v1/environments/{environment_api_key}/identities/` — the end users flags are evaluated against; without them feature_states cannot be attributed to anyone (high)
+- [x] `/api/v1/environments/{environment_api_key}/identities/{identity_pk}/traits/` — identity traits, the attributes segments are defined on - the core targeting dimension (high)
+- [x] `/api/v1/features/feature-segments/` — lookup/join table linking already-synced features to already-synced segments (the segment overrides) (high)
- [ ] `/api/v1/projects/{project_pk}/features/{id}/evaluation-data/` — flag evaluation counts over time, Flagsmith's headline usage metric (high)
- [ ] `/api/v1/projects/{project_pk}/segments/{id}/members/` — segment membership rows resolving which identities fall into each synced segment (high)
-- [ ] `/api/v1/projects/{project_pk}/tags/` — lookup resolving the tag IDs carried on synced feature rows (high)
+- [x] `/api/v1/projects/{project_pk}/tags/` — lookup resolving the tag IDs carried on synced feature rows (high)
- [ ] `/api/v1/organisations/{organisation_pk}/usage-data/` — API request volume per organisation, needed for cost and adoption analysis (medium)
- [ ] `/api/v1/projects/{project_pk}/features/{feature_pk}/mv-options/` — multivariate variant definitions and weights behind multivariate feature states (medium)
- [ ] `/api/v1/environments/{environment_api_key}/identities/{identity_pk}/featurestates/` — per-identity flag overrides, distinct from the environment-level feature_states already synced (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/canonical_descriptions.py
index 7e602bb76d3d..38b8c017b071 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/canonical_descriptions.py
@@ -59,6 +59,22 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"_project_id": "ID of the parent project this row was fetched for (added by PostHog).",
},
},
+ "tags": {
+ "description": "Tags defined per project. Tags are applied to features, so this resolves the tag IDs carried on feature rows.",
+ "docs_url": "https://docs.flagsmith.com/basic-features/managing-features",
+ "columns": {
+ "id": "Unique identifier for the tag.",
+ "uuid": "Stable UUID for the tag.",
+ "label": "Display label of the tag.",
+ "color": "Hexadecimal value of the tag color.",
+ "description": "Human-readable description of the tag.",
+ "project": "ID of the project the tag belongs to.",
+ "is_permanent": "Whether features with this tag are excluded from stale flag detection.",
+ "is_system_tag": "Whether the tag was created by Flagsmith rather than a user.",
+ "type": "Identifier Flagsmith uses for tag business logic (NONE, STALE, GITHUB, UNHEALTHY or GITLAB).",
+ "_project_id": "ID of the parent project this row was fetched for (added by PostHog).",
+ },
+ },
"feature_states": {
"description": "The current state of every feature per environment: enabled/disabled plus the effective value, including segment overrides.",
"docs_url": "https://docs.flagsmith.com/basic-features/managing-features",
@@ -91,6 +107,47 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"_project_id": "ID of the parent project this row was fetched for (added by PostHog).",
},
},
+ "feature_segments": {
+ "description": "Segment overrides: one row per feature that a segment overrides within an environment, with the priority that decides which override wins.",
+ "docs_url": "https://docs.flagsmith.com/basic-features/segments",
+ "columns": {
+ "id": "Unique identifier for the segment override.",
+ "uuid": "Stable UUID for the segment override.",
+ "segment": "ID of the segment the override targets.",
+ "segment_name": "Display name of the segment the override targets.",
+ "environment": "ID of the environment the override applies in.",
+ "priority": "Order the override is evaluated in — lower values win.",
+ "is_feature_specific": "Whether the segment exists only for this feature rather than project-wide.",
+ "_environment_id": "ID of the environment this row was fetched for (added by PostHog).",
+ "_feature_id": "ID of the feature this override belongs to (added by PostHog).",
+ },
+ },
+ "identities": {
+ "description": "The end users flag evaluation runs against, listed per environment. An identity is created the first time your SDK evaluates flags for that user.",
+ "docs_url": "https://docs.flagsmith.com/basic-features/managing-identities",
+ "columns": {
+ "id": "Unique identifier for the identity.",
+ "identifier": "The identifier your SDK sends for this user.",
+ "environment": "ID of the environment the identity belongs to.",
+ "_environment_api_key": "API key of the parent environment this row was fetched for (added by PostHog).",
+ },
+ },
+ "identity_traits": {
+ "description": "Trait values stored against each identity. Traits are the attributes segment rules match on, so they are the targeting dimension behind segment overrides.",
+ "docs_url": "https://docs.flagsmith.com/basic-features/managing-identities#identity-traits",
+ "columns": {
+ "id": "Unique identifier for the trait value.",
+ "trait_key": "Name of the trait, as referenced by segment rules.",
+ "value_type": "Which of the typed value columns holds this trait's value.",
+ "string_value": "Trait value when the trait is a string.",
+ "integer_value": "Trait value when the trait is an integer.",
+ "float_value": "Trait value when the trait is a float.",
+ "boolean_value": "Trait value when the trait is a boolean.",
+ "created_date": "When the trait was first set for this identity.",
+ "_environment_api_key": "API key of the environment this row was fetched for (added by PostHog).",
+ "_identity_id": "ID of the identity the trait belongs to (added by PostHog).",
+ },
+ },
"audit_logs": {
"description": "Append-only audit history of changes across the organisation: who changed what, when. Retention on Flagsmith SaaS depends on your plan.",
"docs_url": "https://docs.flagsmith.com/system-administration/audit-logs",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/flagsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/flagsmith.py
index fca27dc6c4e2..4489ea85154f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/flagsmith.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/flagsmith.py
@@ -140,16 +140,34 @@ def _error_snippet(response: requests.Response) -> str:
return ""
[email protected](frozen=True)
class FlagsmithResumeConfig:
# Full URL of the next page to fetch ("" once a resource is exhausted).
next_url: str = ""
# For fan-out endpoints, the parent (organisation id, project id, or environment
# api_key) currently being paginated ("" for top-level endpoints or before the first
- # parent starts).
+ # parent starts). Two-level parents use ``FanoutParent.resume_key``.
parent_key: str = ""
[email protected](frozen=True)
+class FanoutParent:
+ """One fan-out parent: the identifiers substituted into a child endpoint's path or query.
+
+ ``child`` is empty for the single-level parents (organisation, project, environment) and
+ carries the inner identifier for the two-level ones (an identity id, or a feature id paired
+ with an environment id).
+ """
+
+ key: str
+ child: str = ""
+
+ @property
+ def resume_key(self) -> str:
+ # Identifiers are numeric ids or api_keys, so a "/" join stays unambiguous.
+ return f"{self.key}/{self.child}" if self.child else self.key
+
+
def normalize_base_url(base_url: str | None) -> str:
"""Normalize the (optional) instance URL and reject anything that isn't plain http(s).
@@ -317,13 +335,23 @@ def _iter_pages(
def _extend_capped(
- keys: list[str], listing: Iterator[list[dict[str, Any]]], field: str, logger: FilteringBoundLogger
+ keys: list[str],
+ listing: Iterator[list[dict[str, Any]]],
+ field: str,
+ logger: FilteringBoundLogger,
+ limit: int | None = None,
) -> bool:
"""Append ``row[field]`` from each row of a parent listing into ``keys``, stopping once the
- retained list hits MAX_FANOUT_PARENTS so a hostile host can't balloon it and exhaust worker
- memory. Keys longer than MAX_FANOUT_KEY_LENGTH are skipped so an oversized id/api_key can't
- balloon retained bytes or poison a child request URL. Returns True if the count cap was reached
- (the caller should stop enumerating)."""
+ retained list hits ``limit`` so a hostile host can't balloon it and exhaust worker memory. A
+ two-level enumeration passes the allowance left over from the outer level, so the cap bounds
+ the parents retained across the whole fan-out rather than per inner listing. Keys longer than
+ MAX_FANOUT_KEY_LENGTH are skipped so an oversized id/api_key can't balloon retained bytes or
+ poison a child request URL. Returns True if the count cap was reached (the caller should stop
+ enumerating)."""
+ # Resolved at call time, not bound as a default, so the module-level cap stays patchable.
+ limit = MAX_FANOUT_PARENTS if limit is None else limit
+ if limit <= 0:
+ return True
for rows in listing:
for row in rows:
key = str(row[field])
@@ -331,12 +359,87 @@ def _extend_capped(
logger.warning(f"Flagsmith: skipping fan-out parent with oversized {field} ({len(key)} chars)")
continue
keys.append(key)
- if len(keys) >= MAX_FANOUT_PARENTS:
+ if len(keys) >= limit:
logger.warning(f"Flagsmith: fan-out parent cap ({MAX_FANOUT_PARENTS}) reached, truncating enumeration")
return True
return False
+def _fetch_identity_parents(
+ session: requests.Session,
+ base: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ environment_keys: list[str],
+ budget: _PageBudget,
+) -> list[FanoutParent]:
+ """Pair every environment with each of its identities. Flagsmith has no bulk traits listing,
+ so a traits sync fans out once per identity and both caps apply: the shared page budget bounds
+ the requests and MAX_FANOUT_PARENTS the identities retained."""
+ parents: list[FanoutParent] = []
+ for environment_key in environment_keys:
+ listing = _iter_pages(
+ session,
+ base,
+ _initial_url(base, f"/environments/{environment_key}/identities/", {"page_size": 100}),
+ headers,
+ logger,
+ budget,
+ )
+ identity_ids: list[str] = []
+ capped = _extend_capped(identity_ids, listing, "id", logger, limit=MAX_FANOUT_PARENTS - len(parents))
+ parents.extend(FanoutParent(environment_key, identity_id) for identity_id in identity_ids)
+ if capped:
+ break
+ return parents
+
+
+def _fetch_environment_feature_parents(
+ session: requests.Session,
+ base: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ project_ids: list[str],
+ budget: _PageBudget,
+) -> list[FanoutParent]:
+ """Pair every environment with every feature of the same project. The feature-segments listing
+ requires both filters, and a pair only resolves within the project that owns them."""
+ parents: list[FanoutParent] = []
+ for project_id in project_ids:
+ environment_ids: list[str] = []
+ _extend_capped(
+ environment_ids,
+ _iter_pages(
+ session, base, _initial_url(base, f"/environments/?project={project_id}", {}), headers, logger, budget
+ ),
+ "id",
+ logger,
+ )
+ feature_ids: list[str] = []
+ _extend_capped(
+ feature_ids,
+ _iter_pages(
+ session,
+ base,
+ _initial_url(base, f"/projects/{project_id}/features/", {"page_size": 100}),
+ headers,
+ logger,
+ budget,
+ ),
+ "id",
+ logger,
+ )
+ for environment_id in environment_ids:
+ for feature_id in feature_ids:
+ if len(parents) >= MAX_FANOUT_PARENTS:
+ logger.warning(
+ f"Flagsmith: fan-out parent cap ({MAX_FANOUT_PARENTS}) reached, truncating enumeration"
+ )
+ return parents
+ parents.append(FanoutParent(environment_id, feature_id))
+ return parents
+
+
def _fetch_parent_keys(
session: requests.Session,
base: str,
@@ -344,18 +447,21 @@ def _fetch_parent_keys(
logger: FilteringBoundLogger,
parent: ParentResource,
budget: _PageBudget,
-) -> list[str]:
+) -> list[FanoutParent]:
if parent == "organisation":
listing = _iter_pages(session, base, _initial_url(base, "/organisations/", {}), headers, logger, budget)
org_ids: list[str] = []
_extend_capped(org_ids, listing, "id", logger)
- return org_ids
+ return [FanoutParent(org_id) for org_id in org_ids]
project_listing = _iter_pages(session, base, _initial_url(base, "/projects/", {}), headers, logger, budget)
project_ids: list[str] = []
_extend_capped(project_ids, project_listing, "id", logger)
if parent == "project":
- return project_ids
+ return [FanoutParent(project_id) for project_id in project_ids]
+
+ if parent == "environment_feature":
+ return _fetch_environment_feature_parents(session, base, headers, logger, project_ids, budget)
# Environments are addressed by their (non-secret, client-side) api_key and listed
# per project; keep API order so the resume bookmark resolves deterministically.
@@ -366,7 +472,10 @@ def _fetch_parent_keys(
)
if _extend_capped(keys, env_listing, "api_key", logger):
break
- return keys
+ if parent == "environment":
+ return [FanoutParent(key) for key in keys]
+
+ return _fetch_identity_parents(session, base, headers, logger, keys, budget)
def _paginate_resource(
@@ -376,8 +485,9 @@ def _paginate_resource(
headers: dict[str, str],
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[FlagsmithResumeConfig],
- parent_key: str,
+ parent: FanoutParent,
parent_field: str | None,
+ child_field: str | None,
budget: _PageBudget,
) -> Iterator[list[dict[str, Any]]]:
url: str | None = start_url
@@ -386,21 +496,25 @@ def _paginate_resource(
logger.warning(f"Flagsmith: sync page budget ({MAX_PAGES_PER_SYNC}) exhausted at {start_url}, truncating")
# Terminal resume state so a resume advances past this parent instead of re-entering
# the same (possibly cyclic) chain and re-spending the budget on it.
- resumable_source_manager.save_state(FlagsmithResumeConfig(next_url="", parent_key=parent_key))
+ resumable_source_manager.save_state(FlagsmithResumeConfig(next_url="", parent_key=parent.resume_key))
return
data = _fetch_page(session, url, headers, logger)
rows, next_url = _extract_rows(base, data)
- if parent_field:
- for row in rows:
- row[parent_field] = parent_key
+ for row in rows:
+ if parent_field:
+ row[parent_field] = parent.key
+ if child_field:
+ row[child_field] = parent.child
if rows:
yield rows
# Save state AFTER yielding so a heartbeat-timeout crash re-fetches from the next
# page rather than re-emitting the page we just yielded (merge dedupes regardless).
- resumable_source_manager.save_state(FlagsmithResumeConfig(next_url=next_url or "", parent_key=parent_key))
+ resumable_source_manager.save_state(
+ FlagsmithResumeConfig(next_url=next_url or "", parent_key=parent.resume_key)
+ )
url = next_url
@@ -422,8 +536,9 @@ def _get_fan_out_rows(
start_idx = 0
resume_url: str | None = None
- if resume is not None and resume.parent_key and resume.parent_key in parent_keys:
- idx = parent_keys.index(resume.parent_key)
+ resume_keys = [parent.resume_key for parent in parent_keys]
+ if resume is not None and resume.parent_key and resume.parent_key in resume_keys:
+ idx = resume_keys.index(resume.parent_key)
if resume.next_url:
# Mid-parent: pick up at the saved page within that parent. Re-pin onto the current base
# so a stale URL from a since-retargeted source can't send the current API key to the
@@ -435,13 +550,22 @@ def _get_fan_out_rows(
start_idx = idx + 1
for i in range(start_idx, len(parent_keys)):
- parent_key = parent_keys[i]
+ parent = parent_keys[i]
if i == start_idx and resume_url:
start_url = resume_url
else:
- start_url = _initial_url(base, config.path.format(parent=parent_key), config.params)
+ start_url = _initial_url(base, config.path.format(parent=parent.key, child=parent.child), config.params)
yield from _paginate_resource(
- session, base, start_url, headers, logger, resumable_source_manager, parent_key, config.parent_field, budget
+ session,
+ base,
+ start_url,
+ headers,
+ logger,
+ resumable_source_manager,
+ parent,
+ config.parent_field,
+ config.child_field,
+ budget,
)
@@ -487,8 +611,9 @@ def get_rows(
headers,
logger,
resumable_source_manager,
- parent_key="",
+ parent=FanoutParent(""),
parent_field=None,
+ child_field=None,
budget=budget,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/settings.py
index 57e454f77bbc..6303062c8c4c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/settings.py
@@ -4,22 +4,27 @@ from typing import Any, Literal
from products.warehouse_sources.backend.types import IncrementalField
# Which root listing a fan-out endpoint enumerates its parents from. Environments are
-# discovered project-by-project, so their prerequisite is the projects listing.
-ParentResource = Literal["organisation", "project", "environment"]
+# discovered project-by-project, so their prerequisite is the projects listing. The last two are
+# two-level parents: identities are listed per environment, and the feature-segments listing needs
+# an environment and a feature together, both enumerated per project.
+ParentResource = Literal["organisation", "project", "environment", "identity", "environment_feature"]
-@dataclass
+@dataclass(frozen=True)
class FlagsmithEndpointConfig:
name: str
# Path under ``/api/v1``. A ``{parent}`` placeholder marks a fan-out endpoint queried
- # once per parent resource (organisation id, project id, or environment api_key). The
- # path may carry its own query string (e.g. the environments listing filter).
+ # once per parent resource (organisation id, project id, or environment api_key), and a
+ # ``{child}`` placeholder the inner identifier of a two-level parent. The path may carry
+ # its own query string (e.g. the environments listing filter).
path: str
primary_keys: list[str]
parent: ParentResource | None = None
# Row field the parent identifier is injected into, so a single table stays meaningful
# (and uniquely keyed) across parents whose rows don't carry the parent id themselves.
parent_field: str | None = None
+ # Same, for the inner identifier of a two-level parent (the ``{child}`` path placeholder).
+ child_field: str | None = None
# Static query params for the initial request. Only endpoints whose OpenAPI spec
# documents ``page_size`` get one — DRF silently ignores it elsewhere, so don't imply it.
params: dict[str, Any] = field(default_factory=dict)
@@ -62,6 +67,14 @@ FLAGSMITH_ENDPOINTS: dict[str, FlagsmithEndpointConfig] = {
params={"page_size": 100, "sort_field": "created_date", "sort_direction": "ASC"},
partition_key="created_date",
),
+ # Project-level tag lookup resolving the tag ids carried on feature rows.
+ "tags": FlagsmithEndpointConfig(
+ name="tags",
+ path="/projects/{parent}/tags/",
+ primary_keys=["id"],
+ parent="project",
+ parent_field="_project_id",
+ ),
# Current flag values per environment (environment defaults and segment overrides).
"feature_states": FlagsmithEndpointConfig(
name="feature_states",
@@ -80,6 +93,39 @@ FLAGSMITH_ENDPOINTS: dict[str, FlagsmithEndpointConfig] = {
params={"page_size": 100},
partition_key="created_at",
),
+ # Segment overrides: the join rows tying a feature to a segment within one environment. The
+ # listing requires both an environment id and a feature id, so the fan-out walks every valid
+ # pair within each project.
+ "feature_segments": FlagsmithEndpointConfig(
+ name="feature_segments",
+ path="/features/feature-segments/?environment={parent}&feature={child}",
+ primary_keys=["id"],
+ parent="environment_feature",
+ parent_field="_environment_id",
+ # The response carries the segment and environment but not the feature it overrides.
+ child_field="_feature_id",
+ ),
+ # The end users flags are evaluated against, listed per environment.
+ "identities": FlagsmithEndpointConfig(
+ name="identities",
+ path="/environments/{parent}/identities/",
+ primary_keys=["id"],
+ parent="environment",
+ parent_field="_environment_api_key",
+ params={"page_size": 100},
+ ),
+ # Trait values per identity — the attributes segment rules match on. Flagsmith exposes no bulk
+ # traits listing, so this costs at least one request per identity and is bounded by the shared
+ # page budget on very large environments.
+ "identity_traits": FlagsmithEndpointConfig(
+ name="identity_traits",
+ path="/environments/{parent}/identities/{child}/traits/",
+ primary_keys=["id"],
+ parent="identity",
+ parent_field="_environment_api_key",
+ child_field="_identity_id",
+ partition_key="created_date",
+ ),
# Append-only change history for the organisation. Retention on Flagsmith SaaS is
# plan-gated, so the table reflects the currently retained window.
"audit_logs": FlagsmithEndpointConfig(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/source.py
index 3fcf9d8b9c9b..91d4bf7d1729 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/source.py
@@ -41,6 +41,8 @@ _PARENT_PROBE_PATHS = {
"organisation": "/organisations/",
"project": "/projects/",
"environment": "/projects/",
+ "identity": "/projects/",
+ "environment_feature": "/projects/",
}
@@ -65,7 +67,7 @@ class FlagsmithSource(ResumableSource[FlagsmithSourceConfig, FlagsmithResumeConf
keywords=["feature flags", "remote config"],
label="Flagsmith",
releaseStatus=ReleaseStatus.ALPHA,
- caption="""Enter your Flagsmith organisation API key to pull your projects, environments, feature flags, flag states, segments, and audit log into the PostHog Data warehouse.
+ caption="""Enter your Flagsmith organisation API key to pull your projects, environments, feature flags, flag states, segments, identities, and audit log into the PostHog Data warehouse.
Create an organisation API key under **Organisation Settings > API Keys** in your Flagsmith dashboard. Note that organisation API keys grant admin access to every project in the organisation, so store them carefully.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith.py
index f00716e5c0e6..5e70638d0d60 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith.py
@@ -405,6 +405,117 @@ class TestGetRowsFanout:
]
+class TestGetRowsTwoLevelFanout:
+ # Identity traits and feature segments need two identifiers per request, so their parent
+ # enumeration walks a second level and both identifiers are injected into each row.
+
+ @staticmethod
+ def _identity_dispatch() -> Any:
+ def _get(url, **kwargs):
+ if url.endswith("/projects/"):
+ return _resp([{"id": 1}])
+ if "/environments/?project=" in url:
+ return _resp(_page([{"id": 10, "api_key": "env-a"}], None))
+ if url.endswith("/identities/?page_size=100"):
+ return _resp(_page([{"id": 500}, {"id": 501}], None))
+ identity_id = url.split("/identities/")[1].split("/")[0]
+ return _resp(_page([{"id": 9000 + int(identity_id), "trait_key": "plan"}], None))
+
+ return _get
+
+ @mock.patch(SESSION_PATH)
+ def test_traits_fan_out_per_identity(self, mock_session):
+ mock_session.return_value.get.side_effect = self._identity_dispatch()
+
+ batches = list(get_rows("key", None, "identity_traits", mock.MagicMock(), _make_manager()))
+
+ assert [row for batch in batches for row in batch] == [
+ {"id": 9500, "trait_key": "plan", "_environment_api_key": "env-a", "_identity_id": "500"},
+ {"id": 9501, "trait_key": "plan", "_environment_api_key": "env-a", "_identity_id": "501"},
+ ]
+ urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if c.args[0].endswith("/traits/")]
+ assert urls == [
+ f"{API_BASE}/environments/env-a/identities/500/traits/",
+ f"{API_BASE}/environments/env-a/identities/501/traits/",
+ ]
+
+ @mock.patch(SESSION_PATH)
+ def test_traits_resume_key_identifies_the_inner_parent(self, mock_session):
+ # The resume bookmark has to name the environment AND the identity, or a resume would
+ # restart at the wrong identity (or the whole environment).
+ mock_session.return_value.get.side_effect = self._identity_dispatch()
+ manager = _make_manager()
+
+ list(get_rows("key", None, "identity_traits", mock.MagicMock(), manager))
+ saved = [call.args[0].parent_key for call in manager.save_state.call_args_list]
+ assert saved == ["env-a/500", "env-a/501"]
+
+ mock_session.return_value.get.side_effect = self._identity_dispatch()
+ resumed = _make_manager(FlagsmithResumeConfig(next_url="", parent_key="env-a/500"))
+ batches = list(get_rows("key", None, "identity_traits", mock.MagicMock(), resumed))
+
+ assert [row["_identity_id"] for batch in batches for row in batch] == ["501"]
+
+ @mock.patch(PARENTS_PATH, 2)
+ @mock.patch(SESSION_PATH)
+ def test_identity_parent_cap_spans_environments(self, mock_session):
+ # The cap bounds the identities retained across the whole fan-out; applied per environment
+ # it would let the retained list grow with the environment count.
+ def _get(url, **kwargs):
+ if url.endswith("/projects/"):
+ return _resp([{"id": 1}])
+ if "/environments/?project=" in url:
+ return _resp(_page([{"id": 10, "api_key": "env-a"}, {"id": 11, "api_key": "env-b"}], None))
+ if url.endswith("/identities/?page_size=100"):
+ return _resp(_page([{"id": 500}, {"id": 501}], None))
+ return _resp(_page([{"id": 9000}], None))
+
+ mock_session.return_value.get.side_effect = _get
+
+ list(get_rows("key", None, "identity_traits", mock.MagicMock(), _make_manager()))
+
+ trait_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if c.args[0].endswith("/traits/")]
+ assert trait_urls == [
+ f"{API_BASE}/environments/env-a/identities/500/traits/",
+ f"{API_BASE}/environments/env-a/identities/501/traits/",
+ ]
+
+ @mock.patch(SESSION_PATH)
+ def test_feature_segments_pair_environments_with_features(self, mock_session):
+ # The listing requires both filters, and a pair only resolves inside the project that owns
+ # both, so the cross product is built per project rather than globally.
+ def _get(url, **kwargs):
+ if url.endswith("/projects/"):
+ return _resp([{"id": 1}, {"id": 2}])
+ if "/environments/?project=1" in url:
+ return _resp(_page([{"id": 10}, {"id": 11}], None))
+ if "/environments/?project=2" in url:
+ return _resp(_page([{"id": 20}], None))
+ if "/projects/1/features/" in url:
+ return _resp(_page([{"id": 100}], None))
+ if "/projects/2/features/" in url:
+ return _resp(_page([{"id": 200}], None))
+ return _resp(_page([{"id": 7, "segment": 3}], None))
+
+ mock_session.return_value.get.side_effect = _get
+
+ batches = list(get_rows("key", None, "feature_segments", mock.MagicMock(), _make_manager()))
+
+ assert [row for batch in batches for row in batch] == [
+ {"id": 7, "segment": 3, "_environment_id": "10", "_feature_id": "100"},
+ {"id": 7, "segment": 3, "_environment_id": "11", "_feature_id": "100"},
+ {"id": 7, "segment": 3, "_environment_id": "20", "_feature_id": "200"},
+ ]
+ pair_urls = [
+ c.args[0] for c in mock_session.return_value.get.call_args_list if "/feature-segments/" in c.args[0]
+ ]
+ assert pair_urls == [
+ f"{API_BASE}/features/feature-segments/?environment=10&feature=100",
+ f"{API_BASE}/features/feature-segments/?environment=11&feature=100",
+ f"{API_BASE}/features/feature-segments/?environment=20&feature=200",
+ ]
+
+
class TestErrors:
@mock.patch(SESSION_PATH)
def test_4xx_raises(self, mock_session):
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith_source.py
index 1b86ac1257b1..9d271649b05f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/flagsmith/tests/test_flagsmith_source.py
@@ -72,6 +72,14 @@ class TestFlagsmithSource:
self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
assert mock_validate.call_args.args[2] == expected_path
+ @pytest.mark.parametrize("schema_name", list(ENDPOINTS))
+ @mock.patch(VALIDATE_PATH)
+ def test_validate_credentials_resolves_a_probe_path_for_every_endpoint(self, mock_validate, schema_name):
+ # A fan-out parent with no probe path raises instead of validating the schema.
+ mock_validate.return_value = 200
+ is_valid, _error = self.source.validate_credentials(self.config, self.team_id, schema_name=schema_name)
+ assert is_valid is True
+
@mock.patch(VALIDATE_PATH)
def test_validate_credentials_rejects_invalid_base_url(self, mock_validate):
config = FlagsmithSourceConfig(api_key="org-key", base_url="https://[email protected]")