diff --git a/docs/development/cleanup-execution.md b/docs/development/cleanup-execution.md index d0768426..031227ec 100644 --- a/docs/development/cleanup-execution.md +++ b/docs/development/cleanup-execution.md @@ -110,3 +110,20 @@ Implementation references: plan `4ddffa6b`; foundations `805a9f8f`; shared resea application cleanup (including the reviewed foundation follow-up) `8c39ccf7`. All 13 manifest entries identify the validated implementation tree while reserving completed commit/sign-off for acceptance of independent review. + +## Review follow-up — October 26 + +See [cleanup-review.md](cleanup-review.md) for reproduced findings, corrections and the +actual-data pilot. Fixed lifecycle reuse, bounded rollback, Redis ACL forwarding and +preservation of omitted PostgreSQL server timeout settings. These are CL02/CL03 follow-ups; +other cleanup stories remain unchanged and none has received independent sign-off yet. + +The read-only pilot found stored intraday data but zero retained datasets and a concrete +null-volume/session preparation blocker. No real-market backtest result was invented, +no eligibility gate was weakened and no development database was modified. + +Follow-up gate: `CARGO_BUILD_JOBS=2 bun run check` passed with 1,226 integration tests +(14 existing skips), 132 tooling, 43 utility, 44 calculation and 150 Rust tests +(4 ignored), plus build/types/contracts/secret audit/lint. The focused lifecycle and +store regressions passed 35 tests / 115 assertions. No financial simulation or strategy +policy was changed by these corrections. diff --git a/docs/development/cleanup-review.md b/docs/development/cleanup-review.md new file mode 100644 index 00000000..b2f37d15 --- /dev/null +++ b/docs/development/cleanup-review.md @@ -0,0 +1,84 @@ +# Cleanup review and first research pilot + +Review baseline: `512f2f1c`, October 26, 2026. This records the primary agent's +follow-up inspection and fixes, **not independent sign-off**. The 13 cleanup stories +remain in `review`. A request to use three independent read-only reviewer agents is +pending; no separate reviewer has been launched or represented as approving this work. + +## Findings and corrections + +| Finding | Severity / evidence | Correction and regression | +| --- | --- | --- | +| CL03: cleanup was remembered across connection lifetimes | High / Verified: two initialize/shutdown cycles produced two connects and only one disconnect | Reset cleanup ownership before a fresh connection, wait for an earlier close, and reject overlapping unresolved initialization. Test repeated cycles and retry after a timed-out pending initializer. | +| CL03: rollback could hang indefinitely | High / Verified: a never-settling disconnect kept the original startup rejection pending beyond the initialization timeout | Bound rollback waiting by the configured timeout, keep its promise owned, clear the timer and preserve the original failure. Test a deferred disconnect and eventual cleanup. | +| CL02: Redis ACL username was dropped | Medium / Verified: the core schema accepted username, but cache/global cache, proxy/queue adapters and the rate-limiter connection omitted it | Forward username through the existing adapters and queue config. A separate child process substitutes only ioredis, captures both real constructor settings and queue worker connection settings, and opens no sockets. | +| CL02: omitted PostgreSQL timeouts became explicit zero | High / Verified: the DI mapping supplied query, statement, lock and idle-transaction zero values without corresponding user settings | Make individual client timeout fields optional and forward only the configured connection timeout. Assert omitted wire fields stay undefined so server-configured limits remain effective. | + +Implementation: [lifecycle](../../libs/core/di/src/utils/lifecycle.ts), +[database mapping](../../libs/core/di/src/registrations/database.registration.ts), +[cache mapping](../../libs/core/di/src/registrations/cache.registration.ts), +[service mapping](../../libs/core/di/src/registrations/service.registration.ts), +[queue transport](../../libs/core/queue/src/queue-manager.ts). +MongoDB's adapter now states its existing effective minimum pool size (one), instead of +passing zero into a client that treats zero as its fallback of one. + +The backend inspection checked canonical-only admission, exact receipt recovery before +mutable eligibility checks, run/outbox transaction order, result reads using an existing +transaction connection, retained artifact identity and historical result compatibility. +The frontend inspection checked request ownership across route changes, exact retry bodies, +submission-mode exclusion and cookie transport without automatic retries. This pass found +no additional blocking issue in those extracted paths; an independent review is still needed. +Rust accounting, matching, risk and strategy decision semantics were not changed. + +## Validation + +- `bun test test/integration/store-configuration.test.ts test/integration/questdb-configuration.test.ts libs/core/di/test/container-builder.test.ts libs/core/di/test/lifecycle.test.ts test/integration/service-startup-rollback.test.ts` — 35 pass / 115 assertions. +- PostgreSQL, queue and DI package builds, plus `bun run typecheck` — pass. +- Full combined check outcome is recorded in [cleanup-execution.md](cleanup-execution.md). +- No PostgreSQL/browser suite rerun is claimed for this follow-up. The previous 273 SQL + and 18 browser passes belong to the preceding cleanup implementation tree. These fixes + change configuration/lifecycle paths; SQL transaction and browser application code is unchanged. + +## Actual-data pilot: stopped at preparation + +Read-only checks used the configured development stores; no records, credentials, source +prices or trading state were changed. Network-isolated connection failures were rechecked +outside the sandbox before drawing conclusions. + +- PostgreSQL contained **zero retained datasets**, 138 existing runs and one strategy. + Existing runs alone do not establish canonical research readiness. +- MongoDB contains indexed EOD intraday history. A bounded October 2024 five-minute query + returned no SPY.US rows and **1,816 AAPL.US rows over 23 dates**. +- **22 AAPL rows have null volume**, all at **20:00 UTC**; no duplicate timestamps were + observed in that sample. Their timing is a diagnostic, not proof of an approved session + exclusion rule. The current strict historical reader rejects null-volume rows before + dataset preparation, so this whole-window source is not directly ready for admission. +- The exact raw query snapshot hash is + `a8772d01d388b8fc9bca0d2790ad0d37146570fd09d057fcf1f1fcb5e6113bde`. + This hashes source-query JSON, **not** the canonical dataset format. The temporary capture + is `/tmp/stock-bot-review-20261026/aapl-2024-10-source.json`, with diagnostics in + `/tmp/stock-bot-review-20261026/data-quality.json`; temporary storage is not durable custody. +- Session/calendar identity, timestamp-availability assumptions and corporate-action + coverage still need supported declarations. Unknown coverage was not relabelled eligible. + +No financial simulation, parameter selection, alpha claim or paper activation was made +from these raw observations. No real-market result or finding was saved without evidence. +Synthetic integration examples remain test evidence, not a substitute for this pilot. + +## Next useful vertical slice + +The next product work should make this preparation explicit using the existing source +preview/retain APIs and workbench, without adding another research engine: + +1. Inspect indexed asset/timeframe/date coverage before selecting a source window. +2. Show quality diagnostics and proposed session inclusion/exclusion with counts. Any + approved transformation must retain its source snapshot, policy and exclusions; + never turn null volume into zero or silently omit unexplained records. +3. Supply reviewed calendar/timing/action metadata, preview eligibility, and freeze a + dataset through the existing retention path. Keep exploratory and execution eligibility + distinct. Do not weaken the worker's eligible-dataset gate to make a demonstration run. +4. Run one reviewed TypeScript baseline on Rust, then a bounded chronological/cost study, + reopen results and save a source-linked finding. Report sample and data limitations. + +MCP/notebook tooling can wrap these verified interfaces later. The immediate gap is getting +existing stored market history into inspectable, trustworthy research inputs. diff --git a/libs/core/di/src/registrations/cache.registration.ts b/libs/core/di/src/registrations/cache.registration.ts index cfba72da..d0a7204e 100644 --- a/libs/core/di/src/registrations/cache.registration.ts +++ b/libs/core/di/src/registrations/cache.registration.ts @@ -20,6 +20,7 @@ export function registerCacheServices( host: config.redis.host, port: config.redis.port, password: config.redis.password, + username: config.redis.username, db: config.redis.db, // This will be overridden by ServiceCache }, { logger } @@ -37,6 +38,7 @@ export function registerCacheServices( host: config.redis.host, port: config.redis.port, password: config.redis.password, + username: config.redis.username, }, { global: true, logger } ); diff --git a/libs/core/di/src/registrations/database.registration.ts b/libs/core/di/src/registrations/database.registration.ts index cec2f794..1f4aec04 100644 --- a/libs/core/di/src/registrations/database.registration.ts +++ b/libs/core/di/src/registrations/database.registration.ts @@ -26,7 +26,7 @@ export function registerDatabaseServices( uri: config.mongodb.uri, poolSettings: { maxPoolSize: config.mongodb.poolSize, - minPoolSize: 0, + minPoolSize: 1, maxIdleTime: 10000, }, }; @@ -55,13 +55,8 @@ export function registerDatabaseServices( max: config.postgres.poolSize, idleTimeoutMillis: config.postgres.idleTimeout, }, - timeouts: { - connection: config.postgres.connectionTimeout, - query: 0, - statement: 0, - lock: 0, - idleInTransaction: 0, - }, + // Omitted query/session limits retain the server's configured defaults. + timeouts: { connection: config.postgres.connectionTimeout }, }; logger.debug('PostgreSQL config:', { diff --git a/libs/core/di/src/registrations/service.registration.ts b/libs/core/di/src/registrations/service.registration.ts index e86b532e..4e746ced 100644 --- a/libs/core/di/src/registrations/service.registration.ts +++ b/libs/core/di/src/registrations/service.registration.ts @@ -38,6 +38,7 @@ export function registerApplicationServices( host: config.redis.host, port: config.redis.port, password: config.redis.password, + username: config.redis.username, db: 1, // Use cache DB (usually DB 1) }, keyPrefix: 'cache:proxy:', @@ -70,6 +71,7 @@ export function registerApplicationServices( host: config.redis.host, port: config.redis.port, password: config.redis.password, + username: config.redis.username, db: config.redis.db, }, defaultQueueOptions: { diff --git a/libs/core/di/src/utils/lifecycle.ts b/libs/core/di/src/utils/lifecycle.ts index b9537131..fa196a93 100644 --- a/libs/core/di/src/utils/lifecycle.ts +++ b/libs/core/di/src/utils/lifecycle.ts @@ -34,14 +34,33 @@ export class ServiceLifecycleManager { if (!service) { return Promise.resolve(); } + if (this.initializing.has(service)) { + throw new Error(`${name} initialization is already in progress`); + } + this.initializing.add(service); const entry = { name, service, settled: false }; started.push(entry); // A timeout cannot cancel connect(). Keep ownership until it settles, // including resources allocated by an initializer that later rejects. - const initialization = this.initializeService(name, service).finally(async () => { + const initialization = (async () => { + // A completed shutdown belongs to the preceding connection lifetime. + // Wait for an in-flight close before starting a fresh lifetime. + const previousCleanup = this.cleanup.get(service); + if (previousCleanup) { + await previousCleanup; + } + if (!failed) { + this.cleanup.delete(service); + await this.initializeService(name, service); + } + })().finally(async () => { entry.settled = true; - if (failed) { - await this.cleanupOnce(name, service); + try { + if (failed) { + await this.cleanupOnce(name, service); + } + } finally { + this.initializing.delete(service); } }); let timer: ReturnType; @@ -61,12 +80,28 @@ export class ServiceLifecycleManager { failed = true; // Only settled work can be released finally. Pending work retains the // cleanup continuation above, so startup need not wait on a hung connect. - await Promise.allSettled( + const rollback = Promise.allSettled( started .filter(entry => entry.settled) .reverse() .map(({ name, service }) => this.cleanupOnce(name, service)) ); + let cleanupTimer: ReturnType | undefined; + try { + // A hanging disconnect must not turn a bounded startup failure into a + // permanently pending build. Keep the cleanup promise owned after this cap. + await Promise.race([ + rollback, + new Promise(resolve => { + cleanupTimer = setTimeout(() => { + this.logger.warn(`Startup rollback still pending after ${timeout}ms`); + resolve(); + }, timeout); + }), + ]); + } finally { + clearTimeout(cleanupTimer); + } throw error; } finally { for (const clear of cancelTimers) { @@ -75,6 +110,7 @@ export class ServiceLifecycleManager { } } + private readonly initializing = new WeakSet(); private readonly cleanup = new WeakMap>(); private cleanupOnce(name: string, service: ServiceWithLifecycle): Promise { diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index 44f16839..1a0f024e 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -65,6 +65,7 @@ export class QueueManager { host: config.redis.host, port: config.redis.port, password: config.redis.password, + username: config.redis.username, db: config.redis.db || 0, maxRetriesPerRequest: 3, enableReadyCheck: true, diff --git a/libs/core/queue/src/types.ts b/libs/core/queue/src/types.ts index 9960e2db..ea473ff5 100644 --- a/libs/core/queue/src/types.ts +++ b/libs/core/queue/src/types.ts @@ -42,6 +42,7 @@ export interface RedisConfig { host: string; port: number; password?: string; + username?: string; db?: number; } diff --git a/libs/data/postgres/src/types.ts b/libs/data/postgres/src/types.ts index 78e9b55c..9737201e 100644 --- a/libs/data/postgres/src/types.ts +++ b/libs/data/postgres/src/types.ts @@ -19,11 +19,11 @@ export interface PostgreSQLClientConfig { rejectUnauthorized: boolean; }; timeouts?: { - query: number; - connection: number; - statement: number; - lock: number; - idleInTransaction: number; + query?: number; + connection?: number; + statement?: number; + lock?: number; + idleInTransaction?: number; }; } diff --git a/test/integration/service-startup-rollback.test.ts b/test/integration/service-startup-rollback.test.ts index 86d30684..d1256f7e 100644 --- a/test/integration/service-startup-rollback.test.ts +++ b/test/integration/service-startup-rollback.test.ts @@ -94,3 +94,54 @@ test('successful initialization clears timeout handles immediately', async () => clearTimeout(timer); } }); + +test('reusing a manager after shutdown closes each new connection lifetime once', async () => { + const connect = mock(async () => {}), + disconnect = mock(async () => {}); + const c = container({ cache: { connect, disconnect } }); + const manager = new ServiceLifecycleManager(); + await manager.initializeServices(c); + await manager.shutdownServices(c); + await manager.shutdownServices(c); + await manager.initializeServices(c); + await manager.shutdownServices(c); + expect(connect).toHaveBeenCalledTimes(2); + expect(disconnect).toHaveBeenCalledTimes(2); +}); + +test('hung rollback does not hide or indefinitely delay the original startup failure', async () => { + const pending = deferred(); + const failure = new Error('startup failed'); + const disconnect = mock(() => pending.promise); + const c = container({ + cache: { connect: async () => {}, disconnect }, + mongoClient: { + connect: async () => { + throw failure; + }, + }, + }); + const manager = new ServiceLifecycleManager(); + try { + await expect(manager.initializeServices(c, 5)).rejects.toBe(failure); + expect(disconnect).toHaveBeenCalledTimes(1); + } finally { + pending.resolve(); + } + await manager.shutdownServices(c); + expect(disconnect).toHaveBeenCalledTimes(1); +}); + +test('a retry cannot overlap an earlier unresolved initializer after a timeout', async () => { + const pending = deferred(); + const connect = mock(() => pending.promise), + disconnect = mock(async () => {}); + const c = container({ cache: { connect, disconnect } }); + const manager = new ServiceLifecycleManager(); + await expect(manager.initializeServices(c, 5)).rejects.toThrow('timed out'); + await expect(manager.initializeServices(c, 5)).rejects.toThrow('already in progress'); + expect(connect).toHaveBeenCalledTimes(1); + pending.resolve(); + await Bun.sleep(0); + expect(disconnect).toHaveBeenCalledTimes(1); +}); diff --git a/test/integration/store-configuration.test.ts b/test/integration/store-configuration.test.ts index 2b623e7c..b1160ba2 100644 --- a/test/integration/store-configuration.test.ts +++ b/test/integration/store-configuration.test.ts @@ -88,6 +88,14 @@ test('PostgreSQL nondefault fields reach wire configuration and Mongo retains UR connectionTimeoutMillis: 4321, idleTimeoutMillis: 8765, }); + for (const key of [ + 'query_timeout', + 'statement_timeout', + 'lock_timeout', + 'idle_in_transaction_session_timeout', + ] as const) { + expect(wire[key]).toBeUndefined(); + } const mongo = c.resolve('mongoClient') as unknown as { config: { uri: string; poolSettings: { maxPoolSize: number } }; }; @@ -148,3 +156,53 @@ test('all-disabled default composition needs neither store settings nor connecti await c.dispose(); } }); + +test('Redis ACL username reaches cache and both queue connection settings without opening sockets', async () => { + // Isolate the transport substitution: Bun module mocks otherwise leak between suites. + const child = Bun.spawn( + [ + process.execPath, + '-e', + String.raw` + import {mock} from 'bun:test'; + const captured=[]; + class Redis { + constructor(options){captured.push(options);} + on(){return this;} + disconnect(){} + async quit(){} + } + mock.module('ioredis',()=>({default:Redis,Redis,Cluster:Redis})); + const {ServiceContainerBuilder}=await import('./libs/core/di/src/container/builder.ts'); + const c=await new ServiceContainerBuilder().withConfig({ + name:'redis-auth-test',version:'1.0.0',service:{name:'redis-auth-test',port:3000},log:{level:'fatal'}, + database:{dragonfly:{enabled:true,host:'redis.fixture.test',username:'research-reader',password:'fixture-only'}, + mongodb:{enabled:false,uri:'mongodb://localhost/test',database:'test'}, + postgres:{enabled:false,database:'test',user:'test',password:'fixture-only'},questdb:{enabled:false}}, + }).withOptions({enableBrowser:false,enableProxy:false}).skipInitialization().build(); + c.resolve('cache');c.resolve('globalCache'); + const queue=c.resolve('queueManager'); + process.stdout.write('__redis_capture__'+JSON.stringify({captured,queue:queue.redisConnection})+'\n'); + await c.dispose(); + `, + ], + { stdout: 'pipe', stderr: 'pipe' } + ); + const [stdout, stderr, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + if (code !== 0) throw new Error(`Redis transport probe failed: ${stderr}`); + const line = stdout.split('\n').find(line => line.startsWith('__redis_capture__')); + expect(line).toBeDefined(); + const result = JSON.parse(line!.slice('__redis_capture__'.length)); + expect(result.captured).toHaveLength(2); + for (const config of [...result.captured, result.queue]) { + expect(config).toMatchObject({ + host: 'redis.fixture.test', + username: 'research-reader', + password: 'fixture-only', + }); + } +});