From 0e9f49a51d37c6a5cbba0a37882008f0597e9044 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 23:07:50 -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 | 23 + .../source-field-shapes-benchmark.ts | 167 ++++ .../src/security-master/index.ts | 41 + .../probe-source-field-shapes.ts | 291 ++++++ .../security-master/source-field-shapes.ts | 857 ++++++++++++++++++ .../security-master/source-symbol-readers.ts | 3 + .../test/source-field-shapes.test.ts | 647 +++++++++++++ 7 files changed, 2029 insertions(+) create mode 100644 apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts create mode 100644 apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts create mode 100644 apps/stock/data-pipeline/src/security-master/source-field-shapes.ts create mode 100644 apps/stock/data-pipeline/test/source-field-shapes.test.ts diff --git a/apps/stock/data-pipeline/README.md b/apps/stock/data-pipeline/README.md index 6664a2b0..c9b3ec50 100644 --- a/apps/stock/data-pipeline/README.md +++ b/apps/stock/data-pipeline/README.md @@ -206,3 +206,26 @@ All four files are deterministic and byte-identical for identical inputs (no wal - `conflicts.csv` — Unified deterministic conflict export across Stage A, Stage B, Pass 4, and Pass 6. - `override-template.sql` — Commented SQL template for director-reviewed `override` entries. - `run-stats.json` — Canonical ASCII-key-sorted JSON summary of exchange, reader, security-type, bar-span, composer, and report stats (`pass4Wired: false`). + +## Read-Only Source Field-Shape Probe (`source-field-shapes.ts`) +`apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` and its CLI `probe-source-field-shapes.ts` sample raw MongoDB collections read-only to report exact field names, BSON/JS value types (`string`, `int`, `double`, `bool`, `date`, `null`, `objectId`, `array`, `object`, `other`), one-level nested `parent.child` keys, string pattern classes (`ymd`, `isoDatetime`, `numeric`, `emptyOrWhitespace`, `other`), and bounded sanitized examples (never emitted for `_id` / `_id.*`). + +- **Bounded read-only contract:** Initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`), refuses non-read-only readers before issuing any query, and runs strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` (default `limit = 1,000`, max `10,000`) over allowlisted collections (`ceoShorts`, `qmSplits`, `qmDividends`, `qmFilings`, `qmEarnings`, `qmPrices`, `eodPrices`, `teMarketData`) — no aggregations, no `$sample`, no writes, and no index operations. +- **Host live-run command (read-only QA MongoDB):** + +```bash +MONGODB_READ_URI="mongodb://studio_stock_bot_read:@localhost:27017/stock?authSource=stock" \ + bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts \ + --out ./tmp/source-field-shapes.md \ + --limit 1000 +``` + +- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 80,000-doc streaming benchmark (`8` collections × `10,000` limit) with: + +```bash +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):** + - 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). diff --git a/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts b/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts new file mode 100644 index 00000000..ddb6ba75 --- /dev/null +++ b/apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts @@ -0,0 +1,167 @@ +/** + * 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 { + 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 = { + _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 = Record>( + collectionName: string, + _filter?: Record, + options?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor { + 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 { + for (let i = 0; i < count; i++) { + yield makeSyntheticDoc(colIdx, i, rng) as T; + } + }, + async close(): Promise { + // No-op for in-memory benchmark cursor. + }, + }; + }, + }; +} + +async function main(): Promise { + 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(); diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 7dbcd44c..7cefbc51 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -265,6 +265,47 @@ export { type UnknownSecurityTypeCount, } from './security-type'; +export { + parseProbeSourceFieldShapesArgs, + PROBE_SOURCE_FIELD_SHAPES_USAGE, + runCli as runProbeSourceFieldShapesCli, + runSourceFieldShapesProbe, + type ParsedProbeSourceFieldShapesArgs, + type RunSourceFieldShapesProbeDeps, + type RunSourceFieldShapesProbeOptions, + type RunSourceFieldShapesProbeOutput, +} from './probe-source-field-shapes'; + +export { + DEFAULT_FIELD_SHAPE_LIMIT, + DEFAULT_MAX_EXAMPLE_LENGTH, + DEFAULT_MAX_EXAMPLES, + FIELD_SHAPE_PROBE_COLLECTIONS, + FIELD_VALUE_TYPES, + isFieldShapeProbeCollection, + MAX_EXAMPLE_LENGTH_CAP, + MAX_EXAMPLES_CAP, + MAX_FIELD_SHAPE_LIMIT, + normalizeProbeCollections, + readFieldShapes, + renderFieldShapesMarkdown, + STRING_PATTERN_CLASSES, + summarizeFieldShapes, + UnknownProbeCollectionError, + type CollectionFieldShapesProbeResult, + type CollectionFieldShapesSummary, + type FieldShapeProbeCollection, + type FieldShapeSummary, + type FieldStringStats, + type FieldValueType, + type FieldValueTypeCounts, + type ReadFieldShapesOptions, + type ReadFieldShapesResult, + type StringPatternClass, + type StringPatternCounts, + type SummarizeFieldShapesOptions, +} from './source-field-shapes'; + export { adaptCeoSymbolDoc, adaptEodSymbolChangeDoc, diff --git a/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts new file mode 100644 index 00000000..b3fbcfca --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts @@ -0,0 +1,291 @@ +import { mkdir, writeFile } from 'node:fs/promises'; +import { dirname } from 'node:path'; +import { getLogger } from '@stock-bot/logger'; +import { MongoDBClient } from '@stock-bot/mongodb'; +import { initializeStockConfig } from '@stock-bot/stock-config'; +import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed'; +import { + DEFAULT_FIELD_SHAPE_LIMIT, + FIELD_SHAPE_PROBE_COLLECTIONS, + MAX_FIELD_SHAPE_LIMIT, + normalizeProbeCollections, + readFieldShapes, + renderFieldShapesMarkdown, + type FieldShapeProbeCollection, + type ReadFieldShapesResult, +} from './source-field-shapes'; +import { + createReadOnlyMongoSourceSymbolReader, + type ReadOnlyMongoCollectionClient, +} from './source-symbol-readers'; + +export const PROBE_SOURCE_FIELD_SHAPES_USAGE = [ + 'Usage: bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --out [--limit ] [--collections ] [--help]', + '', + 'Options:', + ' --out Required. Output Markdown report file path.', + ` --limit Optional. Max documents sampled per collection (1..${MAX_FIELD_SHAPE_LIMIT}, default: ${DEFAULT_FIELD_SHAPE_LIMIT}).`, + ` --collections Optional. Comma-separated allowlisted collections (default: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(',')}).`, + ' --help Show this help message and exit.', +].join('\n'); + +export type ParsedProbeSourceFieldShapesArgs = + | { readonly help: true } + | { + readonly help: false; + readonly outPath: string; + readonly limit: number; + readonly collections: readonly FieldShapeProbeCollection[]; + }; + +export interface RunSourceFieldShapesProbeDeps { + readonly mongoCollectionClient: ReadOnlyMongoCollectionClient; + readonly closeMongo?: () => Promise | void; + readonly writeFile?: (filePath: string, content: string) => Promise | void; + readonly writeStdout?: (text: string) => void; +} + +export interface RunSourceFieldShapesProbeOptions { + readonly outPath: string; + readonly limit?: number; + readonly collections?: readonly string[]; + readonly maxExamples?: number; + readonly maxExampleLength?: number; + readonly batchSize?: number; +} + +export interface RunSourceFieldShapesProbeOutput { + readonly outPath: string; + readonly result: ReadFieldShapesResult; + readonly markdown: string; + readonly summary: string; +} + +const STRICT_INT_PATTERN = /^-?\d+$/; + +function usageError(message: string): Error { + return new Error(`${message}\n\n${PROBE_SOURCE_FIELD_SHAPES_USAGE}`); +} + +function parseLimitArg(raw: string): number { + if (!STRICT_INT_PATTERN.test(raw)) { + throw usageError( + `Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}` + ); + } + const parsed = Number(raw); + if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_FIELD_SHAPE_LIMIT) { + throw usageError( + `Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}` + ); + } + return parsed; +} + +function parseCollectionsArg(raw: string): FieldShapeProbeCollection[] { + const parts = raw + .split(',') + .map(part => part.trim()) + .filter(part => part.length > 0); + if (parts.length === 0) { + throw usageError('Missing value for --collections'); + } + return normalizeProbeCollections(parts); +} + +export function parseProbeSourceFieldShapesArgs( + argv: readonly string[] +): ParsedProbeSourceFieldShapesArgs { + let help = false; + let outPath: string | undefined; + let limit = DEFAULT_FIELD_SHAPE_LIMIT; + let collectionsRaw: string[] | undefined; + + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + if (arg === '--help') { + help = true; + continue; + } + if (arg === '--out') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --out'); + } + outPath = value.trim(); + i += 1; + continue; + } + if (arg?.startsWith('--out=')) { + const value = arg.slice('--out='.length).trim(); + if (value.length === 0) { + throw usageError('Missing value for --out'); + } + outPath = value; + continue; + } + if (arg === '--limit') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --limit'); + } + limit = parseLimitArg(value.trim()); + i += 1; + continue; + } + if (arg?.startsWith('--limit=')) { + const value = arg.slice('--limit='.length).trim(); + if (value.length === 0) { + throw usageError('Missing value for --limit'); + } + limit = parseLimitArg(value); + continue; + } + if (arg === '--collections') { + const value = argv[i + 1]; + if (!value || value.trim().length === 0 || value.startsWith('--')) { + throw usageError('Missing value for --collections'); + } + const parsed = parseCollectionsArg(value); + collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed; + i += 1; + continue; + } + if (arg?.startsWith('--collections=')) { + const value = arg.slice('--collections='.length).trim(); + if (value.length === 0) { + throw usageError('Missing value for --collections'); + } + const parsed = parseCollectionsArg(value); + collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed; + continue; + } + throw usageError(`Unknown argument: ${String(arg)}`); + } + + if (help) { + return { help: true }; + } + + if (outPath === undefined || outPath.trim().length === 0) { + throw usageError('Missing required argument: --out '); + } + + const collections = normalizeProbeCollections(collectionsRaw); + return { + help: false, + outPath, + limit, + collections, + }; +} + +async function defaultWriteFile(filePath: string, content: string): Promise { + await mkdir(dirname(filePath), { recursive: true }); + await writeFile(filePath, content, 'utf8'); +} + +export async function runSourceFieldShapesProbe( + deps: RunSourceFieldShapesProbeDeps, + options: RunSourceFieldShapesProbeOptions +): Promise { + let primaryError: unknown = undefined; + let hasPrimaryError = false; + let output: RunSourceFieldShapesProbeOutput | undefined; + + try { + if (typeof options.outPath !== 'string' || options.outPath.trim().length === 0) { + throw new Error('outPath must be a non-empty string'); + } + + const reader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient); + const result = await readFieldShapes(reader, { + limit: options.limit, + collections: options.collections, + maxExamples: options.maxExamples, + maxExampleLength: options.maxExampleLength, + batchSize: options.batchSize, + }); + + const markdown = renderFieldShapesMarkdown(result); + const writer = deps.writeFile ?? defaultWriteFile; + await writer(options.outPath, markdown); + + const summary = [ + `Source field-shape probe complete (limit=${result.limit})`, + ` Collections: ${result.collections.length} | Documents sampled: ${result.totalDocsSampled}`, + ` Report written: ${options.outPath}`, + ].join('\n'); + + output = { + outPath: options.outPath, + result, + markdown, + summary: `${summary}\n`, + }; + } catch (error) { + primaryError = error; + hasPrimaryError = true; + } finally { + if (deps.closeMongo) { + try { + await deps.closeMongo(); + } catch (closeError) { + if (!hasPrimaryError) { + primaryError = closeError; + hasPrimaryError = true; + } + } + } + } + + if (hasPrimaryError) { + throw primaryError; + } + if (output === undefined) { + throw new Error('Source field-shape probe completed without producing output'); + } + + const writeStdout = + deps.writeStdout ?? + ((text: string) => { + process.stdout.write(text); + }); + writeStdout(output.summary); + + return output; +} + +export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise { + const parsed = parseProbeSourceFieldShapesArgs(argv); + if (parsed.help) { + process.stdout.write(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`); + return; + } + + const logger = getLogger('source-field-shapes-probe'); + const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true }); + const mongoConfig = resolveReadOnlyMongoClientConfig(config); + const mongo = new MongoDBClient(mongoConfig, logger); + + await mongo.connect(); + await runSourceFieldShapesProbe( + { + mongoCollectionClient: mongo, + closeMongo: () => mongo.disconnect(), + }, + { + outPath: parsed.outPath, + limit: parsed.limit, + collections: parsed.collections, + } + ); +} + +if (import.meta.main) { + runCli().catch(error => { + const message = error instanceof Error ? error.message : String(error); + process.stderr.write(`Error: ${message}\n`); + process.exit(1); + }); +} 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 new file mode 100644 index 00000000..16f271ca --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/source-field-shapes.ts @@ -0,0 +1,857 @@ +import { compareAscii } from './exchange-pass1'; +import type { + ReadOnlySourceSymbolCursor, + ReadOnlySourceSymbolReader, + SourceSymbolFindOptions, +} from './source-symbol-readers'; + +export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([ + 'ceoShorts', + 'qmSplits', + 'qmDividends', + 'qmFilings', + 'qmEarnings', + 'qmPrices', + 'eodPrices', + 'teMarketData', +] as const); + +export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]; + +export const FIELD_VALUE_TYPES = Object.freeze([ + 'string', + 'int', + 'double', + 'bool', + 'date', + 'null', + 'objectId', + 'array', + 'object', + 'other', +] as const); + +export type FieldValueType = (typeof FIELD_VALUE_TYPES)[number]; + +export const STRING_PATTERN_CLASSES = Object.freeze([ + 'ymd', + 'isoDatetime', + 'numeric', + 'emptyOrWhitespace', + 'other', +] as const); + +export type StringPatternClass = (typeof STRING_PATTERN_CLASSES)[number]; + +export const DEFAULT_FIELD_SHAPE_LIMIT = 1_000; +export const MAX_FIELD_SHAPE_LIMIT = 10_000; +export const DEFAULT_MAX_EXAMPLES = 3; +export const MAX_EXAMPLES_CAP = 10; +export const DEFAULT_MAX_EXAMPLE_LENGTH = 48; +export const MAX_EXAMPLE_LENGTH_CAP = 120; + +const ALLOWED_PROBE_COLLECTION_SET: ReadonlySet = new Set( + FIELD_SHAPE_PROBE_COLLECTIONS +); + +export class UnknownProbeCollectionError extends Error { + readonly collectionName: string; + readonly allowedCollections: readonly FieldShapeProbeCollection[]; + + constructor(collectionName: string) { + super( + `Unknown probe collection "${collectionName}". Allowed collections: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(', ')}` + ); + this.name = 'UnknownProbeCollectionError'; + this.collectionName = collectionName; + this.allowedCollections = FIELD_SHAPE_PROBE_COLLECTIONS; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +export type FieldValueTypeCounts = Record; +export type StringPatternCounts = Record; + +export interface FieldStringStats { + minLength: number; + maxLength: number; + patterns: StringPatternCounts; +} + +export interface FieldShapeSummary { + field: string; + presentCount: number; + missingCount: number; + typeCounts: FieldValueTypeCounts; + stringStats: FieldStringStats | null; + examples: string[]; +} + +export interface SummarizeFieldShapesOptions { + readonly maxExamples?: number; + readonly maxExampleLength?: number; +} + +export interface CollectionFieldShapesSummary { + docCount: number; + fields: FieldShapeSummary[]; +} + +export interface ReadFieldShapesOptions extends SummarizeFieldShapesOptions { + readonly collections?: readonly string[]; + readonly limit?: number; + readonly batchSize?: number; +} + +export interface CollectionFieldShapesProbeResult extends CollectionFieldShapesSummary { + collection: FieldShapeProbeCollection; +} + +export interface ReadFieldShapesResult { + limit: number; + maxExamples: number; + maxExampleLength: number; + totalDocsSampled: number; + collections: CollectionFieldShapesProbeResult[]; +} + +const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/; +const STRICT_ISO_DATETIME_PATTERN = + /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):?(\d{2}))?$/; +const NUMERIC_STRING_PATTERN = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function isValidCalendarDate(year: number, month: number, day: number): boolean { + if (year < 1 || year > 9999 || month < 1 || month > 12) { + return false; + } + const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0); + return day >= 1 && day <= maxDay; +} + +function isValidYmd(value: string): boolean { + if (!EXACT_YMD_PATTERN.test(value)) { + return false; + } + const year = + (value.charCodeAt(0) - 48) * 1000 + + (value.charCodeAt(1) - 48) * 100 + + (value.charCodeAt(2) - 48) * 10 + + (value.charCodeAt(3) - 48); + const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48); + const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48); + return isValidCalendarDate(year, month, day); +} + +function isValidIsoDatetime(value: string): boolean { + const match = STRICT_ISO_DATETIME_PATTERN.exec(value); + if (match === null) { + return false; + } + const year = Number(match[1]); + const month = Number(match[2]); + const day = Number(match[3]); + const hour = Number(match[4]); + const minute = Number(match[5]); + const second = Number(match[6]); + + if (!isValidCalendarDate(year, month, day)) { + return false; + } + if (hour > 23 || minute > 59 || second > 59) { + return false; + } + if (match[7] !== undefined) { + const tzHour = Number(match[8]); + const tzMinute = Number(match[9]); + if (tzHour > 23 || tzMinute > 59) { + return false; + } + } + return true; +} + +function classifyStringPattern(value: string): StringPatternClass { + if (value.length === 0 || value.trim().length === 0) { + return 'emptyOrWhitespace'; + } + if (value.length === 10 && isValidYmd(value)) { + return 'ymd'; + } + if (value.length >= 19 && value.charCodeAt(10) === 84 && isValidIsoDatetime(value)) { + return 'isoDatetime'; + } + if (NUMERIC_STRING_PATTERN.test(value)) { + return 'numeric'; + } + return 'other'; +} + +function createEmptyTypeCounts(): FieldValueTypeCounts { + return { + string: 0, + int: 0, + double: 0, + bool: 0, + date: 0, + null: 0, + objectId: 0, + array: 0, + object: 0, + other: 0, + }; +} + +function createEmptyStringPatternCounts(): StringPatternCounts { + return { + ymd: 0, + isoDatetime: 0, + numeric: 0, + emptyOrWhitespace: 0, + other: 0, + }; +} + +function isNonPlainBuiltInObject(value: object): boolean { + return ( + value instanceof Date || + Array.isArray(value) || + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + value instanceof RegExp || + value instanceof Map || + value instanceof Set + ); +} + +function getBsonTypeTag(value: object): string | null { + const tag = (value as { _bsontype?: unknown })._bsontype; + return typeof tag === 'string' && tag.length > 0 ? tag : null; +} + +function isPlainNestedObject(value: unknown): value is Record { + if (value === null || typeof value !== 'object') { + return false; + } + if (isNonPlainBuiltInObject(value)) { + return false; + } + if (getBsonTypeTag(value) !== null) { + return false; + } + return true; +} + +function classifyValueType(value: unknown): FieldValueType { + if (value === null) { + return 'null'; + } + const primitiveType = typeof value; + if (primitiveType === 'string') { + return 'string'; + } + if (primitiveType === 'boolean') { + return 'bool'; + } + if (primitiveType === 'number') { + return Number.isInteger(value) ? 'int' : 'double'; + } + if (primitiveType === 'bigint') { + return 'int'; + } + if (primitiveType !== 'object') { + return 'other'; + } + + const obj = value as object; + if (obj instanceof Date) { + return 'date'; + } + if (Array.isArray(obj)) { + return 'array'; + } + + const bsonTag = getBsonTypeTag(obj); + if (bsonTag !== null) { + if (bsonTag === 'Int32' || bsonTag === 'Long') { + return 'int'; + } + if (bsonTag === 'Double') { + return 'double'; + } + if (bsonTag === 'ObjectId' || bsonTag === 'ObjectID') { + return 'objectId'; + } + return 'other'; + } + + if (isNonPlainBuiltInObject(obj)) { + return 'other'; + } + + return 'object'; +} + +function isSuppressedExampleField(fieldPath: string): boolean { + return fieldPath === '_id' || fieldPath.startsWith('_id.'); +} + +function sanitizeAndTruncateExample(raw: string, maxLength: number): string { + let cleaned = ''; + for (let i = 0; i < raw.length; i++) { + const code = raw.charCodeAt(i); + if (code === 9 || code === 10 || code === 13) { + cleaned += ' '; + } else if (code >= 32 && code !== 127) { + cleaned += raw[i]; + } + } + if (cleaned.length <= maxLength) { + return cleaned; + } + if (maxLength <= 3) { + return cleaned.slice(0, maxLength); + } + return `${cleaned.slice(0, maxLength - 3)}...`; +} + +function extractScalarExample( + value: unknown, + valueType: FieldValueType, + maxExampleLength: number +): string | null { + if (valueType === 'null' || valueType === 'array' || valueType === 'object') { + return null; + } + + let raw: string | null = null; + if (valueType === 'string') { + raw = value as string; + } else if (valueType === 'bool') { + raw = (value as boolean) ? 'true' : 'false'; + } else if (valueType === 'int' || valueType === 'double') { + if (typeof value === 'number' || typeof value === 'bigint') { + raw = String(value); + } else if (value !== null && typeof value === 'object') { + raw = String(value); + } + } else if (valueType === 'date' && value instanceof Date) { + raw = Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString(); + } else if (valueType === 'objectId') { + raw = String(value); + } else if (valueType === 'other' && value !== null && typeof value === 'object') { + const bsonTag = getBsonTypeTag(value); + if (bsonTag === 'Decimal128' || bsonTag === 'UUID') { + raw = String(value); + } + } + + if (raw === null) { + return null; + } + return sanitizeAndTruncateExample(raw, maxExampleLength); +} + +function validateBoundedInt(value: unknown, name: string, min: number, max: number): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) { + throw new RangeError(`${name} must be an integer between ${min} and ${max}, received ${String(value)}`); + } + return value; +} + +function validatePositiveSafeInt(value: unknown, name: string): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`); + } + return value; +} + +function resolveSummarizeOptions(options?: SummarizeFieldShapesOptions): { + maxExamples: number; + maxExampleLength: number; +} { + if (options !== undefined && (options === null || typeof options !== 'object')) { + throw new TypeError('options must be an object'); + } + const maxExamples = + options?.maxExamples !== undefined + ? validateBoundedInt(options.maxExamples, 'options.maxExamples', 0, MAX_EXAMPLES_CAP) + : DEFAULT_MAX_EXAMPLES; + const maxExampleLength = + options?.maxExampleLength !== undefined + ? validateBoundedInt( + options.maxExampleLength, + 'options.maxExampleLength', + 1, + MAX_EXAMPLE_LENGTH_CAP + ) + : DEFAULT_MAX_EXAMPLE_LENGTH; + return { maxExamples, maxExampleLength }; +} + +interface MutableFieldAccumulator { + presentCount: number; + typeCounts: FieldValueTypeCounts; + stringStats: FieldStringStats | null; + examples: string[]; +} + +/** + * Streaming, order-independent field-shape accumulator shared by `summarizeFieldShapes` + * and `readFieldShapes`. Keeps O(`maxExamples`) distinct ASCII-smallest examples per field. + */ +class FieldShapeAccumulator { + private readonly maxExamples: number; + private readonly maxExampleLength: number; + private readonly fields = new Map(); + private docCount = 0; + + constructor(maxExamples: number, maxExampleLength: number) { + this.maxExamples = maxExamples; + this.maxExampleLength = maxExampleLength; + } + + addDocument(doc: unknown): void { + this.docCount += 1; + if (!isPlainNestedObject(doc)) { + return; + } + + const keys = Object.keys(doc); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + if (key === undefined) { + continue; + } + const value = doc[key]; + if (value === undefined) { + continue; + } + + const valueType = this.recordFieldValue(key, value); + if (valueType === 'object' && isPlainNestedObject(value)) { + const childKeys = Object.keys(value); + for (let j = 0; j < childKeys.length; j++) { + const childKey = childKeys[j]; + if (childKey === undefined) { + continue; + } + const childValue = value[childKey]; + if (childValue === undefined) { + continue; + } + this.recordFieldValue(`${key}.${childKey}`, childValue); + } + } + } + } + + finalize(): CollectionFieldShapesSummary { + const sortedNames = Array.from(this.fields.keys()).sort(compareAscii); + const summaries: FieldShapeSummary[] = []; + for (let i = 0; i < sortedNames.length; i++) { + const fieldName = sortedNames[i]; + if (fieldName === undefined) { + continue; + } + const acc = this.fields.get(fieldName); + if (acc === undefined) { + continue; + } + summaries.push({ + field: fieldName, + presentCount: acc.presentCount, + missingCount: this.docCount - acc.presentCount, + typeCounts: { ...acc.typeCounts }, + stringStats: + acc.stringStats === null + ? null + : { + minLength: acc.stringStats.minLength, + maxLength: acc.stringStats.maxLength, + patterns: { ...acc.stringStats.patterns }, + }, + examples: [...acc.examples], + }); + } + + return { + docCount: this.docCount, + fields: summaries, + }; + } + + private recordFieldValue(fieldPath: string, value: unknown): FieldValueType { + let acc = this.fields.get(fieldPath); + if (acc === undefined) { + acc = { + presentCount: 0, + typeCounts: createEmptyTypeCounts(), + stringStats: null, + examples: [], + }; + this.fields.set(fieldPath, acc); + } + + const valueType = classifyValueType(value); + acc.presentCount += 1; + acc.typeCounts[valueType] += 1; + + if (valueType === 'string') { + const str = value as string; + const len = str.length; + if (acc.stringStats === null) { + acc.stringStats = { + minLength: len, + maxLength: len, + patterns: createEmptyStringPatternCounts(), + }; + } else { + if (len < acc.stringStats.minLength) { + acc.stringStats.minLength = len; + } + if (len > acc.stringStats.maxLength) { + acc.stringStats.maxLength = len; + } + } + acc.stringStats.patterns[classifyStringPattern(str)] += 1; + } + + if (this.maxExamples > 0 && !isSuppressedExampleField(fieldPath)) { + const example = extractScalarExample(value, valueType, this.maxExampleLength); + if (example !== null) { + this.insertExample(acc.examples, example); + } + } + + return valueType; + } + + private insertExample(examples: string[], candidate: string): void { + const len = examples.length; + const last = len > 0 ? examples[len - 1] : undefined; + if (len === this.maxExamples && last !== undefined && compareAscii(candidate, last) >= 0) { + return; + } + + let insertAt = len; + for (let i = 0; i < len; i++) { + const existing = examples[i]; + if (existing === undefined) { + continue; + } + const cmp = compareAscii(candidate, existing); + if (cmp === 0) { + return; + } + if (cmp < 0) { + insertAt = i; + break; + } + } + + examples.splice(insertAt, 0, candidate); + if (examples.length > this.maxExamples) { + examples.pop(); + } + } +} + +/** + * Pure, deterministic summarizer for field names, BSON/JS value types, string patterns, + * and bounded sanitized examples across an iterable of documents from one collection. + */ +export function summarizeFieldShapes( + docs: Iterable>, + options?: SummarizeFieldShapesOptions +): CollectionFieldShapesSummary { + if ( + docs === null || + docs === undefined || + typeof (docs as unknown as Record)[Symbol.iterator] !== 'function' + ) { + throw new TypeError('docs must be an Iterable of document objects'); + } + const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options); + const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength); + for (const doc of docs) { + accumulator.addDocument(doc); + } + return accumulator.finalize(); +} + +export function isFieldShapeProbeCollection(value: string): value is FieldShapeProbeCollection { + return ALLOWED_PROBE_COLLECTION_SET.has(value); +} + +export function normalizeProbeCollections( + collections?: readonly string[] +): FieldShapeProbeCollection[] { + const source = collections === undefined ? FIELD_SHAPE_PROBE_COLLECTIONS : collections; + if (!Array.isArray(source) || source.length === 0) { + throw new RangeError('collections must be a non-empty array of allowed probe collection names'); + } + const unique = new Set(); + for (let i = 0; i < source.length; i++) { + const name = source[i]; + if (typeof name !== 'string' || !isFieldShapeProbeCollection(name)) { + throw new UnknownProbeCollectionError(String(name)); + } + unique.add(name); + } + return Array.from(unique).sort(compareAscii); +} + +function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void { + if ( + reader === null || + reader === undefined || + typeof reader !== 'object' || + typeof reader.isReadOnly !== 'function' || + typeof reader.find !== 'function' || + reader.isReadOnly() !== true + ) { + throw new Error( + 'Source field-shape probe requires a read-only MongoDB reader (isReadOnly() must be true)' + ); + } +} + +function isAsyncIterable(value: unknown): value is AsyncIterable { + return ( + value !== null && + (typeof value === 'object' || typeof value === 'function') && + typeof (value as Record)[Symbol.asyncIterator] === 'function' + ); +} + +function wrapCollectionReadError(collectionName: string, error: unknown): Error { + const detail = error instanceof Error ? error.message : String(error); + const message = detail.includes(collectionName) + ? detail + : `Failed reading collection "${collectionName}": ${detail}`; + return new Error(message, { cause: error }); +} + +async function streamBoundedCollectionIntoAccumulator( + reader: ReadOnlySourceSymbolReader, + collectionName: FieldShapeProbeCollection, + limit: number, + findOptions: SourceSymbolFindOptions, + accumulator: FieldShapeAccumulator +): Promise { + assertReadOnlyReader(reader); + let closableHandle: Pick>, 'close'> | null = + null; + let primaryError: unknown = undefined; + let hasPrimaryError = false; + let isInvalidCursorError = false; + + try { + const rawCursor = await reader.find>(collectionName, {}, findOptions); + if ( + rawCursor !== null && + (typeof rawCursor === 'object' || typeof rawCursor === 'function') + ) { + closableHandle = rawCursor as Pick< + ReadOnlySourceSymbolCursor>, + 'close' + >; + } + if (Array.isArray(rawCursor) || !isAsyncIterable>(rawCursor)) { + isInvalidCursorError = true; + throw new TypeError( + `Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)` + ); + } + + let seen = 0; + for await (const doc of rawCursor) { + if (seen >= limit) { + break; + } + accumulator.addDocument(doc); + seen += 1; + } + } catch (error) { + primaryError = error; + hasPrimaryError = true; + } finally { + if (closableHandle !== null && typeof closableHandle.close === 'function') { + try { + await closableHandle.close(); + } catch (closeError) { + if (!hasPrimaryError) { + primaryError = closeError; + hasPrimaryError = true; + } + } + } + } + + if (hasPrimaryError) { + if (isInvalidCursorError) { + throw primaryError; + } + throw wrapCollectionReadError(collectionName, primaryError); + } +} + +/** + * Bounded, read-only MongoDB field-shape probe over allowlisted source collections. + * Issues strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` + * with zero aggregations, `$sample`, writes, or index operations. + */ +export async function readFieldShapes( + reader: ReadOnlySourceSymbolReader, + options?: ReadFieldShapesOptions +): Promise { + assertReadOnlyReader(reader); + + if (options !== undefined && (options === null || typeof options !== 'object')) { + throw new TypeError('options must be an object'); + } + + const limit = + options?.limit !== undefined + ? validateBoundedInt(options.limit, 'options.limit', 1, MAX_FIELD_SHAPE_LIMIT) + : DEFAULT_FIELD_SHAPE_LIMIT; + const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options); + const batchSize = + options?.batchSize !== undefined + ? validatePositiveSafeInt(options.batchSize, 'options.batchSize') + : undefined; + const collections = normalizeProbeCollections(options?.collections); + + const findOptions: SourceSymbolFindOptions = { + limit, + promoteValues: false, + promoteLongs: false, + ...(batchSize !== undefined ? { batchSize } : {}), + }; + + const results: CollectionFieldShapesProbeResult[] = []; + let totalDocsSampled = 0; + + for (const collection of collections) { + const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength); + await streamBoundedCollectionIntoAccumulator( + reader, + collection, + limit, + findOptions, + accumulator + ); + const summary = accumulator.finalize(); + totalDocsSampled += summary.docCount; + results.push({ + collection, + docCount: summary.docCount, + fields: summary.fields, + }); + } + + return { + limit, + maxExamples, + maxExampleLength, + totalDocsSampled, + collections: results, + }; +} + +function escapeMarkdownTableCell(value: string): string { + return value + .replace(/\\/g, '\\\\') + .replace(/\|/g, '\\|') + .replace(/`/g, '\\`') + .replace(/\r?\n/g, ' '); +} + +function formatTypeCountsCell(typeCounts: FieldValueTypeCounts): string { + const parts: string[] = []; + for (const typeName of FIELD_VALUE_TYPES) { + const count = typeCounts[typeName]; + if (count > 0) { + parts.push(`${typeName}: ${count}`); + } + } + return parts.length > 0 ? parts.join(', ') : '—'; +} + +function formatStringStatsCell(stringStats: FieldStringStats | null): string { + if (stringStats === null) { + return '—'; + } + const parts: string[] = []; + for (const pattern of STRING_PATTERN_CLASSES) { + const count = stringStats.patterns[pattern]; + if (count > 0) { + parts.push(`${pattern}: ${count}`); + } + } + const patternText = parts.length > 0 ? parts.join(', ') : 'none'; + return `${patternText} (len ${stringStats.minLength}..${stringStats.maxLength})`; +} + +function formatExamplesCell(examples: readonly string[]): string { + if (examples.length === 0) { + return '—'; + } + return examples.map(ex => `\`${escapeMarkdownTableCell(ex)}\``).join(', '); +} + +/** + * Renders a deterministic Markdown field-shape report (zero wall-clock timestamps or + * filesystem paths). Identical results always produce byte-identical Markdown. + */ +export function renderFieldShapesMarkdown(result: ReadFieldShapesResult): string { + const sortedCollections = [...result.collections].sort((a, b) => + compareAscii(a.collection, b.collection) + ); + + const lines: string[] = [ + '# Source Field Shapes Report', + '', + '- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)', + `- **Sample limit per collection:** ${result.limit}`, + `- **Collections probed:** ${sortedCollections.length}`, + `- **Total documents sampled:** ${result.totalDocsSampled}`, + ]; + + for (const col of sortedCollections) { + lines.push('', `## \`${col.collection}\` (${col.docCount} docs sampled)`, ''); + + if (col.docCount === 0) { + lines.push('_No documents sampled._'); + continue; + } + + const sortedFields = [...col.fields].sort((a, b) => compareAscii(a.field, b.field)); + if (sortedFields.length === 0) { + lines.push('_No fields observed._'); + continue; + } + + lines.push('| Field | Presence | Types | String Patterns | Examples |'); + lines.push('| --- | --- | --- | --- | --- |'); + + for (const field of sortedFields) { + const pct = ((field.presentCount / col.docCount) * 100).toFixed(1); + const fieldCell = `\`${escapeMarkdownTableCell(field.field)}\``; + const presenceCell = `${pct}% (${field.presentCount}/${col.docCount})`; + const typesCell = formatTypeCountsCell(field.typeCounts); + const patternsCell = formatStringStatsCell(field.stringStats); + const examplesCell = formatExamplesCell(field.examples); + lines.push( + `| ${fieldCell} | ${presenceCell} | ${typesCell} | ${patternsCell} | ${examplesCell} |` + ); + } + } + + return `${lines.join('\n')}\n`; +} diff --git a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts index 58b7ea6a..528814f2 100644 --- a/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts +++ b/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts @@ -53,6 +53,9 @@ export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US', export interface SourceSymbolFindOptions { projection?: Record; batchSize?: number; + limit?: number; + promoteValues?: boolean; + promoteLongs?: boolean; } /** diff --git a/apps/stock/data-pipeline/test/source-field-shapes.test.ts b/apps/stock/data-pipeline/test/source-field-shapes.test.ts new file mode 100644 index 00000000..d9a60660 --- /dev/null +++ b/apps/stock/data-pipeline/test/source-field-shapes.test.ts @@ -0,0 +1,647 @@ +import { describe, expect, test } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { + DEFAULT_FIELD_SHAPE_LIMIT, + DEFAULT_MAX_EXAMPLE_LENGTH, + DEFAULT_MAX_EXAMPLES, + FIELD_SHAPE_PROBE_COLLECTIONS, + FIELD_VALUE_TYPES, + MAX_EXAMPLE_LENGTH_CAP, + MAX_EXAMPLES_CAP, + MAX_FIELD_SHAPE_LIMIT, + parseProbeSourceFieldShapesArgs, + readFieldShapes, + renderFieldShapesMarkdown, + runSourceFieldShapesProbe, + STRING_PATTERN_CLASSES, + summarizeFieldShapes, + UnknownProbeCollectionError, + type FieldShapeSummary, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolCursor, + type ReadOnlySourceSymbolReader, + type SourceSymbolFindOptions, +} from '../src/security-master'; + +interface RecordedFindCall { + collectionName: string; + filter: Record | undefined; + options: SourceSymbolFindOptions | undefined; +} + +interface FakeBsonWrapper { + _bsontype: string; + valueOf?: () => unknown; + toString: () => string; +} + +function fakeInt32(value: number): FakeBsonWrapper { + return { + _bsontype: 'Int32', + valueOf: () => value, + toString: () => String(value), + }; +} + +function fakeDouble(value: number): FakeBsonWrapper { + return { + _bsontype: 'Double', + valueOf: () => value, + toString: () => String(value), + }; +} + +function fakeLong(value: string): FakeBsonWrapper { + return { + _bsontype: 'Long', + toString: () => value, + }; +} + +function fakeObjectId(hex: string): FakeBsonWrapper { + return { + _bsontype: 'ObjectId', + toString: () => hex, + }; +} + +function fakeDecimal128(value: string): FakeBsonWrapper { + return { + _bsontype: 'Decimal128', + toString: () => value, + }; +} + +function sumTypeCounts(summary: FieldShapeSummary): number { + let total = 0; + for (const typeName of FIELD_VALUE_TYPES) { + total += summary.typeCounts[typeName]; + } + return total; +} + +function sumPatternCounts(summary: FieldShapeSummary): number { + if (summary.stringStats === null) { + return 0; + } + let total = 0; + for (const pattern of STRING_PATTERN_CLASSES) { + total += summary.stringStats.patterns[pattern]; + } + return total; +} + +function createFakeReader( + docsByCollection: Record[]>, + opts?: { + readOnly?: boolean; + failFindOnCollection?: string; + failIterOnCollection?: string; + failCloseOnCollection?: string; + returnBufferedArrayOnCollection?: string; + ignoreLimit?: boolean; + } +): { + reader: ReadOnlySourceSymbolReader; + calls: RecordedFindCall[]; + closedCollections: string[]; +} { + const calls: RecordedFindCall[] = []; + const closedCollections: string[] = []; + const readOnly = opts?.readOnly ?? true; + + const reader: ReadOnlySourceSymbolReader = { + isReadOnly(): boolean { + return readOnly; + }, + find = Record>( + collectionName: string, + filter?: Record, + options?: SourceSymbolFindOptions + ): ReadOnlySourceSymbolCursor { + calls.push({ collectionName, filter, options }); + + if (opts?.failFindOnCollection === collectionName) { + throw new Error('simulated find failure'); + } + if (opts?.returnBufferedArrayOnCollection === collectionName) { + return [...(docsByCollection[collectionName] ?? [])] as unknown as ReadOnlySourceSymbolCursor; + } + + const sourceDocs = docsByCollection[collectionName] ?? []; + const maxToYield = + opts?.ignoreLimit === true || options?.limit === undefined + ? sourceDocs.length + : Math.min(sourceDocs.length, options.limit); + + return { + async *[Symbol.asyncIterator](): AsyncIterator { + for (let i = 0; i < maxToYield; i++) { + if (opts?.failIterOnCollection === collectionName && i === 1) { + throw new Error('simulated cursor iteration failure'); + } + yield sourceDocs[i] as T; + } + }, + async close(): Promise { + closedCollections.push(collectionName); + if (opts?.failCloseOnCollection === collectionName) { + throw new Error('simulated cursor close failure'); + } + }, + }; + }, + }; + + return { reader, calls, closedCollections }; +} + +describe('source-field-shapes static purity', () => { + test('source-field-shapes.ts has zero runtime DB, FS, or network imports', () => { + const filePath = resolve(import.meta.dir, '../src/security-master/source-field-shapes.ts'); + const source = readFileSync(filePath, 'utf8'); + const runtimeImportLines = source + .split('\n') + .filter(line => /^\s*import\s+(?!type\b)/.test(line)); + + for (const line of runtimeImportLines) { + expect(line).not.toMatch(/mongodb|postgres|node:fs|node:http|node:https|node:net|fetch/i); + } + expect(source).not.toMatch(/\bDate\.now\s*\(|\bnew Date\s*\(\s*\)/); + }); +}); + +describe('summarizeFieldShapes', () => { + test('classifies mixed JS and BSON value types on one field and reconciles counts', () => { + const docs: Record[] = [ + { mixed: 'hello' }, + { mixed: 42 }, + { mixed: 3.14 }, + { mixed: fakeInt32(7) }, + { mixed: fakeLong('9007199254740993') }, + { mixed: fakeDouble(1.0) }, + { mixed: true }, + { mixed: new Date('2025-01-15T12:00:00.000Z') }, + { mixed: null }, + { mixed: fakeObjectId('507f1f77bcf86cd799439011') }, + { mixed: [1, 2, 3] }, + { mixed: { nested: 'a' } }, + { mixed: fakeDecimal128('12.34') }, + { mixed: new Uint8Array([1, 2]) }, + {}, // missing + ]; + + const summary = summarizeFieldShapes(docs); + expect(summary.docCount).toBe(docs.length); + + const mixed = summary.fields.find(f => f.field === 'mixed'); + expect(mixed).toBeDefined(); + expect(mixed!.presentCount).toBe(14); + expect(mixed!.missingCount).toBe(1); + expect(mixed!.presentCount + mixed!.missingCount).toBe(summary.docCount); + expect(sumTypeCounts(mixed!)).toBe(mixed!.presentCount); + + expect(mixed!.typeCounts).toEqual({ + string: 1, + int: 3, // 42, Int32(7), Long(...) + double: 2, // 3.14, Double(1.0) + bool: 1, + date: 1, + null: 1, + objectId: 1, + array: 1, + object: 1, + other: 2, // Decimal128, Uint8Array + }); + }); + + test('tracks one level of nested parent.child keys and stops at depth 1', () => { + const docs: Record[] = [ + { + meta: { + exchange: 'TSX', + deep: { level2: 'ignored' }, + recordedAt: new Date('2025-02-01T00:00:00Z'), + }, + arr: [{ insideArray: 1 }], + bsonObj: fakeObjectId('507f1f77bcf86cd799439012'), + }, + { + meta: { + exchange: 'NYSE', + }, + }, + ]; + + const summary = summarizeFieldShapes(docs); + const fieldNames = summary.fields.map(f => f.field); + + expect(fieldNames).toEqual([ + 'arr', + 'bsonObj', + 'meta', + 'meta.deep', + 'meta.exchange', + 'meta.recordedAt', + ]); + expect(fieldNames).not.toContain('meta.deep.level2'); + expect(fieldNames).not.toContain('bsonObj._bsontype'); + + const metaExchange = summary.fields.find(f => f.field === 'meta.exchange')!; + expect(metaExchange.presentCount).toBe(2); + expect(metaExchange.missingCount).toBe(0); + expect(metaExchange.typeCounts.string).toBe(2); + + const metaDeep = summary.fields.find(f => f.field === 'meta.deep')!; + expect(metaDeep.presentCount).toBe(1); + expect(metaDeep.missingCount).toBe(1); + expect(metaDeep.typeCounts.object).toBe(1); + }); + + test('classifies all five string pattern classes and tracks min/max string length', () => { + const docs: Record[] = [ + { s: '2024-02-29' }, // valid leap-year ymd (len 10) + { s: '2023-02-29' }, // invalid calendar date -> other (len 10) + { s: '2025-05-01T14:30:00Z' }, // isoDatetime (len 20) + { s: '2025-05-01T14:30:00.123-04:00' }, // isoDatetime (len 29) + { s: '-123.45' }, // numeric (len 7) + { s: '1.5e-4' }, // numeric (len 6) + { s: '' }, // emptyOrWhitespace (len 0) + { s: ' \t ' }, // emptyOrWhitespace (len 5) + { s: 'AAPL.US' }, // other (len 7) + ]; + + const summary = summarizeFieldShapes(docs); + const field = summary.fields.find(f => f.field === 's')!; + + expect(field.typeCounts.string).toBe(9); + expect(field.stringStats).toEqual({ + minLength: 0, + maxLength: 29, + patterns: { + ymd: 1, + isoDatetime: 2, + numeric: 2, + emptyOrWhitespace: 2, + other: 2, + }, + }); + expect(sumPatternCounts(field)).toBe(field.typeCounts.string); + }); + + test('truncates and caps examples, suppresses _id and _id.* examples, and validates bounds', () => { + const docs: Record[] = [ + { + _id: fakeObjectId('507f1f77bcf86cd799439011'), + symbol: 'ZZZZ', + note: 'line1\nline2\twith a very long description that must be truncated', + }, + { + _id: { key: 'secret-composite-id' }, + symbol: 'AAAA', + note: 'short', + }, + { + _id: 'string-id-should-never-appear', + symbol: 'MMMM', + }, + { + symbol: 'BBBB', + }, + ]; + + const summary = summarizeFieldShapes(docs, { maxExamples: 2, maxExampleLength: 16 }); + const idField = summary.fields.find(f => f.field === '_id')!; + const idChildField = summary.fields.find(f => f.field === '_id.key')!; + const symbolField = summary.fields.find(f => f.field === 'symbol')!; + const noteField = summary.fields.find(f => f.field === 'note')!; + + expect(idField.examples).toEqual([]); + expect(idChildField.examples).toEqual([]); + expect(symbolField.examples).toEqual(['AAAA', 'BBBB']); + expect(noteField.examples.length).toBe(2); + expect(noteField.examples[0]).toBe('line1 line2 w...'); + expect(noteField.examples[0]!.length).toBeLessThanOrEqual(16); + expect(noteField.examples[1]).toBe('short'); + + expect(() => summarizeFieldShapes(docs, { maxExamples: -1 })).toThrow(RangeError); + expect(() => summarizeFieldShapes(docs, { maxExamples: MAX_EXAMPLES_CAP + 1 })).toThrow( + RangeError + ); + expect(() => summarizeFieldShapes(docs, { maxExampleLength: 0 })).toThrow(RangeError); + expect(() => + summarizeFieldShapes(docs, { maxExampleLength: MAX_EXAMPLE_LENGTH_CAP + 1 }) + ).toThrow(RangeError); + }); + + test('produces deep-equal output for shuffled input order and handles empty iterable', () => { + expect(summarizeFieldShapes([])).toEqual({ docCount: 0, fields: [] }); + + const original: Record[] = [ + { _id: fakeObjectId('000000000000000000000001'), z: 'delta', a: 10, meta: { k: 'v3' } }, + { _id: fakeObjectId('000000000000000000000002'), z: 'alpha', a: 2.5, meta: { k: 'v1' } }, + { _id: fakeObjectId('000000000000000000000003'), z: 'charlie', b: true, meta: { k: 'v4' } }, + { _id: fakeObjectId('000000000000000000000004'), z: 'bravo', a: null, meta: { k: 'v2' } }, + ]; + const shuffled = [original[2]!, original[0]!, original[3]!, original[1]!]; + + const a = summarizeFieldShapes(original, { maxExamples: 2 }); + const b = summarizeFieldShapes(shuffled, { maxExamples: 2 }); + + expect(b).toEqual(a); + expect(a.fields.map(f => f.field)).toEqual(['_id', 'a', 'b', 'meta', 'meta.k', 'z']); + }); +}); + +describe('readFieldShapes', () => { + test('calls only find() with limit and promoteValues/promoteLongs false, closes cursors, and enforces client limit', async () => { + const docsByCollection: Record[]> = { + qmDividends: [ + { _id: fakeObjectId('507f1f77bcf86cd799439011'), amount: fakeDouble(0.25), currency: 'USD' }, + { _id: fakeObjectId('507f1f77bcf86cd799439012'), amount: fakeDouble(0.5), currency: 'CAD' }, + { _id: fakeObjectId('507f1f77bcf86cd799439013'), amount: fakeDouble(1.0), currency: 'USD' }, + ], + ceoShorts: [ + { _id: fakeObjectId('507f1f77bcf86cd799439014'), symbol: 'ABC', shares: fakeInt32(1000) }, + ], + }; + + const { reader, calls, closedCollections } = createFakeReader(docsByCollection, { + ignoreLimit: true, + }); + + const result = await readFieldShapes(reader, { + collections: ['qmDividends', 'ceoShorts', 'qmDividends'], + limit: 2, + batchSize: 500, + }); + + expect(calls.length).toBe(2); + expect(calls.map(c => c.collectionName)).toEqual(['ceoShorts', 'qmDividends']); + for (const call of calls) { + expect(call.filter).toEqual({}); + expect(call.options).toEqual({ + limit: 2, + promoteValues: false, + promoteLongs: false, + batchSize: 500, + }); + } + expect(closedCollections).toEqual(['ceoShorts', 'qmDividends']); + + // Defensively capped at limit=2 even though fake reader ignored limit + expect(result.limit).toBe(2); + expect(result.totalDocsSampled).toBe(3); + const qmDiv = result.collections.find(c => c.collection === 'qmDividends')!; + expect(qmDiv.docCount).toBe(2); + const amountField = qmDiv.fields.find(f => f.field === 'amount')!; + expect(amountField.typeCounts.double).toBe(2); + }); + + test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => { + const { reader, calls } = createFakeReader({}); + const result = await readFieldShapes(reader); + + expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT); + expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES); + expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH); + expect(calls.length).toBe(FIELD_SHAPE_PROBE_COLLECTIONS.length); + for (const call of calls) { + expect(call.options).toEqual({ + limit: DEFAULT_FIELD_SHAPE_LIMIT, + promoteValues: false, + promoteLongs: false, + }); + } + }); + + test('rejects invalid limit, unknown collection, and non-read-only reader before any query', async () => { + const nonRo = createFakeReader({}, { readOnly: false }); + await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i); + expect(nonRo.calls.length).toBe(0); + + const badLimitHigh = createFakeReader({}); + await expect( + readFieldShapes(badLimitHigh.reader, { limit: MAX_FIELD_SHAPE_LIMIT + 1 }) + ).rejects.toThrow(RangeError); + expect(badLimitHigh.calls.length).toBe(0); + + const badLimitZero = createFakeReader({}); + await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError); + expect(badLimitZero.calls.length).toBe(0); + + const unknownCol = createFakeReader({}); + let caught: unknown; + try { + await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] }); + } catch (err) { + caught = err; + } + expect(caught).toBeInstanceOf(UnknownProbeCollectionError); + expect((caught as UnknownProbeCollectionError).collectionName).toBe('notACollection'); + expect(unknownCol.calls.length).toBe(0); + }); + + test('rejects buffered array cursor with TypeError and surfaces per-collection errors with cause', async () => { + const buffered = createFakeReader( + { eodPrices: [{ date: '2025-01-02' }] }, + { returnBufferedArrayOnCollection: 'eodPrices' } + ); + await expect( + readFieldShapes(buffered.reader, { collections: ['eodPrices'] }) + ).rejects.toThrow(TypeError); + + const findErr = createFakeReader({}, { failFindOnCollection: 'qmFilings' }); + let caughtFind: unknown; + try { + await readFieldShapes(findErr.reader, { collections: ['eodPrices', 'qmFilings'] }); + } catch (err) { + caughtFind = err; + } + expect(caughtFind).toBeInstanceOf(Error); + expect((caughtFind as Error).message).toContain('qmFilings'); + expect((caughtFind as Error).cause).toBeInstanceOf(Error); + + const iterErr = createFakeReader( + { qmEarnings: [{ a: 1 }, { a: 2 }] }, + { failIterOnCollection: 'qmEarnings' } + ); + let caughtIter: unknown; + try { + await readFieldShapes(iterErr.reader, { collections: ['qmEarnings'] }); + } catch (err) { + caughtIter = err; + } + expect(caughtIter).toBeInstanceOf(Error); + expect((caughtIter as Error).message).toContain('qmEarnings'); + expect((caughtIter as Error).cause).toBeInstanceOf(Error); + expect(iterErr.closedCollections).toEqual(['qmEarnings']); + + const closeErr = createFakeReader( + { teMarketData: [{ country: 'US' }] }, + { failCloseOnCollection: 'teMarketData' } + ); + let caughtClose: unknown; + try { + await readFieldShapes(closeErr.reader, { collections: ['teMarketData'] }); + } catch (err) { + caughtClose = err; + } + expect(caughtClose).toBeInstanceOf(Error); + expect((caughtClose as Error).message).toContain('teMarketData'); + expect((caughtClose as Error).cause).toBeInstanceOf(Error); + }); +}); + +describe('renderFieldShapesMarkdown', () => { + test('renders byte-identical Markdown with bounded-sample header, escaping, 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' }, + ]; + const docsB = [docsA[1]!, docsA[0]!]; + + const run1 = await readFieldShapes( + createFakeReader({ eodPrices: docsA, qmSplits: [] }).reader, + { collections: ['eodPrices', 'qmSplits'], limit: 500 } + ); + const run2 = await readFieldShapes( + createFakeReader({ eodPrices: docsB, qmSplits: [] }).reader, + { collections: ['qmSplits', 'eodPrices'], limit: 500 } + ); + + const md1 = renderFieldShapesMarkdown(run1); + const md2 = renderFieldShapesMarkdown(run2); + + expect(md1).toBe(md2); + 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._'); + }); +}); + +describe('CLI arg parsing and headless probe runner', () => { + test('parseProbeSourceFieldShapesArgs validates flags without opening any DB connection', () => { + expect(parseProbeSourceFieldShapesArgs(['--help'])).toEqual({ help: true }); + expect(() => parseProbeSourceFieldShapesArgs([])).toThrow(/--out/); + expect(() => parseProbeSourceFieldShapesArgs(['--out', ' '])).toThrow(/--out/); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=0'])).toThrow( + /--limit/ + ); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', '-1'])).toThrow( + /--limit/ + ); + expect(() => + parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', String(MAX_FIELD_SHAPE_LIMIT + 1)]) + ).toThrow(/--limit/); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=abc'])).toThrow( + /--limit/ + ); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=1.5'])).toThrow( + /--limit/ + ); + expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--bogus'])).toThrow( + /Unknown argument/ + ); + expect(() => + parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--collections=eodPrices,bogusCol']) + ).toThrow(UnknownProbeCollectionError); + + const parsed = parseProbeSourceFieldShapesArgs([ + '--out', + './tmp/report.md', + '--limit', + '250', + '--collections', + 'qmDividends,ceoShorts,qmDividends', + ]); + expect(parsed).toEqual({ + help: false, + outPath: './tmp/report.md', + limit: 250, + collections: ['ceoShorts', 'qmDividends'], + }); + }); + + test('runSourceFieldShapesProbe rejects non-read-only client before any query and writes report headlessly', async () => { + let getCollectionCalls = 0; + let closeCalls = 0; + + const writableClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => false, + getCollection() { + getCollectionCalls += 1; + throw new Error('should never be called'); + }, + }; + + await expect( + runSourceFieldShapesProbe( + { + mongoCollectionClient: writableClient, + closeMongo: () => { + closeCalls += 1; + }, + writeFile: () => {}, + writeStdout: () => {}, + }, + { outPath: './tmp/should-not-write.md' } + ) + ).rejects.toThrow(/read-only/i); + expect(getCollectionCalls).toBe(0); + expect(closeCalls).toBe(1); + + const writtenFiles: Array<{ filePath: string; content: string }> = []; + const stdoutChunks: string[] = []; + let roCloseCalls = 0; + + const roClient: ReadOnlyMongoCollectionClient = { + isReadOnly: () => true, + getCollection(name: string) { + return { + find() { + const docs = name === 'ceoShorts' ? [{ symbol: 'XYZ', shares: 100 }] : []; + return { + async *[Symbol.asyncIterator]() { + for (const doc of docs) { + yield doc; + } + }, + async close() {}, + }; + }, + }; + }, + }; + + const output = await runSourceFieldShapesProbe( + { + mongoCollectionClient: roClient, + closeMongo: () => { + roCloseCalls += 1; + }, + writeFile: (filePath, content) => { + writtenFiles.push({ filePath, content }); + }, + writeStdout: text => { + stdoutChunks.push(text); + }, + }, + { + outPath: './tmp/field-shapes.md', + limit: 10, + collections: ['ceoShorts'], + } + ); + + expect(roCloseCalls).toBe(1); + expect(writtenFiles.length).toBe(1); + expect(writtenFiles[0]!.filePath).toBe('./tmp/field-shapes.md'); + expect(writtenFiles[0]!.content).toBe(output.markdown); + expect(stdoutChunks.join('')).toContain('Documents sampled: 1'); + }); +});