Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions docs/KNOWN-ISSUES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions docs/bounds.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion docs/error-codes.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
17 changes: 17 additions & 0 deletions docs/formats.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
77 changes: 77 additions & 0 deletions docs/superpowers/plans/2026-11-27-csv-strict-quotes.md
Original file line number Diff line number Diff line change
@@ -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`.
60 changes: 60 additions & 0 deletions docs/superpowers/specs/2026-11-27-csv-strict-quotes-design.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 2 additions & 0 deletions src/TriasDev.Tabular/Abstractions/CursorDiagnostics.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <see cref="CsvQuoteMode.Strict"/> repairs nothing and refuses instead, so its
/// counts stay zero.
/// </remarks>
public sealed record CursorDiagnostics
{
Expand Down
Loading
Loading