From f471c644f5e7936509fdc769314be9f54027355a Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 23:23:47 -0500 Subject: [PATCH] =?UTF-8?q?T-108:=20M1.2x=20=E2=80=94=20data-pipeline:=20r?= =?UTF-8?q?ead-only=20source=20field-shape=20probe=20(field=20names=20+=20?= =?UTF-8?q?value=20types=20for=20the=20collections=20`tools/curate-etl`=20?= =?UTF-8?q?decodes)=20with=20tests=20and=20local=20benchmark?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/stock/data-pipeline/README.md | 5 +- .../security-master/source-field-shapes.ts | 26 ++- .../test/source-field-shapes.test.ts | 168 ++++++++++-------- 3 files changed, 121 insertions(+), 78 deletions(-) diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index c9b3ec50..a714a1f5 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -226,6 +226,7 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/sto bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts ``` -- **Recorded baseline (`2026-11-28`, local sandbox, in-memory async cursor fake reader):** +- **Recorded baselines (`2026-11-28`, local sandbox, in-memory async cursor fake reader):** - Workload: `80,000` synthetic docs (`8` collections × `10,000` limit) with mixed BSON/JS types, one-level nested objects, and all five string pattern classes, including `renderFieldShapesMarkdown`. - - Observed throughput: `442,496 docs/s` (`180.8 ms` elapsed, `28.50 MiB` heap delta). + - Initial implementation: `442,496 docs/s` (`180.8 ms` elapsed, `28.50 MiB` heap delta). + - After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting: `365,756 docs/s` (`218.7 ms` elapsed, `27.66 MiB` heap delta). diff --git a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts index cb05c636..da009d68 100644 --- a/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts +++ b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts @@ -779,10 +779,32 @@ export async function readFieldShapes( }; } +function formatHtmlCodeElement(value: string): string { + const escaped = value.replace(/[&<>|\\`*_~[\]!]/g, ch => { + switch (ch) { + case '&': + return '&'; + case '<': + return '<'; + case '>': + return '>'; + case '|': + return '|'; + default: + return `&#${ch.charCodeAt(0)};`; + } + }); + return `${escaped}`; +} + function formatMarkdownCodeCell(value: string): string { const normalized = value.replace(/\r\n|\r|\n/g, ' '); - if (normalized.length === 0) { - return ''; + // Empty spans cannot be written with backtick fences; values containing `\|` + // would become `\\|` under pipe escaping, which GFM/micromark parses as an + // escaped backslash followed by a cell-splitting pipe. Use an HTML + // element with entity-encoded pipes and Markdown metacharacters instead. + if (normalized.length === 0 || normalized.includes('\\|')) { + return formatHtmlCodeElement(normalized); } const tableSafe = normalized.replace(/\|/g, '\\|'); let maxBacktickRun = 0; diff --git a/apps/stock/data-pipeline/test/source-field-shapes.test.ts b/apps/stock/data-pipeline/test/source-field-shapes.test.ts index 8cdce534..47e150e9 100644 --- a/apps/stock/data-pipeline/test/source-field-shapes.test.ts +++ b/apps/stock/data-pipeline/test/source-field-shapes.test.ts @@ -1,6 +1,8 @@ import { describe, expect, test } from 'bun:test'; import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; +import type { ParserOptions } from 'prettier'; +import * as markdownPlugin from 'prettier/plugins/markdown'; import { DEFAULT_FIELD_SHAPE_LIMIT, DEFAULT_MAX_EXAMPLE_LENGTH, @@ -537,77 +539,91 @@ describe('readFieldShapes', () => { }); }); -function splitGfmTableRow(line: string): string[] { - const trimmed = line.trim(); - const inner = trimmed.slice(trimmed.startsWith('|') ? 1 : 0, trimmed.endsWith('|') ? -1 : undefined); - const cells: string[] = []; - let current = ''; - for (let i = 0; i < inner.length; i++) { - if (inner[i] === '\\' && inner[i + 1] === '|') { - current += '|'; - i += 1; - } else if (inner[i] === '|') { - cells.push(current.trim()); - current = ''; - } else { - current += inner[i]; - } - } - cells.push(current.trim()); - return cells; +interface MdastNode { + type: string; + value?: string; + children?: MdastNode[]; } -function parseCommonMarkCodeSpans(cell: string): string[] { - const spans: string[] = []; - let i = 0; - while (i < cell.length) { - if (cell.startsWith('', i)) { - spans.push(''); - i += ''.length; - } else if (cell[i] === '`') { - let fenceLen = 0; - while (i + fenceLen < cell.length && cell[i + fenceLen] === '`') { - fenceLen += 1; - } - const contentStart = i + fenceLen; - let j = contentStart; - let foundEnd = -1; - while (j < cell.length) { - if (cell[j] === '`') { - let run = 0; - while (j + run < cell.length && cell[j + run] === '`') { - run += 1; - } - if (run === fenceLen) { - foundEnd = j; - break; - } - j += run; - } else { - j += 1; - } - } - if (foundEnd === -1) { - throw new Error(`Unclosed CommonMark code span in cell: ${cell}`); - } - let content = cell.slice(contentStart, foundEnd); - if ( - content.length >= 2 && - content.startsWith(' ') && - content.endsWith(' ') && - content.trim().length > 0 - ) { - content = content.slice(1, -1); - } - spans.push(content); - i = foundEnd + fenceLen; - } else if (cell.startsWith(', ', i)) { - i += 2; - } else { - throw new Error(`Unexpected text outside code span in cell "${cell}" at index ${i}`); +function decodeHtmlEntities(text: string): string { + return text.replace(/&(amp|lt|gt|#(\d+));/g, (_, entity: string, code?: string) => { + if (code !== undefined) { + return String.fromCharCode(Number(code)); + } + switch (entity) { + case 'amp': + return '&'; + case 'lt': + return '<'; + case 'gt': + return '>'; + default: + return `&${entity};`; + } + }); +} + +function parseGfmTables(markdown: string): MdastNode[][] { + const ast = markdownPlugin.parsers.markdown.parse( + markdown, + {} as ParserOptions + ) as unknown as MdastNode; + const rows: MdastNode[][] = []; + for (const node of ast.children ?? []) { + if (node.type !== 'table') { + continue; + } + const tableRows = node.children ?? []; + for (let rowIndex = 1; rowIndex < tableRows.length; rowIndex++) { + rows.push(tableRows[rowIndex]?.children ?? []); } } - return spans; + return rows; +} + +function extractGfmCodeCellValues(cell: MdastNode): string[] { + const nodes = cell.children ?? []; + if (nodes.length === 1 && nodes[0]?.type === 'text' && nodes[0].value === '—') { + return []; + } + + const values: string[] = []; + let i = 0; + while (i < nodes.length) { + const node = nodes[i]!; + if (node.type === 'inlineCode') { + values.push(node.value ?? ''); + i += 1; + } else if (node.type === 'html' && node.value === '') { + let inner = ''; + i += 1; + let closed = false; + while (i < nodes.length) { + const innerNode = nodes[i]!; + if (innerNode.type === 'html' && innerNode.value === '') { + closed = true; + i += 1; + break; + } + if (innerNode.type !== 'text') { + throw new Error( + `Unexpected Markdown node "${innerNode.type}" inside element: ${JSON.stringify(innerNode)}` + ); + } + inner += decodeHtmlEntities(innerNode.value ?? ''); + i += 1; + } + if (!closed) { + throw new Error('Unclosed HTML element in GFM table cell'); + } + values.push(inner); + } else if (node.type === 'text' && node.value === ', ') { + i += 1; + } else { + throw new Error(`Unexpected node in GFM code cell: ${JSON.stringify(node)}`); + } + } + return values; } describe('renderFieldShapesMarkdown', () => { @@ -616,6 +632,7 @@ describe('renderFieldShapesMarkdown', () => { { _id: fakeObjectId('000000000000000000000001'), 'pipe|col': 'val|with`ticks\\slash', + 'slash\\|field': 'slash\\|pipe*em*_u_&', 'tick`field\nname': '`leading`', edge: 'double``ticks', dt: '2025-01-02', @@ -623,6 +640,7 @@ describe('renderFieldShapesMarkdown', () => { { _id: fakeObjectId('000000000000000000000002'), 'pipe|col': 'slash\\|pipe', + 'slash\\|field': 'slash\\\\|pipe', 'tick`field\nname': ' spaced ', edge: '', dt: '2025-01-03', @@ -648,21 +666,23 @@ describe('renderFieldShapesMarkdown', () => { expect(md1).toContain('Total documents sampled:** 2'); expect(md1).toContain('_No documents sampled._'); - const tableRows = md1 - .split('\n') - .filter(line => line.startsWith('| ') && !line.startsWith('| Field |') && !line.startsWith('| --- |')); + const tableRows = parseGfmTables(md1); + expect(tableRows.length).toBe(6); const visibleByField = new Map(); - for (const row of tableRows) { - const cells = splitGfmTableRow(row); + for (const cells of tableRows) { expect(cells.length).toBe(5); - const parsedField = parseCommonMarkCodeSpans(cells[0]!); + const parsedField = extractGfmCodeCellValues(cells[0]!); expect(parsedField.length).toBe(1); - const parsedExamples = cells[4] === '—' ? [] : parseCommonMarkCodeSpans(cells[4]!); + const parsedExamples = extractGfmCodeCellValues(cells[4]!); visibleByField.set(parsedField[0]!, parsedExamples); } expect(visibleByField.get('pipe|col')).toEqual(['slash\\|pipe', 'val|with`ticks\\slash']); + expect(visibleByField.get('slash\\\\|field')).toEqual([ + 'slash\\\\|pipe', + 'slash\\|pipe*em*_u_&', + ]); expect(visibleByField.get('tick`field name')).toEqual([' spaced ', '`leading`']); expect(visibleByField.get('edge')).toEqual(['', 'double``ticks']); expect(visibleByField.get('_id')).toEqual([]);