Clear M1 milestone bugs (T-37, T-39, T-41, T-42, T-44, T-45, T-46, T-48, T-49, T-51, T-52)

This commit is contained in:
Boki 2026-11-27 16:11:57 -05:00
parent 199f7beecd
commit 9e259ca43b
18 changed files with 255 additions and 34 deletions

View file

@ -122,8 +122,30 @@ function parseNumericIpv4Octets(host: string): [number, number, number, number]
return [p0, p1, p2, p3];
}
function isIpv4Loopback(host: string): boolean {
const octets = parseNumericIpv4Octets(host);
function parseDecimalIpv4Octets(host: string): [number, number, number, number] | null {
const octets = host.split('.');
if (octets.length !== 4) {
return null;
}
const values: number[] = [];
for (const part of octets) {
if (!/^\d+$/.test(part)) {
return null;
}
const value = Number(part);
if (!Number.isSafeInteger(value) || value < 0 || value > 255) {
return null;
}
values.push(value);
}
const [a, b, c, d] = values;
if (a === undefined || b === undefined || c === undefined || d === undefined) {
return null;
}
return [a, b, c, d];
}
function isIpv4LoopbackOctets(octets: [number, number, number, number] | null): boolean {
return (
octets !== null &&
(octets[0] === 127 ||
@ -131,6 +153,16 @@ function isIpv4Loopback(host: string): boolean {
);
}
function isIpv4Loopback(host: string): boolean {
// Check both POSIX numeric IPv4 (octal/hex/shorthand, e.g. 0177.0.0.1, 127.1, 0x7f000001)
// and decimal dotted-quad interpretation (e.g. 0127.0.0.1 -> 127.0.0.1) so resolvers that
// read leading-zero quads as decimal cannot bypass the loopback guard.
return (
isIpv4LoopbackOctets(parseNumericIpv4Octets(host)) ||
isIpv4LoopbackOctets(parseDecimalIpv4Octets(host))
);
}
function parseIpv6Side(side: string, allowIpv4Tail: boolean): number[] | null {
if (side === '') {
return [];

View file

@ -11,7 +11,7 @@ Normalizes raw provider collections from MongoDB (`stock`) into canonical Postgr
## Current Runtime Scope
- **MongoDB Inputs:** `exchanges`, `eodExchanges`, `ibExchanges`, `qmExchanges`, `eodSymbols`, `ibSymbols`, `qmSymbols`.
- **PostgreSQL Tables (`database/postgres/init/02-exchange-symbol-schema.sql`):**
- **PostgreSQL Tables (`database/postgres/init/02-master-schema.sql`):**
- `exchanges` & `provider_exchange_mappings`
- `symbols` & `provider_mappings`
- `sync_status`
@ -23,9 +23,9 @@ Normalizes raw provider collections from MongoDB (`stock`) into canonical Postgr
## Target Architecture (`Milestone M1` & `M2`)
Full specifications live in:
- [DATA-CONTRACTS.md](../../../docs/DATA-CONTRACTS.md) — Empirical 31-collection rules, bi-temporal security master (`instruments`, `instrument_listings`, `provider_symbol_map`, `corporate_actions`), Hive Parquet + DuckDB schemas (`bars_1d`, `fundamentals_pit`, `earnings_events_pit`, `short_interest_pit`, `macro_pit`, `fx_rates_1d`), and QuestDB `10.2.0` intraday schema.
- [MILESTONES.md](../../../docs/MILESTONES.md) — Step-by-step `M0` (read-only wrapper hardening), `M1` (US + Canada security master & `bars_1d` + `fx_rates_1d` curation), and `M2` (`qmFilings`-backed PIT fundamentals, earnings, short interest, and macro curation).
- [phase1-investigation.md](../../../docs/data-pipeline/phase1-investigation.md) — Initial provider exchange/symbol investigation notes.
- [DATA-CONTRACTS.md](../../../design/DATA-CONTRACTS.md) — Empirical 31-collection rules, bi-temporal security master (`exchange`, `exchange_source_map`, `instrument`, `instrument_identifier_history`, `listing`, `corporate_action_continuity`, `listing_symbol_history`, `provider_mapping`, `resolution_conflict`, `override`, `golden_field_audit`), Hive Parquet + DuckDB schemas (`bars_1d`, `fundamentals_pit`, `earnings_events_pit`, `short_interest_pit`, `macro_pit`, `fx_rates_1d`), and QuestDB `10.2.0` intraday schema.
- [MILESTONES.md](../../../design/MILESTONES.md) — Step-by-step `M0` (read-only wrapper hardening), `M1` (US + Canada security master & `bars_1d` + `fx_rates_1d` curation), and `M2` (`qmFilings`-backed PIT fundamentals, earnings, short interest, and macro curation).
- [phase1-investigation.md](../../../design/data-pipeline/phase1-investigation.md) — Initial provider exchange/symbol investigation notes.
## Commands
Run from the repository root:

View file

@ -487,7 +487,11 @@ function buildNormalizedSpanStages(spec: BarSpanCollectionSpec): Record<string,
_id: '$sourceId',
firstBarDate: { $min: '$normalizedDate' },
lastBarDate: { $max: '$normalizedDate' },
barCount: { $sum: 1 },
barCount: {
$sum: {
$cond: [{ $ne: ['$normalizedDate', null] }, 1, 0],
},
},
},
};
return [projectStage, groupStage];
@ -638,12 +642,11 @@ function normalizeRequestedSourceIds(source: BarSpanSource, rawIds: readonly str
`sourceIdsBySource.${source}[${i}] must be a string, received ${typeof raw}`
);
}
const trimmed = raw.trim();
if (trimmed.length === 0 || seen.has(trimmed)) {
if (raw.trim().length === 0 || seen.has(raw)) {
continue;
}
seen.add(trimmed);
deduped.push(trimmed);
seen.add(raw);
deduped.push(raw);
}
return deduped;
}
@ -672,8 +675,8 @@ function foldGroupedRow(
return;
}
const sourceId = record._id.trim();
if (sourceId.length === 0) {
const sourceId = record._id;
if (sourceId.trim().length === 0) {
sourceSkipped.invalidId++;
sourceSkipped.total++;
totalSkipped.invalidId++;

View file

@ -1,5 +1,7 @@
export type TickerSource = 'eod' | 'qm' | 'ib' | 'ceo';
export const MAX_CLASS_SUFFIX_LENGTH = 12;
export interface ParsedTicker {
tickerRoot: string;
classSuffix: string;
@ -82,7 +84,8 @@ export function parseTicker(
const secondSep = findNextSeparator(s, pos);
if (secondSep === -1) {
return { tickerRoot, classSuffix: s.slice(pos) };
const classSuffix = s.slice(pos);
return classSuffix.length <= MAX_CLASS_SUFFIX_LENGTH ? { tickerRoot, classSuffix } : null;
}
let classSuffix = s.slice(pos, secondSep);
@ -104,5 +107,9 @@ export function parseTicker(
pos = nextSep;
}
if (classSuffix.length > MAX_CLASS_SUFFIX_LENGTH) {
return null;
}
return { tickerRoot, classSuffix };
}

View file

@ -13,8 +13,11 @@ export type BoardLotPolicy = 'us_100' | 'tsx_tiered' | 'fx';
export type ClassificationMethod = 'explicit_rule' | 'operating_mic';
export const MAX_EXCHANGE_SOURCE_CODE_LENGTH = 32;
export type UnresolvedExchangeReason =
| 'empty_code'
| 'source_code_too_long'
| 'multi_valued_operating_mic'
| 'invalid_operating_mic_format'
| 'unknown_operating_mic'
@ -347,6 +350,20 @@ export function classifySourceExchanges(
continue;
}
if (normalizedCode.length > MAX_EXCHANGE_SOURCE_CODE_LENGTH) {
unresolved.push({
source: record.source,
sourceCode: normalizedCode,
rawCode,
name: normalizeOptionalString(record.name),
country: normalizeOptionalString(record.country),
operatingMic: normalizeOptionalString(record.operatingMic),
currency: normalizeOptionalString(record.currency),
reason: 'source_code_too_long',
});
continue;
}
const key = makeRuleKey(record.source, normalizedCode);
const existing = grouped.get(key);
if (existing) {

View file

@ -1,6 +1,7 @@
import {
compareAscii,
compareUnresolvedExchangeRecords,
MAX_EXCHANGE_SOURCE_CODE_LENGTH,
type ExchangeClassificationResult,
type ExchangeSeedRow,
type ExchangeSourceMapRow,
@ -22,11 +23,63 @@ export function escapeSqlLiteral(value: string | null | undefined): string {
return `'${value.replaceAll("'", "''")}'`;
}
export function generateExchangeSeedSql(input: GenerateExchangeSeedSqlInput): string {
const exchanges = [...(input.exchanges ?? [])].sort((a, b) => compareAscii(a.mic, b.mic));
const mappings = [...input.mappings].sort(
function deduplicateExchanges(rows: readonly ExchangeSeedRow[]): ExchangeSeedRow[] {
const byMic = new Map<string, ExchangeSeedRow>();
for (const row of rows) {
const existing = byMic.get(row.mic);
if (!existing) {
byMic.set(row.mic, row);
continue;
}
if (
existing.operatingMic !== row.operatingMic ||
existing.name !== row.name ||
existing.countryIso !== row.countryIso ||
existing.currency !== row.currency ||
existing.timezone !== row.timezone ||
existing.calendarCode !== row.calendarCode ||
existing.boardLotPolicy !== row.boardLotPolicy
) {
throw new Error(`Conflicting duplicate exchange row for mic "${row.mic}"`);
}
}
return Array.from(byMic.values()).sort((a, b) => compareAscii(a.mic, b.mic));
}
function deduplicateMappings(rows: readonly ExchangeSourceMapRow[]): ExchangeSourceMapRow[] {
const byKey = new Map<string, ExchangeSourceMapRow>();
for (const row of rows) {
if (row.sourceCode.length === 0 || row.sourceCode.length > MAX_EXCHANGE_SOURCE_CODE_LENGTH) {
throw new Error(
`Invalid sourceCode "${row.sourceCode}" for source "${row.source}": length must be between 1 and ${MAX_EXCHANGE_SOURCE_CODE_LENGTH} characters`
);
}
const key = `${row.source}\u0000${row.sourceCode}`;
const existing = byKey.get(key);
if (!existing) {
byKey.set(key, row);
continue;
}
if (
existing.role !== row.role ||
existing.mic !== row.mic ||
existing.countryIso !== row.countryIso ||
existing.method !== row.method ||
(existing.reviewedBy ?? null) !== (row.reviewedBy ?? null)
) {
throw new Error(
`Conflicting duplicate exchange_source_map row for (${row.source}, "${row.sourceCode}")`
);
}
}
return Array.from(byKey.values()).sort(
(a, b) => compareAscii(a.source, b.source) || compareAscii(a.sourceCode, b.sourceCode)
);
}
export function generateExchangeSeedSql(input: GenerateExchangeSeedSqlInput): string {
const exchanges = deduplicateExchanges(input.exchanges ?? []);
const mappings = deduplicateMappings(input.mappings);
const sections: string[] = [
[

View file

@ -44,8 +44,3 @@ tracing-subscriber = "0.3"
[build-dependencies]
napi-build = "2"
[profile.release]
lto = true
opt-level = 3
codegen-units = 1