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): stabilize elasticsearch numeric column types (#72871)

Tom Owerse528fd520d38
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
index 24e3efe3db8a..5cd2cf5d54d5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/elasticsearch.py
@@ -21,6 +21,14 @@ MAX_RETRY_ATTEMPTS = 5
# get_non_retryable_errors without the two strings silently drifting apart.
NON_JSON_RESPONSE_ERROR = "Elasticsearch returned a non-JSON response"
+# Elasticsearch numeric types whose _source JSON alternates between whole (40) and fractional
+# (40.5) representations across documents. Left alone, that makes a column infer as int64 on one
+# scroll page and double on the next, which PyArrow/Delta refuse to merge ("incompatible types:
+# int64 vs double"). Coercing these fields to float up front pins the type deterministically.
+# Integer types (long/integer/short/byte) are excluded on purpose: they're always whole in JSON,
+# and widening a large `long` id to float64 would silently lose precision past 2^53.
+_ES_FLOAT_TYPES = frozenset({"float", "double", "half_float", "scaled_float"})
+
class ElasticsearchRetryableError(Exception):
pass
@@ -91,6 +99,74 @@ def list_indices(host: str, auth: ElasticsearchAuth) -> list[str]:
return sorted(index for index in indices if index and not index.startswith("."))
+def _collect_float_paths(properties: dict[str, Any], prefix: str, paths: set[str]) -> None:
+ """Walk an Elasticsearch mapping's `properties` tree, recording dotted paths of float-typed fields."""
+ for name, spec in properties.items():
+ if not isinstance(spec, dict):
+ continue
+ path = f"{prefix}{name}"
+ if spec.get("type") in _ES_FLOAT_TYPES:
+ paths.add(path)
+ sub_properties = spec.get("properties")
+ if isinstance(sub_properties, dict):
+ _collect_float_paths(sub_properties, f"{path}.", paths)
+
+
+def get_float_field_paths(session: requests.Session, base_url: str, index: str) -> set[str]:
+ """Dotted paths of fields the index mapping types as floating point.
+
+ Best-effort: a mapping we can't read (permissions, non-JSON body) yields no paths, so the sync
+ behaves as before rather than failing on the mapping lookup alone.
+ """
+ try:
+ response = session.get(f"{base_url}/{quote(index)}/_mapping", timeout=REQUEST_TIMEOUT_SECONDS)
+ response.raise_for_status()
+ body = response.json()
+ except (requests.exceptions.RequestException, requests.exceptions.JSONDecodeError, ValueError):
+ return set()
+
+ paths: set[str] = set()
+ # Shape: {"<index>": {"mappings": {"properties": {...}}}}. An alias resolves to several indices,
+ # so union every block's float paths.
+ if isinstance(body, dict):
+ for index_block in body.values():
+ properties = ((index_block or {}).get("mappings") or {}).get("properties")
+ if isinstance(properties, dict):
+ _collect_float_paths(properties, "", paths)
+ return paths
+
+
+def _to_float(value: Any) -> Any:
+ # bool is an int subclass but never a numeric field value here — leave it untouched.
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, int):
+ return float(value)
+ if isinstance(value, list):
+ return [_to_float(item) for item in value]
+ return value
+
+
+def _coerce_path(obj: Any, parts: list[str]) -> None:
+ key = parts[0]
+ if isinstance(obj, list):
+ for item in obj:
+ _coerce_path(item, parts)
+ return
+ if not isinstance(obj, dict) or key not in obj:
+ return
+ if len(parts) == 1:
+ obj[key] = _to_float(obj[key])
+ else:
+ _coerce_path(obj[key], parts[1:])
+
+
+def coerce_float_fields(doc: dict[str, Any], float_paths: set[str]) -> None:
+ """Rewrite whole-number values under float-typed fields to float, in place."""
+ for path in float_paths:
+ _coerce_path(doc, path.split("."))
+
+
def get_rows(
host: str,
auth: ElasticsearchAuth,
@@ -99,6 +175,7 @@ def get_rows(
) -> Iterator[list[dict[str, Any]]]:
session = _get_session(auth)
base_url = normalize_host(host)
+ float_paths = get_float_field_paths(session, base_url, index)
@retry(
retry=retry_if_exception_type((ElasticsearchRetryableError, requests.ReadTimeout, requests.ConnectionError)),
@@ -134,6 +211,10 @@ def get_rows(
hits = ((data.get("hits") or {}).get("hits")) or []
items = [{**(hit.get("_source") or {}), "_id": hit["_id"]} for hit in hits]
+ if float_paths:
+ for item in items:
+ coerce_float_fields(item, float_paths)
+
if items:
yield items
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
index 0a0ede48b941..f2bdc737105e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/elasticsearch/tests/test_elasticsearch.py
@@ -8,7 +8,9 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.elasticsearch.elasticsearch import (
PAGE_SIZE,
ElasticsearchAuth,
+ coerce_float_fields,
elasticsearch_source,
+ get_float_field_paths,
get_rows,
hostname_of,
list_indices,
@@ -171,6 +173,121 @@ class TestGetRows:
list(get_rows("https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock())) == []
)
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_float_typed_fields_are_coerced_across_rows(self, mock_session):
+ # A float-typed field whose docs mix whole (40) and fractional (40.5) values must all
+ # arrive as floats so the column infers a single Arrow type; the long id stays an int.
+ mock_session.return_value.headers = {}
+ mock_session.return_value.get.return_value = _response(
+ {"orders": {"mappings": {"properties": {"amount": {"type": "float"}, "id": {"type": "long"}}}}}
+ )
+ mock_session.return_value.post.return_value = _response(
+ _scroll_page(
+ [
+ {"_id": "1", "_source": {"amount": 40, "id": 100}},
+ {"_id": "2", "_source": {"amount": 40.5, "id": 200}},
+ ]
+ )
+ )
+
+ batches = list(get_rows("https://es.example.com", ElasticsearchAuth(api_key="k"), "orders", mock.MagicMock()))
+
+ assert batches == [
+ [
+ {"amount": 40.0, "id": 100, "_id": "1"},
+ {"amount": 40.5, "id": 200, "_id": "2"},
+ ]
+ ]
+ assert [type(row["amount"]) for row in batches[0]] == [float, float]
+ assert [type(row["id"]) for row in batches[0]] == [int, int]
+
+
+class TestFloatFieldPaths:
+ @pytest.mark.parametrize(
+ "mappings, expected",
+ [
+ # Scalar float types are collected; integer/keyword types are not.
+ (
+ {
+ "properties": {
+ "threshold_amount": {"type": "float"},
+ "total_hours_worked": {"type": "double"},
+ "ratio": {"type": "half_float"},
+ "price": {"type": "scaled_float", "scaling_factor": 100},
+ "id": {"type": "long"},
+ "count": {"type": "integer"},
+ "name": {"type": "keyword"},
+ }
+ },
+ {"threshold_amount", "total_hours_worked", "ratio", "price"},
+ ),
+ # Nested object properties are walked and reported as dotted paths.
+ (
+ {
+ "properties": {
+ "payroll": {
+ "properties": {
+ "rate": {"type": "double"},
+ "employee_id": {"type": "long"},
+ }
+ }
+ }
+ },
+ {"payroll.rate"},
+ ),
+ ({"properties": {}}, set()),
+ ({}, set()),
+ ],
+ )
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_collects_float_typed_paths(self, mock_session, mappings, expected):
+ mock_session.return_value.headers = {}
+ session = mock_session.return_value
+ session.get.return_value = _response({"orders": {"mappings": mappings}})
+
+ assert get_float_field_paths(session, "https://es.example.com", "orders") == expected
+
+ @mock.patch(f"{_MODULE}.make_tracked_session")
+ def test_unreadable_mapping_yields_no_paths(self, mock_session):
+ mock_session.return_value.headers = {}
+ session = mock_session.return_value
+ session.get.side_effect = requests.exceptions.ConnectionError("boom")
+
+ assert get_float_field_paths(session, "https://es.example.com", "orders") == set()
+
+
+class TestCoerceFloatFields:
+ @pytest.mark.parametrize(
+ "doc, float_paths, expected",
+ [
+ # Whole numbers under float fields become floats; ints under non-float fields stay ints.
+ (
+ {"amount": 40, "id": 12345678901234567, "name": "x"},
+ {"amount"},
+ {"amount": 40.0, "id": 12345678901234567, "name": "x"},
+ ),
+ # Already-float values are untouched, missing paths are ignored.
+ ({"amount": 40.5}, {"amount", "missing"}, {"amount": 40.5}),
+ # Nested and array-of-scalar float fields are coerced element-wise.
+ (
+ {"payroll": {"rate": 20}, "readings": [1, 2, 3]},
+ {"payroll.rate", "readings"},
+ {"payroll": {"rate": 20.0}, "readings": [1.0, 2.0, 3.0]},
+ ),
+ # Arrays of nested objects are traversed.
+ (
+ {"lines": [{"cost": 5}, {"cost": 6}]},
+ {"lines.cost"},
+ {"lines": [{"cost": 5.0}, {"cost": 6.0}]},
+ ),
+ # Booleans are ints in Python but must not be coerced to float.
+ ({"flag": True}, {"flag"}, {"flag": True}),
+ ],
+ )
+ def test_coercion(self, doc, float_paths, expected):
+ coerce_float_fields(doc, float_paths)
+ assert doc == expected
+
class TestElasticsearchSourceResponse:
def test_response_metadata(self):