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): implement zep import source (#70014)

Tom Owersa3ebfa6e5666
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 713705011047..2d2f49a95cfe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -445,6 +445,7 @@ the row lists both.
| zendesk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| zendesk_sell | HTTP | requests | ✅ |
| zenloop | HTTP | requests | ✅ |
+| zep | HTTP | requests | ✅ |
| zonka_feedback | HTTP | requests | ✅ |
| zoom | HTTP | requests | ✅ |
| zuora | HTTP | requests | ✅ |
@@ -971,7 +972,6 @@ doesn't conflict with concurrent PRs.
- zenduty
- zenefits
- zenloop
-- zep
- zoho_analytics
- zoho_bigin
- zoho_billing
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 6dcabcded005..9422ce6b58e5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -4647,7 +4647,7 @@ class ZenloopSourceConfig(config.Config):
@config.config
class ZepSourceConfig(config.Config):
- pass
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/canonical_descriptions.py
new file mode 100644
index 000000000000..29a1057015aa
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/canonical_descriptions.py
@@ -0,0 +1,50 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "users": {
+ "description": "An individual interacting with your application. Each user owns a set of threads and a user-level knowledge graph.",
+ "docs_url": "https://help.getzep.com/users",
+ "columns": {
+ "uuid": "Zep-assigned unique identifier for the user.",
+ "user_id": "Your identifier for the user (any string, e.g. a username, email, or UUID).",
+ "email": "Email address of the user.",
+ "first_name": "First name of the user.",
+ "last_name": "Last name of the user.",
+ "metadata": "Arbitrary metadata associated with the user (deprecated).",
+ "project_uuid": "Identifier of the Zep project the user belongs to.",
+ "created_at": "Timestamp when the user was created.",
+ "updated_at": "Timestamp when the user was last updated (deprecated).",
+ "deleted_at": "Timestamp when the user was deleted, if applicable.",
+ "session_count": "Number of sessions for the user (deprecated).",
+ "disable_default_ontology": "Whether the default entity/edge ontology is disabled for this user's graph.",
+ },
+ },
+ "threads": {
+ "description": "A conversation belonging to a user. Each thread is a sequence of chat messages ingested into the user's knowledge graph.",
+ "docs_url": "https://help.getzep.com/threads",
+ "columns": {
+ "uuid": "Zep-assigned unique identifier for the thread.",
+ "thread_id": "Your identifier for the thread.",
+ "user_id": "Identifier of the user the thread belongs to.",
+ "project_uuid": "Identifier of the Zep project the thread belongs to.",
+ "created_at": "Timestamp when the thread was created.",
+ },
+ },
+ "thread_messages": {
+ "description": "Chat messages within each thread. One row per message, enriched with its parent thread_id.",
+ "docs_url": "https://help.getzep.com/sdk-reference/thread/get-messages-of-a-thread",
+ "columns": {
+ "uuid": "Unique identifier of the message.",
+ "content": "The text content of the message.",
+ "role": "Role of the message sender (e.g. user, assistant, system, tool).",
+ "name": "Customizable name of the sender (e.g. 'john', 'sales_agent').",
+ "processed": "Whether the message has been processed into the knowledge graph.",
+ "metadata": "Arbitrary metadata associated with the message.",
+ "created_at": "Timestamp when the message was created.",
+ "thread_id": "Identifier of the thread this message belongs to.",
+ "user_id": "Identifier of the user this thread's messages belong to.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/settings.py
new file mode 100644
index 000000000000..7df239b50828
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/settings.py
@@ -0,0 +1,59 @@
+from dataclasses import dataclass, field
+
+# Zep is a single global deployment; there are no regional hosts.
+ZEP_BASE_URL = "https://api.getzep.com/api/v2"
+
+
+@dataclass
+class ZepEndpointConfig:
+ name: str
+ path: str
+ # Key in the JSON response body that holds the list of rows.
+ data_key: str
+ primary_keys: list[str] = field(default_factory=lambda: ["uuid"])
+ # Stable creation-time field to partition by (never a mutable field like updated_at).
+ partition_key: str | None = "created_at"
+ # Page-based endpoints use different param casing (users: pageNumber/pageSize,
+ # threads: page_number/page_size). Left None for the cursor-paginated fan-out.
+ page_number_param: str | None = None
+ page_size_param: str | None = None
+ page_size: int = 100
+ # Value passed to `order_by` so pagination walks a stable, monotonic order. Must be a
+ # creation-time column so the sort matches sort_mode="asc" and page boundaries are stable
+ # as new rows arrive mid-sync.
+ order_by: str | None = None
+ should_sync_default: bool = True
+ # thread_messages fans out one paginated request per thread (Zep only exposes messages
+ # per-thread). When True, `path` is a template with a `{thread_id}` placeholder.
+ fan_out_over_threads: bool = False
+
+
+ZEP_ENDPOINTS: dict[str, ZepEndpointConfig] = {
+ "users": ZepEndpointConfig(
+ name="users",
+ path="/users-ordered",
+ data_key="users",
+ page_number_param="pageNumber",
+ page_size_param="pageSize",
+ order_by="created_at",
+ ),
+ "threads": ZepEndpointConfig(
+ name="threads",
+ path="/threads",
+ data_key="threads",
+ page_number_param="page_number",
+ page_size_param="page_size",
+ order_by="created_at",
+ ),
+ # Fan out over every thread and pull its messages. Message `uuid` is a globally-unique id
+ # per the API docs, so it alone is a safe table-wide primary key; each row is enriched with
+ # its parent `thread_id` for joinability.
+ "thread_messages": ZepEndpointConfig(
+ name="thread_messages",
+ path="/threads/{thread_id}/messages",
+ data_key="messages",
+ fan_out_over_threads=True,
+ ),
+}
+
+ENDPOINTS = tuple(ZEP_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/source.py
index 839c84ea2a66..954e3f3c85fc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/source.py
@@ -1,19 +1,39 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ZepSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep.settings import ENDPOINTS, ZEP_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep.zep import (
+ ZepResumeConfig,
+ validate_credentials as validate_zep_credentials,
+ zep_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ZepSource(SimpleSource[ZepSourceConfig]):
+class ZepSource(ResumableSource[ZepSourceConfig, ZepResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.ZEP
@@ -24,8 +44,89 @@ class ZepSource(SimpleSource[ZepSourceConfig]):
name=SchemaExternalDataSourceType.ZEP,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Zep",
- iconPath="/static/services/zep.png",
+ releaseStatus=ReleaseStatus.ALPHA,
keywords=["agent memory", "llm", "knowledge graph", "ai"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ caption="""Enter your Zep API key to sync your Zep agent-memory data into the PostHog Data warehouse.
+
+You can create an API key in the [Zep dashboard](https://app.getzep.com/) under Project Settings. Keys are prefixed with `z_`.""",
+ iconPath="/static/services/zep.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/zep",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="z_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.zep.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked Zep API key surfaces as an HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.
+ "401 Client Error: Unauthorized for url: https://api.getzep.com": "Your Zep API key is invalid or has been revoked. Create a new API key in your Zep dashboard, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.getzep.com": "Your Zep API key does not have access to this data. Check the key's permissions in your Zep dashboard, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: ZepSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # Zep exposes no server-side timestamp filter (no created_since / updated_since), so every
+ # endpoint is full-refresh only. See settings.py / the source docs for the rationale.
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = ZEP_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: ZepSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_zep_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Zep API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ZepResumeConfig]:
+ return ResumableSourceManager[ZepResumeConfig](inputs, ZepResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ZepSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ZepResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return zep_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/tests/test_zep.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/tests/test_zep.py
new file mode 100644
index 000000000000..6f31f03abae2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/tests/test_zep.py
@@ -0,0 +1,222 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep import zep
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep.settings import ZEP_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep.zep import (
+ ZEP_BASE_URL,
+ ZepResumeConfig,
+ _build_url,
+ _headers,
+ get_rows,
+ validate_credentials,
+ zep_source,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: ZepResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[ZepResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> ZepResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: ZepResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _collect(manager: _FakeResumableManager, monkeypatch: Any, endpoint: str, responses: list[dict]) -> list[dict]:
+ """Drive get_rows with a queue of page responses, recording the URLs requested."""
+ urls: list[str] = []
+ queue = list(responses)
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:
+ urls.append(url)
+ return queue.pop(0)
+
+ monkeypatch.setattr(zep, "_fetch_page", fake_fetch)
+
+ rows: list[dict] = []
+ for page in get_rows(
+ api_key="z_test",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ ):
+ rows.extend(page)
+ manager.urls = urls # type: ignore[attr-defined]
+ return rows
+
+
+class TestHelpers:
+ def test_headers_use_api_key_scheme(self) -> None:
+ assert _headers("z_abc") == {"Authorization": "Api-Key z_abc", "Accept": "application/json"}
+
+ def test_build_url_encodes_params(self) -> None:
+ url = _build_url("/users-ordered", {"pageSize": 1, "order_by": "created_at"})
+ assert url == f"{ZEP_BASE_URL}/users-ordered?pageSize=1&order_by=created_at"
+
+ def test_build_url_no_params(self) -> None:
+ assert _build_url("/threads", {}) == f"{ZEP_BASE_URL}/threads"
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("server_error", 500, False)])
+ def test_validate_credentials_maps_status(self, _name: str, status_code: int, expected: bool) -> None:
+ response = MagicMock(status_code=status_code)
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(zep, "make_tracked_session", return_value=session):
+ assert validate_credentials("z_test") is expected
+
+ def test_validate_credentials_swallows_network_error(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(zep, "make_tracked_session", return_value=session):
+ assert validate_credentials("z_test") is False
+
+
+class TestFetchPage:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_statuses_retry_then_succeed(self, _name: str, status_code: int) -> None:
+ bad = MagicMock(status_code=status_code)
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"users": []}
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(zep._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = zep._fetch_page(session, f"{ZEP_BASE_URL}/users-ordered", {}, MagicMock())
+
+ assert result == {"users": []}
+ assert session.get.call_count == 2
+
+ def test_client_error_raises_immediately(self) -> None:
+ response = MagicMock(status_code=401, ok=False, text="unauthorized")
+ response.raise_for_status.side_effect = requests.HTTPError("401 Client Error", response=response)
+ session = MagicMock()
+ session.get.return_value = response
+
+ with pytest.raises(requests.HTTPError):
+ zep._fetch_page(session, f"{ZEP_BASE_URL}/users-ordered", {}, MagicMock())
+ # A 4xx is a permanent failure: no retry.
+ assert session.get.call_count == 1
+
+
+class TestPageBasedPagination:
+ def test_stops_on_short_page_and_injects_nothing(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(ZEP_ENDPOINTS["users"], "page_size", 2)
+ manager = _FakeResumableManager()
+ rows = _collect(
+ manager,
+ monkeypatch,
+ "users",
+ [
+ {"users": [{"uuid": "u1"}, {"uuid": "u2"}], "total_count": 3},
+ {"users": [{"uuid": "u3"}], "total_count": 3},
+ ],
+ )
+ assert [r["uuid"] for r in rows] == ["u1", "u2", "u3"]
+ # First page requested pageNumber=1; state saved pointing at page 2 after yielding page 1.
+ assert "pageNumber=1" in manager.urls[0] # type: ignore[attr-defined]
+ assert manager.saved == [ZepResumeConfig(page_number=2)]
+
+ def test_stops_when_total_count_reached(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(ZEP_ENDPOINTS["users"], "page_size", 2)
+ manager = _FakeResumableManager()
+ rows = _collect(manager, monkeypatch, "users", [{"users": [{"uuid": "u1"}, {"uuid": "u2"}], "total_count": 2}])
+ assert [r["uuid"] for r in rows] == ["u1", "u2"]
+ # Reached total_count on the first full page, so no further pages and no state saved.
+ assert manager.saved == []
+
+ def test_resumes_from_saved_page(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(ZEP_ENDPOINTS["users"], "page_size", 2)
+ manager = _FakeResumableManager(ZepResumeConfig(page_number=2))
+ rows = _collect(manager, monkeypatch, "users", [{"users": [{"uuid": "u3"}], "total_count": 3}])
+ assert [r["uuid"] for r in rows] == ["u3"]
+ assert "pageNumber=2" in manager.urls[0] # type: ignore[attr-defined]
+
+ def test_threads_use_snake_case_page_params(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(ZEP_ENDPOINTS["threads"], "page_size", 2)
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, "threads", [{"threads": [{"uuid": "t1"}], "total_count": 1}])
+ assert "page_number=1" in manager.urls[0] # type: ignore[attr-defined]
+ assert "page_size=2" in manager.urls[0] # type: ignore[attr-defined]
+
+
+class TestThreadMessagesFanOut:
+ def test_fans_out_over_threads_and_injects_parent_ids(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(ZEP_ENDPOINTS["thread_messages"], "page_size", 2)
+ monkeypatch.setattr(zep, "_iter_thread_ids", lambda *a, **k: ["T1", "T2"])
+ manager = _FakeResumableManager()
+ rows = _collect(
+ manager,
+ monkeypatch,
+ "thread_messages",
+ [
+ {"messages": [{"uuid": "m1"}], "total_count": 1, "user_id": "U1"},
+ {"messages": [{"uuid": "m2"}], "total_count": 1, "user_id": "U2"},
+ ],
+ )
+ assert rows == [
+ {"uuid": "m1", "thread_id": "T1", "user_id": "U1"},
+ {"uuid": "m2", "thread_id": "T2", "user_id": "U2"},
+ ]
+
+ def test_resumes_from_saved_thread(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(ZEP_ENDPOINTS["thread_messages"], "page_size", 2)
+ monkeypatch.setattr(zep, "_iter_thread_ids", lambda *a, **k: ["T1", "T2"])
+ manager = _FakeResumableManager(ZepResumeConfig(thread_id="T2", cursor=0))
+ rows = _collect(
+ manager,
+ monkeypatch,
+ "thread_messages",
+ [{"messages": [{"uuid": "m2"}], "total_count": 1, "user_id": "U2"}],
+ )
+ # T1 is skipped: we resume straight into T2.
+ assert [r["uuid"] for r in rows] == ["m2"]
+ assert all("/threads/T2/messages" in u for u in manager.urls) # type: ignore[attr-defined]
+
+ def test_cursor_advances_across_message_pages(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(ZEP_ENDPOINTS["thread_messages"], "page_size", 2)
+ monkeypatch.setattr(zep, "_iter_thread_ids", lambda *a, **k: ["T1"])
+ manager = _FakeResumableManager()
+ rows = _collect(
+ manager,
+ monkeypatch,
+ "thread_messages",
+ [
+ {"messages": [{"uuid": "m1"}, {"uuid": "m2"}], "total_count": 3, "user_id": "U1"},
+ {"messages": [{"uuid": "m3"}], "total_count": 3, "user_id": "U1"},
+ ],
+ )
+ assert [r["uuid"] for r in rows] == ["m1", "m2", "m3"]
+ # Second page requested with cursor advanced past the first two messages.
+ assert "cursor=2" in manager.urls[1] # type: ignore[attr-defined]
+ assert manager.saved == [ZepResumeConfig(thread_id="T1", cursor=2)]
+
+
+class TestZepSourceResponse:
+ @parameterized.expand(
+ [
+ ("users", ["uuid"]),
+ ("threads", ["uuid"]),
+ ("thread_messages", ["uuid"]),
+ ]
+ )
+ def test_source_response_shape(self, endpoint: str, expected_pks: list[str]) -> None:
+ response = zep_source("z_test", endpoint, MagicMock(), MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pks
+ assert response.sort_mode == "asc"
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_mode == "datetime"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/tests/test_zep_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/tests/test_zep_source.py
new file mode 100644
index 000000000000..676f0619bf4f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/tests/test_zep_source.py
@@ -0,0 +1,101 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import ZepSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep.source import ZepSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep.zep import ZepResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _inputs(schema_name: str = "users") -> Any:
+ inputs = MagicMock()
+ inputs.schema_name = schema_name
+ return inputs
+
+
+class TestZepSource:
+ def setup_method(self) -> None:
+ self.source = ZepSource()
+ self.team_id = 7
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.ZEP
+
+ def test_source_config_exposes_api_key_password_field(self) -> None:
+ config = self.source.get_source_config
+ assert config.label == "Zep"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/zep"
+
+ assert len(config.fields) == 1
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ def test_get_schemas_returns_every_endpoint_as_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Zep has no server-side timestamp filter, so nothing is incremental/append.
+ for schema in schemas:
+ assert schema.supports_incremental is False
+ assert schema.supports_append is False
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["threads"])
+ assert [s.name for s in schemas] == ["threads"]
+
+ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Zep API key"))])
+ def test_validate_credentials(self, _name: str, probe_ok: bool, expected: tuple[bool, str | None]) -> None:
+ config = ZepSourceConfig(api_key="z_test")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zep.source.validate_zep_credentials",
+ return_value=probe_ok,
+ ):
+ assert self.source.validate_credentials(config, self.team_id) == expected
+
+ @parameterized.expand(["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors_cover_auth_failures(self, expected_key_prefix: str) -> None:
+ keys = self.source.get_non_retryable_errors()
+ assert any(k.startswith(expected_key_prefix) for k in keys)
+
+ def test_get_resumable_source_manager_is_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ZepResumeConfig
+
+ def test_source_for_pipeline_plumbs_api_key_and_schema(self) -> None:
+ config = ZepSourceConfig(api_key="z_secret")
+ manager = MagicMock()
+ inputs = _inputs(schema_name="thread_messages")
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.zep.source.zep_source"
+ ) as mock_zep_source:
+ self.source.source_for_pipeline(config, manager, inputs)
+
+ mock_zep_source.assert_called_once()
+ kwargs = mock_zep_source.call_args.kwargs
+ assert kwargs["api_key"] == "z_secret"
+ assert kwargs["endpoint"] == "thread_messages"
+ assert kwargs["resumable_source_manager"] is manager
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(ENDPOINTS).issubset(descriptions.keys())
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # lists_tables_without_credentials=True: get_schemas is a static catalog, so public docs
+ # can render the table list with no live connection.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/zep.py b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/zep.py
new file mode 100644
index 000000000000..26c89eef459c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/zep.py
@@ -0,0 +1,298 @@
+import itertools
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import quote, urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.zep.settings import (
+ ZEP_BASE_URL,
+ ZEP_ENDPOINTS,
+ ZepEndpointConfig,
+)
+
+# Zep's rate limits are plan-based and undocumented, so we lean on retries with backoff and honor
+# any Retry-After the API sends on a 429.
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+
+
+class ZepRetryableError(Exception):
+ pass
+
+
+class ZepResumeConfig:
+ # Page-based endpoints (users, threads): the next 1-based page to fetch.
+ page_number: int | None = None
+ # thread_messages fan-out: the thread we were part-way through and the message cursor
+ # (offset) to resume it at. `thread_id` is a stable id (not a positional index) so threads
+ # added/removed between a crash and the retry can't resume us into the wrong thread.
+ thread_id: str | None = None
+ cursor: int | None = None
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Api-Key {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ url = f"{ZEP_BASE_URL}{path}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params)}"
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ ZepRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> dict:
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ZepRetryableError(f"Zep API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Never log the response body: Zep error payloads can echo customer content (users,
+ # threads, messages), which must stay inside the access-controlled warehouse tables.
+ logger.error(f"Zep API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> bool:
+ # A single cheap probe: 200 means the key is genuine. Any non-200 (401 "unauthorized" for a
+ # bad key) means invalid. Never raises; network blips fall through to False.
+ url = _build_url("/users-ordered", {"pageSize": 1})
+ try:
+ # capture=False: the probe returns a user record, which is customer content the
+ # name-based sample scrubbers can't strip. Stay metered/logged, just don't sample the body.
+ response = make_tracked_session(redact_values=(api_key,), capture=False).get(
+ url, headers=_headers(api_key), timeout=10
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _page_based_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ZepResumeConfig],
+ config: ZepEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk a page-numbered endpoint (users, threads), yielding one page of rows at a time."""
+ assert config.page_number_param is not None and config.page_size_param is not None
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ page_number = resume.page_number if resume is not None and resume.page_number else 1
+
+ seen = 0
+ while True:
+ params: dict[str, Any] = {
+ config.page_size_param: config.page_size,
+ config.page_number_param: page_number,
+ }
+ if config.order_by:
+ params["order_by"] = config.order_by
+ # Ascending (oldest-first) so the order matches SourceResponse.sort_mode="asc".
+ params["asc"] = "true"
+
+ data = _fetch_page(session, _build_url(config.path, params), headers, logger)
+ items = data.get(config.data_key) or []
+ if not items:
+ break
+
+ yield items
+ seen += len(items)
+
+ total_count = data.get("total_count")
+ # A short page or reaching the reported total means the last page has been served.
+ if (total_count is not None and seen >= total_count) or len(items) < config.page_size:
+ break
+
+ page_number += 1
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it; merge
+ # dedupes the re-pulled rows on the primary key.
+ resumable_source_manager.save_state(ZepResumeConfig(page_number=page_number))
+
+
+def _iter_thread_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[str]:
+ """Lazily page /threads, yielding thread ids one at a time (used to fan out into messages).
+
+ Streaming rather than materialising the whole catalog keeps memory flat no matter how many
+ threads a project has, so a large Zep project can't exhaust the sync worker.
+ """
+ threads_config = ZEP_ENDPOINTS["threads"]
+ page_number = 1
+ seen = 0
+ while True:
+ params: dict[str, Any] = {
+ "page_size": threads_config.page_size,
+ "page_number": page_number,
+ "order_by": "created_at",
+ "asc": "true",
+ }
+ data = _fetch_page(session, _build_url("/threads", params), headers, logger)
+ items = data.get("threads") or []
+ if not items:
+ break
+ for item in items:
+ thread_id = item.get("thread_id")
+ if thread_id is not None:
+ yield thread_id
+ seen += len(items)
+ total_count = data.get("total_count")
+ if (total_count is not None and seen >= total_count) or len(items) < threads_config.page_size:
+ break
+ page_number += 1
+
+
+def _fan_out_message_rows(
+ session: requests.Session,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ZepResumeConfig],
+ config: ZepEndpointConfig,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out over every thread, yielding its messages enriched with the parent thread id.
+
+ Messages paginate with an integer `cursor`. The API documents `cursor` only as "Cursor for
+ pagination" with no next-cursor field in the response, so we treat it as an offset (advance by
+ the number of rows returned) and stop once a short page or the reported total is reached. If Zep
+ ever changes cursor semantics this stays safe: merge dedupes on the message `uuid` primary key.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ resume_thread_id = resume.thread_id if resume is not None else None
+ resume_cursor: int | None = resume.cursor if resume is not None and resume_thread_id is not None else None
+
+ thread_id_iter = iter(_iter_thread_ids(session, headers, logger))
+
+ if resume_thread_id is not None:
+ # Skip forward until the bookmarked thread. Thread order (created_at asc) is stable, so the
+ # bookmark's position doesn't move; seeking lazily avoids holding the full id list in memory.
+ for thread_id in thread_id_iter:
+ if thread_id == resume_thread_id:
+ break
+ else:
+ # The bookmarked thread vanished before the retry (rare). Its messages are gone anyway,
+ # so there's nothing to resume; the next full-refresh job re-reads every thread.
+ logger.warning(f"Zep: resume thread_id={resume_thread_id} no longer present, ending thread_messages")
+ return
+ logger.debug(f"Zep: resuming thread_messages from thread_id={resume_thread_id}, cursor={resume_cursor}")
+ # Re-inject the matched thread so it's processed below rather than skipped.
+ thread_id_iter = itertools.chain([resume_thread_id], thread_id_iter)
+
+ # Keep one id of lookahead so we can bookmark the *next* thread without knowing the total count.
+ current = next(thread_id_iter, None)
+ cursor = resume_cursor or 0
+ while current is not None:
+ nxt = next(thread_id_iter, None)
+ thread_id = current
+ # thread_id is a user-defined string; escape path-significant characters (/, ?, #) so it
+ # can't break out of its path segment and hit the wrong URL.
+ path = config.path.format(thread_id=quote(thread_id, safe=""))
+
+ seen = 0
+ while True:
+ params: dict[str, Any] = {"limit": config.page_size}
+ if cursor:
+ params["cursor"] = cursor
+
+ data = _fetch_page(session, _build_url(path, params), headers, logger)
+ items = data.get(config.data_key) or []
+ if not items:
+ break
+
+ user_id = data.get("user_id")
+ rows = [{**item, "thread_id": thread_id, "user_id": user_id} for item in items]
+ yield rows
+
+ seen += len(items)
+ cursor += len(items)
+
+ total_count = data.get("total_count")
+ if (total_count is not None and seen >= total_count) or len(items) < config.page_size:
+ break
+
+ # Save mid-thread progress after yielding, so a crash resumes this thread at the cursor.
+ resumable_source_manager.save_state(ZepResumeConfig(thread_id=thread_id, cursor=cursor))
+
+ # Advance the bookmark to the next thread so a crash between threads resumes correctly.
+ if nxt is not None:
+ resumable_source_manager.save_state(ZepResumeConfig(thread_id=nxt, cursor=0))
+
+ current = nxt
+ cursor = 0 # only the resumed-into thread uses the saved cursor
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ZepResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = ZEP_ENDPOINTS[endpoint]
+ headers = _headers(api_key)
+ # One session reused across every page (and, for the fan-out, every thread) so urllib3 keeps
+ # the connection alive instead of re-handshaking per request. The API key rides in a custom
+ # `Authorization: Api-Key ...` header the auto-redactor can't recognise, so mask it explicitly.
+ # capture=False: response bodies are users/threads/messages — customer content the name-based
+ # sample scrubbers can't strip, so keep it out of HTTP sample capture (still metered/logged).
+ session = make_tracked_session(redact_values=(api_key,), capture=False)
+
+ if config.fan_out_over_threads:
+ yield from _fan_out_message_rows(session, headers, logger, resumable_source_manager, config)
+ else:
+ yield from _page_based_rows(session, headers, logger, resumable_source_manager, config)
+
+
+def zep_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ZepResumeConfig],
+) -> SourceResponse:
+ config = ZEP_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=config.primary_keys,
+ # Rows arrive oldest-first (created_at ascending / message cursor order).
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+__all__ = ["ZepResumeConfig", "get_rows", "validate_credentials", "zep_source"]