fix(csv): decompress a compressed CSV file named for its compression

Merged
BE
19d ago
+195-4

Fixes #4711

Summary

partition_csv() crashed with UnicodeDecodeError on a CSV file whose name carries a compression suffix (.csv.gz/.bz2/.xz): _CsvPartitioningContext.open() opened the filename with a plain open(), so the delimiter sniff decoded raw compressed bytes as text. The TSV partitioner already opens its filename through get_handle(..., compression="infer") (_open_decompressed) — the mechanism pd.read_csv(filename) uses to read compressed files by name.

This change opens the CSV filename the same way, at the single choke point _CsvPartitioningContext.open(), so the delimiter sniff, the size check, and the read each get their own decompressing handle on the same content (the TSV partitioner does the same for its size check and read).

Notes on scope:

  • uncompressed .csv behavior is unchanged — compression="infer" on an unsuffixed name opens the file exactly as before;
  • decompression stays filename-driven, like the TSV partitioner and pd.read_csv(): a compression-suffixed stream passed via file= is out of scope, since a file object carries no name to infer from;
  • .zip (single member) and .zst (when the optional zstandard is installed) come along for free through compression="infer", with a clear ValueError for multi-member archives; a corrupt archive now raises its native error (e.g. BadGzipFile) instead of a misleading decode error.

Testing

  • uv run --no-sync pytest test_unstructured/partition/test_csv.py test_unstructured/partition/test_tsv.py — 112 passed, 9 skipped
  • new tests in test_unstructured/partition/test_csv.py, all five cases confirmed to fail on main with UnicodeDecodeError and pass with this change:
    • test_partition_csv_decompresses_a_compressed_filename — mirrors the TSV precedent test, including the CSV_MAX_CELLS monkeypatch proving the size check measures the decompressed content;
    • test_partition_csv_decompresses_a_filename_named_for_its_compression — parametrized over .gz/.bz2/.xz;
    • test_partition_csv_produces_no_elements_for_an_empty_compressed_file — an empty .csv.gz returns [], matching the empty-file semantics of #4707.
  • ruff check and ruff format --check clean.