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(data-warehouse): add four Flagsmith tables for uncovered endpoints (#107706)

Tom Owers8e855f2bd2e7
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 af1643af4424..bde2c3dffb65 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
@@ -3206,15 +3206,15 @@ Diffed against: <https://api.flagsmith.com/api/v1/swagger.json>
- [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)
+- [x] `/api/v1/projects/{project_pk}/features/{id}/evaluation-data/` — flag evaluation counts over time, Flagsmith's headline usage metric (high)
+- [x] `/api/v1/projects/{project_pk}/segments/{id}/members/` — segment membership rows resolving which identities fall into each synced segment (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)
-- [ ] `/api/v1/environments/{environment_pk}/features/{feature_pk}/versions/` — environment feature version history - the state-change trail for a flag in an environment (medium)
+- [x] `/api/v1/environments/{environment_pk}/features/{feature_pk}/versions/` — environment feature version history - the state-change trail for a flag in an environment (medium)
- [ ] `/api/v1/projects/{project_pk}/change-requests/ (and the environment list-change-requests)` — flag change approval workflow records, showing who requested and approved each change (medium)
-- [ ] `/api/v1/organisations/{organisation_pk}/groups/` — user group membership lookup resolving the groups referenced on feature owners and permissions (medium)
+- [x] `/api/v1/organisations/{organisation_pk}/groups/` — user group membership lookup resolving the groups referenced on feature owners and permissions (medium)
Note: Spec is the live Flagsmith SaaS swagger (325 paths). Roles, permissions, SAML/SCIM, integrations and master API keys are excluded as access-control and plumbing config.
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 38b8c017b071..4578f882ab82 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,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"_project_id": "ID of the parent project this row was fetched for (added by PostHog).",
},
},
+ "evaluation_data": {
+ "description": "Daily flag evaluation counts per feature and environment, Flagsmith's core usage metric. Each sync refreshes a rolling 30-day window, so the table accumulates history over time.",
+ "docs_url": "https://docs.flagsmith.com/advanced-use/flag-analytics",
+ "columns": {
+ "day": "The day the evaluations were counted on.",
+ "count": "Number of times the feature was evaluated that day.",
+ "labels": "Client application name, version and user agent the count is broken down by, when a breakdown applies.",
+ "_project_id": "ID of the parent project this row was fetched for (added by PostHog).",
+ "_feature_id": "ID of the feature the evaluations were counted for (added by PostHog).",
+ "_environment_id": "ID of the environment the evaluations were counted in (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",
@@ -92,6 +104,23 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"_environment_api_key": "API key of the parent environment this row was fetched for (added by PostHog).",
},
},
+ "environment_feature_versions": {
+ "description": "Version history of a feature in one environment: the state-change trail behind its current feature states. Only environments that use v2 feature versioning have versions.",
+ "docs_url": "https://docs.flagsmith.com/advanced-use/feature-versioning",
+ "columns": {
+ "uuid": "Stable UUID for the version.",
+ "created_at": "When the version was created.",
+ "updated_at": "When the version was last changed.",
+ "published": "Whether the version has been published.",
+ "published_by": "ID of the user who published the version.",
+ "created_by": "ID of the user who created the version.",
+ "live_from": "When the version started serving traffic.",
+ "is_live": "Whether the version is the one currently serving traffic.",
+ "description": "Optional description of what the version changed.",
+ "_environment_id": "ID of the environment the version belongs to (added by PostHog).",
+ "_feature_id": "ID of the feature the version belongs to (added by PostHog).",
+ },
+ },
"segments": {
"description": "User segments per project — rule-based groups of identities used to target feature overrides.",
"docs_url": "https://docs.flagsmith.com/basic-features/segments",
@@ -107,6 +136,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"_project_id": "ID of the parent project this row was fetched for (added by PostHog).",
},
},
+ "segment_members": {
+ "description": "Which identities fall into each segment, resolved per environment. Segment rules are matched against an environment's identities, so membership is listed one environment at a time.",
+ "docs_url": "https://docs.flagsmith.com/basic-features/segments",
+ "columns": {
+ "identifier": "The identifier the end user is known by in Flagsmith.",
+ "identity_key": "Key uniquely identifying the identity within its environment.",
+ "traits": "Trait values the identity matched the segment rules on.",
+ "_project_id": "ID of the parent project this row was fetched for (added by PostHog).",
+ "_segment_id": "ID of the segment the identity belongs to (added by PostHog).",
+ "_environment_id": "ID of the environment membership was resolved in (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",
@@ -177,4 +218,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"_organisation_id": "ID of the parent organisation this row was fetched for (added by PostHog).",
},
},
+ "groups": {
+ "description": "Permission groups in the organisation, resolving the group IDs referenced by feature owners and permission assignments.",
+ "docs_url": "https://docs.flagsmith.com/system-administration/rbac",
+ "columns": {
+ "id": "Unique identifier for the group.",
+ "name": "Display name of the group.",
+ "users": "Members of the group and whether each is a group admin.",
+ "is_default": "Whether new organisation members are added to this group automatically.",
+ "external_id": "ID of the group in an external system, when the group is managed there.",
+ "_organisation_id": "ID of the parent organisation this row was fetched for (added by PostHog).",
+ },
+ },
}
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 4489ea85154f..c1201a95df1f 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
@@ -1,9 +1,9 @@
import json
import threading
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from typing import Any
-from urllib.parse import urlencode, urlparse
+from urllib.parse import parse_qsl, urlencode, urlparse
import requests
from structlog.types import FilteringBoundLogger
@@ -156,16 +156,18 @@ class FanoutParent:
``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).
+ with an environment id). ``extra`` carries the third identifier of a three-level parent (an
+ environment paired with a project and a resource inside it).
"""
key: str
child: str = ""
+ extra: 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
+ return "/".join(part for part in (self.key, self.child, self.extra) if part)
def normalize_base_url(base_url: str | None) -> str:
@@ -239,14 +241,32 @@ def _pinned_next_url(base: str, next_link: Any) -> str | None:
return f"{base}{parsed.path}{query}"
-def _extract_rows(base: str, data: Any) -> tuple[list[dict[str, Any]], str | None]:
- """Rows + next-page URL from a response body: either a DRF pagination envelope
- (``{count, next, previous, results}``) or a plain JSON array (projects, users)."""
+def _cursor_next_url(base: str, current_url: str, cursor: Any) -> str | None:
+ """Next-page URL for a listing that returns an opaque body cursor instead of a ``next`` link.
+
+ The next request repeats the current one with ``cursor`` replaced, rebuilt onto the configured
+ base for the same host-pinning reason as ``_pinned_next_url``.
+ """
+ if not cursor or not isinstance(cursor, str):
+ return None
+ parsed = urlparse(current_url)
+ query = [(key, value) for key, value in parse_qsl(parsed.query) if key != "cursor"]
+ query.append(("cursor", cursor))
+ return f"{base}{parsed.path}?{urlencode(query)}"
+
+
+def _extract_rows(base: str, data: Any, current_url: str) -> tuple[list[dict[str, Any]], str | None]:
+ """Rows + next-page URL from a response body: a DRF pagination envelope
+ (``{count, next, previous, results}``), a cursor envelope (``{results, next_cursor}``), or a
+ plain JSON array (projects, users, evaluation data)."""
if isinstance(data, list):
return [row for row in data if isinstance(row, dict)], None
if isinstance(data, dict):
rows = [row for row in data.get("results") or [] if isinstance(row, dict)]
- return rows, _pinned_next_url(base, data.get("next"))
+ next_url = _pinned_next_url(base, data.get("next")) or _cursor_next_url(
+ base, current_url, data.get("next_cursor")
+ )
+ return rows, next_url
return [], None
@@ -329,7 +349,7 @@ def _iter_pages(
logger.warning(f"Flagsmith: sync page budget ({MAX_PAGES_PER_SYNC}) exhausted at {start_url}, truncating")
return
data = _fetch_page(session, url, headers, logger)
- rows, url = _extract_rows(base, data)
+ rows, url = _extract_rows(base, data, url)
if rows:
yield rows
@@ -340,20 +360,23 @@ def _extend_capped(
field: str,
logger: FilteringBoundLogger,
limit: int | None = None,
+ predicate: Callable[[dict[str, Any]], bool] | None = None,
) -> bool:
"""Append ``row[field]`` from each row of a parent listing into ``keys``, stopping once the
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)."""
+ poison a child request URL. ``predicate`` drops parents whose child endpoint would not serve
+ them. 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:
+ if predicate is not None and not predicate(row):
+ continue
key = str(row[field])
if len(key) > MAX_FANOUT_KEY_LENGTH:
logger.warning(f"Flagsmith: skipping fan-out parent with oversized {field} ({len(key)} chars)")
@@ -394,6 +417,10 @@ def _fetch_identity_parents(
return parents
+def _uses_v2_versioning(environment: dict[str, Any]) -> bool:
+ return bool(environment.get("use_v2_feature_versioning"))
+
+
def _fetch_environment_feature_parents(
session: requests.Session,
base: str,
@@ -401,9 +428,13 @@ def _fetch_environment_feature_parents(
logger: FilteringBoundLogger,
project_ids: list[str],
budget: _PageBudget,
+ require_v2_versioning: bool = False,
) -> 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."""
+ """Pair every environment with every feature of the same project. The feature-segments and
+ version listings require both filters, and a pair only resolves within the project that owns
+ them. ``require_v2_versioning`` keeps only the environments whose version listing exists,
+ because Flagsmith rejects the request outright on an environment still using unversioned
+ feature states."""
parents: list[FanoutParent] = []
for project_id in project_ids:
environment_ids: list[str] = []
@@ -414,6 +445,7 @@ def _fetch_environment_feature_parents(
),
"id",
logger,
+ predicate=_uses_v2_versioning if require_v2_versioning else None,
)
feature_ids: list[str] = []
_extend_capped(
@@ -440,6 +472,54 @@ def _fetch_environment_feature_parents(
return parents
+def _fetch_project_resource_environment_parents(
+ session: requests.Session,
+ base: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ project_ids: list[str],
+ budget: _PageBudget,
+ resource_path: str,
+) -> list[FanoutParent]:
+ """Build the (project, project resource, environment) triples the evaluation-data and
+ segment-members listings need: the project and the resource sit in the path, the environment
+ is a required query filter, and a triple only resolves within the project that owns it."""
+ 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,
+ )
+ resource_ids: list[str] = []
+ _extend_capped(
+ resource_ids,
+ _iter_pages(
+ session,
+ base,
+ _initial_url(base, resource_path.format(project=project_id), {"page_size": 100}),
+ headers,
+ logger,
+ budget,
+ ),
+ "id",
+ logger,
+ )
+ for resource_id in resource_ids:
+ for environment_id in environment_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(project_id, resource_id, environment_id))
+ return parents
+
+
def _fetch_parent_keys(
session: requests.Session,
base: str,
@@ -463,6 +543,21 @@ def _fetch_parent_keys(
if parent == "environment_feature":
return _fetch_environment_feature_parents(session, base, headers, logger, project_ids, budget)
+ if parent == "versioned_environment_feature":
+ return _fetch_environment_feature_parents(
+ session, base, headers, logger, project_ids, budget, require_v2_versioning=True
+ )
+
+ if parent == "project_feature_environment":
+ return _fetch_project_resource_environment_parents(
+ session, base, headers, logger, project_ids, budget, "/projects/{project}/features/"
+ )
+
+ if parent == "project_segment_environment":
+ return _fetch_project_resource_environment_parents(
+ session, base, headers, logger, project_ids, budget, "/projects/{project}/segments/"
+ )
+
# Environments are addressed by their (non-secret, client-side) api_key and listed
# per project; keep API order so the resume bookmark resolves deterministically.
keys: list[str] = []
@@ -488,6 +583,7 @@ def _paginate_resource(
parent: FanoutParent,
parent_field: str | None,
child_field: str | None,
+ extra_field: str | None,
budget: _PageBudget,
) -> Iterator[list[dict[str, Any]]]:
url: str | None = start_url
@@ -499,13 +595,15 @@ def _paginate_resource(
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)
+ rows, next_url = _extract_rows(base, data, url)
for row in rows:
if parent_field:
row[parent_field] = parent.key
if child_field:
row[child_field] = parent.child
+ if extra_field:
+ row[extra_field] = parent.extra
if rows:
yield rows
@@ -554,7 +652,11 @@ def _get_fan_out_rows(
if i == start_idx and resume_url:
start_url = resume_url
else:
- start_url = _initial_url(base, config.path.format(parent=parent.key, child=parent.child), config.params)
+ start_url = _initial_url(
+ base,
+ config.path.format(parent=parent.key, child=parent.child, extra=parent.extra),
+ config.params,
+ )
yield from _paginate_resource(
session,
base,
@@ -565,6 +667,7 @@ def _get_fan_out_rows(
parent,
config.parent_field,
config.child_field,
+ config.extra_field,
budget,
)
@@ -614,6 +717,7 @@ def get_rows(
parent=FanoutParent(""),
parent_field=None,
child_field=None,
+ extra_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 6303062c8c4c..2f63cd7d8aa3 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,19 +4,32 @@ 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. 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"]
+# discovered project-by-project, so their prerequisite is the projects listing. The rest are
+# multi-level parents: identities are listed per environment; the feature-segments and version
+# listings need an environment and a feature together, both enumerated per project (the versioned
+# variant keeps only the environments that run v2 feature versioning, the only ones that serve a
+# version listing); and the last two need three identifiers, a project plus a resource inside it
+# plus an environment.
+ParentResource = Literal[
+ "organisation",
+ "project",
+ "environment",
+ "identity",
+ "environment_feature",
+ "versioned_environment_feature",
+ "project_feature_environment",
+ "project_segment_environment",
+]
@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), 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).
+ # once per parent resource (organisation id, project id, or environment api_key), a
+ # ``{child}`` placeholder the inner identifier of a two-level parent, and ``{extra}`` the
+ # third identifier of a three-level one. The path may carry its own query string (e.g. the
+ # environments listing filter).
path: str
primary_keys: list[str]
parent: ParentResource | None = None
@@ -25,8 +38,11 @@ class FlagsmithEndpointConfig:
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.
+ # Same, for the third identifier of a three-level parent (the ``{extra}`` path placeholder).
+ extra_field: str | None = None
+ # Static query params for the initial request. Only params the endpoint's OpenAPI spec
+ # documents get one (page size, cursor limit, lookback window), because DRF silently
+ # ignores anything else and adding one would imply support for it.
params: dict[str, Any] = field(default_factory=dict)
# A STABLE datetime field to partition by — never one that mutates on update.
partition_key: str | None = None
@@ -67,6 +83,25 @@ FLAGSMITH_ENDPOINTS: dict[str, FlagsmithEndpointConfig] = {
params={"page_size": 100, "sort_field": "created_date", "sort_direction": "ASC"},
partition_key="created_date",
),
+ # Daily evaluation counts per feature per environment, Flagsmith's headline usage metric.
+ # ``environment_id`` is a required filter, so the fan-out needs the project, the feature and
+ # an environment of that project together. ``period`` is a rolling window of days back from
+ # now, so a sync refreshes the recent window and merge accumulates the history over time.
+ # The published spec types the 200 body as a single object, but the endpoint returns the
+ # series as a plain JSON array (one entry per day).
+ "evaluation_data": FlagsmithEndpointConfig(
+ name="evaluation_data",
+ path="/projects/{parent}/features/{child}/evaluation-data/?environment_id={extra}",
+ # Rows carry no id of their own. The grain is one feature/environment/day because we
+ # pass no client-application or user-agent filter, so the counts arrive aggregated.
+ primary_keys=["_feature_id", "_environment_id", "day"],
+ parent="project_feature_environment",
+ parent_field="_project_id",
+ child_field="_feature_id",
+ extra_field="_environment_id",
+ params={"period": 30},
+ partition_key="day",
+ ),
# Project-level tag lookup resolving the tag ids carried on feature rows.
"tags": FlagsmithEndpointConfig(
name="tags",
@@ -84,6 +119,20 @@ FLAGSMITH_ENDPOINTS: dict[str, FlagsmithEndpointConfig] = {
parent_field="_environment_api_key",
partition_key="created_at",
),
+ # Version history of a feature in one environment: the state-change trail behind the current
+ # feature_states rows. Only environments on v2 feature versioning serve this listing, so the
+ # parent enumeration filters the rest out rather than letting them fail the sync.
+ "environment_feature_versions": FlagsmithEndpointConfig(
+ name="environment_feature_versions",
+ path="/environments/{parent}/features/{child}/versions/",
+ # Versions expose a uuid rather than an id, and it is unique across environments.
+ primary_keys=["uuid"],
+ parent="versioned_environment_feature",
+ parent_field="_environment_id",
+ child_field="_feature_id",
+ params={"page_size": 100},
+ partition_key="created_at",
+ ),
"segments": FlagsmithEndpointConfig(
name="segments",
path="/projects/{parent}/segments/",
@@ -93,6 +142,19 @@ FLAGSMITH_ENDPOINTS: dict[str, FlagsmithEndpointConfig] = {
params={"page_size": 100},
partition_key="created_at",
),
+ # Which identities fall into each segment, resolved per environment because segment rules are
+ # evaluated against an environment's identities. Pages with an opaque body cursor.
+ "segment_members": FlagsmithEndpointConfig(
+ name="segment_members",
+ path="/projects/{parent}/segments/{child}/members/?environment={extra}",
+ # Rows carry no id; an identity_key is unique within its environment.
+ primary_keys=["_segment_id", "_environment_id", "identity_key"],
+ parent="project_segment_environment",
+ parent_field="_project_id",
+ child_field="_segment_id",
+ extra_field="_environment_id",
+ params={"limit": 100},
+ ),
# 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.
@@ -146,6 +208,15 @@ FLAGSMITH_ENDPOINTS: dict[str, FlagsmithEndpointConfig] = {
parent="organisation",
parent_field="_organisation_id",
),
+ # Permission groups, resolving the group ids referenced by feature owners and permissions.
+ # Each group belongs to exactly one organisation, so its id alone keys the table.
+ "groups": FlagsmithEndpointConfig(
+ name="groups",
+ path="/organisations/{parent}/groups/",
+ primary_keys=["id"],
+ parent="organisation",
+ parent_field="_organisation_id",
+ ),
}
ENDPOINTS = tuple(FLAGSMITH_ENDPOINTS.keys())
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 91d4bf7d1729..5fe2506ddc4f 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
@@ -43,6 +43,9 @@ _PARENT_PROBE_PATHS = {
"environment": "/projects/",
"identity": "/projects/",
"environment_feature": "/projects/",
+ "versioned_environment_feature": "/projects/",
+ "project_feature_environment": "/projects/",
+ "project_segment_environment": "/projects/",
}
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 5e70638d0d60..cae0986f42b5 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
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.flagsmith.
FlagsmithResponseTimeoutError,
FlagsmithResponseTooLargeError,
FlagsmithResumeConfig,
+ _cursor_next_url,
_initial_url,
_pinned_next_url,
_read_bounded,
@@ -118,6 +119,33 @@ class TestUrlHelpers:
url = _initial_url(DEFAULT_BASE_URL, "/environments/?project=1", {"page_size": 100})
assert url == f"{API_BASE}/environments/?project=1&page_size=100"
+ @pytest.mark.parametrize(
+ "current_url, cursor, expected",
+ [
+ (
+ f"{API_BASE}/projects/1/segments/3/members/?environment=10&limit=100",
+ "abc",
+ f"{API_BASE}/projects/1/segments/3/members/?environment=10&limit=100&cursor=abc",
+ ),
+ # A cursor already on the URL is replaced, not appended a second time.
+ (
+ f"{API_BASE}/projects/1/segments/3/members/?limit=100&cursor=old",
+ "new",
+ f"{API_BASE}/projects/1/segments/3/members/?limit=100&cursor=new",
+ ),
+ # A cursor page is pinned onto the configured base, like a DRF next link.
+ (
+ "https://evil.example.com/api/v1/projects/1/segments/3/members/?limit=100",
+ "abc",
+ f"{API_BASE}/projects/1/segments/3/members/?limit=100&cursor=abc",
+ ),
+ (f"{API_BASE}/projects/1/segments/3/members/?limit=100", None, None),
+ (f"{API_BASE}/projects/1/segments/3/members/?limit=100", "", None),
+ ],
+ )
+ def test_cursor_next_url(self, current_url, cursor, expected):
+ assert _cursor_next_url(DEFAULT_BASE_URL, current_url, cursor) == expected
+
class TestValidateCredentials:
@pytest.mark.parametrize("status_code", [200, 401, 403, 500])
@@ -515,6 +543,157 @@ class TestGetRowsTwoLevelFanout:
f"{API_BASE}/features/feature-segments/?environment=20&feature=200",
]
+ @mock.patch(SESSION_PATH)
+ def test_versions_skip_environments_without_v2_versioning(self, mock_session):
+ # Flagsmith rejects the version listing outright on an environment still using unversioned
+ # feature states, so those environments must be dropped from the enumeration rather than
+ # failing the whole sync on the first one.
+ def _get(url, **kwargs):
+ if "/versions/" in url:
+ return _resp(_page([{"uuid": "v-1", "created_at": "2026-09-01T00:00:00Z"}], None))
+ if url.endswith("/projects/"):
+ return _resp([{"id": 1}])
+ if "/environments/?project=1" in url:
+ return _resp(
+ _page(
+ [
+ {"id": 10, "use_v2_feature_versioning": True},
+ {"id": 11, "use_v2_feature_versioning": False},
+ {"id": 12},
+ ],
+ None,
+ )
+ )
+ return _resp(_page([{"id": 100}], None)) # features
+
+ mock_session.return_value.get.side_effect = _get
+
+ batches = list(get_rows("key", None, "environment_feature_versions", mock.MagicMock(), _make_manager()))
+
+ assert [row for batch in batches for row in batch] == [
+ {"uuid": "v-1", "created_at": "2026-09-01T00:00:00Z", "_environment_id": "10", "_feature_id": "100"}
+ ]
+ version_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/versions/" in c.args[0]]
+ assert version_urls == [f"{API_BASE}/environments/10/features/100/versions/?page_size=100"]
+
+
+class TestGetRowsThreeLevelFanout:
+ # Evaluation data and segment members each need three identifiers per request: a project and a
+ # resource inside it in the path, plus an environment of that project as a required filter.
+
+ @mock.patch(SESSION_PATH)
+ def test_evaluation_data_pairs_features_with_environments_of_the_same_project(self, mock_session):
+ def _get(url, **kwargs):
+ if "/evaluation-data/" in url:
+ # The series arrives as a plain JSON array, one entry per day.
+ return _resp([{"day": "2026-09-01", "count": 5, "labels": None}])
+ if url.endswith("/projects/"):
+ return _resp([{"id": 1}])
+ if "/environments/?project=1" in url:
+ return _resp(_page([{"id": 10}, {"id": 11}], None))
+ return _resp(_page([{"id": 100}], None)) # features
+
+ mock_session.return_value.get.side_effect = _get
+
+ batches = list(get_rows("key", None, "evaluation_data", mock.MagicMock(), _make_manager()))
+
+ assert [row for batch in batches for row in batch] == [
+ {
+ "day": "2026-09-01",
+ "count": 5,
+ "labels": None,
+ "_project_id": "1",
+ "_feature_id": "100",
+ "_environment_id": "10",
+ },
+ {
+ "day": "2026-09-01",
+ "count": 5,
+ "labels": None,
+ "_project_id": "1",
+ "_feature_id": "100",
+ "_environment_id": "11",
+ },
+ ]
+ urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/evaluation-data/" in c.args[0]]
+ assert urls == [
+ f"{API_BASE}/projects/1/features/100/evaluation-data/?environment_id=10&period=30",
+ f"{API_BASE}/projects/1/features/100/evaluation-data/?environment_id=11&period=30",
+ ]
+
+ @mock.patch(SESSION_PATH)
+ def test_segment_members_page_on_a_body_cursor(self, mock_session):
+ # The listing returns an opaque `next_cursor` instead of a DRF `next` link, so the next
+ # page has to be rebuilt from the current request with `cursor` set.
+ def _get(url, **kwargs):
+ if "/members/" in url:
+ if "cursor=" in url:
+ return _resp({"results": [{"identity_key": "k2"}], "next_cursor": None})
+ return _resp({"results": [{"identity_key": "k1"}], "next_cursor": "c1"})
+ if url.endswith("/projects/"):
+ return _resp([{"id": 1}])
+ if "/environments/?project=1" in url:
+ return _resp(_page([{"id": 10}], None))
+ return _resp(_page([{"id": 300}], None)) # segments
+
+ mock_session.return_value.get.side_effect = _get
+
+ batches = list(get_rows("key", None, "segment_members", mock.MagicMock(), _make_manager()))
+
+ assert [row for batch in batches for row in batch] == [
+ {"identity_key": "k1", "_project_id": "1", "_segment_id": "300", "_environment_id": "10"},
+ {"identity_key": "k2", "_project_id": "1", "_segment_id": "300", "_environment_id": "10"},
+ ]
+ member_urls = [c.args[0] for c in mock_session.return_value.get.call_args_list if "/members/" in c.args[0]]
+ assert member_urls == [
+ f"{API_BASE}/projects/1/segments/300/members/?environment=10&limit=100",
+ f"{API_BASE}/projects/1/segments/300/members/?environment=10&limit=100&cursor=c1",
+ ]
+
+ @mock.patch(BUDGET_PATH, 4)
+ @mock.patch(SESSION_PATH)
+ def test_repeating_body_cursor_is_capped(self, mock_session):
+ # A host that keeps returning the same `next_cursor` would page forever; the shared budget
+ # has to terminate it just as it does a cyclic `next` link.
+ def _get(url, **kwargs):
+ if "/members/" in url:
+ return _resp({"results": [{"identity_key": "k"}], "next_cursor": "same"})
+ if url.endswith("/projects/"):
+ return _resp([{"id": 1}])
+ if "/environments/?project=1" in url:
+ return _resp(_page([{"id": 10}], None))
+ return _resp(_page([{"id": 300}], None))
+
+ mock_session.return_value.get.side_effect = _get
+
+ list(get_rows("key", None, "segment_members", mock.MagicMock(), _make_manager()))
+
+ assert mock_session.return_value.get.call_count == 4
+
+ @mock.patch(SESSION_PATH)
+ def test_resume_key_names_all_three_identifiers(self, mock_session):
+ # The bookmark has to name the project, the segment AND the environment, or a resume would
+ # restart at the wrong triple.
+ def _get(url, **kwargs):
+ if "/members/" in url:
+ return _resp({"results": [{"identity_key": "k"}], "next_cursor": None})
+ if url.endswith("/projects/"):
+ return _resp([{"id": 1}])
+ if "/environments/?project=1" in url:
+ return _resp(_page([{"id": 10}, {"id": 11}], None))
+ return _resp(_page([{"id": 300}], None))
+
+ mock_session.return_value.get.side_effect = _get
+ manager = _make_manager()
+
+ list(get_rows("key", None, "segment_members", mock.MagicMock(), manager))
+ assert [call.args[0].parent_key for call in manager.save_state.call_args_list] == ["1/300/10", "1/300/11"]
+
+ resumed = _make_manager(FlagsmithResumeConfig(next_url="", parent_key="1/300/10"))
+ batches = list(get_rows("key", None, "segment_members", mock.MagicMock(), resumed))
+
+ assert [row["_environment_id"] for batch in batches for row in batch] == ["11"]
+
class TestErrors:
@mock.patch(SESSION_PATH)
@@ -576,5 +755,6 @@ class TestFlagsmithSourceResponse:
@pytest.mark.parametrize("endpoint", [e for e, c in FLAGSMITH_ENDPOINTS.items() if c.partition_key])
def test_partition_keys_are_stable_creation_timestamps(self, endpoint):
- # Partitioning on a mutable field rewrites partitions every sync.
- assert FLAGSMITH_ENDPOINTS[endpoint].partition_key in ("created_date", "created_at")
+ # Partitioning on a mutable field rewrites partitions every sync. `day` is the evaluation
+ # bucket a usage row belongs to, which never moves even as its count is refreshed.
+ assert FLAGSMITH_ENDPOINTS[endpoint].partition_key in ("created_date", "created_at", "day")