diff --git a/docs/docs/namespaces/csv.md b/docs/docs/namespaces/csv.md
index e5358391a..fceed624e 100644
--- a/docs/docs/namespaces/csv.md
+++ b/docs/docs/namespaces/csv.md
@@ -21,12 +21,13 @@ Signatures:
- `(.csv.read "path")` — auto-detect column types from the header + a content sample.
- `(.csv.read [types] "path")` — types is a SYM vector naming `B8`, `I64`, `F64`, `STR`, `SYMBOL`, `F32`, `DATE`, `TIME`, `TIMESTAMP`, `GUID` (case-insensitive). One entry per column.
- `(.csv.read [names] [types] "path")` — also override the column names. With explicit names the input is assumed to have **no header row**.
+- `(.csv.read {strict: true} ...)` — any arrangement above may start with an options dict. `strict` true refuses a malformed file instead of reading its bad cells as nulls; see [Strict mode](#csv-strict). `strict` is the only key: an unknown key, a non-bool value, a second options dict or one that is not the first argument is a `domain` error. Each arrangement takes exactly its own arguments; one more is an `arity` error.
Returns: a `table`. Empty fields use the selected type's missing-input behavior. Sentinel-nullable columns record nulls with `RAY_ATTR_HAS_NULLS`; `SYM`/`STR` fields collapse to ordinary empty values and those columns do not acquire `RAY_ATTR_HAS_NULLS` from them.
A UTF-8 byte-order mark (the bytes `EF BB BF`, as spreadsheet exports write) at the start of the file is skipped: it is part of neither the first column name nor, in a file without a header, the first cell. `.csv.splayed` and `.csv.parted` skip it too.
-Errors: `type` (bad arg), `domain` (path is null / too long, or zero columns), `io` (open/read failure), `limit` (>256 columns).
+Errors: `type` (bad arg), `domain` (path is null / too long, zero columns, or a bad options dict), `io` (open/read failure), `limit` (>256 columns), `parse` (a bad row under `{strict: true}`).
Examples:
@@ -46,6 +47,39 @@ Examples:
(set t (.csv.read [sym price qty date] [SYMBOL F64 I64 DATE] "/tmp/rayforce-trades-headerless.csv"))
```
+### Strict mode { #csv-strict }
+
+By default the reader is lenient: a cell it cannot read as its column's type becomes a null (`false` in a `B8` column, `0` in a `U8` one, which hold no null), a row with too few cells is padded with nulls, and cells past the last column are dropped. `{strict: true}` makes each of these an error instead, a `parse` error that names the file, its line and, for a cell, the column, its text and the type:
+
+```text
+.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 rule: a non-empty cell must be stored as the value its text says. A strict load refuses a row when
+
+- its 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 is one empty cell — an error unless the table has one column. Without a header the first row is checked like any other (the schema, not the first line, says how many cells a row has);
+- a non-empty cell does not parse as its column's type: `"abc" is not an F64`. A number with a space before or after it (`" 1"`, `"2.5 "`) is such a cell; a leading `+` is not. `SYM` and `STR` cells hold any text;
+- a value is past its type's range: `"300" is out of range for a U8`. The default wraps these (300 in a `U8` reads as 44, 40000 in an `I16` as -25536, `9999-01-01T00:00:00` in a `TIMESTAMP` as an instant in 1815, `106752D00:00:00` in a `TIMESPAN` as a negative duration) or makes them an infinity (1e39 in an `F32`); a wrapped value is worse than a null. The ranges are `U8` 0 to 255; `I16`, `I32`, `I64` from their minimum plus one; `F32` and `F64` finite; `TIMESTAMP` 1707-09-22T00:12:43.145224193 to 2292-04-10T23:47:16.854775807; a finite `TIMESPAN` short of `0Wn`, the infinity it would otherwise read as (`0Wn` itself is accepted);
+- a non-zero float text stores as zero: `"1e-400" underflows to zero for an F64` (`1e-50` in an `F32`), the counterpart of overflowing to an infinity. Rounding to the nearest value the type holds is not a loss and is accepted, a non-zero subnormal (`5e-324`, `1e-45` in an `F32`) included;
+- the text spells the type's null: `"-32768" reads as a null I16`. These are the values each type keeps as its null sentinel: 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` for a `TIMESPAN`;
+- a time has more fraction digits than its type holds and they are not zeros: `"10:00:00.1234" has more fraction digits than a TIME holds` (`TIME` keeps milliseconds, `TIMESPAN` and `TIMESTAMP` nanoseconds);
+- a quoted cell has text after its closing quote (`"ab"cd`) or no closing quote. The header's quoted cells are held to the same: `line 1: header cell 1: text after the closing quote`;
+- in a file without quotes, where rows end at LF (or CRLF), text follows a lone CR inside the row: the default never reads it.
+
+Without a schema the types checked are the inferred ones: a column inferred from the sample as `I64` refuses a later cell of text, so give a schema when the sample may not show every kind of value. An empty cell (`,,` or `""`) is a null in both modes. A final line without a newline is an ordinary row. The line is the file's: the header is line 1 when there is one, and newlines inside quoted cells count, so the line is the one an editor shows the row starting on. When several rows are bad the error names the first in the file, whatever the parallel split.
+
+The message fits the 255 bytes an error holds, and only the cell text gives way: at most 40 bytes of it are shown, fewer when the path and the column leave less room, cut on a whole character and ending in `...`; quotes, control bytes and bytes that are not UTF-8 are escaped (`\"`, `\n`, `\x01`), never split. The path and the column name are shortened first only when they would leave the text no room, and the note `.csv.parted` adds about retained output always fits.
+
+The default path costs nothing for the option: the lenient parse is unchanged, and the strict checks run only when the option is given. Strict costs a few percent of a load, more where cells are short: about 5% at one worker (3% across all cores) on files of eight mixed column types, measured up to 12%; about 10-15% on a file of one narrow numeric or date column, up to about 20% on one of only `TIME` or `TIMESPAN` cells, and 1% on one of `GUID` cells. `.csv.splayed` and `.csv.parted` share the reader and take the same option.
+
+```lisp
+(write "/tmp/rayforce-strict.csv" "a,b,c\n1,x,2.5\n2,y\n")
+(.csv.read [I64 SYMBOL F64] "/tmp/rayforce-strict.csv") ;; 2 rows, c is [2.5 0Nf]
+(try (.csv.read {strict: true} [I64 SYMBOL F64] "/tmp/rayforce-strict.csv")
+ (fn [e] (at e 'msg))) ;; ".csv.read \"/tmp/rayforce-strict.csv\": line 3: expected 3 cells, got 2"
+```
+
The reader memory-maps the input, splits it into chunks, parses chunks in parallel, then merges column types and symbol-intern tables. Scaling depends on parsing, dictionary work, memory pressure, and output I/O; see the [measured load comparisons](../guides/storage.md#full-clickbench-load-proof).
## `.csv.write` { #csv-write }
@@ -65,7 +99,7 @@ Signatures:
- `(.csv.splayed "src.csv" "out_dir")`
- `(.csv.splayed [types] "src.csv" "out_dir")`
- `(.csv.splayed [names] [types] "src.csv" "out_dir")`
-- `(.csv.splayed {compress: true} ...)` — any arrangement above may start with an options dict. `compress` true writes generation-2 (compressed) column files where eligible, false generation 0; absent inherits per file (generation 2 when the existing destination's current file is generation 2). Unknown keys, a non-bool value or a second options dict are a `domain` error. Linked and nested/list columns are always written uncompressed. A compressed string column persists its dictionary index, as a generation-0 one does, unless it would make the file larger than the generation-0 one (mostly distinct strings); see `.db.splayed.set` in [Storage](../storage/index.md).
+- `(.csv.splayed {compress: true} ...)` — any arrangement above may start with an options dict. `compress` true writes generation-2 (compressed) column files where eligible, false generation 0; absent inherits per file (generation 2 when the existing destination's current file is generation 2). `strict` true reads the source as [`.csv.read`'s strict mode](#csv-strict) does, the message headed `.csv.splayed "src.csv":`. Unknown keys, a non-bool value or a second options dict are a `domain` error. Linked and nested/list columns are always written uncompressed. A compressed string column persists its dictionary index, as a generation-0 one does, unless it would make the file larger than the generation-0 one (mostly distinct strings); see `.db.splayed.set` in [Storage](../storage/index.md).
Streams `src.csv` chunk-by-chunk through the parser into a splayed directory at `out_dir` (one column file per field, `.d` schema, and `.sym` symbol dictionary when needed). Returns the resulting splayed table loaded with `ray_read_splayed`: generation-0 columns are zero-copy mmap, so the bytes stay on disk; a compressed column decodes into heap memory the first time a query reads it.
@@ -77,7 +111,7 @@ Use this when the CSV is too large to fit in memory but you want to query it lik
;; big is now a splayed table mmap'd from /tmp/rayforce-huge/.
```
-Errors propagate from the CSV parser (`type`, `domain`, `limit`) and from the splayed writer (`io`, `oom`).
+Errors propagate from the CSV parser (`type`, `domain`, `limit`, and `parse` under `strict`) and from the splayed writer (`io`, `oom`).
## `.csv.parted` { #csv-parted }
@@ -87,7 +121,7 @@ Signatures (with optional rows-per-part):
- `(.csv.parted [types] "src.csv" "db_root" 'tbl_name)`
- `(.csv.parted [names] [types] "src.csv" "db_root" 'tbl_name)`
- `(.csv.parted [...]types "src.csv" rows_per_part "db_root" 'tbl_name)` — pass a positive integer just before the db-root to override the default partition size.
-- `(.csv.parted {compress: true} ...)` — any arrangement above may start with an options dict. `compress` true writes generation-2 (compressed) files where eligible, false generation 0; absent inherits per file (generation 2 when the existing destination file is generation 2). Unknown keys, a non-bool value or a second options dict are a `domain` error. Linked and nested/list columns are always written uncompressed. A compressed string column persists its dictionary index, as a generation-0 one does, unless it would make the file larger than the generation-0 one (mostly distinct strings); see `.db.splayed.set` in [Storage](../storage/index.md).
+- `(.csv.parted {compress: true} ...)` — any arrangement above may start with an options dict. `compress` true writes generation-2 (compressed) files where eligible, false generation 0; absent inherits per file (generation 2 when the existing destination file is generation 2). `strict` true reads the source as [`.csv.read`'s strict mode](#csv-strict) does, the message headed `.csv.parted "src.csv":`; a bad line after the first partition was written leaves the staging directory as any failed import does, and the message ends `; partial output retained in "
"`. Unknown keys, a non-bool value or a second options dict are a `domain` error. Linked and nested/list columns are always written uncompressed. A compressed string column persists its dictionary index, as a generation-0 one does, unless it would make the file larger than the generation-0 one (mostly distinct strings); see `.db.splayed.set` in [Storage](../storage/index.md).
Streams the CSV into `db_root//tbl_name/`. Returns the parted table loaded back from disk. A new root is staged at `.csv-partial` and published after the shared dictionary flush; staging from an import that failed after writing a partition is retained for diagnosis, and a retry into the same root fails with an `io` error naming the directory to remove. A failure before the first partition (an unreadable or empty source, a type vector that does not match) leaves nothing behind. Existing roots retain per-partition update behavior. Bulk writes require an external file and directory sync for durability.
diff --git a/src/io/csv.c b/src/io/csv.c
index 89927fcf5..cc927e7ee 100644
--- a/src/io/csv.c
+++ b/src/io/csv.c
@@ -2197,6 +2197,16 @@ static bool csv_finalize_run(csv_finalize_ctx_t* ctx, int* fill_cols,
* Parallel parse context and callback
* -------------------------------------------------------------------------- */
+/* The first bad row a strict parse saw (#1885); row INT64_MAX: none. */
+enum { CSV_BAD_CELLS = 1, CSV_BAD_CELL, CSV_BAD_AFTER_QUOTE, CSV_BAD_UNCLOSED,
+ CSV_BAD_LONE_CR, CSV_BAD_RANGE, CSV_BAD_NULLV, CSV_BAD_PRECISION,
+ CSV_BAD_UNDERFLOW };
+typedef struct {
+ int64_t row;
+ int32_t col; /* the bad cell's column; -1 for CSV_BAD_CELLS */
+ uint8_t kind;
+} csv_bad_t;
+
typedef struct {
const char* buf;
size_t buf_size;
@@ -2211,8 +2221,51 @@ typedef struct {
bool* worker_had_null; /* [n_workers * n_cols] */
bool* worker_had_escaped; /* [n_workers * n_cols] */
uint8_t* row_done; /* [n_rows], marks initialized strref rows */
+ /* strict only (#1885); last, so the default parse's offsets are as they were */
+ csv_bad_t* worker_bad; /* [n_workers]: the first bad row each saw */
+ size_t rows_end; /* where the last row ends: the next chunk's start */
} csv_par_ctx_t;
+/* Strict mode (#1885): which rows a strict load refuses. A row is cut into
+ * cells as the lenient reader cuts it; a cell is a field ended by the
+ * delimiter, the line end or the end of the file, so a row has one cell more
+ * than the delimiters it holds before its line end, and a blank line is one
+ * empty cell. A row is bad when its cell count is not the schema's, when a
+ * quoted cell has text after its closing quote or no closing quote, or when
+ * a non-empty cell does not parse as its column's type -- exactly the cells
+ * the lenient reader turns into nulls (or, for B8 and U8, which hold none,
+ * into false and 0). A number out of its column's range -- which the
+ * lenient reader wraps (300 in a U8 is 44), stores as the null sentinel
+ * (INT16_MIN in an I16), or turns into an infinity (1e39 in an F32) -- is
+ * bad too: a wrapped value is worse than a null. (Out-of-range I64 and
+ * non-finite F64 text already parses to a null.) An empty cell is a null
+ * in both modes. A file
+ * without quotes splits rows at LF only, and a cell ends at CR, so text
+ * after a lone CR inside a row is never read: strict refuses it too. */
+static bool csv_quote_closed(const char* p, const char* buf_end) {
+ for (p++; p < buf_end; p++) {
+ if (*p != '"') continue;
+ if (p + 1 < buf_end && p[1] == '"') { p++; continue; }
+ return true;
+ }
+ return false;
+}
+
+/* After the scan of a field that started at p0 and ended at p: did it end on
+ * the delimiter (another cell follows), and is the cell well formed? */
+RAY_INLINE bool csv_strict_cell_end(const char* p0, const char* p,
+ const char* row_end, const char* buf_end,
+ char delim, uint8_t* kind) {
+ if (p0 < buf_end && *p0 == '"' && !csv_quote_closed(p0, buf_end)) {
+ *kind = CSV_BAD_UNCLOSED;
+ return false;
+ }
+ if (p > p0 && p[-1] == delim) return true;
+ if (p < row_end && p < buf_end && *p != '\n' && *p != '\r')
+ *kind = CSV_BAD_AFTER_QUOTE;
+ return false;
+}
+
static void csv_parse_fn(void* arg, uint32_t worker_id,
int64_t start, int64_t end_row) {
csv_par_ctx_t* ctx = (csv_par_ctx_t*)arg;
@@ -2395,11 +2448,438 @@ static void csv_parse_fn(void* arg, uint32_t worker_id,
}
}
+/* Why a non-empty number cell did not parse: an integer or a finite-looking
+ * float too big for the type is out of range; anything else is not one. */
+static uint8_t csv_bad_int_kind(const char* p, size_t n) {
+ size_t i = (n > 0 && (p[0] == '-' || p[0] == '+')) ? 1 : 0;
+ if (i == n) return CSV_BAD_CELL;
+ for (; i < n; i++) if (p[i] < '0' || p[i] > '9') return CSV_BAD_CELL;
+ return CSV_BAD_RANGE;
+}
+
+/* A float text with a non-zero digit before its exponent: if it stores as
+ * zero it underflowed (#1885 review). Rounding to the nearest value, a
+ * subnormal included, is not a loss; a non-zero text stored as 0 is. */
+static bool csv_float_text_nonzero(const char* p, size_t n) {
+ for (size_t i = 0; i < n && p[i] != 'e' && p[i] != 'E'; i++)
+ if (p[i] >= '1' && p[i] <= '9') return true;
+ return false;
+}
+
+static uint8_t csv_bad_float_kind(const char* p, size_t n) {
+ bool digit = false;
+ for (size_t i = 0; i < n; i++) if (p[i] >= '0' && p[i] <= '9') { digit = true; break; }
+ double v;
+ return digit && ray_parse_f64(p, n, &v) == n ? CSV_BAD_RANGE : CSV_BAD_CELL;
+}
+
+/* Temporal cells the lenient parsers take but store as something other than
+ * the text says (#1885 review): an instant or a duration past the type's
+ * range, which the arithmetic wraps, and fraction digits past the type's
+ * precision, which are dropped. Called after a lenient parse succeeded. */
+
+/* Every fraction digit past the first `keep` (the one '.' a TIME, TIMESPAN
+ * or TIMESTAMP holds) is a zero. */
+/* The same for a cell whose fraction ends it (TIME, TIMESPAN): read back
+ * from the end, so only the fraction's digits are looked at. */
+RAY_INLINE bool csv_frac_tail_kept(const char* p, size_t n, unsigned keep) {
+ size_t i = n;
+ while (i > 0 && p[i - 1] >= '0' && p[i - 1] <= '9') i--;
+ if (i == 0 || p[i - 1] != '.' || n - i <= keep) return true;
+ for (size_t k = i + keep; k < n; k++)
+ if (p[k] != '0') return false;
+ return true;
+}
+
+static bool csv_frac_kept(const char* p, size_t n, unsigned keep) {
+ const char* dot = memchr(p, '.', n);
+ if (!dot) return true;
+ unsigned i = 0;
+ for (const char* q = dot + 1; q < p + n && *q >= '0' && *q <= '9'; q++, i++)
+ if (i >= keep && *q != '0') return false;
+ return true;
+}
+
+/* The strict timestamp parse: fast_timestamp's grammar and value, but with
+ * the arithmetic checked, since past the type's range fast_timestamp's
+ * overflows (undefined; and on the earliest day even for an instant inside
+ * it). Returns CSV_TS_OK with *out, CSV_TS_NULL where fast_timestamp reads a
+ * null (the text is not a timestamp), or CSV_TS_RANGE: well formed, but the
+ * instant is outside the type. */
+enum { CSV_TS_OK, CSV_TS_NULL, CSV_TS_RANGE };
+RAY_INLINE int csv_strict_timestamp(const char* p, size_t n, int64_t* out) {
+ const int64_t NS_PER_DAY = 86400000000000LL;
+ const int64_t DMAX = INT64_MAX / NS_PER_DAY; /* 106751 */
+ if (n < 19) return CSV_TS_NULL;
+ bool sep = p[10] == 'T' || p[10] == 't' || p[10] == ' ' || (p[10] == 'D' && p[4] == '.');
+ if (!sep) return CSV_TS_NULL;
+ bool nul = false;
+ int64_t days = fast_date(p, 10, &nul);
+ if (nul) return CSV_TS_NULL;
+ size_t used = 8;
+ int64_t t = fast_time_ns(p + 11, n - 11, &nul, &used);
+ if (nul) return CSV_TS_NULL;
+ int64_t adj = 0;
+ size_t off = 11 + used, tz_used = 0;
+ if (off < n && (!parse_tz_offset(p + off, n - off, &adj, &tz_used) || off + tz_used != n))
+ return CSV_TS_NULL;
+ /* days * NS_PER_DAY + t - adj, with t in [0, NS_PER_DAY) and
+ * |adj| < NS_PER_DAY; the earliest day starts below INT64_MIN, so its
+ * day is folded into the time */
+ int64_t d = days, r = t;
+ if (d == -DMAX - 1) { d++; r -= NS_PER_DAY; }
+ if (d > DMAX || d < -DMAX) return CSV_TS_RANGE;
+ int64_t base = d * NS_PER_DAY;
+ if ((r > 0 && base > INT64_MAX - r) || (r < 0 && base < INT64_MIN - r)) return CSV_TS_RANGE;
+ base += r;
+ if ((adj > 0 && base < INT64_MIN + adj) || (adj < 0 && base > INT64_MAX + adj))
+ return CSV_TS_RANGE;
+ *out = base - adj;
+ return CSV_TS_OK;
+}
+
+/* A duration's days * NS_PER_DAY + the rest fits below the infinities
+ * (+-INT64_MAX, which a finite text must not reach); "0Wn" is the infinity
+ * itself and fits. */
+static bool csv_timespan_fits_slow(const char* p, size_t n, size_t i) {
+ uint64_t days = 0;
+ for (; i < n && p[i] >= '0' && p[i] <= '9'; i++) days = days * 10 + (uint64_t)(p[i] - '0');
+ char t[130];
+ if (n - i + 1 >= sizeof t) return false;
+ t[0] = '0';
+ memcpy(t + 1, p + i, n - i);
+ t[n - i + 1] = 0;
+ size_t used = 0;
+ int64_t rest = 0;
+ if (!ray_parse_timespan(t, &used, &rest) || rest < 0) return false;
+ const uint64_t day_ns = UINT64_C(86400000000000);
+ uint64_t lim = (uint64_t)INT64_MAX - 1;
+ return days <= (lim - (uint64_t)rest) / day_ns;
+}
+
+RAY_INLINE bool csv_timespan_fits(const char* p, size_t n) {
+ size_t i = (n > 0 && p[0] == '-') ? 1 : 0;
+ if (n - i == 3 && p[i] == '0' && p[i + 1] == 'W') return true;
+ /* fewer than six day digits: under 100000 days, inside the range */
+ size_t dd = 0;
+ while (dd < 6 && i + dd < n && p[i + dd] >= '0' && p[i + dd] <= '9') dd++;
+ return dd < 6 || csv_timespan_fits_slow(p, n, i);
+}
+
+/* The strict parse: csv_parse_fn with the checks above, which also records
+ * each worker's first bad row. A copy rather than a flag on csv_parse_fn,
+ * so that the default parse, here and in csv_parse_serial, is the same
+ * machine code it was before. */
+static void csv_parse_fn_strict(void* arg, uint32_t worker_id,
+ int64_t start, int64_t end_row) {
+ csv_par_ctx_t* ctx = (csv_par_ctx_t*)arg;
+ /* the context in locals: a column store could alias it */
+ const char* const buf = ctx->buf;
+ const int64_t* const row_offsets = ctx->row_offsets;
+ const int64_t n_rows = ctx->n_rows;
+ const int n_cols = ctx->n_cols;
+ const char delim = ctx->delim;
+ const csv_type_t* const col_types = ctx->col_types;
+ const int8_t* const resolved_types = ctx->resolved_types;
+ void* const* const col_data = ctx->col_data;
+ csv_strref_t* const* const str_refs = ctx->str_refs;
+ uint8_t* const row_done = ctx->row_done;
+ char esc_buf[8192];
+ const char* buf_end = buf + ctx->buf_size;
+ const char* last_end = buf + ctx->rows_end;
+ bool* my_had_null = &ctx->worker_had_null[(size_t)worker_id * (size_t)n_cols];
+ bool* my_had_escaped = &ctx->worker_had_escaped[(size_t)worker_id * (size_t)n_cols];
+
+ for (int64_t row = start; row < end_row; row++) {
+ if (RAY_UNLIKELY(((row - start) & 1023) == 0 && ray_interrupted()))
+ return;
+ const char* p = buf + row_offsets[row];
+ const char* row_end = (row + 1 < n_rows)
+ ? buf + row_offsets[row + 1]
+ : last_end;
+ /* the cells seen, and the row's first bad cell */
+ int cells = 1;
+ bool more = true;
+ int bad_col = -1;
+ uint8_t bad_kind = 0;
+
+ for (int c = 0; c < n_cols; c++) {
+ /* Guard: if past row boundary, fill remaining columns with defaults + null */
+ if (p >= row_end) {
+ for (; c < n_cols; c++) {
+ switch (col_types[c]) {
+ case CSV_TYPE_BOOL: ((uint8_t*)col_data[c])[row] = 0; break;
+ case CSV_TYPE_U8: ((uint8_t*)col_data[c])[row] = 0; break;
+ case CSV_TYPE_I16: ((int16_t*)col_data[c])[row] = NULL_I16; break;
+ case CSV_TYPE_I32: ((int32_t*)col_data[c])[row] = NULL_I32; break;
+ case CSV_TYPE_I64: ((int64_t*)col_data[c])[row] = NULL_I64; break;
+ case CSV_TYPE_F32: ((float*)col_data[c])[row] = NULL_F32; break;
+ case CSV_TYPE_F64: ((double*)col_data[c])[row] = NULL_F64; break;
+ case CSV_TYPE_DATE: ((int32_t*)col_data[c])[row] = NULL_I32; break;
+ case CSV_TYPE_TIME: ((int32_t*)col_data[c])[row] = NULL_I32; break;
+ case CSV_TYPE_TIMESPAN:
+ case CSV_TYPE_TIMESTAMP:
+ ((int64_t*)col_data[c])[row] = NULL_I64; break;
+ case CSV_TYPE_GUID:
+ memset((uint8_t*)col_data[c] + (size_t)row * 16, 0, 16);
+ break;
+ case CSV_TYPE_STR:
+ str_refs[c][row].ptr = NULL;
+ str_refs[c][row].len = 0;
+ break;
+ default: break;
+ }
+ /* BOOL/U8 are non-nullable; empty cells store 0/false. */
+ if (col_types[c] != CSV_TYPE_BOOL &&
+ col_types[c] != CSV_TYPE_U8) {
+ my_had_null[c] = true;
+ }
+ }
+ break;
+ }
+
+ const char* fld;
+ size_t flen;
+ char* dyn_esc = NULL;
+ const char* p0 = p;
+ p = scan_field(p, buf_end, delim, &fld, &flen, esc_buf, &dyn_esc);
+ {
+ uint8_t k = 0;
+ bool delim_end = csv_strict_cell_end(p0, p, row_end, buf_end,
+ delim, &k);
+ if (k && bad_col < 0) { bad_col = c; bad_kind = k; }
+ if (more && delim_end) cells++;
+ else more = false;
+ }
+
+ switch (col_types[c]) {
+ case CSV_TYPE_BOOL: {
+ /* BOOL is non-nullable; fast_bool returns 0 for
+ * empty / unparseable input and we store it as-is. */
+ bool is_null;
+ uint8_t v = fast_bool(fld, flen, &is_null);
+ ((uint8_t*)col_data[c])[row] = v;
+ if (is_null && flen > 0 && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_CELL; }
+ break;
+ }
+ case CSV_TYPE_I64: {
+ bool is_null;
+ int64_t v = fast_i64(fld, flen, &is_null);
+ ((int64_t*)col_data[c])[row] = is_null ? NULL_I64 : v;
+ /* INT64_MIN parses, but it is the null sentinel */
+ if (!is_null && v == INT64_MIN && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_NULLV; }
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = csv_bad_int_kind(fld, flen); }
+ }
+ break;
+ }
+ case CSV_TYPE_U8: {
+ /* U8 is non-nullable; fast_i64 returns 0 for
+ * empty / unparseable input and we store it as-is. */
+ bool is_null;
+ int64_t v = fast_i64(fld, flen, &is_null);
+ ((uint8_t*)col_data[c])[row] = (uint8_t)v;
+ if (is_null && flen > 0 && bad_col < 0) { bad_col = c; bad_kind = csv_bad_int_kind(fld, flen); }
+ else if (!is_null && (v < 0 || v > 255) && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_RANGE; }
+ break;
+ }
+ case CSV_TYPE_I16: {
+ bool is_null;
+ int64_t v = fast_i64(fld, flen, &is_null);
+ ((int16_t*)col_data[c])[row] = is_null ? NULL_I16 : (int16_t)v;
+ if (!is_null && (v < INT16_MIN || v > INT16_MAX) && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_RANGE; }
+ else if (!is_null && v == INT16_MIN && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_NULLV; }
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = csv_bad_int_kind(fld, flen); }
+ }
+ break;
+ }
+ case CSV_TYPE_I32: {
+ bool is_null;
+ int64_t v = fast_i64(fld, flen, &is_null);
+ ((int32_t*)col_data[c])[row] = is_null ? NULL_I32 : (int32_t)v;
+ if (!is_null && (v < INT32_MIN || v > INT32_MAX) && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_RANGE; }
+ else if (!is_null && v == INT32_MIN && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_NULLV; }
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = csv_bad_int_kind(fld, flen); }
+ }
+ break;
+ }
+ case CSV_TYPE_F64: {
+ bool is_null;
+ double v = fast_f64(fld, flen, &is_null);
+ ((double*)col_data[c])[row] = is_null ? NULL_F64 : v;
+ if (!is_null && v == 0.0 && bad_col < 0 && csv_float_text_nonzero(fld, flen)) {
+ bad_col = c; bad_kind = CSV_BAD_UNDERFLOW;
+ }
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = csv_bad_float_kind(fld, flen); }
+ }
+ break;
+ }
+ case CSV_TYPE_F32: {
+ bool is_null;
+ double v = fast_f64(fld, flen, &is_null);
+ ((float*)col_data[c])[row] = is_null ? NULL_F32 : (float)v;
+ if (!is_null && !isfinite((float)v) && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_RANGE; }
+ else if (!is_null && (float)v == 0.0f && bad_col < 0 && csv_float_text_nonzero(fld, flen)) {
+ bad_col = c; bad_kind = CSV_BAD_UNDERFLOW;
+ }
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = csv_bad_float_kind(fld, flen); }
+ }
+ break;
+ }
+ case CSV_TYPE_DATE: {
+ bool is_null;
+ int32_t v = fast_date(fld, flen, &is_null);
+ ((int32_t*)col_data[c])[row] = is_null ? NULL_I32 : v;
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_CELL; }
+ }
+ break;
+ }
+ case CSV_TYPE_TIME: {
+ bool is_null;
+ int32_t v = fast_time(fld, flen, &is_null);
+ ((int32_t*)col_data[c])[row] = is_null ? NULL_I32 : v;
+ if (!is_null && bad_col < 0) {
+ if (v == NULL_I32) { bad_col = c; bad_kind = CSV_BAD_NULLV; }
+ /* "H:MM:SS.ddd" is 11: only a longer cell has more digits */
+ else if (flen > 11 && !csv_frac_tail_kept(fld, flen, 3)) { bad_col = c; bad_kind = CSV_BAD_PRECISION; }
+ }
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_CELL; }
+ }
+ break;
+ }
+ case CSV_TYPE_TIMESPAN: {
+ bool is_null;
+ int64_t v = fast_timespan(fld, flen, &is_null);
+ ((int64_t*)col_data[c])[row] = is_null ? NULL_I64 : v;
+ if (!is_null && bad_col < 0) {
+ if (!csv_timespan_fits(fld, flen)) { bad_col = c; bad_kind = CSV_BAD_RANGE; }
+ /* "0D00:00:00.123456789" is 20 */
+ else if (flen > 20 && !csv_frac_tail_kept(fld, flen, 9)) { bad_col = c; bad_kind = CSV_BAD_PRECISION; }
+ }
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) {
+ bad_col = c;
+ bad_kind = flen == 3 && memcmp(fld, "0Nn", 3) == 0 ? CSV_BAD_NULLV : CSV_BAD_CELL;
+ }
+ }
+ break;
+ }
+ case CSV_TYPE_TIMESTAMP: {
+ bool is_null;
+ /* parsed with checked arithmetic: past the type's range
+ * fast_timestamp's overflows */
+ int64_t v = 0;
+ int cls = csv_strict_timestamp(fld, flen, &v);
+ is_null = cls != CSV_TS_OK;
+ ((int64_t*)col_data[c])[row] = is_null ? NULL_I64 : v;
+ if (cls == CSV_TS_RANGE && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_RANGE; }
+ if (!is_null && bad_col < 0) {
+ if (v == NULL_I64) { bad_col = c; bad_kind = CSV_BAD_NULLV; }
+ /* 19 + '.' + 9 digits: only a longer cell has more */
+ else if (flen > 29 && !csv_frac_kept(fld, flen, 9)) { bad_col = c; bad_kind = CSV_BAD_PRECISION; }
+ }
+ if (is_null) {
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_CELL; }
+ }
+ break;
+ }
+ case CSV_TYPE_GUID: {
+ bool is_null;
+ uint8_t* slot = (uint8_t*)col_data[c] + (size_t)row * 16;
+ fast_guid(fld, flen, slot, &is_null);
+ if (!is_null && bad_col < 0) {
+ static const uint8_t zero[16];
+ if (memcmp(slot, zero, 16) == 0) { bad_col = c; bad_kind = CSV_BAD_NULLV; }
+ }
+ if (is_null) {
+ memset(slot, 0, 16);
+ my_had_null[c] = true;
+ if (flen > 0 && bad_col < 0) { bad_col = c; bad_kind = CSV_BAD_CELL; }
+ }
+ break;
+ }
+ case CSV_TYPE_STR: {
+ if (flen == 0) {
+ str_refs[c][row].ptr = NULL;
+ str_refs[c][row].len = 0;
+ my_had_null[c] = true;
+ } else {
+ /* fld may point into esc_buf (stack) or dyn_esc
+ * (freed below) — both die before csv_fill_str_cols
+ * reads the strref. Persist escaped fields. */
+ if (fld < buf || fld >= buf_end) {
+ my_had_escaped[c] = true;
+ if (dyn_esc && fld == dyn_esc) {
+ dyn_esc = NULL; /* transfer ownership */
+ } else {
+ char* cp = (char*)ray_sys_alloc(flen);
+ if (cp) { memcpy(cp, fld, flen); fld = cp; }
+ }
+ }
+ str_refs[c][row].ptr = fld;
+ str_refs[c][row].len = (uint32_t)flen;
+ /* SYM columns are deduplicated by hash right after
+ * the parse; hash here while the bytes are hot. */
+ if (resolved_types[c] == RAY_SYM)
+ str_refs[c][row].hash = (uint32_t)ray_hash_bytes(fld, flen);
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ if (RAY_UNLIKELY(dyn_esc != NULL)) ray_sys_free(dyn_esc);
+ }
+ if (row_done) row_done[row] = 1;
+ {
+ /* A malformed quote is reported first: it is what cut the
+ * cells. Then a wrong cell count, then an unparsed cell. */
+ if ((bad_kind == CSV_BAD_CELL || bad_kind == CSV_BAD_RANGE ||
+ bad_kind == CSV_BAD_NULLV || bad_kind == CSV_BAD_PRECISION ||
+ bad_kind == CSV_BAD_UNDERFLOW) &&
+ cells != n_cols) bad_kind = 0;
+ if (!bad_kind && cells == n_cols) {
+ const char* q = p;
+ while (q < row_end && (*q == '\r' || *q == '\n')) q++;
+ if (q < row_end) bad_kind = CSV_BAD_LONE_CR;
+ }
+ csv_bad_t* bad = &ctx->worker_bad[worker_id];
+ if ((bad_kind || cells != n_cols) && row < bad->row) {
+ bad->row = row;
+ bad->kind = bad_kind ? bad_kind : (uint8_t)CSV_BAD_CELLS;
+ bad->col = (bad_kind && bad_kind != CSV_BAD_LONE_CR) ? bad_col : -1;
+ }
+ }
+ }
+}
+
/* --------------------------------------------------------------------------
* Serial parse fallback (small files or no thread pool)
* -------------------------------------------------------------------------- */
-static bool csv_parse_serial(const char* buf, size_t buf_size,
+/* Not inlined into its one caller, csv_parse_all: inlined there it ran more
+ * instructions per row than it does on its own. */
+#if defined(_MSC_VER)
+#define CSV_NOINLINE __declspec(noinline)
+#else
+#define CSV_NOINLINE __attribute__((noinline))
+#endif
+CSV_NOINLINE static bool csv_parse_serial(const char* buf, size_t buf_size,
const int64_t* row_offsets, int64_t n_rows,
int n_cols, char delim,
const csv_type_t* col_types,
@@ -2583,6 +3063,286 @@ static bool csv_parse_serial(const char* buf, size_t buf_size,
return true;
}
+/* --------------------------------------------------------------------------
+ * Parse every row: across the pool for a large file, else on this thread
+ * (small files, no pool, or no memory for the per-worker flags). The
+ * per-column null/escaped flags are ORed into ctx's [n_cols] arrays.
+ * strict: *bad is the file's first bad row (row INT64_MAX: none) -- the
+ * smallest row any worker saw, so the parallel answer is the serial one.
+ * -------------------------------------------------------------------------- */
+
+static void csv_parse_all(csv_par_ctx_t* ctx, bool strict, csv_bad_t* bad) {
+ bad->row = INT64_MAX; bad->col = -1; bad->kind = 0;
+ bool* col_had_null = ctx->worker_had_null;
+ bool* col_had_escaped = ctx->worker_had_escaped;
+ int ncols = ctx->n_cols;
+ ray_pool_t* pool = ray_pool_get();
+ if (pool && ctx->n_rows > 8192) {
+ uint32_t n_workers = ray_pool_total_workers(pool);
+ size_t flags_sz = (size_t)n_workers * (size_t)ncols * sizeof(bool);
+ size_t bad_sz = strict ? (size_t)n_workers * sizeof(csv_bad_t) : 0;
+ /* [bad: n_workers, strict only][had_null][had_escaped] */
+ char* scratch = (char*)ray_sys_alloc(bad_sz + flags_sz * 2);
+ if (scratch) {
+ bool* worker_flags = (bool*)(void*)(scratch + bad_sz);
+ memset(worker_flags, 0, flags_sz * 2);
+ csv_par_ctx_t pctx = *ctx;
+ pctx.worker_had_null = worker_flags;
+ pctx.worker_had_escaped = worker_flags + (size_t)n_workers * (size_t)ncols;
+ pctx.worker_bad = NULL;
+ if (strict) {
+ pctx.worker_bad = (csv_bad_t*)(void*)scratch;
+ for (uint32_t w = 0; w < n_workers; w++) pctx.worker_bad[w] = *bad;
+ }
+ ray_pool_dispatch(pool, strict ? csv_parse_fn_strict : csv_parse_fn,
+ &pctx, ctx->n_rows);
+ for (uint32_t w = 0; w < n_workers; w++) {
+ for (int c = 0; c < ncols; c++) {
+ if (pctx.worker_had_null[(size_t)w * (size_t)ncols + (size_t)c])
+ col_had_null[c] = true;
+ if (pctx.worker_had_escaped[(size_t)w * (size_t)ncols + (size_t)c])
+ col_had_escaped[c] = true;
+ }
+ if (strict && pctx.worker_bad[w].row < bad->row) *bad = pctx.worker_bad[w];
+ }
+ ray_sys_free(scratch);
+ return;
+ }
+ }
+ if (strict) {
+ csv_par_ctx_t sctx = *ctx;
+ sctx.worker_bad = bad;
+ csv_parse_fn_strict(&sctx, 0, 0, ctx->n_rows);
+ } else {
+ (void)csv_parse_serial(ctx->buf, ctx->buf_size, ctx->row_offsets, ctx->n_rows,
+ ctx->n_cols, ctx->delim, ctx->col_types,
+ ctx->resolved_types, ctx->col_data, ctx->str_refs,
+ col_had_null, col_had_escaped, ctx->row_done);
+ }
+}
+
+/* Text for a strict error, written to `out` (NUL-terminated) in at most
+ * `cap` bytes. Whole units only: a quote, a backslash, \n \r \t (two bytes
+ * each), any other control byte or a byte that does not start a complete
+ * UTF-8 character (\xHH), or a whole UTF-8 character. When the text does
+ * not fit, or `more` says it goes on past `len`, the units that fit are
+ * followed by "...", so the message is valid UTF-8 and no escape is cut.
+ * Returns the bytes written. */
+#define CSV_SHOW_MAX 40
+static size_t csv_show(const char* p, size_t len, bool more, char* out, size_t cap) {
+ size_t o = 0, i = 0;
+ if (cap < 4) { out[0] = 0; return 0; }
+ while (i < len) {
+ unsigned char ch = (unsigned char)p[i];
+ char unit[5];
+ size_t ul, take = 1;
+ if (ch == '"' || ch == '\\') { unit[0] = '\\'; unit[1] = (char)ch; ul = 2; }
+ else if (ch == '\n') { unit[0] = '\\'; unit[1] = 'n'; ul = 2; }
+ else if (ch == '\r') { unit[0] = '\\'; unit[1] = 'r'; ul = 2; }
+ else if (ch == '\t') { unit[0] = '\\'; unit[1] = 't'; ul = 2; }
+ else if (ch < 0x80 && ch >= 0x20 && ch != 0x7F) { unit[0] = (char)ch; ul = 1; }
+ else {
+ size_t n = ch >= 0xC2 && ch <= 0xDF ? 2 : ch >= 0xE0 && ch <= 0xEF ? 3
+ : ch >= 0xF0 && ch <= 0xF4 ? 4 : 0;
+ bool whole = n > 0 && i + n <= len;
+ for (size_t k = 1; whole && k < n; k++)
+ whole = ((unsigned char)p[i + k] & 0xC0) == 0x80;
+ if (whole) { memcpy(unit, p + i, n); ul = n; take = n; }
+ else if (n > 0 && i + n > len && more) break; /* cut by the capture */
+ else { snprintf(unit, sizeof unit, "\\x%02x", ch); ul = 4; }
+ }
+ bool last = i + take >= len && !more;
+ /* room for this unit, and for "..." unless it is the last one */
+ if (o + ul + (last ? 0 : 3) > cap - 1) { more = true; break; }
+ memcpy(out + o, unit, ul);
+ o += ul;
+ i += take;
+ }
+ if (more) { memcpy(out + o, "...", 3); o += 3; }
+ out[o] = 0;
+ return o;
+}
+
+/* The file's line `at` starts on, 1-based: a line ends at LF, CRLF (or
+ * LFCR) or a lone CR, as a row can. */
+static int64_t csv_line_of(const char* buf, const char* buf_end, const char* at) {
+ int64_t line = 1;
+ for (const char* q = buf; q < at; ) {
+ q = memchr(q, '\n', (size_t)(at - q));
+ if (!q) break;
+ line++; q++;
+ }
+ for (const char* q = buf; q < at; ) {
+ q = memchr(q, '\r', (size_t)(at - q));
+ if (!q) break;
+ if ((q + 1 >= buf_end || q[1] != '\n') && (q == buf || q[-1] != '\n')) line++;
+ q++;
+ }
+ return line;
+}
+
+/* A strict error's message, composed so that it fits: ray_error keeps 255
+ * bytes, the caller may append `reserve` of its own (the note a parted
+ * import adds), and only the cell text gives way, cut by csv_show. The path
+ * and the column name are clipped first only when they would leave the text
+ * no room. `where` is "column " or NULL; `text` is the cell, NULL for
+ * a message without one; pre and post surround it. */
+#define CSV_MSG_MAX 255
+static ray_t* csv_strict_msg(const char* op, const char* path, int64_t line,
+ const char* name, size_t name_len,
+ const char* pre, const char* text, size_t text_len,
+ bool text_more, const char* post, size_t reserve) {
+ char msg[CSV_MSG_MAX + 1];
+ size_t limit = reserve < CSV_MSG_MAX - 64 ? CSV_MSG_MAX - reserve : 64;
+ size_t path_max = 72, name_max = 48;
+ for (;;) {
+ char pbuf[RAY_ERR_PATH_MAX + 1], nbuf[CSV_MSG_MAX + 1];
+ int n = snprintf(msg, sizeof msg, "%s \"%s\": line %" PRId64, op,
+ ray_err_path_n(path, pbuf, path_max), line);
+ size_t o = n > 0 ? (size_t)n : 0;
+ if (name) {
+ csv_show(name, name_len, false, nbuf, name_max + 1);
+ n = snprintf(msg + o, sizeof msg - o, ", column %s", nbuf);
+ o += n > 0 ? (size_t)n : 0;
+ }
+ size_t fixed = o + strlen(pre) + strlen(post);
+ if (text && fixed + 12 > limit && (path_max > 16 || name_max > 16)) {
+ if (path_max > 16) path_max = path_max > 32 ? path_max - 16 : 16;
+ else name_max = name_max > 32 ? name_max - 16 : 16;
+ continue;
+ }
+ if (o + strlen(pre) < limit) {
+ memcpy(msg + o, pre, strlen(pre));
+ o += strlen(pre);
+ }
+ if (text) {
+ size_t room = limit > o + strlen(post) ? limit - o - strlen(post) : 4;
+ o += csv_show(text, text_len, text_more, msg + o, room + 1);
+ }
+ if (o + strlen(post) <= CSV_MSG_MAX) {
+ memcpy(msg + o, post, strlen(post));
+ o += strlen(post);
+ }
+ msg[o] = 0;
+ return ray_error("parse", "%s", msg);
+ }
+}
+
+/* The strict error for the first bad row (#1885): the file's line it starts
+ * on (1-based, counting the header and the newlines inside quoted cells),
+ * and the column and cell text, or the cell count. The row is cut again
+ * here as the parse cut it; only the error pays for it. */
+static ray_t* csv_strict_error(const ray_csv_opts_t* opts, const char* path,
+ const char* buf, size_t buf_size,
+ size_t rows_end,
+ const int64_t* row_offsets, int64_t n_rows,
+ const csv_bad_t* bad, int ncols, char delim,
+ const int64_t* col_name_ids,
+ const int8_t* resolved_types) {
+ const char* buf_end = buf + buf_size;
+ const char* row_start = buf + row_offsets[bad->row];
+ const char* row_end = bad->row + 1 < n_rows ? buf + row_offsets[bad->row + 1] : buf + rows_end;
+ int64_t line = csv_line_of(buf, buf_end, row_start);
+ const char* op = opts->op ? opts->op : "csv";
+
+ /* Cut the row: its cell count, and the bad cell's text. */
+ char esc_buf[8192];
+ /* at most CSV_SHOW_MAX bytes of the cell are shown, less if the
+ * message has no room for them */
+ char text[CSV_SHOW_MAX];
+ size_t text_len = 0, cell_len = 0;
+ int cells = 1;
+ const char* p = row_start;
+ for (int c = 0; ; c++) {
+ if (p >= row_end && c > 0) break;
+ const char* fld; size_t flen; char* dyn = NULL;
+ const char* p0 = p;
+ p = scan_field(p, buf_end, delim, &fld, &flen, esc_buf, &dyn);
+ if (c == bad->col) {
+ cell_len = flen;
+ text_len = flen < sizeof text ? flen : sizeof text;
+ memcpy(text, fld, text_len);
+ }
+ if (dyn) ray_sys_free(dyn);
+ uint8_t k = 0;
+ if (!csv_strict_cell_end(p0, p, row_end, buf_end, delim, &k)) break;
+ cells++;
+ }
+
+ const char* name = NULL;
+ size_t name_len = 0;
+ if (bad->col >= 0) {
+ ray_t* nm = ray_sym_str(col_name_ids[bad->col]); /* borrowed */
+ name = nm ? ray_str_ptr(nm) : "?";
+ name_len = nm ? ray_str_len(nm) : 1;
+ }
+ char post[96];
+ const char* tn = bad->col >= 0 ? ray_type_name(resolved_types[bad->col]) : "";
+ const char* an = (tn[0] == 'F' || tn[0] == 'I') ? "an" : "a";
+ bool more = cell_len > text_len;
+ size_t rsv = opts->reserve;
+ switch (bad->kind) {
+ case CSV_BAD_CELLS:
+ snprintf(post, sizeof post, ": expected %d cell%s, got %d", ncols, ncols == 1 ? "" : "s", cells);
+ return csv_strict_msg(op, path, line, NULL, 0, post, NULL, 0, false, "", rsv);
+ case CSV_BAD_LONE_CR:
+ return csv_strict_msg(op, path, line, NULL, 0,
+ ": text after a CR inside the row (a row ends at LF or CRLF)",
+ NULL, 0, false, "", rsv);
+ case CSV_BAD_UNCLOSED:
+ return csv_strict_msg(op, path, line, name, name_len,
+ ": a quoted cell with no closing quote", NULL, 0, false, "", rsv);
+ case CSV_BAD_AFTER_QUOTE:
+ return csv_strict_msg(op, path, line, name, name_len,
+ ": text after the closing quote", NULL, 0, false, "", rsv);
+ case CSV_BAD_RANGE:
+ snprintf(post, sizeof post, "\" is out of range for %s %s", an, tn);
+ break;
+ case CSV_BAD_NULLV:
+ snprintf(post, sizeof post, "\" reads as a null %s", tn);
+ break;
+ case CSV_BAD_PRECISION:
+ snprintf(post, sizeof post, "\" has more fraction digits than %s %s holds", an, tn);
+ break;
+ case CSV_BAD_UNDERFLOW:
+ snprintf(post, sizeof post, "\" underflows to zero for %s %s", an, tn);
+ break;
+ default:
+ snprintf(post, sizeof post, "\" is not %s %s", an, tn);
+ break;
+ }
+ return csv_strict_msg(op, path, line, name, name_len, ": \"", text, text_len, more, post, rsv);
+}
+
+/* Strict (#1885 review): the header's quoted cells are well formed, as a
+ * row's must be -- a quote closed, and nothing after it but the delimiter
+ * or the line end. Returns the error, or NULL. */
+static ray_t* csv_strict_header(const ray_csv_opts_t* opts, const char* path,
+ const char* buf, const char* buf_end,
+ const char* text, char delim, int ncols) {
+ char esc_buf[8192];
+ const char* p = text;
+ for (int c = 0; c < ncols; c++) {
+ const char* fld; size_t flen; char* dyn = NULL;
+ const char* p0 = p;
+ p = scan_field(p, buf_end, delim, &fld, &flen, esc_buf, &dyn);
+ if (dyn) ray_sys_free(dyn);
+ uint8_t k = 0;
+ bool more = csv_strict_cell_end(p0, p, buf_end, buf_end, delim, &k);
+ if (k == CSV_BAD_UNCLOSED || k == CSV_BAD_AFTER_QUOTE) {
+ char pre[96];
+ snprintf(pre, sizeof pre, ": header cell %d: %s", c + 1,
+ k == CSV_BAD_UNCLOSED ? "a quoted cell with no closing quote"
+ : "text after the closing quote");
+ return csv_strict_msg(opts->op ? opts->op : "csv", path,
+ csv_line_of(buf, buf_end, text), NULL, 0, pre,
+ NULL, 0, false, "", opts->reserve);
+ }
+ if (!more) break;
+ }
+ return NULL;
+}
+
/* --------------------------------------------------------------------------
* `INT` schema columns — auto narrowest integer width.
*
@@ -2725,12 +3485,15 @@ static bool csv_resolve_auto_streamed(const char* buf, size_t file_size,
return true;
}
-static ray_t* csv_materialize_rows(const char* buf, size_t file_size,
+static ray_t* csv_materialize_rows(const char* path,
+ const char* buf, size_t file_size, size_t rows_end,
const int64_t* row_offsets, int64_t n_rows,
int ncols, char delimiter,
const int64_t* col_name_ids,
const int8_t* resolved_types,
- struct ray_sym_domain_s* sym_dom) {
+ struct ray_sym_domain_s* sym_dom,
+ const ray_csv_opts_t* opts) {
+ bool strict = opts && opts->strict;
/* Defensive guard: RAY_CSV_AUTO_TAG must be resolved to a concrete width
* before reaching this point (by csv_resolve_auto_in_place or
* csv_resolve_auto_streamed). If a marker slips through, the resolution
@@ -2829,58 +3592,25 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size,
}
}
+ csv_bad_t bad;
{
- ray_pool_t* pool = ray_pool_get();
- bool use_parallel = pool && n_rows > 8192;
-
- if (use_parallel) {
- uint32_t n_workers = ray_pool_total_workers(pool);
- size_t worker_flags_sz = (size_t)n_workers * (size_t)ncols * sizeof(bool);
- bool* worker_flags = (bool*)ray_sys_alloc(worker_flags_sz * 2);
- if (!worker_flags) {
- use_parallel = false;
- } else {
- memset(worker_flags, 0, worker_flags_sz * 2);
- bool* worker_had_null_buf = worker_flags;
- bool* worker_had_escaped_buf = worker_flags +
- (size_t)n_workers * (size_t)ncols;
-
- csv_par_ctx_t ctx = {
- .buf = buf,
- .buf_size = file_size,
- .row_offsets = row_offsets,
- .n_rows = n_rows,
- .n_cols = ncols,
- .delim = delimiter,
- .col_types = parse_types,
- .resolved_types = resolved_types,
- .col_data = col_data,
- .str_refs = str_ref_bufs,
- .worker_had_null = worker_had_null_buf,
- .worker_had_escaped = worker_had_escaped_buf,
- .row_done = row_done,
- };
-
- ray_pool_dispatch(pool, csv_parse_fn, &ctx, n_rows);
-
- for (uint32_t w = 0; w < n_workers; w++) {
- for (int c = 0; c < ncols; c++) {
- if (worker_had_null_buf[(size_t)w * (size_t)ncols + (size_t)c])
- col_had_null[c] = true;
- if (worker_had_escaped_buf[(size_t)w * (size_t)ncols + (size_t)c])
- col_had_escaped[c] = true;
- }
- }
- ray_sys_free(worker_flags);
- }
- }
-
- if (!use_parallel) {
- (void)csv_parse_serial(buf, file_size, row_offsets, n_rows,
- ncols, delimiter, parse_types, resolved_types,
- col_data, str_ref_bufs, col_had_null,
- col_had_escaped, row_done);
- }
+ csv_par_ctx_t ctx = {
+ .buf = buf,
+ .buf_size = file_size,
+ .rows_end = rows_end,
+ .row_offsets = row_offsets,
+ .n_rows = n_rows,
+ .n_cols = ncols,
+ .delim = delimiter,
+ .col_types = parse_types,
+ .resolved_types = resolved_types,
+ .col_data = col_data,
+ .str_refs = str_ref_bufs,
+ .worker_had_null = col_had_null,
+ .worker_had_escaped = col_had_escaped,
+ .row_done = row_done,
+ };
+ csv_parse_all(&ctx, strict, &bad);
}
if (ray_interrupted()) {
@@ -2892,6 +3622,17 @@ static ray_t* csv_materialize_rows(const char* buf, size_t file_size,
return ray_error("cancel", "interrupted");
}
+ if (RAY_UNLIKELY(bad.row != INT64_MAX)) {
+ ray_t* e = csv_strict_error(opts, path, buf, file_size, rows_end, row_offsets, n_rows,
+ &bad, ncols, delimiter, col_name_ids, resolved_types);
+ csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows,
+ buf, file_size, row_done, col_had_escaped);
+ for (int c = 0; c < ncols; c++) scratch_free(str_ref_hdrs[c]);
+ scratch_free(row_done_hdr);
+ for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]);
+ return e;
+ }
+
if (has_text_cols) {
csv_finalize_ctx_t fctx = {
.str_refs = str_ref_bufs,
@@ -3046,7 +3787,9 @@ static inline size_t csv_bom_len(const char* buf, size_t size) {
* fires. */
static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool header,
const int8_t* col_types_in, int32_t n_types,
- const int64_t* col_names_in, int32_t n_names) {
+ const int64_t* col_names_in, int32_t n_names,
+ const ray_csv_opts_t* opts) {
+ bool strict = opts && opts->strict;
if (ray_interrupted()) return ray_error("cancel", "interrupted");
/* ---- 1. Open file and get size ---- */
@@ -3119,6 +3862,9 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h
p++;
}
}
+ /* Strict without a header: the schema says how many cells a row has,
+ * and the first row is checked as every other row is (#1885 review). */
+ if (strict && !header && col_types_in) ncols = n_types;
if (ncols > CSV_MAX_COLS) {
ray_vm_unmap_file(buf, file_size);
/* fd already closed after mmap (line 1044) — do not close again */
@@ -3145,6 +3891,10 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h
int64_t col_name_ids[CSV_MAX_COLS];
if (header) {
+ if (strict) {
+ ray_t* herr = csv_strict_header(opts, path, buf, buf_end, text, delimiter, ncols);
+ if (herr) { ray_vm_unmap_file(buf, file_size); return herr; }
+ }
for (int c = 0; c < ncols; c++) {
const char* fld;
size_t flen;
@@ -3325,62 +4075,33 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h
}
ray_progress_span_phase("parse", prog_scan_end, prog_parse_end - prog_scan_end);
+ csv_bad_t bad;
{
- ray_pool_t* pool = ray_pool_get();
- bool use_parallel = pool && n_rows > 8192;
-
- if (use_parallel) {
- uint32_t n_workers = ray_pool_total_workers(pool);
- size_t worker_flags_sz = (size_t)n_workers * (size_t)ncols * sizeof(bool);
- bool* worker_flags = (bool*)ray_sys_alloc(worker_flags_sz * 2);
- if (!worker_flags) {
- use_parallel = false;
- } else {
- memset(worker_flags, 0, worker_flags_sz * 2);
- bool* worker_had_null_buf = worker_flags;
- bool* worker_had_escaped_buf = worker_flags +
- (size_t)n_workers * (size_t)ncols;
-
- csv_par_ctx_t ctx = {
- .buf = buf,
- .buf_size = file_size,
- .row_offsets = row_offsets,
- .n_rows = n_rows,
- .n_cols = ncols,
- .delim = delimiter,
- .col_types = parse_types,
- .resolved_types = resolved_types,
- .col_data = col_data,
- .str_refs = str_ref_bufs,
- .worker_had_null = worker_had_null_buf,
- .worker_had_escaped = worker_had_escaped_buf,
- .row_done = row_done,
- };
-
- ray_pool_dispatch(pool, csv_parse_fn, &ctx, n_rows);
-
- /* OR worker null flags into col_had_null */
- for (uint32_t w = 0; w < n_workers; w++) {
- for (int c = 0; c < ncols; c++) {
- if (worker_had_null_buf[(size_t)w * (size_t)ncols + (size_t)c])
- col_had_null[c] = true;
- if (worker_had_escaped_buf[(size_t)w * (size_t)ncols + (size_t)c])
- col_had_escaped[c] = true;
- }
- }
- ray_sys_free(worker_flags);
- }
- }
-
- if (!use_parallel) {
- (void)csv_parse_serial(buf, file_size, row_offsets, n_rows,
- ncols, delimiter, parse_types, resolved_types,
- col_data, str_ref_bufs, col_had_null,
- col_had_escaped, row_done);
- }
+ csv_par_ctx_t ctx = {
+ .buf = buf,
+ .buf_size = file_size,
+ .rows_end = file_size,
+ .row_offsets = row_offsets,
+ .n_rows = n_rows,
+ .n_cols = ncols,
+ .delim = delimiter,
+ .col_types = parse_types,
+ .resolved_types = resolved_types,
+ .col_data = col_data,
+ .str_refs = str_ref_bufs,
+ .worker_had_null = col_had_null,
+ .worker_had_escaped = col_had_escaped,
+ .row_done = row_done,
+ };
+ csv_parse_all(&ctx, strict, &bad);
}
if (ray_interrupted()) goto fail_parsed_cancel;
+ if (RAY_UNLIKELY(bad.row != INT64_MAX)) {
+ result = csv_strict_error(opts, path, buf, file_size, file_size, row_offsets, n_rows,
+ &bad, ncols, delimiter, col_name_ids, resolved_types);
+ goto fail_parsed;
+ }
/* ---- 9b. Materialize RAY_STR columns AND batch-intern sym columns ----
* These two phases touch disjoint columns and (after the GUID fix)
@@ -3512,6 +4233,15 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h
return result;
/* Error paths */
+fail_parsed: /* every row parsed; `result` is the error */
+ csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows,
+ buf, file_size, row_done, col_had_escaped);
+ for (int c = 0; c < ncols; c++) scratch_free(str_ref_hdrs[c]);
+ scratch_free(row_done_hdr);
+ for (int c = 0; c < ncols; c++) ray_release(col_vecs[c]);
+ scratch_free(row_offsets_hdr);
+ ray_vm_unmap_file(buf, file_size);
+ return result;
fail_parsed_cancel:
csv_free_escaped_strrefs(str_ref_bufs, ncols, parse_types, n_rows,
buf, file_size, row_done, col_had_escaped);
@@ -3530,16 +4260,24 @@ static ray_t* csv_read_named_opts_inner(const char* path, char delimiter, bool h
return ray_error("oom", NULL);
}
-ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header,
- const int8_t* col_types_in, int32_t n_types,
- const int64_t* col_names_in, int32_t n_names) {
+ray_t* ray_read_csv_ex(const char* path, char delimiter, bool header,
+ const int8_t* col_types_in, int32_t n_types,
+ const int64_t* col_names_in, int32_t n_names,
+ const ray_csv_opts_t* opts) {
ray_t* r = csv_read_named_opts_inner(path, delimiter, header,
col_types_in, n_types,
- col_names_in, n_names);
+ col_names_in, n_names, opts);
ray_progress_span_end();
return r;
}
+ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header,
+ const int8_t* col_types_in, int32_t n_types,
+ const int64_t* col_names_in, int32_t n_names) {
+ return ray_read_csv_ex(path, delimiter, header, col_types_in, n_types,
+ col_names_in, n_names, NULL);
+}
+
ray_t* ray_read_csv_opts(const char* path, char delimiter, bool header,
const int8_t* col_types_in, int32_t n_types) {
return ray_read_csv_named_opts(path, delimiter, header,
@@ -3619,12 +4357,21 @@ bool ray_csv_source_failure(const char** call, int* errnum) {
return true;
}
+/* A chunk's strict error (#1885) goes to opts->err for the caller, which
+ * shows its message; any other chunk error is reported by its code alone. */
+static void csv_keep_strict_error(ray_t* tbl, ray_err_t err, ray_csv_opts_t* opts) {
+ if (!tbl) return;
+ if (err == RAY_ERR_PARSE && opts && opts->strict && !opts->err) opts->err = tbl;
+ else ray_error_free(tbl);
+}
+
static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool header,
const int8_t* col_types_in, int32_t n_types,
const int64_t* col_names_in, int32_t n_names,
const char* dir, int64_t rows_per_chunk,
const char* sym_path, ray_compress_t mode,
- const char* cur, ray_err_t cur_err) {
+ const char* cur, ray_err_t cur_err,
+ ray_csv_opts_t* opts) {
if (ray_interrupted()) return RAY_ERR_CANCEL;
if (!path || !dir || !sym_path) return RAY_ERR_DOMAIN;
if (rows_per_chunk <= 0) rows_per_chunk = CSV_PART_ROWS_DEFAULT;
@@ -3692,6 +4439,8 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool
q++;
}
}
+ /* strict without a header: the schema's cell count (#1885 review) */
+ if (opts && opts->strict && !header && col_types_in) ncols = n_types;
if (ncols > CSV_MAX_COLS) {
ray_vm_unmap_file(buf, file_size);
return RAY_ERR_LIMIT;
@@ -3707,6 +4456,14 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool
int64_t col_name_ids[CSV_MAX_COLS];
if (header) {
+ if (opts && opts->strict) {
+ ray_t* herr = csv_strict_header(opts, path, buf, buf_end, text, delimiter, ncols);
+ if (herr) {
+ if (!opts->err) opts->err = herr; else ray_error_free(herr);
+ ray_vm_unmap_file(buf, file_size);
+ return RAY_ERR_PARSE;
+ }
+ }
for (int c = 0; c < ncols; c++) {
const char* fld;
size_t flen;
@@ -3881,14 +4638,14 @@ static ray_err_t csv_save_splayed_to_dir(const char* path, char delimiter, bool
}
int64_t tr_c1 = ray_profile_now_ns();
- ray_t* tbl = csv_materialize_rows(buf, file_size, row_offsets,
+ ray_t* tbl = csv_materialize_rows(path, buf, file_size, next_offset, row_offsets,
cnt, ncols, delimiter, col_name_ids,
- resolved_types, sym_dom);
+ resolved_types, sym_dom, opts);
scratch_free(row_offsets_hdr);
if (!tbl || RAY_IS_ERR(tbl)) {
err = (tbl && RAY_IS_ERR(tbl)) ? ray_err_from_obj(tbl)
: RAY_ERR_OOM;
- if (tbl) ray_release(tbl);
+ csv_keep_strict_error(tbl, err, opts);
break;
}
int64_t tr_c2 = ray_profile_now_ns();
@@ -4041,6 +4798,15 @@ ray_err_t ray_csv_save_splayed_mode(const char* path, char delimiter, bool heade
const int8_t* col_types_in, int32_t n_types,
const int64_t* col_names_in, int32_t n_names,
const char* dir, int64_t rows_per_chunk, ray_compress_t mode) {
+ return ray_csv_save_splayed_ex(path, delimiter, header, col_types_in, n_types,
+ col_names_in, n_names, dir, rows_per_chunk, mode, NULL);
+}
+
+ray_err_t ray_csv_save_splayed_ex(const char* path, char delimiter, bool header,
+ const int8_t* col_types_in, int32_t n_types,
+ const int64_t* col_names_in, int32_t n_names,
+ const char* dir, int64_t rows_per_chunk, ray_compress_t mode,
+ ray_csv_opts_t* opts) {
g_csv_src_fail.call = NULL; /* this import's own failure only */
if (ray_interrupted()) return RAY_ERR_CANCEL;
if (!path || !dir) return RAY_ERR_DOMAIN;
@@ -4052,7 +4818,8 @@ ray_err_t ray_csv_save_splayed_mode(const char* path, char delimiter, bool heade
if (err != RAY_OK) return err;
err = csv_save_splayed_to_dir(path, delimiter, header, col_types_in, n_types,
col_names_in, n_names, write.dir,
- rows_per_chunk, sym_path, mode, write.cur, write.cur_err);
+ rows_per_chunk, sym_path, mode, write.cur, write.cur_err,
+ opts);
return ray_splay_write_finish(&write, err, false);
}
@@ -4061,6 +4828,7 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea
const int64_t* col_names_in, int32_t n_names,
const char* root, const char* table_name,
int64_t rows_per_part, bool staged,
+ ray_csv_opts_t* opts,
ray_compress_t mode) {
if (ray_interrupted()) return RAY_ERR_CANCEL;
if (!path || !root || !table_name) return RAY_ERR_DOMAIN;
@@ -4123,6 +4891,8 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea
q++;
}
}
+ /* strict without a header: the schema's cell count (#1885 review) */
+ if (opts && opts->strict && !header && col_types_in) ncols = n_types;
if (ncols > CSV_MAX_COLS) {
ray_vm_unmap_file(buf, file_size);
return RAY_ERR_LIMIT;
@@ -4138,6 +4908,14 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea
int64_t col_name_ids[CSV_MAX_COLS];
if (header) {
+ if (opts && opts->strict) {
+ ray_t* herr = csv_strict_header(opts, path, buf, buf_end, text, delimiter, ncols);
+ if (herr) {
+ if (!opts->err) opts->err = herr; else ray_error_free(herr);
+ ray_vm_unmap_file(buf, file_size);
+ return RAY_ERR_PARSE;
+ }
+ }
for (int c = 0; c < ncols; c++) {
const char* fld;
size_t flen;
@@ -4252,13 +5030,13 @@ static ray_err_t csv_save_parted_impl(const char* path, char delimiter, bool hea
}
}
- ray_t* tbl = csv_materialize_rows(buf, file_size, row_offsets,
+ ray_t* tbl = csv_materialize_rows(path, buf, file_size, next_offset, row_offsets,
cnt, ncols, delimiter, col_name_ids, resolved_types,
- import_domain);
+ import_domain, opts);
if (!tbl || RAY_IS_ERR(tbl)) {
err = (tbl && RAY_IS_ERR(tbl)) ? ray_err_from_obj(tbl)
: RAY_ERR_OOM;
- if (tbl) ray_release(tbl);
+ csv_keep_strict_error(tbl, err, opts);
scratch_free(row_offsets_hdr);
if (trace)
fprintf(stderr, "csv.parted: materialize failure part=%" PRId64 " rows=%" PRId64 "\n",
@@ -4361,6 +5139,17 @@ ray_err_t ray_csv_save_parted_mode(const char* path, char delimiter, bool header
const int64_t* col_names, int32_t n_names,
const char* root, const char* table_name,
int64_t rows_per_part, ray_compress_t mode) {
+ return ray_csv_save_parted_ex(path, delimiter, header, col_types, n_types,
+ col_names, n_names, root, table_name,
+ rows_per_part, mode, NULL);
+}
+
+ray_err_t ray_csv_save_parted_ex(const char* path, char delimiter, bool header,
+ const int8_t* col_types, int32_t n_types,
+ const int64_t* col_names, int32_t n_names,
+ const char* root, const char* table_name,
+ int64_t rows_per_part, ray_compress_t mode,
+ ray_csv_opts_t* opts) {
g_csv_src_fail.call = NULL; /* this import's own failure only */
if (!path || !root || !*root || !table_name || !*table_name ||
table_name[0] == '.' || strchr(table_name,'/') || strchr(table_name,'\\'))
@@ -4372,7 +5161,7 @@ ray_err_t ray_csv_save_parted_mode(const char* path, char delimiter, bool header
struct stat st;
if (stat(dest,&st) == 0)
return csv_save_parted_impl(path,delimiter,header,col_types,n_types,
- col_names,n_names,dest,table_name,rows_per_part,false,mode);
+ col_names,n_names,dest,table_name,rows_per_part,false,opts,mode);
/* Fail on an unreadable input before claiming the staging directory:
* failed staging is retained and blocks the root, which a mistyped
* source path must not do. */
@@ -4394,7 +5183,7 @@ ray_err_t ray_csv_save_parted_mode(const char* path, char delimiter, bool header
if (mkdir(staging,0755) != 0) return RAY_ERR_IO;
#endif
ray_err_t err = csv_save_parted_impl(path,delimiter,header,col_types,n_types,
- col_names,n_names,staging,table_name,rows_per_part,true,mode);
+ col_names,n_names,staging,table_name,rows_per_part,true,opts,mode);
if (err != RAY_OK) {
/* Failed staging is kept for diagnosis only when it holds a
* partition. A failure before the first one (a type vector that
diff --git a/src/io/csv.h b/src/io/csv.h
index ba23d6ec1..151f20d78 100644
--- a/src/io/csv.h
+++ b/src/io/csv.h
@@ -70,12 +70,36 @@ typedef enum {
* CSV_TYPE_I64. */
csv_type_t csv_resolve_int_width(int64_t min, int64_t max, bool has_null);
+/* Options of a CSV load beyond its schema (#1885).
+ * strict a row whose cell count is not the schema's, a malformed quoted
+ * cell, or a non-empty cell that does not parse as its column's
+ * type fails the load with a `parse` error naming the file's line
+ * and the column; the default reads such cells as nulls. An empty
+ * cell is a null in both modes.
+ * op the caller's name at the head of that message ("csv" if NULL).
+ * reserve bytes of the 255-byte message the caller will append to a
+ * strict error (a parted import's note on retained output); the
+ * cell text is cut to leave them.
+ * err out, the save forms only (they return a code): the strict error
+ * with its message, which the caller then owns; NULL otherwise. */
+typedef struct {
+ bool strict;
+ const char* op;
+ size_t reserve;
+ ray_t* err;
+} ray_csv_opts_t;
+
ray_t* ray_read_csv(const char* path);
ray_t* ray_read_csv_opts(const char* path, char delimiter, bool header,
const int8_t* col_types, int32_t n_types);
ray_t* ray_read_csv_named_opts(const char* path, char delimiter, bool header,
const int8_t* col_types, int32_t n_types,
const int64_t* col_names, int32_t n_names);
+/* The same with load options (NULL: the defaults). */
+ray_t* ray_read_csv_ex(const char* path, char delimiter, bool header,
+ const int8_t* col_types, int32_t n_types,
+ const int64_t* col_names, int32_t n_names,
+ const ray_csv_opts_t* opts);
/* `root` without trailing separators, and the `.csv-partial` staging
* directory a new parted root is imported into. */
ray_err_t ray_csv_parted_paths(const char* root, char* dest, size_t dest_size,
@@ -90,6 +114,12 @@ ray_err_t ray_csv_save_parted_mode(const char* path, char delimiter, bool header
const int64_t* col_names, int32_t n_names,
const char* root, const char* table_name,
int64_t rows_per_part, ray_compress_t mode);
+ray_err_t ray_csv_save_parted_ex(const char* path, char delimiter, bool header,
+ const int8_t* col_types, int32_t n_types,
+ const int64_t* col_names, int32_t n_names,
+ const char* root, const char* table_name,
+ int64_t rows_per_part, ray_compress_t mode,
+ ray_csv_opts_t* opts);
ray_err_t ray_csv_save_splayed_named_opts(const char* path, char delimiter, bool header,
const int8_t* col_types, int32_t n_types,
const int64_t* col_names, int32_t n_names,
@@ -100,6 +130,12 @@ ray_err_t ray_csv_save_splayed_mode(const char* path, char delimiter, bool heade
const int8_t* col_types, int32_t n_types,
const int64_t* col_names, int32_t n_names,
const char* dir, int64_t rows_per_chunk, ray_compress_t mode);
+/* The same with load options (NULL: the defaults). */
+ray_err_t ray_csv_save_splayed_ex(const char* path, char delimiter, bool header,
+ const int8_t* col_types, int32_t n_types,
+ const int64_t* col_names, int32_t n_names,
+ const char* dir, int64_t rows_per_chunk, ray_compress_t mode,
+ ray_csv_opts_t* opts);
ray_err_t ray_write_csv(ray_t* table, const char* path);
/* After a failed ray_csv_save_splayed_mode / ray_csv_save_parted_mode: the
diff --git a/src/lang/sig.c b/src/lang/sig.c
index 5356cbe2c..b6fb663a9 100644
--- a/src/lang/sig.c
+++ b/src/lang/sig.c
@@ -664,7 +664,7 @@ static const ray_sig_entry_t own_sigs[] = {
"Define a Datalog rule (head + body clauses)"},
{"env", "(env )",
"List all global environment bindings"},
- {".csv.read", "(.csv.read [] [] )",
+ {".csv.read", "(.csv.read [] [] [] )",
"Load CSV file into table (mmap, parallel parse)"},
{".csv.write", "(.csv.write [])",
"Write table to CSV file"},
diff --git a/src/ops/builtins.c b/src/ops/builtins.c
index 6a051fb77..3b1262b44 100644
--- a/src/ops/builtins.c
+++ b/src/ops/builtins.c
@@ -862,7 +862,68 @@ static int8_t resolve_type_name(int64_t sym_id) {
return result;
}
+/* The leading options dict of the CSV loaders (#1885): `strict` on each,
+ * `compress` on the ones that write columns (`writes`). As for compress
+ * alone: the keys are symbols, an unknown key or a non-bool value is a
+ * domain error. */
+static ray_t* csv_load_opts_parse(ray_t* opts, bool writes,
+ ray_compress_t* mode, bool* strict) {
+ *mode = RAY_COMPRESS_ABSENT;
+ *strict = false;
+ ray_t* keys = ray_dict_keys(opts);
+ if (keys && keys->len > 0 && keys->type != RAY_SYM)
+ return ray_error("domain", "option keys must be symbols");
+ for (int64_t i = 0; keys && i < keys->len; i++) {
+ ray_t* k = ray_sym_vec_cell(keys, i);
+ size_t kl = k ? ray_str_len(k) : 0;
+ const char* kp = k ? ray_str_ptr(k) : "?";
+ bool known = (kl == 6 && memcmp(kp, "strict", 6) == 0) ||
+ (writes && kl == 8 && memcmp(kp, "compress", 8) == 0);
+ if (!known)
+ return ray_error("domain", "unknown option '%.*s' (only %s accepted)",
+ k ? (int)kl : 1, kp,
+ writes ? "compress and strict are" : "strict is");
+ }
+ if (writes) {
+ ray_t* oerr = ray_compress_opt_parse(opts, false, mode);
+ if (oerr) return oerr;
+ }
+ ray_t* key = ray_sym(ray_sym_intern("strict", 6));
+ if (!key || RAY_IS_ERR(key)) return key ? key : ray_error("oom", NULL);
+ ray_t* v = ray_dict_get(opts, key);
+ ray_release(key);
+ if (!v) return NULL;
+ if (RAY_IS_ERR(v)) return v;
+ bool ok = v->type == -RAY_BOOL;
+ if (ok) *strict = v->b8 != 0;
+ ray_release(v);
+ return ok ? NULL : ray_error("domain", "strict must be true or false");
+}
+
+/* Arguments a CSV loader's arrangement left over (#1885 review): an options
+ * dict there is a second one, or one that does not lead; anything else is
+ * one argument too many. Each arrangement consumes exactly its own. */
+static ray_t* csv_extra_args(const char* op, ray_t** extra, int64_t k, bool had_opts) {
+ for (int64_t i = 0; i < k; i++)
+ if (extra[i] && extra[i]->type == RAY_DICT)
+ return had_opts ? ray_error("domain", "%s: a second options dict", op)
+ : ray_error("domain", "%s: the options dict must be the first argument", op);
+ return ray_error("arity", "%s: %lld argument%s past its schema and path", op,
+ (long long)k, k == 1 ? "" : "s");
+}
+
ray_t* ray_read_csv_fn(ray_t** args, int64_t n) {
+ ray_csv_opts_t copts = { .strict = false, .op = ".csv.read", .err = NULL };
+ bool had_opts = false;
+ if (n >= 1 && args[0] && args[0]->type == RAY_DICT) {
+ if (n >= 2 && args[1] && args[1]->type == RAY_DICT)
+ return ray_error("domain", ".csv.read: a second options dict");
+ had_opts = true;
+ ray_compress_t unused;
+ ray_t* oerr = csv_load_opts_parse(args[0], false, &unused, &copts.strict);
+ if (oerr) return oerr;
+ args++; n--;
+ }
if (n < 1 || n > 3) return ray_error("arity", ".csv.read: expects 1 to 3 arguments, got %lld", (long long)n);
/* (.csv.read [types] "path"), (.csv.read [names] [types] "path"), or (.csv.read "path") */
@@ -880,6 +941,8 @@ ray_t* ray_read_csv_fn(ray_t** args, int64_t n) {
} else {
path_obj = args[0];
}
+ int64_t used = names ? 3 : schema ? 2 : 1;
+ if (n != used) return csv_extra_args(".csv.read", args + used, n - used, had_opts);
const char* path = NULL;
if (path_obj->type == -RAY_STR)
@@ -907,15 +970,15 @@ ray_t* ray_read_csv_fn(ray_t** args, int64_t n) {
}
ray_t* tbl = names
// cppcheck-suppress uninitvar // col_types is filled for all ncols (<= 256, checked above); col_names only when names is set, the only case it is passed
- ? ray_read_csv_named_opts(path, 0, false, col_types, (int32_t)ncols,
- col_names, (int32_t)ncols)
- : ray_read_csv_opts(path, 0, true, col_types, (int32_t)ncols);
+ ? ray_read_csv_ex(path, 0, false, col_types, (int32_t)ncols,
+ col_names, (int32_t)ncols, &copts)
+ : ray_read_csv_ex(path, 0, true, col_types, (int32_t)ncols, NULL, 0, &copts);
if (!tbl) { char pbuf[RAY_ERR_PATH_MAX + 1]; return ray_error("io", ".csv.read \"%s\": read failed", ray_err_path(path, pbuf)); }
if (RAY_IS_ERR(tbl)) return tbl;
return tbl;
}
- ray_t* tbl = ray_read_csv(path);
+ ray_t* tbl = ray_read_csv_ex(path, 0, true, NULL, 0, NULL, 0, &copts);
if (!tbl) { char pbuf[RAY_ERR_PATH_MAX + 1]; return ray_error("io", ".csv.read \"%s\": read failed", ray_err_path(path, pbuf)); }
if (RAY_IS_ERR(tbl)) return tbl;
return tbl;
@@ -988,10 +1051,13 @@ static ray_t* csv_import_error(ray_err_t err, const char* op, const char* src, c
ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) {
ray_compress_t mode = RAY_COMPRESS_ABSENT;
+ ray_csv_opts_t copts = { .strict = false, .op = ".csv.splayed", .err = NULL };
+ bool had_opts = false;
if (n >= 1 && args[0] && args[0]->type == RAY_DICT) {
if (n >= 2 && args[1] && args[1]->type == RAY_DICT)
return ray_error("domain", "csv.splayed: a second options dict");
- ray_t* oerr = ray_compress_opt_parse(args[0], true, &mode);
+ had_opts = true;
+ ray_t* oerr = csv_load_opts_parse(args[0], true, &mode, &copts.strict);
if (oerr) return oerr;
args++; n--;
}
@@ -1017,6 +1083,10 @@ ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) {
} else {
return ray_error("domain", "csv.splayed: invalid argument arrangement");
}
+ {
+ int64_t used = names ? 3 : schema ? 2 : 1;
+ if (data_n != used) return csv_extra_args("csv.splayed", args + used, data_n - used, had_opts);
+ }
if (!path_obj || path_obj->type != -RAY_STR) return ray_error("type", "csv.splayed: source path must be str, got %s", path_obj ? ray_type_name(path_obj->type) : "null");
const char* path = ray_str_ptr(path_obj);
if (!path) return ray_error("domain", "csv.splayed: empty source path");
@@ -1048,10 +1118,11 @@ ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) {
}
}
- ray_err_t err = ray_csv_save_splayed_mode(path, 0, header,
- types_arg, ncols,
- names_arg, ncols,
- dir, 0, mode);
+ ray_err_t err = ray_csv_save_splayed_ex(path, 0, header,
+ types_arg, ncols,
+ names_arg, ncols,
+ dir, 0, mode, &copts);
+ if (copts.err) return copts.err;
if (err != RAY_OK) {
ray_t* serr = err == RAY_ERR_IO ? csv_source_error(".csv.splayed", path) : NULL;
return serr ? serr : csv_import_error(err, ".csv.splayed", path, dir);
@@ -1070,10 +1141,13 @@ ray_t* ray_read_csv_splayed_fn(ray_t** args, int64_t n) {
ray_t* ray_read_csv_parted_fn(ray_t** args, int64_t n) {
ray_compress_t mode = RAY_COMPRESS_ABSENT;
+ ray_csv_opts_t copts = { .strict = false, .op = ".csv.parted", .err = NULL };
+ bool had_opts = false;
if (n >= 1 && args[0] && args[0]->type == RAY_DICT) {
if (n >= 2 && args[1] && args[1]->type == RAY_DICT)
return ray_error("domain", "csv.parted: a second options dict");
- ray_t* oerr = ray_compress_opt_parse(args[0], true, &mode);
+ had_opts = true;
+ ray_t* oerr = csv_load_opts_parse(args[0], true, &mode, &copts.strict);
if (oerr) return oerr;
args++; n--;
}
@@ -1113,6 +1187,10 @@ ray_t* ray_read_csv_parted_fn(ray_t** args, int64_t n) {
} else {
return ray_error("domain", "csv.parted: invalid argument arrangement");
}
+ {
+ int64_t used = names ? 3 : schema ? 2 : 1;
+ if (data_n != used) return csv_extra_args("csv.parted", args + used, data_n - used, had_opts);
+ }
if (!path_obj || path_obj->type != -RAY_STR) return ray_error("type", "csv.parted: source path must be str, got %s", path_obj ? ray_type_name(path_obj->type) : "null");
const char* path = ray_str_ptr(path_obj);
@@ -1158,10 +1236,31 @@ ray_t* ray_read_csv_parted_fn(ray_t** args, int64_t n) {
return ray_error("io", "csv.parted: %s is left from an earlier failed import; remove it to retry",
staging);
- ray_err_t err = ray_csv_save_parted_mode(path, 0, header,
- types_arg, ncols,
- names_arg, ncols,
- root, table_name, rows_per_part, mode);
+ /* A strict error may be followed by the note on retained output: the
+ * message is composed to leave it room, so cutting the cell text can
+ * never cut the note (#1885 review). */
+ char note[128];
+ {
+ char sbuf[RAY_ERR_PATH_MAX + 1];
+ /* the clipped path is at most 60 bytes; the precision says so */
+ snprintf(note, sizeof note, "; partial output retained in \"%.64s\"",
+ ray_err_path_n(staging, sbuf, 60));
+ copts.reserve = strlen(note);
+ }
+ ray_err_t err = ray_csv_save_parted_ex(path, 0, header,
+ types_arg, ncols,
+ names_arg, ncols,
+ root, table_name, rows_per_part, mode, &copts);
+ if (copts.err) {
+ struct stat st;
+ if (stat(dest, &st) != 0 && stat(staging, &st) == 0) {
+ char m[256];
+ snprintf(m, sizeof m, "%s", ray_err_msg(copts.err));
+ ray_error_free(copts.err);
+ return ray_error("parse", "%s%s", m, note);
+ }
+ return copts.err;
+ }
if (err != RAY_OK) {
struct stat st;
if (stat(dest, &st) != 0 && stat(staging, &st) == 0)
diff --git a/test/rfl/io/csv_strict.rfl b/test/rfl/io/csv_strict.rfl
new file mode 100644
index 000000000..757dd1f34
--- /dev/null
+++ b/test/rfl/io/csv_strict.rfl
@@ -0,0 +1,269 @@
+;; @requires: posix (fixtures are written through a POSIX shell via .sys.exec)
+;; .csv.read {strict: true} (#1885): a row whose cell count is not the
+;; schema's, a malformed quoted cell, or a non-empty cell that does not parse
+;; as its column's type is a `parse` error naming the file's line and the
+;; column. An empty cell is a null in both modes; the default stays lenient.
+;; Fixtures use the rf_test_csvst_ prefix (the Makefile removes rf_test_*.csv).
+
+(.sys.exec "rm -rf rf_test_csvst_* rf_test_csvst_sp rf_test_csvst_pt rf_test_csvst_pt.csv-partial rf_test_csvst_pt2") -- 0
+(set M (fn [f] (try (do (f) "no error") (fn [e] (at e 'msg)))))
+(set C (fn [f] (try (do (f) "no error") (fn [e] (at e 'code)))))
+
+;; ── the option: a leading dict, as .csv.splayed and .csv.parted take it ─────
+(.sys.exec "printf 'a,b,c\\n1,x,2.5\\n2,y\\n3,z,abc\\n' > rf_test_csvst_bad.csv") -- 0
+(M (fn [] (.csv.read {stric: true} [I64 SYM F64] "rf_test_csvst_bad.csv"))) -- "unknown option 'stric' (only strict is accepted)"
+(M (fn [] (.csv.read {compress: true} [I64 SYM F64] "rf_test_csvst_bad.csv"))) -- "unknown option 'compress' (only strict is accepted)"
+(M (fn [] (.csv.read {strict: 1} [I64 SYM F64] "rf_test_csvst_bad.csv"))) -- "strict must be true or false"
+(M (fn [] (.csv.read {strict: "yes"} "rf_test_csvst_bad.csv"))) -- "strict must be true or false"
+(M (fn [] (.csv.read {strict: true} {strict: true} "rf_test_csvst_bad.csv"))) -- ".csv.read: a second options dict"
+(C (fn [] (.csv.read {stric: true} "rf_test_csvst_bad.csv"))) -- 'domain
+
+;; ── the default and {strict: false} stay lenient ─────────────────────────────
+(set L (.csv.read [I64 SYM F64] "rf_test_csvst_bad.csv"))
+(at L 'c) -- [2.5 0Nf 0Nf]
+(identical L (.csv.read {strict: false} [I64 SYM F64] "rf_test_csvst_bad.csv")) -- true
+(identical L (.csv.read {} [I64 SYM F64] "rf_test_csvst_bad.csv")) -- true
+
+;; ── cell count, with a header: the header is line 1 ─────────────────────────
+(.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_bad.csv") !- parse
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_bad.csv"))) -- ".csv.read \"rf_test_csvst_bad.csv\": line 3: expected 3 cells, got 2"
+;; the schema inferred from the file is checked the same way
+(M (fn [] (.csv.read {strict: true} "rf_test_csvst_bad.csv"))) -- ".csv.read \"rf_test_csvst_bad.csv\": line 3: expected 3 cells, got 2"
+(.sys.exec "printf 'a,b,c\\n1,x,2.5\\n2,y,3.5,9\\n' > rf_test_csvst_more.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_more.csv"))) -- ".csv.read \"rf_test_csvst_more.csv\": line 3: expected 3 cells, got 4"
+;; a trailing delimiter is one more (empty) cell
+(.sys.exec "printf 'a,b,c\\n1,x,2.5,\\n' > rf_test_csvst_trail.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_trail.csv"))) -- ".csv.read \"rf_test_csvst_trail.csv\": line 2: expected 3 cells, got 4"
+
+;; ── a bad cell names the column, its text and the type ──────────────────────
+(.sys.exec "printf 'a,b,c\\n1,x,2.5\\n2,y,3.5\\n3,z,abc\\n' > rf_test_csvst_cell.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_cell.csv"))) -- ".csv.read \"rf_test_csvst_cell.csv\": line 4, column c: \"abc\" is not an F64"
+(at (.csv.read [I64 SYM F64] "rf_test_csvst_cell.csv") 'c) -- [2.5 3.5 0Nf]
+
+;; ── without a header (names given): line 1 is the first row ─────────────────
+(.sys.exec "printf '1,x,2.5\\n2,y,oops\\n' > rf_test_csvst_nohdr.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [a b c] [I64 SYM F64] "rf_test_csvst_nohdr.csv"))) -- ".csv.read \"rf_test_csvst_nohdr.csv\": line 2, column c: \"oops\" is not an F64"
+
+;; ── the line is the file's: a quoted newline counts, as do CRLF and lone CR ─
+(.sys.exec "printf 'a,b,c\\n1,\"two\\nlines\",2.5\\n2,y,bad\\n' > rf_test_csvst_qnl.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 STR F64] "rf_test_csvst_qnl.csv"))) -- ".csv.read \"rf_test_csvst_qnl.csv\": line 4, column c: \"bad\" is not an F64"
+(.sys.exec "printf 'a,b,c\\r\\n1,x,2.5\\r\\n2,y,\\r\\n3,z,bad\\r\\n' > rf_test_csvst_crlf.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_crlf.csv"))) -- ".csv.read \"rf_test_csvst_crlf.csv\": line 4, column c: \"bad\" is not an F64"
+;; a file with quotes splits rows at a lone CR as well
+(.sys.exec "printf 'a,b,c\\r1,\"x\",2.5\\r2,y\\r' > rf_test_csvst_cr.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_cr.csv"))) -- ".csv.read \"rf_test_csvst_cr.csv\": line 3: expected 3 cells, got 2"
+;; one without quotes splits at LF only and ends a cell at CR: lenient reads
+;; one row and drops the text after its first CR, which strict refuses
+(.sys.exec "printf 'a,b,c\\r1,x,2.5\\r2,y,3.5\\r' > rf_test_csvst_cr2.csv") -- 0
+(count (.csv.read [I64 SYM F64] "rf_test_csvst_cr2.csv")) -- 1
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_cr2.csv"))) -- ".csv.read \"rf_test_csvst_cr2.csv\": line 2: text after a CR inside the row (a row ends at LF or CRLF)"
+;; a bad cell that itself spans lines is reported at the line its row starts on
+(.sys.exec "printf 'a,b\\n\"1\\n2\",x\\n' > rf_test_csvst_qbad.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 SYM] "rf_test_csvst_qbad.csv"))) -- ".csv.read \"rf_test_csvst_qbad.csv\": line 2, column a: \"1\\n2\" is not an I64"
+
+;; ── empty cells are nulls; a CRLF file whose last cell is empty is fine ─────
+(at (.csv.read [I64 SYM F64] "rf_test_csvst_crlf.csv") 'c) -- [2.5 0Nf 0Nf]
+(.sys.exec "printf 'a,b,c\\r\\n1,x,2.5\\r\\n2,,\\r\\n,z,3.5\\r\\n' > rf_test_csvst_empty.csv") -- 0
+(set E (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_empty.csv"))
+(at E 'a) -- [1 2 0Nl]
+(at E 'c) -- [2.5 0Nf 3.5]
+(identical E (.csv.read [I64 SYM F64] "rf_test_csvst_empty.csv")) -- true
+;; a quoted empty cell is empty too
+(.sys.exec "printf 'a,b\\n\"\",x\\n' > rf_test_csvst_qempty.csv") -- 0
+(at (.csv.read {strict: true} [I64 SYM] "rf_test_csvst_qempty.csv") 'a) -- [0Nl]
+
+;; ── a final line without a newline is an ordinary row ───────────────────────
+(.sys.exec "printf 'a,b,c\\n1,x,2.5\\n2,y,3.5' > rf_test_csvst_nonl.csv") -- 0
+(at (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_nonl.csv") 'c) -- [2.5 3.5]
+(.sys.exec "printf 'a,b,c\\n1,x,2.5\\n2,y' > rf_test_csvst_nonl2.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_nonl2.csv"))) -- ".csv.read \"rf_test_csvst_nonl2.csv\": line 3: expected 3 cells, got 2"
+
+;; ── a blank line is one empty cell: refused unless the schema has one column ─
+;; (lenient reads it as a row of nulls -- a trailing blank line too)
+(.sys.exec "printf 'a,b,c\\n1,x,2.5\\n\\n2,y,3.5\\n' > rf_test_csvst_blank.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_blank.csv"))) -- ".csv.read \"rf_test_csvst_blank.csv\": line 3: expected 3 cells, got 1"
+(.sys.exec "printf 'a,b,c\\n1,x,2.5\\n\\n' > rf_test_csvst_blank2.csv") -- 0
+(count (.csv.read [I64 SYM F64] "rf_test_csvst_blank2.csv")) -- 2
+(M (fn [] (.csv.read {strict: true} [I64 SYM F64] "rf_test_csvst_blank2.csv"))) -- ".csv.read \"rf_test_csvst_blank2.csv\": line 3: expected 3 cells, got 1"
+(.sys.exec "printf 'a\\n1\\n\\n2\\n' > rf_test_csvst_one.csv") -- 0
+(at (.csv.read {strict: true} [I64] "rf_test_csvst_one.csv") 'a) -- [1 0Nl 2]
+
+;; ── whitespace around a number: lenient reads a null, so strict refuses ─────
+(.sys.exec "printf 'a,b\\n 1,2.5\\n' > rf_test_csvst_ws1.csv; printf 'a,b\\n1,2.5 \\n' > rf_test_csvst_ws2.csv; printf 'a,b\\n+1,+2.5\\n' > rf_test_csvst_ws3.csv") -- 0
+(at (.csv.read [I64 F64] "rf_test_csvst_ws1.csv") 'a) -- [0Nl]
+(M (fn [] (.csv.read {strict: true} [I64 F64] "rf_test_csvst_ws1.csv"))) -- ".csv.read \"rf_test_csvst_ws1.csv\": line 2, column a: \" 1\" is not an I64"
+(M (fn [] (.csv.read {strict: true} [I64 F64] "rf_test_csvst_ws2.csv"))) -- ".csv.read \"rf_test_csvst_ws2.csv\": line 2, column b: \"2.5 \" is not an F64"
+(at (.csv.read {strict: true} [I64 F64] "rf_test_csvst_ws3.csv") 'b) -- [2.5]
+;; text keeps its spaces in either mode
+(at (.csv.read {strict: true} [STR STR] "rf_test_csvst_ws1.csv") 'a) -- (list " 1")
+
+;; ── malformed quotes ────────────────────────────────────────────────────────
+(.sys.exec "printf 'a,b\\n\"ab\"cd,1\\n' > rf_test_csvst_q1.csv; printf 'a,b\\n1,\"ab\\n' > rf_test_csvst_q2.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [STR I64] "rf_test_csvst_q1.csv"))) -- ".csv.read \"rf_test_csvst_q1.csv\": line 2, column a: text after the closing quote"
+(M (fn [] (.csv.read {strict: true} [I64 STR] "rf_test_csvst_q2.csv"))) -- ".csv.read \"rf_test_csvst_q2.csv\": line 2, column b: a quoted cell with no closing quote"
+;; quoted cells with delimiters, escaped quotes and newlines are well formed
+(.sys.exec "printf 'a,b\\n\"x,y\",\"say \"\"hi\"\"\"\\n\"p\\nq\",\"\"\\n' > rf_test_csvst_q3.csv") -- 0
+(at (.csv.read {strict: true} [STR STR] "rf_test_csvst_q3.csv") 'b) -- (list "say \"hi\"" "")
+
+;; ── long cell text is cut at a character boundary ───────────────────────────
+(.sys.exec "printf 'a,b\\n1,' > rf_test_csvst_long.csv; i=0; while [ $i -lt 60 ]; do printf '\\303\\251' >> rf_test_csvst_long.csv; i=$((i+1)); done; printf '\\n' >> rf_test_csvst_long.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 I64] "rf_test_csvst_long.csv"))) -- ".csv.read \"rf_test_csvst_long.csv\": line 2, column b: \"éééééééééééééééééééé...\" is not an I64"
+;; control bytes in the cell are escaped in the message
+(.sys.exec "printf 'a,b\\n1,x\\ty\\n' > rf_test_csvst_tab.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 I64] "rf_test_csvst_tab.csv"))) -- ".csv.read \"rf_test_csvst_tab.csv\": line 2, column b: \"x\\ty\" is not an I64"
+
+;; ── every column type: strict reads a valid file exactly as lenient does ────
+(.sys.exec "printf 'b,u,h,i,j,e,f,d,t,s,p,y,r,g\\ntrue,1,1,1,1,1.5,1.5,2024.01.02,10:00:00.000,0D00:00:01,2024.01.02D10:00:00.000000000,a,x,0a0b0c0d-0102-0304-0506-0708090a0b0c\\n,,,,,,,,,,,,,\\nFALSE,255,-7,-70000,9000000000,-2e3,3.25e-2,2024-03-04,23:59:59,1D02:03:04.5,2024-03-04T01:02:03,\"q,r\",\"multi\\nline\",0A0B0C0D-0102-0304-0506-0708090A0B0C\\n' > rf_test_csvst_types.csv") -- 0
+(set TS [B8 U8 I16 I32 I64 F32 F64 DATE TIME TIMESPAN TIMESTAMP SYM STR GUID])
+(set TL (.csv.read TS "rf_test_csvst_types.csv"))
+(identical TL (.csv.read {strict: true} TS "rf_test_csvst_types.csv")) -- true
+(identical (.csv.read "rf_test_csvst_types.csv") (.csv.read {strict: true} "rf_test_csvst_types.csv")) -- true
+;; what .csv.write writes, nulls included, reads back under strict
+(.csv.write TL "rf_test_csvst_rt.csv")
+(identical TL (.csv.read {strict: true} TS "rf_test_csvst_rt.csv")) -- true
+
+;; ── every column type: a non-empty cell lenient cannot read is refused ──────
+(set B (fn [t v] (.sys.exec (format "printf 'k,v\\n1,%\\n' > rf_test_csvst_t.csv" v)) (M (fn [] (.csv.read {strict: true} (concat [I64] t) "rf_test_csvst_t.csv")))))
+(B [B8] "yes") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"yes\" is not a B8"
+(B [U8] "x1") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"x1\" is not a U8"
+(B [I16] "1.5") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"1.5\" is not an I16"
+(B [I32] "abc") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"abc\" is not an I32"
+(B [I64] "1e3") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"1e3\" is not an I64"
+(B [F32] "1.2.3") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"1.2.3\" is not an F32"
+(B [F64] "nan") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"nan\" is not an F64"
+(B [DATE] "2024-13-45") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"2024-13-45\" is not a DATE"
+(B [TIME] "25:99") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"25:99\" is not a TIME"
+(B [TIMESPAN] "1") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"1\" is not a TIMESPAN"
+(B [TIMESTAMP] "noon") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"noon\" is not a TIMESTAMP"
+(B [GUID] "0a0b") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"0a0b\" is not a GUID"
+(B [SYM] "anything") -- "no error"
+(B [STR] "anything") -- "no error"
+
+;; ── a number out of its column's range: lenient wraps it, keeps the null
+;; sentinel or makes an infinity; strict refuses it, at every width ────────
+(.sys.exec "printf 'u,h,i,e\\n300,40000,3000000000,1e39\\n' > rf_test_csvst_wrap.csv") -- 0
+(set W (.csv.read [U8 I16 I32 F32] "rf_test_csvst_wrap.csv"))
+(at W 'u) -- [0x2c]
+(at W 'h) -- [-25536]
+(at W 'i) -- [-1294967296]
+(set R (fn [t v] (.sys.exec (format "printf 'k,v\\n1,%\\n' > rf_test_csvst_t.csv" v)) (M (fn [] (.csv.read {strict: true} (concat [I64] t) "rf_test_csvst_t.csv")))))
+(R [U8] "300") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"300\" is out of range for a U8"
+(R [U8] "-1") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"-1\" is out of range for a U8"
+(R [U8] "99999999999999999999") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"99999999999999999999\" is out of range for a U8"
+(R [U8] "255") -- "no error"
+(R [U8] "0") -- "no error"
+(R [I16] "40000") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"40000\" is out of range for an I16"
+(R [I16] "-32769") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"-32769\" is out of range for an I16"
+;; the type's minimum is its null sentinel, so it is not a value either
+(R [I16] "-32768") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"-32768\" reads as a null I16"
+(R [I16] "-32767") -- "no error"
+(R [I16] "32767") -- "no error"
+(R [I32] "3000000000") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"3000000000\" is out of range for an I32"
+(R [I32] "-2147483648") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"-2147483648\" reads as a null I32"
+(R [I32] "2147483647") -- "no error"
+(R [I64] "9223372036854775808") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"9223372036854775808\" is out of range for an I64"
+(R [I64] "-9223372036854775808") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"-9223372036854775808\" reads as a null I64"
+(R [I64] "-9223372036854775807") -- "no error"
+(R [I64] "9223372036854775807") -- "no error"
+;; a float too big for its type is an infinity, which is a null (#1828)
+(R [F32] "1e39") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"1e39\" is out of range for an F32"
+(R [F32] "-1e39") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"-1e39\" is out of range for an F32"
+(R [F32] "3.4e38") -- "no error"
+(R [F64] "1e400") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"1e400\" is out of range for an F64"
+(R [F64] "1.7e308") -- "no error"
+(R [F64] "inf") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"inf\" is not an F64"
+;; the parallel reader refuses one too
+(.sys.exec "awk 'BEGIN{print \"a,b\"; for(i=1;i<=20000;i++) printf \"%d,%d\\n\", i, (i==15000 ? 70000 : i%30000) }' > rf_test_csvst_wbig.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 I16] "rf_test_csvst_wbig.csv"))) -- ".csv.read \"rf_test_csvst_wbig.csv\": line 15001, column b: \"70000\" is out of range for an I16"
+
+;; ── the parallel parse: the first bad line of the file, whatever the split ──
+;; 100000 rows (past the 8192-row serial cutoff), a quoted newline in row 10,
+;; a short row at 30000 and a bad cell at 20000 and 90000: line 20002 wins.
+(.sys.exec "awk 'BEGIN{print \"a,b,c\"; for(i=1;i<=100000;i++){ if(i==10) printf \"%d,\\\"two\\nlines\\\",1.5\\n\", i; else if(i==20000||i==90000) printf \"%d,x,zz\\n\", i; else if(i==30000) printf \"%d,x\\n\", i; else printf \"%d,s%d,%d.5\\n\", i, i%7, i } }' > rf_test_csvst_big.csv") -- 0
+(count (.csv.read [I64 STR F64] "rf_test_csvst_big.csv")) -- 100000
+(M (fn [] (.csv.read {strict: true} [I64 STR F64] "rf_test_csvst_big.csv"))) -- ".csv.read \"rf_test_csvst_big.csv\": line 20002, column c: \"zz\" is not an F64"
+(.sys.exec "sed 's/^20000,x,zz$/20000,x,1/' rf_test_csvst_big.csv > rf_test_csvst_big.tmp && mv rf_test_csvst_big.tmp rf_test_csvst_big.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64 STR F64] "rf_test_csvst_big.csv"))) -- ".csv.read \"rf_test_csvst_big.csv\": line 30002: expected 3 cells, got 2"
+
+;; ── .csv.splayed and .csv.parted share the reader, and the option ──────────
+(M (fn [] (.csv.splayed {strict: true} [I64 STR F64] "rf_test_csvst_big.csv" "rf_test_csvst_sp"))) -- ".csv.splayed \"rf_test_csvst_big.csv\": line 30002: expected 3 cells, got 2"
+(M (fn [] (.csv.splayed {strict: true compress: false} [I64 SYM F64] "rf_test_csvst_cell.csv" "rf_test_csvst_sp"))) -- ".csv.splayed \"rf_test_csvst_cell.csv\": line 4, column c: \"abc\" is not an F64"
+(M (fn [] (.csv.splayed {strict: 1} [I64 SYM F64] "rf_test_csvst_cell.csv" "rf_test_csvst_sp"))) -- "strict must be true or false"
+(M (fn [] (.csv.splayed {strictly: true} [I64 SYM F64] "rf_test_csvst_cell.csv" "rf_test_csvst_sp"))) -- "unknown option 'strictly' (only compress and strict are accepted)"
+(count (.csv.splayed {strict: true} [I64 SYM F64] "rf_test_csvst_empty.csv" "rf_test_csvst_sp")) -- 3
+;; a later partition's bad line, after earlier partitions were written
+(M (fn [] (.csv.parted {strict: true} [I64 STR F64] "rf_test_csvst_big.csv" 10000 "rf_test_csvst_pt" 't))) -- ".csv.parted \"rf_test_csvst_big.csv\": line 30002: expected 3 cells, got 2; partial output retained in \"rf_test_csvst_pt.csv-partial\""
+(.sys.exec "rm -rf rf_test_csvst_pt.csv-partial") -- 0
+(count (.csv.parted {strict: true compress: true} [I64 SYM F64] "rf_test_csvst_empty.csv" 2 "rf_test_csvst_pt2" 't)) -- 3
+
+;; ── review round 1 (#1885) ────────────────────────────────────────────────
+;; a value the type stores as its null, or past its range, is refused for the
+;; temporal types and GUID too; the default reads them as before
+(.sys.exec "printf 'v\\n-596:31:23.648\\n' > rf_test_csvst_r1.csv; printf 'v\\n00000000-0000-0000-0000-000000000000\\n' > rf_test_csvst_r2.csv; printf 'v\\n9999-01-01T00:00:00\\n' > rf_test_csvst_r3.csv; printf 'v\\n106752D00:00:00\\n' > rf_test_csvst_r4.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [TIME] "rf_test_csvst_r1.csv"))) -- ".csv.read \"rf_test_csvst_r1.csv\": line 2, column v: \"-596:31:23.648\" reads as a null TIME"
+(M (fn [] (.csv.read {strict: true} [GUID] "rf_test_csvst_r2.csv"))) -- ".csv.read \"rf_test_csvst_r2.csv\": line 2, column v: \"00000000-0000-0000-0000-000000000000\" reads as a null GUID"
+(M (fn [] (.csv.read {strict: true} [TIMESTAMP] "rf_test_csvst_r3.csv"))) -- ".csv.read \"rf_test_csvst_r3.csv\": line 2, column v: \"9999-01-01T00:00:00\" is out of range for a TIMESTAMP"
+(M (fn [] (.csv.read {strict: true} [TIMESPAN] "rf_test_csvst_r4.csv"))) -- ".csv.read \"rf_test_csvst_r4.csv\": line 2, column v: \"106752D00:00:00\" is out of range for a TIMESPAN"
+(M (fn [] (.csv.splayed {strict: true} [TIMESTAMP] "rf_test_csvst_r3.csv" "rf_test_csvst_sp"))) -- ".csv.splayed \"rf_test_csvst_r3.csv\": line 2, column v: \"9999-01-01T00:00:00\" is out of range for a TIMESTAMP"
+(M (fn [] (.csv.parted {strict: true} [TIMESPAN] "rf_test_csvst_r4.csv" "rf_test_csvst_pt" 't))) -- ".csv.parted \"rf_test_csvst_r4.csv\": line 2, column v: \"106752D00:00:00\" is out of range for a TIMESPAN"
+;; the extremes that do fit
+(.sys.exec "printf 'p,n\\n2292-04-10T23:47:16.854775807,106751D23:47:16.854775806\\n1707-09-22T00:12:43.145224193,0Wn\\n' > rf_test_csvst_r5.csv") -- 0
+(count (.csv.read {strict: true} [TIMESTAMP TIMESPAN] "rf_test_csvst_r5.csv")) -- 2
+
+;; the first row is checked as any row is, without a header ...
+(.sys.exec "printf '1\\n2,3\\n' > rf_test_csvst_h1.csv; printf '1,2,3\\n2,3\\n' > rf_test_csvst_h2.csv; printf '\\n2,3\\n' > rf_test_csvst_h3.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [a b] [I64 I64] "rf_test_csvst_h1.csv"))) -- ".csv.read \"rf_test_csvst_h1.csv\": line 1: expected 2 cells, got 1"
+(M (fn [] (.csv.read {strict: true} [a b] [I64 I64] "rf_test_csvst_h2.csv"))) -- ".csv.read \"rf_test_csvst_h2.csv\": line 1: expected 2 cells, got 3"
+(M (fn [] (.csv.read {strict: true} [a b] [I64 I64] "rf_test_csvst_h3.csv"))) -- ".csv.read \"rf_test_csvst_h3.csv\": line 1: expected 2 cells, got 1"
+(M (fn [] (.csv.splayed {strict: true} [a b] [I64 I64] "rf_test_csvst_h1.csv" "rf_test_csvst_sp"))) -- ".csv.splayed \"rf_test_csvst_h1.csv\": line 1: expected 2 cells, got 1"
+(M (fn [] (.csv.parted {strict: true} [a b] [I64 I64] "rf_test_csvst_h1.csv" "rf_test_csvst_pt" 't))) -- ".csv.parted \"rf_test_csvst_h1.csv\": line 1: expected 2 cells, got 1"
+;; (the default still sizes the table from the first line)
+(C (fn [] (.csv.read [a b] [I64 I64] "rf_test_csvst_h1.csv"))) -- 'length
+;; ... and a header's quoted cells must be well formed
+(.sys.exec "printf '\"v\\n1\\n' > rf_test_csvst_h4.csv; printf '\"v\"junk\\n1\\n' > rf_test_csvst_h5.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [STR] "rf_test_csvst_h4.csv"))) -- ".csv.read \"rf_test_csvst_h4.csv\": line 1: header cell 1: a quoted cell with no closing quote"
+(M (fn [] (.csv.read {strict: true} [STR] "rf_test_csvst_h5.csv"))) -- ".csv.read \"rf_test_csvst_h5.csv\": line 1: header cell 1: text after the closing quote"
+(M (fn [] (.csv.splayed {strict: true} [STR] "rf_test_csvst_h5.csv" "rf_test_csvst_sp"))) -- ".csv.splayed \"rf_test_csvst_h5.csv\": line 1: header cell 1: text after the closing quote"
+(M (fn [] (.csv.parted {strict: true} [STR] "rf_test_csvst_h4.csv" "rf_test_csvst_pt" 't))) -- ".csv.parted \"rf_test_csvst_h4.csv\": line 1: header cell 1: a quoted cell with no closing quote"
+
+;; every argument is consumed by the arrangement: a later dict is an error
+(.sys.exec "printf 'v\\n1\\n' > rf_test_csvst_ok.csv") -- 0
+(M (fn [] (.csv.read {strict: true} [I64] "rf_test_csvst_ok.csv" {strict: false}))) -- ".csv.read: a second options dict"
+(M (fn [] (.csv.read [I64] "rf_test_csvst_ok.csv" {strict: true}))) -- ".csv.read: the options dict must be the first argument"
+(M (fn [] (.csv.read [I64] "rf_test_csvst_ok.csv" 42))) -- ".csv.read: 1 argument past its schema and path"
+(C (fn [] (.csv.read [I64] "rf_test_csvst_ok.csv" 42))) -- 'arity
+(M (fn [] (.csv.splayed {strict: true} [I64] "rf_test_csvst_ok.csv" {strict: false} "rf_test_csvst_sp"))) -- "csv.splayed: a second options dict"
+(M (fn [] (.csv.parted {strict: true} [I64] "rf_test_csvst_ok.csv" {x: 1} "rf_test_csvst_pt" 't))) -- "csv.parted: a second options dict"
+
+;; a message that would pass 255 bytes is cut in the cell text only, on whole
+;; characters and escapes, and keeps the parted note whole
+(set LD "rf_test_csvst_dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
+(.sys.exec (format "mkdir -p % && printf 'a,b\\n1,2\\n3,' > %/c.csv && i=0; while [ $i -lt 60 ]; do printf '\\001' >> %/c.csv; i=$((i+1)); done; printf '\\n' >> %/c.csv" LD LD LD LD)) -- 0
+(set E1 (M (fn [] (.csv.read {strict: true} [I64 I64] (format "%/c.csv" LD)))))
+(count E1) -- 255
+(last (split E1 "\\x01")) -- "...\" is not an I64"
+(.sys.exec (format "rm -rf %/rt %/rt.csv-partial" LD LD)) -- 0
+(set E2 (M (fn [] (.csv.parted {strict: true} [I64 I64] (format "%/c.csv" LD) 1 (format "%/rt" LD) 't))))
+(count (split E2 "...\" is not an I64; partial output retained in \"")) -- 2
+(last (split E2 "/")) -- "rt.csv-partial\""
+(<= (count E2) 255) -- true
+
+;; ── review round 2 (#1885): a non-zero float that stores as zero ──────────
+;; rounding, to a subnormal too, is kept; a total loss to zero is refused
+(R [F64] "1e-400") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"1e-400\" underflows to zero for an F64"
+(R [F64] "2e-324") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"2e-324\" underflows to zero for an F64"
+(R [F64] "-2e-324") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"-2e-324\" underflows to zero for an F64"
+(R [F32] "1e-50") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"1e-50\" underflows to zero for an F32"
+(R [F32] "-1e-46") -- ".csv.read \"rf_test_csvst_t.csv\": line 2, column v: \"-1e-46\" underflows to zero for an F32"
+(R [F64] "5e-324") -- "no error"
+(R [F64] "1e-310") -- "no error"
+(R [F32] "1e-45") -- "no error"
+(R [F32] "1e-40") -- "no error"
+(R [F64] "0") -- "no error"
+(R [F64] "-0.0e-400") -- "no error"
+(R [F32] "0.000e-50") -- "no error"
+;; the default stores zero
+(.sys.exec "printf 'v\\n1e-400\\n' > rf_test_csvst_uf.csv") -- 0
+(at (.csv.read [F64] "rf_test_csvst_uf.csv") 'v) -- [0.0]
+
+(.sys.exec "rm -rf rf_test_csvst_* rf_test_csvst_sp rf_test_csvst_pt rf_test_csvst_pt.csv-partial rf_test_csvst_pt2") -- 0
diff --git a/test/test_csv.c b/test/test_csv.c
index 948d4bba2..67944312e 100644
--- a/test/test_csv.c
+++ b/test/test_csv.c
@@ -2469,6 +2469,150 @@ static test_result_t test_csv_splayed_cancel_symfile(void) {
PASS();
}
+/* Strict mode (#1885): every rule, for every column type, on the first row,
+ * a middle row and the last one, in a file the serial parse reads and one
+ * the parallel parse reads, with a header and without. Each case swaps one
+ * line of a valid file for a bad one and expects the error to name its line
+ * and say why; the valid file itself must read. */
+typedef struct {
+ int8_t type;
+ const char* good;
+ const char* not_type; /* text that is not the type; NULL: any text is */
+ const char* range; /* a value past the type's range, or NULL */
+ const char* nullv; /* text that reads as the type's null, or NULL */
+ const char* precision; /* digits past the type's precision, or NULL */
+ const char* underflow; /* a non-zero text that stores as zero, and */
+ const char* underflow_neg; /* its negative, or NULL */
+} csv_strict_case_t;
+
+static const csv_strict_case_t csv_strict_cases[] = {
+ { RAY_BOOL, "true", "yes", NULL, NULL, NULL, NULL, NULL },
+ { RAY_U8, "7", "x", "300", NULL, NULL, NULL, NULL },
+ { RAY_I16, "7", "x", "40000", "-32768", NULL, NULL, NULL },
+ { RAY_I32, "7", "x", "3000000000", "-2147483648", NULL, NULL, NULL },
+ { RAY_I64, "7", "x", "9223372036854775808", "-9223372036854775808", NULL, NULL, NULL },
+ { RAY_F32, "1.5", "x", "1e39", NULL, NULL, "1e-50", "-1e-46" },
+ { RAY_F64, "1.5", "x", "1e400", NULL, NULL, "1e-400", "-2e-324" },
+ { RAY_DATE, "2024-01-02", "2024-13-01", NULL, NULL, NULL, NULL, NULL },
+ { RAY_TIME, "10:00:00", "10:99:00", NULL, "-596:31:23.648", "10:00:00.1234", NULL, NULL },
+ { RAY_TIMESPAN, "0D00:00:01", "1", "106752D00:00:00", "0Nn", "0D00:00:01.1234567891", NULL, NULL },
+ { RAY_TIMESTAMP, "2024-01-02T10:00:00", "noon", "9999-01-01T00:00:00",
+ "1707-09-22T00:12:43.145224192", "2024-01-02T10:00:00.1234567891", NULL, NULL },
+ { RAY_SYM, "s", NULL, NULL, NULL, NULL, NULL, NULL },
+ { RAY_STR, "s", NULL, NULL, NULL, NULL, NULL, NULL },
+ { RAY_GUID, "0a0b0c0d-0102-0304-0506-0708090a0b0c", "0a0b", NULL,
+ "00000000-0000-0000-0000-000000000000", NULL, NULL, NULL },
+};
+
+/* Write `rows` rows "," (after a "k,v" header when `header`), with
+ * row `bad_row` replaced by `bad` (no replacement when bad is NULL). */
+static bool csv_strict_write(const char* path, bool header, int rows,
+ const char* good, int bad_row, const char* bad) {
+ FILE* f = fopen(path, "wb");
+ if (!f) return false;
+ if (header) fputs("k,v\n", f);
+ for (int i = 0; i < rows; i++) {
+ if (bad && i == bad_row) fprintf(f, "%s\n", bad);
+ else fprintf(f, "%d,%s\n", i, good);
+ }
+ return fclose(f) == 0;
+}
+
+static test_result_t test_csv_strict_matrix(void) {
+ ray_heap_init();
+ (void)ray_sym_init();
+ const char* path = TMP_CSV;
+ int64_t names[2] = { ray_sym_intern("k", 1), ray_sym_intern("v", 1) };
+ static const int sizes[2] = { 10, 8300 }; /* serial; parallel (> 8192 rows) */
+ char bad[160], want[256], err[512];
+ int checked = 0;
+ for (size_t t = 0; t < sizeof csv_strict_cases / sizeof csv_strict_cases[0]; t++) {
+ const csv_strict_case_t* tc = &csv_strict_cases[t];
+ int8_t types[2] = { RAY_I64, tc->type };
+ for (int hdr = 0; hdr < 2; hdr++) {
+ for (int z = 0; z < 2; z++) {
+ int rows = sizes[z];
+ ray_csv_opts_t opts = { .strict = true, .op = ".csv.read" };
+ /* the valid file reads */
+ TEST_ASSERT_TRUE(csv_strict_write(path, hdr, rows, tc->good, -1, NULL));
+ ray_t* ok = ray_read_csv_ex(path, ',', hdr, types, 2, hdr ? NULL : names, hdr ? 0 : 2, &opts);
+ if (!ok || RAY_IS_ERR(ok)) {
+ snprintf(err, sizeof err, "type %d %s %d rows: the valid file fails: %s",
+ tc->type, hdr ? "header" : "headerless", rows,
+ ok ? ray_err_msg(ok) : "NULL");
+ ray_error_free(ok);
+ FAIL(strdup(err));
+ }
+ TEST_ASSERT_EQ_I(ray_table_nrows(ok), rows);
+ ray_release(ok);
+ /* each rule at each place */
+ for (int rule = 0; rule < 11; rule++) {
+ const char* why = NULL;
+ switch (rule) {
+ case 0: if (!tc->not_type) continue;
+ snprintf(bad, sizeof bad, "%%d,%s", tc->not_type);
+ snprintf(want, sizeof want, "column v: \"%s\" is not ", tc->not_type); break;
+ case 1: if (!tc->range) continue;
+ snprintf(bad, sizeof bad, "%%d,%s", tc->range);
+ snprintf(want, sizeof want, "column v: \"%s\" is out of range for ", tc->range); break;
+ case 2: if (!tc->nullv) continue;
+ snprintf(bad, sizeof bad, "%%d,%s", tc->nullv);
+ snprintf(want, sizeof want, "column v: \"%s\" reads as a null ", tc->nullv); break;
+ case 3: if (!tc->precision) continue;
+ snprintf(bad, sizeof bad, "%%d,%s", tc->precision);
+ snprintf(want, sizeof want, "column v: \"%s\" has more fraction digits", tc->precision); break;
+ case 4: snprintf(bad, sizeof bad, "%%d");
+ why = ": expected 2 cells, got 1"; break;
+ case 5: snprintf(bad, sizeof bad, "%%d,%s,9", tc->good);
+ why = ": expected 2 cells, got 3"; break;
+ case 6: snprintf(bad, sizeof bad, "%%d,\"%s\"x", tc->good);
+ why = ", column v: text after the closing quote"; break;
+ case 7: snprintf(bad, sizeof bad, "%%d,\"%s", tc->good);
+ why = ", column v: a quoted cell with no closing quote"; break;
+ case 8: snprintf(bad, sizeof bad, "%%d,%s\rjunk", tc->good);
+ why = ": text after a CR inside the row"; break;
+ case 9: case 10: {
+ const char* u = rule == 9 ? tc->underflow : tc->underflow_neg;
+ if (!u) continue;
+ snprintf(bad, sizeof bad, "%%d,%s", u);
+ snprintf(want, sizeof want, "column v: \"%s\" underflows to zero for ", u); break;
+ }
+ }
+ if (why) snprintf(want, sizeof want, "%s", why + (why[0] == ',' ? 2 : 0));
+ int places[3] = { 0, rows / 2, rows - 1 };
+ for (int pl = 0; pl < 3; pl++) {
+ int r = places[pl];
+ char line[200];
+ snprintf(line, sizeof line, bad, r);
+ TEST_ASSERT_TRUE(csv_strict_write(path, hdr, rows, tc->good, r, line));
+ ray_t* res = ray_read_csv_ex(path, ',', hdr, types, 2,
+ hdr ? NULL : names, hdr ? 0 : 2, &opts);
+ char head[128];
+ snprintf(head, sizeof head, ".csv.read \"%s\": line %d", path, r + 1 + hdr);
+ const char* msg = res && RAY_IS_ERR(res) ? ray_err_msg(res) : NULL;
+ bool good = msg && strcmp(ray_err_code(res), "parse") == 0 &&
+ strncmp(msg, head, strlen(head)) == 0 && strstr(msg, want);
+ if (!good) {
+ snprintf(err, sizeof err, "type %d %s %d rows, rule %d at row %d: got %s; want \"%s\" ... \"%s\"",
+ tc->type, hdr ? "header" : "headerless", rows, rule, r,
+ msg ? msg : "no error", head, want);
+ if (res && RAY_IS_ERR(res)) ray_error_free(res); else if (res) ray_release(res);
+ FAIL(strdup(err));
+ }
+ ray_error_free(res);
+ checked++;
+ }
+ }
+ }
+ }
+ }
+ unlink(path);
+ ray_sym_destroy();
+ ray_heap_destroy();
+ TEST_ASSERT_EQ_I(checked, 1248);
+ PASS();
+}
+
const test_entry_t csv_entries[] = {
{ "csv/splayed_cancel", test_csv_splayed_cancel, NULL, NULL },
{ "csv/splayed_cancel_hash", test_csv_splayed_cancel_hash, NULL, NULL },
@@ -2536,5 +2680,6 @@ const test_entry_t csv_entries[] = {
{ "csv/scan_boundary_matrix", test_csv_scan_boundary_matrix, NULL, NULL },
{ "csv/sym_id_order", test_csv_sym_id_order, NULL, NULL },
{ "csv/streaming_infers_like_read", test_csv_streaming_infers_like_read, NULL, NULL },
+ { "csv/strict_matrix", test_csv_strict_matrix, NULL, NULL },
{ NULL, NULL, NULL, NULL },
};