:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): sync Convex non-default component tables (#67078)
Luke Belton13fe34eb9f45
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.pyindex 787babbae20a..f99008ea3f0c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/convex.py@@ -100,6 +100,15 @@ def _headers(deploy_key: str) -> dict[str, str]:}+# Convex tables can live in non-default components (e.g. an installed `betterAuth` component), which+# the streaming-export API addresses by component path (the root component is the empty path). We+# encode `(component_path, table)` into one warehouse table name so component tables round-trip from+# the schema list back to the per-table API calls; root tables keep their bare name, so existing+# synced tables are unaffected.+_ROOT_COMPONENT = ""+_COMPONENT_TABLE_DELIMITER = "."++@retry(retry=retry_if_exception_type(ChunkedEncodingError),stop=stop_after_attempt(5),@@ -118,21 +127,71 @@ def _convex_get(url: str, deploy_key: str, params: dict[str, Any], timeout: int)def get_json_schemas(deploy_url: str, deploy_key: str) -> dict[str, Any]:url = f"{deploy_url.rstrip('/')}/api/json_schemas"- response = _convex_get(url, deploy_key, {"deltaSchema": "true", "format": "json"}, timeout=30)+ # byComponent=true groups the response by component so non-default components are discoverable.+ response = _convex_get(+ url, deploy_key, {"deltaSchema": "true", "format": "json", "byComponent": "true"}, timeout=30+ )response.raise_for_status()return response.json()+def iter_component_tables(schemas_response: dict[str, Any]) -> Generator[tuple[str, str]]:+ """Yield `(component_path, table_name)` for every table; root tables yield `""`.++ `byComponent=true` groups as {component_path: {table: schema}}; older deployments ignore the flag+ and return the flat {table: schema} shape, where each value is itself a JSON schema.+ """+ if not isinstance(schemas_response, dict) or not schemas_response:+ return+ # The grouped shape always includes the root component under the "" key, and "" is never a valid+ # table name — so its presence reliably marks the grouped shape. Only when it's absent do we fall+ # back to inspecting the first value (a {table: schema} map carries no "type"/"properties").+ if _ROOT_COMPONENT in schemas_response:+ grouped = True+ else:+ first_value = next(iter(schemas_response.values()))+ grouped = isinstance(first_value, dict) and "type" not in first_value and "properties" not in first_value+ if grouped:+ for component_path, tables in schemas_response.items():+ if isinstance(tables, dict):+ for table_name in tables:+ yield component_path, table_name+ else:+ for table_name in schemas_response:+ yield _ROOT_COMPONENT, table_name+++def qualified_table_name(component_path: str, table_name: str) -> str:+ """Encode a `(component_path, table_name)` pair into a single warehouse table name."""+ if not component_path:+ return table_name+ return f"{component_path}{_COMPONENT_TABLE_DELIMITER}{table_name}"+++def split_qualified_table_name(name: str) -> tuple[str, str]:+ """Inverse of `qualified_table_name` — returns `(component_path, table_name)`.++ Splits on the final ".": component path segments join with "/" and table names contain no ".".+ """+ component_path, delimiter, table_name = name.rpartition(_COMPONENT_TABLE_DELIMITER)+ if not delimiter:+ return _ROOT_COMPONENT, name+ return component_path, table_name++def list_snapshot(deploy_url: str,deploy_key: str,table_name: str,resumable_source_manager: ResumableSourceManager[ConvexResumeConfig],+ component: str = _ROOT_COMPONENT,) -> Generator[list[dict[str, Any]], None, int]:"""Paginate through a full table snapshot.Yields batches of documents. Returns the snapshot cursor (as the generator return value)which can be used as the starting cursor for document_deltas.++ A non-root `component` reads the table from that component; the root component is the default."""base_url = f"{deploy_url.rstrip('/')}/api/list_snapshot"# Convex returns the snapshot cursor as an opaque {tablet, id} string, not an integer.@@ -146,6 +205,8 @@ def list_snapshot(while True:params: dict[str, Any] = {"tableName": table_name, "format": "json"}+ if component:+ params["component"] = componentif cursor is not None:params["cursor"] = cursorif snapshot is not None:@@ -182,12 +243,15 @@ def document_deltas(table_name: str,cursor: int,resumable_source_manager: ResumableSourceManager[ConvexResumeConfig],+ component: str = _ROOT_COMPONENT,) -> Generator[list[dict[str, Any]], None, int]:"""Paginate through incremental document changes since a cursor.Yields batches of changed documents. Returns the new cursor.Deleted documents have _deleted=True.+ A non-root `component` reads the table from that component; the root component is the default.+Raises InvalidWindowError if the cursor is older than Convex's retention window (~30 days)."""base_url = f"{deploy_url.rstrip('/')}/api/document_deltas"@@ -210,6 +274,8 @@ def document_deltas(while True:params: dict[str, Any] = {"tableName": table_name, "cursor": current_cursor, "format": "json"}+ if component:+ params["component"] = componentresponse = _convex_get(base_url, deploy_key, params, timeout=60)@@ -289,16 +355,21 @@ def convex_source(resumable_source_manager: ResumableSourceManager[ConvexResumeConfig],) -> SourceResponse:clean_url = validate_deploy_url(deploy_url)+ # Decode the warehouse table name into component + bare table for the API; the qualified name+ # stays as the SourceResponse name so the Delta storage path is stable.+ component, convex_table_name = split_qualified_table_name(table_name)def items_generator():if should_use_incremental_field and db_incremental_field_last_value is not None:cursor = int(db_incremental_field_last_value)deltas_manager = resumable_source_manager.with_namespace(_DELTAS_RESUME_NAMESPACE)- for batch in document_deltas(clean_url, deploy_key, table_name, cursor, deltas_manager):+ for batch in document_deltas(+ clean_url, deploy_key, convex_table_name, cursor, deltas_manager, component=component+ ):yield _normalize_timestamps(batch)else:snapshot_manager = resumable_source_manager.with_namespace(_SNAPSHOT_RESUME_NAMESPACE)- for batch in list_snapshot(clean_url, deploy_key, table_name, snapshot_manager):+ for batch in list_snapshot(clean_url, deploy_key, convex_table_name, snapshot_manager, component=component):yield _normalize_timestamps(batch)return SourceResponse(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/source.pyindex 2ed4dce245e2..ac6468f09800 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/source.py@@ -21,6 +21,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.convex.conConvexResumeConfig,convex_source,get_json_schemas,+ iter_component_tables,+ qualified_table_name,validate_credentials as validate_convex_credentials,validate_deploy_url,)@@ -85,9 +87,10 @@ You can find your deployment URL and deploy key in your [Convex Dashboard](httpsclean_url = validate_deploy_url(config.deploy_url)schemas_response = get_json_schemas(clean_url, config.deploy_key)- tables: list[str] = []- if isinstance(schemas_response, dict):- tables = list(schemas_response.keys())+ tables: list[str] = [+ qualified_table_name(component_path, table_name)+ for component_path, table_name in iter_component_tables(schemas_response)+ ]incremental_field: list[IncrementalField] = [IncrementalField(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.pyindex 79c0073434d0..a9b9f20ed7ea 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/convex/tests/test_convex.py@@ -16,7 +16,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.convex.con_convex_get,convex_source,document_deltas,+ get_json_schemas,+ iter_component_tables,list_snapshot,+ qualified_table_name,+ split_qualified_table_name,validate_credentials,validate_deploy_url,)@@ -365,6 +369,109 @@ class TestConvexSource:assert first_params[key] == value+class TestComponentSupport:+ @parameterized.expand(+ [+ # Root-component tables keep their bare name so existing synced tables are unaffected.+ ("root", "", "users", "users"),+ ("single_component", "betterAuth", "users", "betterAuth.users"),+ # Convex nests component paths with "/"; the table name is still the segment after the+ # final ".", so the round-trip must recover the full path.+ ("nested_component", "parent/child", "users", "parent/child.users"),+ ]+ )+ def test_qualified_table_name_round_trips(+ self, _name: str, component_path: str, table_name: str, expected_qualified: str+ ) -> None:+ qualified = qualified_table_name(component_path, table_name)+ assert qualified == expected_qualified+ assert split_qualified_table_name(qualified) == (component_path, table_name)++ @parameterized.expand(+ [+ # byComponent shape: {component_path: {table: schema}} — root is the "" key.+ (+ "grouped_by_component",+ {+ "": {"users": {"type": "object"}, "messages": {"type": "object"}},+ "betterAuth": {"users": {"type": "object"}},+ },+ [("", "users"), ("", "messages"), ("betterAuth", "users")],+ ),+ # Legacy deployments ignore byComponent and return the flat {table: schema} shape; every+ # table is then a root-component table.+ (+ "legacy_flat",+ {"users": {"type": "object"}, "messages": {"type": "object"}},+ [("", "users"), ("", "messages")],+ ),+ # `type`/`properties` are valid Convex table names: the "" root key must classify the+ # response as grouped, not a schema-key inspection that misfires on such a table.+ (+ "grouped_with_table_named_type",+ {"": {"type": {"type": "object"}}, "betterAuth": {"users": {"type": "object"}}},+ [("", "type"), ("betterAuth", "users")],+ ),+ ("empty", {}, []),+ ]+ )+ def test_iter_component_tables(+ self, _name: str, schemas_response: dict[str, Any], expected: list[tuple[str, str]]+ ) -> None:+ assert sorted(iter_component_tables(schemas_response)) == sorted(expected)++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")+ def test_get_json_schemas_requests_by_component(self, mock_get: Mock) -> None:+ # Without byComponent=true the API returns only root-component tables, so non-default+ # components (e.g. betterAuth) become invisible — this guards against that regression.+ mock_get.return_value.get.return_value = _make_response({})++ get_json_schemas("https://x.convex.cloud", "key")++ assert mock_get.return_value.get.call_args.kwargs["params"]["byComponent"] == "true"++ @parameterized.expand(+ [+ # Root tables must not send a component param — the API defaults to the root component.+ ("root", "users", "users", None),+ # A component-qualified warehouse table name must read the bare table from its component.+ ("component", "betterAuth.users", "users", "betterAuth"),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")+ def test_convex_source_routes_to_component(+ self,+ _name: str,+ warehouse_table_name: str,+ expected_convex_table: str,+ expected_component: str | None,+ mock_get: Mock,+ ) -> None:+ manager = _make_manager(can_resume=False)+ mock_get.return_value.get.return_value = _make_response(+ {"values": [{"_id": "a", "_creationTime": 1}], "cursor": 1, "snapshot": 1, "hasMore": False}+ )++ response = convex_source(+ deploy_url="https://x.convex.cloud",+ deploy_key="key",+ table_name=warehouse_table_name,+ team_id=1,+ job_id="job",+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ resumable_source_manager=manager,+ )++ # The storage name stays qualified so the Delta path is stable per warehouse table.+ assert response.name == warehouse_table_name++ list(cast(Iterable[Any], response.items()))+ params = mock_get.return_value.get.call_args_list[0].kwargs["params"]+ assert params["tableName"] == expected_convex_table+ assert params.get("component") == expected_component++class TestConvexNonRetryableErrors:@patch("products.warehouse_sources.backend.temporal.data_imports.sources.convex.convex.make_tracked_session")def test_invalid_window_message_is_recognised_as_non_retryable(self, mock_get: Mock) -> None: