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.

fix(data-warehouse): stop mem0 memories sync at a page mem0 rejects (#103675)

Tom Owersf63ee831fcc6
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/mem0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/mem0.py
index ff5bcaaac5f5..61dcc6296e23 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/mem0.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/mem0.py
@@ -8,10 +8,14 @@ it is redacted from logs and raised error messages.
"""
import dataclasses
+from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
from urllib.parse import urljoin, urlparse
+import structlog
+from requests.exceptions import HTTPError
+
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.rest_source import (
RESTAPIConfig,
@@ -33,6 +37,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mem0.setti
MEMORIES_ENDPOINT,
)
+logger = structlog.get_logger(__name__)
+
# Every memory carries at least one owning entity id (user_id / agent_id / app_id / run_id are
# required at add time), so OR-ing the wildcard over all four matches the whole store. A bare
# {"user_id": "*"} would miss memories scoped only to an agent, app, or run.
@@ -210,6 +216,40 @@ def mem0_source(
)
+def _pages_until_page_rejected(resource: Any, *, resumed: bool) -> Iterator[list[Any]]:
+ """Yield the memories pages, ending the table when Mem0 rejects a page it told us to fetch.
+
+ Mem0 keeps putting a ``next`` link in the memories envelope past the point where it answers
+ that page with 400, so a store large enough to reach that page fails the whole sync and the
+ table never lands at all. Every request after the first targets a URL Mem0 itself handed us,
+ so a 400 there is Mem0 refusing to page deeper rather than a malformed request: finish the
+ table with the rows already read.
+
+ A 400 on the first request is a real request-validation failure (Mem0 documents a missing or
+ empty ``filters`` as the cause) and must still fail the run instead of syncing an empty table.
+ A resumed run starts on a saved ``next`` link, so its first request counts as a followed link.
+ """
+ followed_mem0_link = resumed
+ pages = iter(resource)
+ while True:
+ try:
+ page = next(pages)
+ except StopIteration:
+ return
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status != 400 or not followed_mem0_link:
+ raise
+ logger.warning(
+ "mem0.memories_pagination_rejected",
+ endpoint=MEMORIES_ENDPOINT,
+ status_code=status,
+ )
+ return
+ followed_mem0_link = True
+ yield page
+
+
def _memories_resource(
client: ClientConfig,
team_id: int,
@@ -264,7 +304,7 @@ def _memories_resource(
Mem0ResumeConfig(endpoint=MEMORIES_ENDPOINT, next_url=state["next_url"], cutoff=cutoff)
)
- return rest_api_resource(
+ resource = rest_api_resource(
rest_config,
team_id,
job_id,
@@ -273,6 +313,8 @@ def _memories_resource(
initial_paginator_state=initial_paginator_state,
)
+ return _pages_until_page_rejected(resource, resumed=initial_paginator_state is not None)
+
def _entities_resource(
client: ClientConfig,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/tests/test_mem0.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/tests/test_mem0.py
index 749a516d9f15..98451944935d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/tests/test_mem0.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/tests/test_mem0.py
@@ -203,6 +203,52 @@ class TestMemoriesRows:
assert _query(prepared[0])["page"] == ["1"]
+class TestMemoriesRejectedPage:
+ def test_a_rejected_next_page_ends_the_table_with_the_rows_already_read(self):
+ # Mem0 keeps putting a `next` link in the memories envelope past the page it answers with
+ # 400, so following it failed the whole sync and the table never landed.
+ next_url = f"{MEM0_BASE_URL}/v3/memories/?page=2&page_size=100"
+ rows, prepared = _run(
+ MEMORIES_ENDPOINT,
+ [_response([{"id": "m1"}], next_url=next_url), _response([], status=400)],
+ _manager(),
+ )
+
+ assert rows == [{"id": "m1"}]
+ assert len(prepared) == 2
+
+ def test_a_resumed_run_ends_the_table_when_its_saved_page_is_rejected(self):
+ # A resumed run's first request is Mem0's own saved `next` link, so a 400 there is the same
+ # refusal to page deeper rather than a bad request of ours.
+ saved_url = f"{MEM0_BASE_URL}/v3/memories/?page=21&page_size=100"
+ manager = _manager(Mem0ResumeConfig(endpoint=MEMORIES_ENDPOINT, next_url=saved_url, cutoff=None))
+
+ rows, prepared = _run(MEMORIES_ENDPOINT, [_response([], status=400)], manager)
+
+ assert rows == []
+ assert len(prepared) == 1
+
+ @parameterized.expand(
+ [
+ # A 400 on the first request is a request-validation failure (Mem0 documents an empty
+ # `filters` as the cause), not a page Mem0 sent us to — syncing an empty table would hide it.
+ ("bad_request_on_first_page", 400, True),
+ ("unauthorized_on_a_later_page", 401, False),
+ ("not_found_on_a_later_page", 404, False),
+ ]
+ )
+ def test_other_rejections_still_fail_the_sync(self, _name, status, on_first_request):
+ next_url = f"{MEM0_BASE_URL}/v3/memories/?page=2&page_size=100"
+ responses = (
+ [_response([], status=status)]
+ if on_first_request
+ else [_response([{"id": "m1"}], next_url=next_url), _response([], status=status)]
+ )
+
+ with pytest.raises(requests.HTTPError):
+ _run(MEMORIES_ENDPOINT, responses, _manager())
+
+
class TestCutoffFormatting:
@parameterized.expand(
[