: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): implement the neo4j import source (#113247)
Tom Owers4509c6746049
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 81e2520843e1..b6c4a858a6c8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -558,6 +558,7 @@ the row lists both.| n8n | HTTP | requests | ✅ || nager_date | HTTP | requests | ✅ || nebius_ai | HTTP | requests | ✅ |+| neo4j | HTTP | requests | ✅ || neon | DB protocol | psycopg (delegates to PostgresSource) | ➖ || netlify | HTTP | requests | ✅ || new_relic | HTTP (GraphQL/NerdGraph) | requests | ✅ |@@ -1291,7 +1292,6 @@ doesn't conflict with concurrent PRs.- nasa- nationbuilder- navan-- neo4j- neon_crm- netsuite- news_apidiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/neo4j.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/neo4j.pyindex 2c2322b7e6f4..2e0f09e65609 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/neo4j.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/neo4j.py@@ -6,4 +6,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass Neo4jSourceConfig(config.Config):- pass+ host: str+ database: str+ username: str+ password: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/canonical_descriptions.pynew file mode 100644index 000000000000..dcaeef3931df--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/canonical_descriptions.py@@ -0,0 +1,22 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalEndpoint,+)++NODE_DESCRIPTION: CanonicalEndpoint = {+ "description": "Nodes with this label, including their properties and labels.",+ "docs_url": "https://neo4j.com/docs/query-api/current/plain-json/",+ "columns": {+ "element_id": "The node identifier. Neo4j does not guarantee its identity across transactions.",+ "labels": "The labels attached to the node.",+ },+}++RELATIONSHIP_DESCRIPTION: CanonicalEndpoint = {+ "description": "Relationships of this type, including their properties and connected node identifiers.",+ "docs_url": "https://neo4j.com/docs/query-api/current/plain-json/",+ "columns": {+ "element_id": "The relationship identifier. Neo4j does not guarantee its identity across transactions.",+ "start_element_id": "The identifier of the start node.",+ "end_element_id": "The identifier of the end node.",+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/neo4j.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/neo4j.pynew file mode 100644index 000000000000..11d55be29e40--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/neo4j.py@@ -0,0 +1,150 @@+import re+from collections.abc import Iterator+from typing import Any+from urllib.parse import quote, urlsplit++from requests.auth import HTTPBasicAuth++from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import (+ DEFAULT_RETRY,+ make_tracked_session,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.neo4j import Neo4jSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.settings import (+ API_VERSION,+ MAX_ROWS_PER_SYNC,+ NON_RETRYABLE_ERRORS,+ PAGE_SIZE,+ REQUEST_TIMEOUT,+)+++class Neo4jQueryError(Exception):+ pass+++class Neo4jClient:+ def __init__(self, config: Neo4jSourceConfig, team_id: int) -> None:+ self.config = config+ self.team_id = team_id++ def query(self, statement: str, parameters: dict[str, int | str] | None = None) -> list[dict[str, Any]]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import (+ ValidateDatabaseHostMixin, # noqa: PLC0415 - Keep Django models off the config import path.+ )++ host = self.config.host+ try:+ parsed = urlsplit(host)+ valid_url = (+ parsed.scheme == "https"+ and bool(parsed.hostname)+ and parsed.username is None+ and parsed.password is None+ and parsed.path in ("", "/")+ and not parsed.query+ and not parsed.fragment+ and (parsed.port is None or 1 <= parsed.port <= 65535)+ and not any(character.isspace() or character == "\\" for character in host)+ )+ except ValueError:+ valid_url = False+ if not valid_url:+ raise ValueError("Invalid Neo4j host")+ assert parsed.hostname is not None+ valid_host, _ = ValidateDatabaseHostMixin().is_database_host_valid(parsed.hostname, self.team_id)+ if not valid_host:+ raise ValueError("Invalid Neo4j host")+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]*", self.config.database):+ raise ValueError("Invalid Neo4j database")+ url = f"{host.rstrip('/')}/db/{quote(self.config.database, safe='')}/query/{API_VERSION}"+ with make_tracked_session(+ retry=DEFAULT_RETRY.new(allowed_methods=frozenset({"POST"})),+ headers={"Accept": "application/json"},+ redact_values=(self.config.password,),+ allow_redirects=False,+ ) as session:+ response = session.post(+ url,+ auth=HTTPBasicAuth(self.config.username, self.config.password),+ json={"statement": statement, "parameters": parameters or {}, "accessMode": "Read"},+ timeout=REQUEST_TIMEOUT,+ )+ if 300 <= response.status_code < 400:+ raise ValueError("Neo4j redirects are not allowed")+ response.raise_for_status()+ payload = response.json()+ if payload.get("errors"):+ codes = [str(error.get("code", "Unknown")) for error in payload["errors"]]+ raise Neo4jQueryError("Neo4j query failed: " + ", ".join(codes))+ data = payload["data"]+ return [dict(zip(data["fields"], values, strict=True)) for values in data["values"]]++ def discover_tables(self) -> list[str]:+ labels = self.query("CALL db.labels() YIELD label RETURN label ORDER BY label")+ relationships = self.query(+ "CALL db.relationshipTypes() YIELD relationshipType RETURN relationshipType ORDER BY relationshipType"+ )+ return [f"node_{row['label']}" for row in labels] + [f"rel_{row['relationshipType']}" for row in relationships]++ @staticmethod+ def table_query(table: str) -> str:+ prefix, separator, name = table.partition("_")+ if not separator or prefix not in ("node", "rel") or not name:+ raise ValueError("Invalid Neo4j table")+ identifier = "`" + name.replace("`", "``") + "`"+ # Cypher interprets Unicode escapes in identifiers. Parameters preserve names that contain backslashes.+ if prefix == "node":+ match = "MATCH (x) WHERE $name IN labels(x)" if "\\" in name else f"MATCH (x:{identifier})"+ fields = "labels(x) AS labels"+ else:+ match = "MATCH (a)-[x]->(b) WHERE type(x) = $name" if "\\" in name else f"MATCH (a)-[x:{identifier}]->(b)"+ fields = "elementId(a) AS start_element_id, elementId(b) AS end_element_id"+ return (+ f"{match} RETURN elementId(x) AS element_id, properties(x) AS properties, {fields} "+ "ORDER BY elementId(x) SKIP $offset LIMIT $limit"+ )++ def rows(self, table: str) -> Iterator[list[dict[str, Any]]]:+ statement = self.table_query(table)+ offset = 0+ while True:+ limit = min(PAGE_SIZE, MAX_ROWS_PER_SYNC - offset + 1)+ parameters: dict[str, int | str] = {"offset": offset, "limit": limit}+ if "\\" in table:+ parameters["name"] = table.partition("_")[2]+ page = self.query(statement, parameters)+ if offset + len(page) > MAX_ROWS_PER_SYNC:+ raise ValueError("Neo4j sync row limit exceeded")+ if not page:+ return+ rows = []+ for record in page:+ properties = record.pop("properties")+ if properties.keys() & record.keys():+ raise ValueError("Neo4j property conflicts with a reserved column name")+ rows.append({**properties, **record})+ yield rows+ offset += len(page)+ if len(page) < limit:+ return+++def validate_credentials(config: Neo4jSourceConfig, team_id: int) -> tuple[bool, str | None]:+ try:+ Neo4jClient(config, team_id).query("RETURN 1 AS ok")+ except Exception as error:+ for pattern, message in NON_RETRYABLE_ERRORS.items():+ if pattern in str(error):+ return False, message+ return False, "Could not connect to Neo4j. Check the host, database, and Query API availability."+ return True, None+++def neo4j_source(config: Neo4jSourceConfig, team_id: int, table: str) -> SourceResponse:+ client = Neo4jClient(config, team_id)+ client.table_query(table)+ return SourceResponse(+ name=table, items=lambda: client.rows(table), primary_keys=["element_id"], supports_resume=False+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/settings.pynew file mode 100644index 000000000000..31bd426cba8e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/settings.py@@ -0,0 +1,22 @@+API_VERSION = "v2"+PAGE_SIZE = 1_000+MAX_ROWS_PER_SYNC = 1_000_000+REQUEST_TIMEOUT = (10, 120)++NON_RETRYABLE_ERRORS = {+ "401 Client Error": "Neo4j authentication failed. Check your database username and password.",+ "403 Client Error": "Neo4j denied access. Ask your database administrator for read access.",+ "404 Client Error": "Neo4j Query API was not found. Check the host, database, and Query API configuration.",+ "Neo.ClientError.Security.Unauthorized": "Neo4j authentication failed. Check your database username and password.",+ "Neo.ClientError.Security.CredentialsExpired": "Your Neo4j password has expired. Change it before you connect.",+ "Neo.ClientError.Security.Forbidden": "Neo4j denied access. Ask your database administrator for read access.",+ "Neo.ClientError.Security.TokenExpired": "Your Neo4j credentials have expired. Update the connection credentials.",+ "Neo.ClientError.Database.DatabaseNotFound": "Neo4j could not find the database. Check the database name.",+ "Neo.ClientError.": "Neo4j rejected the query. Check the database permissions and Query API configuration.",+ "Neo4j sync row limit exceeded": "This Neo4j table exceeds the import limit of 1,000,000 rows. Select a smaller label or relationship type.",+ "Neo4j property conflicts": "A Neo4j property uses a reserved column name. Rename the property before importing this table.",+ "Invalid Neo4j host": "Enter a public HTTPS host without a path, query, or embedded credentials.",+ "Invalid Neo4j database": "Enter a valid Neo4j database name.",+ "Invalid Neo4j table": "Select a discovered Neo4j node label or relationship type.",+ "Neo4j redirects are not allowed": "Enter the final HTTPS address of your Neo4j server.",+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/source.pyindex 3345d669b913..5e66605860e7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/source.py@@ -1,26 +1,133 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ 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.sources.common.mixins import ValidateDatabaseHostMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.neo4j import Neo4jSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.canonical_descriptions import (+ NODE_DESCRIPTION,+ RELATIONSHIP_DESCRIPTION,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.neo4j import (+ Neo4jClient,+ neo4j_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.settings import (+ API_VERSION,+ NON_RETRYABLE_ERRORS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class Neo4jSource(SimpleSource[Neo4jSourceConfig]):+class Neo4jSource(SimpleSource[Neo4jSourceConfig], ValidateDatabaseHostMixin):+ supported_versions = (API_VERSION,)+ default_version = API_VERSION+ api_docs_url = "https://neo4j.com/docs/query-api/current/"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NEO4J+ @property+ def connection_host_fields(self) -> list[str]:+ return ["host"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return dict(NON_RETRYABLE_ERRORS)++ def validate_credentials(+ self,+ config: Neo4jSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(config, team_id)++ def get_schemas(+ self,+ config: Neo4jSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return [+ SourceSchema(+ name=name,+ supports_incremental=False,+ supports_append=False,+ detected_primary_keys=["element_id"],+ description=(NODE_DESCRIPTION if name.startswith("node_") else RELATIONSHIP_DESCRIPTION)["description"],+ )+ for name in Neo4jClient(config, team_id).discover_tables()+ if names is None or name in names+ ]++ def source_for_pipeline(self, config: Neo4jSourceConfig, inputs: SourceInputs) -> SourceResponse:+ return neo4j_source(config, inputs.team_id, inputs.schema_name)+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=ExternalDataSourceType.NEO4J,category=DataWarehouseSourceCategory.DATABASES,label="Neo4j",- keywords=["graph database", "cypher"],+ caption=(+ "Use the database credentials saved when you created your Aura instance, or ask your database administrator. "+ "Requires a public HTTPS endpoint with Query API enabled (Neo4j 5.19 or later). "+ "Imports support full refresh only, with a limit of 1,000,000 rows per table."+ ),+ keywords=["graph database", "cypher", "auradb"],iconPath="/static/services/neo4j.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="host",+ label="HTTPS host",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://your-instance.databases.neo4j.io",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="database",+ label="Database",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="neo4j",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="username",+ label="Username",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="neo4j",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="password",+ label="Password",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/tests/test_neo4j.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/tests/test_neo4j.pynew file mode 100644index 000000000000..6186dae2ad2f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/tests/test_neo4j.py@@ -0,0 +1,269 @@+import json+from collections.abc import Iterable, Iterator+from typing import Any, cast++import pytest+from unittest.mock import patch++from requests import PreparedRequest, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.neo4j import Neo4jSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.neo4j import (+ Neo4jClient,+ Neo4jQueryError,+ neo4j_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.source import Neo4jSource+++def config() -> Neo4jSourceConfig:+ return Neo4jSourceConfig(+ host="https://graph.example.com:7473/", database="neo4j", username="reader", password="test-password"+ )++[email protected](autouse=True)+def safe_host() -> Iterator[None]:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.ValidateDatabaseHostMixin.is_database_host_valid",+ return_value=(True, None),+ ):+ yield+++def transport() -> Iterator[tuple[list[PreparedRequest], list[tuple[int, dict[str, Any]]]]]:+ requests: list[PreparedRequest] = []+ replies: list[tuple[int, dict[str, Any]]] = []++ def send(_adapter: object, request: PreparedRequest, **_kwargs: object) -> Response:+ requests.append(request)+ status, payload = replies.pop(0)+ response = Response()+ response.status_code = status+ assert request.url is not None+ response.url = request.url+ response.request = request+ response._content = json.dumps(payload).encode()+ return response++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport.TrackedHTTPAdapter.send",+ new=send,+ ):+ yield requests, replies++[email protected]("prefix", ["node", "rel"])[email protected]("count", [0, 1, 2, 3, 4])+def test_full_refresh_pagination_and_rows(config: Neo4jSourceConfig, transport: Any, prefix: str, count: int) -> None:+ requests, replies = transport+ fields = (+ ["element_id", "properties", "labels"]+ if prefix == "node"+ else ["element_id", "properties", "start_element_id", "end_element_id"]+ )+ values = [+ [f"id-{index}", {"amount": index, "tags": ["example"], "created": "2026-01-01"}]+ + ([["Order", "Record"]] if prefix == "node" else ["start-1", "end-1"])+ for index in range(count)+ ]+ for offset in range(0, count + 1, 2):+ replies.append((202, {"data": {"fields": fields, "values": values[offset : offset + 2]}}))+ with patch("products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.neo4j.PAGE_SIZE", 2):+ result = neo4j_source(config, 1, f"{prefix}_Order")+ pages = cast(Iterable[list[dict[str, Any]]], result.items())+ rows = [row for page in pages for row in page]+ assert len(rows) == count+ assert [row["element_id"] for row in rows] == [f"id-{index}" for index in range(count)]+ for index, row in enumerate(rows):+ assert row["amount"] == index+ assert row["tags"] == ["example"]+ assert "properties" not in row+ if prefix == "node":+ assert row["labels"] == ["Order", "Record"]+ else:+ assert row["start_element_id"] == "start-1"+ assert row["end_element_id"] == "end-1"+ assert len(requests) == count // 2 + 1+ for index, request in enumerate(requests):+ assert request.method == "POST"+ assert request.url == "https://graph.example.com:7473/db/neo4j/query/v2"+ assert request.headers["Authorization"] == "Basic cmVhZGVyOnRlc3QtcGFzc3dvcmQ="+ assert request.headers["Accept"] == "application/json"+ body = json.loads(request.body)+ assert body["parameters"] == {"offset": index * 2, "limit": 2}+ assert body["accessMode"] == "Read"+ assert "ORDER BY elementId(x) SKIP $offset LIMIT $limit" in body["statement"]++[email protected]("prefix", ["node", "rel"])[email protected]("label", ["two words", "a`b", "x`) MATCH (secret) RETURN secret //", "日本語", r"x\u0060"])+def test_identifiers_are_quoted(config: Neo4jSourceConfig, transport: Any, prefix: str, label: str) -> None:+ requests, replies = transport+ replies.append((202, {"data": {"fields": [], "values": []}}))+ list(Neo4jClient(config, 1).rows(f"{prefix}_{label}"))+ body = json.loads(requests[0].body)+ statement = body["statement"]+ if "\\" in label:+ assert label not in statement+ assert body["parameters"]["name"] == label+ assert ("WHERE $name IN labels(x)" if prefix == "node" else "WHERE type(x) = $name") in statement+ else:+ escaped = label.replace("`", "``")+ assert f":`{escaped}`" in statement++[email protected]("table", ["", "nodes", "node_", "rel_", "other_Person"])+def test_invalid_table_does_not_send_request(config: Neo4jSourceConfig, transport: Any, table: str) -> None:+ with pytest.raises(ValueError, match="Invalid Neo4j table"):+ neo4j_source(config, 1, table)+ assert not transport[0]++[email protected]("count", [2, 3])+def test_row_cap_does_not_silently_truncate(config: Neo4jSourceConfig, transport: Any, count: int) -> None:+ requests, replies = transport+ replies.append(+ (+ 202,+ {+ "data": {+ "fields": ["element_id", "properties", "labels"],+ "values": [["id-0", {}, ["Person"]], ["id-1", {}, ["Person"]]],+ }+ },+ )+ )+ replies.append(+ (+ 202,+ {+ "data": {+ "fields": ["element_id", "properties", "labels"],+ "values": [["id-2", {}, ["Person"]]] if count == 3 else [],+ }+ },+ )+ )+ with (+ patch("products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.neo4j.PAGE_SIZE", 2),+ patch("products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.neo4j.MAX_ROWS_PER_SYNC", 2),+ ):+ iterator = Neo4jClient(config, 1).rows("node_Person")+ assert len(next(iterator)) == 2+ if count == 3:+ with pytest.raises(ValueError, match="Neo4j sync row limit exceeded"):+ next(iterator)+ else:+ assert list(iterator) == []+ assert json.loads(requests[-1].body)["parameters"] == {"offset": 2, "limit": 1}++[email protected]("key", ["element_id", "labels"])+def test_reserved_properties_fail_before_data_is_lost(config: Neo4jSourceConfig, transport: Any, key: str) -> None:+ transport[1].append(+ (+ 202,+ {+ "data": {+ "fields": ["element_id", "properties", "labels"],+ "values": [["id-1", {key: "property-value"}, ["Person"]]],+ }+ },+ )+ )+ with pytest.raises(ValueError, match="Neo4j property conflicts"):+ list(Neo4jClient(config, 1).rows("node_Person"))+++ ("status", "code", "message"),+ [+ (401, None, "authentication failed"),+ (403, None, "denied access"),+ (404, None, "Query API was not found"),+ (202, "Neo.ClientError.Security.Unauthorized", "authentication failed"),+ (202, "Neo.ClientError.Security.CredentialsExpired", "password has expired"),+ (202, "Neo.ClientError.Security.Forbidden", "denied access"),+ (202, "Neo.ClientError.Database.DatabaseNotFound", "could not find the database"),+ (202, "Neo.ClientError.Statement.SyntaxError", "rejected the query"),+ (503, None, "Could not connect"),+ (202, "Neo.TransientError.General.DatabaseUnavailable", "Could not connect"),+ (307, None, "final HTTPS address"),+ ],+)+def test_credential_error_mapping(+ config: Neo4jSourceConfig, transport: Any, status: int, code: str | None, message: str+) -> None:+ transport[1].append((status, {"errors": [{"code": code, "message": "private details"}]} if code else {}))+ valid, error = validate_credentials(config, 1)+ assert not valid+ assert error is not None and message in error+ assert "private details" not in error+ assert len(transport[0]) == 1+ if status == 503 or (code and code.startswith("Neo.TransientError")):+ assert not any(pattern in (code or "503 Client Error") for pattern in Neo4jSource().get_non_retryable_errors())+++def test_query_error_with_partial_data_is_not_imported(config: Neo4jSourceConfig, transport: Any) -> None:+ transport[1].append(+ (+ 202,+ {+ "data": {"fields": ["element_id", "properties"], "values": [["id-1", {}]]},+ "errors": [{"code": "Neo.TransientError.General.DatabaseUnavailable"}],+ },+ )+ )+ with pytest.raises(Neo4jQueryError):+ list(Neo4jClient(config, 1).rows("node_Person"))+++def test_credential_probe_is_one_cheap_query(config: Neo4jSourceConfig, transport: Any) -> None:+ transport[1].append((202, {"data": {"fields": ["ok"], "values": [[1]]}}))+ assert validate_credentials(config, 1) == (True, None)+ assert len(transport[0]) == 1+ assert json.loads(transport[0][0].body)["statement"] == "RETURN 1 AS ok"+++ "host",+ [+ "http://graph.example.com",+ "https://reader:[email protected]",+ "https://graph.example.com/path",+ "https://graph.example.com?query=1",+ "https://graph.example.com#fragment",+ "https://graph.example.com:wrong",+ "https://graph.example.com:99999",+ "https://graph.example.com\\@other.example.com",+ "https://graph.example.com\n",+ "neo4j+s://graph.example.com",+ "https://",+ "https://[broken",+ ],+)+def test_invalid_hosts_never_receive_credentials(config: Neo4jSourceConfig, transport: Any, host: str) -> None:+ config.host = host+ assert validate_credentials(config, 1)[0] is False+ assert not transport[0]+++def test_internal_host_is_rejected(config: Neo4jSourceConfig, transport: Any) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.ValidateDatabaseHostMixin.is_database_host_valid",+ return_value=(False, "Internal IP"),+ ) as check:+ assert validate_credentials(config, 1)[0] is False+ check.assert_called_once_with("graph.example.com", 1)+ assert not transport[0]++[email protected]("database", ["", "../system", "a/b", "a?query", "a#fragment"])+def test_invalid_database_is_rejected(config: Neo4jSourceConfig, transport: Any, database: str) -> None:+ config.database = database+ assert validate_credentials(config, 1) == (False, "Enter a valid Neo4j database name.")+ assert not transport[0]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/tests/test_neo4j_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/tests/test_neo4j_source.pynew file mode 100644index 000000000000..02053ce55f66--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/neo4j/tests/test_neo4j_source.py@@ -0,0 +1,46 @@+import json+from typing import Any++import pytest+from unittest.mock import patch++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.neo4j import Neo4jSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.neo4j.source import Neo4jSource++[email protected]("names", [None, [], ["node_Person"], ["rel_KNOWS"], ["missing"]])+def test_live_schema_discovery_and_filtering(names: list[str] | None) -> None:+ payloads: list[dict[str, Any]] = [+ {"data": {"fields": ["label"], "values": [["Person"], ["Person_Record"], ["two words"]]}},+ {"data": {"fields": ["relationshipType"], "values": [["KNOWS"], ["Person"]]}},+ ]+ responses = []+ for payload in payloads:+ response = Response()+ response.status_code = 202+ response._content = json.dumps(payload).encode()+ responses.append(response)+ config = Neo4jSourceConfig(+ host="https://graph.example.com", database="neo4j", username="reader", password="test-password"+ )+ with (+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins.ValidateDatabaseHostMixin.is_database_host_valid",+ return_value=(True, None),+ ),+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.http.transport.TrackedHTTPAdapter.send",+ side_effect=responses,+ ) as send,+ ):+ schemas = Neo4jSource().get_schemas(config, 1, names=names)+ expected = ["node_Person", "node_Person_Record", "node_two words", "rel_KNOWS", "rel_Person"]+ assert [schema.name for schema in schemas] == [name for name in expected if names is None or name in names]+ assert all(not schema.supports_incremental and not schema.supports_append for schema in schemas)+ statements = [json.loads(call.args[0].body)["statement"] for call in send.call_args_list]+ assert statements == [+ "CALL db.labels() YIELD label RETURN label ORDER BY label",+ "CALL db.relationshipTypes() YIELD relationshipType RETURN relationshipType ORDER BY relationshipType",+ ]