diff --git a/docs/development/architecture-cleanup-execution.md b/docs/development/architecture-cleanup-execution.md index c350e56a..318ec7f2 100644 --- a/docs/development/architecture-cleanup-execution.md +++ b/docs/development/architecture-cleanup-execution.md @@ -9,3 +9,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone - **CL24:** Root reviewed route compatibility, removed demo-only consumers and real App rendering. Focused home/navigation tests passed; scoped lint/format passed. Final browser gate pending combined source. + +- **CL22:** Queue library tsc build passed; independent root queue-lifecycle and cache-ownership suites passed (see /tmp/stock-bot-cl22-root.log). Scoped lint/format passed. Pending payload ownership, drain behavior, and connection cleanup covered without service mutation. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 029e20ef..39f55230 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -1,6 +1,6 @@ # Canonical development backlog -**Active: E13 architecture cleanup, CL22–CL35 (1/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). +**Active: E13 architecture cleanup, CL22–CL35 (2/14 complete).** Owner authorized all October 28 audit recommendations and a commit per validated task. Earlier completion counts below are historical. [Execution record](../architecture-cleanup-execution.md). **Current scheduled backlog: 99/99 complete.** The owner resumed performance and authorized review of all seven conditions. P08 and O02 are implemented; five optional extensions remain deliberately deferred, and four merged IDs are redirects. This is not a claim that all 108 retained IDs were implemented. [Decisions, measurements and validation](../conditional-review.md). diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 6e4d39b7..d69de824 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -3750,7 +3750,7 @@ "epic": "E13", "priority": "P1", "severity": "High", - "status": "in_progress", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL22.md", @@ -3760,7 +3760,9 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "completion_evidence": "architecture-cleanup-execution.md" + "completion_evidence": "architecture-cleanup-execution.md", + "integration_state": "accepted", + "validation": "Queue library tsc build passed; independent root queue-lifecycle and cache-ownership suites passed (see /tmp/stock-bot-cl22-root.log). Scoped lint/format passed. Pending payload ownership, drain behavior, and connection cleanup covered without service mutation." }, { "id": "CL23", @@ -3793,7 +3795,7 @@ "complexity": "M", "assignment": null, "write_locks": ["CL24"], - "completed_commit": null, + "completed_commit": "5400dba47ee4fbd0f1aa0f12a358864df6bb7a38", "blocker": null, "release_gates": [], "completion_evidence": "architecture-cleanup-execution.md", @@ -10383,7 +10385,7 @@ ], "work_policy": "Root integrates/commits reviewed tasks; agents own disjoint explicit files in the root integration worktree. Only root builds shared outputs and runs combined gates. No isolated native agent build claim.", "first_wave": ["CL22", "CL23", "CL24"], - "completed": 1, - "last_verification": "Root reviewed route compatibility, removed demo-only consumers and real App rendering. Focused home/navigation tests passed; scoped lint/format passed. Final browser gate pending combined source." + "completed": 2, + "last_verification": "Queue library tsc build passed; independent root queue-lifecycle and cache-ownership suites passed (see /tmp/stock-bot-cl22-root.log). Scoped lint/format passed. Pending payload ownership, drain behavior, and connection cleanup covered without service mutation." } } diff --git a/docs/development/backlog/tasks/CL22.md b/docs/development/backlog/tasks/CL22.md index d51e777b..c2c3c0a2 100644 --- a/docs/development/backlog/tasks/CL22.md +++ b/docs/development/backlog/tasks/CL22.md @@ -18,3 +18,7 @@ Queue lifecycle/cache ownership regressions; disposable Redis payload survival. 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 + +Queue library tsc build passed; independent root queue-lifecycle and cache-ownership suites passed (see /tmp/stock-bot-cl22-root.log). Scoped lint/format passed. Pending payload ownership, drain behavior, and connection cleanup covered without service mutation. diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index ea2d0b7d..846cbaad 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -31,7 +31,7 @@ export class QueueManager { private rateLimiter?: QueueRateLimiter; private redisConnection: ReturnType; private ioredisConnection?: Redis; - private isShuttingDown = false; + private lifecycle: 'running' | 'draining' | 'closed' = 'running'; private shutdownPromise: Promise | null = null; private config: QueueManagerConfig; private readonly logger: Logger; @@ -95,6 +95,7 @@ export class QueueManager { * If serviceName is configured, automatically handles namespacing */ getQueue(queueName: string, options: QueueOptions = {}): Queue { + this.assertConnectionsOpen(); let fullQueueName = queueName; let isOwnQueue = true; @@ -135,6 +136,9 @@ export class QueueManager { return existingQueue; } } + if (this.lifecycle !== 'running') { + throw new Error('QueueManager is shutting down; new queues cannot be created'); + } // Create new queue with merged options const mergedOptions = { @@ -167,12 +171,9 @@ export class QueueManager { // Store the queue this.queues.set(queueName, queue); - // Automatically initialize batch cache for the queue - this.initializeBatchCacheSync(queueName); - // Rate limit rules are now added via addRateLimitRules after handlers are initialized - this.logger.info('Queue created with batch cache', { + this.logger.info('Queue created', { queueName, originalQueueName: options.handlerRegistry ? 'has-handler-registry' : 'no-handler-registry', workers: workers, @@ -204,6 +205,7 @@ export class QueueManager { * Get or create a cache for a queue */ getCache(queueName: string): CacheProvider { + this.assertConnectionsOpen(); if (!this.caches.has(queueName)) { const cacheProvider = createCache({ redisConfig: this.config.redis, @@ -241,16 +243,6 @@ export class QueueManager { this.logger.info('Cache initialized for queue', { queueName }); } - /** - * Initialize batch cache synchronously (for automatic initialization) - * The cache will be ready for use, but we don't wait for Redis connection - */ - private initializeBatchCacheSync(queueName: string): void { - // Just create the cache - it will connect automatically when first used - this.getCache(queueName); - this.logger.trace('Batch cache initialized synchronously for queue', { queueName }); - } - /** * Get the queues map (for subclasses) */ @@ -455,89 +447,82 @@ export class QueueManager { /** * Shutdown all queues and workers (thread-safe) */ - async shutdown(): Promise { - // If already shutting down, return the existing promise - if (this.shutdownPromise) { - return this.shutdownPromise; + shutdown(): Promise { + if (!this.shutdownPromise) { + this.lifecycle = 'draining'; + this.logger.info('Shutting down QueueManager...'); + // Store the promise before invoking owned transports, including cleanup + // callbacks that can request shutdown again. + this.shutdownPromise = Promise.resolve().then(() => this.performShutdown()); } - - if (this.isShuttingDown) { - return; - } - - this.isShuttingDown = true; - this.logger.info('Shutting down QueueManager...'); - - // Create shutdown promise - this.shutdownPromise = this.performShutdown(); return this.shutdownPromise; } - /** - * Perform the actual shutdown - */ - private async performShutdown(): Promise { + private assertConnectionsOpen(): void { + if (this.lifecycle === 'closed') { + throw new Error('QueueManager is closed'); + } + } + + private async closeQueue(queue: Pick): Promise { + let timer: ReturnType | undefined; try { - // Close all queues (this now includes workers since they're managed by Queue class) - const queueShutdownPromises = Array.from(this.queues.values()).map(async queue => { + await Promise.race([ + queue.close(), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('Queue close timeout')), 5000); + }), + ]); + } catch (error) { + this.logger.warn('Error closing queue', { error }); + } finally { + clearTimeout(timer); + } + } + + private async performShutdown(): Promise { + // Active workers may still read batch payloads or publish child jobs while + // their queues drain. Close those connections only after queue close settles. + await Promise.all([...this.queues.values()].map(queue => this.closeQueue(queue))); + this.lifecycle = 'closed'; + await Promise.all([...this.producerQueues.values()].map(queue => this.closeQueue(queue))); + await Promise.all( + [...this.caches.values()].map(async cache => { try { - // Add timeout to queue.close() to prevent hanging - const closePromise = queue.close(); - const timeoutPromise = new Promise( - (_, reject) => setTimeout(() => reject(new Error('Queue close timeout')), 5000) // 5 second timeout per queue - ); - - await Promise.race([closePromise, timeoutPromise]); - } catch (error) { - this.logger.warn('Error closing queue', { error: (error as Error).message }); - } - }); - - await Promise.all(queueShutdownPromises); - - // Close all caches - const cacheShutdownPromises = Array.from(this.caches.values()).map(async cache => { - try { - // Clear cache before shutdown - await cache.clear(); - } catch (error) { - this.logger.warn('Error clearing cache', { error: (error as Error).message }); - } finally { + // Batch payloads belong to queued work, not to this process. Completion + // cleanup and TTL own deletion, even when another process uses this namespace. await cache.disconnect?.(); - } - }); - - await Promise.all(cacheShutdownPromises); - - // Close ioredis connection - if (this.ioredisConnection) { - try { - await this.ioredisConnection.quit(); - this.logger.debug('IoRedis connection closed'); } catch (error) { - this.logger.warn('Error closing ioredis connection', { error: (error as Error).message }); + this.logger.warn('Error disconnecting batch cache', { error }); + } + }) + ); + if (this.ioredisConnection) { + try { + await this.ioredisConnection.quit(); + } catch (error) { + this.logger.warn('Error closing ioredis connection', { error }); + try { + this.ioredisConnection.disconnect(); + } catch (disconnectError) { + this.logger.warn('Error disconnecting ioredis connection', { error: disconnectError }); } } - - // Clear collections - this.queues.clear(); - this.caches.clear(); - - this.logger.info('QueueManager shutdown complete'); - } catch (error) { - this.logger.error('Error during shutdown', { error: (error as Error).message }); - throw error; - } finally { - // Reset shutdown state - this.shutdownPromise = null; - this.isShuttingDown = false; } + this.queues.clear(); + this.producerQueues.clear(); + this.caches.clear(); + this.ioredisConnection = undefined; + this.logger.info('QueueManager shutdown complete'); } /** * Start workers for all queues (used when delayWorkerStart is enabled) */ startAllWorkers(): void { + if (this.lifecycle !== 'running') { + throw new Error('QueueManager is shutting down; workers cannot be started'); + } let workersStarted = 0; const queues = this.queues; @@ -699,6 +684,7 @@ export class QueueManager { * Get a producer queue for sending to other services */ private getProducerQueue(queueName: string): BullQueue { + this.assertConnectionsOpen(); if (!this.producerQueues.has(queueName)) { const queue = new BullQueue(queueName, { connection: this.redisConnection, diff --git a/test/integration/queue-lifecycle.test.ts b/test/integration/queue-lifecycle.test.ts new file mode 100644 index 00000000..0db4d78e --- /dev/null +++ b/test/integration/queue-lifecycle.test.ts @@ -0,0 +1,185 @@ +import { expect, test } from 'bun:test'; + +// Keep module mocks in a child. QueueManager, Queue, RedisCache and batch processing +// are the real implementations; only Redis/BullMQ transports are replaced. +const transports = String.raw` + import { mock } from 'bun:test'; + import { EventEmitter } from 'node:events'; + const sockets = [], handles = [], values = new Map(), writes = [], warnings = []; + let workerCount = 0, eventCount = 0, clears = 0; + class Redis { + constructor(options) { this.options = options; this.closed = 0; this.quits = 0; this.status = 'ready'; sockets.push(this); } + on() { return this; } + async setex(key, ttl, value) { values.set(key, value); writes.push({key, ttl}); } + async get(key) { if (this.closed) throw new Error('closed socket'); return values.get(key) ?? null; } + async del(key) { values.delete(key); } + scanStream({match}) { + clears++; + const stream = new EventEmitter(); + queueMicrotask(() => { stream.emit('data', [...values.keys()].filter(key => key.startsWith(match.slice(0,-1)))); stream.emit('end'); }); + return stream; + } + pipeline() { const deleted = []; return {del(key) { deleted.push(key); }, async exec() { deleted.forEach(key => values.delete(key)); }}; } + disconnect() { this.closed++; this.status = 'end'; if (this.failDisconnect) throw new Error('fixture disconnect failure'); } + async quit() { this.quits++; if (this.failQuit) throw new Error('fixture quit failure'); this.disconnect(); } + } + class BullQueue { + constructor(name) { this.name = name; this.closed = 0; this.jobs = []; handles.push(this); } + on() { return this; } + async add(name, data, opts) { const job = {id:String(this.jobs.length + 1),name,data,opts}; this.jobs.push(job); return job; } + async addBulk(jobs) { return Promise.all(jobs.map(job => this.add(job.name,job.data,job.opts))); } + async close() { this.closed++; await this.onClose?.(); if (this.failClose) throw new Error('fixture close failure'); } + } + class Worker { constructor() { workerCount++; throw new Error('Observer started a worker'); } } + class QueueEvents { constructor() { eventCount++; throw new Error('Observer started queue events'); } } + mock.module('ioredis', () => ({default:Redis,Redis,Cluster:Redis})); + mock.module('bullmq', () => ({Queue:BullQueue,Worker,QueueEvents})); + const { QueueManager } = await import('./libs/core/queue/src/queue-manager.ts'); + const { processItems, processBatchJob } = await import('./libs/core/queue/src/batch-processor.ts'); + const logger = {info() {}, error() {}, warn(message) { warnings.push(message); }, debug() {}, trace() {}}; + const manager = () => new QueueManager({serviceName:'ingestion',redis:{host:'queue.fixture.test',port:16379},defaultQueueOptions:{workers:0},autoDiscoverHandlers:false}, undefined, logger); + const output = value => process.stdout.write('__queue_lifecycle__' + JSON.stringify(value) + '\n'); +`; + +async function probe(source: string): Promise> { + const child = Bun.spawn([process.execPath, '--no-env-file', '-e', transports + source], { + 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(`Queue lifecycle probe failed: ${stderr}`); + } + const line = stdout.split('\n').find(item => item.startsWith('__queue_lifecycle__')); + if (!line) { + throw new Error('Queue lifecycle probe returned no evidence'); + } + return JSON.parse(line.slice('__queue_lifecycle__'.length)); +} + +test('observer and producer shutdown preserve pending batch payloads until a consumer completes them', async () => { + const result = await probe(String.raw` + const producer = manager(), observer = manager(); + producer.getQueue('data', {workers:0}); + observer.getQueue('data', {workers:0}); + const observationSockets = sockets.length; + await processItems([{symbol:'AAPL.US'}, {symbol:'MSFT.US'}], 'data', { + totalDelayHours:0, useBatching:true, batchSize:2, ttl:123, handler:'data', operation:'save' + }, producer); + const batch = handles[0].jobs[0].data.payload; + const cacheKey = 'batch:data:' + batch.payloadKey; + // Two process-owned sockets can access the same payload; neither owns deletion. + const sharedRead = await observer.getCache('data').get(batch.payloadKey); + await observer.shutdown(); await observer.shutdown(); + const afterObserver = values.has(cacheKey); + await producer.send('{remote_jobs}', 'save', {symbol:'AAPL.US'}); + await producer.shutdown(); await producer.shutdown(); + const afterProducer = values.has(cacheKey); + const consumer = manager(); + consumer.getQueue('data', {workers:0}); + const completed = await processBatchJob(batch, 'data', consumer); + const afterCompletion = values.has(cacheKey); + const consumerJobs = handles.at(-1).jobs.map(job => job.data.payload); + await consumer.shutdown(); + output({observationSockets, sharedRead:sharedRead.items, afterObserver, afterProducer, + afterCompletion, consumerJobs, completed, clears, workerCount, eventCount, + ttls:writes.map(write=>write.ttl), closed:handles.map(handle=>handle.closed), + socketsClosed:sockets.map(socket=>socket.closed)}); + `); + expect(result.observationSockets).toBe(2); // Only each manager's rate-limiter connection. + expect(result.sharedRead).toEqual([{ symbol: 'AAPL.US' }, { symbol: 'MSFT.US' }]); + expect(result.afterObserver).toBe(true); + expect(result.afterProducer).toBe(true); + expect(result.afterCompletion).toBe(false); + expect(result.consumerJobs).toEqual([{ symbol: 'AAPL.US' }, { symbol: 'MSFT.US' }]); + expect(result.completed).toEqual({ batchIndex: 0, itemsProcessed: 2, jobsCreated: 2 }); + expect(result.clears).toBe(0); + expect(result.workerCount).toBe(0); + expect(result.eventCount).toBe(0); + expect(result.ttls).toEqual([123]); + expect(result.closed).toEqual([1, 1, 1, 1]); + expect(result.socketsClosed).toEqual([1, 1, 1, 1, 1, 1]); +}); + +test('shutdown drains existing workers before closing lazily acquired cache and producer connections', async () => { + const result = await probe(String.raw` + const running = manager(); + const queue = running.getQueue('data', {workers:0}); + let release; + const drain = new Promise(resolve => { release = resolve; }); + let entered, reentrant; + const started = new Promise(resolve => { entered = resolve; }); + handles[0].onClose = async () => { + reentrant = running.shutdown(); + // An active batch can first need these transports while its worker drains. + if (running.getQueue('data') !== queue) throw new Error('Existing queue changed'); + await running.getCache('data').set('pending', {items:[1]}); + await running.send('{remote_jobs}', 'save', 1); + entered(); + await drain; + }; + const first = running.shutdown(); + await started; + const concurrent = running.shutdown(); + const producerClosedDuringDrain = handles[1].closed; + const cacheClosedDuringDrain = sockets[1].closed; + let newQueueBlocked = false; + try { running.getQueue('new', {workers:0}); } catch { newQueueBlocked = true; } + release(); + await Promise.all([first, concurrent]); + const repeated = running.shutdown(); + await repeated; + const blocked = []; + for (const work of [() => running.getQueue('data'), () => running.getCache('data'), + () => running.send('{remote_jobs}', 'save', 2), () => running.startAllWorkers()]) { + try { await work(); blocked.push(false); } catch { blocked.push(true); } + } + output({samePromise:first===concurrent && first===repeated && first===reentrant, producerClosedDuringDrain, + cacheClosedDuringDrain, newQueueBlocked, blocked, payload:values.has('batch:data:pending'), + closed:handles.map(handle=>handle.closed), socketsClosed:sockets.map(socket=>socket.closed)}); + `); + expect(result.samePromise).toBe(true); + expect(result.producerClosedDuringDrain).toBe(0); + expect(result.cacheClosedDuringDrain).toBe(0); + expect(result.newQueueBlocked).toBe(true); + expect(result.blocked).toEqual([true, true, true, true]); + expect(result.payload).toBe(true); + expect(result.closed).toEqual([1, 1]); + expect(result.socketsClosed).toEqual([1, 1]); +}); + +test('one failing queue or cache cleanup cannot skip other owned transports or repeat close attempts', async () => { + const result = await probe(String.raw` + const running = manager(); + running.getQueue('data', {workers:0}); + await running.send('{remote_jobs}', 'save', 1); + await running.send('{remote_other}', 'save', 2); + await running.getCache('first').set('pending', 1); + await running.getCache('second').set('pending', 2); + handles[0].failClose = true; + handles[1].failClose = true; + sockets[0].failQuit = true; + sockets[1].failDisconnect = true; + await Promise.all([running.shutdown(), running.shutdown()]); + await running.shutdown(); + output({closed:handles.map(handle=>handle.closed), socketsClosed:sockets.map(socket=>socket.closed), + quits:sockets.map(socket=>socket.quits), warnings, clears, + payloads:[...values.keys()].sort(), queues:running.getQueueNames()}); + `); + expect(result.closed).toEqual([1, 1, 1]); + expect(result.socketsClosed).toEqual([1, 1, 1]); + expect(result.quits).toEqual([1, 0, 0]); + expect(result.warnings).toEqual([ + 'Error closing queue', + 'Error closing queue', + 'Error disconnecting batch cache', + 'Error closing ioredis connection', + ]); + expect(result.clears).toBe(0); + expect(result.payloads).toEqual(['batch:first:pending', 'batch:second:pending']); + expect(result.queues).toEqual([]); +});