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
0e9f49a51d
commit
47f8258607
2 changed files with 210 additions and 29 deletions
|
|
@ -296,8 +296,16 @@ function classifyValueType(value: unknown): FieldValueType {
|
|||
return 'object';
|
||||
}
|
||||
|
||||
function isSuppressedExampleField(fieldPath: string): boolean {
|
||||
return fieldPath === '_id' || fieldPath.startsWith('_id.');
|
||||
function escapeFieldSegment(segment: string): string {
|
||||
if (!segment.includes('.') && !segment.includes('\\')) {
|
||||
return segment;
|
||||
}
|
||||
return segment.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
|
||||
}
|
||||
|
||||
function formatFieldPath(parentKey: string, childKey?: string): string {
|
||||
const escapedParent = escapeFieldSegment(parentKey);
|
||||
return childKey === undefined ? escapedParent : `${escapedParent}.${escapeFieldSegment(childKey)}`;
|
||||
}
|
||||
|
||||
function sanitizeAndTruncateExample(raw: string, maxLength: number): string {
|
||||
|
|
@ -432,7 +440,8 @@ class FieldShapeAccumulator {
|
|||
continue;
|
||||
}
|
||||
|
||||
const valueType = this.recordFieldValue(key, value);
|
||||
const suppressExamples = key === '_id';
|
||||
const valueType = this.recordFieldValue(formatFieldPath(key), value, suppressExamples);
|
||||
if (valueType === 'object' && isPlainNestedObject(value)) {
|
||||
const childKeys = Object.keys(value);
|
||||
for (let j = 0; j < childKeys.length; j++) {
|
||||
|
|
@ -444,7 +453,7 @@ class FieldShapeAccumulator {
|
|||
if (childValue === undefined) {
|
||||
continue;
|
||||
}
|
||||
this.recordFieldValue(`${key}.${childKey}`, childValue);
|
||||
this.recordFieldValue(formatFieldPath(key, childKey), childValue, suppressExamples);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -485,7 +494,11 @@ class FieldShapeAccumulator {
|
|||
};
|
||||
}
|
||||
|
||||
private recordFieldValue(fieldPath: string, value: unknown): FieldValueType {
|
||||
private recordFieldValue(
|
||||
fieldPath: string,
|
||||
value: unknown,
|
||||
suppressExamples: boolean
|
||||
): FieldValueType {
|
||||
let acc = this.fields.get(fieldPath);
|
||||
if (acc === undefined) {
|
||||
acc = {
|
||||
|
|
@ -521,7 +534,7 @@ class FieldShapeAccumulator {
|
|||
acc.stringStats.patterns[classifyStringPattern(str)] += 1;
|
||||
}
|
||||
|
||||
if (this.maxExamples > 0 && !isSuppressedExampleField(fieldPath)) {
|
||||
if (this.maxExamples > 0 && !suppressExamples) {
|
||||
const example = extractScalarExample(value, valueType, this.maxExampleLength);
|
||||
if (example !== null) {
|
||||
this.insertExample(acc.examples, example);
|
||||
|
|
@ -670,12 +683,14 @@ async function streamBoundedCollectionIntoAccumulator(
|
|||
}
|
||||
|
||||
let seen = 0;
|
||||
for await (const doc of rawCursor) {
|
||||
if (seen >= limit) {
|
||||
break;
|
||||
if (limit > 0) {
|
||||
for await (const doc of rawCursor) {
|
||||
accumulator.addDocument(doc);
|
||||
seen += 1;
|
||||
if (seen >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
accumulator.addDocument(doc);
|
||||
seen += 1;
|
||||
}
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
|
|
@ -764,12 +779,33 @@ export async function readFieldShapes(
|
|||
};
|
||||
}
|
||||
|
||||
function escapeMarkdownTableCell(value: string): string {
|
||||
return value
|
||||
.replace(/\\/g, '\\\\')
|
||||
.replace(/\|/g, '\\|')
|
||||
.replace(/`/g, '\\`')
|
||||
.replace(/\r?\n/g, ' ');
|
||||
function formatMarkdownCodeCell(value: string): string {
|
||||
const normalized = value.replace(/\r\n|\r|\n/g, ' ');
|
||||
if (normalized.length === 0) {
|
||||
return '<code></code>';
|
||||
}
|
||||
const tableSafe = normalized.replace(/\|/g, '\\|');
|
||||
let maxBacktickRun = 0;
|
||||
let currentRun = 0;
|
||||
for (let i = 0; i < tableSafe.length; i++) {
|
||||
if (tableSafe.charCodeAt(i) === 96) {
|
||||
currentRun += 1;
|
||||
if (currentRun > maxBacktickRun) {
|
||||
maxBacktickRun = currentRun;
|
||||
}
|
||||
} else {
|
||||
currentRun = 0;
|
||||
}
|
||||
}
|
||||
const fence = '`'.repeat(maxBacktickRun + 1);
|
||||
const startsWithBacktick = tableSafe.charCodeAt(0) === 96;
|
||||
const endsWithBacktick = tableSafe.charCodeAt(tableSafe.length - 1) === 96;
|
||||
const startsAndEndsWithSpace =
|
||||
tableSafe.charCodeAt(0) === 32 &&
|
||||
tableSafe.charCodeAt(tableSafe.length - 1) === 32 &&
|
||||
tableSafe.trim().length > 0;
|
||||
const needsPadding = startsWithBacktick || endsWithBacktick || startsAndEndsWithSpace;
|
||||
return needsPadding ? `${fence} ${tableSafe} ${fence}` : `${fence}${tableSafe}${fence}`;
|
||||
}
|
||||
|
||||
function formatTypeCountsCell(typeCounts: FieldValueTypeCounts): string {
|
||||
|
|
@ -802,7 +838,7 @@ function formatExamplesCell(examples: readonly string[]): string {
|
|||
if (examples.length === 0) {
|
||||
return '—';
|
||||
}
|
||||
return examples.map(ex => `\`${escapeMarkdownTableCell(ex)}\``).join(', ');
|
||||
return examples.map(formatMarkdownCodeCell).join(', ');
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -842,7 +878,7 @@ export function renderFieldShapesMarkdown(result: ReadFieldShapesResult): string
|
|||
|
||||
for (const field of sortedFields) {
|
||||
const pct = ((field.presentCount / col.docCount) * 100).toFixed(1);
|
||||
const fieldCell = `\`${escapeMarkdownTableCell(field.field)}\``;
|
||||
const fieldCell = formatMarkdownCodeCell(field.field);
|
||||
const presenceCell = `${pct}% (${field.presentCount}/${col.docCount})`;
|
||||
const typesCell = formatTypeCountsCell(field.typeCounts);
|
||||
const patternsCell = formatStringStatsCell(field.stringStats);
|
||||
|
|
|
|||
|
|
@ -98,6 +98,7 @@ function createFakeReader(
|
|||
readOnly?: boolean;
|
||||
failFindOnCollection?: string;
|
||||
failIterOnCollection?: string;
|
||||
failIterAtIndex?: number;
|
||||
failCloseOnCollection?: string;
|
||||
returnBufferedArrayOnCollection?: string;
|
||||
ignoreLimit?: boolean;
|
||||
|
|
@ -106,9 +107,11 @@ function createFakeReader(
|
|||
reader: ReadOnlySourceSymbolReader;
|
||||
calls: RecordedFindCall[];
|
||||
closedCollections: string[];
|
||||
pullsByCollection: Record<string, number>;
|
||||
} {
|
||||
const calls: RecordedFindCall[] = [];
|
||||
const closedCollections: string[] = [];
|
||||
const pullsByCollection: Record<string, number> = {};
|
||||
const readOnly = opts?.readOnly ?? true;
|
||||
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
|
|
@ -134,11 +137,13 @@ function createFakeReader(
|
|||
opts?.ignoreLimit === true || options?.limit === undefined
|
||||
? sourceDocs.length
|
||||
: Math.min(sourceDocs.length, options.limit);
|
||||
const failAt = opts?.failIterAtIndex ?? 1;
|
||||
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
for (let i = 0; i < maxToYield; i++) {
|
||||
if (opts?.failIterOnCollection === collectionName && i === 1) {
|
||||
pullsByCollection[collectionName] = (pullsByCollection[collectionName] ?? 0) + 1;
|
||||
if (opts?.failIterOnCollection === collectionName && i === failAt) {
|
||||
throw new Error('simulated cursor iteration failure');
|
||||
}
|
||||
yield sourceDocs[i] as T;
|
||||
|
|
@ -154,7 +159,7 @@ function createFakeReader(
|
|||
},
|
||||
};
|
||||
|
||||
return { reader, calls, closedCollections };
|
||||
return { reader, calls, closedCollections, pullsByCollection };
|
||||
}
|
||||
|
||||
describe('source-field-shapes static purity', () => {
|
||||
|
|
@ -259,6 +264,37 @@ describe('summarizeFieldShapes', () => {
|
|||
expect(metaDeep.typeCounts.object).toBe(1);
|
||||
});
|
||||
|
||||
test('keeps literal dotted top-level keys distinct from nested parent.child keys', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{
|
||||
'meta.exchange': 'LITERAL_EXCHANGE',
|
||||
meta: {
|
||||
exchange: 42,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
expect(summary.docCount).toBe(1);
|
||||
|
||||
const literalField = summary.fields.find(f => f.field === 'meta\\.exchange');
|
||||
const nestedField = summary.fields.find(f => f.field === 'meta.exchange');
|
||||
expect(literalField).toBeDefined();
|
||||
expect(nestedField).toBeDefined();
|
||||
|
||||
expect(literalField!.presentCount).toBe(1);
|
||||
expect(literalField!.missingCount).toBe(0);
|
||||
expect(literalField!.typeCounts.string).toBe(1);
|
||||
expect(literalField!.typeCounts.int).toBe(0);
|
||||
expect(literalField!.examples).toEqual(['LITERAL_EXCHANGE']);
|
||||
|
||||
expect(nestedField!.presentCount).toBe(1);
|
||||
expect(nestedField!.missingCount).toBe(0);
|
||||
expect(nestedField!.typeCounts.int).toBe(1);
|
||||
expect(nestedField!.typeCounts.string).toBe(0);
|
||||
expect(nestedField!.examples).toEqual(['42']);
|
||||
});
|
||||
|
||||
test('classifies all five string pattern classes and tracks min/max string length', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{ s: '2024-02-29' }, // valid leap-year ymd (len 10)
|
||||
|
|
@ -367,9 +403,14 @@ describe('readFieldShapes', () => {
|
|||
],
|
||||
};
|
||||
|
||||
const { reader, calls, closedCollections } = createFakeReader(docsByCollection, {
|
||||
ignoreLimit: true,
|
||||
});
|
||||
const { reader, calls, closedCollections, pullsByCollection } = createFakeReader(
|
||||
docsByCollection,
|
||||
{
|
||||
ignoreLimit: true,
|
||||
failIterOnCollection: 'qmDividends',
|
||||
failIterAtIndex: 2,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await readFieldShapes(reader, {
|
||||
collections: ['qmDividends', 'ceoShorts', 'qmDividends'],
|
||||
|
|
@ -389,6 +430,8 @@ describe('readFieldShapes', () => {
|
|||
});
|
||||
}
|
||||
expect(closedCollections).toEqual(['ceoShorts', 'qmDividends']);
|
||||
// Breaks immediately after recording the limit-th doc without pulling a 3rd item
|
||||
expect(pullsByCollection).toEqual({ ceoShorts: 1, qmDividends: 2 });
|
||||
|
||||
// Defensively capped at limit=2 even though fake reader ignored limit
|
||||
expect(result.limit).toBe(2);
|
||||
|
|
@ -494,11 +537,96 @@ 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;
|
||||
}
|
||||
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
return spans;
|
||||
}
|
||||
|
||||
describe('renderFieldShapesMarkdown', () => {
|
||||
test('renders byte-identical Markdown with bounded-sample header, escaping, and empty collection notice', async () => {
|
||||
test('renders byte-identical Markdown with bounded-sample header, valid GFM code spans, and empty collection notice', async () => {
|
||||
const docsA = [
|
||||
{ _id: fakeObjectId('000000000000000000000001'), 'pipe|col': 'val|with`ticks\\slash', dt: '2025-01-02' },
|
||||
{ _id: fakeObjectId('000000000000000000000002'), 'pipe|col': 'plain', dt: '2025-01-03' },
|
||||
{
|
||||
_id: fakeObjectId('000000000000000000000001'),
|
||||
'pipe|col': 'val|with`ticks\\slash',
|
||||
'tick`field\nname': '`leading`',
|
||||
edge: 'double``ticks',
|
||||
dt: '2025-01-02',
|
||||
},
|
||||
{
|
||||
_id: fakeObjectId('000000000000000000000002'),
|
||||
'pipe|col': 'slash\\|pipe',
|
||||
'tick`field\nname': ' spaced ',
|
||||
edge: '',
|
||||
dt: '2025-01-03',
|
||||
},
|
||||
];
|
||||
const docsB = [docsA[1]!, docsA[0]!];
|
||||
|
||||
|
|
@ -518,9 +646,26 @@ describe('renderFieldShapesMarkdown', () => {
|
|||
expect(md1).toContain('bounded sample');
|
||||
expect(md1).toContain('Sample limit per collection:** 500');
|
||||
expect(md1).toContain('Total documents sampled:** 2');
|
||||
expect(md1).toContain('`pipe\\|col`');
|
||||
expect(md1).toContain('`val\\|with\\`ticks\\\\slash`');
|
||||
expect(md1).toContain('_No documents sampled._');
|
||||
|
||||
const tableRows = md1
|
||||
.split('\n')
|
||||
.filter(line => line.startsWith('| ') && !line.startsWith('| Field |') && !line.startsWith('| --- |'));
|
||||
|
||||
const visibleByField = new Map<string, string[]>();
|
||||
for (const row of tableRows) {
|
||||
const cells = splitGfmTableRow(row);
|
||||
expect(cells.length).toBe(5);
|
||||
const parsedField = parseCommonMarkCodeSpans(cells[0]!);
|
||||
expect(parsedField.length).toBe(1);
|
||||
const parsedExamples = cells[4] === '—' ? [] : parseCommonMarkCodeSpans(cells[4]!);
|
||||
visibleByField.set(parsedField[0]!, parsedExamples);
|
||||
}
|
||||
|
||||
expect(visibleByField.get('pipe|col')).toEqual(['slash\\|pipe', 'val|with`ticks\\slash']);
|
||||
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