: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(data-warehouse): add launchdarkly segments, flag statuses, experiments and holdouts (#114504)
Tom Owers22229b7a6436
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 4ea19872e562..5f3af88a6c76 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -749,7 +749,6 @@1 products/warehouse_sources/backend/temporal/data_imports/sources/lattice/lattice.py1 products/warehouse_sources/backend/temporal/data_imports/sources/lattice/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/launchdarkly.py-1 products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/leadfeeder.py1 products/warehouse_sources/backend/temporal/data_imports/sources/leadfeeder/settings.py1 products/warehouse_sources/backend/temporal/data_imports/sources/leexi/leexi.pydiff --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 5493f12851c8..b785725d0b45 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@@ -5027,9 +5027,10 @@ Today (6): `auditlog`, `environments`, `flags`, `members`, `metrics`, `projects`Diffed against: <https://app.launchdarkly.com/api/v2/openapi.json>-- [ ] `GET /api/v2/projects/{projectKey}/environments/{environmentKey}/experiments` — experiments and their results are LaunchDarkly's headline analytical object and are entirely absent today (high)-- [ ] `GET /api/v2/segments/{projectKey}/{environmentKey}` — segments referenced by the flag targeting rules already synced - without them rule targets are unresolvable ids (high)-- [ ] `GET /api/v2/flag-statuses/{projectKey}/{environmentKey}` — per-flag status and last-requested timestamp, the basis for stale-flag and adoption reporting (high)+- [x] `GET /api/v2/projects/{projectKey}/environments/{environmentKey}/experiments` — experiments and their results are LaunchDarkly's headline analytical object and are entirely absent today (high)+- [x] `GET /api/v2/segments/{projectKey}/{environmentKey}` — segments referenced by the flag targeting rules already synced - without them rule targets are unresolvable ids (high)+- [x] `GET /api/v2/flag-statuses/{projectKey}/{environmentKey}` — per-flag status and last-requested timestamp, the basis for stale-flag and adoption reporting (high)+- [x] `GET /api/v2/projects/{projectKey}/environments/{environmentKey}/holdouts` — holdout groups tied to experiment measurement (medium)- [ ] `GET /api/v2/projects/{projectKey}/metric-groups` — lookup grouping the metrics already synced, and what experiments actually attach to (medium)- [ ] `GET /api/v2/teams (+ /teams/{teamKey}/maintainers, /teams/{teamKey}/roles)` — team membership and maintainer mapping for the members table already synced (medium)- [ ] `GET /api/v2/code-refs/statistics/{projectKey} and /api/v2/code-refs/repositories` — flag code-reference counts per repo - how you prove a flag is safe to remove (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/canonical_descriptions.pyindex 23d647864ee9..4b838744da31 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/canonical_descriptions.py@@ -98,4 +98,75 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"creationDate": "Time the flag was created, as an epoch-millisecond timestamp.",},},+ "segments": {+ "description": "A segment of contexts that flag targeting rules can include or exclude, per environment.",+ "docs_url": "https://apidocs.launchdarkly.com/tag/Segments",+ "columns": {+ "_project_key": "Key of the project this segment belongs to (injected during sync).",+ "_environment_key": "Key of the environment this segment belongs to (injected during sync).",+ "key": "The segment's unique key within its environment.",+ "name": "The segment's human-readable name.",+ "description": "Description of the segment's purpose.",+ "tags": "Tags applied to the segment.",+ "creationDate": "Time the segment was created, as an epoch-millisecond timestamp.",+ "lastModifiedDate": "Time the segment was last modified, as an epoch-millisecond timestamp.",+ "included": "Keys of targets that are always members of the segment.",+ "excluded": "Keys of targets that are never members of the segment through individual targeting.",+ "rules": "The targeting rules for the segment.",+ "version": "Version of the segment.",+ "deleted": "Whether the segment has been deleted.",+ "unbounded": "Whether this is a big segment (true) or a standard segment (false).",+ },+ },+ "flag_statuses": {+ "description": "The status of each feature flag in an environment, with the time it was last requested.",+ "docs_url": "https://apidocs.launchdarkly.com/tag/Feature-flags#operation/getFeatureFlagStatuses",+ "columns": {+ "_project_key": "Key of the project the flag belongs to (injected during sync).",+ "_environment_key": "Key of the environment the status applies to (injected during sync).",+ "_flag_key": "Key of the flag, taken from the status row's link (injected during sync).",+ "name": "The flag's status: new, active, inactive, or launched.",+ "lastRequested": "Time the flag was last requested in this environment.",+ "default": "The default value of the flag seen from code.",+ },+ },+ "experiments": {+ "description": "A LaunchDarkly experiment, including its current, draft, and previous iterations.",+ "docs_url": "https://apidocs.launchdarkly.com/tag/Experiments",+ "columns": {+ "_project_key": "Key of the project this experiment belongs to (injected during sync).",+ "_environment_key": "Key of the environment this experiment runs in (injected during sync).",+ "_id": "Unique identifier for the experiment.",+ "key": "The experiment's unique key.",+ "name": "The experiment's human-readable name.",+ "description": "Description of the experiment.",+ "_maintainerId": "ID of the member who maintains the experiment.",+ "_creationDate": "Time the experiment was created, as an epoch-millisecond timestamp.",+ "archivedDate": "Time the experiment was archived, as an epoch-millisecond timestamp.",+ "methodology": "The results analysis approach.",+ "dataSource": "The source of metric data used to analyze results.",+ "holdoutId": "ID of the holdout the experiment belongs to.",+ "currentIteration": "Details of the current iteration.",+ "draftIteration": "Details of the iteration that has not started yet, if any.",+ "previousIterations": "Details of the iterations before the current one.",+ "analysisConfig": "The analysis configuration of the experiment.",+ "tags": "Tags applied to the experiment.",+ "type": "The experiment type.",+ },+ },+ "holdouts": {+ "description": "A holdout that excludes a percentage of traffic from experiments to measure their overall effect.",+ "docs_url": "https://apidocs.launchdarkly.com/tag/Holdouts",+ "columns": {+ "_project_key": "Key of the project this holdout belongs to (injected during sync).",+ "_environment_key": "Key of the environment this holdout belongs to (injected during sync).",+ "_id": "Unique identifier for the holdout.",+ "key": "The holdout's key.",+ "name": "The holdout's human-readable name.",+ "status": "The holdout's status.",+ "createdAt": "Time the holdout was created, as an epoch-millisecond timestamp.",+ "updatedAt": "Time the holdout was last updated, as an epoch-millisecond timestamp.",+ "experiments": "The experiments that belong to the holdout.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/launchdarkly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/launchdarkly.pyindex 7e8c74575687..036ec2fa9cf1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/launchdarkly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/launchdarkly.py@@ -1,5 +1,6 @@import dataclassesfrom typing import Any, Optional+from urllib.parse import urlparsefrom requests import Response@@ -10,6 +11,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,rest_api_resources,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ rename_parent_fields,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (BaseNextUrlPaginator,)@@ -29,6 +33,8 @@ BASE_URL = f"{API_HOST}/api/v2"# project key under `_project_key` (make_parent_key_name(name, "key") == f"_{name}_key"), matching# the column the hand-rolled source emitted.PROJECTS_PARENT_NAME = "project"+# Parent resource name for environment-scoped endpoints, injecting the environment key as `_environment_key`.+ENVIRONMENTS_PARENT_NAME = "environment"@dataclasses.dataclass@@ -84,6 +90,21 @@ class LaunchDarklyLinkPaginator(BaseNextUrlPaginator):return "LaunchDarklyLinkPaginator()"+def _endpoint_params(config: LaunchDarklyEndpointConfig) -> dict[str, Any]:+ params: dict[str, Any] = dict(config.extra_params)+ if config.page_size is not None:+ params["limit"] = config.page_size+ return params+++def _with_flag_key(row: dict[str, Any]) -> dict[str, Any]:+ # A flag status row names its flag only in its links: /api/v2/flag-statuses/{project}/{environment}/{flag}.+ links = row.get("_links") or {}+ href = (links.get("self") or {}).get("href") or (links.get("parent") or {}).get("href") or ""+ row["_flag_key"] = urlparse(href).path.rstrip("/").rsplit("/", 1)[-1] or None+ return row++def _client_config(access_token: str) -> ClientConfig:return {"base_url": BASE_URL,@@ -109,7 +130,7 @@ def _build_toplevel_resource("name": config.name,"endpoint": {"path": config.path,- "params": {"limit": config.page_size},+ "params": _endpoint_params(config),"data_selector": "items","paginator": LaunchDarklyLinkPaginator(),},@@ -137,15 +158,8 @@ def _build_toplevel_resource()-def _build_fanout_resource(- config: LaunchDarklyEndpointConfig,- access_token: str,- team_id: int,- job_id: str,- resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],- resume: Optional[LaunchDarklyResumeConfig],-) -> Resource:- rest_config: RESTAPIConfig = {+def _project_fanout_config(config: LaunchDarklyEndpointConfig, access_token: str) -> RESTAPIConfig:+ return {"client": _client_config(access_token),"resources": [{@@ -163,7 +177,7 @@ def _build_fanout_resource("path": config.path,"params": {"project_key": {"type": "resolve", "resource": PROJECTS_PARENT_NAME, "field": "key"},- "limit": config.page_size,+ **_endpoint_params(config),},"data_selector": "items","paginator": LaunchDarklyLinkPaginator(),@@ -174,6 +188,15 @@ def _build_fanout_resource(],}++def _build_fanout_resource(+ config: LaunchDarklyEndpointConfig,+ access_token: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],+ resume: Optional[LaunchDarklyResumeConfig],+) -> Resource:initial_paginator_state: Optional[dict[str, Any]] = Noneif resume is not None and resume.fanout_state:initial_paginator_state = resume.fanout_state@@ -182,7 +205,7 @@ def _build_fanout_resource(resumable_source_manager.save_state(LaunchDarklyResumeConfig(fanout_state=state))resources = rest_api_resources(- rest_config,+ _project_fanout_config(config, access_token),team_id,job_id,None,@@ -192,6 +215,77 @@ def _build_fanout_resource(return next(resource for resource in resources if resource.name == config.name)+def _build_environment_fanout_resource(+ config: LaunchDarklyEndpointConfig,+ access_token: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[LaunchDarklyResumeConfig],+ resume: Optional[LaunchDarklyResumeConfig],+) -> Resource:+ # The framework resumes only one dependent level, so the project -> environment walk feeds the+ # child as a plain iterator and the per-environment child progress is what gets checkpointed.+ environments_config = LAUNCHDARKLY_ENDPOINTS["environments"]+ environments = next(+ resource+ for resource in rest_api_resources(+ _project_fanout_config(environments_config, access_token), team_id, job_id, None+ )+ if resource.name == environments_config.name+ )++ rest_config: RESTAPIConfig = {+ "client": _client_config(access_token),+ "resources": [+ {+ "name": ENVIRONMENTS_PARENT_NAME,+ # The iterator supplies the rows; the path is never requested.+ "endpoint": {"path": "/projects"},+ "data_iterator": lambda: iter(environments),+ },+ {+ "name": config.name,+ "endpoint": {+ "path": config.path,+ "params": {+ "project_key": {+ "type": "resolve",+ "resource": ENVIRONMENTS_PARENT_NAME,+ "field": "_project_key",+ },+ "environment_key": {"type": "resolve", "resource": ENVIRONMENTS_PARENT_NAME, "field": "key"},+ **_endpoint_params(config),+ },+ "data_selector": "items",+ "paginator": LaunchDarklyLinkPaginator(),+ },+ "include_from_parent": ["key", "_project_key"],+ },+ ],+ }++ initial_paginator_state: Optional[dict[str, Any]] = None+ if resume is not None and resume.fanout_state:+ initial_paginator_state = resume.fanout_state++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ resumable_source_manager.save_state(LaunchDarklyResumeConfig(fanout_state=state))++ resources = rest_api_resources(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+ resource = next(resource for resource in resources if resource.name == config.name)+ resource.add_map(rename_parent_fields(ENVIRONMENTS_PARENT_NAME, {"_project_key": "_project_key"}))+ if config.name == "flag_statuses":+ resource.add_map(_with_flag_key)+ return resource++def launchdarkly_source(access_token: str,endpoint: str,@@ -203,7 +297,11 @@ def launchdarkly_source(resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None- if config.requires_project:+ if config.requires_environment:+ resource = _build_environment_fanout_resource(+ config, access_token, team_id, job_id, resumable_source_manager, resume+ )+ elif config.requires_project:resource = _build_fanout_resource(config, access_token, team_id, job_id, resumable_source_manager, resume)else:resource = _build_toplevel_resource(config, access_token, team_id, job_id, resumable_source_manager, resume)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/settings.pyindex f322daf727be..4d6f0403813e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/settings.py@@ -1,9 +1,10 @@from dataclasses import dataclass, field+from typing import Anyfrom products.warehouse_sources.backend.types import IncrementalField-@dataclass+@dataclass(frozen=True)class LaunchDarklyEndpointConfig:name: str# Path under the API root. A ``{project_key}`` placeholder marks a fan-out endpoint@@ -13,9 +14,15 @@ class LaunchDarklyEndpointConfig:# Fan-out endpoints depend on the list of projects; we inject ``_project_key`` into# every row so a single table stays meaningful (and uniquely keyed) across projects.requires_project: bool = False+ # Environment-scoped endpoints take both ``{project_key}`` and ``{environment_key}`` and are+ # queried once per environment of every project, with ``_project_key`` and ``_environment_key``+ # injected into every row.+ requires_environment: bool = False# LaunchDarkly's list endpoints default to a small page size; 20 is the documented# safe default across every endpoint we sync. Raise per-endpoint only once verified.- page_size: int = 20+ # ``None`` for endpoints that return every row in one response and take no ``limit``.+ page_size: int | None = 20+ extra_params: dict[str, Any] = field(default_factory=dict)# LaunchDarkly exposes no server-side timestamp filter on these resources (its# timestamps are epoch-millisecond integers and the public API offers no# ``updated_after``/``since`` parameter), so every endpoint is full-refresh only.@@ -58,6 +65,38 @@ LAUNCHDARKLY_ENDPOINTS: dict[str, LaunchDarklyEndpointConfig] = {primary_key=["key", "_project_key"],requires_project=True,),+ "segments": LaunchDarklyEndpointConfig(+ name="segments",+ path="/segments/{project_key}/{environment_key}",+ primary_key=["key", "_project_key", "_environment_key"],+ requires_environment=True,+ extra_params={"sort": "creationDate"},+ ),+ "flag_statuses": LaunchDarklyEndpointConfig(+ name="flag_statuses",+ path="/flag-statuses/{project_key}/{environment_key}",+ # Status rows carry no flag key field; ``_flag_key`` is derived from the row's self link.+ primary_key=["_flag_key", "_project_key", "_environment_key"],+ requires_environment=True,+ page_size=None,+ ),+ "experiments": LaunchDarklyEndpointConfig(+ name="experiments",+ path="/projects/{project_key}/environments/{environment_key}/experiments",+ primary_key=["key", "_project_key", "_environment_key"],+ requires_environment=True,+ extra_params={+ # The API returns only active experiments and only the current iteration by default.+ "lifecycleState": "active,archived",+ "expand": "previousIterations,draftIteration,secondaryMetrics,treatments,analysisConfig",+ },+ ),+ "holdouts": LaunchDarklyEndpointConfig(+ name="holdouts",+ path="/projects/{project_key}/environments/{environment_key}/holdouts",+ primary_key=["_id", "_project_key", "_environment_key"],+ requires_environment=True,+ ),}ENDPOINTS = tuple(LAUNCHDARKLY_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/source.pyindex e0e0b7944035..5670a933567e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/source.py@@ -51,7 +51,7 @@ class LaunchDarklySource(ResumableSource[LaunchDarklySourceConfig, LaunchDarklyRkeywords=["feature flags"],label="LaunchDarkly",releaseStatus=ReleaseStatus.ALPHA,- caption="""Enter your LaunchDarkly access token to pull your projects, environments, feature flags, metrics, members, and audit log into the PostHog Data warehouse.+ caption="""Enter your LaunchDarkly access token to pull your projects, environments, feature flags, flag statuses, segments, experiments, holdouts, metrics, members, and audit log into the PostHog Data warehouse.You can create a personal or service access token in your [LaunchDarkly account settings](https://app.launchdarkly.com/settings/authorization). A token with the **Reader** role grants read access to every resource this source syncs.""",iconPath="/static/services/launchdarkly.png",@@ -122,7 +122,9 @@ You can create a personal or service access token in your [LaunchDarkly accountif schema_name is not None:endpoint = LAUNCHDARKLY_ENDPOINTS.get(schema_name)if endpoint is not None:- probe_path = "/projects" if endpoint.requires_project else endpoint.path+ probe_path = (+ "/projects" if endpoint.requires_project or endpoint.requires_environment else endpoint.path+ )status = validate_launchdarkly_credentials(config.access_token, probe_path)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly.pyindex d21a9a5c8483..df6e4d78bbe7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/launchdarkly/tests/test_launchdarkly.py@@ -188,6 +188,96 @@ class TestGetRowsFanout:]+class TestGetRowsEnvironmentFanout:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_iterates_environments_of_every_project_and_injects_both_keys(self, mock_session):+ session = mock_session.return_value+ snaps = _wire(+ session,+ [+ _response([{"key": "proj1"}], None),+ _response([{"key": "prod"}, {"key": "dev"}], None),+ _response([{"key": "s1"}], "/api/v2/segments/proj1/prod?limit=20&offset=20&sort=creationDate"),+ _response([{"key": "s2"}], None),+ _response([{"key": "s3"}], None),+ ],+ )++ rows = _rows(_source("segments", _make_manager()))++ assert rows == [+ {"key": "s1", "_environment_key": "prod", "_project_key": "proj1"},+ {"key": "s2", "_environment_key": "prod", "_project_key": "proj1"},+ {"key": "s3", "_environment_key": "dev", "_project_key": "proj1"},+ ]+ assert [snap["url"] for snap in snaps] == [+ f"{BASE_URL}/projects",+ f"{BASE_URL}/projects/proj1/environments",+ f"{BASE_URL}/segments/proj1/prod",+ f"{API_HOST}/api/v2/segments/proj1/prod?limit=20&offset=20&sort=creationDate",+ f"{BASE_URL}/segments/proj1/dev",+ ]+ assert snaps[2]["params"] == {"limit": 20, "sort": "creationDate"}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_flag_statuses_take_flag_key_from_self_link(self, mock_session):+ session = mock_session.return_value+ status = {+ "name": "inactive",+ "_links": {+ "parent": {"href": "/api/v2/flags/proj1/my-flag"},+ "self": {"href": "/api/v2/flag-statuses/proj1/prod/my-flag"},+ },+ }+ snaps = _wire(+ session,+ [+ _response([{"key": "proj1"}], None),+ _response([{"key": "prod"}], None),+ _response([status], None),+ ],+ )++ rows = _rows(_source("flag_statuses", _make_manager()))++ assert [(row["_flag_key"], row["_project_key"], row["_environment_key"]) for row in rows] == [+ ("my-flag", "proj1", "prod")+ ]+ assert snaps[2]["url"] == f"{BASE_URL}/flag-statuses/proj1/prod"+ assert snaps[2]["params"] == {}++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resume_skips_completed_environments(self, mock_session):+ session = mock_session.return_value+ resume_url = f"{BASE_URL}/projects/proj1/environments/dev/holdouts?limit=20&offset=20"+ snaps = _wire(+ session,+ [+ _response([{"key": "proj1"}], None),+ _response([{"key": "prod"}, {"key": "dev"}], None),+ _response([{"_id": "h2"}], None),+ ],+ )+ manager = _make_manager(+ LaunchDarklyResumeConfig(+ fanout_state={+ "completed": ["/projects/proj1/environments/prod/holdouts"],+ "current": "/projects/proj1/environments/dev/holdouts",+ "child_state": {"next_url": resume_url},+ }+ )+ )++ rows = _rows(_source("holdouts", manager))++ assert rows == [{"_id": "h2", "_environment_key": "dev", "_project_key": "proj1"}]+ assert [snap["url"] for snap in snaps] == [+ f"{BASE_URL}/projects",+ f"{BASE_URL}/projects/proj1/environments",+ resume_url,+ ]++class TestRetryAndErrors:@mock.patch(CLIENT_SESSION_PATCH)def test_4xx_raises(self, mock_session):