167 lines
5.8 KiB
TypeScript
167 lines
5.8 KiB
TypeScript
/**
|
||
* Reproducible headless benchmark for `readFieldShapes` + `renderFieldShapesMarkdown`.
|
||
* Streams 80,000 fixed-seed synthetic documents (8 allowlisted collections × 10,000 limit)
|
||
* with mixed BSON/JS types, one-level nested objects, and all 5 string pattern classes
|
||
* through an in-memory async-generator fake reader with zero MongoDB or network dependencies.
|
||
*
|
||
* Usage:
|
||
* bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts
|
||
*/
|
||
|
||
import {
|
||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||
FIELD_VALUE_TYPES,
|
||
MAX_FIELD_SHAPE_LIMIT,
|
||
readFieldShapes,
|
||
renderFieldShapesMarkdown,
|
||
STRING_PATTERN_CLASSES,
|
||
type ReadOnlySourceSymbolCursor,
|
||
type ReadOnlySourceSymbolReader,
|
||
type SourceSymbolFindOptions,
|
||
} from '../src/security-master';
|
||
|
||
const DOCS_PER_COLLECTION = MAX_FIELD_SHAPE_LIMIT;
|
||
|
||
function mulberry32(seed: number): () => number {
|
||
let state = seed >>> 0;
|
||
return () => {
|
||
state = (state + 0x6d2b79f5) >>> 0;
|
||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||
};
|
||
}
|
||
|
||
function makeSyntheticDoc(collectionIndex: number, docIndex: number, rng: () => number): Record<string, unknown> {
|
||
const r = rng();
|
||
const day = String((docIndex % 28) + 1).padStart(2, '0');
|
||
const month = String(((docIndex + collectionIndex) % 12) + 1).padStart(2, '0');
|
||
const dateStr = `2025-${month}-${day}`;
|
||
const isoStr = `${dateStr}T14:30:00Z`;
|
||
|
||
const doc: Record<string, unknown> = {
|
||
_id: {
|
||
_bsontype: 'ObjectId',
|
||
toString: () =>
|
||
`${String(collectionIndex).padStart(2, '0')}${String(docIndex).padStart(22, '0')}`,
|
||
},
|
||
symbol: `SYM${String(docIndex % 2000).padStart(4, '0')}`,
|
||
date: r < 0.85 ? dateStr : r < 0.95 ? isoStr : '',
|
||
value:
|
||
r < 0.5
|
||
? { _bsontype: 'Double', toString: () => (10 + (docIndex % 500) * 0.25).toFixed(2) }
|
||
: r < 0.8
|
||
? { _bsontype: 'Int32', toString: () => String(docIndex % 10000) }
|
||
: r < 0.92
|
||
? String((docIndex % 1000) / 10)
|
||
: null,
|
||
active: docIndex % 5 !== 0,
|
||
updatedAt: new Date(1735689600000 + (docIndex % 365) * 86_400_000),
|
||
meta: {
|
||
exchange: docIndex % 2 === 0 ? 'NYSE' : 'TSX',
|
||
version: { _bsontype: 'Int32', toString: () => '2' },
|
||
},
|
||
};
|
||
|
||
if (docIndex % 7 === 0) {
|
||
doc.tags = ['equity', 'na'];
|
||
}
|
||
return doc;
|
||
}
|
||
|
||
function createSyntheticBenchmarkReader(): ReadOnlySourceSymbolReader {
|
||
return {
|
||
isReadOnly(): boolean {
|
||
return true;
|
||
},
|
||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||
collectionName: string,
|
||
_filter?: Record<string, unknown>,
|
||
options?: SourceSymbolFindOptions
|
||
): ReadOnlySourceSymbolCursor<T> {
|
||
const colIdx = FIELD_SHAPE_PROBE_COLLECTIONS.indexOf(
|
||
collectionName as (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]
|
||
);
|
||
const count = Math.min(DOCS_PER_COLLECTION, options?.limit ?? DOCS_PER_COLLECTION);
|
||
const rng = mulberry32(0x5eed108 + (colIdx + 1) * 7919);
|
||
|
||
return {
|
||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||
for (let i = 0; i < count; i++) {
|
||
yield makeSyntheticDoc(colIdx, i, rng) as T;
|
||
}
|
||
},
|
||
async close(): Promise<void> {
|
||
// No-op for in-memory benchmark cursor.
|
||
},
|
||
};
|
||
},
|
||
};
|
||
}
|
||
|
||
async function main(): Promise<void> {
|
||
const reader = createSyntheticBenchmarkReader();
|
||
|
||
if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') {
|
||
Bun.gc(true);
|
||
}
|
||
const heapBefore = process.memoryUsage().heapUsed;
|
||
const startedAt = performance.now();
|
||
|
||
const result = await readFieldShapes(reader, {
|
||
limit: DOCS_PER_COLLECTION,
|
||
batchSize: 2_000,
|
||
});
|
||
const markdown = renderFieldShapesMarkdown(result);
|
||
|
||
const elapsedMs = performance.now() - startedAt;
|
||
const heapAfter = process.memoryUsage().heapUsed;
|
||
const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024);
|
||
|
||
const expectedTotal = FIELD_SHAPE_PROBE_COLLECTIONS.length * DOCS_PER_COLLECTION;
|
||
if (result.totalDocsSampled !== expectedTotal) {
|
||
throw new Error(
|
||
`Unexpected totalDocsSampled=${result.totalDocsSampled} (expected ${expectedTotal})`
|
||
);
|
||
}
|
||
|
||
for (const col of result.collections) {
|
||
for (const field of col.fields) {
|
||
if (field.presentCount + field.missingCount !== col.docCount) {
|
||
throw new Error(`Presence mismatch on ${col.collection}.${field.field}`);
|
||
}
|
||
let typeSum = 0;
|
||
for (const typeName of FIELD_VALUE_TYPES) {
|
||
typeSum += field.typeCounts[typeName];
|
||
}
|
||
if (typeSum !== field.presentCount) {
|
||
throw new Error(`Type sum mismatch on ${col.collection}.${field.field}`);
|
||
}
|
||
if (field.stringStats !== null) {
|
||
let patternSum = 0;
|
||
for (const p of STRING_PATTERN_CLASSES) {
|
||
patternSum += field.stringStats.patterns[p];
|
||
}
|
||
if (patternSum !== field.typeCounts.string) {
|
||
throw new Error(`Pattern sum mismatch on ${col.collection}.${field.field}`);
|
||
}
|
||
}
|
||
if ((field.field === '_id' || field.field.startsWith('_id.')) && field.examples.length > 0) {
|
||
throw new Error(`_id example leaked on ${col.collection}.${field.field}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
const docsPerSec = Math.round(result.totalDocsSampled / (elapsedMs / 1000));
|
||
const lines = [
|
||
'Source field-shapes probe benchmark (in-memory async cursor, zero MongoDB)',
|
||
` Workload: ${result.totalDocsSampled.toLocaleString('en-US')} docs (${FIELD_SHAPE_PROBE_COLLECTIONS.length} collections x ${DOCS_PER_COLLECTION.toLocaleString('en-US')} limit)`,
|
||
` Markdown: ${markdown.length.toLocaleString('en-US')} chars`,
|
||
` Elapsed: ${elapsedMs.toFixed(1)} ms`,
|
||
` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`,
|
||
` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`,
|
||
];
|
||
process.stdout.write(`${lines.join('\n')}\n`);
|
||
}
|
||
|
||
await main();
|