: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(warehouse_sources): add mem0 memory history, organizations and projects tables (#115047)
Tom Owers8fa0c9dd8a50
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.mdindex 0035cf9439d6..f8ee3419565c 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@@ -5502,15 +5502,15 @@ Note: Read the vendor SDK's controller docs (32 controllers) and enumerated the## Mem0 — gaps-Today (3): `entities`, `events`, `memories`+Today (6): `entities`, `events`, `memories`, `memory_history`, `organizations`, `projects`Diffed against: <https://docs.mem0.ai/openapi.json>-- [ ] `GET /v1/memories/{memory_id}/history/` — Per-memory state transition history - how a memory was updated over time (high)-- [ ] `GET /v1/stats/` — Aggregate memory/search/add counts, the product's headline usage metric (medium)-- [ ] `GET /api/v1/orgs/organizations/{org_id}/projects/` — Lookup table resolving the project scope that memories and events belong to (medium)+- [x] `GET /v1/memories/{memory_id}/history/` — Per-memory state transition history - how a memory was updated over time (high). Added as `memory_history` (fan-out over `memories`).+- ~~`GET /v1/stats/`~~ — skipped: it returns one unkeyed, untimestamped object of running totals, so a table of it holds a single row whose meaning depends on when the sync ran. The memory, entity and add/search counts come from queries over `memories`, `entities` and `events`.+- [x] `GET /api/v1/orgs/organizations/{org_id}/projects/` — Lookup table resolving the project scope that memories and events belong to (medium). Added as `projects` (fan-out over `organizations`).- [ ] `GET /api/v1/orgs/organizations/{org_id}/members/` — Org membership rows for attributing memory activity to people (low)-- [ ] `GET /api/v1/orgs/organizations/` — Parent lookup for the projects and members tables (low)+- [x] `GET /api/v1/orgs/organizations/` — Parent lookup for the projects and members tables (low). Added as `organizations`.Note: Mem0 publishes a real OpenAPI spec (33 paths, linked from https://docs.mem0.ai/llms.txt). Most non-covered paths are POST-only write/search operations, so the readable surface is genuinely small and the existing 3 tables cover the bulk of it.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/canonical_descriptions.pyindex 0f5b1e4d7eb3..26485d32c00f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/canonical_descriptions.py@@ -55,4 +55,53 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"latency": "Processing time in milliseconds.",},},+ "memory_history": {+ "description": "One change to a memory (add, update, or delete), with the memory text before and after.",+ "docs_url": "https://docs.mem0.ai/api-reference/memory/history-memory",+ "columns": {+ "id": "Unique identifier (UUID) for the history entry.",+ "memory_id": "Identifier of the memory this entry belongs to.",+ "input": "The conversation messages that led to this memory change.",+ "old_memory": "The memory text before the change, if any.",+ "new_memory": "The memory text after the change.",+ "event": "The type of change: ADD, UPDATE, or DELETE.",+ "user_id": "The user associated with the memory.",+ "agent_id": "The agent associated with the memory, if any.",+ "app_id": "The app associated with the memory, if any.",+ "session_id": "The run associated with the memory, if any.",+ "categories": "Categories of the memory at this point in its history.",+ "metadata": "Additional metadata attached to the change.",+ "created_at": "Time at which the history entry was created.",+ "updated_at": "Time at which the history entry was last updated.",+ },+ },+ "organizations": {+ "description": "A Mem0 organization that the API key's owner belongs to.",+ "docs_url": "https://docs.mem0.ai/api-reference/organization/get-orgs",+ "columns": {+ "org_id": "Unique identifier for the organization.",+ "name": "Name of the organization.",+ "members": "Members of the organization, with their roles.",+ "is_default": "Whether this is the caller's default organization.",+ "is_owner": "Whether the caller owns the organization.",+ "user_role": "The caller's role in the organization.",+ "created_at": "Time at which the organization was created.",+ "updated_at": "Time at which the organization was last updated.",+ },+ },+ "projects": {+ "description": "A Mem0 project, the scope that memories and events belong to.",+ "docs_url": "https://docs.mem0.ai/api-reference/project/get-projects",+ "columns": {+ "org_id": "Identifier of the organization the project belongs to.",+ "project_id": "Unique identifier for the project.",+ "name": "Name of the project.",+ "description": "Description of the project.",+ "members": "Members of the project, with their roles.",+ "custom_instructions": "Custom instructions for memory processing in the project.",+ "custom_categories": "Custom categories for memory categorization in the project.",+ "created_at": "Time at which the project was created.",+ "updated_at": "Time at which the project was last updated.",+ },+ },}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.pyindex 61dcc6296e23..97fad6640413 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,7 +8,7 @@ it is redacted from logs and raised error messages."""import dataclasses-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optionalfrom urllib.parse import urljoin, urlparse@@ -20,12 +20,19 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.httfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (RESTAPIConfig,rest_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 (JSONResponsePaginator,SinglePagePaginator,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -35,6 +42,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mem0.settiMEM0_BASE_URL,MEM0_ENDPOINTS,MEMORIES_ENDPOINT,+ MEMORY_HISTORY_ENDPOINT,+ ORGANIZATIONS_ENDPOINT,+ PROJECTS_ENDPOINT,)logger = structlog.get_logger(__name__)@@ -196,6 +206,14 @@ def mem0_source(resource = _entities_resource(client, team_id, job_id, org_id, project_id)elif endpoint == EVENTS_ENDPOINT:resource = _events_resource(client, team_id, job_id, resumable_source_manager, resume)+ elif endpoint == MEMORY_HISTORY_ENDPOINT:+ resource = _memory_history_resource(+ client, team_id, job_id, should_use_incremental_field, db_incremental_field_last_value+ )+ elif endpoint == ORGANIZATIONS_ENDPOINT:+ resource = _organizations_resource(client, team_id, job_id)+ elif endpoint == PROJECTS_ENDPOINT:+ resource = _projects_resource(client, team_id, job_id)else:raise ValueError(f"Unknown Mem0 endpoint: {endpoint}")@@ -260,8 +278,6 @@ def _memories_resource(db_incremental_field_last_value: Any,incremental_field: str | None,) -> Any:- config = MEM0_ENDPOINTS[MEMORIES_ENDPOINT]-# On resume the pinned cutoff (not a freshly computed one) drives the filter, otherwise the# resumed run paginates a different server-side result set than the pages already fetched.if resume is not None and resume.next_url:@@ -277,6 +293,37 @@ def _memories_resource(filters = _build_memories_filters(incremental_field or "updated_at", cutoff)+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields+ # the last page (the merge dedupes) rather than skipping it. The cutoff is pinned so a+ # resumed run filters on the same value the original run started with.+ if state and state.get("next_url"):+ resumable_source_manager.save_state(+ Mem0ResumeConfig(endpoint=MEMORIES_ENDPOINT, next_url=state["next_url"], cutoff=cutoff)+ )++ return _memories_pages(+ client,+ team_id,+ job_id,+ filters,+ db_incremental_field_last_value,+ resume_hook=save_checkpoint,+ initial_paginator_state=initial_paginator_state,+ )+++def _memories_pages(+ client: ClientConfig,+ team_id: int,+ job_id: str,+ filters: dict[str, Any],+ db_incremental_field_last_value: Any,+ resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,+ initial_paginator_state: dict[str, Any] | None = None,+) -> Iterator[list[Any]]:+ config = MEM0_ENDPOINTS[MEMORIES_ENDPOINT]+rest_config: RESTAPIConfig = {"client": client,"resource_defaults": {},@@ -295,21 +342,12 @@ def _memories_resource(],}- def save_checkpoint(state: Optional[dict[str, Any]]) -> None:- # Persist only when a next page remains; save AFTER a page is yielded so a crash re-yields- # the last page (the merge dedupes) rather than skipping it. The cutoff is pinned so a- # resumed run filters on the same value the original run started with.- if state and state.get("next_url"):- resumable_source_manager.save_state(- Mem0ResumeConfig(endpoint=MEMORIES_ENDPOINT, next_url=state["next_url"], cutoff=cutoff)- )-resource = rest_api_resource(rest_config,team_id,job_id,db_incremental_field_last_value,- resume_hook=save_checkpoint,+ resume_hook=resume_hook,initial_paginator_state=initial_paginator_state,)@@ -388,3 +426,105 @@ def _events_resource(resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)+++def _memory_history_resource(+ client: ClientConfig,+ team_id: int,+ job_id: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> Any:+ # The history endpoint takes no filters, so an incremental run only visits memories updated+ # since the watermark: every history entry also moves its memory's `updated_at`. Deleted+ # memories leave the listing, so their history is out of reach either way.+ cutoff = (+ _format_cutoff(db_incremental_field_last_value)+ if should_use_incremental_field and db_incremental_field_last_value+ else None+ )+ filters = _build_memories_filters("updated_at", cutoff)+ config = MEM0_ENDPOINTS[MEMORY_HISTORY_ENDPOINT]++ # No resume hook: fan-out resume state lists every finished parent, which grows with the+ # memory store. A restarted run re-reads the history and the merge dedupes it.+ rest_config: RESTAPIConfig = {+ "client": client,+ "resource_defaults": {},+ "resources": [+ {+ "name": MEMORIES_ENDPOINT,+ "endpoint": {"path": MEM0_ENDPOINTS[MEMORIES_ENDPOINT].path, "method": "POST"},+ "data_iterator": lambda: _memories_pages(client, team_id, job_id, filters, None),+ },+ {+ "name": MEMORY_HISTORY_ENDPOINT,+ "table_name": MEMORY_HISTORY_ENDPOINT,+ "write_disposition": (+ {"disposition": "merge", "strategy": "upsert"} if should_use_incremental_field else "replace"+ ),+ "endpoint": {+ "path": config.path,+ "method": "GET",+ "params": {"memory_id": {"type": "resolve", "resource": MEMORIES_ENDPOINT, "field": "id"}},+ "paginator": SinglePagePaginator(),+ # A memory deleted between the listing and its history fetch.+ "response_actions": [{"status_code": 404, "action": "ignore"}],+ },+ },+ ],+ }++ return _child_resource(rest_config, MEMORY_HISTORY_ENDPOINT, team_id, job_id)+++def _organizations_config() -> EndpointResource:+ return {+ "name": ORGANIZATIONS_ENDPOINT,+ "endpoint": {+ "path": MEM0_ENDPOINTS[ORGANIZATIONS_ENDPOINT].path,+ "method": "GET",+ "paginator": SinglePagePaginator(),+ },+ }+++def _organizations_resource(client: ClientConfig, team_id: int, job_id: str) -> Any:+ rest_config: RESTAPIConfig = {+ "client": client,+ "resource_defaults": {},+ "resources": [_organizations_config()],+ }++ return rest_api_resource(rest_config, team_id, job_id, None)+++def _projects_resource(client: ClientConfig, team_id: int, job_id: str) -> Any:+ rest_config: RESTAPIConfig = {+ "client": client,+ "resource_defaults": {},+ "resources": [+ _organizations_config(),+ {+ "name": PROJECTS_ENDPOINT,+ "table_name": PROJECTS_ENDPOINT,+ "write_disposition": "replace",+ "include_from_parent": ["org_id"],+ "endpoint": {+ "path": MEM0_ENDPOINTS[PROJECTS_ENDPOINT].path,+ "method": "GET",+ "params": {"org_id": {"type": "resolve", "resource": ORGANIZATIONS_ENDPOINT, "field": "org_id"}},+ "paginator": SinglePagePaginator(),+ },+ },+ ],+ }++ return _child_resource(rest_config, PROJECTS_ENDPOINT, team_id, job_id).add_map(+ rename_parent_fields(ORGANIZATIONS_ENDPOINT, {"org_id": "org_id"})+ )+++def _child_resource(rest_config: RESTAPIConfig, name: str, team_id: int, job_id: str) -> Any:+ resources = rest_api_resources(rest_config, team_id, job_id, None)+ return next(r for r in resources if getattr(r, "name", None) == name)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/settings.pyindex e2ea561e3996..c0631109f63b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/settings.py@@ -10,6 +10,12 @@ Reference: https://docs.mem0.ai/api-referencepagination or timestamp filters), so it's full refresh only.- ``events``: GET /v1/events/ — ``{count, next, previous, results}`` envelope followed via the``next`` URL. No documented timestamp filters, so full refresh only.+- ``memory_history``: GET /v1/memories/{memory_id}/history/ — a bare array per memory, fanned out+ over the memories listing. The child has no filters, so incremental syncs bound the fan-out by+ filtering the memories listing on ``updated_at`` instead.+- ``organizations``: GET /api/v1/orgs/organizations/ — a bare array, no pagination.+- ``projects``: GET /api/v1/orgs/organizations/{org_id}/projects/ — a bare array per organization,+ fanned out over the organizations listing."""from dataclasses import dataclass, field@@ -32,11 +38,12 @@ DEFAULT_VERSION = MEM0_API_VERSION_V3MEMORIES_ENDPOINT = "memories"ENTITIES_ENDPOINT = "entities"EVENTS_ENDPOINT = "events"+MEMORY_HISTORY_ENDPOINT = "memory_history"+ORGANIZATIONS_ENDPOINT = "organizations"+PROJECTS_ENDPOINT = "projects"-_DATETIME_INCREMENTAL_FIELD_NAMES = ("updated_at", "created_at")--def _datetime_incremental_fields() -> list[IncrementalField]:+def _datetime_incremental_fields(*names: str) -> list[IncrementalField]:return [{"label": name,@@ -44,7 +51,7 @@ def _datetime_incremental_fields() -> list[IncrementalField]:"field": name,"field_type": IncrementalFieldType.DateTime,}- for name in _DATETIME_INCREMENTAL_FIELD_NAMES+ for name in names]@@ -68,7 +75,7 @@ MEM0_ENDPOINTS: dict[str, Mem0EndpointConfig] = {path="/v3/memories/",method="POST",partition_key="created_at",- incremental_fields=_datetime_incremental_fields(),+ incremental_fields=_datetime_incremental_fields("updated_at", "created_at"),page_size=100,),ENTITIES_ENDPOINT: Mem0EndpointConfig(@@ -85,6 +92,28 @@ MEM0_ENDPOINTS: dict[str, Mem0EndpointConfig] = {partition_key="created_at",should_sync_default=False,),+ # Opt-in: one request per memory, so it costs far more API calls than the memories table.+ MEMORY_HISTORY_ENDPOINT: Mem0EndpointConfig(+ name=MEMORY_HISTORY_ENDPOINT,+ path="/v1/memories/{memory_id}/history/",+ method="GET",+ partition_key="created_at",+ incremental_fields=_datetime_incremental_fields("created_at"),+ should_sync_default=False,+ ),+ ORGANIZATIONS_ENDPOINT: Mem0EndpointConfig(+ name=ORGANIZATIONS_ENDPOINT,+ path="/api/v1/orgs/organizations/",+ method="GET",+ primary_keys=["org_id"],+ ),+ PROJECTS_ENDPOINT: Mem0EndpointConfig(+ name=PROJECTS_ENDPOINT,+ path="/api/v1/orgs/organizations/{org_id}/projects/",+ method="GET",+ # Project rows carry no org id, so the fan-out adds it and the key includes it.+ primary_keys=["org_id", "project_id"],+ ),}ENDPOINTS = tuple(MEM0_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/source.pyindex 3416b47dd38a..f5ea3e06c951 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mem0/source.py@@ -31,7 +31,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mem0.settiENDPOINTS,INCREMENTAL_FIELDS,MEM0_ENDPOINTS,- MEMORIES_ENDPOINT,SUPPORTED_VERSIONS,)from products.warehouse_sources.backend.types import ExternalDataSourceType@@ -68,7 +67,7 @@ class Mem0Source(ResumableSource[Mem0SourceConfig, Mem0ResumeConfig]):name=ExternalDataSourceType.MEM0,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Mem0",- caption="""Enter your Mem0 API key to automatically pull your Mem0 memories, entities, and operation events into the PostHog Data warehouse.+ caption="""Enter your Mem0 API key to automatically pull your Mem0 memories, memory history, entities, operation events, organizations, and projects into the PostHog Data warehouse.You can find your API key in the [Mem0 dashboard](https://app.mem0.ai/dashboard/api-keys).""",iconPath="/static/services/mem0.svg",@@ -175,7 +174,7 @@ You can find your API key in the [Mem0 dashboard](https://app.mem0.ai/dashboard/job_id=inputs.job_id,resumable_source_manager=resumable_source_manager,should_use_incremental_field=inputs.should_use_incremental_field- and inputs.schema_name == MEMORIES_ENDPOINT,+ and bool(INCREMENTAL_FIELDS.get(inputs.schema_name)),db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,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.pyindex 15c2e0cf01f2..711c7c274d09 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@@ -22,6 +22,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mem0.settiEVENTS_ENDPOINT,MEM0_BASE_URL,MEMORIES_ENDPOINT,+ MEMORY_HISTORY_ENDPOINT,+ PROJECTS_ENDPOINT,)# RESTClient builds its session via make_tracked_session in the rest_client module.@@ -233,6 +235,71 @@ class TestEntitiesRows:assert _query(prepared[0]) == expected_query+class TestMemoryHistoryRows:+ @parameterized.expand(+ [+ ("full_refresh", False, None, _MATCH_ALL_FILTER),+ # The child takes no filters, so the watermark bounds the memories listing on+ # `updated_at`, whichever history field the user picked as the cursor.+ (+ "incremental",+ True,+ datetime(2026, 7, 1, 12, 30, tzinfo=UTC),+ {"AND": [_MATCH_ALL_FILTER, {"updated_at": {"gte": "2026-07-01"}}]},+ ),+ ]+ )+ def test_fans_out_over_every_memories_page(self, _name, incremental, last_value, expected_filters):+ next_url = f"{MEM0_BASE_URL}/v3/memories/?page=2&page_size=100"+ rows, prepared = _run(+ MEMORY_HISTORY_ENDPOINT,+ [+ _response([{"id": "m1"}, {"id": "m2"}], next_url=next_url),+ _raw_response([{"id": "h1", "memory_id": "m1", "event": "ADD"}]),+ # A memory deleted between the listing and its history fetch.+ _raw_response({"detail": "Not found"}, status=404),+ _response([{"id": "m3"}], next_url=None),+ _raw_response([{"id": "h3", "memory_id": "m3", "event": "UPDATE"}]),+ ],+ _manager(),+ should_use_incremental_field=incremental,+ db_incremental_field_last_value=last_value,+ incremental_field="created_at",+ )++ assert [row["id"] for row in rows] == ["h1", "h3"]+ assert _body(prepared[0]) == {"filters": expected_filters}+ assert [urlsplit(p.url).path for p in prepared[1:]] == [+ "/v1/memories/m1/history/",+ "/v1/memories/m2/history/",+ "/v3/memories/",+ "/v1/memories/m3/history/",+ ]+++class TestProjectsRows:+ def test_fans_out_over_organizations_and_tags_rows_with_the_org_id(self):+ rows, prepared = _run(+ PROJECTS_ENDPOINT,+ [+ _raw_response([{"org_id": "org_1", "name": "One"}, {"org_id": "org_2", "name": "Two"}]),+ _raw_response([{"project_id": "proj_a", "name": "A"}]),+ _raw_response([{"project_id": "proj_b", "name": "B"}]),+ ],+ _manager(),+ )++ assert rows == [+ {"project_id": "proj_a", "name": "A", "org_id": "org_1"},+ {"project_id": "proj_b", "name": "B", "org_id": "org_2"},+ ]+ assert [urlsplit(p.url).path for p in prepared] == [+ "/api/v1/orgs/organizations/",+ "/api/v1/orgs/organizations/org_1/projects/",+ "/api/v1/orgs/organizations/org_2/projects/",+ ]++class TestEventsRows:def test_follows_next_urls_and_checkpoints_after_each_yield(self):next_url = f"{MEM0_BASE_URL}/v1/events/?page=2"