From 480cd132df4475496a6e40f3dabf469142435f01 Mon Sep 17 00:00:00 2001 From: Slava Date: Fri, 27 Nov 2026 10:00:06 +0100 Subject: [PATCH 1/4] feat: add CsvCursorOptions.QuoteMode --- .../plans/2026-11-27-csv-strict-quotes.md | 77 +++++++++++++++++++ .../2026-11-27-csv-strict-quotes-design.md | 60 +++++++++++++++ src/TriasDev.Tabular/Csv/CsvCursorOptions.cs | 21 +++++ src/TriasDev.Tabular/Csv/CsvQuoteMode.cs | 34 ++++++++ src/TriasDev.Tabular/PublicAPI.Unshipped.txt | 5 ++ .../OptionDefaultsTests.cs | 1 + .../OptionsValidationTests.cs | 1 + 7 files changed, 199 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-27-csv-strict-quotes.md create mode 100644 docs/superpowers/specs/2026-11-27-csv-strict-quotes-design.md create mode 100644 src/TriasDev.Tabular/Csv/CsvQuoteMode.cs diff --git a/docs/superpowers/plans/2026-11-27-csv-strict-quotes.md b/docs/superpowers/plans/2026-11-27-csv-strict-quotes.md new file mode 100644 index 0000000..8060212 --- /dev/null +++ b/docs/superpowers/plans/2026-11-27-csv-strict-quotes.md @@ -0,0 +1,77 @@ +# Csv strict quotes Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** `CsvCursorOptions.QuoteMode = CsvQuoteMode.Strict` reads quotes as RFC 4180 does and refuses quoting it would otherwise repair (#198). + +**Architecture:** One enum and one option; `CsvCursor.ReadRowCore` reads a `strict` local once per row and skips every replay path under it, refusing instead where the repair mode would repair. Default mode untouched and measured. + +**Tech Stack:** C# / net10.0 (tests net10.0 + net11.0), xUnit v3 on MTP. + +**Spec:** `docs/superpowers/specs/2026-11-27-csv-strict-quotes-design.md` + +## Global Constraints + +- `CsvQuoteMode { Repair = 0, Strict = 1 }`, public, namespace `TriasDev.Tabular`; default `Repair`. +- Refusals: `TabularFormatException(TabularFormatException.Corrupt, …)`, message names the row (`CurrentRowNumber + 1`). +- Strict whitespace = `' '`, and `'\t'` unless tab is the delimiter. +- Default (`Repair`) behaviour unchanged; read speed of the default path not worse than `main` (min-of-N). +- No product names in code, docs or commits. + +## Review Focus + +- The issue's own Excel export (five columns, comma-laden note across a line) → two records, clean. (Task 2) +- `""` escaped quote directly before the closing quote and before EOF: `"a"""` → `a"`. (Task 2) +- Closing quote, spaces, then `\r\n` / lone `\r` / EOF → closes. (Task 2) +- Tab delimiter: `a\t "b"` — the tab is the delimiter, the space is whitespace → `b`. (Task 2) +- A custom `Quote = '\''` honours strict rules the same way. (Task 2) + +--- + +### Task 1: The option + +**Files:** +- Create: `src/TriasDev.Tabular/Csv/CsvQuoteMode.cs` +- Modify: `src/TriasDev.Tabular/Csv/CsvCursorOptions.cs` (property + `Checked()`), `src/TriasDev.Tabular/PublicAPI.Unshipped.txt` +- Test: `tests/TriasDev.Tabular.Tests/OptionDefaultsTests.cs`, `tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs` + +**Interfaces:** +- Produces: `public enum CsvQuoteMode { Repair = 0, Strict = 1 }`; `public CsvQuoteMode CsvCursorOptions.QuoteMode { get; init; }` (default `Repair`). + +- [ ] Step 1: tests — `Assert.Equal(CsvQuoteMode.Repair, csv.QuoteMode)` in the defaults test; `new CsvCursorOptions { QuoteMode = (CsvQuoteMode)7 }` refused with `ArgumentOutOfRangeException` when a cursor opens, in the validation test's style. +- [ ] Step 2: run, expect compile failure. +- [ ] Step 3: implement; `Checked()` uses `Enum.IsDefined` as `OdsWriterOptions` does; XML docs say what each mode repairs or refuses. +- [ ] Step 4: `dotnet test --project tests/TriasDev.Tabular.Tests --filter "FullyQualifiedName~Option"` passes; build has no RS0016. +- [ ] Step 5: commit `feat: add CsvCursorOptions.QuoteMode`. + +### Task 2: Strict reading in the cursor + +**Files:** +- Modify: `src/TriasDev.Tabular/Csv/CsvCursor.cs` (`ReadRowCore`, the quoted-run fast path) +- Test: create `tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs` + +**Interfaces:** +- Consumes: `CsvCursorOptions.QuoteMode`, `CsvQuoteMode.Strict`. + +- [ ] Step 1: tests (helper reads with `new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict }`, plus `Delimiter`/`Quote` where named): + - `ReadsAnExcelCellWithALineBreakAndCommasAsOneValue` — the issue's sample: 3 rows incl. header; row 1 = `1 | Payroll | Monthly salary run.\nUses names, addresses, bank accounts, tax ids, and social security numbers. | HR | People`; `IsClean`. + - `KeepsAQuotedFieldOfMoreThanTheLineBoundAsOneValue` — 150 line breaks in one field, `MaxQuotedFieldLines` 100 → one value with 150 `\n`; clean. + - `RefusesAQuoteTheInputEndsInside` — `a,b\n1,"open\nmore` → `TabularFormatException`, `Code == Corrupt`, message contains `row 2`; a further `ReadRow` throws `InvalidOperationException`. + - `RefusesTextAfterAClosingQuote` — `"C" Road,x` and multi-line `"a\n135"th",x` → `Corrupt`. + - `IgnoresWhitespaceAroundAQuotedField` — `ID, Name, Note\r\n1, "Payroll", "monthly, HR" \r\n` → `1 | Payroll | monthly, HR`. + - `KeepsAQuoteInsideAnUnquotedField` — `21"st AVE,x` → `21"st AVE`. + - Review Focus cases: `"a"""` at EOF → `a"`; `"a" \r` lone CR and `"a" ` at EOF; tab delimiter `a\t "b"` → `b`; `Quote = '\''`: `'x, y' ,z` → `x, y | z` and `'C' Road` refused. + - `RepairModeIsUnchanged` — the issue's sample without options still splits (`RecoveredStrayQuotes > 0`), pinning that the default did not move. +- [ ] Step 2: run, expect failures. +- [ ] Step 3: implement. `bool strict = _options.QuoteMode == CsvQuoteMode.Strict` at the top of `ReadRowCore`. Under `strict`: no `_quotedRaw` appends (fast path and per char), no line counting/bound, no delimiter-count replay, no `135"th` rule; EOF in quotes throws; a quote with `!atFieldStart` opens a quoted field when the field so far (pending run or `_field`) is only strict whitespace, discarding it; on a closing quote, consume strict whitespace via `PeekChar`/`ReadChar`, then anything but delimiter, `\r`, `\n`, EOF throws. Refusals through one `[NoInlining]` helper returning the exception. +- [ ] Step 4: whole test project passes on both targets. +- [ ] Step 5: fuzz round trip: in the csv writer fuzz (`Fuzz/`), also read every written file with `Strict` and assert the same rows — the writer's output is RFC 4180. Run passes. +- [ ] Step 6: measure the default path, `main` vs branch, alternating, min-of-N, on the 5M csv (memory: final perf check always includes it); report time and allocations. +- [ ] Step 7: commit `feat: read csv quotes strictly when asked (#198)`. + +### Task 3: Docs + +**Files:** `docs/formats.md` (repair section: a paragraph on strict mode), `docs/bounds.md` (quoted-field line: not applied in strict), `docs/error-codes.md` (`format.corrupt` covers strict csv quoting), `docs/KNOWN-ISSUES.md` (the stray-quote and `"C" Road` entries point at strict mode), remarks on `CsvCursorOptions.MaxQuotedFieldLines` and `CursorDiagnostics`. + +- [ ] Step 1: edit; `dotnet build` (doc comments) clean. +- [ ] Step 2: commit `docs: describe strict csv quoting`. diff --git a/docs/superpowers/specs/2026-11-27-csv-strict-quotes-design.md b/docs/superpowers/specs/2026-11-27-csv-strict-quotes-design.md new file mode 100644 index 0000000..493d754 --- /dev/null +++ b/docs/superpowers/specs/2026-11-27-csv-strict-quotes-design.md @@ -0,0 +1,60 @@ +# Csv: reading quotes strictly (#198) — design + +## Why + +The csv reader repairs malformed quoting, and one of its repairs splits valid csv: a quoted field that +spans lines and holds a record's worth of delimiters (tables of five columns or more), or more than +`MaxQuotedFieldLines` line breaks, is replayed as records. An Excel export of a cell with a line break +and a few commas is exactly that shape. A caller that reads small, user-authored files and turns each +row into work would rather refuse a file than misread a row, and today its only signal is +`Diagnostics.IsClean`, which also trips on the valid export. + +## Goals + +- An opt-in mode that reads quotes as RFC 4180 does and refuses, rather than repairs, quoting that + could be misread. +- In that mode, whitespace around a quoted field is insignificant: `1, "Payroll", "monthly, HR"` reads + as `1 | Payroll | monthly, HR`. + +## Non-goals + +- The default mode does not change, in behaviour or in speed. +- The writer (`write.ambiguous-line-breaks`) stays as it is; a strict writer is a possible follow-up. +- No new diagnostics counter. + +## Approaches + +- **A.** Only the issue's three switches: no delimiter-count replay, no line-bound replay, an + unterminated quote at the end refused. `"C" Road` would still be repaired silently. +- **B (chosen).** A, plus refusing text after a closing quote (`"C" Road`; `135"th` past a line + ending). A quote inside an unquoted field (`21"st`) stays content: lossless, and what Excel does. +- **C.** Full RFC, refusing `21"st` too — refuses ordinary files with inch marks. + +## Design + +`CsvCursorOptions.QuoteMode`, of a new public enum `CsvQuoteMode { Repair = 0, Strict = 1 }`; +`Repair` is the default and today's behaviour. An undefined value is refused by `Checked()`. + +In `Strict`: + +- A quote opens a quoted field at the start of a field, or after nothing but whitespace (space, and + tab where tab is not the delimiter); that whitespace is dropped. +- Inside quotes, `""` is a quote. A quote followed by optional whitespace and then a delimiter, a line + ending or the end of the input closes the field; the whitespace is dropped. Anything else after a + closing quote is refused. +- A quoted field may span any number of lines and hold any number of delimiters: no replay at all. + `MaxFieldChars` still bounds it. `MaxQuotedFieldLines` does not apply. +- The end of the input inside a quoted field is refused. +- The raw text kept for a replay is not kept, so a quoted field is held once, not twice. +- `Diagnostics` stays clean: nothing is repaired. + +Refusals are `TabularFormatException` with `format.corrupt`, the message naming the row (the record +number the cursor would have given). The cursor is faulted afterwards, as for any failed read. The +same options reach csv files inside archives and gzip, so they read the same way. + +Dropping the whitespace changes no value: `RawCell.FromText` trims text anyway. + +## Left to the builder + +Performance: the default path gets a branch on a local per quote and per quoted run at most; +measured against `main` before merging. diff --git a/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs b/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs index 50fd7e2..63275cc 100644 --- a/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs +++ b/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs @@ -72,6 +72,17 @@ public sealed record CsvCursorOptions /// public int MaxQuotedFieldLines { get; init; } = 100; + /// + /// Whether quoting RFC 4180 does not allow is repaired, and counted, or refused. + /// + /// + /// by default: one malformed address must not fail an import of + /// five million rows. for a caller that would rather refuse a + /// file than misread a row of it — a repair can split a value that was quoted correctly, such as a + /// spreadsheet cell holding a line break and a few commas. + /// + public CsvQuoteMode QuoteMode { get; init; } = CsvQuoteMode.Repair; + /// /// The most characters one field may hold. /// @@ -112,6 +123,16 @@ internal CsvCursorOptions Checked() OptionChecks.AtLeast(DialectProbeBytes, 1, nameof(CsvCursorOptions), nameof(DialectProbeBytes)); OptionChecks.AtLeast(MaxColumns, 1, nameof(CsvCursorOptions), nameof(MaxColumns)); + if (!Enum.IsDefined(QuoteMode)) + { +#pragma warning disable S3928 // Justification: the options arrive through a parameter named options, as OptionChecks names it + throw new ArgumentOutOfRangeException( + "options", + QuoteMode, + $"{nameof(CsvCursorOptions)}.{nameof(QuoteMode)} is not a quote mode."); +#pragma warning restore S3928 + } + if (Delimiter is { } delimiter && !CsvDialectDetector.IsDelimiter(delimiter)) { #pragma warning disable S3928 // Justification: the options arrive through a parameter named options, as OptionChecks names it diff --git a/src/TriasDev.Tabular/Csv/CsvQuoteMode.cs b/src/TriasDev.Tabular/Csv/CsvQuoteMode.cs new file mode 100644 index 0000000..494c542 --- /dev/null +++ b/src/TriasDev.Tabular/Csv/CsvQuoteMode.cs @@ -0,0 +1,34 @@ +namespace TriasDev.Tabular; + +/// How the csv reader treats quoting that RFC 4180 does not allow. +/// +/// The choice is between two kinds of failure. A repaired file is read whole, but a repair is a guess, +/// and a guess can split a value that was written correctly. A strict read never guesses, and refuses +/// a file a repair would have read. A caller importing millions of rows from many producers wants the +/// first; a caller turning each of a few rows into work, for whom one misread row is worse than a +/// refused upload, wants the second. +/// +public enum CsvQuoteMode +{ + /// + /// Repairs what it can and counts each repair in : a quoted field + /// that spans lines and holds a record's worth of delimiters, or more than + /// line breaks, or that the file ends inside, is + /// read again as records; text after a closing quote ("C" Road) is kept as text. + /// + Repair = 0, + + /// + /// Reads quotes as RFC 4180 does and refuses, as , + /// what would repair: a quoted field the file ends inside, and text after a + /// closing quote. A quoted field may span any number of lines and hold any number of delimiters; + /// only bounds it. + /// + /// + /// Whitespace before an opening quote and after a closing one is not part of the field, so + /// 1, "Payroll", "monthly, HR" reads as three values. A quote inside a field that does not + /// start with one (21"st AVE) is a character of the text, as it is in every spreadsheet + /// program. Nothing is repaired, so stays true. + /// + Strict = 1, +} diff --git a/src/TriasDev.Tabular/PublicAPI.Unshipped.txt b/src/TriasDev.Tabular/PublicAPI.Unshipped.txt index 7dc5c58..37da979 100644 --- a/src/TriasDev.Tabular/PublicAPI.Unshipped.txt +++ b/src/TriasDev.Tabular/PublicAPI.Unshipped.txt @@ -1 +1,6 @@ #nullable enable +TriasDev.Tabular.CsvCursorOptions.QuoteMode.get -> TriasDev.Tabular.CsvQuoteMode +TriasDev.Tabular.CsvCursorOptions.QuoteMode.init -> void +TriasDev.Tabular.CsvQuoteMode +TriasDev.Tabular.CsvQuoteMode.Repair = 0 -> TriasDev.Tabular.CsvQuoteMode +TriasDev.Tabular.CsvQuoteMode.Strict = 1 -> TriasDev.Tabular.CsvQuoteMode diff --git a/tests/TriasDev.Tabular.Tests/OptionDefaultsTests.cs b/tests/TriasDev.Tabular.Tests/OptionDefaultsTests.cs index 087dce2..2c53975 100644 --- a/tests/TriasDev.Tabular.Tests/OptionDefaultsTests.cs +++ b/tests/TriasDev.Tabular.Tests/OptionDefaultsTests.cs @@ -42,6 +42,7 @@ public void ShipsTheDefaultsTheDocumentsPromise() Assert.Equal(16_384, csv.MaxColumns); Assert.Equal(16 * 1024 * 1024, csv.MaxFieldChars); Assert.Equal(100, csv.MaxQuotedFieldLines); + Assert.Equal(CsvQuoteMode.Repair, csv.QuoteMode); Assert.Equal(1_000, ExtractionOptions.Default.MaxErrorRows); Assert.Equal(2_000_000, AnalysisOptions.Default.DistinctTrackingBudget); diff --git a/tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs b/tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs index 2e3d450..bcb775a 100644 --- a/tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs +++ b/tests/TriasDev.Tabular.Tests/OptionsValidationTests.cs @@ -38,6 +38,7 @@ public sealed class OptionsValidationTests { new CsvCursorOptions { Quote = '\r' }, nameof(CsvCursorOptions.Quote) }, { new CsvCursorOptions { Quote = ';' }, nameof(CsvCursorOptions.Quote) }, { new CsvCursorOptions { Delimiter = '|', Quote = '|' }, nameof(CsvCursorOptions.Quote) }, + { new CsvCursorOptions { QuoteMode = (CsvQuoteMode)7 }, nameof(CsvCursorOptions.QuoteMode) }, }; public static TheoryData BadXlsxOptions => new() From 99bd06e04503be707300010c0b37ca8bef494305 Mon Sep 17 00:00:00 2001 From: Slava Date: Fri, 27 Nov 2026 10:06:18 +0100 Subject: [PATCH 2/4] feat: read csv quotes strictly when asked (#198) --- src/TriasDev.Tabular/Csv/CsvCursor.cs | 108 ++++++++- .../Csv/StrictQuoteTests.cs | 208 ++++++++++++++++++ .../Fuzz/CsvRoundTripFuzzTests.cs | 38 +++- .../Fuzz/MangledInputFuzzTests.cs | 5 +- 4 files changed, 352 insertions(+), 7 deletions(-) create mode 100644 tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs diff --git a/src/TriasDev.Tabular/Csv/CsvCursor.cs b/src/TriasDev.Tabular/Csv/CsvCursor.cs index e4d8d3f..ea135ad 100644 --- a/src/TriasDev.Tabular/Csv/CsvCursor.cs +++ b/src/TriasDev.Tabular/Csv/CsvCursor.cs @@ -308,6 +308,10 @@ private bool ReadRowCore(CancellationToken cancellationToken) int quotedDelimiters = 0; bool strayFits = true; + // Read once per row: in strict mode nothing is ever replayed, so none of the raw text a replay + // needs is kept, and what the repair mode repairs is refused instead (#198). + bool strict = _options.QuoteMode == CsvQuoteMode.Strict; + int sinceCheck = 0; while (true) @@ -372,7 +376,11 @@ private bool ReadRowCore(CancellationToken cancellationToken) run = ahead.Length; } - _quotedRaw.Append(ahead[..run]); + if (!strict) + { + _quotedRaw.Append(ahead[..run]); + } + AppendRunToField(ahead[..run]); _bufferPosition += run; sinceCheck += run; @@ -386,6 +394,11 @@ private bool ReadRowCore(CancellationToken cancellationToken) { if (inQuotes) { + if (strict) + { + throw Malformed("a quoted field is never closed, the file ends inside it"); + } + // The file ended inside a quoted field. Nothing to recover towards, so the text // gathered so far is the value. Diagnostics.RecoveredUnterminatedQuotes++; @@ -417,7 +430,7 @@ private bool ReadRowCore(CancellationToken cancellationToken) char c = (char)next; - if (inQuotes) + if (inQuotes && !strict) { // Kept before anything is decided about it, so that the character which trips the // bound is part of what gets replayed. Keeping it afterwards loses the line ending @@ -508,8 +521,36 @@ private bool ReadRowCore(CancellationToken cancellationToken) continue; } - if (c == Dialect.Quote && atFieldStart && !suppressQuote) + if (inQuotes) + { + // Strict: RFC 4180 and nothing else. However many lines and delimiters the field + // holds, only a quote can end it, and only where a field can end. + if (c != Dialect.Quote) + { + AppendToField(c); + continue; + } + + if (PeekChar() == Dialect.Quote) + { + ReadChar(); + AppendToField(Dialect.Quote); + continue; + } + + EndQuotedFieldStrictly(); + inQuotes = false; + continue; + } + + if (c == Dialect.Quote && !suppressQuote && (atFieldStart || (strict && OnlyBlankSoFar()))) { + // In strict mode a quote after nothing but whitespace opens the field too, as most + // readers take it, and the whitespace goes: `1, "monthly, HR"` is two values, not + // three. The text is trimmed when it becomes a cell anyway, so no value changes. + _field.Clear(); + _pendingStart = -1; + inQuotes = true; fieldWasQuoted = true; atFieldStart = false; @@ -594,6 +635,67 @@ private void AppendToField(char c) _field.Append(c); } + /// Whitespace that strict mode drops around a quoted field: a space, and a tab that is not the delimiter. + private bool IsBlank(int c) => c == ' ' || (c == '\t' && Dialect.Delimiter != '\t'); + + /// Whether the field read so far is nothing but whitespace. + /// Asked only at a quote inside a field, in strict mode; it stops at the first character that is not blank. + private bool OnlyBlankSoFar() + { + if (_pendingStart >= 0) + { + foreach (char c in _buffer.AsSpan(_pendingStart, _pendingLength)) + { + if (!IsBlank(c)) + { + return false; + } + } + + // A pending run is the field's only content: nothing was added to the builder before it. + return true; + } + + for (int i = 0; i < _field.Length; i++) + { + if (!IsBlank(_field[i])) + { + return false; + } + } + + return true; + } + + /// + /// After a closing quote in strict mode: drops the whitespace that follows it, and refuses + /// anything else but the end of the field. + /// + [MethodImpl(MethodImplOptions.NoInlining)] + private void EndQuotedFieldStrictly() + { + int next = PeekChar(); + + while (IsBlank(next)) + { + ReadChar(); + next = PeekChar(); + } + + if (next >= 0 && next != Dialect.Delimiter && next != '\r' && next != '\n') + { + throw Malformed("text follows the closing quote of a field"); + } + } + + /// The refusal of strict mode, naming the record being read. + [MethodImpl(MethodImplOptions.NoInlining)] + private TabularFormatException Malformed(string what) => new( + TabularFormatException.Corrupt, + $"The csv file is not valid at row {(long)CurrentRowNumber + 1}: {what}. " + + $"It was read with {nameof(CsvQuoteMode)}.{nameof(CsvQuoteMode.Strict)}; " + + $"{nameof(CsvQuoteMode)}.{nameof(CsvQuoteMode.Repair)} would have repaired it."); + /// /// Puts back everything a quoted field swallowed, its opening quote first, to be read again as /// ordinary characters. diff --git a/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs b/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs new file mode 100644 index 0000000..8231641 --- /dev/null +++ b/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs @@ -0,0 +1,208 @@ +using System.Text; + +using TriasDev.Tabular.Csv; + +using Xunit; + +namespace TriasDev.Tabular.Tests.Csv; + +/// +/// reads quotes as RFC 4180 does and refuses what the default mode +/// repairs (#198). +/// +public sealed class StrictQuoteTests +{ + private static readonly UTF8Encoding Utf8NoBom = new(encoderShouldEmitUTF8Identifier: false); + + /// A spreadsheet's export of a cell holding a line break and four commas, in a table of five columns. + private const string ExcelExport = + "ID,Name,Description,Owner,Department\r\n" + + "1,Payroll,\"Monthly salary run.\nUses names, addresses, bank accounts, tax ids, and social security numbers.\",HR,People\r\n" + + "2,Recruiting,Applicant tracking,HR,People\r\n"; + + private static CsvCursor Open(string text, CsvCursorOptions options) => + new(new MemoryStream(Utf8NoBom.GetBytes(text), writable: false), "t.csv", options); + + private static (List Rows, CursorDiagnostics Diagnostics) Read(string text, CsvCursorOptions? options = null) + { + using CsvCursor cursor = Open(text, options ?? new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict }); + List rows = []; + + while (cursor.ReadRow(TestContext.Current.CancellationToken)) + { + rows.Add([.. cursor.CurrentRow.ToArray().Select(c => c.AsText() ?? string.Empty)]); + } + + return (rows, cursor.Diagnostics); + } + + private static TabularFormatException Refused(string text, CsvCursorOptions? options = null) + { + using CsvCursor cursor = Open(text, options ?? new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict }); + + TabularFormatException error = Assert.Throws(() => + { + while (cursor.ReadRow(TestContext.Current.CancellationToken)) + { + _ = cursor.CurrentRow.Length; + } + }); + + Assert.Equal(TabularFormatException.Corrupt, error.Code); + Assert.Throws(() => cursor.ReadRow(TestContext.Current.CancellationToken)); + return error; + } + + [Fact] + public void ReadsAnExcelCellWithALineBreakAndCommasAsOneValue() + { + (List rows, CursorDiagnostics diagnostics) = Read(ExcelExport); + + Assert.Equal(3, rows.Count); + Assert.Equal( + ["1", "Payroll", "Monthly salary run.\nUses names, addresses, bank accounts, tax ids, and social security numbers.", "HR", "People"], + rows[1]); + Assert.Equal(["2", "Recruiting", "Applicant tracking", "HR", "People"], rows[2]); + Assert.True(diagnostics.IsClean); + } + + [Fact] + public void RepairModeStillSplitsTheExcelCell() + { + // Pins that the default did not move: the repair is what strict mode exists to avoid. + (List rows, CursorDiagnostics diagnostics) = Read(ExcelExport, CsvCursorOptions.Default); + + Assert.Equal(4, rows.Count); + Assert.True(diagnostics.RecoveredStrayQuotes > 0); + } + + [Fact] + public void KeepsAQuotedFieldOfMoreThanTheLineBoundAsOneValue() + { + string note = string.Join('\n', Enumerable.Range(1, 151).Select(i => $"line {i}")); + + (List rows, CursorDiagnostics diagnostics) = Read($"id,note\n1,\"{note}\"\n2,b\n"); + + Assert.Equal(3, rows.Count); + Assert.Equal(note, rows[1][1]); + Assert.Equal(["2", "b"], rows[2]); + Assert.True(diagnostics.IsClean); + } + + [Fact] + public void RefusesAQuoteTheInputEndsInside() + { + TabularFormatException error = Refused("a,b\n1,\"open\nmore"); + + Assert.Contains("row 2", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void RefusesAQuoteTheInputEndsInsideOnItsFirstLine() + { + Refused("a,b\n1,\"open"); + } + + [Theory] + [InlineData("a,b\n\"C\" Road,x\n")] + [InlineData("a,b\n\"C\"Road,x\n")] + [InlineData("a,b\n\"note\n135\"th\",x\n")] + [InlineData("a,b\n1,\"x\" \"y\"\n")] + public void RefusesTextAfterAClosingQuote(string text) + { + TabularFormatException error = Refused(text); + + Assert.Contains("row 2", error.Message, StringComparison.Ordinal); + } + + [Fact] + public void IgnoresWhitespaceAroundAQuotedField() + { + (List rows, CursorDiagnostics diagnostics) = Read("ID, Name, Note\r\n1, \"Payroll\", \"monthly, HR\" \r\n"); + + Assert.Equal(["1", "Payroll", "monthly, HR"], rows[1]); + Assert.True(diagnostics.IsClean); + } + + [Fact] + public void KeepsAQuoteInsideAnUnquotedField() + { + (List rows, _) = Read("a,b\n21\"st AVE,x\nsize 5 \"big\",y\n"); + + Assert.Equal(["21\"st AVE", "x"], rows[1]); + Assert.Equal(["size 5 \"big\"", "y"], rows[2]); + } + + [Theory] + [InlineData("a\n\"x\"\"\"", "x\"")] + [InlineData("a\n\"x\"\"\"\n", "x\"")] + [InlineData("a\n\"\"\"\"\n", "\"")] + [InlineData("a\n\"x\" \r", "x")] + [InlineData("a\n\"x\" \rb\r", "x")] + [InlineData("a\n\"x\" ", "x")] + [InlineData("a\n\"x\" \t \r\n", "x")] + public void ClosesAQuotedFieldBeforeWhitespaceAndTheEnd(string text, string value) + { + (List rows, _) = Read(text); + + Assert.Equal([value], rows[1]); + } + + [Fact] + public void TakesATabDelimiterAsADelimiterNotAsWhitespace() + { + (List rows, _) = Read( + "a\tb\tc\n1\t \"x\ty\"\t\"z\"\n", + new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict, Delimiter = '\t' }); + + Assert.Equal(["1", "x\ty", "z"], rows[1]); + } + + [Fact] + public void HonoursAStatedQuoteCharacter() + { + CsvCursorOptions options = new() { QuoteMode = CsvQuoteMode.Strict, Quote = '\'', Delimiter = ',' }; + + (List rows, _) = Read("a,b\n 'x, y' ,z\n'it''s',\"q\"\n", options); + + Assert.Equal(["x, y", "z"], rows[1]); + Assert.Equal(["it's", "\"q\""], rows[2]); + Refused("a,b\n'C' Road,x\n", options); + } + + [Fact] + public void ReadsACsvInsideGzipStrictlyToo() + { + MemoryStream compressed = new(); + + using (System.IO.Compression.GZipStream gzip = new(compressed, System.IO.Compression.CompressionLevel.Fastest, leaveOpen: true)) + { + gzip.Write(Utf8NoBom.GetBytes(ExcelExport)); + } + + compressed.Position = 0; + TabularOpenOptions options = new() { Csv = new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict } }; + using ITabularCursor cursor = TabularFile.Open(compressed, "t.csv.gz", options, TestContext.Current.CancellationToken); + int rows = 0; + + while (cursor.ReadRow(TestContext.Current.CancellationToken)) + { + rows++; + } + + Assert.Equal(3, rows); + Assert.True(cursor.Diagnostics.IsClean); + } + + [Fact] + public void HoldsAQuotedFieldToTheFieldLimit() + { + CsvCursorOptions options = new() { QuoteMode = CsvQuoteMode.Strict, MaxFieldChars = 8 }; + + Assert.Equal(["12345678"], Read("a\n\"12345678\"\n", options).Rows[1]); + + using CsvCursor cursor = Open("a\n\"123456789\"\n", options); + Assert.True(cursor.ReadRow(TestContext.Current.CancellationToken)); + Assert.Throws(() => cursor.ReadRow(TestContext.Current.CancellationToken)); + } +} diff --git a/tests/TriasDev.Tabular.Tests/Fuzz/CsvRoundTripFuzzTests.cs b/tests/TriasDev.Tabular.Tests/Fuzz/CsvRoundTripFuzzTests.cs index 6bde10c..ae14c33 100644 --- a/tests/TriasDev.Tabular.Tests/Fuzz/CsvRoundTripFuzzTests.cs +++ b/tests/TriasDev.Tabular.Tests/Fuzz/CsvRoundTripFuzzTests.cs @@ -37,6 +37,30 @@ public void ReadsBackEveryTableItWrote() } } + [Fact] + public void ReadsBackEveryTableItWroteStrictlyWhateverItsFieldsHold() + { + // No value is taken out of the stray-quote rule here: strict mode has none, so a field may + // hold any number of delimiters and lines. Quoted fields get whitespace around them, which + // strict mode drops. + foreach ((int seed, Random random) in FuzzCases.Generate(300)) + { + char delimiter = random.Pick(';', ',', '\t', '|'); + string lineEnd = random.Pick("\n", "\r\n"); + Encoding encoding = random.Pick(new UTF8Encoding(false), new UTF8Encoding(true), new UnicodeEncoding(false, true)); + string[][] table = Table(random, Pieces); + byte[] file = Write(table, delimiter, lineEnd, encoding, random, quoteAlways: random.Chance(0.2), padQuoted: true); + + FuzzCases.Keep(seed, ".strict.csv", file); + using CsvCursor cursor = new( + new MemoryStream(file), + "fuzz.csv", + new CsvCursorOptions { Encoding = encoding, Delimiter = delimiter, QuoteMode = CsvQuoteMode.Strict }); + AssertReadsAs(table, cursor, seed); + Assert.True(cursor.Diagnostics.IsClean, $"seed {seed}: strict mode counted a repair"); + } + } + [Fact] public void FindsTheDialectOfPlainTables() { @@ -121,13 +145,17 @@ private static string Value(Random random, string[] pieces) return value.ToString(); } - private static byte[] Write(string[][] table, char delimiter, string lineEnd, Encoding encoding, Random random, bool quoteAlways) + private static byte[] Write(string[][] table, char delimiter, string lineEnd, Encoding encoding, Random random, bool quoteAlways, bool padQuoted = false) { StringBuilder csv = new(); for (int r = 0; r < table.Length; r++) { - csv.Append(string.Join(delimiter, table[r].Select(v => Field(v, delimiter, quoteAlways || random.Chance(0.1))))); + csv.Append(string.Join(delimiter, table[r].Select(v => + { + string field = Field(v, delimiter, quoteAlways || random.Chance(0.1)); + return padQuoted && field.StartsWith('"') ? Blank(random, delimiter) + field + Blank(random, delimiter) : field; + }))); if (r < table.Length - 1 || random.Chance(0.5)) { @@ -138,6 +166,12 @@ private static byte[] Write(string[][] table, char delimiter, string lineEnd, En return [.. encoding.GetPreamble(), .. encoding.GetBytes(csv.ToString())]; } + /// Nothing, or a few spaces and — where tab is not the delimiter — tabs. + private static string Blank(Random random, char delimiter) => + random.Chance(0.5) + ? string.Empty + : new string([.. Enumerable.Range(0, random.Next(1, 4)).Select(_ => delimiter != '\t' && random.Chance(0.3) ? '\t' : ' ')]); + private static string Field(string value, char delimiter, bool quote) { bool needs = value.Contains(delimiter, StringComparison.Ordinal) || value.Contains('"', StringComparison.Ordinal) diff --git a/tests/TriasDev.Tabular.Tests/Fuzz/MangledInputFuzzTests.cs b/tests/TriasDev.Tabular.Tests/Fuzz/MangledInputFuzzTests.cs index 50764a9..15829af 100644 --- a/tests/TriasDev.Tabular.Tests/Fuzz/MangledInputFuzzTests.cs +++ b/tests/TriasDev.Tabular.Tests/Fuzz/MangledInputFuzzTests.cs @@ -41,6 +41,7 @@ public void ReadsOrRefusesMangledCsv() } ReadsOrRefuses([.. file], "fuzz.csv", seed); + ReadsOrRefuses([.. file], "fuzz.csv", seed, new TabularOpenOptions { Csv = new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict } }); } } @@ -154,7 +155,7 @@ private static byte[] RandomTar(Random random) return TarArchive.Of(format, [.. files]); } - private static void ReadsOrRefuses(byte[] file, string name, int seed) + private static void ReadsOrRefuses(byte[] file, string name, int seed, TabularOpenOptions? options = null) { FuzzCases.Keep(seed, Path.GetExtension(name), file); @@ -164,7 +165,7 @@ private static void ReadsOrRefuses(byte[] file, string name, int seed) try { - using ITabularCursor cursor = TabularFile.Open(new MemoryStream(file), name, cancellationToken: deadline.Token); + using ITabularCursor cursor = TabularFile.Open(new MemoryStream(file), name, options, cancellationToken: deadline.Token); for (int s = 0; s < cursor.Sheets.Count && cursor.MoveToSheet(s, deadline.Token); s++) { From 85e172b46736af6436aad47b5bac6724323e4351 Mon Sep 17 00:00:00 2001 From: Slava Date: Fri, 27 Nov 2026 10:08:11 +0100 Subject: [PATCH 3/4] docs: describe strict csv quoting --- docs/KNOWN-ISSUES.md | 7 +++++-- docs/bounds.md | 6 +++--- docs/error-codes.md | 2 +- docs/formats.md | 17 +++++++++++++++++ .../Abstractions/CursorDiagnostics.cs | 2 ++ src/TriasDev.Tabular/Csv/CsvCursor.cs | 3 ++- src/TriasDev.Tabular/Csv/CsvCursorOptions.cs | 4 ++++ 7 files changed, 34 insertions(+), 7 deletions(-) diff --git a/docs/KNOWN-ISSUES.md b/docs/KNOWN-ISSUES.md index 9cdf796..26e6cce 100644 --- a/docs/KNOWN-ISSUES.md +++ b/docs/KNOWN-ISSUES.md @@ -18,7 +18,9 @@ line ending is read as one field spanning lines, as RFC 4180 says — unless the swallowed a whole record's worth of delimiters, which marks it as a stray quote (#20, #10). A stray quote that happens to be closed at a field boundary before that point keeps the two lines joined: nothing in the text tells it from a genuine multi-line value. In tables narrower than five columns -the delimiter test is off, and only the 100-line bound catches a stray quote. +the delimiter test is off, and only the 100-line bound catches a stray quote. The reverse holds too: +a genuine value that crosses a line and holds a record's worth of delimiters is split. A caller who +cannot afford either reads with `CsvQuoteMode.Strict`, which never repairs and refuses instead (#198). **Matters when** a producer writes lone quotes into fields often enough for two of them to meet at a field boundary within one record. Neither the real-world nor the synthetic 5M-row fixture has such a @@ -160,7 +162,8 @@ Decided, not deferred — listed so they are not mistaken for gaps. - **The header is the first row.** No heuristic looks elsewhere; `MappingPlan.HeaderRowIndex` is where a user says otherwise. - **`"C" Road` is repaired without a diagnostic.** The repair is lossy, and unlike an unterminated - quote it is not counted. Whether it should be is a judgement, not an oversight. + quote it is not counted. Whether it should be is a judgement, not an oversight. `CsvQuoteMode.Strict` + refuses it. ## Writing: what does not come back exactly as written diff --git a/docs/bounds.md b/docs/bounds.md index fba35b7..4279e1a 100644 --- a/docs/bounds.md +++ b/docs/bounds.md @@ -6,7 +6,7 @@ or do, each with a default and, where it is not the format's own, an option — a structural ceiling is refused with `TabularLimitException`, whose `Limit` names the option — or, for a ceiling the format fixes, the nearest one (the reader's fixed tag and buffer ceilings report `MaxValueChars`); an xlsx cell past the format's 16,384 columns is a damaged file, `TabularFormatException`; past the -quoted-field bound a csv quote is repaired and counted instead; past an analysis budget the profile +quoted-field bound a csv quote is repaired and counted instead (unless `CsvCursorOptions.QuoteMode` is `Strict`, which has no such bound); past an analysis budget the profile reports a lower bound or keeps fewer values rather than failing; and past the error-row ceiling a run stops. **Writing** is held to the formats' own limits and to what the reader reads back; those are fixed, not options, and reaching one is the data's doing, so it is a located `TabularWriteException` — `TabularLimitException` is thrown only while reading. @@ -31,8 +31,8 @@ data's doing, so it is a located `TabularWriteException` — `TabularLimitExcept | Columns per row | 16,384 | `MaxColumns` (csv, ods); fixed for xlsx | The workbook format's own width. A csv has none, and a file of nothing but delimiters is the cheapest attack there is | | Cells repeats hand out (ods) | 100,000,000 | `OdsCursorOptions.MaxRepeatedCells` | The row and column ceilings bound a sheet's shape, not the work: one cell repeated across every column of a row repeated a million times is under a kilobyte and seventeen billion cells. The copies count, across the file: each sheet once, at the most one pass over it hands out, so a sheet read again counts only what goes past its earlier pass | | Rows holding a value (ods) | 1,048,576 | `OdsCursorOptions.MaxRows` | OpenDocument repeats a row or cell with one attribute. An empty repeat only moves the position along; one that holds a value is expanded, so it is bounded here and by the column ceiling — twenty characters of markup could otherwise ask for a billion cells | -| Field length (csv) | 16 M chars | `CsvCursorOptions.MaxFieldChars` | Held twice while a quoted field is open, once as the value and once as the text kept for a replay | -| Quoted field length | 100 lines | `CsvCursorOptions.MaxQuotedFieldLines` | Beyond that an opening quote was never syntax. In a table of five columns or more a stray quote is caught sooner, by swallowing a record's worth of delimiters | +| Field length (csv) | 16 M chars | `CsvCursorOptions.MaxFieldChars` | Held twice while a quoted field is open, once as the value and once as the text kept for a replay (once with `QuoteMode = Strict`, which never replays) | +| Quoted field length | 100 lines | `CsvCursorOptions.MaxQuotedFieldLines` | Beyond that an opening quote was never syntax. In a table of five columns or more a stray quote is caught sooner, by swallowing a record's worth of delimiters. Not applied with `QuoteMode = Strict`, where only the field length bounds a quoted field | | Distinct tracking | 2,000,000 values | `AnalysisOptions.DistinctTrackingBudget` | Exact counting costs memory in proportion; the budget is per file, not per column | | Retained distinct values | 1,000 per column | `AnalysisOptions.RetainedDistinctValues` | Enough to judge a column of codes against a reference set; a column with more is not one | | Error rows | 1,000 | `ExtractionOptions.MaxErrorRows` | A wrong mapping fails every row, and the thousand-and-first error says nothing the first did not | diff --git a/docs/error-codes.md b/docs/error-codes.md index c2fb995..22ebb33 100644 --- a/docs/error-codes.md +++ b/docs/error-codes.md @@ -23,7 +23,7 @@ from them. | `mapping.header-changed` | The column's header is not the one the mapping recorded | | `mapping.invalid-plan` | `MappingPlanException`: the plan does not fit its schema; its `Faults` carry the codes above | | `structure.sheet-missing`, `structure.sheet-changed`, `structure.header-row-missing`, `structure.header-changed` | `TabularStructureException`: the file is not the one the plan was built for | -| `format.unsupported`, `format.corrupt`, `format.truncated` | `TabularFormatException`: not a format this library reads (.xls, .xlsb, .fods, another OpenDocument type, binary, an archive with nothing readable), or damaged, or cut off | +| `format.unsupported`, `format.corrupt`, `format.truncated` | `TabularFormatException`: not a format this library reads (.xls, .xlsb, .fods, another OpenDocument type, binary, an archive with nothing readable), or damaged, or cut off. A csv read with `CsvQuoteMode.Strict` is `format.corrupt` where its quoting would need a repair: a quoted field the file ends inside, or text after a closing quote | | `limit.exceeded` | `TabularLimitException`: a bound was exceeded; `Limit` names the option, `Maximum` its value | | `write.too-many-rows`, `write.too-many-merges`, `write.too-many-styles` | `TabularWriteException`: the data reached a limit of the format while writing — more rows than the sheet holds (1,048,576 in xlsx and ods; 2,147,483,647, the largest row number the reader gives, in csv and a zip of csv; located at the last row the sheet holds, column 0), more merged ranges than an xlsx sheet holds (65,536; located where the range would begin), or a style rule's 4,097th distinct style in a file (located at its cell). Never `TabularLimitException`, which is a reader's bound. The file written so far is incomplete and must be discarded. | | `write.precision-loss`, `write.not-finite`, `write.date-out-of-range`, `write.text-too-long`, `write.too-many-lines`, `write.ambiguous-line-breaks`, `write.invalid-character` | `TabularWriteException`: a value the chosen format cannot hold exactly, found while writing; `SheetName`, `RowNumber`, `ColumnIndex` and `Header` say where. The file written so far is incomplete and must be discarded. In xlsx: a long a double cannot hold exactly (beyond ±2^53 only some are), or a decimal with more than 15 significant digits (precision-loss); a date before 1900-01-01 (date-out-of-range); text over 32,767 characters (text-too-long). In ods: the same precision rule as xlsx (precision-loss); text over 16,777,216 characters, the reader's limit, or text whose escaped form would exceed the reader's per-value token limit (text-too-long); no date limit. | diff --git a/docs/formats.md b/docs/formats.md index a457101..2cf1c3d 100644 --- a/docs/formats.md +++ b/docs/formats.md @@ -157,6 +157,23 @@ one the file ends inside, is abandoned the same way (`RecoveredUnterminatedQuote what protects tables narrower than five columns, where the delimiter test is off. Genuine multi-line values — an address, a long note — hold a delimiter or two at most and are left alone. +A repair is a guess, and a guess can be wrong: a spreadsheet's export of a cell holding a line break +and four commas, in a table of five columns, looks exactly like a stray quote and is split. A caller +for whom one misread row is worse than a refused file — a few rows typed by a person, each turned into +work — reads with `CsvCursorOptions.QuoteMode = CsvQuoteMode.Strict` instead: + +```csharp +TabularOpenOptions options = new() { Csv = new CsvCursorOptions { QuoteMode = CsvQuoteMode.Strict } }; +``` + +Strict mode reads quotes as RFC 4180 does. A quoted field holds any number of lines and delimiters, +bounded only by `MaxFieldChars`; a quoted field the file ends inside, and text after a closing quote +(`"C" Road`), are refused as `format.corrupt`, the message naming the row. Whitespace before an +opening quote and after a closing one is not part of the field, so `1, "Payroll", "monthly, HR"` is +three values — in the default mode the quotes after a space are text, and the last value is split at +its comma. A quote inside a field that does not start with one (`21"st AVE`) is text in both modes. +Nothing is repaired, so `Diagnostics.IsClean` stays true. + ## What each format holds when written A value a format cannot hold exactly is refused with a `TabularWriteException` that names the sheet, diff --git a/src/TriasDev.Tabular/Abstractions/CursorDiagnostics.cs b/src/TriasDev.Tabular/Abstractions/CursorDiagnostics.cs index 66b851e..7c1e655 100644 --- a/src/TriasDev.Tabular/Abstractions/CursorDiagnostics.cs +++ b/src/TriasDev.Tabular/Abstractions/CursorDiagnostics.cs @@ -8,6 +8,8 @@ namespace TriasDev.Tabular; /// anyway. The reader recovers rather than refusing — a single malformed address must not fail an /// import of five million rows — but a recovery nobody is told about is indistinguishable from /// correct reading, and that is the actual defect. Hence the counts. +/// A csv read with repairs nothing and refuses instead, so its +/// counts stay zero. /// public sealed record CursorDiagnostics { diff --git a/src/TriasDev.Tabular/Csv/CsvCursor.cs b/src/TriasDev.Tabular/Csv/CsvCursor.cs index ea135ad..9d9c01d 100644 --- a/src/TriasDev.Tabular/Csv/CsvCursor.cs +++ b/src/TriasDev.Tabular/Csv/CsvCursor.cs @@ -17,7 +17,8 @@ namespace TriasDev.Tabular.Csv; /// The reader repairs input no specification allows, because such input arrives constantly: quotes /// standing inside fields that were never quoted, text after a closing quote, quotes that are never /// closed at all. Refusing the file would be defensible and useless — one malformed address must not -/// fail an import of five million rows — so it recovers and counts what it repaired. +/// fail an import of five million rows — so it recovers and counts what it repaired. Unless the +/// caller asked for : then it reads RFC 4180 and refuses the rest. /// /// internal sealed class CsvCursor : ITabularCursor diff --git a/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs b/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs index 63275cc..a999067 100644 --- a/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs +++ b/src/TriasDev.Tabular/Csv/CsvCursorOptions.cs @@ -69,6 +69,10 @@ public sealed record CsvCursorOptions /// bound is what stands behind narrower tables, and every recovery by it is counted in /// . /// + /// + /// Not applied when is : nothing is + /// replayed there, and only bounds a quoted field. + /// /// public int MaxQuotedFieldLines { get; init; } = 100; From 455992c19b30f43ceb46d7dee45742ff3cb6f363 Mon Sep 17 00:00:00 2001 From: Slava Date: Fri, 27 Nov 2026 10:16:07 +0100 Subject: [PATCH 4/4] fix: look for leading blanks from the end of a strict csv field, so a run of quotes costs linear time --- src/TriasDev.Tabular/Csv/CsvCursor.cs | 17 ++++++++++++----- .../Csv/StrictQuoteTests.cs | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/TriasDev.Tabular/Csv/CsvCursor.cs b/src/TriasDev.Tabular/Csv/CsvCursor.cs index 9d9c01d..4837805 100644 --- a/src/TriasDev.Tabular/Csv/CsvCursor.cs +++ b/src/TriasDev.Tabular/Csv/CsvCursor.cs @@ -640,24 +640,31 @@ private void AppendToField(char c) private bool IsBlank(int c) => c == ' ' || (c == '\t' && Dialect.Delimiter != '\t'); /// Whether the field read so far is nothing but whitespace. - /// Asked only at a quote inside a field, in strict mode; it stops at the first character that is not blank. + /// + /// Asked at every quote inside a field, in strict mode, so it looks from the end and stops at the + /// first character that is not blank. Looking from the start cost the length of the field's leading + /// blanks per quote — quadratic in a field of blanks, a letter and a run of quotes, where from the + /// end each quote meets the one before it at once. + /// private bool OnlyBlankSoFar() { if (_pendingStart >= 0) { - foreach (char c in _buffer.AsSpan(_pendingStart, _pendingLength)) + // A pending run is the field's only content: nothing was added to the builder before it. + ReadOnlySpan run = _buffer.AsSpan(_pendingStart, _pendingLength); + + for (int i = run.Length - 1; i >= 0; i--) { - if (!IsBlank(c)) + if (!IsBlank(run[i])) { return false; } } - // A pending run is the field's only content: nothing was added to the builder before it. return true; } - for (int i = 0; i < _field.Length; i++) + for (int i = _field.Length - 1; i >= 0; i--) { if (!IsBlank(_field[i])) { diff --git a/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs b/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs index 8231641..d777c0a 100644 --- a/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs +++ b/tests/TriasDev.Tabular.Tests/Csv/StrictQuoteTests.cs @@ -170,6 +170,25 @@ public void HonoursAStatedQuoteCharacter() Refused("a,b\n'C' Road,x\n", options); } + [Fact] + public void ReadsQuotesAfterLeadingBlanksInLinearTime() + { + // Each quote inside a field asks whether the field so far is only whitespace. Asked from the + // field's start, that cost the length of its leading blanks per quote: sixty thousand blanks + // and as many quotes took some fifteen seconds, eighty thousand thirty-seven, and cancellation, + // checked per character, could not reach it. Linear, it is milliseconds, so the ceiling sits a + // thousand times above it and far below the defect. + const int n = 60_000; + string text = "a,b\n" + new string(' ', n) + "x" + new string('"', n) + ",y\n"; + System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew(); + + (List rows, _) = Read(text); + + watch.Stop(); + Assert.Equal("x" + new string('"', n), rows[1][0]); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(3), $"took {watch.Elapsed}"); + } + [Fact] public void ReadsACsvInsideGzipStrictlyToo() {