From e2292e4883516cf2e4cb5d19d3dff003f60567b7 Mon Sep 17 00:00:00 2001 From: Boki Date: Wed, 28 Oct 2026 13:56:31 -0400 Subject: [PATCH] refactor(data): normalize provider symbols and remove dead scaffolding (CL34) --- .../src/handlers/qm/shared/index.ts | 10 +- .../qm/shared/session-manager-redis.ts | 381 ------------------ .../qm/shared/session-manager-wrapper.ts | 128 ------ .../data-pipeline/src/container-setup.ts | 34 -- .../sync-symbols-from-provider.operations.ts | 13 +- apps/stock/data-pipeline/src/index.ts | 5 - .../src/normalization/provider-symbol.ts | 50 +++ .../repositories/PipelineSyncRepository.ts | 32 +- docs/development/backlog/tasks/CL34.md | 4 + test/integration/provider-symbol.test.ts | 148 +++++++ test/postgres/pipeline-safety.test.ts | 63 ++- 11 files changed, 287 insertions(+), 581 deletions(-) delete mode 100644 apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts delete mode 100644 apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts delete mode 100644 apps/stock/data-pipeline/src/container-setup.ts create mode 100644 apps/stock/data-pipeline/src/normalization/provider-symbol.ts create mode 100644 test/integration/provider-symbol.test.ts diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/index.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/index.ts index 8bcf8471..0a055a6d 100644 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/index.ts +++ b/apps/stock/data-ingestion/src/handlers/qm/shared/index.ts @@ -1,6 +1,4 @@ -export * from './config'; -export * from './session-manager'; -export * from './session-manager-redis'; -export * from './session-manager-wrapper'; -export * from './types'; -export * from './operation-provider'; \ No newline at end of file +export * from './config'; +export * from './session-manager'; +export * from './types'; +export * from './operation-provider'; diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts deleted file mode 100644 index 7346e260..00000000 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-redis.ts +++ /dev/null @@ -1,381 +0,0 @@ -/** - * QM Session Manager - Redis-based implementation for cluster support - * Uses Redis as the single source of truth for session management - */ - -import type { CacheProvider } from '@stock-bot/cache'; -import type { Logger } from '@stock-bot/services'; -import { QM_SESSION_IDS, SESSION_CONFIG } from './config'; -import type { QMSession } from './types'; - -export class QMSessionManagerRedis { - private static instance: QMSessionManagerRedis | null = null; - private cacheProvider: CacheProvider | null = null; - private logger: Logger | null = null; - private readonly SESSION_TTL = 86400; // 24 hours - - private constructor() {} - - static getInstance(): QMSessionManagerRedis { - if (!QMSessionManagerRedis.instance) { - QMSessionManagerRedis.instance = new QMSessionManagerRedis(); - } - return QMSessionManagerRedis.instance; - } - - /** - * Initialize with cache provider and logger - */ - initialize(cache?: CacheProvider, logger?: Logger): void { - if (cache) { - this.cacheProvider = cache; - } - if (logger) { - this.logger = logger; - this.logger.trace('Redis-based SessionManager initialized'); - } - } - - /** - * Get a random valid session for the given session ID - */ - async getSession(sessionId: string): Promise { - if (!this.cacheProvider) { - this.logger?.error('No cache provider available'); - return null; - } - - try { - // Get all session UUIDs for this sessionId - const sessionUuids = await this.getSessionUuids(sessionId); - - if (sessionUuids.length === 0) { - this.logger?.debug(`No sessions found for ${sessionId}`); - return null; - } - - // Shuffle and try to find a valid session - const shuffled = [...sessionUuids].sort(() => Math.random() - 0.5); - - for (const uuid of shuffled) { - const session = await this.getSessionByUuid(sessionId, uuid); - if (session && (session.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS) { - this.logger?.trace(`Selected session`, { - uuid: session.uuid, - failedCalls: session.failedCalls, - successfulCalls: session.successfulCalls, - }); - return session; - } - } - - this.logger?.warn(`No valid sessions found for ${sessionId}`); - return null; - } catch (error) { - this.logger?.error('Failed to get session', { error, sessionId }); - return null; - } - } - - /** - * Get a specific session by UUID - */ - async getSessionByUuid(sessionId: string, uuid: string): Promise { - if (!this.cacheProvider) { - return null; - } - - const sessionKey = this.getSessionKey(sessionId, uuid); - try { - const session = await this.cacheProvider.get(sessionKey); - if (session) { - // Ensure dates are Date objects - session.lastUsed = new Date(session.lastUsed); - session.createdAt = new Date(session.createdAt); - } - return session; - } catch (error) { - this.logger?.error('Failed to get session by UUID', { error, sessionId, uuid }); - return null; - } - } - - /** - * Add a session - */ - async addSession(sessionId: string, session: QMSession): Promise { - if (!this.cacheProvider) { - throw new Error('No cache provider available'); - } - - const sessionKey = this.getSessionKey(sessionId, session.uuid); - const listKey = this.getSessionListKey(sessionId); - - try { - // Store the session data - await this.cacheProvider.set(sessionKey, session, this.SESSION_TTL); - - // Add UUID to the session list (using SET to simulate SADD) - const uuids = await this.getSessionUuids(sessionId); - if (!uuids.includes(session.uuid)) { - uuids.push(session.uuid); - await this.cacheProvider.set(listKey, uuids, this.SESSION_TTL); - } - - this.logger?.debug(`Added session ${session.uuid} to ${sessionId}`); - } catch (error) { - this.logger?.error('Failed to add session', { error, sessionId, uuid: session.uuid }); - throw error; - } - } - - /** - * Remove a session - */ - async removeSession(sessionId: string, uuid: string): Promise { - if (!this.cacheProvider) { - return; - } - - const sessionKey = this.getSessionKey(sessionId, uuid); - const listKey = this.getSessionListKey(sessionId); - - try { - // Remove session data - await this.cacheProvider.del(sessionKey); - - // Remove UUID from list - const uuids = await this.getSessionUuids(sessionId); - const filtered = uuids.filter(u => u !== uuid); - if (filtered.length !== uuids.length) { - await this.cacheProvider.set(listKey, filtered, this.SESSION_TTL); - } - - this.logger?.debug(`Removed session ${uuid} from ${sessionId}`); - } catch (error) { - this.logger?.error('Failed to remove session', { error, sessionId, uuid }); - } - } - - /** - * Get all sessions for a session ID - */ - async getSessions(sessionId: string): Promise { - if (!this.cacheProvider) { - return []; - } - - const uuids = await this.getSessionUuids(sessionId); - const sessions: QMSession[] = []; - - for (const uuid of uuids) { - const session = await this.getSessionByUuid(sessionId, uuid); - if (session) { - sessions.push(session); - } - } - - return sessions; - } - - /** - * Get session count - */ - async getSessionCount(sessionId?: string): Promise { - if (!this.cacheProvider) { - return 0; - } - - if (sessionId) { - const uuids = await this.getSessionUuids(sessionId); - return uuids.length; - } - - // Count all sessions - let total = 0; - for (const sid of Object.values(QM_SESSION_IDS)) { - const uuids = await this.getSessionUuids(sid); - total += uuids.length; - } - return total; - } - - /** - * Clean up failed sessions - */ - async cleanupFailedSessions(): Promise { - if (!this.cacheProvider) { - return 0; - } - - let removedCount = 0; - - for (const sessionId of Object.values(QM_SESSION_IDS)) { - const sessions = await this.getSessions(sessionId); - - for (const session of sessions) { - if (session.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS) { - await this.removeSession(sessionId, session.uuid); - removedCount++; - } - } - } - - this.logger?.info(`Cleaned up ${removedCount} failed sessions`); - return removedCount; - } - - /** - * Check if more sessions are needed - */ - async needsMoreSessions(sessionId: string): Promise { - const sessions = await this.getSessions(sessionId); - const validSessions = sessions.filter( - s => (s.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS - ); - return validSessions.length < SESSION_CONFIG.MAX_SESSIONS; - } - - /** - * Get statistics - */ - async getStats(): Promise> { - const stats: Record = {}; - - for (const [_sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) { - const sessions = await this.getSessions(sessionId); - const validSessions = sessions.filter( - s => (s.failedCalls || 0) <= SESSION_CONFIG.MAX_FAILED_CALLS - ); - const failedSessions = sessions.filter(s => s.failedCalls > SESSION_CONFIG.MAX_FAILED_CALLS); - - stats[sessionId] = { - total: sessions.length, - valid: validSessions.length, - failed: failedSessions.length, - }; - } - - return stats; - } - - /** - * Increment failed calls for a session - */ - async incrementFailedCalls(sessionId: string, sessionUuid: string): Promise { - const session = await this.getSessionByUuid(sessionId, sessionUuid); - - if (session) { - session.failedCalls = (session.failedCalls || 0) + 1; - session.lastUsed = new Date(); - - const sessionKey = this.getSessionKey(sessionId, sessionUuid); - await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL); - - this.logger?.debug(`Incremented failed calls for session`, { - sessionUuid, - failedCalls: session.failedCalls, - sessionId, - }); - } else { - this.logger?.warn(`Session not found`, { sessionUuid, sessionId }); - } - } - - /** - * Increment successful calls for a session - */ - async incrementSuccessfulCalls(sessionId: string, sessionUuid: string): Promise { - const session = await this.getSessionByUuid(sessionId, sessionUuid); - - if (session) { - session.successfulCalls = (session.successfulCalls || 0) + 1; - session.lastUsed = new Date(); - - const sessionKey = this.getSessionKey(sessionId, sessionUuid); - await this.cacheProvider?.set(sessionKey, session, this.SESSION_TTL); - - this.logger?.debug(`Incremented successful calls for session`, { - sessionUuid, - successfulCalls: session.successfulCalls, - sessionId, - }); - } else { - this.logger?.warn(`Session not found`, { sessionUuid, sessionId }); - } - } - - /** - * Helper: Get session UUIDs from cache - */ - private async getSessionUuids(sessionId: string): Promise { - if (!this.cacheProvider) { - return []; - } - - const listKey = this.getSessionListKey(sessionId); - try { - const uuids = await this.cacheProvider.get(listKey); - return uuids || []; - } catch (error) { - this.logger?.error('Failed to get session UUIDs', { error, sessionId }); - return []; - } - } - - /** - * Helper: Generate cache keys - */ - private getSessionKey(sessionId: string, uuid: string): string { - return `qm:sessions:${sessionId}:session:${uuid}`; - } - - private getSessionListKey(sessionId: string): string { - return `qm:sessions:${sessionId}:list`; - } - - /** - * Migrate from old session manager (for backward compatibility) - */ - async migrateFromOldFormat(): Promise { - if (!this.cacheProvider) { - return; - } - - this.logger?.info('Starting migration from old session format'); - - for (const [sessionType, sessionId] of Object.entries(QM_SESSION_IDS)) { - const oldListKey = `qm:sessions:${sessionType.toLowerCase()}:list`; - const oldSessionIds = await this.cacheProvider.get(oldListKey); - - if (oldSessionIds && Array.isArray(oldSessionIds)) { - this.logger?.info(`Migrating ${oldSessionIds.length} sessions for ${sessionType}`); - - for (const id of oldSessionIds) { - const oldSessionKey = `qm:sessions:${sessionType.toLowerCase()}:${id}`; - const oldSession = - await this.cacheProvider.get(oldSessionKey); - - if (oldSession && oldSession.uuid) { - const session: QMSession = { - uuid: oldSession.uuid, - proxy: oldSession.proxy, - headers: oldSession.headers, - successfulCalls: oldSession.successfulCalls || 0, - failedCalls: oldSession.failedCalls || 0, - lastUsed: new Date(oldSession.lastUsed), - createdAt: new Date(oldSession.createdAt || new Date()), - }; - - await this.addSession(sessionId, session); - await this.cacheProvider.del(oldSessionKey); - } - } - - await this.cacheProvider.del(oldListKey); - } - } - - this.logger?.info('Migration completed'); - } -} diff --git a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts b/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts deleted file mode 100644 index b3ad7e0a..00000000 --- a/apps/stock/data-ingestion/src/handlers/qm/shared/session-manager-wrapper.ts +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Session Manager Wrapper - Provides a unified interface that can switch between implementations - */ - -import type { CacheProvider } from '@stock-bot/cache'; -import type { Logger } from '@stock-bot/services'; -import { QMSessionManager } from './session-manager'; -import { QMSessionManagerRedis } from './session-manager-redis'; -import type { QMSession } from './types'; - -/** - * Wrapper that delegates to either in-memory or Redis-based implementation - * Set REDIS_SESSION_MANAGER=true to use Redis implementation - */ -export class SessionManagerWrapper { - private implementation: QMSessionManager | QMSessionManagerRedis; - private static instance: SessionManagerWrapper | null = null; - - private constructor() { - // Use Redis implementation if env var is set or if in production - const useRedis = - process.env.REDIS_SESSION_MANAGER === 'true' || process.env.NODE_ENV === 'production'; - - if (useRedis) { - this.implementation = QMSessionManagerRedis.getInstance(); - } else { - this.implementation = QMSessionManager.getInstance(); - } - } - - static getInstance(): SessionManagerWrapper { - if (!SessionManagerWrapper.instance) { - SessionManagerWrapper.instance = new SessionManagerWrapper(); - } - return SessionManagerWrapper.instance; - } - - /** - * Reset instance (for testing) - */ - static resetInstance(): void { - SessionManagerWrapper.instance = null; - } - - /** - * Initialize with cache provider and logger - */ - initialize(cache?: CacheProvider, logger?: Logger): void { - this.implementation.initialize(cache, logger); - } - - /** - * Get the implementation type - */ - getImplementationType(): string { - return this.implementation instanceof QMSessionManagerRedis ? 'redis' : 'memory'; - } - - // Delegate all methods to the implementation - async getSession(sessionId: string): Promise { - return this.implementation.getSession(sessionId); - } - - async getSessionByUuid(sessionId: string, uuid: string): Promise { - if (this.implementation instanceof QMSessionManagerRedis) { - return this.implementation.getSessionByUuid(sessionId, uuid); - } else { - return this.implementation.getSessionByUuid(sessionId, uuid); - } - } - - async addSession(sessionId: string, session: QMSession): Promise { - return this.implementation.addSession(sessionId, session); - } - - async getSessions(sessionId: string): Promise { - if (this.implementation instanceof QMSessionManagerRedis) { - return this.implementation.getSessions(sessionId); - } else { - return this.implementation.getSessions(sessionId); - } - } - - async getSessionCount(sessionId?: string): Promise { - if (this.implementation instanceof QMSessionManagerRedis) { - return this.implementation.getSessionCount(sessionId); - } else { - return this.implementation.getSessionCount(sessionId ?? ''); - } - } - - async cleanupFailedSessions(): Promise { - return this.implementation.cleanupFailedSessions(); - } - - async needsMoreSessions(sessionId: string): Promise { - return this.implementation.needsMoreSessions(sessionId); - } - - async getStats(): Promise> { - return this.implementation.getStats(); - } - - async incrementFailedCalls(sessionId: string, sessionUuid: string): Promise { - return this.implementation.incrementFailedCalls(sessionId, sessionUuid); - } - - async incrementSuccessfulCalls(sessionId: string, sessionUuid: string): Promise { - return this.implementation.incrementSuccessfulCalls(sessionId, sessionUuid); - } - - // Additional methods for memory implementation - async isAtCapacity(sessionId: string): Promise { - if (this.implementation instanceof QMSessionManager) { - return this.implementation.isAtCapacity(sessionId); - } - // For Redis, we'd need to implement this async - throw new Error('isAtCapacity not available for Redis implementation'); - } - - // Migration helper - async migrateToRedis(): Promise { - if (this.implementation instanceof QMSessionManagerRedis) { - return this.implementation.migrateFromOldFormat(); - } - throw new Error('Migration only available for Redis implementation'); - } -} diff --git a/apps/stock/data-pipeline/src/container-setup.ts b/apps/stock/data-pipeline/src/container-setup.ts deleted file mode 100644 index 356de764..00000000 --- a/apps/stock/data-pipeline/src/container-setup.ts +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Service Container Setup for Data Pipeline - * Configures dependency injection for the data pipeline service - */ - -import type { UnifiedAppConfig } from '@stock-bot/config'; -import type { IServiceContainer } from '@stock-bot/handlers'; -import { getLogger } from '@stock-bot/logger'; - -const logger = getLogger('data-pipeline-container'); - -/** - * Configure the service container for data pipeline workloads - */ -export function setupServiceContainer( - config: UnifiedAppConfig, - container: IServiceContainer -): IServiceContainer { - logger.info('Configuring data pipeline service container...'); - - // Data pipeline specific configuration - // This service does more complex queries and transformations - const poolSizes = { - mongodb: config.environment === 'production' ? 40 : 20, - postgres: config.environment === 'production' ? 50 : 25, - cache: config.environment === 'production' ? 30 : 15, - }; - - logger.info('Data pipeline pool sizes configured', poolSizes); - - // The container is already configured with connections - // Just return it with our logging - return container; -} diff --git a/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts b/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts index c28e6390..12a33a0c 100644 --- a/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts +++ b/apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts @@ -1,4 +1,8 @@ import { requireServices, type IServiceContainer } from '@stock-bot/services'; +import { + normalizeProviderSymbol, + type ProviderSymbolDocument, +} from '../../../normalization/provider-symbol'; import { PipelineSyncRepository, rejectDestructiveSync, @@ -21,7 +25,11 @@ export async function syncSymbolsFromProvider( throw new Error('A supported provider (qm, eod, ib) is required'); } const { mongodb, postgres } = requireServices(container, 'mongodb', 'postgres'); - const rows = await mongodb.getDatabase().collection(collection).find({}).toArray(); + const rows = await mongodb + .getDatabase() + .collection(collection) + .find({}) + .toArray(); return PipelineSyncRepository.transaction(postgres, async repository => { const result: SyncResult = { processed: rows.length, @@ -31,7 +39,8 @@ export async function syncSymbolsFromProvider( errors: 0, }; for (const row of rows) { - result[await repository.syncSymbol(provider, row)]++; + const symbol = normalizeProviderSymbol(row); + result[symbol ? await repository.syncSymbol(provider, symbol) : 'skipped']++; } await repository.updateStatus(provider, 'symbols', result.processed); return result; diff --git a/apps/stock/data-pipeline/src/index.ts b/apps/stock/data-pipeline/src/index.ts index 138a336a..77f3e449 100644 --- a/apps/stock/data-pipeline/src/index.ts +++ b/apps/stock/data-pipeline/src/index.ts @@ -7,7 +7,6 @@ import { createHttpSecurity, httpSecurityOptions, ServiceApplication } from '@st import { getLogger } from '@stock-bot/logger'; import { initializeStockConfig } from '@stock-bot/stock-config'; import { createRoutes } from './routes/create-routes'; -import { setupServiceContainer } from './container-setup'; // Local imports import { initializeAllHandlers } from './handlers'; @@ -49,10 +48,6 @@ const app = new ServiceApplication( { // Custom lifecycle hooks onAppReady: app => security.mount(app), - onContainerReady: container => { - // Setup service-specific configuration - setupServiceContainer(config, container); - }, onStarted: _port => { const logger = getLogger('data-pipeline'); logger.info('Data pipeline service startup initiated with ServiceApplication framework'); diff --git a/apps/stock/data-pipeline/src/normalization/provider-symbol.ts b/apps/stock/data-pipeline/src/normalization/provider-symbol.ts new file mode 100644 index 00000000..345c00bd --- /dev/null +++ b/apps/stock/data-pipeline/src/normalization/provider-symbol.ts @@ -0,0 +1,50 @@ +/** Fields retained by the QM, EOD and IB symbol collections, including older spellings. */ +export interface ProviderSymbolDocument { + symbol?: string | null; + code?: string | null; + Code?: string | null; + exchangeCode?: string | null; + exchange?: string | null; + exchange_id?: string | null; + Exchange?: string | null; + companyName?: string | null; + name?: string | null; + company_name?: string | null; + Name?: string | null; + countryCode?: string | null; + country_code?: string | null; + Country?: string | null; + currency?: string | null; + Currency?: string | null; + qmSearchCode?: string | null; + eodSearchCode?: string | null; +} + +/** Provider codes stay exact: exchange resolution and curated mappings belong to SQL. */ +export interface ProviderSymbol { + symbol: string; + exchangeCode: string; + providerSymbol: string; + companyName: string | null; + country: string | null; + currency: string | null; +} + +/** Preserve the existing field precedence without guessing suffixes or exchange aliases. */ +export function normalizeProviderSymbol(document: ProviderSymbolDocument): ProviderSymbol | null { + const symbol = document.symbol || document.code || document.Code; + const exchangeCode = + document.exchangeCode || document.exchange || document.exchange_id || document.Exchange; + if (!symbol || !exchangeCode) { + return null; + } + return { + symbol, + exchangeCode, + providerSymbol: document.qmSearchCode || document.eodSearchCode || symbol, + companyName: + document.companyName || document.name || document.company_name || document.Name || null, + country: document.countryCode || document.country_code || document.Country || null, + currency: document.currency || document.Currency || null, + }; +} diff --git a/apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts b/apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts index 7150640f..b50684d8 100644 --- a/apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts +++ b/apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts @@ -1,7 +1,7 @@ -import type { Document } from 'mongodb'; import type { TransactionCallback } from '@stock-bot/postgres'; import type { PostgresClient } from '@stock-bot/services'; import { parseReferenceDataResetRequest, type ReferenceDataResetScope } from '@stock-bot/types'; +import type { ProviderSymbol } from '../normalization/provider-symbol'; type SqlClient = Pick>[0], 'query'>; export type ResetScope = ReferenceDataResetScope; @@ -73,17 +73,14 @@ export class PipelineSyncRepository { return inserted.rows.length ? 'created' : 'skipped'; } - async syncSymbol(provider: string, symbol: Document): Promise<'created' | 'updated' | 'skipped'> { - const code = symbol.symbol || symbol.code || symbol.Code; - const exchangeCode = - symbol.exchangeCode || symbol.exchange || symbol.exchange_id || symbol.Exchange; - if (!code || !exchangeCode) { - return 'skipped'; - } + async syncSymbol( + provider: string, + symbol: ProviderSymbol + ): Promise<'created' | 'updated' | 'skipped'> { const mapping = await this.sql.query<{ master_exchange_id: string }>( `SELECT master_exchange_id FROM provider_exchange_mappings WHERE provider = $1 AND provider_exchange_code = $2 AND active = true`, - [provider, exchangeCode] + [provider, symbol.exchangeCode] ); const exchangeId = mapping.rows[0]?.master_exchange_id; if (!exchangeId) { @@ -91,7 +88,7 @@ export class PipelineSyncRepository { } const existing = await this.sql.query<{ id: string }>( 'SELECT id FROM symbols WHERE symbol = $1 AND exchange_id = $2', - [code, exchangeId] + [symbol.symbol, exchangeId] ); const saved = await this.sql.query<{ id: string }>( `INSERT INTO symbols (symbol, exchange_id, company_name, country, currency) @@ -99,13 +96,7 @@ export class PipelineSyncRepository { company_name = COALESCE(EXCLUDED.company_name, symbols.company_name), country = COALESCE(EXCLUDED.country, symbols.country), currency = COALESCE(EXCLUDED.currency, symbols.currency), updated_at = NOW() RETURNING id`, - [ - code, - exchangeId, - symbol.companyName || symbol.name || symbol.company_name || symbol.Name || null, - symbol.countryCode || symbol.country_code || symbol.Country || null, - symbol.currency || symbol.Currency || null, - ] + [symbol.symbol, exchangeId, symbol.companyName, symbol.country, symbol.currency] ); const symbolId = saved.rows[0]?.id; if (!symbolId) { @@ -117,12 +108,7 @@ export class PipelineSyncRepository { symbol_id = CASE WHEN provider_mappings.verified THEN provider_mappings.symbol_id ELSE EXCLUDED.symbol_id END, provider_exchange = CASE WHEN provider_mappings.verified THEN provider_mappings.provider_exchange ELSE EXCLUDED.provider_exchange END, last_seen = NOW()`, - [ - symbolId, - provider, - symbol.qmSearchCode || symbol.eodSearchCode || symbol.symbol || symbol.code || symbol.Code, - exchangeCode, - ] + [symbolId, provider, symbol.providerSymbol, symbol.exchangeCode] ); return existing.rows.length ? 'updated' : 'created'; } diff --git a/docs/development/backlog/tasks/CL34.md b/docs/development/backlog/tasks/CL34.md index 8b10abf2..4b083364 100644 --- a/docs/development/backlog/tasks/CL34.md +++ b/docs/development/backlog/tasks/CL34.md @@ -18,3 +18,7 @@ Provider variant fixtures; PostgreSQL pipeline mapping/safety; types/imports. Fo No new service/framework, financial simulator, real trading activation, external research execution, push/PR or .env changes. D04/P03/P05/P06/CL21 remain deferred. Root owns shared outputs, task state and commits; agents own disjoint files in the integration worktree. + +## Accepted verification + +Independent provider normalization suite: 6 passed, 10 assertions. Disposable PostgreSQL pipeline safety: 8 passed, 28 assertions, including verified mapping preservation, unverified update and replay identity. Scoped lint/format passed; active QM session manager preserved. diff --git a/test/integration/provider-symbol.test.ts b/test/integration/provider-symbol.test.ts new file mode 100644 index 00000000..cb1b9483 --- /dev/null +++ b/test/integration/provider-symbol.test.ts @@ -0,0 +1,148 @@ +import { expect, test } from 'bun:test'; +import { + normalizeProviderSymbol, + type ProviderSymbol, + type ProviderSymbolDocument, +} from '../../apps/stock/data-pipeline/src/normalization/provider-symbol'; + +const variants: { + name: string; + input: ProviderSymbolDocument; + expected: ProviderSymbol; +}[] = [ + { + name: 'QM camel case fields and qualified search code', + input: { + symbol: 'RY', + exchangeCode: 'TSX', + qmSearchCode: 'RY:CA', + companyName: 'Royal Bank', + countryCode: 'CA', + currency: 'CAD', + }, + expected: { + symbol: 'RY', + exchangeCode: 'TSX', + providerSymbol: 'RY:CA', + companyName: 'Royal Bank', + country: 'CA', + currency: 'CAD', + }, + }, + { + name: 'EOD title case fields and qualified search code', + input: { + Code: 'RY', + Exchange: 'TO', + eodSearchCode: 'RY.TO', + Name: 'Royal Bank', + Country: 'CA', + Currency: 'CAD', + }, + expected: { + symbol: 'RY', + exchangeCode: 'TO', + providerSymbol: 'RY.TO', + companyName: 'Royal Bank', + country: 'CA', + currency: 'CAD', + }, + }, + { + name: 'IB style code and snake case fields', + input: { + code: 'BRK.B', + exchange_id: 'NYSE', + company_name: 'Berkshire', + country_code: 'US', + currency: 'USD', + }, + expected: { + symbol: 'BRK.B', + exchangeCode: 'NYSE', + providerSymbol: 'BRK.B', + companyName: 'Berkshire', + country: 'US', + currency: 'USD', + }, + }, + { + name: 'older lowercase exchange and name', + input: { symbol: 'aapl', exchange: 'nas', name: 'Apple' }, + expected: { + symbol: 'aapl', + exchangeCode: 'nas', + providerSymbol: 'aapl', + companyName: 'Apple', + country: null, + currency: null, + }, + }, +]; + +test.each(variants)( + 'normalizes $name without changing provider identity', + ({ input, expected }) => { + expect(normalizeProviderSymbol(Object.freeze(input))).toEqual(expected); + } +); + +test('mixed and empty field variants preserve historical precedence', () => { + expect( + normalizeProviderSymbol({ + symbol: 'FIRST', + code: 'SECOND', + Code: 'THIRD', + exchangeCode: 'FIRST_EXCHANGE', + exchange: 'SECOND_EXCHANGE', + exchange_id: 'THIRD_EXCHANGE', + Exchange: 'FOURTH_EXCHANGE', + qmSearchCode: 'FIRST_SEARCH', + eodSearchCode: 'SECOND_SEARCH', + companyName: 'FIRST_NAME', + name: 'SECOND_NAME', + company_name: 'THIRD_NAME', + Name: 'FOURTH_NAME', + countryCode: 'CA', + country_code: 'US', + Country: 'GB', + currency: 'CAD', + Currency: 'USD', + }) + ).toEqual({ + symbol: 'FIRST', + exchangeCode: 'FIRST_EXCHANGE', + providerSymbol: 'FIRST_SEARCH', + companyName: 'FIRST_NAME', + country: 'CA', + currency: 'CAD', + }); + expect( + normalizeProviderSymbol({ + symbol: '', + code: '', + Code: 'RY', + exchangeCode: null, + exchange: '', + exchange_id: '', + Exchange: 'TO', + qmSearchCode: '', + eodSearchCode: 'RY.TO', + companyName: '', + name: '', + company_name: '', + Name: 'Royal Bank', + countryCode: '', + country_code: '', + Country: 'CA', + currency: '', + Currency: 'CAD', + }) + ).toEqual(variants[1]!.expected); +}); + +test('incomplete symbol identities remain skipped instead of manufacturing a mapping', () => { + for (const input of [{}, { symbol: 'RY' }, { Exchange: 'TO' }, { Code: '', Exchange: 'TO' }]) { + expect(normalizeProviderSymbol(input)).toBeNull(); + } +}); diff --git a/test/postgres/pipeline-safety.test.ts b/test/postgres/pipeline-safety.test.ts index 05cd3758..e3b6ee8e 100644 --- a/test/postgres/pipeline-safety.test.ts +++ b/test/postgres/pipeline-safety.test.ts @@ -15,12 +15,15 @@ const logger = getLogger('pipeline-postgres-test'); const url = process.env.PIPELINE_TEST_DATABASE_URL; const cleanup: (() => Promise)[] = []; afterEach(async () => { - for (const close of cleanup.splice(0).reverse()) await close(); + for (const close of cleanup.splice(0).reverse()) { + await close(); + } }); async function fixture() { - if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) + if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) { throw new Error('A dedicated stock_bot_safety database is required'); + } const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`; const admin = new Pool({ connectionString: url }); await admin.query(`CREATE SCHEMA ${schema}`); @@ -154,6 +157,62 @@ describe.skipIf(!url)('pipeline safety on real PostgreSQL', () => { ).rejects.toThrow('non-destructive'); }); + test('normalized symbol sync preserves verified mapping ownership and replay identity', async () => { + const f = await fixture(); + const original = ( + await f.pool.query( + 'SELECT id, symbol_id, provider, provider_symbol, provider_exchange, verified FROM provider_mappings' + ) + ).rows[0]; + await f.pool.query( + `INSERT INTO provider_mappings (provider, provider_symbol, symbol_id, verified) + SELECT 'eod', 'ROUTE.TO', id, false FROM symbols WHERE symbol = 'KEEP'` + ); + f.documents.eodSymbols = [ + { Code: 'MOVED', Exchange: 'TO', eodSearchCode: 'KEEP.TO', Name: 'Moved', Currency: 'CAD' }, + { code: 'ROUTE', exchange_id: 'TO', eodSearchCode: 'ROUTE.TO', company_name: 'Route' }, + { Code: 'MISSING_EXCHANGE' }, + ]; + expect(await syncSymbolsFromProvider({ provider: 'EOD' }, f.services)).toEqual({ + processed: 3, + created: 2, + updated: 0, + skipped: 1, + errors: 0, + }); + expect( + ( + await f.pool.query( + `SELECT id, symbol_id, provider, provider_symbol, provider_exchange, verified + FROM provider_mappings WHERE provider_symbol = 'KEEP.TO'` + ) + ).rows[0] + ).toEqual(original); + expect( + ( + await f.pool.query( + `SELECT s.symbol, m.provider_exchange FROM provider_mappings m + JOIN symbols s ON s.id = m.symbol_id WHERE m.provider_symbol = 'ROUTE.TO'` + ) + ).rows + ).toEqual([{ symbol: 'ROUTE', provider_exchange: 'TO' }]); + const beforeReplay = (await f.pool.query('SELECT id, symbol FROM symbols ORDER BY symbol')) + .rows; + expect(await syncSymbolsFromProvider({ provider: 'eod' }, f.services)).toEqual({ + processed: 3, + created: 0, + updated: 2, + skipped: 1, + errors: 0, + }); + expect((await f.pool.query('SELECT id, symbol FROM symbols ORDER BY symbol')).rows).toEqual( + beforeReplay + ); + expect( + (await f.pool.query("SELECT last_sync_count FROM sync_status WHERE provider = 'eod'")).rows + ).toEqual([{ last_sync_count: 3 }]); + }); + test('QM mapping writes also roll back as one transaction', async () => { const f = await fixture(); const before = await f.snapshot();