Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(swarm): wait for consensus events instead of polling (#4498)

ordinary being9250d4e2bf89
diff --git a/v3/@claude-flow/swarm/__tests__/byzantine-gossip-await-event-driven.test.ts b/v3/@claude-flow/swarm/__tests__/byzantine-gossip-await-event-driven.test.ts
new file mode 100644
index 0000000000..3ef7559d6a
--- /dev/null
+++ b/v3/@claude-flow/swarm/__tests__/byzantine-gossip-await-event-driven.test.ts
@@ -0,0 +1,139 @@
+/**
+ * #4458 swarm scan: ByzantineConsensus.awaitConsensus() and
+ * GossipConsensus.awaitConsensus() polled this.proposals with setInterval
+ * every 10/50 ms even though both already emit 'consensus.achieved'.
+ *
+ * These tests resolve a pending proposal through the event, and exercise the
+ * timeout path, while asserting no polling interval is created. The timeout
+ * tests also guard against leaving a consensus.achieved listener behind.
+ */
+
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import {
+ createByzantineConsensus,
+ type ByzantineConsensus,
+} from '../src/consensus/byzantine.js';
+import {
+ createGossipConsensus,
+ type GossipConsensus,
+} from '../src/consensus/gossip.js';
+import type { ConsensusVote } from '../src/types.js';
+
+function vote(voterId: string, approve = true): ConsensusVote {
+ return {
+ voterId,
+ approve,
+ confidence: 1.0,
+ timestamp: new Date(),
+ };
+}
+
+describe('Byzantine/Gossip awaitConsensus() event-driven resolution (#4458)', () => {
+ let bft: ByzantineConsensus | undefined;
+ let gossip: GossipConsensus | undefined;
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ if (bft) {
+ await bft.shutdown();
+ bft = undefined;
+ }
+ if (gossip) {
+ await gossip.shutdown();
+ gossip = undefined;
+ }
+ });
+
+ it('Byzantine resolves a pending proposal from consensus.achieved, without polling', async () => {
+ bft = createByzantineConsensus('bft-primary', {
+ maxFaultyNodes: 1,
+ timeoutMs: 1000,
+ });
+ await bft.initialize();
+ bft.electPrimary();
+ bft.addNode('bft-1');
+ bft.addNode('bft-2');
+ bft.addNode('bft-3');
+
+ const proposal = await bft.propose({ action: 'commit' });
+ const setIntervalSpy = vi.spyOn(globalThis, 'setInterval');
+
+ const resultPromise = bft.awaitConsensus(proposal.id);
+ await bft.vote(proposal.id, vote('bft-1'));
+ await bft.vote(proposal.id, vote('bft-2'));
+ await bft.vote(proposal.id, vote('bft-3'));
+
+ const result = await resultPromise;
+ expect(result.proposalId).toBe(proposal.id);
+ expect(result.approved).toBe(true);
+ expect(setIntervalSpy).not.toHaveBeenCalled();
+ expect(bft.listenerCount('consensus.achieved')).toBe(0);
+ });
+
+ it('Gossip resolves a pending proposal from consensus.achieved, without polling', async () => {
+ gossip = createGossipConsensus('gossip-1', {
+ timeoutMs: 1000,
+ convergenceThreshold: 1.0,
+ gossipIntervalMs: 50,
+ });
+ await gossip.initialize();
+ gossip.addNode('gossip-2');
+ gossip.addNode('gossip-3');
+ gossip.addNode('gossip-4');
+
+ const proposal = await gossip.propose({ action: 'commit' });
+ const setIntervalSpy = vi.spyOn(globalThis, 'setInterval');
+
+ const resultPromise = gossip.awaitConsensus(proposal.id);
+ await gossip.vote(proposal.id, vote('gossip-2'));
+ await gossip.vote(proposal.id, vote('gossip-3'));
+ await gossip.vote(proposal.id, vote('gossip-4'));
+
+ const result = await resultPromise;
+ expect(result.proposalId).toBe(proposal.id);
+ expect(result.approved).toBe(true);
+ expect(setIntervalSpy).not.toHaveBeenCalled();
+ expect(gossip.listenerCount('consensus.achieved')).toBe(0);
+ });
+
+ it('Byzantine expires a pending proposal with one timer and no listener leak', async () => {
+ bft = createByzantineConsensus('bft-timeout', {
+ maxFaultyNodes: 1,
+ timeoutMs: 40,
+ });
+ await bft.initialize();
+ bft.electPrimary();
+ bft.addNode('bft-1');
+ bft.addNode('bft-2');
+ bft.addNode('bft-3');
+ const proposal = await bft.propose({ action: 'never-voted' });
+
+ const setIntervalSpy = vi.spyOn(globalThis, 'setInterval');
+ const result = await bft.awaitConsensus(proposal.id);
+
+ expect(result.proposalId).toBe(proposal.id);
+ expect(result.approved).toBe(false);
+ expect(setIntervalSpy).not.toHaveBeenCalled();
+ expect(bft.listenerCount('consensus.achieved')).toBe(0);
+ });
+
+ it('Gossip expires a pending proposal with one timer and no listener leak', async () => {
+ gossip = createGossipConsensus('gossip-timeout', {
+ timeoutMs: 40,
+ convergenceThreshold: 1.0,
+ gossipIntervalMs: 50,
+ });
+ await gossip.initialize();
+ gossip.addNode('gossip-2');
+ gossip.addNode('gossip-3');
+ const proposal = await gossip.propose({ action: 'never-voted' });
+
+ const setIntervalSpy = vi.spyOn(globalThis, 'setInterval');
+ const result = await gossip.awaitConsensus(proposal.id);
+
+ expect(result.proposalId).toBe(proposal.id);
+ expect(result.approved).toBe(false);
+ expect(setIntervalSpy).not.toHaveBeenCalled();
+ expect(gossip.listenerCount('consensus.achieved')).toBe(0);
+ });
+});
diff --git a/v3/@claude-flow/swarm/src/consensus/byzantine.ts b/v3/@claude-flow/swarm/src/consensus/byzantine.ts
index b4a347eb17..c681180f66 100644
--- a/v3/@claude-flow/swarm/src/consensus/byzantine.ts
+++ b/v3/@claude-flow/swarm/src/consensus/byzantine.ts
@@ -281,27 +281,39 @@ export class ByzantineConsensus extends EventEmitter {
async awaitConsensus(proposalId: string): Promise<ConsensusResult> {
const startTime = Date.now();
- return new Promise((resolve, reject) => {
- const checkInterval = setInterval(() => {
- const proposal = this.proposals.get(proposalId);
- if (!proposal) {
- clearInterval(checkInterval);
- reject(new Error(`Proposal ${proposalId} not found`));
- return;
- }
+ const proposal = this.proposals.get(proposalId);
+ if (!proposal) {
+ throw new Error(`Proposal ${proposalId} not found`);
+ }
- if (proposal.status !== 'pending') {
- clearInterval(checkInterval);
- resolve(this.createResult(proposal, Date.now() - startTime));
- return;
- }
+ if (proposal.status !== 'pending') {
+ return this.createResult(proposal, Date.now() - startTime);
+ }
- if (Date.now() - startTime > (this.config.timeoutMs ?? 30000)) {
- clearInterval(checkInterval);
+ // checkConsensus() already emits 'consensus.achieved' on every
+ // accept/reject transition. Wait for that event plus one expiry timer
+ // instead of polling this.proposals with setInterval every 10 ms.
+ return new Promise(resolve => {
+ const cleanup = (): void => {
+ clearTimeout(timer);
+ this.off('consensus.achieved', onAchieved);
+ };
+
+ const onAchieved = (event: { proposalId: string }): void => {
+ if (event.proposalId !== proposalId) return;
+ cleanup();
+ resolve(this.createResult(this.proposals.get(proposalId) ?? proposal, Date.now() - startTime));
+ };
+
+ const timer = setTimeout(() => {
+ cleanup();
+ if (proposal.status === 'pending') {
proposal.status = 'expired';
- resolve(this.createResult(proposal, Date.now() - startTime));
}
- }, 10);
+ resolve(this.createResult(proposal, Date.now() - startTime));
+ }, this.config.timeoutMs ?? 30000);
+
+ this.on('consensus.achieved', onAchieved);
});
}
diff --git a/v3/@claude-flow/swarm/src/consensus/gossip.ts b/v3/@claude-flow/swarm/src/consensus/gossip.ts
index 6a7e95df25..cf42d02253 100644
--- a/v3/@claude-flow/swarm/src/consensus/gossip.ts
+++ b/v3/@claude-flow/swarm/src/consensus/gossip.ts
@@ -276,40 +276,59 @@ export class GossipConsensus extends EventEmitter {
const startTime = Date.now();
const maxWait = this.config.timeoutMs ?? 30000;
- return new Promise((resolve, reject) => {
- const checkInterval = setInterval(() => {
- const proposal = this.proposals.get(proposalId);
- if (!proposal) {
- clearInterval(checkInterval);
- reject(new Error(`Proposal ${proposalId} not found`));
- return;
- }
+ const proposal = this.proposals.get(proposalId);
+ if (!proposal) {
+ throw new Error(`Proposal ${proposalId} not found`);
+ }
- if (proposal.status !== 'pending') {
- clearInterval(checkInterval);
- resolve(this.createResult(proposal, Date.now() - startTime));
- return;
- }
+ if (proposal.status !== 'pending') {
+ return this.createResult(proposal, Date.now() - startTime);
+ }
- // Check convergence
- this.checkConvergence(proposalId);
+ // checkConvergence() already emits 'consensus.achieved' when the vote
+ // ratio crosses the configured threshold. Wait for that event plus one
+ // expiry timer instead of polling this.proposals with setInterval.
+ return new Promise(resolve => {
+ const cleanup = (): void => {
+ clearTimeout(timer);
+ this.off('consensus.achieved', onAchieved);
+ };
- if (Date.now() - startTime > maxWait) {
- clearInterval(checkInterval);
- // Gossip is eventually consistent, so mark as accepted if threshold met
- const totalNodes = this.nodes.size + 1;
- const votes = proposal.votes.size;
- const threshold = this.config.convergenceThreshold ?? 0.9;
+ const onAchieved = (event: { proposalId: string }): void => {
+ if (event.proposalId !== proposalId) return;
+ cleanup();
+ resolve(this.createResult(this.proposals.get(proposalId) ?? proposal, Date.now() - startTime));
+ };
- if (votes / totalNodes >= threshold) {
- proposal.status = 'accepted';
- } else {
- proposal.status = 'expired';
- }
+ const timer = setTimeout(() => {
+ cleanup();
+ const current = this.proposals.get(proposalId) ?? proposal;
- resolve(this.createResult(proposal, Date.now() - startTime));
+ if (current.status !== 'pending') {
+ resolve(this.createResult(current, Date.now() - startTime));
+ return;
}
- }, 50);
+
+ // Preserve the old timeout fallback: run convergence once more, then
+ // accept when the participation ratio meets the threshold, otherwise
+ // expire.
+ void this.checkConvergence(proposalId).then(() => {
+ if (current.status === 'pending') {
+ const totalNodes = this.nodes.size + 1;
+ const votes = current.votes.size;
+ const threshold = this.config.convergenceThreshold ?? 0.9;
+ current.status = votes / totalNodes >= threshold ? 'accepted' : 'expired';
+ }
+ resolve(this.createResult(current, Date.now() - startTime));
+ }).catch(() => {
+ if (current.status === 'pending') {
+ current.status = 'expired';
+ }
+ resolve(this.createResult(current, Date.now() - startTime));
+ });
+ }, maxWait);
+
+ this.on('consensus.achieved', onAchieved);
});
}