T-108: M1.2x — data-pipeline: read-only source field-shape probe (field names + value types for the collections tools/curate-etl decodes) with tests and local benchmark
This commit is contained in:
parent
47f8258607
commit
f471c644f5
3 changed files with 121 additions and 78 deletions
|
|
@ -226,6 +226,7 @@ MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@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).
|
||||
|
|
|
|||
|
|
@ -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 `<code>${escaped}</code>`;
|
||||
}
|
||||
|
||||
function formatMarkdownCodeCell(value: string): string {
|
||||
const normalized = value.replace(/\r\n|\r|\n/g, ' ');
|
||||
if (normalized.length === 0) {
|
||||
return '<code></code>';
|
||||
// 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 <code>
|
||||
// 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;
|
||||
|
|
|
|||
|
|
@ -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('<code></code>', i)) {
|
||||
spans.push('');
|
||||
i += '<code></code>'.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 === '<code>') {
|
||||
let inner = '';
|
||||
i += 1;
|
||||
let closed = false;
|
||||
while (i < nodes.length) {
|
||||
const innerNode = nodes[i]!;
|
||||
if (innerNode.type === 'html' && innerNode.value === '</code>') {
|
||||
closed = true;
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
if (innerNode.type !== 'text') {
|
||||
throw new Error(
|
||||
`Unexpected Markdown node "${innerNode.type}" inside <code> element: ${JSON.stringify(innerNode)}`
|
||||
);
|
||||
}
|
||||
inner += decodeHtmlEntities(innerNode.value ?? '');
|
||||
i += 1;
|
||||
}
|
||||
if (!closed) {
|
||||
throw new Error('Unclosed <code> 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_<tag>&',
|
||||
'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<string, string[]>();
|
||||
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_<tag>&',
|
||||
]);
|
||||
expect(visibleByField.get('tick`field name')).toEqual([' spaced ', '`leading`']);
|
||||
expect(visibleByField.get('edge')).toEqual(['', 'double``ticks']);
|
||||
expect(visibleByField.get('_id')).toEqual([]);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue