fix(swarm): track acknowledgements per recipient (#4234)

Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com>
This commit is contained in:
Rudy Mizrahi Celekli authored and GitHub committed 2026-10-17 15:00:39 +01:00
1 parent 0793f96248
commit 56da074181
2 files changed
+103 -6

No files matched your search

@@ -0,0 +1,80 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createMessageBus, type MessageBus } from '../src/message-bus.js';
let bus: MessageBus;
const message = {
type: 'direct' as const, from: 'sender', payload: {},
priority: 'normal' as const, requiresAck: true, ttlMs: 60_000,
};
const ack = (messageId: string, from: string) => ({
messageId, from, received: true, processedAt: new Date(),
});
beforeEach(async () => {
vi.useFakeTimers();
bus = createMessageBus({ ackTimeoutMs: 100, processingIntervalMs: 5000 });
await bus.initialize();
});
afterEach(async () => {
await bus.shutdown();
vi.useRealTimers();
});
describe('MessageBus recipient acknowledgement tracking', () => {
it('allows every broadcast recipient to acknowledge without orphaned timeouts', async () => {
const timeouts = vi.fn();
bus.on('message.ack_timeout', timeouts);
bus.subscribe('first', (received) => { void bus.acknowledge(ack(received.id, 'first')); });
bus.subscribe('second', (received) => { void bus.acknowledge(ack(received.id, 'second')); });
await bus.broadcast(message);
await vi.advanceTimersByTimeAsync(150);
expect(timeouts).not.toHaveBeenCalled();
expect(bus.getStats().ackRate).toBe(1);
});
it('does not accept an acknowledgement from another agent', async () => {
const timeouts = vi.fn();
bus.on('message.ack_timeout', timeouts);
bus.subscribe('target', (received) => { void bus.acknowledge(ack(received.id, 'other')); });
await bus.send({ ...message, to: 'target' });
await vi.advanceTimersByTimeAsync(150);
expect(timeouts).toHaveBeenCalledTimes(1);
});
it('retains the other broadcast recipient timeout after one acknowledges', async () => {
const timeouts = vi.fn();
bus.on('message.ack_timeout', timeouts);
bus.subscribe('first', (received) => { void bus.acknowledge(ack(received.id, 'first')); });
bus.subscribe('second', () => {});
await bus.broadcast(message);
await vi.advanceTimersByTimeAsync(150);
expect(timeouts).toHaveBeenCalledTimes(1);
expect(bus.getStats().ackRate).toBe(0.99);
});
it('clears every broadcast recipient timeout at shutdown', async () => {
const timeouts = vi.fn();
bus.on('message.ack_timeout', timeouts);
bus.subscribe('first', () => {});
bus.subscribe('second', () => {});
await bus.broadcast(message);
await vi.advanceTimersByTimeAsync(5);
await bus.shutdown();
await vi.advanceTimersByTimeAsync(150);
expect(timeouts).not.toHaveBeenCalled();
});
it('clears the failed delivery attempt timeout before a successful retry', async () => {
const timeouts = vi.fn();
bus.on('message.ack_timeout', timeouts);
let attempts = 0;
bus.subscribe('target', (received) => {
if (++attempts === 1) throw new Error('temporary subscriber failure');
void bus.acknowledge(ack(received.id, 'target'));
});
await bus.send({ ...message, to: 'target' });
await vi.advanceTimersByTimeAsync(150);
expect(attempts).toBe(2);
expect(timeouts).not.toHaveBeenCalled();
});
});
+23 -6
View File
@@ -425,13 +425,14 @@ export class MessageBus extends EventEmitter implements IMessageBus {
}
async acknowledge(ack: MessageAck): Promise<void> {
const pending = this.pendingAcks.get(ack.messageId);
const key = this.ackKey(ack.messageId, ack.from);
const pending = this.pendingAcks.get(key);
if (!pending) {
return;
}
clearTimeout(pending.timeout);
this.pendingAcks.delete(ack.messageId);
this.pendingAcks.delete(key);
if (!ack.received && ack.error) {
this.handleAckFailure(pending.message, ack.error);
@@ -443,6 +444,18 @@ export class MessageBus extends EventEmitter implements IMessageBus {
});
}
private ackKey(messageId: string, recipient: string): string {
// Broadcast recipients share a message ID, but acknowledge independently.
return JSON.stringify([messageId, recipient]);
}
private clearPendingAck(messageId: string, recipient: string): void {
const key = this.ackKey(messageId, recipient);
const pending = this.pendingAcks.get(key);
if (pending) clearTimeout(pending.timeout);
this.pendingAcks.delete(key);
}
private startProcessing(): void {
// Dispatch is event-driven via scheduleProcessing() (triggered from
// enqueue() and from retry re-queuing); this interval is only a
@@ -537,11 +550,13 @@ export class MessageBus extends EventEmitter implements IMessageBus {
try {
// Set up ack timeout if required
if (message.requiresAck) {
const key = this.ackKey(message.id, subscription.agentId);
this.clearPendingAck(message.id, subscription.agentId);
const timeout = setTimeout(() => {
this.handleAckTimeout(message);
this.handleAckTimeout(message, key);
}, this.config.ackTimeoutMs);
this.pendingAcks.set(message.id, { message, timeout });
this.pendingAcks.set(key, { message, timeout });
}
// Deliver asynchronously; shutdown owns and cancels pending handles.
@@ -564,8 +579,8 @@ export class MessageBus extends EventEmitter implements IMessageBus {
}
}
private handleAckTimeout(message: Message): void {
this.pendingAcks.delete(message.id);
private handleAckTimeout(message: Message, key: string): void {
this.pendingAcks.delete(key);
this.stats.ackRate = Math.max(0, this.stats.ackRate - 0.01);
this.emit('message.ack_timeout', { messageId: message.id });
}
@@ -576,6 +591,8 @@ export class MessageBus extends EventEmitter implements IMessageBus {
}
private handleDeliveryError(message: Message, entry: MessageQueueEntry, error: Error, subscriberAgentId: string): void {
// A failed callback never completed delivery; its retry owns a fresh timer.
this.clearPendingAck(message.id, subscriberAgentId);
entry.attempts++;
entry.lastAttemptAt = new Date();