A 20,000-order CSV had 20,785 lines. Line splits and LF-resync readers broke records with quoted newlines; cutting at record ends kept all 20,000.
The export had more lines than orders
Every night Belgavi's Book Store exports the day's orders to a CSV file: order id, ISBN, quantity and a free-text note from the customer. A reconciliation job compared wc -l with the number of orders in the database and alerted when they differed. One night the file had 20,785 lines for 20,000 orders, the alert fired, and the on-call engineer found nothing wrong with the export.
Nothing was wrong. 589 of the notes contained line breaks, such as "Gift wrap, please." on one line and "Leave with the front desk." on the next. CSV allows that: a field in double quotes may contain line breaks. One record became two or three physical lines. The line count was a count of lines, not of records, and the same confusion was quietly damaging a second job that split the file into pieces for parallel loading.
What CSV actually allows
RFC 4180, the closest thing CSV has to a common definition, says that fields containing line breaks, double quotes or commas should be enclosed in double quotes, and that a double quote inside such a field is written as two double quotes. Records end with CRLF, and a CRLF inside a quoted field is data. Most producers follow this: Python's csv module, spreadsheet exports and database COPY ... CSV all quote fields that contain newlines rather than escaping or removing them.
The consequence is simple and easy to forget: the end of a record is a line break that is not inside quotes, and you cannot find it without reading the quotes from the start of the file.
Measuring the damage on a synthetic export
The companion example writes a synthetic export of 20,000 records (seed 20261120, CRLF record ends) in which 589 notes contain an LF or CRLF, then processes it the ways real pipelines do.
| Method | Rows produced | Malformed or misaligned rows |
|---|---|---|
wc -l style line count | 20,785 lines | not applicable |
| Pieces of 5,000 lines, parsed separately | 20,000 | 0 |
| Pieces of 1,000 lines | 20,000 | 0 |
| Pieces of 250 lines | 20,004 | 4 |
| Pieces of 100 lines | 20,022 | 22 |
| 4 byte ranges, each resyncing at the next LF | 20,000 | 0 |
| 16 byte ranges, resync at next LF | 20,001 | 1 |
| 64 byte ranges, resync at next LF | 20,004 | 4 |
| 4, 16 or 64 byte ranges cut at record boundaries | 20,000 | 0 |
The most dangerous rows are the clean ones. Splitting into pieces of 5,000 or 1,000 lines happened not to cut inside a quoted note, so a test at that size passes. At 250 lines a cut landed inside a note, and the first bad row is a single field holding Leave with the front desk.": the second half of a note parsed as a record of its own. The more pieces, the more cuts, the more damage. Whether a given split is safe depends on where the multi-line notes fall, which is to say on luck.
Why byte-range readers break the same way
Parallel readers usually split a file into byte ranges, one per worker. Each worker seeks to its start offset, skips forward to the next line break, and reads records until it passes the end of its range. That resync step assumes every line break ends a record. When the offset lands inside a quoted note, the worker starts mid-field, the parser sees the closing quote as an opening one, and records are shifted or merged until the quotes happen to realign.
The fix is to cut where records actually end. The example makes one sequential pass that tracks whether it is inside quotes and records the offset after every LF outside quotes; each worker then starts at the first record boundary at or after its byte offset:
def record_boundaries(data):
"""One sequential pass tracking quote parity: offsets where a record ends outside quotes."""
out, quoted = [], False
for i, byte in enumerate(data):
if byte == 0x22:
quoted = not quoted # a doubled quote flips twice, so parity stays right
elif byte == 0x0A and not quoted:
out.append(i + 1)
return outA doubled quote inside a field flips the state twice, so parity stays correct for RFC 4180 files. With boundaries found this way, every worker count produced exactly 20,000 rows and no malformed ones. The pass is sequential, but it only scans bytes for one character class and can be done once at ingestion and stored as an index next to the file.
What Spark does with it
Spark's CSV source makes the tradeoff explicit with the multiLine option, which is off by default. The Spark 4.1.1 documentation describes it as allowing a row to span multiple lines by parsing line breaks within quoted values as part of the value itself. With it off, Spark splits files by line like the byte-range readers above, so a quoted line break ends the record early and the rest of the value becomes a record of its own. Depending on the schema and the parse mode, the fragments are flagged as corrupt, dropped, or kept with nulls; a fragment whose field count happens to match the schema can pass as a valid row. Turning multiLine on parses quoted line breaks correctly, at the price of parsing each file as a whole rather than splitting it across tasks.
So for Spark: if your CSV can contain quoted newlines, set multiLine to true and make files small enough that per-file parallelism is acceptable, or convert to a format with unambiguous record boundaries at ingestion.
Python and other readers
Python's csv module parses quoted newlines correctly, but only if the file is opened with newline=''. The documentation says so in a footnote, and the example shows why: with newline='', 195 notes keep their embedded CRLF; without it, universal newline translation rewrites every CRLF to LF before the parser sees it, and 0 do. The row count is the same, so nothing fails; the data is just different.
DuckDB 2.0.1 read the same file as 20,000 rows with 589 notes containing a line break, with and without parallel reading, in the example's optional probe. Mature CSV readers handle this case; the bugs live in the glue code around them: split -l, head -n, wc -l, line-based sampling, and home-grown chunkers.
Failure modes
- Wrong counts and false alarms. Reconciliation by line count fires on valid files, and people learn to ignore it.
- Truncated values that pass validation. A note cut in two can leave a record with the right number of fields, so schema checks pass and the data is wrong.
- Shifted columns. A fragment that starts mid-field can push values into the wrong columns for several records.
- Lost line endings. Reading without
newline=''in Python changes field content silently. - Tests that pass by luck. Small fixtures or large split sizes put no cut inside a quoted field.
Tradeoffs
| Approach | Cost | Benefit |
|---|---|---|
| Single sequential parse | No parallelism within a file | Always correct |
| Record-boundary index, then parallel parse | One extra pass | Parallel and correct |
Spark multiLine on | One task per file | Correct with no custom code |
| Producer removes or escapes newlines | Changes the data contract | Line-based tools work again |
| Convert to Parquet at ingestion | One conversion job | Every later reader is safe |
Changing the producer is tempting but means agreeing a non-standard format with everyone who reads the file. Converting once at ingestion to a columnar format with explicit record boundaries is usually the cleanest end state.
Verification
Count records with a CSV parser, never with wc -l, and alert on the difference between the two only as information. Put a fixture in your tests that contains quoted LF, quoted CRLF, doubled quotes and a newline as the very last character of a field, and run every splitter and parallel reader against it at several piece sizes, including small ones. Compare the parsed result with a single sequential parse, field by field, not just row counts. The companion example's tests do exactly that.
Running the companion code
cd examples/python/csv_quoted_newlines
python example.py
python -m unittest -v test_example.py
pip install -r requirements.txt && python live_probe_duckdb.pyThe example generates the file in a temporary directory, so it leaves nothing behind. Only the optional DuckDB probe installs anything.