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): read uploaded CSVs with the quoting they were detected under (#104005)

Thomas Obermüller7ee207f1c00b
diff --git a/products/data_warehouse/backend/models/test/test_table.py b/products/data_warehouse/backend/models/test/test_table.py
index 22eb3c025aa2..d8d40fd92617 100644
--- a/products/data_warehouse/backend/models/test/test_table.py
+++ b/products/data_warehouse/backend/models/test/test_table.py
@@ -956,6 +956,32 @@ class TestTable(BaseTest):
with pytest.raises(Exception, match=expected):
table._validate_csv_double_quotes_setting()
+ @parameterized.expand(
+ [
+ ("rfc_4180_parses", [None], True),
+ ("literal_quotes_parses", ["parse_error", None], False),
+ ("neither_parses", ["parse_error", "parse_error"], None),
+ ]
+ )
+ def test_detect_csv_double_quotes_setting(self, _name, outcomes, expected):
+ from clickhouse_driver.errors import ServerException
+
+ credential = DataWarehouseCredential.objects.create(access_key="key", access_secret="secret", team=self.team)
+ table = DataWarehouseTable.objects.create(
+ name="test_csv",
+ url_pattern="https://example.com/test.csv",
+ credential=credential,
+ format=DataWarehouseTable.TableFormat.CSVWithNames,
+ team=self.team,
+ )
+ side_effect = [
+ ServerException("Expected end of line", code=117) if outcome == "parse_error" else outcome
+ for outcome in outcomes
+ ]
+
+ with patch("products.warehouse_sources.backend.models.table.sync_execute", side_effect=side_effect):
+ assert table.detect_csv_double_quotes_setting() is expected
+
def test_validate_csv_double_quotes_reraises_a_non_parse_error(self):
from clickhouse_driver.errors import ServerException
@@ -1049,7 +1075,7 @@ class TestTable(BaseTest):
assert definition.top_level_settings is not None
assert definition.top_level_settings.format_csv_allow_double_quotes is True
- def test_hogql_definition_sets_false_for_csv_with_none(self):
+ def test_hogql_definition_sends_no_quote_setting_for_csv_with_none(self):
credential = DataWarehouseCredential.objects.create(access_key="test", access_secret="test", team=self.team)
with patch("products.warehouse_sources.backend.models.table.sync_execute", return_value=[]):
table = DataWarehouseTable.objects.create(
@@ -1060,13 +1086,11 @@ class TestTable(BaseTest):
columns={"id": {"clickhouse": "String", "hogql": "StringDatabaseField"}},
credential=credential,
)
- # Simulate detection having returned None (both failed)
table.options.pop("csv_allow_double_quotes", None)
table.save_base(raw=True)
definition = table.hogql_definition()
- assert definition.top_level_settings is not None
- assert definition.top_level_settings.format_csv_allow_double_quotes is False
+ assert definition.top_level_settings is None
def test_hogql_definition_reads_a_json_column_as_the_json_type(self):
credential = DataWarehouseCredential.objects.create(access_key="test", access_secret="test", team=self.team)
diff --git a/products/data_warehouse/backend/presentation/views/table.py b/products/data_warehouse/backend/presentation/views/table.py
index b3afcfb20ad0..c778660a23ed 100644
--- a/products/data_warehouse/backend/presentation/views/table.py
+++ b/products/data_warehouse/backend/presentation/views/table.py
@@ -30,6 +30,7 @@ from products.data_warehouse.backend.facade.api import get_s3_client
from products.warehouse_sources.backend.facade.api import (
FILE_FORMAT_READ_HINTS,
FILE_FORMAT_TO_TABLE_FORMAT,
+ FORMAT_CSV,
MAX_FILE_UPLOAD_SIZE_BYTES,
SUPPORTED_FILE_FORMATS,
build_file_upload_s3_path,
@@ -99,6 +100,11 @@ def resolve_created_via(request: request.Request) -> str:
return created_via
+def _file_read_error_message(file_format: str) -> str:
+ hint = FILE_FORMAT_READ_HINTS.get(file_format, "")
+ return f"Couldn't read the columns from your file. {hint}".strip()
+
+
def _delete_hosted_upload_file(table: DataWarehouseTable) -> None:
"""Best-effort removal of a self-managed table's backing file from PostHog's own bucket.
@@ -127,6 +133,17 @@ def _delete_hosted_upload_file(table: DataWarehouseTable) -> None:
capture_exception(e)
+def _discard_failed_upload(table: DataWarehouseTable) -> None:
+ """Reclaim a table and its hosted file after the upload that created them failed.
+
+ The legacy `file` action writes the object and persists the row before it reads the file even
+ once, so every failure after that point has both to undo. The file goes first, because
+ `_delete_hosted_upload_file` decides by looking for another live table on the same url_pattern.
+ """
+ _delete_hosted_upload_file(table)
+ table.delete()
+
+
class CredentialSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
@@ -797,17 +814,31 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.M
created_by=request.user if isinstance(request.user, User) else None,
created_via=resolve_created_via(request),
)
+
+ # An upload carries no quote preference, unlike a self-managed source where the user picks
+ # one, so store a detected setting rather than leave the read to a ClickHouse default.
+ if table._is_csv_format():
+ try:
+ allow_double_quotes = table.detect_csv_double_quotes_setting()
+ except Exception as err:
+ capture_exception(err)
+ allow_double_quotes = None
+ if allow_double_quotes is None:
+ return response.Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": _file_read_error_message(file_format)},
+ )
+ table.options = {"csv_allow_double_quotes": allow_double_quotes}
+
try:
table.columns = table.get_columns()
except Exception as err:
# The raw column-detection failure is a ClickHouse error that's opaque to users, so keep it
# in error tracking and hand back plain, format-specific guidance on what to check instead.
capture_exception(err)
- hint = FILE_FORMAT_READ_HINTS.get(file_format, "")
- message = f"Couldn't read the columns from your file. {hint}".strip()
return response.Response(
status=status.HTTP_400_BAD_REQUEST,
- data={"message": message},
+ data={"message": _file_read_error_message(file_format)},
)
table.save()
@@ -887,6 +918,8 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.M
data={"message": f"File size exceeds maximum allowed size of 50MB"},
)
+ created_table = table is None
+
# Create the table record
try:
# Create the table if it doesn't exist, otherwise use existing one
@@ -920,6 +953,23 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.M
)
table.format = file_format
+ # Detect on this path too, so a CSV uploaded here is read under the quoting its
+ # columns are detected with. Only an unset option is filled, so an explicit choice
+ # on an existing table survives a re-upload.
+ if table._is_csv_format() and table.csv_allow_double_quotes is None:
+ allow_double_quotes = table.detect_csv_double_quotes_setting()
+ if allow_double_quotes is None:
+ # Left behind, the row is an incomplete table that the next upload of the
+ # same name silently reuses. A table that already existed belongs to the
+ # caller, so leave it alone.
+ if created_table:
+ _discard_failed_upload(table)
+ return response.Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": _file_read_error_message(FORMAT_CSV)},
+ )
+ table.options = {**table.options, "csv_allow_double_quotes": allow_double_quotes}
+
# Try to determine columns from the file
table.columns = table.get_columns()
# team_id comes from routing and safe_filename is sanitized (no path separators), so
@@ -943,4 +993,9 @@ class TableViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.M
)
except Exception as e:
capture_exception(e)
+ # Reading the file can fail outright rather than return an answer, in column detection
+ # and in quote detection alike. A table that already existed belongs to the caller, so
+ # leave it alone.
+ if created_table and table is not None:
+ _discard_failed_upload(table)
return response.Response(status=status.HTTP_400_BAD_REQUEST, data={"message": "Failed to upload file"})
diff --git a/products/data_warehouse/backend/tests/api/test_table.py b/products/data_warehouse/backend/tests/api/test_table.py
index 7669298f1978..f15e574875ff 100644
--- a/products/data_warehouse/backend/tests/api/test_table.py
+++ b/products/data_warehouse/backend/tests/api/test_table.py
@@ -2,7 +2,7 @@ import ipaddress
from typing import Any
from posthog.test.base import APIBaseTest
-from unittest.mock import ANY, MagicMock, patch
+from unittest.mock import ANY, MagicMock, Mock, patch
from django.conf import settings
from django.test import SimpleTestCase, override_settings
@@ -960,9 +960,14 @@ class TestTable(APIBaseTest):
file_content = b"id,name,value\n1,Test,100\n2,Test2,200"
test_file = SimpleUploadedFile("test_file.csv", file_content, content_type="text/csv")
- with patch(
- "products.warehouse_sources.backend.models.table.DataWarehouseTable.get_columns"
- ) as mock_get_columns:
+ with (
+ patch("products.warehouse_sources.backend.models.table.DataWarehouseTable.get_columns") as mock_get_columns,
+ # Quote detection reads the file for real, which a mocked S3 client can't serve.
+ patch(
+ "products.warehouse_sources.backend.models.table.DataWarehouseTable.detect_csv_double_quotes_setting",
+ return_value=True,
+ ),
+ ):
mock_get_columns.return_value = {
"id": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField", "valid": True},
"name": {"clickhouse": "Nullable(String)", "hogql": "StringDatabaseField", "valid": True},
@@ -988,6 +993,7 @@ class TestTable(APIBaseTest):
# Verify the table was created
table = DataWarehouseTable.objects.get(name="test_csv_table")
assert table is not None
+ assert table.options == {"csv_allow_double_quotes": True}
# Verify S3 client was called to upload the file
mock_s3.upload_fileobj.assert_called_once_with(
@@ -997,6 +1003,47 @@ class TestTable(APIBaseTest):
# Verify URL pattern was set correctly
assert table.url_pattern == f"https://test-bucket.s3.amazonaws.com/managed/team_{self.team.id}/test_file.csv"
+ @parameterized.expand(
+ [
+ ("neither_quote_setting_parses", None, "comma-separated CSV with a header row"),
+ ("the_read_fails_outright", ServerException("Access Denied", code=499), "Failed to upload file"),
+ ]
+ )
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ @patch("boto3.client")
+ def test_file_upload_leaves_no_table_when_the_csv_cannot_be_read(
+ self, _name, detect_outcome, expected_message, mock_boto3_client, mock_feature_enabled
+ ):
+ mock_boto3_client.return_value = MagicMock()
+
+ from django.core.files.uploadedfile import SimpleUploadedFile
+
+ test_file = SimpleUploadedFile("test_file.csv", b'id,name\n1,"Test\n', content_type="text/csv")
+ detect = Mock(side_effect=detect_outcome) if isinstance(detect_outcome, Exception) else Mock(return_value=None)
+
+ s3 = MagicMock()
+
+ with (
+ patch.object(DataWarehouseTable, "detect_csv_double_quotes_setting", detect),
+ patch("products.data_warehouse.backend.presentation.views.table.get_s3_client", return_value=s3),
+ self.settings(
+ DATAWAREHOUSE_LOCAL_ACCESS_KEY="test_key",
+ DATAWAREHOUSE_LOCAL_ACCESS_SECRET="test_secret",
+ DATAWAREHOUSE_BUCKET_DOMAIN="test-bucket.s3.amazonaws.com",
+ DATAWAREHOUSE_BUCKET="test-warehouse-bucket",
+ ),
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/warehouse_tables/file/",
+ {"file": test_file, "name": "unreadable_csv", "format": "CSVWithNames"},
+ format="multipart",
+ )
+
+ assert response.status_code == 400
+ assert expected_message in response.json()["message"]
+ assert not DataWarehouseTable.objects.filter(name="unreadable_csv").exists()
+ s3.rm.assert_called_once_with(f"test-warehouse-bucket/managed/team_{self.team.id}/test_file.csv")
+
@patch("posthoganalytics.feature_enabled", return_value=False)
def test_file_upload_api_disabled(self, mock_feature_enabled):
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -1033,6 +1080,7 @@ class TestTable(APIBaseTest):
assert response.status_code == 400
assert "Table names must start with a letter or underscore" in response.json()["message"]
+ @patch.object(DataWarehouseTable, "detect_csv_double_quotes_setting", lambda self: True)
@patch("posthoganalytics.feature_enabled", return_value=True)
@patch("boto3.client")
def test_file_upload_updates_existing_table(self, mock_boto3_client, mock_feature_enabled):
@@ -1099,6 +1147,7 @@ class TestTable(APIBaseTest):
if "Key" in obj:
s3_client.delete_object(Bucket=bucket_name, Key=obj["Key"])
+ @patch.object(DataWarehouseTable, "detect_csv_double_quotes_setting", lambda self: True)
@patch("posthoganalytics.feature_enabled", return_value=True)
def test_file_upload_with_minio(self, mock_feature_enabled):
"""Test file upload using actual MinIO bucket instead of mocking."""
@@ -1164,6 +1213,7 @@ class TestTable(APIBaseTest):
self._delete_all_from_s3(s3_client, test_bucket_name)
s3_client.delete_bucket(Bucket=test_bucket_name)
+ @patch.object(DataWarehouseTable, "detect_csv_double_quotes_setting", lambda self: True)
@patch("posthoganalytics.feature_enabled", return_value=True)
@patch("boto3.client")
def test_file_upload_sanitizes_filename_for_s3_key(self, mock_boto3_client, mock_feature_enabled):
@@ -1235,6 +1285,7 @@ class TestTable(APIBaseTest):
assert response.status_code == 400
assert "Table names must start with a letter" in response.json()["message"]
+ @patch.object(DataWarehouseTable, "detect_csv_double_quotes_setting", lambda self: True)
@patch("posthoganalytics.feature_enabled", return_value=True)
@patch("boto3.client")
def test_file_upload_table_name_defaults_to_sanitized_filename_when_valid(
diff --git a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py
index e87d7f63ec43..2ffad9b78e50 100644
--- a/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py
+++ b/products/data_warehouse/backend/tests/api/test_warehouse_table_file_upload.py
@@ -198,10 +198,15 @@ class TestCreateTableFromUpload(APIBaseTest):
assert response.status_code == status.HTTP_201_CREATED, response.json()
return response.json()["upload_id"]
- def _create(self, *, exists: bool = True, **payload):
+ def _create(self, *, exists: bool = True, detected_quotes: bool | None = True, **payload):
with (
patch(f"{VIEW_MODULE}.get_s3_client", return_value=_FakeS3(exists_result=exists)),
patch(f"{MODEL_MODULE}.DataWarehouseTable.get_columns", return_value=dict(FAKE_COLUMNS)),
+ # Quote detection reads the file for real, which a fake S3 object can't serve.
+ patch(
+ f"{MODEL_MODULE}.DataWarehouseTable.detect_csv_double_quotes_setting",
+ return_value=detected_quotes,
+ ),
# Background column validation runs eagerly under test and would re-query the (faked) S3
# table, stamping `valid` onto each column. It's out of scope for these wiring tests, so
# keep it from mutating the columns the create endpoint just persisted.
@@ -281,6 +286,45 @@ class TestCreateTableFromUpload(APIBaseTest):
table = DataWarehouseTable.objects.get(id=response.json()["id"])
assert table.format == expected_format
+ @parameterized.expand(
+ [
+ ("rfc_4180_quoting", "csv", True, {"csv_allow_double_quotes": True}),
+ ("literal_quoting", "csv", False, {"csv_allow_double_quotes": False}),
+ ("non_csv_skips_detection", "parquet", None, {}),
+ ]
+ )
+ def test_an_upload_stores_the_detected_csv_quote_setting(
+ self, _name: str, file_format: str, detected: bool | None, expected_options: dict
+ ) -> None:
+ upload_id = self._upload(filename=f"data.{file_format}", file_format=file_format)
+
+ response = self._create(
+ upload_id=upload_id,
+ filename=f"data.{file_format}",
+ file_format=file_format,
+ table_name=f"data_{file_format}",
+ detected_quotes=detected,
+ )
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ table = DataWarehouseTable.objects.get(id=response.json()["id"])
+ assert table.options == expected_options
+
+ def test_a_csv_that_parses_under_neither_quote_setting_is_rejected(self) -> None:
+ upload_id = self._upload()
+
+ response = self._create(
+ upload_id=upload_id,
+ filename="orders.csv",
+ file_format="csv",
+ table_name="orders",
+ detected_quotes=None,
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert FILE_FORMAT_READ_HINTS["csv"] in response.json()["message"]
+ assert not DataWarehouseTable.objects.filter(name="orders").exists()
+
def test_url_pattern_is_scoped_to_the_requesting_team(self) -> None:
# The read location is always built from the caller's own team, so a client-supplied upload_id
# can only ever resolve inside that team's folder.
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/components/SelfManagedSourceForm.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/components/SelfManagedSourceForm.tsx
index 7c2e7dae8b75..d68dbd30a8b2 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/components/SelfManagedSourceForm.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/components/SelfManagedSourceForm.tsx
@@ -139,7 +139,7 @@ export function SelfManagedSourceForm({ onUpdate }: Props): JSX.Element {
{ label: 'RFC 4180 double quotes', value: true },
{ label: 'Literal quotes', value: false },
]}
- value={value ?? false}
+ value={value ?? true}
onChange={onChange}
/>
)}
diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx
index 2a46f4d9e28f..871cdb9bd839 100644
--- a/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx
+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/selfManagedSourceLogic.tsx
@@ -25,7 +25,8 @@ const NEW_WAREHOUSE_TABLE: DataWarehouseTable = {
name: '',
url_pattern: '',
format: 'Parquet',
- options: { csv_allow_double_quotes: false },
+ // RFC 4180 is what almost every CSV export produces, and save-time validation redirects the rest.
+ options: { csv_allow_double_quotes: true },
credential: {
access_key: '',
access_secret: '',
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index b7683c9144ed..e518fad318ac 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -28,6 +28,7 @@ from django.db.models import OuterRef, Prefetch, QuerySet, Subquery
from products.warehouse_sources.backend.file_uploads import (
FILE_FORMAT_READ_HINTS,
FILE_FORMAT_TO_TABLE_FORMAT,
+ FORMAT_CSV,
MAX_UPLOAD_SIZE_BYTES as MAX_FILE_UPLOAD_SIZE_BYTES,
SUPPORTED_FILE_FORMATS,
build_file_upload_s3_key,
@@ -104,6 +105,7 @@ __all__ = [
# file-upload storage contract
"FILE_FORMAT_READ_HINTS",
"FILE_FORMAT_TO_TABLE_FORMAT",
+ "FORMAT_CSV",
"MAX_FILE_UPLOAD_SIZE_BYTES",
"SUPPORTED_FILE_FORMATS",
"build_file_upload_s3_key",
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index 1aace48bb41d..963b55cf6945 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -1190,10 +1190,12 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
source_type=self.external_data_source.source_type if self.external_data_source else None,
)
- if self._is_csv_format():
- effective = self.csv_allow_double_quotes if self.csv_allow_double_quotes is not None else False
+ # Must resolve an unset option the same way _describe_settings does, by sending no setting.
+ # Column detection reads the file through that method, so forcing a value here would query a
+ # table under different quoting than the columns it was created from.
+ if self._is_csv_format() and self.csv_allow_double_quotes is not None:
table_def.top_level_settings = HogQLQuerySettings(
- format_csv_allow_double_quotes=effective,
+ format_csv_allow_double_quotes=self.csv_allow_double_quotes,
)
return table_def
@@ -1261,6 +1263,28 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
raise
return True
+ def detect_csv_double_quotes_setting(self) -> bool | None:
+ """Return the csv_allow_double_quotes setting that parses this file, or None when neither does.
+
+ RFC 4180 is tried first because almost every CSV export quotes fields that contain a comma.
+ Each probe reads a sample rather than the whole file, so a file whose quoting only varies
+ past the sample stays undisambiguated and takes the RFC 4180 answer. That is the same
+ setting ClickHouse applies to an unset option, so the sample bounds how much this method
+ can learn, not how correct its answer is. False comes back only when RFC 4180 fails.
+ """
+ tag_queries(
+ team_id=self.team.pk,
+ table_id=self.id,
+ warehouse_query=True,
+ name="detect_csv_double_quotes",
+ product=Product.WAREHOUSE,
+ feature=Feature.QUERY,
+ )
+ for allow_double_quotes in (True, False):
+ if self._csv_parses_with_double_quotes(allow_double_quotes):
+ return allow_double_quotes
+ return None
+
def _validate_csv_double_quotes_setting(self) -> None:
"""Validate the user-chosen csv_allow_double_quotes setting by trying to parse data rows.
Raises Exception with a helpful message if parsing fails."""