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 4 missing tables to the Zep source (#124609)

Tom Owers2b493931d6e0
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 6521822d5285..c439411dd2a0 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
@@ -13609,10 +13609,10 @@ Today (3): `thread_messages`, `threads`, `users`
Diffed against: <https://help.getzep.com/sitemap.xml>
-- [ ] `graph/edge/user/{user_id} and graph/edge/graph/{graph_id} (edges/facts)` — the temporal fact triples that are Zep's headline product - relationships with valid_at/invalid_at intervals (high)
-- [ ] `graph/node/user/{user_id} and graph/node/graph/{graph_id} (nodes/entities)` — the extracted entities in the knowledge graph, the lookup table every edge and observation points at (high)
-- [ ] `graph/episodes/user/{user_id} and graph/episodes/graph/{graph_id}` — the ingested source episodes that produced each node and edge - the provenance link back to thread messages (high)
-- [ ] `graph/list-all (graphs)` — lookup enumerating non-user graphs; without it the entire graph-scoped side of the API is unreachable (high)
+- [x] `graph/edge/user/{user_id} and graph/edge/graph/{graph_id} (edges/facts)` — the temporal fact triples that are Zep's headline product - relationships with valid_at/invalid_at intervals (high)
+- [x] `graph/node/user/{user_id} and graph/node/graph/{graph_id} (nodes/entities)` — the extracted entities in the knowledge graph, the lookup table every edge and observation points at (high)
+- [x] `graph/episodes/user/{user_id} and graph/episodes/graph/{graph_id}` — the ingested source episodes that produced each node and edge - the provenance link back to thread messages (high)
+- [x] `graph/list-all (graphs)` — lookup enumerating non-user graphs; without it the entire graph-scoped side of the API is unreachable (high)
- [ ] `graph/observation/user/{user_id} and graph/observation/graph/{graph_id}` — per-entity observations, the granular memory records behind summarized facts (medium)
- [ ] `graph thread summaries (get-user-thread-summaries / get-graph-thread-summaries)` — generated summaries per thread, the analytical rollup of the thread_messages we already sync (medium)
- [ ] `graph/list-ontology (entity and edge type definitions)` — lookup resolving the type labels stamped on nodes and edges (medium)
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
index 29a1057015aa..11f07fe83ea7 100644
--- 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
@@ -47,4 +47,76 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"user_id": "Identifier of the user this thread's messages belong to.",
},
},
+ "graphs": {
+ "description": "Standalone knowledge graphs in the project, created directly rather than owned by a user.",
+ "docs_url": "https://help.getzep.com/v3/sdk-reference/graph/list-standalone-graphs-in-the-graph-directory",
+ "columns": {
+ "uuid": "Zep-assigned unique identifier for the graph.",
+ "graph_id": "Your identifier for the graph.",
+ "name": "Display name of the graph.",
+ "description": "Description of the graph.",
+ "project_uuid": "Identifier of the Zep project the graph belongs to.",
+ "time_zone": "IANA time zone of the graph.",
+ "created_at": "Timestamp when the graph was created.",
+ "updated_at": "Timestamp when the graph was last updated.",
+ },
+ },
+ "graph_edges": {
+ "description": "Facts in each user graph and standalone graph. Each edge links a source node to a target node, with the time range in which the fact was true.",
+ "docs_url": "https://help.getzep.com/v3/sdk-reference/graph/edge/get-user-edges",
+ "columns": {
+ "uuid": "Unique identifier of the edge.",
+ "name": "Name of the relation, for example RELATES_TO.",
+ "fact": "The natural-language fact that the edge represents.",
+ "source_node_uuid": "UUID of the source node.",
+ "target_node_uuid": "UUID of the target node.",
+ "episodes": "UUIDs of the episodes that reference this edge.",
+ "attributes": "Additional attributes of the edge, which depend on the edge type.",
+ "valid_at": "Timestamp when the fact became true.",
+ "invalid_at": "Timestamp when the fact stopped being true.",
+ "expired_at": "Timestamp when the edge was invalidated.",
+ "created_at": "Timestamp when the edge was created.",
+ "graph_scope": "Kind of graph the row came from: 'user' for a user's graph, 'graph' for a standalone graph.",
+ "graph_owner_id": "The user_id or graph_id of the graph the row came from.",
+ "user_id": "Identifier of the user whose graph the row came from. Empty for standalone graphs.",
+ "graph_id": "Identifier of the standalone graph the row came from. Empty for user graphs.",
+ },
+ },
+ "graph_nodes": {
+ "description": "Entities in each user graph and standalone graph. Edges and episodes refer to nodes by uuid.",
+ "docs_url": "https://help.getzep.com/v3/sdk-reference/graph/node/get-user-nodes",
+ "columns": {
+ "uuid": "Unique identifier of the node.",
+ "name": "Name of the entity.",
+ "summary": "Generated summary of the entity and its surrounding edges.",
+ "labels": "Entity type labels of the node.",
+ "attributes": "Additional attributes of the node, which depend on its labels.",
+ "created_at": "Timestamp when the node was created.",
+ "graph_scope": "Kind of graph the row came from: 'user' for a user's graph, 'graph' for a standalone graph.",
+ "graph_owner_id": "The user_id or graph_id of the graph the row came from.",
+ "user_id": "Identifier of the user whose graph the row came from. Empty for standalone graphs.",
+ "graph_id": "Identifier of the standalone graph the row came from. Empty for user graphs.",
+ },
+ },
+ "graph_episodes": {
+ "description": "Source data ingested into each user graph and standalone graph, such as thread messages, text and JSON. Nodes and edges are extracted from episodes.",
+ "docs_url": "https://help.getzep.com/v3/sdk-reference/graph/episode/list-by-user-id",
+ "columns": {
+ "uuid": "Unique identifier of the episode.",
+ "content": "Content of the episode.",
+ "source": "Type of the source data: text, json, message or fact_triple.",
+ "source_description": "Description of the source data.",
+ "role": "Role of the message sender, present when the episode came from a thread message.",
+ "role_type": "Role type of the message sender, for example user or assistant.",
+ "thread_id": "Identifier of the thread the episode came from, if any.",
+ "document_id": "Identifier of the document the episode is part of, if any.",
+ "processed": "Whether Zep has processed the episode into the graph.",
+ "metadata": "Arbitrary metadata associated with the episode.",
+ "created_at": "Timestamp when the episode was created.",
+ "graph_scope": "Kind of graph the row came from: 'user' for a user's graph, 'graph' for a standalone graph.",
+ "graph_owner_id": "The user_id or graph_id of the graph the row came from.",
+ "user_id": "Identifier of the user whose graph the row came from. Empty for standalone graphs.",
+ "graph_id": "Identifier of the standalone graph the row came from. Empty for user graphs.",
+ },
+ },
}
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
index 7df239b50828..703114c2a514 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/settings.py
@@ -4,7 +4,7 @@ from dataclasses import dataclass, field
ZEP_BASE_URL = "https://api.getzep.com/api/v2"
-@dataclass
+@dataclass(frozen=False) # tests patch fields such as page_size
class ZepEndpointConfig:
name: str
path: str
@@ -26,8 +26,14 @@ class ZepEndpointConfig:
# 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
+ # Graph endpoints list one graph per request. When True, `path` is a template with `{scope}`
+ # ("user" or "graph") and `{owner_id}` placeholders, and the source fans out over every user
+ # graph and every standalone graph. The response body is a bare list.
+ fan_out_over_graphs: bool = False
+GRAPH_ELEMENT_PRIMARY_KEYS = ["graph_scope", "graph_owner_id", "uuid"]
+
ZEP_ENDPOINTS: dict[str, ZepEndpointConfig] = {
"users": ZepEndpointConfig(
name="users",
@@ -54,6 +60,40 @@ ZEP_ENDPOINTS: dict[str, ZepEndpointConfig] = {
data_key="messages",
fan_out_over_threads=True,
),
+ "graphs": ZepEndpointConfig(
+ name="graphs",
+ path="/graph/list-all",
+ data_key="graphs",
+ page_number_param="pageNumber",
+ page_size_param="pageSize",
+ order_by="created_at",
+ ),
+ # Graph elements carry no reference to their graph, so each row gets `graph_scope` and
+ # `graph_owner_id` (the user_id or graph_id). The key includes them because the API does not
+ # document element uuids as unique across graphs.
+ "graph_edges": ZepEndpointConfig(
+ name="graph_edges",
+ path="/graph/edge/{scope}/{owner_id}",
+ data_key="",
+ primary_keys=GRAPH_ELEMENT_PRIMARY_KEYS,
+ fan_out_over_graphs=True,
+ ),
+ "graph_nodes": ZepEndpointConfig(
+ name="graph_nodes",
+ path="/graph/node/{scope}/{owner_id}",
+ data_key="",
+ primary_keys=GRAPH_ELEMENT_PRIMARY_KEYS,
+ fan_out_over_graphs=True,
+ ),
+ "graph_episodes": ZepEndpointConfig(
+ name="graph_episodes",
+ path="/graph/episodes/{scope}/{owner_id}",
+ data_key="",
+ primary_keys=GRAPH_ELEMENT_PRIMARY_KEYS,
+ # The API clamps an explicit episode `limit` to 50.
+ page_size=50,
+ fan_out_over_graphs=True,
+ ),
}
ENDPOINTS = tuple(ZEP_ENDPOINTS.keys())
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
index a7c9c501e6cd..aeb8aa26f732 100644
--- 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
@@ -147,21 +147,163 @@ class TestThreadMessagesFanOut:
assert result.saved_states == [ZepResumeConfig(thread_id="T1", cursor=2)]
+class TestGraphFanOut:
+ @staticmethod
+ def _owners(users: list[str], graphs: list[str]) -> dict[str, list[ScriptedResponse]]:
+ return {
+ "/users-ordered": [
+ ScriptedResponse(json={"users": [{"user_id": u} for u in users], "total_count": len(users)})
+ ],
+ "/graph/list-all": [
+ ScriptedResponse(json={"graphs": [{"graph_id": g} for g in graphs], "total_count": len(graphs)})
+ ],
+ }
+
+ @parameterized.expand(
+ [
+ ("graph_edges", "edge", 100),
+ ("graph_nodes", "node", 100),
+ ("graph_episodes", "episodes", 50),
+ ]
+ )
+ def test_walks_user_and_standalone_graphs_by_cursor_header(self, endpoint: str, kind: str, limit: int) -> None:
+ result = _run(
+ endpoint,
+ route(
+ {
+ **self._owners(["U1"], ["G1"]),
+ f"/graph/{kind}/user/U1": [
+ ScriptedResponse(json=[{"uuid": "a"}], headers={"Zep-Next-Cursor": "c1"}),
+ ScriptedResponse(json=[{"uuid": "b"}]),
+ ],
+ f"/graph/{kind}/graph/G1": [ScriptedResponse(json=[{"uuid": "c"}])],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert result.rows == [
+ {"uuid": "a", "graph_scope": "user", "graph_owner_id": "U1", "user_id": "U1", "graph_id": None},
+ {"uuid": "b", "graph_scope": "user", "graph_owner_id": "U1", "user_id": "U1", "graph_id": None},
+ {"uuid": "c", "graph_scope": "graph", "graph_owner_id": "G1", "user_id": None, "graph_id": "G1"},
+ ]
+ graph_requests = [r for r in result.requests if r.path.startswith(f"/api/v2/graph/{kind}/")]
+ assert [r.method for r in graph_requests] == ["POST", "POST", "POST"]
+ assert [r.json() for r in graph_requests] == [
+ {"limit": limit, "order_by": "created_at", "direction": "asc"},
+ {"limit": limit, "order_by": "created_at", "direction": "asc", "cursor": "c1"},
+ {"limit": limit, "order_by": "created_at", "direction": "asc"},
+ ]
+ # Each cursor is staged before the page it follows is yielded.
+ assert result.saved_states == [
+ ZepResumeConfig(graph_scope="user", graph_owner_id="U1", graph_cursor="c1"),
+ ZepResumeConfig(graph_scope="graph", graph_owner_id="G1"),
+ ZepResumeConfig(graph_finished=True),
+ ]
+
+ @parameterized.expand(
+ [
+ ("deleted_graph", ScriptedResponse(status=404, json={"message": "not found"})),
+ ("empty_graph", ScriptedResponse(json=[])),
+ ("null_body", ScriptedResponse(body=b"null")),
+ ]
+ )
+ def test_graph_without_rows_moves_on_to_next_graph(self, _name: str, first_answer: ScriptedResponse) -> None:
+ result = _run(
+ "graph_edges",
+ route(
+ {
+ **self._owners(["U1", "U2"], []),
+ "/graph/edge/user/U1": [first_answer],
+ "/graph/edge/user/U2": [ScriptedResponse(json=[{"uuid": "e2"}])],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert [r["uuid"] for r in result.rows] == ["e2"]
+ assert result.committed_states[0] == ZepResumeConfig(graph_scope="user", graph_owner_id="U2")
+
+ def test_repeated_cursor_ends_the_graph(self) -> None:
+ result = _run(
+ "graph_nodes",
+ route(
+ {
+ **self._owners(["U1"], []),
+ "/graph/node/user/U1": [
+ ScriptedResponse(json=[{"uuid": "n1"}], headers={"Zep-Next-Cursor": "c1"}),
+ ScriptedResponse(json=[{"uuid": "n2"}], headers={"Zep-Next-Cursor": "c1"}),
+ ],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert [r["uuid"] for r in result.rows] == ["n1", "n2"]
+
+ def test_resumes_from_saved_graph_and_cursor(self) -> None:
+ result = _run(
+ "graph_episodes",
+ route(
+ {
+ **self._owners(["U1"], ["G1", "G2"]),
+ "/graph/episodes/graph/G1": [ScriptedResponse(json=[{"uuid": "ep2"}])],
+ "/graph/episodes/graph/G2": [ScriptedResponse(json=[{"uuid": "ep3"}])],
+ }
+ ),
+ resume_state=ZepResumeConfig(graph_scope="graph", graph_owner_id="G1", graph_cursor="c9"),
+ )
+
+ assert [r["uuid"] for r in result.rows] == ["ep2", "ep3"]
+ graph_requests = [r for r in result.requests if r.path.startswith("/api/v2/graph/episodes/")]
+ assert [r.path for r in graph_requests] == [
+ "/api/v2/graph/episodes/graph/G1",
+ "/api/v2/graph/episodes/graph/G2",
+ ]
+ assert graph_requests[0].json()["cursor"] == "c9"
+ assert "cursor" not in graph_requests[1].json()
+
+ def test_resume_into_vanished_graph_ends_cleanly(self) -> None:
+ result = _run(
+ "graph_edges",
+ route(self._owners(["U1"], [])),
+ resume_state=ZepResumeConfig(graph_scope="graph", graph_owner_id="gone"),
+ )
+
+ assert result.raised is None
+ assert result.rows == []
+
+ def test_resume_after_last_graph_reads_nothing_again(self) -> None:
+ result = _run(
+ "graph_edges",
+ route(self._owners(["U1"], [])),
+ resume_state=ZepResumeConfig(graph_finished=True),
+ )
+
+ assert result.raised is None
+ assert result.rows == []
+ assert result.requests == []
+
+
class TestZepSourceResponse:
@parameterized.expand(
[
- ("users", ["uuid"]),
- ("threads", ["uuid"]),
- ("thread_messages", ["uuid"]),
+ ("users", ["uuid"], "asc"),
+ ("threads", ["uuid"], "asc"),
+ ("thread_messages", ["uuid"], "asc"),
+ ("graphs", ["uuid"], "asc"),
+ ("graph_edges", ["graph_scope", "graph_owner_id", "uuid"], None),
+ ("graph_nodes", ["graph_scope", "graph_owner_id", "uuid"], None),
+ ("graph_episodes", ["graph_scope", "graph_owner_id", "uuid"], None),
]
)
- def test_source_response_shape(self, endpoint: str, expected_pks: list[str]) -> None:
- result = _run(endpoint, always(ScriptedResponse(json={"users": [], "threads": [], "messages": []})))
+ def test_source_response_shape(self, endpoint: str, expected_pks: list[str], expected_sort: str | None) -> None:
+ result = _run(endpoint, always(ScriptedResponse(json={"users": [], "threads": [], "graphs": []})))
response = result.response
assert response is not None
assert response.name == endpoint
assert response.primary_keys == expected_pks
- assert response.sort_mode == "asc"
+ assert response.sort_mode == expected_sort
assert response.partition_keys == ["created_at"]
assert response.partition_mode == "datetime"
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
index d8a9df58a499..d1b2d2166cc0 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/zep/zep.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/zep/zep.py
@@ -8,6 +8,8 @@ import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import (
make_tracked_session,
retry_with_deadline,
@@ -24,13 +26,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.zep.settin
# any Retry-After the API sends on a 429.
REQUEST_TIMEOUT_SECONDS = 60
MAX_RETRIES = 5
+# The graph list endpoints return a bare JSON list and send the next page's cursor in this header.
+NEXT_CURSOR_HEADER = "Zep-Next-Cursor"
class ZepRetryableError(Exception):
pass
[email protected](frozen=True)
class ZepResumeConfig:
# Page-based endpoints (users, threads): the next 1-based page to fetch.
page_number: int | None = None
@@ -39,6 +43,19 @@ class ZepResumeConfig:
# 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
+ # Graph fan-out (graph_edges, graph_nodes, graph_episodes): the graph to resume at and the
+ # opaque page cursor within it. None for the cursor means the first page of that graph.
+ graph_scope: str | None = None
+ graph_owner_id: str | None = None
+ graph_cursor: str | None = None
+ # Set once the last graph's rows are all yielded, so a resume after that reads nothing again.
+ graph_finished: bool = False
+
+
+@frozen
+class GraphOwner:
+ scope: str # "user" or "graph"
+ owner_id: str
def _headers(api_key: str) -> dict[str, str]:
@@ -55,7 +72,7 @@ def _build_url(path: str, params: dict[str, Any]) -> str:
return f"{url}?{urlencode(params)}"
-@retry_with_deadline(
+_retry_request = retry_with_deadline(
retry=retry_if_exception_type(
(
ZepRetryableError,
@@ -68,6 +85,9 @@ def _build_url(path: str, params: dict[str, Any]) -> str:
wait=wait_exponential_jitter(initial=1, max=30),
reraise=True,
)
+
+
+@_retry_request
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)
@@ -83,6 +103,26 @@ def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], lo
return response.json()
+@_retry_request
+def _post_graph_page(
+ session: requests.Session, url: str, headers: dict[str, str], body: dict[str, Any], logger: FilteringBoundLogger
+) -> tuple[list[dict[str, Any]], str | None] | None:
+ """POST one page of a graph list endpoint. Returns the rows and the next cursor, or None on a 404."""
+ response = session.post(url, headers=headers, json=body, 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 response.status_code == 404:
+ return None
+
+ if not response.ok:
+ logger.error(f"Zep API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json() or [], response.headers.get(NEXT_CURSOR_HEADER) or None
+
+
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.
@@ -250,6 +290,135 @@ def _fan_out_message_rows(
cursor = 0 # only the resumed-into thread uses the saved cursor
+def _iter_ids(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger, endpoint: str, id_field: str
+) -> Iterator[str]:
+ """Lazily page a page-numbered list endpoint (users, graphs), yielding one id at a time."""
+ config = ZEP_ENDPOINTS[endpoint]
+ assert config.page_number_param is not None and config.page_size_param is not None
+ page_number = 1
+ seen = 0
+ while True:
+ params: dict[str, Any] = {
+ config.page_size_param: config.page_size,
+ config.page_number_param: page_number,
+ "order_by": "created_at",
+ "asc": "true",
+ }
+ data = _fetch_page(session, _build_url(config.path, params), headers, logger)
+ items = data.get(config.data_key) or []
+ if not items:
+ break
+ for item in items:
+ item_id = item.get(id_field)
+ if item_id:
+ yield item_id
+ seen += 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
+ page_number += 1
+
+
+def _iter_graph_owners(
+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger
+) -> Iterator[GraphOwner]:
+ """Yield every user graph, then every standalone graph."""
+ for user_id in _iter_ids(session, headers, logger, "users", "user_id"):
+ yield GraphOwner(scope="user", owner_id=user_id)
+ for graph_id in _iter_ids(session, headers, logger, "graphs", "graph_id"):
+ yield GraphOwner(scope="graph", owner_id=graph_id)
+
+
+def _graph_row(item: dict[str, Any], scope: str, owner_id: str) -> dict[str, Any]:
+ return {
+ **item,
+ "graph_scope": scope,
+ "graph_owner_id": owner_id,
+ "user_id": owner_id if scope == "user" else None,
+ "graph_id": owner_id if scope == "graph" else None,
+ }
+
+
+def _fan_out_graph_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 user graph and standalone graph, yielding the graph's edges, nodes or episodes."""
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.graph_finished:
+ return
+
+ owners: Iterator[GraphOwner] = iter(_iter_graph_owners(session, headers, logger))
+ resume_cursor: str | None = None
+
+ if resume is not None and resume.graph_scope is not None and resume.graph_owner_id is not None:
+ target = GraphOwner(scope=resume.graph_scope, owner_id=resume.graph_owner_id)
+ for owner in owners:
+ if owner == target:
+ break
+ else:
+ logger.warning(f"Zep: resume graph {target} no longer present, ending {config.name}")
+ return
+ owners = itertools.chain([target], owners)
+ resume_cursor = resume.graph_cursor
+
+ def _stage_next_owner(nxt: GraphOwner | None) -> None:
+ if nxt is None:
+ resumable_source_manager.save_state(ZepResumeConfig(graph_finished=True))
+ else:
+ resumable_source_manager.save_state(ZepResumeConfig(graph_scope=nxt.scope, graph_owner_id=nxt.owner_id))
+
+ # One owner of lookahead so the bookmark can point at the next graph before its rows exist.
+ current = next(owners, None)
+ while current is not None:
+ nxt = next(owners, None)
+ scope, owner_id = current.scope, current.owner_id
+ # user_id and graph_id are user-defined strings; escape path-significant characters.
+ path = config.path.format(scope=scope, owner_id=quote(owner_id, safe=""))
+ cursor, resume_cursor = resume_cursor, None
+
+ while True:
+ body: dict[str, Any] = {"limit": config.page_size, "order_by": "created_at", "direction": "asc"}
+ if cursor:
+ body["cursor"] = cursor
+
+ page = _post_graph_page(session, _build_url(path, {}), headers, body, logger)
+ if page is None:
+ # The user or graph was deleted after we listed it.
+ logger.warning(f"Zep: {config.name} for {scope} {owner_id} returned 404, skipping")
+ items: list[dict[str, Any]] = []
+ next_cursor = None
+ else:
+ items, next_cursor = page
+ if next_cursor == cursor:
+ # A repeated cursor would loop forever on the same page.
+ next_cursor = None
+
+ if not items:
+ _stage_next_owner(nxt)
+ resumable_source_manager.safe_point()
+ break
+
+ if next_cursor:
+ resumable_source_manager.save_state(
+ ZepResumeConfig(graph_scope=scope, graph_owner_id=owner_id, graph_cursor=next_cursor)
+ )
+ else:
+ _stage_next_owner(nxt)
+
+ yield [_graph_row(item, scope, owner_id) for item in items]
+
+ if not next_cursor:
+ break
+ cursor = next_cursor
+
+ current = nxt
+
+
def get_rows(
api_key: str,
endpoint: str,
@@ -267,6 +436,8 @@ def get_rows(
if config.fan_out_over_threads:
yield from _fan_out_message_rows(session, headers, logger, resumable_source_manager, config)
+ elif config.fan_out_over_graphs:
+ yield from _fan_out_graph_rows(session, headers, logger, resumable_source_manager, config)
else:
yield from _page_based_rows(session, headers, logger, resumable_source_manager, config)
@@ -288,8 +459,9 @@ def zep_source(
resumable_source_manager=resumable_source_manager,
),
primary_keys=config.primary_keys,
- # Rows arrive oldest-first (created_at ascending / message cursor order).
- sort_mode="asc",
+ # Rows arrive oldest-first (created_at ascending / message cursor order). The graph fan-out
+ # restarts the order for each graph, so it is not one ordered series.
+ sort_mode=None if config.fan_out_over_graphs else "asc",
partition_count=1,
partition_size=1,
partition_mode="datetime" if config.partition_key else None,