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

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15739-csv-a-field-past-the-kept-columns-is-onl → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/15739-csv-a-field-past-the-kept-columns-is-onl was merged into main as ee85ab0.

Review

Sign in to review this change.
4 files changed +98 −21
docs/features/csv-view.md +1 −1
@@ -5,7 +5,7 @@ row: CSV and TSV as a table
55 # CSV and TSV as a table
66
77 `.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).
99 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.
1010 `?all=1` ("Show all N rows", no JavaScript needed) draws up to 20,000. The header line shows rows × columns and the delimiter.
1111 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 {
2929 readonly delimiter?: Delimiter;
3030 }
3131
32 /** How many characters of the first record the delimiter guess reads. */
33 export const DETECT_CHARS = 64 * 1024;
outdated

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'.

34
3235 /** Each candidate delimiter's count in the first record, quotes respected. */
3336 export function detectDelimiter(text: string): Delimiter {
34 const counts = new Map<string, number>();
37 const counts = [0, 0, 0, 0];
3538 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]!++;
4149 }
4250 let best: Delimiter = ",";
4351 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]!;
4956 }
5057 }
5158 return best;
@@ -75,10 +82,33 @@ export function parseCsv(input: string, limits: Limits = {}): Parsed {
7582 row = [];
7683 fields = 0;
7784 };
85 const dc = delimiter.charCodeAt(0);
7886 let field = "";
87 // True at the first character of a field: only there does a quote open one.
88 let atStart = true;
7989 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 }
80110 const c = text[i]!;
81 if (c === '"' && field === "") {
111 if (c === '"' && atStart) {
82112 // A quoted field runs to its closing quote; "" inside is one quote.
83113 const wanted = keeping() && fields < keepCols;
84114 i++;
@@ -97,14 +127,17 @@ export function parseCsv(input: string, limits: Limits = {}): Parsed {
97127 const after = text[i];
98128 if (after !== undefined && after !== delimiter && after !== "\n" && after !== "\r")
99129 return { error: `Text follows a closing quote on row ${records + 1}.` };
130 atStart = false;
100131 } else if (c === delimiter) {
101132 addField(field);
102133 field = "";
134 atStart = true;
103135 i++;
104136 } else if (c === "\n" || c === "\r") {
105137 addField(field);
106138 field = "";
107139 endRow();
140 atStart = true;
108141 i += c === "\r" && text[i + 1] === "\n" ? 2 : 1;
109142 } else {
110143 // Unquoted run up to the next special character.
@@ -115,6 +148,7 @@ export function parseCsv(input: string, limits: Limits = {}): Parsed {
115148 j++;
116149 }
117150 if (keeping() && fields < keepCols) field += text.slice(i, j);
151 atStart = false;
118152 i = j;
119153 }
120154 }
test/render-csv.test.ts +44 −1
@@ -1,6 +1,6 @@
11 /** CSV/TSV as a table: the parser, the shape of the page, and the budget. */
22 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";
44 import { COLUMN_CAP, csv, csvJs, isCsvPath, ROW_CAP, sortColumn, sortRows } from "../src/web/render/csv.ts";
55 import { parseJsonl } from "../src/web/render/jsonl-parse.ts";
66 import { fileKind } from "../src/web/render/kinds.ts";
@@ -283,3 +283,46 @@ describe("csv sort: links, windows and bad input", () => {
283283 expect(draw({})).not.toContain("aria-sort");
284284 });
285285 });
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";
3636 import type { Blob } from "../src/view/source.ts";
3737 import { zip } from "./helpers/zip.ts";
3838
39 /** Cells in the 10 MB one-record CSV and TSV lines. */
40 const LINE_CELLS = 5_000_000;
41
3942 /** The most wall-clock time one hostile render may take, in milliseconds: a guard, not a budget. */
4043 const GUARD_MS = 2_000;
4144 const MB = 1_000_000;
@@ -85,9 +88,6 @@ interface Bomb {
8588 readonly holds?: (text: string) => void;
8689 }
8790
88 /** Cells in the one-record CSV: 1 MB of `a,`. */
89 const CELLS = 500_000;
90
9191 const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9292
9393 const nested = (n: number, open: string, close: string, root = ""): string =>
@@ -170,10 +170,10 @@ const BOMBS: readonly Bomb[] = [
170170 says: new RegExp(escape(TOO_LONG)),
171171 },
172172 { 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`) },
177177 { path: "quote.csv", body: () => enc(`"${"x".repeat(10 * MB - 2)}`), says: /never closed/ },
178178 { path: "line.jsonl", body: () => enc(`{"a":"${"x".repeat(10 * MB - 20)}"}`), says: /csv-view/ },
179179 // SVG is drawn by the browser from the media route, in an <img>: the page never parses it. This

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs