Skip to content

feat(csv): .csv.read {strict: true} refuses a malformed row or cell, naming the line and the column - #1888

Merged
singaraiona merged 1 commit into
devfrom
fix/1885-csv-strict
Nov 28, 2026
Merged

singaraiona merged 1 commit into
devfrom
fix/1885-csv-strict

Conversation

@singaraiona

@singaraiona singaraiona commented Nov 27, 2026 •

Copy link
Copy Markdown
Collaborator

.csv.read reads a row with too few cells, too many, or a cell that does
not parse as its column's type without an error: the cell becomes a null
and extra cells are dropped. It now takes an opt-in options dict,
(.csv.read {strict: true} [types] "path"), as .csv.splayed and
.csv.parted take {compress: ...}. Under it such a row is a parse
error naming the file, the line and the column:

.csv.read "bad.csv": line 3: expected 3 cells, got 2
.csv.read "bad.csv": line 5, column c: "abc" is not an F64

The default stays lenient and unchanged. strict is the option's only
key on .csv.read; an unknown key, a non-bool value, a second dict or one
that is not the first argument is a domain error, as for compress.
Each argument arrangement of the three loaders now consumes exactly its
own arguments: one left over was silently dropped and is an arity
error.

The rule: a non-empty cell must be stored as the value its text says.
What strict refuses, decided by what the lenient reader does today:

  • a row whose cell count is not the schema's. A cell is a field ended by
    the delimiter, the line end or the end of the file, so a trailing
    delimiter adds an empty cell and a blank line, a trailing one included,
    is one empty cell: an error unless the table has one column. A final
    line without a newline is an ordinary row. Without a header the schema,
    not the first line, gives the cell count, so the first row is checked
    as every other row is (lenient sizes the table from it);
  • a non-empty cell lenient turns into a null (into false or 0 for B8 and
    U8, which hold no null). A number with a space around it (" 1",
    "2.5 ") reads as a null today, so strict refuses it; a leading "+"
    parses, so strict takes it. An empty cell (,, or "") is a null in
    both modes;
  • a number out of its column's range, "300" is out of range for a U8.
    Lenient keeps these as something else, and is left so here: it wraps an
    integer to the column's width (300 in a U8 reads as 44, 40000 in an I16
    as -25536, 3000000000 in an I32 as -1294967296), stores the type's
    minimum, which is its null sentinel (-32768 in an I16), and turns a
    float past the F32 range into an infinity, which is a null by the fix(io): a raw float infinity becomes the null where data enters #1828
    rule. A wrapped value is worse than a null, so strict refuses each.
    The ranges are U8 0..255, I16/I32/I64 minimum+1..maximum, F32/F64
    finite; I64 overflow and 1e400 in an F64 already read as nulls and are
    now named as out of range too. The temporal types are held to the
    same: a TIMESTAMP past 1707-09-22T00:12:43.145224193 ..
    2292-04-10T23:47:16.854775807, which lenient's arithmetic wraps
    (9999-01-01T00:00:00 reads as an instant in 1815; the overflow is
    signed, so strict parses timestamps with checked arithmetic of its own
    and never runs lenient's on them), and a TIMESPAN that wraps past
    INT64_MAX (106752D00:00:00 reads as a negative duration) or lands on
    the 0Wn infinity, are out of range;
  • a non-zero float text that stores as zero: "1e-400" underflows to zero for an F64 (1e-400 and 2e-324 in an F64, 1e-50 and 1e-46 in an
    F32, either sign), the counterpart of overflow to an infinity.
    Rounding to the nearest value the type holds is not a loss, a non-zero
    subnormal (5e-324, 1e-45 in an F32) included;
  • text that spells the type's null: "-32768" reads as a null I16. The
    sentinels are the minimum of I16, I32, I64, TIME (-596:31:23.648) and
    TIMESTAMP (1707-09-22T00:12:43.145224192), the all-zero GUID, and 0Nn;
  • fraction digits a time cannot hold, when they are not zeros:
    "10:00:00.1234" has more fraction digits than a TIME holds (TIME keeps
    milliseconds, TIMESPAN and TIMESTAMP nanoseconds; lenient drops them).
    Every other value lenient reads is read the same way: on a file of all
    fourteen column types the two give identical tables, and what
    .csv.write writes, nulls included, reads back;
  • a quoted cell with text after its closing quote, or with no closing
    quote: lenient splits the first into an extra cell and runs the second
    to the end of the file. The header's cells are held to the same:
    line 1: header cell 1: text after the closing quote;
  • in a file without quotes, text after a lone CR inside a row. Such a
    file splits rows at LF only and a cell ends at CR, so lenient never
    reads that text.

The line is the file's: the header is line 1 when there is one, and
newlines inside quoted cells, CRLF and lone-CR line ends count, so it is
the line an editor shows the row starting on. Every row is parsed and
each worker keeps the first bad row it saw; the error is the smallest, so
the parallel reader names the first bad line of the file, as the serial
one does (checked at 1, 4 and 28 workers and across a parted chunk
boundary). The message is built once, from that row alone, re-cut as the
parse cut it, and composed to fit the 255 bytes an error holds: the
operation, the path, the line, the column, the reason and the type come
first, then the cell text gets what room is left, at most 40 bytes of the
cell, cut on whole characters and whole escapes (quotes, control bytes and
bytes that are not UTF-8 are escaped, never split) and ending in "...".
The path and the column name are shortened first only if they would leave
the text no room.

.csv.splayed and .csv.parted parse through the same rows-to-columns
code (csv_materialize_rows), so they take strict beside compress; the
message is headed by the builtin, and a parted import that fails after
writing a partition adds ; partial output retained in "<dir>", as its
other failures already say; the message is composed with that note's room
kept, so cutting the cell text never cuts the note. For them the last row of a chunk now ends at
the next chunk's start rather than the end of the file, which only strict
looks past. The C API gains ray_read_csv_ex,
ray_csv_save_splayed_ex and ray_csv_save_parted_ex, taking a
ray_csv_opts_t; the existing entry points are unchanged.

The default path is the same machine code as before. The lenient
csv_parse_fn and csv_parse_serial are dev's functions, unchanged; the
strict parse is its own copy beside them (it takes the place of nothing:
dev already kept two copies of this loop). Sharing one body behind a
compile-time flag cost the default parse 3-4% under gcc on a quoted file
from register allocation alone, and passing the serial parse through the
context cost 1-3% more instructions under clang, so neither was kept. The
new context fields are last so the default parse reads its fields at the
same offsets; csv_parse_serial is kept out of line, as it was with two
callers. With gcc both functions disassemble identically to dev's, and
the instructions a load runs match dev's to 0.001% under gcc and clang.

Interleaved timings, best of 7, ms, clean gcc release builds (the
compiler CI builds), one worker pinned to a performance core and all 28;
the machine was shared, load average 5 to 16 during the runs. A 1 GB
file of 13M rows (I64 F64 SYM STR DATE TIMESTAMP I32 B8), a 520 MB one of
6.5M rows whose STR cells are quoted with commas and some with newlines,
a 520 MB one of 6M rows of eight types with TIME and TIMESTAMP (I64 F64
SYM STR DATE TIME TIMESTAMP I32), and an 8000-row file read 2000 times
(the serial parse); strict is against this build's default:

file workers dev this strict
1 GB 1 1740 1745 (+0.3%) 1823 (+4.4%)
1 GB all 386 386 (+0.0%) 389 (+0.9%)
quoted 1 1256 1257 (+0.0%) 1327 (+5.6%)
quoted all 207 206 (-0.9%) 213 (+3.4%)
8 types, TIME 1 843 852 (+1.1%) 894 (+5.0%)
8 types, TIME all 205 205 (+0.2%) 211 (+2.9%)
8000 rows x2000 1 1522 1513 (-0.6%) 1597 (+5.6%)

The default is the same code as dev's and runs the same instructions
(1 GB: 33315637065 against 33315639577), so no shape is slower beyond
noise. Strict costs more where cells are short, since its checks are per
cell: on 3M-row files of one column, at one worker, GUID +1%, SYM +5%,
TIMESTAMP +9%, STR +9%, F64 +9%, I64 +12%, DATE +13%, B8 +15%, TIME and
TIMESPAN +19%. So about 5% on a mixed file (a review measured 12% on
another eight-type file), up to about 20% on a file of only short time
cells, and less across all cores. The checks on TIME and TIMESPAN read
the fraction back from the end of the cell, which took those two from
+29% and +28%.

Tests: test/rfl/io/csv_strict.rfl, which fails on dev (the options dict
is read as the path) and covers the option's errors, the argument
arrangements, every rule above (each integer width at and past its
limits, the temporal ranges and sentinels, F32 and F64 overflow and
underflow), line
numbers with a header and without, the header's quotes, quoted newlines,
CRLF and lone CR, every column type both ways, the parallel reader's
first bad line, .csv.splayed/.csv.parted with a bad line after a
written partition, and messages that would pass 255 bytes.
csv/strict_matrix (test_csv.c) checks each rule for every column type on
the first row, a middle row and the last one, at 10 rows (the serial
parse) and 8300 (the parallel one), with a header and without: 1248
cases, each expecting its line and reason, and each valid file reading.

Fixes #1885
BREAKING CHANGE: .csv.read, .csv.splayed and .csv.parted refuse an
argument their arrangement does not consume (an arity error, a domain
error for an options dict that is not the first argument) where it was
silently dropped.

@singaraiona singaraiona left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of b3b9f73: NEEDS CHANGES

  1. Strict still accepts non-empty nulls and wrapped temporal values. The TIME/TIMESPAN/TIMESTAMP/GUID arms of csv_parse_fn_strict trust the existing parsers' is_null flags, which do not establish the new strict contract. For a file containing v\n<CELL>\n, .csv.read {strict: true} [TYPE] path succeeds on all of these:

    TYPE CELL Result
    TIME -596:31:23.648 null sentinel; nil? is true
    TIMESTAMP 1707-09-22T00:12:43.145224192 null sentinel in release; nil? is true
    GUID 00000000-0000-0000-0000-000000000000 null; nil? is true
    TIMESTAMP 9999-01-01T00:00:00 wrapped int64 timestamp
    TIMESPAN 106752D00:00:00 wraps past INT64_MAX to a negative duration

    The same inputs succeed through .csv.splayed and .csv.parted; checked with pools of 1, 4 and 28 workers. Under UBSan, both timestamp examples stop at csv.c:713 on signed overflow before a parse error can be returned. These lenient arithmetic behaviors predate this PR; the finding is that the new strict path also accepts them. Check temporal range before overflowing arithmetic, and reject non-empty sentinel results as the integer arms already do, without changing the default path.

  2. The initial row/header bypasses strict validation. The column-count/header phase runs before the strict row checker (csv.c:3613). With a headerless file 1\n2,3\n, (.csv.read {strict: true} [a b] [I64 I64] path) returns length, “schema has 2 types but file has 1 columns”, with no file line; it should report the malformed first data row as a strict parse error at line 1. Extra cells and a blank first row take the same bypass. Also, a header consisting of "v\n (no closing quote) succeeds with [STR]; "v"junk\n succeeds too, treating junk as data instead of rejecting text after the header's closing quote. Reproduced on all three read/import forms. Apply strict structural checks to the first data row and quoted header fields as well as later rows.

  3. The 255-byte error limit can cut escapes/UTF-8 and remove the partial-output notice. csv_strict_error bounds each input independently, but their escaped expansions do not fit together. A source pathname over 120 bytes, a two-column header a,b, one valid row, and a bad I64 cell containing 60 bytes of 0x01 produces a 255-byte message ending inside \x01, losing the type/reason. With rows-per-part 1, .csv.parted leaves root.csv-partial/0/t/{.d,a,b} but the appended notice at builtins.c:1222 is entirely absent. This also breaks otherwise valid UTF-8: with a long pathname, a header of six 0x01 bytes followed by ab, and a cell of 29 0x01 bytes followed by 40 é characters, the message ends in an isolated byte c3. Budget the complete formatted diagnostic, including any retained-output notice, before clipping escaped text.

  4. A non-adjacent second options dict is silently ignored. For a valid v\n1\n file, (.csv.read {strict: true} [I64] path {strict: false}) succeeds. The second-dict check only examines args[1]; after removing the leading dict, the schema/path branch accepts n == 3 and discards the remaining argument (builtins.c:905, 924). This contradicts the documented second-dict domain error. Validate that the chosen positional signature consumes every argument.

Validation: GCC release/debug builds; make -j4 CC=gcc test TEST_ARGS="-j 4" passed 5,935 tests, four skipped, zero failed; make docs-check passed. Independent probes covered 154 small type/value cases, a 20,000-row 14-type strict/lenient/dev serialization differential, and 225 bad-cell checks using parallel-sized files at 1/4/28 workers. Quoting, escaped quotes, quoted newlines, CRLF/lone CR, empty/trailing fields, blank lines, EOF without newline and headerless inputs were exercised. Earliest-error selection passed on a deliberately expensive earlier chunk and at a million-row import boundary across all three routes. Another 181 focused parser calls and 40 failed imports ran under ASan/UBSan without sanitizer findings, apart from the separately reproduced timestamp overflow above. Normal parted failures retained the completed first partition and named its staging directory; failures before a partition left no staging directory.

Performance: interleaved GCC release runs against dev b65eab9, using a 648 MB / 9M-row eight-type file. At one worker pinned to CPU 4, medians were dev 707.97 ms, default 709.67 ms (+0.24%), strict 749.18 ms (+5.57% versus default). A focused 20-sample all-28-worker comparison gave dev controls 131.67/133.57 ms and head 133.39 ms; no clear default slowdown beyond control variation. The seven-sample strict comparison at 28 workers was 143.01 versus 138.41 ms (+3.33%). Both lenient parser functions have identical normalized disassembly after accounting for code/data addresses. The default results matched dev in the differential.

The commit is single and its final paragraph is Fixes #1885; required PR checks are green. Not covered: Windows/macOS, other compilers, exhaustive encodings or grammar combinations, fault injection, cold-disk throughput, every compression mode, or all existing-root update scenarios. Temporary evidence, fixtures and build outputs will be removed after posting.

@singaraiona singaraiona left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of f1e16db: NEEDS CHANGES

The four findings of the review at b3b9f73 are fixed. One gap is left in the "stored as the value its text says" rule.

Finding

  1. A non-zero float that underflows is stored as zero (strict F64 and F32 cell parsing in src/io/csv.c). Under {strict: true}, for a file v\n<cell>\n:

    type cell stored
    F64 1e-400 0.0
    F64 -1e-400 0.0
    F64 2e-324 0.0
    F32 1e-50 0.0e
    F32 1e-46 below F32's smallest subnormal; strict accepts it

    It is the same at 1, 4 and 28 workers. The text names a non-zero value, and the column keeps zero.

    • That is the case the rule refuses elsewhere. A TIMESPAN 0D00:00:00.0000000001 and a TIME 12:00:00.1234 are refused as "more fraction digits than … holds", and 1e309 is refused as out of range.
    • An underflow to zero is the float form of the same loss. The commit's rule ("a non-empty cell must be stored as the value its text says, for every type") and the docs' range list (F32 and F64 finite) leave it open.
    • Fix: refuse a cell whose digits are not all zero but which parses to ±0 (strtod's ERANGE underflow), as out of range for its type. Then say in the docs whether a subnormal result counts. 3e-324 → 4.94e-324 is rounding, not loss; an F32 subnormal like 1e-40 is the same question.
    • Test: add the rows above to csv_strict.rfl and the matrix.

Observation

Strict cost on my 9M-row file (8 columns: I64, F64, SYMBOL, DATE, TIME, B8, U8 and TIMESTAMP with 6 fraction digits; 745 MB) is above the commit's 5–7%. I ran release builds, interleaved, 5 rounds, each taking the minimum of 5 loads:

dev PR default PR strict
1 worker, pinned 1686 ms 1691 ms (+0.3%) 1891 ms (+11.8%)
28 workers 162.6 ms 161.3 ms 177.0 ms (+9.7%, noisy)

The default path costs nothing. Strict's extra cost is likely its own checked timestamp and time parsing on two of the eight columns. The load average was 5.7–13 during these runs. It is worth a line in the commit message that the cost depends on the column types.

What I checked

The earlier review's repros, on this head.

  • Finding 1:
    • TIME -596:31:23.648, TIMESTAMP 1707-09-22T00:12:43.145224192, the all-zero GUID, 0Nn, and the null-sentinel integers (-32768, -2147483648, -9223372036854775808) answer "reads as a null".
    • TIMESTAMP 9999-01-01T00:00:00 and TIMESPAN 106752D00:00:00 answer "out of range".
    • TIMESTAMP's limits hold at both ends to the nanosecond: …16.854775807 and …43.145224193 are accepted, one past either is refused.
  • Finding 2:
    • A headerless 1\n2,3\n answers line 1: expected 2 cells, got 1, and the same goes for extra cells and a blank first row.
    • A header "v answers "a quoted cell with no closing quote", and "v"junk answers "text after the closing quote".
    • This holds for .csv.splayed and .csv.parted too.
  • Finding 3: see the messages below.
  • Finding 4:
    • (.csv.read {strict: true} [I64] path {strict: false}) answers domain, "a second options dict".
    • A dict after the path answers domain, "must be the first argument".
    • An extra argument answers arity.

Other cells (110 type/cell cases). In each case strict either refuses the cell, or stores what the text says.

  • Integers: +5, 05 and -0; edges of every width; U8 256 and -1; I16 40000.
  • B8: true, TRUE, 1, yes, t, 2.
  • Floats: F64 nan, inf, 0x1p3, 0n, 0w, 1e309; F32 3.5e38.
  • DATE: invalid days, months and leap days; both separators.
  • TIME: 24:00:00 and -00:00:01 are kept as durations; 12:60:00 is refused.
  • TIMESTAMP: Z and +01:00 give the right instant, and a space separator is accepted.
  • TIMESPAN: 1D25:00:00 keeps its 49 hours.
  • GUID: upper case is accepted; braces and bad digits are refused.
  • Quoted STR and I64 cells.

Lines under the parallel reader. The file has 200,000 rows, a quoted newline at row 10, and bad rows at 120,000 and 150,000.

  • At 1, 4 and 28 workers, the error names line 120003, the file's own line, and the earlier bad row wins.
  • With CRLF, the last row reports line 200002.
  • A bad first row reports line 2.

Messages, under ASan+UBSan. The source path has a 150-byte directory. I tried:

  • 60 0x01 bytes; a header of six 0x01 bytes and ab with a cell of 29 0x01 bytes and 40 é; 200 é;
  • 80 repeats of ff fe c3; NUL bytes in a cell; backslash escapes;
  • a 300-byte column name;
  • parted imports with rows-per-part 1.

Every message is at most 255 bytes, ends with its reason and type, cuts on whole characters and escapes, and is valid UTF-8. The parted messages keep their partial output retained in "…" note, and the staging directory exists.

csv/strict_matrix, csv_strict and the csv tests (107, 1 skipped) pass with no report.

Argument check. On dev and on this head I ran the documented forms of .csv.read, .csv.splayed and .csv.parted: bare path, types, names and types, rows-per-part, {compress: true} and {compress: true strict: true}. Every one still answers. The only new refusals are an extra argument and a misplaced or second options dict: the declared breaking change. A string in the rows-per-part slot, which dev also accepted, is now an arity error, which is consistent with that change.

Suite and commit.

  • The gcc suite: 5936 of 5940 passed, 4 skipped, 0 failed.
  • The trailer block (Fixes #1885, then BREAKING CHANGE: …) follows the repository's usual form. Git does not parse it as trailers, as with earlier commits, and no release tooling reads it. The BREAKING CHANGE text wraps over three lines, which is fine.

Not covered

  • Windows and macOS.
  • Other compilers for timing.
  • Cold-disk loads.
  • Every compression mode.
  • The .csv.splayed and .csv.parted timing: only .csv.read was timed.

@singaraiona singaraiona left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of 21bbdea: READY

The finding is fixed: strict no longer stores a non-zero float text as zero.

Underflow.

  • Refused, each with both signs, as "<text>" underflows to zero for an F64/F32:
    • F64 1e-400 and 2e-324; F32 1e-50 and 1e-46;
    • F64 0.0001e-320.
  • Accepted:
    • the values that round to a non-zero subnormal: F64 3e-324, 4.9e-324, 5e-324; F32 1e-45, 1.5e-45, 1e-40;
    • every zero spelling: 0, 0.0, -0.0, 0e-500, 0.000e10, 00.00, and F32 0 and -0.0;
    • F64 1e-300.
  • Default: lenient answers are unchanged.
  • Parallel reader: at 300,000 rows, the cell is refused at the file's line 300002 at 1 and 28 workers.

The three reworked checks refuse what they refused.

  • TIME (now csv_frac_tail_kept): 12:00:00.1234, 23:59:59.9999 and 1:00:00.0001 are refused; .1230 and .123 are accepted; the sentinel -596:31:23.648 is refused.
  • TIMESPAN:
    • The fraction check refuses 0D00:00:00.0000000001 and accepts .1234567890.
    • The range check (fast path for under six day digits, then csv_timespan_fits_slow) refuses 106752D00:00:00 and both ±106751D23:47:16.854775807, which reach 0Wn. It accepts 106751D23:47:16.854775806, 99999D and 100000D.
    • 0Nn is refused; 0Wn and -0Wn are accepted.
  • TIMESTAMP (inlined checked parse): ten fraction digits are refused. 9999-01-01 and one nanosecond past either limit are refused, and both limits are accepted. The sentinel is refused, and +01:00 gives the right instant.

Cell count first. A row with a bad cell and also too many or too few cells reports expected 2 cells, got N. I checked a bad I64, a null sentinel and an underflow.

Default path. The diff since f1e16db touches only strict code:

  • csv_parse_fn_strict;
  • helpers called only from it: csv_float_text_nonzero, csv_frac_tail_kept, csv_timespan_fits, and the inlined csv_strict_timestamp;
  • the new error kind and its message;
  • the docs and tests.

csv_parse_fn and the serial parse are untouched.

Cost against the docs. On my 9M-row, 8-type file (I64, F64, SYMBOL, DATE, TIME, B8, U8, TIMESTAMP; release build; pinned at one worker; 4 rounds of 5 loads each, the minimum taken):

  • default 1696.6 ms, strict 1861.6 ms: +9.7%, down from +11.8% at f1e16db;
  • at 28 workers the runs were within noise (load average 4.9–12.4).

That sits inside the docs' "about 5% … measured up to 12%" for mixed files. Mine has two temporal columns of eight, the upper end of that.

Tests. The csv tests pass: 88 of 89, 1 skipped.

Not covered: a full suite and ASan this round (the change since the last ASan pass is the underflow check and the three helpers above); Windows and macOS.

@singaraiona
singaraiona added this pull request to the merge queue Nov 28, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 28, 2026
…naming the line and the column

`.csv.read` reads a row with too few cells, too many, or a cell that does
not parse as its column's type without an error: the cell becomes a null
and extra cells are dropped.  It now takes an opt-in options dict,
`(.csv.read {strict: true} [types] "path")`, as `.csv.splayed` and
`.csv.parted` take `{compress: ...}`.  Under it such a row is a `parse`
error naming the file, the line and the column:

    .csv.read "bad.csv": line 3: expected 3 cells, got 2
    .csv.read "bad.csv": line 5, column c: "abc" is not an F64

The default stays lenient and unchanged.  `strict` is the option's only
key on `.csv.read`; an unknown key, a non-bool value, a second dict or one
that is not the first argument is a `domain` error, as for `compress`.
Each argument arrangement of the three loaders now consumes exactly its
own arguments: one left over was silently dropped and is an `arity`
error.

The rule: a non-empty cell must be stored as the value its text says.
What strict refuses, decided by what the lenient reader does today:

- a row whose cell count is not the schema's.  A cell is a field ended by
  the delimiter, the line end or the end of the file, so a trailing
  delimiter adds an empty cell and a blank line, a trailing one included,
  is one empty cell: an error unless the table has one column.  A final
  line without a newline is an ordinary row.  Without a header the schema,
  not the first line, gives the cell count, so the first row is checked
  as every other row is (lenient sizes the table from it);
- a non-empty cell lenient turns into a null (into false or 0 for B8 and
  U8, which hold no null).  A number with a space around it (" 1",
  "2.5 ") reads as a null today, so strict refuses it; a leading "+"
  parses, so strict takes it.  An empty cell (`,,` or `""`) is a null in
  both modes;
- a number out of its column's range, `"300" is out of range for a U8`.
  Lenient keeps these as something else, and is left so here: it wraps an
  integer to the column's width (300 in a U8 reads as 44, 40000 in an I16
  as -25536, 3000000000 in an I32 as -1294967296), stores the type's
  minimum, which is its null sentinel (-32768 in an I16), and turns a
  float past the F32 range into an infinity, which is a null by the #1828
  rule.  A wrapped value is worse than a null, so strict refuses each.
  The ranges are U8 0..255, I16/I32/I64 minimum+1..maximum, F32/F64
  finite; I64 overflow and 1e400 in an F64 already read as nulls and are
  now named as out of range too.  The temporal types are held to the
  same: a TIMESTAMP past 1707-09-22T00:12:43.145224193 ..
  2292-04-10T23:47:16.854775807, which lenient's arithmetic wraps
  (9999-01-01T00:00:00 reads as an instant in 1815; the overflow is
  signed, so strict parses timestamps with checked arithmetic of its own
  and never runs lenient's on them), and a TIMESPAN that wraps past
  INT64_MAX (106752D00:00:00 reads as a negative duration) or lands on
  the 0Wn infinity, are out of range;
- a non-zero float text that stores as zero: `"1e-400" underflows to
  zero for an F64` (1e-400 and 2e-324 in an F64, 1e-50 and 1e-46 in an
  F32, either sign), the counterpart of overflow to an infinity.
  Rounding to the nearest value the type holds is not a loss, a non-zero
  subnormal (5e-324, 1e-45 in an F32) included;
- text that spells the type's null: `"-32768" reads as a null I16`.  The
  sentinels are the minimum of I16, I32, I64, TIME (-596:31:23.648) and
  TIMESTAMP (1707-09-22T00:12:43.145224192), the all-zero GUID, and 0Nn;
- fraction digits a time cannot hold, when they are not zeros:
  `"10:00:00.1234" has more fraction digits than a TIME holds` (TIME keeps
  milliseconds, TIMESPAN and TIMESTAMP nanoseconds; lenient drops them).
  Every other value lenient reads is read the same way: on a file of all
  fourteen column types the two give identical tables, and what
  `.csv.write` writes, nulls included, reads back;
- a quoted cell with text after its closing quote, or with no closing
  quote: lenient splits the first into an extra cell and runs the second
  to the end of the file.  The header's cells are held to the same:
  `line 1: header cell 1: text after the closing quote`;
- in a file without quotes, text after a lone CR inside a row.  Such a
  file splits rows at LF only and a cell ends at CR, so lenient never
  reads that text.

The line is the file's: the header is line 1 when there is one, and
newlines inside quoted cells, CRLF and lone-CR line ends count, so it is
the line an editor shows the row starting on.  Every row is parsed and
each worker keeps the first bad row it saw; the error is the smallest, so
the parallel reader names the first bad line of the file, as the serial
one does (checked at 1, 4 and 28 workers and across a parted chunk
boundary).  The message is built once, from that row alone, re-cut as the
parse cut it, and composed to fit the 255 bytes an error holds: the
operation, the path, the line, the column, the reason and the type come
first, then the cell text gets what room is left, at most 40 bytes of the
cell, cut on whole characters and whole escapes (quotes, control bytes and
bytes that are not UTF-8 are escaped, never split) and ending in "...".
The path and the column name are shortened first only if they would leave
the text no room.

`.csv.splayed` and `.csv.parted` parse through the same rows-to-columns
code (csv_materialize_rows), so they take `strict` beside `compress`; the
message is headed by the builtin, and a parted import that fails after
writing a partition adds `; partial output retained in "<dir>"`, as its
other failures already say; the message is composed with that note's room
kept, so cutting the cell text never cuts the note.  For them the last row of a chunk now ends at
the next chunk's start rather than the end of the file, which only strict
looks past.  The C API gains `ray_read_csv_ex`,
`ray_csv_save_splayed_ex` and `ray_csv_save_parted_ex`, taking a
`ray_csv_opts_t`; the existing entry points are unchanged.

The default path is the same machine code as before.  The lenient
`csv_parse_fn` and `csv_parse_serial` are dev's functions, unchanged; the
strict parse is its own copy beside them (it takes the place of nothing:
dev already kept two copies of this loop).  Sharing one body behind a
compile-time flag cost the default parse 3-4% under gcc on a quoted file
from register allocation alone, and passing the serial parse through the
context cost 1-3% more instructions under clang, so neither was kept.  The
new context fields are last so the default parse reads its fields at the
same offsets; csv_parse_serial is kept out of line, as it was with two
callers.  With gcc both functions disassemble identically to dev's, and
the instructions a load runs match dev's to 0.001% under gcc and clang.

Interleaved timings, best of 7, ms, clean gcc release builds (the
compiler CI builds), one worker pinned to a performance core and all 28;
the machine was shared, load average 5 to 16 during the runs.  A 1 GB
file of 13M rows (I64 F64 SYM STR DATE TIMESTAMP I32 B8), a 520 MB one of
6.5M rows whose STR cells are quoted with commas and some with newlines,
a 520 MB one of 6M rows of eight types with TIME and TIMESTAMP (I64 F64
SYM STR DATE TIME TIMESTAMP I32), and an 8000-row file read 2000 times
(the serial parse); strict is against this build's default:

| file | workers | dev | this | strict |
|---|---|---|---|---|
| 1 GB | 1 | 1740 | 1745 (+0.3%) | 1823 (+4.4%) |
| 1 GB | all | 386 | 386 (+0.0%) | 389 (+0.9%) |
| quoted | 1 | 1256 | 1257 (+0.0%) | 1327 (+5.6%) |
| quoted | all | 207 | 206 (-0.9%) | 213 (+3.4%) |
| 8 types, TIME | 1 | 843 | 852 (+1.1%) | 894 (+5.0%) |
| 8 types, TIME | all | 205 | 205 (+0.2%) | 211 (+2.9%) |
| 8000 rows x2000 | 1 | 1522 | 1513 (-0.6%) | 1597 (+5.6%) |

The default is the same code as dev's and runs the same instructions
(1 GB: 33315637065 against 33315639577), so no shape is slower beyond
noise.  Strict costs more where cells are short, since its checks are per
cell: on 3M-row files of one column, at one worker, GUID +1%, SYM +5%,
TIMESTAMP +9%, STR +9%, F64 +9%, I64 +12%, DATE +13%, B8 +15%, TIME and
TIMESPAN +19%.  So about 5% on a mixed file (a review measured 12% on
another eight-type file), up to about 20% on a file of only short time
cells, and less across all cores.  The checks on TIME and TIMESPAN read
the fraction back from the end of the cell, which took those two from
+29% and +28%.

Tests: test/rfl/io/csv_strict.rfl, which fails on dev (the options dict
is read as the path) and covers the option's errors, the argument
arrangements, every rule above (each integer width at and past its
limits, the temporal ranges and sentinels, F32 and F64 overflow and
underflow), line
numbers with a header and without, the header's quotes, quoted newlines,
CRLF and lone CR, every column type both ways, the parallel reader's
first bad line, `.csv.splayed`/`.csv.parted` with a bad line after a
written partition, and messages that would pass 255 bytes.
csv/strict_matrix (test_csv.c) checks each rule for every column type on
the first row, a middle row and the last one, at 10 rows (the serial
parse) and 8300 (the parallel one), with a header and without: 1248
cases, each expecting its line and reason, and each valid file reading.

Fixes #1885
BREAKING CHANGE: `.csv.read`, `.csv.splayed` and `.csv.parted` refuse an
argument their arrangement does not consume (an `arity` error, a `domain`
error for an options dict that is not the first argument) where it was
silently dropped.
@singaraiona

Copy link
Copy Markdown
Collaborator Author

Carry-over: 2565a77 is 21bbdea (Review of 21bbdea: READY) on the same parent with one line changed, test/rfl/io/csv_strict.rfl:185: the GNU-only 'sed -i' edit of the fixture is now 'sed ... > tmp && mv tmp file', which BSD sed also runs; the commit message is unchanged.

@singaraiona
singaraiona added this pull request to the merge queue Nov 28, 2026
Merged via the queue into dev with commit 1691a57 Nov 28, 2026
11 checks passed
singaraiona added a commit that referenced this pull request Nov 28, 2026
…each

A quoted STR or SYM cell with a doubled quote (`"say ""hi"""`) is
unescaped into a stack buffer, so the parse kept a copy of it until the
strings were filled in: `ray_sys_alloc(flen)`, which maps whole pages, and
a later unmap per cell.  At a few microseconds and at least 4 KB of
mapping a cell, a 2M-row file with one such cell per row read in 4.8 s
against 0.09 s without the escapes, and held 8.3 GB of mappings at its
peak.

Each worker now keeps its copies in 1 MB blocks it fills in turn (a copy
over a quarter block gets a block of its own), the workers' blocks go to
the load, and the load frees them where it freed the copies, on success,
failure and cancel alike.  A cell past the 8 KB stack buffer, which the
scanner unescapes into its own allocation, is copied the same way and its
allocation freed with the cell.  The per-column "had escaped" flags and
the per-row "strref initialized" marks existed only so the old cleanup
could find the copies among the strrefs, and are gone, with the n_rows
array the marks needed.  The strict parse (#1888) keeps its copies the
same way.

If a block cannot be allocated the load fails with `oom`: the worker
marks a flag the load shares (serial, parallel and strict parses alike),
the load checks it once the parse is over, frees every block and the rest
of what it built, and answers the error -- in .csv.read, and in each
batch of .csv.splayed and .csv.parted, which then fail as on any other
batch error.  A cell is never kept wrong.  On dev the same failure was
worse than an empty cell: the strref kept pointing at the dead stack
buffer, so the cell read as whatever later rows left there, and the
cleanup then passed that stack address to the allocator's free (with a
failure injected into dev's per-cell copy, a 6-row read stops under UBSan
in src/mem/sys.c, reading the freed "header" at the stack address).

Interleaved timings, best of 7 (5 at 28 workers), ms, clean gcc release
builds of dev (1691a57) and this, one worker pinned to a performance
core and all 28; the machine was shared, load average 4 to 13.  The
escaped-cell file is 2M rows of `id,"n,<i>""x"` read as [I64 STR]; the
others are the files of #1888's measurements: 1 GB of 13M rows (I64 F64
SYM STR DATE TIMESTAMP I32 B8), 520 MB of 6.5M rows with quoted STR cells,
520 MB of 6M rows of eight types with TIME and TIMESTAMP, and an 8000-row
file read 2000 times (the serial parse):

| file | workers | dev | this |
|---|---|---|---|
| escaped cells, 2M rows | 1 | 4756 | 110-116 (-97.6%) |
| escaped cells, 2M rows | all | 8438-9137 | 24.1-26.6 (-99.7%) |
| 1 GB | 1 | 1758 | 1766 (+0.5%) |
| 1 GB | all | 408 | 411 (+0.7%) |
| quoted, 520 MB | 1 | 1270 | 1257 (-1.0%) |
| quoted, 520 MB | all | 225 | 223 (-0.8%) |
| 8 types, 520 MB | 1 | 840 | 844 (+0.5%) |
| 8 types, 520 MB | all | 203 | 201 (-0.6%) |
| 8000 rows x2000 | 1 | 1518 | 1489 (-1.9%) |

Anonymous memory peak of the read (`.sys.mem` anon-peak, after less
before): 100k escaped cells 410 MB -> 13.8 MB; 2M escaped cells 8.29 GB
-> 130 MB.  Instructions of a default load without escapes, against dev:
1 GB +0.19%, quoted +0.10%, the serial file -1.2% (no per-row marks to
write); no shape is slower beyond run-to-run noise.

Test: test/rfl/io/csv_escaped_cells.rfl, which fails on dev (the read
raises the anonymous peak by about 400 MB) and checks the values of
escaped cells small, past the 8 KB stack buffer and past a quarter block,
as STR and SYM, across the parallel parse and through .csv.splayed.  It
runs first in a fresh worker under -j (test/main.c fresh_tests), so the
peak it bounds is its own.  csv/escaped_alloc_fail (test_csv.c) fails each
block allocation in turn through a test hook (ray_csv_esc_fail_for_test,
DEBUG only: the blocks come from the system allocator, which the heap's
failure sweeps do not reach) in a 50-row file (the serial parse) and a
20000-row one (the parallel parse), each read lenient and strict and
imported with .csv.splayed and .csv.parted, and expects `oom` with the
system allocator's committed bytes back where they were; with the flag
not checked it answers success at the first failure.  (The second row of
timings is after the oom change: the escaped-cell file runs the same
instructions, 2131599106 against 2131595748; the ordinary files stay
within 0.7% of dev.)

Fixes #1890
singaraiona added a commit that referenced this pull request Nov 28, 2026
…each

A quoted STR or SYM cell with a doubled quote (`"say ""hi"""`) is
unescaped into a stack buffer, so the parse kept a copy of it until the
strings were filled in: `ray_sys_alloc(flen)`, which maps whole pages, and
a later unmap per cell.  At a few microseconds and at least 4 KB of
mapping a cell, a 2M-row file with one such cell per row read in 4.8 s
against 0.09 s without the escapes, and held 8.3 GB of mappings at its
peak.

Each worker now keeps its copies in 1 MB blocks it fills in turn (a copy
over a quarter block gets a block of its own), the workers' blocks go to
the load, and the load frees them where it freed the copies, on success,
failure and cancel alike.  A cell past the 8 KB stack buffer, which the
scanner unescapes into its own allocation, is copied the same way and its
allocation freed with the cell.  The per-column "had escaped" flags and
the per-row "strref initialized" marks existed only so the old cleanup
could find the copies among the strrefs, and are gone, with the n_rows
array the marks needed.  The strict parse (#1888) keeps its copies the
same way.

If a block cannot be allocated the load fails with `oom`: the worker
marks a flag the load shares (serial, parallel and strict parses alike),
the load checks it once the parse is over, frees every block and the rest
of what it built, and answers the error -- in .csv.read, and in each
batch of .csv.splayed and .csv.parted, which then fail as on any other
batch error.  A cell is never kept wrong.  On dev the same failure was
worse than an empty cell: the strref kept pointing at the dead stack
buffer, so the cell read as whatever later rows left there, and the
cleanup then passed that stack address to the allocator's free (with a
failure injected into dev's per-cell copy, a 6-row read stops under UBSan
in src/mem/sys.c, reading the freed "header" at the stack address).

Interleaved timings, best of 7 (5 at 28 workers), ms, clean gcc release
builds of dev (1691a57) and this, one worker pinned to a performance
core and all 28; the machine was shared, load average 4 to 13.  The
escaped-cell file is 2M rows of `id,"n,<i>""x"` read as [I64 STR]; the
others are the files of #1888's measurements: 1 GB of 13M rows (I64 F64
SYM STR DATE TIMESTAMP I32 B8), 520 MB of 6.5M rows with quoted STR cells,
520 MB of 6M rows of eight types with TIME and TIMESTAMP, and an 8000-row
file read 2000 times (the serial parse):

| file | workers | dev | this |
|---|---|---|---|
| escaped cells, 2M rows | 1 | 4756 | 110-116 (-97.6%) |
| escaped cells, 2M rows | all | 8438-9137 | 24.1-26.6 (-99.7%) |
| 1 GB | 1 | 1758 | 1766 (+0.5%) |
| 1 GB | all | 408 | 411 (+0.7%) |
| quoted, 520 MB | 1 | 1270 | 1257 (-1.0%) |
| quoted, 520 MB | all | 225 | 223 (-0.8%) |
| 8 types, 520 MB | 1 | 840 | 844 (+0.5%) |
| 8 types, 520 MB | all | 203 | 201 (-0.6%) |
| 8000 rows x2000 | 1 | 1518 | 1489 (-1.9%) |

Anonymous memory peak of the read (`.sys.mem` anon-peak, after less
before): 100k escaped cells 410 MB -> 13.8 MB; 2M escaped cells 8.29 GB
-> 130 MB.  Instructions of a default load without escapes, against dev:
1 GB +0.19%, quoted +0.10%, the serial file -1.2% (no per-row marks to
write); no shape is slower beyond run-to-run noise.

Test: test/rfl/io/csv_escaped_cells.rfl, which fails on dev (the read
raises the anonymous peak by about 400 MB) and checks the values of
escaped cells small, past the 8 KB stack buffer and past a quarter block,
as STR and SYM, across the parallel parse and through .csv.splayed.  It
runs first in a fresh worker under -j (test/main.c fresh_tests), so the
peak it bounds is its own.  csv/escaped_alloc_fail (test_csv.c) fails each
block allocation in turn through a test hook (ray_csv_esc_fail_for_test,
DEBUG only: the blocks come from the system allocator, which the heap's
failure sweeps do not reach) in a 50-row file (the serial parse) and a
20000-row one (the parallel parse), each read lenient and strict and
imported with .csv.splayed and .csv.parted, and expects `oom`, and no
block live after any run, failed or not (the hook counts blocks allocated
less blocks freed: they are mapped pages, which the leak checker does not
see).  With the flag not checked it answers success at the first failure;
with one free left out it reports the blocks left live.  It passed 20 runs
of 20 at each of RAYFORCE_CORES 1, 2, 4, 8 and 28.  (The second row of
timings is after the oom change: the escaped-cell file runs the same
instructions, 2131599106 against 2131595748; the ordinary files stay
within 0.7% of dev.)

Fixes #1890
singaraiona added a commit that referenced this pull request Nov 28, 2026
…he file or without

The CSV row splitter has two paths.  For a file with quotes it walks the
bytes and ends a row at LF, CRLF or a lone CR; for a file without quotes
it searched for LF only.  The cell scanner ends a cell at CR in both, so
in a quote-free file with CR line ends everything after a row's first CR
was never read: `a,b\r1,2\r3,4\r` read as one row, and with one quoted
cell anywhere in the file the same text read as two.  And the header
reader consumed a CR, then an LF -- CRLF, but not LFCR -- so after an
`a,b\n\r` header the first data row started at the CR and read as empty
(`a,b\n\r1,2\n\r3,4\n\r` read [0N 0N] and [3 4], the 1,2 lost).

The rule now, for the header and every row, with quotes in the file or
without: a line ends at LF, CRLF, a lone CR, or LFCR (an LF and the CR
right after it, unless that CR starts a CRLF), in any mix; inside a quoted
cell they are text.  One helper, csv_eol_len, says how long the line end
at a byte is, and the byte-at-a-time scans, the parallel scan's chunk
boundaries and the header readers use it.

The fast path for a file without quotes searched for LF with memchr; it
now searches for LF and CR in the same pass and takes the line end there
by csv_eol_len.  csv_find_eol reads aligned 32-byte blocks with AVX2, as
the C library's memchr does (an aligned block never leaves its page, so
the bytes before and after the range in its first and last block, all in
the file's mapping, are read and masked off), 16 unaligned bytes at a time
with SSE2, and bytewise otherwise; a version with unaligned 32-byte loads
ran 1-2% more cycles on a one-worker load, the aligned one runs dev's.  So
an LF or CRLF file costs one search per line, as before, and no pass is
added to find out which kind of file it is.  The three versions agree
with a bytewise search on 400000 random ranges each.  The byte-at-a-time path, for files with
quotes, already stopped at both and now reads LFCR as one line end; the
parallel scan's chunk boundaries never split a CRLF or an LFCR, in either
path.  Strict mode's refusal of text after a lone CR (#1888) cannot happen
any more and is gone.

What .csv.write writes is unaffected: it ends rows with LF and quotes
every cell holding a CR or an LF, so its output takes the same path and
reads back cell for cell, CR and LF in cells included (checked).

Interleaved timings, best of 7 (5 at 28 workers, 7 for the imports), ms,
clean gcc release builds of dev (1691a57) and this, one worker pinned to
a performance core and all 28; the machine was shared, load average 4 to
12.  The files are those of #1888's and #1894's measurements -- 1 GB of
13M rows with LF line ends (I64 F64 SYM STR DATE TIMESTAMP I32 B8), the
same with CRLF, 520 MB of 6.5M rows with quoted cells, 520 MB of 6M rows
of eight types, an 8000-row file read 2000 times (the serial scan) -- and
.csv.splayed imports of the two 1 GB files:

| file | workers | dev | this |
|---|---|---|---|
| 1 GB, LF | 1 | 1737 | 1745 (+0.4%) |
| 1 GB, LF | all | 384 | 385 (+0.3%) |
| 1 GB, CRLF | 1 | 1741 | 1744 (+0.2%) |
| 1 GB, CRLF | all | 414 | 411 (-0.6%) |
| quoted, 520 MB | 1 | 1245 | 1251 (+0.5%) |
| quoted, 520 MB | all | 223 | 221 (-0.6%) |
| 8 types, 520 MB | 1 | 826 | 823 (-0.3%) |
| 8 types, 520 MB | all | 200 | 200 (+0.1%) |
| 8000 rows x2000 | 1 | 1522 | 1521 (-0.0%) |
| .csv.splayed 1 GB, LF | all | 2189 | 2218 (+1.3%) |
| .csv.splayed 1 GB, CRLF | all | 2192 | 2138 (-2.5%) |

CPU cycles of a one-worker load, against dev: 1 GB LF -0.6%, CRLF +1.4%,
quoted +0.9%, the serial file +0.3% (instructions +0.5%, +0.6%, +0.1%,
+0.5%).  No shape is slower beyond run-to-run noise.

Test: test/rfl/io/csv_line_ends.rfl, which fails on dev (the CR-only file
reads one row): CR line ends with and without quotes, an LFCR header and
rows, every kind of line end mixed in one file (LF, CRLF, CR, LFCR, and LF
followed by CRLF for an empty line), CR and LF inside quoted cells under
CR line ends, a .csv.write round trip of cells holding CR, LF and CRLF,
400000-row files past the parallel scan's 4 MB with CR, LFCR, CR and
quotes, and CRLF line ends, the same files through .csv.splayed and
.csv.parted, and a header-only file and a last line without its CR.
csv/strict_matrix's lone-CR case now expects the text after the CR as
the next row, one line on; csv_strict.rfl reads the quote-free CR file
whole.

Fixes #1891
BREAKING CHANGE: a CSV file without quotes whose lines end in a lone CR,
or whose header ends in LFCR, now reads every row; before, the rows after
a CR in the same LF-delimited line were dropped, and the first row after
an LFCR header read as nulls.
singaraiona added a commit that referenced this pull request Nov 28, 2026
…he file or without

The CSV row splitter has two paths.  For a file with quotes it walks the
bytes and ends a row at LF, CRLF or a lone CR; for a file without quotes
it searched for LF only.  The cell scanner ends a cell at CR in both, so
in a quote-free file with CR line ends everything after a row's first CR
was never read: `a,b\r1,2\r3,4\r` read as one row, and with one quoted
cell anywhere in the file the same text read as two.  And the header
reader consumed a CR, then an LF -- CRLF, but not LFCR -- so after an
`a,b\n\r` header the first data row started at the CR and read as empty
(`a,b\n\r1,2\n\r3,4\n\r` read [0N 0N] and [3 4], the 1,2 lost).

The rule now, for the header and every row, with quotes in the file or
without: a line ends at LF, CRLF, a lone CR, or LFCR (an LF and the CR
right after it, unless that CR starts a CRLF), in any mix; inside a quoted
cell they are text.  One helper, csv_eol_len, says how long the line end
at a byte is, and the byte-at-a-time scans, the parallel scan's chunk
boundaries and the header readers use it.

The fast path for a file without quotes searched for LF with memchr; it
now searches for LF and CR in the same pass and takes the line end there
by csv_eol_len.  csv_find_eol reads aligned 32-byte blocks with AVX2, as
the C library's memchr does (an aligned block never leaves its page, so
the bytes before and after the range in its first and last block, all in
the file's mapping, are read and masked off), 16 unaligned bytes at a time
with SSE2, and bytewise otherwise; a version with unaligned 32-byte loads
ran 1-2% more cycles on a one-worker load, the aligned one runs dev's.  So
an LF or CRLF file costs one search per line, as before, and no pass is
added to find out which kind of file it is.  The three versions agree
with a bytewise search on 400000 random ranges each.  The byte-at-a-time path, for files with
quotes, already stopped at both and now reads LFCR as one line end; the
parallel scan's chunk boundaries never split a CRLF or an LFCR, in either
path.  Strict mode's refusal of text after a lone CR (#1888) cannot happen
any more and is gone, and its line counter reads line ends the same way.

What .csv.write writes is unaffected: it ends rows with LF and quotes
every cell holding a CR or an LF, so its output takes the same path and
reads back cell for cell, CR and LF in cells included (checked).

Interleaved timings, best of 7 (5 at 28 workers, 7 for the imports), ms,
clean gcc release builds of dev (1691a57) and this, one worker pinned to
a performance core and all 28; the machine was shared, load average 4 to
12.  The files are those of #1888's and #1894's measurements -- 1 GB of
13M rows with LF line ends (I64 F64 SYM STR DATE TIMESTAMP I32 B8), the
same with CRLF, 520 MB of 6.5M rows with quoted cells, 520 MB of 6M rows
of eight types, an 8000-row file read 2000 times (the serial scan) -- and
.csv.splayed imports of the two 1 GB files:

| file | workers | dev | this |
|---|---|---|---|
| 1 GB, LF | 1 | 1737 | 1745 (+0.4%) |
| 1 GB, LF | all | 384 | 385 (+0.3%) |
| 1 GB, CRLF | 1 | 1741 | 1744 (+0.2%) |
| 1 GB, CRLF | all | 414 | 411 (-0.6%) |
| quoted, 520 MB | 1 | 1245 | 1251 (+0.5%) |
| quoted, 520 MB | all | 223 | 221 (-0.6%) |
| 8 types, 520 MB | 1 | 826 | 823 (-0.3%) |
| 8 types, 520 MB | all | 200 | 200 (+0.1%) |
| 8000 rows x2000 | 1 | 1522 | 1521 (-0.0%) |
| .csv.splayed 1 GB, LF | all | 2189 | 2218 (+1.3%) |
| .csv.splayed 1 GB, CRLF | all | 2192 | 2138 (-2.5%) |

The parallel scan's two loops are separate out-of-line functions
(csv_scan_chunk_fast, csv_scan_chunk_quoted), so the quoted byte loop is
not compiled around the inlined vector search; a review saw a quoted
276 MB file 3-4% slower at 28 workers.  Measured here against dev
283f08f on such a file (6M rows, I64 F64 SYMBOL quoted STR DATE, 267 MB),
15 interleaved rounds at 28 workers on a loaded machine (load 11-13): dev
168.4 ms, the reviewed head 165.6 (-1.7%), this 164.3 (-2.4%), medians
179.5 / 179.2 / 179.4; one worker pinned: 709.1, 697.6, 702.6.  The
slowdown did not show here.

CPU cycles of a one-worker load, against dev: 1 GB LF -0.6%, CRLF +1.4%,
quoted +0.9%, the serial file +0.3% (instructions +0.5%, +0.6%, +0.1%,
+0.5%).  No shape is slower beyond run-to-run noise.

Test: test/rfl/io/csv_line_ends.rfl, which fails on dev (the CR-only file
reads one row): CR line ends with and without quotes, an LFCR header and
rows, every kind of line end mixed in one file (LF, CRLF, CR, LFCR, and LF
followed by CRLF for an empty line), CR and LF inside quoted cells under
CR line ends, a .csv.write round trip of cells holding CR, LF and CRLF,
400000-row files past the parallel scan's 4 MB with CR, LFCR, CR and
quotes, and CRLF line ends, the same files through .csv.splayed and
.csv.parted, and a header-only file and a last line without its CR.
csv/strict_matrix's lone-CR case now expects the text after the CR as
the next row, one line on; csv_strict.rfl reads the quote-free CR file
whole.  csv/strict_line_ends puts every pair and triple of the four
line ends back to back between a valid row and a bad one, with quotes in
the file and without, and expects the strict error at the line the reader's
row count gives: the line counter reads line ends as the row scans do
(csv_line_of walks the file with csv_find_eol and csv_eol_len), so a CRLF
followed by a lone CR is two lines, not one.

Fixes #1891
BREAKING CHANGE: CSV reads (.csv.read, .csv.splayed, .csv.parted) return
different rows for these inputs, all of which lost or added rows before:
(1) a file without quotes whose lines end in a lone CR now reads every row
(before, a CR-only file read as one row, and the text after a lone CR in
an LF line was dropped); (2) a file whose header ends in LFCR now reads its
first data row (before, it read as nulls, the row starting at the CR), and
so does one read with names whose matching LFCR header is skipped; (3) a
file with quotes whose lines end in LFCR no longer reads an empty, null row
after each one (before, [0N 1 0N 2 0N] for two rows, now [1 2]); (4) the
delimiter of a file whose header ends in a CR is now chosen from the header
alone (before, the count of commas and tabs ran on into the data up to the
first LF).  Under {strict: true} the text after a lone CR is now a row of
its own rather than the "text after a CR inside the row" error.
singaraiona added a commit that referenced this pull request Nov 28, 2026
…he file or without

The CSV row splitter has two paths.  For a file with quotes it walks the
bytes and ends a row at LF, CRLF or a lone CR; for a file without quotes
it searched for LF only.  The cell scanner ends a cell at CR in both, so
in a quote-free file with CR line ends everything after a row's first CR
was never read: `a,b\r1,2\r3,4\r` read as one row, and with one quoted
cell anywhere in the file the same text read as two.  And the header
reader consumed a CR, then an LF -- CRLF, but not LFCR -- so after an
`a,b\n\r` header the first data row started at the CR and read as empty
(`a,b\n\r1,2\n\r3,4\n\r` read [0N 0N] and [3 4], the 1,2 lost).

The rule now, for the header and every row, with quotes in the file or
without: line ends are read greedily from left to right, a CRLF or an
LFCR whenever the byte at the position starts one, else the single LF or
CR (so \n\r\n\r is two line ends, as dev read it in a quote-free file);
inside a quoted cell these bytes are text.  One helper, csv_eol_len, says
how long the line end at a byte is, and every reader of line ends uses
it: the fast and the byte-at-a-time scans, serial and parallel, the
header readers, and the strict line counter.  A parallel chunk boundary
that falls inside a run of line-end bytes is moved to the end of the line
end that covers it, found by reading the run greedily from its start, so
every chunk begins where the serial scan would begin a row.

The fast path for a file without quotes searched for LF with memchr; it
now searches for LF and CR in the same pass and takes the line end there
by csv_eol_len.  csv_find_eol reads aligned 32-byte blocks with AVX2, as
the C library's memchr does (an aligned block never leaves its page, so
the bytes before and after the range in its first and last block, all in
the file's mapping, are read and masked off), 16 unaligned bytes at a time
with SSE2, and bytewise otherwise; a version with unaligned 32-byte loads
ran 1-2% more cycles on a one-worker load, the aligned one runs dev's.  So
an LF or CRLF file costs one search per line, as before, and no pass is
added to find out which kind of file it is.  The three versions agree
with a bytewise search on 400000 random ranges each.  The byte-at-a-time path, for files with
quotes, already stopped at both and now reads LFCR as one line end; the
parallel scan's chunk boundaries never split a CRLF or an LFCR, in either
path.  Strict mode's refusal of text after a lone CR (#1888) cannot happen
any more and is gone, and its line counter reads line ends the same way.

What .csv.write writes is unaffected: it ends rows with LF and quotes
every cell holding a CR or an LF, so its output takes the same path and
reads back cell for cell, CR and LF in cells included (checked).

Interleaved timings, best of 7 (5 at 28 workers, 7 for the imports), ms,
clean gcc release builds of dev (1691a57) and this, one worker pinned to
a performance core and all 28; the machine was shared, load average 4 to
12.  The files are those of #1888's and #1894's measurements -- 1 GB of
13M rows with LF line ends (I64 F64 SYM STR DATE TIMESTAMP I32 B8), the
same with CRLF, 520 MB of 6.5M rows with quoted cells, 520 MB of 6M rows
of eight types, an 8000-row file read 2000 times (the serial scan) -- and
.csv.splayed imports of the two 1 GB files:

| file | workers | dev | this |
|---|---|---|---|
| 1 GB, LF | 1 | 1737 | 1745 (+0.4%) |
| 1 GB, LF | all | 384 | 385 (+0.3%) |
| 1 GB, CRLF | 1 | 1741 | 1744 (+0.2%) |
| 1 GB, CRLF | all | 414 | 411 (-0.6%) |
| quoted, 520 MB | 1 | 1245 | 1251 (+0.5%) |
| quoted, 520 MB | all | 223 | 221 (-0.6%) |
| 8 types, 520 MB | 1 | 826 | 823 (-0.3%) |
| 8 types, 520 MB | all | 200 | 200 (+0.1%) |
| 8000 rows x2000 | 1 | 1522 | 1521 (-0.0%) |
| .csv.splayed 1 GB, LF | all | 2189 | 2218 (+1.3%) |
| .csv.splayed 1 GB, CRLF | all | 2192 | 2138 (-2.5%) |

The parallel scan's two loops are separate out-of-line functions
(csv_scan_chunk_fast, csv_scan_chunk_quoted), so the quoted byte loop is
not compiled around the inlined vector search; a review saw a quoted
276 MB file 3-4% slower at 28 workers.  Measured here against dev
283f08f on such a file (6M rows, I64 F64 SYMBOL quoted STR DATE, 267 MB),
15 interleaved rounds at 28 workers on a loaded machine (load 11-13): dev
168.4 ms, the reviewed head 165.6 (-1.7%), the split 164.3 (-2.4%); on
this head, 12 rounds at load 3-6: dev 147.5, this 146.6 (-0.6%), medians
150.3 / 149.9.  The slowdown did not show here.

On this head, against dev 283f08f (best of 5, load 3-6): 1 GB LF
1738.6 -> 1744.4 ms (+0.3%) at one worker, 386.6 -> 394.0 (+1.9%, medians
393.8 / 397.9) at 28; CRLF 1742.7 -> 1748.1 (+0.3%), 403.1 -> 406.2
(+0.8%); quoted 1256.0 -> 1204.5 (-4.1%), 210.7 -> 208.4 (-1.1%); the
serial file 1494.9 -> 1491.5 (-0.2%).

CPU cycles of a one-worker load, against dev: 1 GB LF -0.6%, CRLF +1.4%,
quoted +0.9%, the serial file +0.3% (instructions +0.5%, +0.6%, +0.1%,
+0.5%).  No shape is slower beyond run-to-run noise.

Test: test/rfl/io/csv_line_ends.rfl, which fails on dev (the CR-only file
reads one row): CR line ends with and without quotes, an LFCR header and
rows, every kind of line end mixed in one file (LF, CRLF, CR, LFCR, and LF
followed by CRLF for an empty line), CR and LF inside quoted cells under
CR line ends, a .csv.write round trip of cells holding CR, LF and CRLF,
400000-row files past the parallel scan's 4 MB with CR, LFCR, CR and
quotes, and CRLF line ends, the same files through .csv.splayed and
.csv.parted, and a header-only file and a last line without its CR.
csv/strict_matrix's lone-CR case now expects the text after the CR as
the next row, one line on; csv_strict.rfl reads the quote-free CR file
whole.  csv/strict_line_ends puts every pair and triple of the four
line ends back to back between a valid row and a bad one, with quotes in
the file and without, and expects the strict error at the line the reader's
row count gives: the line counter reads line ends as the row scans do
(csv_line_of walks the file with csv_find_eol and csv_eol_len), so a CRLF
followed by a lone CR is two lines, not one.  csv/line_end_reference
checks the rule itself against a reference tokenizer written from the
sentence above: files of cells (digits, quoted digits, quoted text holding
line ends) between runs of 1 to 4 line-end bytes -- every one of the 30
such runs, then random ones -- read as one column, rows and cells
compared with the reference, and a malformed last row reported at the
reference's line; 20 seeds each under the serial scan (60 rows) and the
parallel one (3000 rows, which the test build cuts into 64-byte chunks,
so boundaries fall inside runs).  It fails with the previous rule, and
with the greedy rule but the previous boundary handling (5820 rows where
the reference has 5818).

Against dev, 400 random small files (half with quotes, half with a
header, rows separated by random runs of 1 to 4 line-end bytes) read
alike at 1 and 28 workers on this head; 302 read differently from dev,
and every one falls in a class the trailer lists.

Fixes #1891
BREAKING CHANGE: CSV reads (.csv.read, .csv.splayed, .csv.parted) can
return different rows from before for exactly these inputs: (1) a file
without quotes in which, read by the rule above, a CR stands alone (rows
were split at LF only, a CR right after an LF was absorbed, and the text
after any other CR in a line was dropped: a CR-only file read as one row,
and \r\n\r read as one line end, now two); (2) a file with quotes that
holds an LFCR outside its quoted cells (each read as two line ends, an
empty, null row after each: [0N 1 0N 2 0N] for two rows, now [1 2]); (3) a
file whose header ends in LFCR (its first data row read as nulls, starting
at the CR), also when names are given and the matching header is skipped;
(4) a file whose header ends in a CR, whose delimiter is now chosen from
the header alone (the count of commas and tabs ran on into the data up to
the first LF).  Under {strict: true} a lone CR now ends a row instead of
raising "text after a CR inside the row".
singaraiona added a commit that referenced this pull request Nov 28, 2026
…he file or without

The CSV row splitter has two paths.  For a file with quotes it walks the
bytes and ends a row at LF, CRLF or a lone CR; for a file without quotes
it searched for LF only.  The cell scanner ends a cell at CR in both, so
in a quote-free file with CR line ends everything after a row's first CR
was never read: `a,b\r1,2\r3,4\r` read as one row, and with one quoted
cell anywhere in the file the same text read as two.  And the header
reader consumed a CR, then an LF -- CRLF, but not LFCR -- so after an
`a,b\n\r` header the first data row started at the CR and read as empty
(`a,b\n\r1,2\n\r3,4\n\r` read [0N 0N] and [3 4], the 1,2 lost).

The rule now, for the header and every row, with quotes in the file or
without: line ends are read greedily from left to right, a CRLF or an
LFCR whenever the byte at the position starts one, else the single LF or
CR (so \n\r\n\r is two line ends, as dev read it in a quote-free file);
inside a quoted cell these bytes are text.  One helper, csv_eol_len, says
how long the line end at a byte is, and every reader of line ends uses
it: the fast and the byte-at-a-time scans, serial and parallel, the
header readers, and the strict line counter.  A parallel chunk boundary
that falls inside a run of line-end bytes is moved, by at most one byte,
to where a line end starts, so every chunk begins where the serial scan
would begin a row.  It is found without reading the run from its start:
read greedily, a line end starts at a run's first byte and at every byte
equal to the one before it (that byte ended a line end), and between such
points the bytes alternate and pair up, so the nearest such point at or
before the boundary -- or the boundary before it, already resolved --
decides by parity.  The walk back never passes the boundary before, so
over all boundaries each byte is read at most once, and in a run of LF or
of CR not at all: 400 MB of LF reads in 3.7 s at 28 workers (dev 3.9 s; a
walk to the run's start at each boundary took 45.5 s), 200M LFCR in
2.2-2.3 s (dev 1.9-2.4 s; it took 25.4 s), and a file of 40000 runs of
5000 alternating bytes in 0.94-1.05 s (dev 0.96-1.03 s).

The fast path for a file without quotes searched for LF with memchr; it
now searches for LF and CR in the same pass and takes the line end there
by csv_eol_len.  csv_find_eol reads aligned 32-byte blocks with AVX2, as
the C library's memchr does (an aligned block never leaves its page, so
the bytes before and after the range in its first and last block, all in
the file's mapping, are read and masked off), 16 unaligned bytes at a time
with SSE2, and bytewise otherwise; a version with unaligned 32-byte loads
ran 1-2% more cycles on a one-worker load, the aligned one runs dev's.  So
an LF or CRLF file costs one search per line, as before, and no pass is
added to find out which kind of file it is.  The three versions agree
with a bytewise search on 400000 random ranges each.  The byte-at-a-time path, for files with
quotes, already stopped at both and now reads LFCR as one line end; the
parallel scan's chunk boundaries never split a CRLF or an LFCR, in either
path.  Strict mode's refusal of text after a lone CR (#1888) cannot happen
any more and is gone, and its line counter reads line ends the same way.

What .csv.write writes is unaffected: it ends rows with LF and quotes
every cell holding a CR or an LF, so its output takes the same path and
reads back cell for cell, CR and LF in cells included (checked).

Interleaved timings, best of 7 (5 at 28 workers, 7 for the imports), ms,
clean gcc release builds of dev (1691a57) and this, one worker pinned to
a performance core and all 28; the machine was shared, load average 4 to
12.  The files are those of #1888's and #1894's measurements -- 1 GB of
13M rows with LF line ends (I64 F64 SYM STR DATE TIMESTAMP I32 B8), the
same with CRLF, 520 MB of 6.5M rows with quoted cells, 520 MB of 6M rows
of eight types, an 8000-row file read 2000 times (the serial scan) -- and
.csv.splayed imports of the two 1 GB files:

| file | workers | dev | this |
|---|---|---|---|
| 1 GB, LF | 1 | 1737 | 1745 (+0.4%) |
| 1 GB, LF | all | 384 | 385 (+0.3%) |
| 1 GB, CRLF | 1 | 1741 | 1744 (+0.2%) |
| 1 GB, CRLF | all | 414 | 411 (-0.6%) |
| quoted, 520 MB | 1 | 1245 | 1251 (+0.5%) |
| quoted, 520 MB | all | 223 | 221 (-0.6%) |
| 8 types, 520 MB | 1 | 826 | 823 (-0.3%) |
| 8 types, 520 MB | all | 200 | 200 (+0.1%) |
| 8000 rows x2000 | 1 | 1522 | 1521 (-0.0%) |
| .csv.splayed 1 GB, LF | all | 2189 | 2218 (+1.3%) |
| .csv.splayed 1 GB, CRLF | all | 2192 | 2138 (-2.5%) |

The parallel scan's two loops are separate out-of-line functions
(csv_scan_chunk_fast, csv_scan_chunk_quoted), so the quoted byte loop is
not compiled around the inlined vector search; a review saw a quoted
276 MB file 3-4% slower at 28 workers.  Measured here against dev
283f08f on such a file (6M rows, I64 F64 SYMBOL quoted STR DATE, 267 MB),
15 interleaved rounds at 28 workers on a loaded machine (load 11-13): dev
168.4 ms, the reviewed head 165.6 (-1.7%), the split 164.3 (-2.4%); and,
as the reviews measured it (each round the minimum of 7 loads in one
process, rounds interleaved, 12 rounds, load 7-9), dev 76.6 ms (median
76.8), a second copy of dev's binary 76.1 (-0.7%, median 77.1), 0fa8911
76.1 (-0.7%), ec4544a 76.7 (+0.1%), this 77.5 (+1.1%, median 78.8).  On
these builds every head is within the spread of dev against its own copy,
so the 3-5% the reviews saw does not reproduce here; the quoted scan's one
added cost is the LFCR test at each line end, +0.13% instructions on a
one-worker read of the file.

On this head, against dev 283f08f (best of 5, load 3-6): 1 GB LF
1738.6 -> 1744.4 ms (+0.3%) at one worker, 386.6 -> 394.0 (+1.9%, medians
393.8 / 397.9) at 28; CRLF 1742.7 -> 1748.1 (+0.3%), 403.1 -> 406.2
(+0.8%); quoted 1256.0 -> 1204.5 (-4.1%), 210.7 -> 208.4 (-1.1%); the
serial file 1494.9 -> 1491.5 (-0.2%).

CPU cycles of a one-worker load, against dev: 1 GB LF -0.6%, CRLF +1.4%,
quoted +0.9%, the serial file +0.3% (instructions +0.5%, +0.6%, +0.1%,
+0.5%).  No shape is slower beyond run-to-run noise.

Test: test/rfl/io/csv_line_ends.rfl, which fails on dev (the CR-only file
reads one row): CR line ends with and without quotes, an LFCR header and
rows, every kind of line end mixed in one file (LF, CRLF, CR, LFCR, and LF
followed by CRLF for an empty line), CR and LF inside quoted cells under
CR line ends, a .csv.write round trip of cells holding CR, LF and CRLF,
400000-row files past the parallel scan's 4 MB with CR, LFCR, CR and
quotes, and CRLF line ends, the same files through .csv.splayed and
.csv.parted, and a header-only file and a last line without its CR.
csv/strict_matrix's lone-CR case now expects the text after the CR as
the next row, one line on; csv_strict.rfl reads the quote-free CR file
whole.  csv/strict_line_ends puts every pair and triple of the four
line ends back to back between a valid row and a bad one, with quotes in
the file and without, and expects the strict error at the line the reader's
row count gives: the line counter reads line ends as the row scans do
(csv_line_of walks the file with csv_find_eol and csv_eol_len), so a CRLF
followed by a lone CR is two lines, not one.  csv/line_end_reference
checks the rule itself against a reference tokenizer written from the
sentence above: files of cells (digits, quoted digits, quoted text holding
line ends) between runs of 1 to 4 line-end bytes -- every one of the 30
such runs, then random ones, and in a third set runs of up to 3000 bytes,
alternating, of one byte or random, so that several chunk boundaries fall
inside one run -- read as one column, rows and cells
compared with the reference, and a malformed last row reported at the
reference's line; 20 seeds each under the serial scan (60 rows) and the
parallel one (3000 rows, which the test build cuts into 64-byte chunks,
so boundaries fall inside runs).  It fails with the previous rule, and
with the greedy rule but the previous boundary handling (5820 rows where
the reference has 5818), and with the boundary not moved inside a run
(5840 rows).

Against dev, 400 random small files (half with quotes, half with a
header, rows separated by random runs of 1 to 4 line-end bytes) read
alike at 1 and 28 workers on this head; 302 read differently from dev,
and every one falls in a class the trailer lists.

Fixes #1891
BREAKING CHANGE: CSV reads (.csv.read, .csv.splayed, .csv.parted) can
return different rows from before for exactly these inputs: (1) a file
without quotes in which, read by the rule above, a CR stands alone (rows
were split at LF only, a CR right after an LF was absorbed, and the text
after any other CR in a line was dropped: a CR-only file read as one row,
and \r\n\r read as one line end, now two); (2) a file with quotes that
holds an LFCR outside its quoted cells (each read as two line ends, an
empty, null row after each: [0N 1 0N 2 0N] for two rows, now [1 2]); (3) a
file whose header ends in LFCR (its first data row read as nulls, starting
at the CR), also when names are given and the matching header is skipped;
(4) a file whose header ends in a CR, whose delimiter is now chosen from
the header alone (the count of commas and tabs ran on into the data up to
the first LF).  Under {strict: true} a lone CR now ends a row instead of
raising "text after a CR inside the row".
singaraiona added a commit that referenced this pull request Nov 28, 2026
…he file or without

The CSV row splitter has two paths.  For a file with quotes it walks the
bytes and ends a row at LF, CRLF or a lone CR; for a file without quotes
it searched for LF only.  The cell scanner ends a cell at CR in both, so
in a quote-free file with CR line ends everything after a row's first CR
was never read: `a,b\r1,2\r3,4\r` read as one row, and with one quoted
cell anywhere in the file the same text read as two.  And the header
reader consumed a CR, then an LF -- CRLF, but not LFCR -- so after an
`a,b\n\r` header the first data row started at the CR and read as empty
(`a,b\n\r1,2\n\r3,4\n\r` read [0N 0N] and [3 4], the 1,2 lost).

The rule now, for the header and every row, with quotes in the file or
without: line ends are read greedily from left to right, a CRLF or an
LFCR whenever the byte at the position starts one, else the single LF or
CR (so \n\r\n\r is two line ends, as dev read it in a quote-free file);
inside a quoted cell these bytes are text.  One helper, csv_eol_len, says
how long the line end at a byte is, and every reader of line ends uses
it: the fast and the byte-at-a-time scans, serial and parallel, the
header readers, and the strict line counter.  A parallel chunk boundary
that falls inside a run of line-end bytes is moved, by at most one byte,
to where a line end starts, so every chunk begins where the serial scan
would begin a row.  It is found without reading the run from its start:
read greedily, a line end starts at a run's first byte and at every byte
equal to the one before it (that byte ended a line end), and between such
points the bytes alternate and pair up, so the nearest such point at or
before the boundary -- or the boundary before it, already resolved --
decides by parity.  The walk back never passes the boundary before, so
over all boundaries each byte is read at most once, and in a run of LF or
of CR not at all: 400 MB of LF reads in 3.7 s at 28 workers (dev 3.9 s; a
walk to the run's start at each boundary took 45.5 s), 200M LFCR in
2.2-2.3 s (dev 1.9-2.4 s; it took 25.4 s), and a file of 40000 runs of
5000 alternating bytes in 0.94-1.05 s (dev 0.96-1.03 s).

The fast path for a file without quotes searched for LF with memchr; it
now searches for LF and CR in the same pass and takes the line end there
by csv_eol_len.  csv_find_eol reads aligned 32-byte blocks with AVX2, as
the C library's memchr does (an aligned block never leaves its page, so
the bytes before and after the range in its first and last block, all in
the file's mapping, are read and masked off), 16 unaligned bytes at a time
with SSE2, and bytewise otherwise; a version with unaligned 32-byte loads
ran 1-2% more cycles on a one-worker load, the aligned one runs dev's.  So
an LF or CRLF file costs one search per line, as before, and no pass is
added to find out which kind of file it is.  The three versions agree
with a bytewise search on 400000 random ranges each.  The byte-at-a-time path, for files with
quotes, already stopped at both and now reads LFCR as one line end; the
parallel scan's chunk boundaries never split a CRLF or an LFCR, in either
path.  Strict mode's refusal of text after a lone CR (#1888) cannot happen
any more and is gone, and its line counter reads line ends the same way.

What .csv.write writes is unaffected: it ends rows with LF and quotes
every cell holding a CR or an LF, so its output takes the same path and
reads back cell for cell, CR and LF in cells included (checked).

Interleaved timings, best of 7 (5 at 28 workers, 7 for the imports), ms,
clean gcc release builds of dev (1691a57) and this, one worker pinned to
a performance core and all 28; the machine was shared, load average 4 to
12.  The files are those of #1888's and #1894's measurements -- 1 GB of
13M rows with LF line ends (I64 F64 SYM STR DATE TIMESTAMP I32 B8), the
same with CRLF, 520 MB of 6.5M rows with quoted cells, 520 MB of 6M rows
of eight types, an 8000-row file read 2000 times (the serial scan) -- and
.csv.splayed imports of the two 1 GB files:

| file | workers | dev | this |
|---|---|---|---|
| 1 GB, LF | 1 | 1737 | 1745 (+0.4%) |
| 1 GB, LF | all | 384 | 385 (+0.3%) |
| 1 GB, CRLF | 1 | 1741 | 1744 (+0.2%) |
| 1 GB, CRLF | all | 414 | 411 (-0.6%) |
| quoted, 520 MB | 1 | 1245 | 1251 (+0.5%) |
| quoted, 520 MB | all | 223 | 221 (-0.6%) |
| 8 types, 520 MB | 1 | 826 | 823 (-0.3%) |
| 8 types, 520 MB | all | 200 | 200 (+0.1%) |
| 8000 rows x2000 | 1 | 1522 | 1521 (-0.0%) |
| .csv.splayed 1 GB, LF | all | 2189 | 2218 (+1.3%) |
| .csv.splayed 1 GB, CRLF | all | 2192 | 2138 (-2.5%) |

The scan for a file with quotes no longer walks bytes one at a time
either.  Inside a quoted cell it jumped to the closing quote with memchr
before; outside one it now jumps to the next quote or line end with
csv_find_qeol (csv_find_eol with the quote as a third byte), in the
parallel chunk scan, the serial scan and the windowed scan of the
imports.  The reviews measured the quoted 276 MB file (6M rows, I64 F64
SYMBOL "q,<i>" DATE) 3-5% slower than dev at 28 workers, which held on a
clang build (the Makefile's default compiler) but not on gcc: phase
timers put the whole difference in the quoted pass of the parallel scan
(12.9 against 17.8 ms), whose byte loop clang compiled about a third
slower here than dev's identical loop, whether out of line or not and
with or without the LFCR test.  Without the byte loop that cost is gone.
As the reviews measured it -- each round the minimum of 7 loads in one
process, 6 rounds interleaved with a byte copy of dev's binary as the
control, load 5-8, the fixture regenerated from the review's recipe:

| build | workers | dev | dev copy | this |
|---|---|---|---|---|
| clang | 28 | 81.9 | 81.4 | 75.1 (-8%) |
| clang | 1 | 471.8 | 467.5 | 399.0 (-15%) |
| gcc | 28 | 78.7 | | 72.8 (-7%) |
| gcc | 1 | 565.9 | | 400.6 (-29%) |

The other files, best of 3, gcc / clang: 1 GB LF at one worker 1728 ->
1737 / 1855 -> 1810 ms, at 28 workers 392 -> 394 / 390 -> 392; CRLF 1730
-> 1737 / 1845 -> 1818, 411 -> 405 / 402 -> 405; the 520 MB quoted file
1262 -> 880 / 1171 -> 927 at one worker, 212 -> 202 / 218 -> 199 at 28.

CPU cycles of a one-worker load, against dev: 1 GB LF -0.6%, CRLF +1.4%,
quoted +0.9%, the serial file +0.3% (instructions +0.5%, +0.6%, +0.1%,
+0.5%).  No shape is slower beyond run-to-run noise.

Test: test/rfl/io/csv_line_ends.rfl, which fails on dev (the CR-only file
reads one row): CR line ends with and without quotes, an LFCR header and
rows, every kind of line end mixed in one file (LF, CRLF, CR, LFCR, and LF
followed by CRLF for an empty line), CR and LF inside quoted cells under
CR line ends, a .csv.write round trip of cells holding CR, LF and CRLF,
400000-row files past the parallel scan's 4 MB with CR, LFCR, CR and
quotes, and CRLF line ends, the same files through .csv.splayed and
.csv.parted, and a header-only file and a last line without its CR.
csv/strict_matrix's lone-CR case now expects the text after the CR as
the next row, one line on; csv_strict.rfl reads the quote-free CR file
whole.  csv/strict_line_ends puts every pair and triple of the four
line ends back to back between a valid row and a bad one, with quotes in
the file and without, and expects the strict error at the line the reader's
row count gives: the line counter reads line ends as the row scans do
(csv_line_of walks the file with csv_find_eol and csv_eol_len), so a CRLF
followed by a lone CR is two lines, not one.  csv/line_end_reference
checks the rule itself against a reference tokenizer written from the
sentence above: files of cells (digits, quoted digits, quoted text holding
line ends) between runs of 1 to 4 line-end bytes -- every one of the 30
such runs, then random ones, and in a third set runs of up to 3000 bytes,
alternating, of one byte or random, so that several chunk boundaries fall
inside one run -- read as one column, rows and cells
compared with the reference, and a malformed last row reported at the
reference's line; 20 seeds each under the serial scan (60 rows) and the
parallel one (3000 rows, which the test build cuts into 64-byte chunks,
so boundaries fall inside runs).  It fails with the previous rule, and
with the greedy rule but the previous boundary handling (5820 rows where
the reference has 5818), and with the boundary not moved inside a run
(5840 rows).

Against dev, 400 random small files (half with quotes, half with a
header, rows separated by random runs of 1 to 4 line-end bytes) read
alike at 1 and 28 workers on this head; 302 read differently from dev,
and every one falls in a class the trailer lists.

Fixes #1891
BREAKING CHANGE: CSV reads (.csv.read, .csv.splayed, .csv.parted) can
return different rows from before for exactly these inputs: (1) a file
without quotes in which, read by the rule above, a CR stands alone (rows
were split at LF only, a CR right after an LF was absorbed, and the text
after any other CR in a line was dropped: a CR-only file read as one row,
and \r\n\r read as one line end, now two); (2) a file with quotes that
holds an LFCR outside its quoted cells (each read as two line ends, an
empty, null row after each: [0N 1 0N 2 0N] for two rows, now [1 2]); (3) a
file whose header ends in LFCR (its first data row read as nulls, starting
at the CR), also when names are given and the matching header is skipped;
(4) a file whose header ends in a CR, whose delimiter is now chosen from
the header alone (the count of commas and tabs ran on into the data up to
the first LF).  Under {strict: true} a lone CR now ends a row instead of
raising "text after a CR inside the row".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.csv.read turns a malformed row or cell into nulls without an error; ask for a strict option

1 participant