Skip to content

refactor(cubestore): append CSV import values directly into Arrow builders - #11064

Merged
waralexrom merged 3 commits into
masterfrom
cubestore-csv-import-improvements
Jun 12, 2026
Merged

waralexrom merged 3 commits into
masterfrom
cubestore-csv-import-improvements

Conversation

@waralexrom

Copy link
Copy Markdown
Member

Summary

Removes the per-row Row/Vec<TableValue> intermediate from the CubeStore CSV file-import path, appending parsed values straight into the Arrow column builders. This drops the allocations that scale with row count — one Vec<TableValue> per row (unconditional) and the TableValue::String copy per string cell (the most common column type) — to relieve allocator pressure on large imports.

Changes

  • do_import now drives the CSV line stream through a shared CsvImportParser and appends each field directly into its ArrayBuilder; strings go straight into StringBuilder, skipping the TableValue::String allocation.
  • Line splitting, header mapping and null-marker handling are factored into CsvImportParser and shared between the builder path and the Row-producing path (still used by HTTP inline tables), so the two cannot diverge.
  • A CSV header that resolves two fields to the same column is now rejected with a clear error instead of silent last-write-wins — this preserves the one-append-per-column invariant the builder path relies on (avoids a length desync / panic at finish()).
  • parse_column_value_str + append_value are reused for all non-string types, so type mapping and null semantics are unchanged.

Testing

  • New baseline unit tests pin CSV type mapping and null semantics (null markers across String/Int/Decimal/Timestamp, typed parse-failure semantics, HLL flavor re-serialization, decimal precision-overflow, quoting across read-buffer boundaries).
  • Differential unit tests assert the builder path produces identical data to the Row path (compared through identical Arrow reconstruction), with and without a header.
  • Unit suite: 13/13 green. In-process integration tests green end-to-end: create_table_with_csv* (5) and create_table_with_location* (6, incl. gzip, reordered columns, invalid-digit error path, and all three HLL flavors).

…ll semantics

Pin current parse behavior before refactoring the row-oriented import path:
- null markers ("", \N, \\N) across String/Int/Decimal/Timestamp, plus quoted-empty
- typed parse-failure semantics (Int/Int96 -> Null, Float/Decimal/Timestamp -> Err)
- Int96/Float/Decimal/Decimal96/Bytes/Timestamp value mapping with hardcoded expectations
- HLL re-serialization for Postgres and Snowflake flavors
- decimal precision-overflow error path
- quoting with delimiter/newline/escape, including across read-buffer boundaries
Remove the per-row Row/Vec<TableValue> intermediate from the file-import
path: do_import now drives the line stream through CsvImportParser and
appends straight into the column builders. String values go directly into
the StringBuilder, dropping the TableValue::String allocation.

Line splitting, header mapping and null-marker handling are shared between
the builder path and the Row-producing path (still used by HTTP inline
tables) via CsvImportParser, so the two cannot diverge. A header that maps
two fields to the same column is now rejected instead of silently doing
last-write-wins, which keeps the one-append-per-column builder invariant.

Differential tests assert the builder path matches the Row path through
identical Arrow reconstruction.
@waralexrom
waralexrom requested a review from a team as a code owner June 11, 2026 10:58
@github-actions github-actions Bot added cube store Issues relating to Cube Store rust Pull requests that update Rust code labels Jun 11, 2026
@claude

claude Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @waralexrom's task in 2m 15s —— View job


Code Review

Overall: nice refactor. Sharing the CsvImportParser between the Row path and the builder path closes a real source of drift, and skipping the per-row Vec<TableValue> + TableValue::String allocation on the bulk import path is a clean win. Tests are thorough: the differential builder-vs-row assertions and the parse-failure-typing test will catch real regressions. A few small comments below; none block merge.

Review checklist (click to expand)
  • Read the diff and surrounding code (rust/cubestore/cubestore/src/import/mod.rs)
  • Verify behavior parity between Row path and builder path
  • Check error handling and partial-row safety
  • Review tests and edge cases
  • Post review

Findings

1. Behavior change worth surfacing — duplicate header columns now hard-error (low)

CsvImportParser::visit_line rejects a header where two fields resolve to the same column. The PR body explains why (the builder path requires one append per column per row), and the new behavior is strictly more correct than the old silent last-write-wins. But it is a user-visible change: any existing import file that happens to repeat a column header — even harmlessly — will now fail with Duplicate column 'X' in CSV header where it previously imported. Worth a line in the changelog and, ideally, an explicit unit test pinning the new error message so a future "helpful" refactor can't quietly revert it.

2. append_csv_value panics on a malformed builder via unwrap() (low)

builder
    .as_any_mut()
    .downcast_mut::<datafusion::arrow::array::StringBuilder>()
    .unwrap()
    .append_value(value);

This is reachable only if create_array_builders ever returns a non-StringBuilder for ColumnType::String — i.e., it's an internal invariant violation, not user input — so unwrap() is acceptable. But .expect("create_array_builders produced a non-StringBuilder for ColumnType::String") would make the panic message immediately actionable if that invariant ever does break (e.g. someone adds a LargeStringBuilder variant). Two-line cost, real debugging payoff.

3. Partial builder advance on visitor error in do_import (informational, not a bug today)

In the builder path, if append_csv_value errors mid-row (e.g. an unparseable Float on field 3 of 6), fields 1–2 have already been appended into their builders before the visitor returns Err. Today this is safe because ? aborts the whole import and builders is dropped without finish(). It will silently become a desync bug the moment anyone catches that error and tries to continue importing — for instance, a future "skip bad rows" option. The one-append-per-column invariant the comment on visit_line calls out is enforced at the line boundary, not the row boundary; a brief note on the field-level partial-advance state would save the next reader 20 minutes.

4. parse_value_error is applied twice on the Row path (cosmetic)

In row_stream_from_reader, the visitor wraps with parse_value_error, but parse_column_value_str errors for Decimal/Timestamp already have rich context. The old code did the same wrapping, so this is preexisting — just flagging that the resulting message has redundant column information (Can't parse 'X' column value for 'A' column: cannot represent 'X' with scale ...). Not worth a follow-up unless someone is auditing error UX.

5. HashSet for header dedup (negligible)

std::collections::HashSet::new() allocates only once at header parse time. For tables with O(10) columns a Vec<usize> + contains() scan would be cheaper and avoid the hash setup, but the difference is unmeasurable here — happy to leave it.


Things done well

  • Differential test builder_path_matches_row_path_* is the right shape — comparing through arrays_to_rows(rows_to_columns(...)) neutralizes representation differences so a regression actually surfaces as a data difference, not a noise diff.
  • parse_failures_are_typed pins the (surprising!) Int-silently-nulls vs Float/Decimal/Timestamp-hard-errors asymmetry. That's exactly the kind of behavior that gets "cleaned up" by a well-meaning refactor; the test makes that mistake impossible to merge silently.
  • quoting_survives_chunk_boundaries with BufReader::with_capacity(1, ...) is a good adversarial test for the line stream.
  • HLL flavor re-serialization test correctly distinguishes the two flavors that decode-and-rewrite (Postgres, Snowflake) from the two that store verbatim (Airlift, ZetaSketch).
    · cubestore-csv-import-improvements

…gBuilder downcast

A builder type mismatch with the column type is an internal invariant
violation, not user input, so surface it as CubeError::internal.
@claude

claude Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @waralexrom's task in 33s —— View job


Re-review of new commit

Looked at 68e54ae refactor(cubestore): return internal error instead of unwrap on StringBuilder downcast — the only change since my earlier review.

This directly addresses prior finding #2: the .unwrap() on the StringBuilder downcast is replaced with an ok_or_else returning CubeError::internal that names the offending column. The treatment is the right one — a builder/column-type mismatch is an internal invariant violation, not user input, so internal (vs. user) is the correct category and including the column name makes the panic-that-now-isn't immediately actionable. No new behavior risk: the Err path was previously a panic, so any caller that didn't crash before still won't.

Nothing else to flag on this commit. Prior findings #1 (duplicate-header hard-error is a user-visible behavior change worth a changelog note), #3 (field-level partial-advance comment), #4 (double error wrapping on Row path), and #5 (HashSet vs Vec) all remain low/informational — not blocking. LGTM.

Tasks
  • Diff the new commit against prior review
  • Confirm fix addresses prior finding MUTEX for requests #2
  • Check no regressions introduced
· `cubestore-csv-import-improvements`

@codecov

codecov Bot commented Jun 11, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 58.50%. Comparing base (107e63f) to head (68e54ae).
⚠️ Report is 24 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master   #11064      +/-   ##
==========================================
+ Coverage   58.44%   58.50%   +0.06%     
==========================================
  Files         216      216              
  Lines       17248    17269      +21     
  Branches     3520     3524       +4     
==========================================
+ Hits        10080    10103      +23     
+ Misses       6660     6651       -9     
- Partials      508      515       +7     
Flag Coverage Δ
cube-backend 58.50% <ø> (+0.06%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@waralexrom
waralexrom merged commit ad64b04 into master Jun 12, 2026
61 checks passed
@waralexrom
waralexrom deleted the cubestore-csv-import-improvements branch June 12, 2026 08:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cube store Issues relating to Cube Store rust Pull requests that update Rust code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants