fix(queue): wait for actual worker drain before disconnecting (CL22)
This commit is contained in:
parent
ec582bd5e8
commit
1aa35d2db3
7 changed files with 177 additions and 29 deletions
|
|
@ -33,3 +33,5 @@ Agents use root-reserved disjoint files in the integration worktree. Root alone
|
|||
- **CL28:** One application composition graph with narrow collaborators and caller-owned transactions; independent review no blockers. Focused API45 passed547 assertions; root combined composition/capability5 passed1091 assertions. Disposable PG research/validation/walk-forward/paper/durable gates69 passed602 assertions plus catalog/durable-validation17 passed186 assertions. Scoped lint/format passed.
|
||||
|
||||
- **CL33:** Canonical concrete/unavailable repositories expose supported writes only; legacy adapter reuses exact fencing helpers and unchanged method bodies. Root capability/composition5 passed1091 assertions. Disposable PG durable/canonical/retention/catalog tests passed in69+17-test gates; source and contract typechecks pass. Historical readers and supported runtime behavior preserved.
|
||||
|
||||
- **CL22:** Independent review reproduced premature worker drain at2s. Follow-up removes false-success2s/5s queue deadlines; actual Queue.close is idempotent and retains workers/transports until completion. Deferred-worker regression crosses both old deadlines; real Redis DB15 smoke preserves queued payloads through observer/producer shutdown and subsequent consumption. Root queue build and focused tests passed; service-level exit deadline remains authoritative.
|
||||
|
|
|
|||
|
|
@ -3762,7 +3762,7 @@
|
|||
"release_gates": [],
|
||||
"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."
|
||||
"validation": "Independent review reproduced premature worker drain at2s. Follow-up removes false-success2s/5s queue deadlines; actual Queue.close is idempotent and retains workers/transports until completion. Deferred-worker regression crosses both old deadlines; real Redis DB15 smoke preserves queued payloads through observer/producer shutdown and subsequent consumption. Root queue build and focused tests passed; service-level exit deadline remains authoritative."
|
||||
},
|
||||
{
|
||||
"id": "CL23",
|
||||
|
|
@ -3975,7 +3975,7 @@
|
|||
"complexity": "M",
|
||||
"assignment": null,
|
||||
"write_locks": ["CL33"],
|
||||
"completed_commit": null,
|
||||
"completed_commit": "ec582bd5e8d3cad13e03486e345a0f383e5a087e",
|
||||
"blocker": null,
|
||||
"release_gates": [],
|
||||
"completion_evidence": "architecture-cleanup-execution.md",
|
||||
|
|
@ -10408,6 +10408,6 @@
|
|||
"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": 13,
|
||||
"last_verification": "Canonical concrete/unavailable repositories expose supported writes only; legacy adapter reuses exact fencing helpers and unchanged method bodies. Root capability/composition5 passed1091 assertions. Disposable PG durable/canonical/retention/catalog tests passed in69+17-test gates; source and contract typechecks pass. Historical readers and supported runtime behavior preserved."
|
||||
"last_verification": "Independent review reproduced premature worker drain at2s. Follow-up removes false-success2s/5s queue deadlines; actual Queue.close is idempotent and retains workers/transports until completion. Deferred-worker regression crosses both old deadlines; real Redis DB15 smoke preserves queued payloads through observer/producer shutdown and subsequent consumption. Root queue build and focused tests passed; service-level exit deadline remains authoritative."
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,3 +22,7 @@ No new service/framework, financial simulator, real trading activation, external
|
|||
## 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.
|
||||
|
||||
## Accepted verification
|
||||
|
||||
Independent review reproduced premature worker drain at2s. Follow-up removes false-success2s/5s queue deadlines; actual Queue.close is idempotent and retains workers/transports until completion. Deferred-worker regression crosses both old deadlines; real Redis DB15 smoke preserves queued payloads through observer/producer shutdown and subsequent consumption. Root queue build and focused tests passed; service-level exit deadline remains authoritative.
|
||||
|
|
|
|||
|
|
@ -465,18 +465,10 @@ export class QueueManager {
|
|||
}
|
||||
|
||||
private async closeQueue(queue: Pick<Queue, 'close'>): Promise<void> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
queue.close(),
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error('Queue close timeout')), 5000);
|
||||
}),
|
||||
]);
|
||||
await queue.close();
|
||||
} catch (error) {
|
||||
this.logger.warn('Error closing queue', { error });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ export class Queue {
|
|||
private bullQueue: BullQueue;
|
||||
private workers: Worker[] = [];
|
||||
private queueEvents?: QueueEvents;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private queueName: string;
|
||||
private redisConfig: RedisConfig;
|
||||
private readonly logger: Logger;
|
||||
|
|
@ -269,27 +270,19 @@ export class Queue {
|
|||
/**
|
||||
* Close the queue (cleanup resources)
|
||||
*/
|
||||
/**
|
||||
* Close the queue (cleanup resources)
|
||||
*/
|
||||
async close(): Promise<void> {
|
||||
close(): Promise<void> {
|
||||
// Retain the actual drain promise. The application owns any deadline that
|
||||
// forces process exit; a queue must not report completion with active jobs.
|
||||
return (this.closePromise ??= Promise.resolve().then(() => this.performClose()));
|
||||
}
|
||||
|
||||
private async performClose(): Promise<void> {
|
||||
try {
|
||||
// Close workers first with timeout
|
||||
// Stop taking jobs and wait for every active worker before its transports.
|
||||
if (this.workers.length > 0) {
|
||||
const workerClosePromises = this.workers.map(async (worker, idx) => {
|
||||
try {
|
||||
const closePromise = worker.close();
|
||||
const timeoutPromise = new Promise<void>(resolve => {
|
||||
setTimeout(() => {
|
||||
this.logger.warn('Worker close timeout, forcing closure', {
|
||||
queueName: this.queueName,
|
||||
workerId: idx,
|
||||
});
|
||||
resolve();
|
||||
}, 2000); // 2 second timeout per worker
|
||||
});
|
||||
|
||||
await Promise.race([closePromise, timeoutPromise]);
|
||||
await worker.close();
|
||||
} catch (error) {
|
||||
this.logger.warn('Error closing worker', {
|
||||
queueName: this.queueName,
|
||||
|
|
|
|||
|
|
@ -183,3 +183,60 @@ test('one failing queue or cache cleanup cannot skip other owned transports or r
|
|||
expect(result.payloads).toEqual(['batch:first:pending', 'batch:second:pending']);
|
||||
expect(result.queues).toEqual([]);
|
||||
});
|
||||
|
||||
test('real Queue.close retains workers and transports beyond the former drain timeouts', async () => {
|
||||
const result = await probe(String.raw`
|
||||
const running = manager();
|
||||
const queue = running.getQueue('data', {workers:0});
|
||||
await running.getCache('data').set('pending', {items:[1]});
|
||||
await running.send('{remote_jobs}', 'save', 1);
|
||||
let release, entered;
|
||||
const active = new Promise(resolve => { release = resolve; });
|
||||
const started = new Promise(resolve => { entered = resolve; });
|
||||
let workerCloses=0, workerDone=false;
|
||||
// Exercise the real Queue.close worker branch; only the worker transport is fake.
|
||||
queue.workers.push({async close() {
|
||||
workerCloses++;
|
||||
entered();
|
||||
await active;
|
||||
workerDone=true;
|
||||
}});
|
||||
const firstClose=queue.close(), repeatedClose=queue.close();
|
||||
let stopped=false;
|
||||
const shutdown=running.shutdown().then(() => { stopped=true; });
|
||||
await started;
|
||||
// Cross both former deadlines: Queue's 2s and QueueManager's 5s.
|
||||
await new Promise(resolve => setTimeout(resolve, 5200));
|
||||
const during={stopped,workerDone,workerCloses,workerHandles:queue.workers.length,
|
||||
queuesClosed:handles.map(handle=>handle.closed),socketsClosed:sockets.map(socket=>socket.closed)};
|
||||
let payload, sendError;
|
||||
try {
|
||||
payload=await running.getCache('data').get('pending');
|
||||
await running.send('{remote_jobs}', 'save', 2);
|
||||
} catch (error) { sendError=error.message; }
|
||||
release();
|
||||
await Promise.all([firstClose,repeatedClose,shutdown]);
|
||||
const finalClose=queue.close();
|
||||
await finalClose;
|
||||
output({during,payload,sendError,sameClose:firstClose===repeatedClose && firstClose===finalClose,
|
||||
workerDone,workerCloses,workerHandles:queue.workers.length,warnings,
|
||||
queuesClosed:handles.map(handle=>handle.closed),socketsClosed:sockets.map(socket=>socket.closed)});
|
||||
`);
|
||||
expect(result.during).toEqual({
|
||||
stopped: false,
|
||||
workerDone: false,
|
||||
workerCloses: 1,
|
||||
workerHandles: 1,
|
||||
queuesClosed: [0, 0],
|
||||
socketsClosed: [0, 0],
|
||||
});
|
||||
expect(result.payload).toEqual({ items: [1] });
|
||||
expect(result.sendError).toBeUndefined();
|
||||
expect(result.sameClose).toBe(true);
|
||||
expect(result.workerDone).toBe(true);
|
||||
expect(result.workerCloses).toBe(1);
|
||||
expect(result.workerHandles).toBe(0);
|
||||
expect(result.warnings).toEqual([]);
|
||||
expect(result.queuesClosed).toEqual([1, 1]);
|
||||
expect(result.socketsClosed).toEqual([1, 1]);
|
||||
}, 10000);
|
||||
|
|
|
|||
100
test/postgres/queue-shutdown.test.ts
Normal file
100
test/postgres/queue-shutdown.test.ts
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { Queue as BullQueue } from 'bullmq';
|
||||
import { expect, test } from 'bun:test';
|
||||
import Redis from 'ioredis';
|
||||
import { processBatchJob, processItems } from '../../libs/core/queue/src/batch-processor';
|
||||
import { QueueManager } from '../../libs/core/queue/src/queue-manager';
|
||||
import type { BatchJobData } from '../../libs/core/queue/src/types';
|
||||
|
||||
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
const logger = { info() {}, debug() {}, trace() {}, warn() {}, error() {} };
|
||||
|
||||
test.skipIf(!redisUrl)(
|
||||
'real Redis retains queued batch payloads across observer and producer shutdown',
|
||||
async () => {
|
||||
const url = new URL(redisUrl!);
|
||||
if (url.pathname !== '/15') {
|
||||
throw new Error('Dedicated Redis fixture using database 15 required');
|
||||
}
|
||||
const connection = {
|
||||
host: url.hostname,
|
||||
port: Number(url.port || 6379),
|
||||
username: decodeURIComponent(url.username) || undefined,
|
||||
password: decodeURIComponent(url.password) || undefined,
|
||||
db: 15,
|
||||
maxRetriesPerRequest: 1,
|
||||
};
|
||||
const queueName = `cl22_${randomUUID().replaceAll('-', '')}`;
|
||||
const redis = new Redis({ ...connection, retryStrategy: () => null });
|
||||
const admin = new BullQueue(queueName, { connection });
|
||||
const managers: QueueManager[] = [];
|
||||
const manager = () => {
|
||||
// serviceName intentionally omitted: service routing forces database 0.
|
||||
const value = new QueueManager(
|
||||
{ redis: connection, defaultQueueOptions: { workers: 0 } },
|
||||
undefined,
|
||||
logger
|
||||
);
|
||||
managers.push(value);
|
||||
return value;
|
||||
};
|
||||
let payloadKey: string | undefined;
|
||||
try {
|
||||
await redis.ping();
|
||||
const producer = manager();
|
||||
const observer = manager();
|
||||
const items = [{ symbol: 'AAPL.US' }, { symbol: 'MSFT.US' }];
|
||||
await processItems(
|
||||
items,
|
||||
queueName,
|
||||
{
|
||||
totalDelayHours: 0,
|
||||
useBatching: true,
|
||||
batchSize: 2,
|
||||
ttl: 120,
|
||||
handler: queueName,
|
||||
operation: 'save',
|
||||
},
|
||||
producer
|
||||
);
|
||||
const jobs = await admin.getJobs(['waiting']);
|
||||
expect(jobs).toHaveLength(1);
|
||||
const batch = jobs[0]!.data.payload as BatchJobData;
|
||||
payloadKey = `batch:${queueName}:${batch.payloadKey}`;
|
||||
observer.getQueue(queueName);
|
||||
expect(await observer.getCache(queueName).get(batch.payloadKey)).toMatchObject({ items });
|
||||
await observer.shutdown();
|
||||
expect(await redis.exists(payloadKey)).toBe(1);
|
||||
await producer.shutdown();
|
||||
expect(await redis.exists(payloadKey)).toBe(1);
|
||||
expect(await redis.ttl(payloadKey)).toBeGreaterThan(0);
|
||||
expect(await admin.getJob(jobs[0]!.id!)).toBeDefined();
|
||||
expect(await admin.getWorkers()).toEqual([]);
|
||||
|
||||
const consumer = manager();
|
||||
expect(await processBatchJob(batch, queueName, consumer)).toEqual({
|
||||
batchIndex: 0,
|
||||
itemsProcessed: 2,
|
||||
jobsCreated: 2,
|
||||
});
|
||||
const itemJobs = (await admin.getJobs(['waiting']))
|
||||
.filter(job => job.name === 'process-item')
|
||||
.map(job => job.data.payload)
|
||||
.sort((a, b) => a.symbol.localeCompare(b.symbol));
|
||||
expect(itemJobs).toEqual(items);
|
||||
expect(await redis.exists(payloadKey)).toBe(0);
|
||||
} finally {
|
||||
await Promise.all(managers.map(value => value.shutdown()));
|
||||
// This unique queue and exact payload key belong only to this test.
|
||||
try {
|
||||
await admin.obliterate({ force: true });
|
||||
if (payloadKey) {
|
||||
await redis.del(payloadKey);
|
||||
}
|
||||
} finally {
|
||||
await admin.close();
|
||||
redis.disconnect();
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
Loading…
Add table
Add a link
Reference in a new issue