Public: anyone can read this; the crew can change it.
CSV: a field past the kept columns is only counted, so a 10 MB one-record line parses in tens of ms #15757
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15739-csv-a-field-past-the-kept-columns-is-onl → main 0 commits fork 2 threads · 2 unresolved
4 files
changed +98
−21
docs/features/csv-view.md +1 −1
| @@ -5,7 +5,7 @@ row: CSV and TSV as a table | ||
| 5 | 5 | # CSV and TSV as a table |
| 6 | 6 | |
| 7 | 7 | `.csv`/`.tsv` files open as a table on the blob page (`src/web/render/csv.ts`, parser in `csv-parse.ts`). |
| 8 | RFC 4180 with quotes, embedded newlines, doubled quotes and a BOM; the delimiter (`,` `;` tab `|`) is detected from the first record. | |
| 8 | RFC 4180 with quotes, embedded newlines, doubled quotes and a BOM; the delimiter (`,` `;` tab `|`) is detected from the first record (its first 65,536 characters). | |
| 9 | 9 | The first 1,000 rows are drawn on the server with a sticky header and (on phones) a sticky first column; numeric columns are right-aligned. |
| 10 | 10 | `?all=1` ("Show all N rows", no JavaScript needed) draws up to 20,000. The header line shows rows × columns and the delimiter. |
| 11 | 11 | A small script adds a filter box over the rows drawn; no library. |
src/web/render/csv-parse.ts +46 −12
| @@ -29,23 +29,30 @@ export interface Limits { | ||
| 29 | 29 | readonly delimiter?: Delimiter; |
| 30 | 30 | } |
| 31 | 31 | |
| 32 | /** How many characters of the first record the delimiter guess reads. */ | |
| 33 | export const DETECT_CHARS = 64 * 1024; | |
| 34 | ||
| 32 | 35 | /** Each candidate delimiter's count in the first record, quotes respected. */ |
| 33 | 36 | export function detectDelimiter(text: string): Delimiter { |
| 34 | const counts = new Map<string, number>(); | |
| 37 | const counts = [0, 0, 0, 0]; | |
| 35 | 38 | let quoted = false; |
| 36 | for (let i = 0; i < text.length; i++) { | |
| 37 | const c = text[i]!; | |
| 38 | if (c === '"') quoted = !quoted; | |
| 39 | else if (!quoted && (c === "\n" || c === "\r")) break; | |
| 40 | else if (!quoted) counts.set(c, (counts.get(c) ?? 0) + 1); | |
| 39 | const end = Math.min(text.length, DETECT_CHARS); | |
| 40 | for (let i = 0; i < end; i++) { | |
| 41 | const c = text.charCodeAt(i); | |
| 42 | if (c === 34) quoted = !quoted; | |
| 43 | else if (quoted) continue; | |
| 44 | else if (c === 10 || c === 13) break; | |
| 45 | else if (c === 44) counts[0]!++; | |
| 46 | else if (c === 59) counts[1]!++; | |
| 47 | else if (c === 9) counts[2]!++; | |
| 48 | else if (c === 124) counts[3]!++; | |
| 41 | 49 | } |
| 42 | 50 | let best: Delimiter = ","; |
| 43 | 51 | let most = 0; |
| 44 | for (const d of DELIMITERS) { | |
| 45 | const n = counts.get(d) ?? 0; | |
| 46 | if (n > most) { | |
| 47 | best = d; | |
| 48 | most = n; | |
| 52 | for (let k = 0; k < DELIMITERS.length; k++) { | |
| 53 | if (counts[k]! > most) { | |
| 54 | best = DELIMITERS[k]!; | |
| 55 | most = counts[k]!; | |
| 49 | 56 | } |
| 50 | 57 | } |
| 51 | 58 | return best; |
| @@ -75,10 +82,33 @@ export function parseCsv(input: string, limits: Limits = {}): Parsed { | ||
| 75 | 82 | row = []; |
| 76 | 83 | fields = 0; |
| 77 | 84 | }; |
| 85 | const dc = delimiter.charCodeAt(0); | |
| 78 | 86 | let field = ""; |
| 87 | // True at the first character of a field: only there does a quote open one. | |
| 88 | let atStart = true; | |
| 79 | 89 | while (i < n) { |
| 90 | if (fields >= keepCols || records >= keepRows) { | |
| 91 | // Nothing here is kept: count delimiters up to a line end or a quote | |
| 92 | // that opens a field. | |
| 93 | let j = i; | |
| 94 | let start: boolean = atStart; | |
| 95 | while (j < n) { | |
| 96 | const k = text.charCodeAt(j); | |
| 97 | if (k === dc) { | |
| 98 | fields++; | |
| 99 | start = true; | |
| 100 | } else if (k === 10 || k === 13 || (k === 34 && start)) break; | |
| 101 | else start = false; | |
| 102 | j++; | |
| 103 | } | |
| 104 | if (j > i) { | |
| 105 | i = j; | |
| 106 | atStart = start; | |
| 107 | continue; | |
| 108 | } | |
| 109 | } | |
| 80 | 110 | const c = text[i]!; |
| 81 | if (c === '"' && field === "") { | |
| 111 | if (c === '"' && atStart) { | |
| 82 | 112 | // A quoted field runs to its closing quote; "" inside is one quote. |
| 83 | 113 | const wanted = keeping() && fields < keepCols; |
| 84 | 114 | i++; |
| @@ -97,14 +127,17 @@ export function parseCsv(input: string, limits: Limits = {}): Parsed { | ||
| 97 | 127 | const after = text[i]; |
| 98 | 128 | if (after !== undefined && after !== delimiter && after !== "\n" && after !== "\r") |
| 99 | 129 | return { error: `Text follows a closing quote on row ${records + 1}.` }; |
| 130 | atStart = false; | |
| 100 | 131 | } else if (c === delimiter) { |
| 101 | 132 | addField(field); |
| 102 | 133 | field = ""; |
| 134 | atStart = true; | |
| 103 | 135 | i++; |
| 104 | 136 | } else if (c === "\n" || c === "\r") { |
| 105 | 137 | addField(field); |
| 106 | 138 | field = ""; |
| 107 | 139 | endRow(); |
| 140 | atStart = true; | |
| 108 | 141 | i += c === "\r" && text[i + 1] === "\n" ? 2 : 1; |
| 109 | 142 | } else { |
| 110 | 143 | // Unquoted run up to the next special character. |
| @@ -115,6 +148,7 @@ export function parseCsv(input: string, limits: Limits = {}): Parsed { | ||
| 115 | 148 | j++; |
| 116 | 149 | } |
| 117 | 150 | if (keeping() && fields < keepCols) field += text.slice(i, j); |
| 151 | atStart = false; | |
| 118 | 152 | i = j; |
| 119 | 153 | } |
| 120 | 154 | } |
test/render-csv.test.ts +44 −1
| @@ -1,6 +1,6 @@ | ||
| 1 | 1 | /** CSV/TSV as a table: the parser, the shape of the page, and the budget. */ |
| 2 | 2 | import { describe, expect, test } from "bun:test"; |
| 3 | import { parseCsv, numericColumns, type Table } from "../src/web/render/csv-parse.ts"; | |
| 3 | import { DETECT_CHARS, detectDelimiter, parseCsv, numericColumns, type Table } from "../src/web/render/csv-parse.ts"; | |
| 4 | 4 | import { COLUMN_CAP, csv, csvJs, isCsvPath, ROW_CAP, sortColumn, sortRows } from "../src/web/render/csv.ts"; |
| 5 | 5 | import { parseJsonl } from "../src/web/render/jsonl-parse.ts"; |
| 6 | 6 | import { fileKind } from "../src/web/render/kinds.ts"; |
| @@ -283,3 +283,46 @@ describe("csv sort: links, windows and bad input", () => { | ||
| 283 | 283 | expect(draw({})).not.toContain("aria-sort"); |
| 284 | 284 | }); |
| 285 | 285 | }); |
| 286 | ||
| 287 | describe("bounded parse", () => { | |
| 288 | const cases: Record<string, string> = { | |
| 289 | quoted: 'a,"b,c",d,e\n1,"2\n3",4,5\n"x""y",,z,w\n', | |
| 290 | crlf: "a,b,c,d\r\n1,2,3,4\r\n5,6,7,8\r\n", | |
| 291 | emptyQuoted: 'a,"",c,""\n"","",,\n1,2,3,4', | |
| 292 | stray: 'a,b"c,d,e\nab"cd,"x",y,z\n1,2,3,4', | |
| 293 | quoteAfterSkip: 'a,b,c,"d,e",f\n1,2,3,"4\n5",6\n', | |
| 294 | }; | |
| 295 | for (const [name, text] of Object.entries(cases)) { | |
| 296 | test(name, () => { | |
| 297 | const full = parseCsv(text) as Table; | |
| 298 | for (const rows of [1, 2, 10]) { | |
| 299 | for (const columns of [1, 2, 3]) { | |
| 300 | const cut = parseCsv(text, { rows, columns }) as Table; | |
| 301 | expect(cut.rows).toEqual(full.rows.slice(0, rows).map((r) => r.slice(0, columns))); | |
| 302 | expect(cut.columns).toBe(full.columns); | |
| 303 | expect(cut.records).toBe(full.records); | |
| 304 | } | |
| 305 | } | |
| 306 | }); | |
| 307 | } | |
| 308 | test("five million cells are counted fast", () => { | |
| 309 | const text = "a,".repeat(5e6); | |
outdated
Passes on the old parser too. Add a timing bound, or a 5e6-cell case with a loose time limit, so it fails without the skip loop. |
||
| 310 | const start = performance.now(); | |
| 311 | const t = parseCsv(text, { columns: COLUMN_CAP }) as Table; | |
| 312 | const ms = performance.now() - start; | |
| 313 | expect(t.columns).toBe(5e6 + 1); | |
| 314 | expect(ms, `took ${ms.toFixed(0)} ms`).toBeLessThan(250); | |
| 315 | }); | |
| 316 | test("the delimiter is read from the first 64 KiB only", () => { | |
| 317 | expect(DETECT_CHARS).toBe(65536); | |
| 318 | const head = "a;b;c" + "x".repeat(DETECT_CHARS); | |
| 319 | expect(detectDelimiter(head + ",,,,,,,,,,")).toBe(";"); | |
| 320 | expect(detectDelimiter("x".repeat(DETECT_CHARS) + ",,,,,")).toBe(","); | |
| 321 | expect(detectDelimiter("x".repeat(DETECT_CHARS) + "\t\t\t")).toBe(","); | |
| 322 | }); | |
| 323 | test("one record of a million cells is counted", () => { | |
| 324 | const t = parseCsv("a,".repeat(1e6), { columns: COLUMN_CAP }) as Table; | |
| 325 | expect(t.columns).toBe(1e6 + 1); | |
| 326 | expect(t.rows[0]!.length).toBe(COLUMN_CAP); | |
| 327 | }); | |
| 328 | }); |
test/render-hostile.test.ts +7 −7
| @@ -36,6 +36,9 @@ import { COLUMN_CAP } from "../src/web/render/csv.ts"; | ||
| 36 | 36 | import type { Blob } from "../src/view/source.ts"; |
| 37 | 37 | import { zip } from "./helpers/zip.ts"; |
| 38 | 38 | |
| 39 | /** Cells in the 10 MB one-record CSV and TSV lines. */ | |
| 40 | const LINE_CELLS = 5_000_000; | |
| 41 | ||
| 39 | 42 | /** The most wall-clock time one hostile render may take, in milliseconds: a guard, not a budget. */ |
| 40 | 43 | const GUARD_MS = 2_000; |
| 41 | 44 | const MB = 1_000_000; |
| @@ -85,9 +88,6 @@ interface Bomb { | ||
| 85 | 88 | readonly holds?: (text: string) => void; |
| 86 | 89 | } |
| 87 | 90 | |
| 88 | /** Cells in the one-record CSV: 1 MB of `a,`. */ | |
| 89 | const CELLS = 500_000; | |
| 90 | ||
| 91 | 91 | const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); |
| 92 | 92 | |
| 93 | 93 | const nested = (n: number, open: string, close: string, root = ""): string => |
| @@ -170,10 +170,10 @@ const BOMBS: readonly Bomb[] = [ | ||
| 170 | 170 | says: new RegExp(escape(TOO_LONG)), |
| 171 | 171 | }, |
| 172 | 172 | { path: "a.kdenlive", body: () => enc(nested(120_000, "<a>", "</a>", "mlt")), says: new RegExp(escape(TOO_LONG)) }, |
| 173 | // CSV: one record of half a million cells (all counted, `COLUMN_CAP` kept), a quote never | |
| 174 | // closed, a 10 MB JSON line. | |
| 175 | { path: "line.csv", body: () => enc("a,".repeat(CELLS - 1)), says: new RegExp(`Showing ${COLUMN_CAP} of ${CELLS.toLocaleString()} columns`) }, | |
| 176 | { path: "line.tsv", body: () => enc("a\t".repeat(CELLS - 1)), says: new RegExp(`Showing ${COLUMN_CAP} of ${CELLS.toLocaleString()} columns`) }, | |
| 173 | // CSV: one record of five million cells (a 10 MB line) (all counted, `COLUMN_CAP` kept), a quote | |
| 174 | // never closed, a 10 MB JSON line. | |
| 175 | { path: "line.csv", body: () => enc("a,".repeat(LINE_CELLS - 1)), says: new RegExp(`Showing ${COLUMN_CAP} of ${LINE_CELLS.toLocaleString()} columns`) }, | |
| 176 | { path: "line.tsv", body: () => enc("a\t".repeat(LINE_CELLS - 1)), says: new RegExp(`Showing ${COLUMN_CAP} of ${LINE_CELLS.toLocaleString()} columns`) }, | |
| 177 | 177 | { path: "quote.csv", body: () => enc(`"${"x".repeat(10 * MB - 2)}`), says: /never closed/ }, |
| 178 | 178 | { path: "line.jsonl", body: () => enc(`{"a":"${"x".repeat(10 * MB - 20)}"}`), says: /csv-view/ }, |
| 179 | 179 | // SVG is drawn by the browser from the media route, in an <img>: the page never parses it. This |
new above
offline
DETECT_BYTES is a new documented behaviour (docs/features/csv-view.md) with no test. Add one where the first delimiter-heavy content sits past 64 KiB. The name says bytes but the code counts UTF-16 units; say 'characters'.