Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /integration /test_multi_agent.py
| """ | |
| test_multi_agent.py - Multi-Agent Integration Tests | |
| This module tests interactions between multiple agents including: | |
| - Agent-to-agent communication | |
| - Task delegation and coordination | |
| - Shared resource access | |
| - Distributed task processing | |
| - Consensus mechanisms | |
| """ | |
| import asyncio | |
| import time | |
| from dataclasses import dataclass, field | |
| from typing import Any, Dict, List, Optional | |
| import pytest | |
| import pytest_asyncio | |
| # Mark all tests in this module | |
| pytestmark = [ | |
| pytest.mark.integration, | |
| pytest.mark.agents, | |
| pytest.mark.concurrency, | |
| ] | |
| # ============================================================================ | |
| # Multi-Agent Communication Tests | |
| # ============================================================================ | |
| class TestMultiAgentCommunication: | |
| """Tests for agent-to-agent communication.""" | |
| async def test_agent_broadcast_message(self, ten_agents): | |
| """Test broadcasting a message to all agents.""" | |
| message = {"type": "broadcast", "content": "test_message"} | |
| # Simulate broadcast | |
| received_count = 0 | |
| for agent in ten_agents: | |
| # Each agent receives the message | |
| result = await agent.execute_task({"action": "receive_message", "message": message}) | |
| if result["status"] == "completed": | |
| received_count += 1 | |
| assert received_count == 10, f"Only {received_count}/10 agents received message" | |
| async def test_agent_direct_message(self, ten_agents): | |
| """Test direct message between two agents.""" | |
| sender = ten_agents[0] | |
| receiver = ten_agents[1] | |
| message = { | |
| "from": sender.agent_id, | |
| "to": receiver.agent_id, | |
| "content": "direct_message", | |
| } | |
| result = await receiver.execute_task({"action": "receive_direct_message", "message": message}) | |
| assert result["status"] == "completed" | |
| async def test_agent_mesh_communication(self, fifty_agents): | |
| """Test mesh communication pattern (each agent talks to all others).""" | |
| message_count = 0 | |
| # Each agent sends a message to every other agent | |
| for sender in fifty_agents: | |
| for receiver in fifty_agents: | |
| if sender.agent_id != receiver.agent_id: | |
| message = { | |
| "from": sender.agent_id, | |
| "to": receiver.agent_id, | |
| "content": f"message_from_{sender.agent_id}", | |
| } | |
| result = await receiver.execute_task( | |
| { | |
| "action": "receive_direct_message", | |
| "message": message, | |
| } | |
| ) | |
| if result["status"] == "completed": | |
| message_count += 1 | |
| # 50 agents * 49 other agents = 2450 messages | |
| expected_messages = 50 * 49 | |
| assert message_count == expected_messages, f"Only {message_count}/{expected_messages} messages delivered" | |
| async def test_agent_pub_sub_pattern(self, hundred_agents): | |
| """Test publish-subscribe pattern with 100 agents.""" | |
| # Subscribe first 50 agents to "scan_results" topic | |
| subscribers = hundred_agents[:50] | |
| publishers = hundred_agents[50:] | |
| # Subscribe | |
| for agent in subscribers: | |
| await agent.execute_task({"action": "subscribe", "topic": "scan_results"}) | |
| # Publish messages | |
| publish_count = 0 | |
| for publisher in publishers: | |
| result = await publisher.execute_task( | |
| { | |
| "action": "publish", | |
| "topic": "scan_results", | |
| "data": {"scan_id": f"scan_{publisher.agent_id}"}, | |
| } | |
| ) | |
| if result["status"] == "completed": | |
| publish_count += 1 | |
| assert publish_count == 50, f"Only {publish_count}/50 publishers succeeded" | |
| # ============================================================================ | |
| # Task Delegation Tests | |
| # ============================================================================ | |
| class TestTaskDelegation: | |
| """Tests for task delegation between agents.""" | |
| async def test_simple_task_delegation(self, ten_agents): | |
| """Test simple task delegation from one agent to another.""" | |
| coordinator = ten_agents[0] | |
| worker = ten_agents[1] | |
| task = {"type": "subtask", "data": "delegated_work"} | |
| # Coordinator delegates to worker | |
| delegation_result = await coordinator.execute_task({"action": "delegate", "to_agent": worker.agent_id, "task": task}) | |
| # Worker executes | |
| worker_result = await worker.execute_task(task) | |
| assert delegation_result["status"] == "completed" | |
| assert worker_result["status"] == "completed" | |
| async def test_distributed_task_processing(self, fifty_agents, generate_tasks): | |
| """Test distributed task processing across 50 agents.""" | |
| coordinator = fifty_agents[0] | |
| workers = fifty_agents[1:] | |
| tasks = generate_tasks(49) # One task per worker | |
| # Coordinator distributes tasks | |
| distribution_results = await asyncio.gather( | |
| *[ | |
| coordinator.execute_task( | |
| { | |
| "action": "delegate", | |
| "to_agent": worker.agent_id, | |
| "task": task, | |
| } | |
| ) | |
| for worker, task in zip(workers, tasks) | |
| ] | |
| ) | |
| # Workers execute | |
| worker_results = await asyncio.gather(*[worker.execute_task(task) for worker, task in zip(workers, tasks)]) | |
| success_count = sum(1 for r in worker_results if r["status"] == "completed") | |
| assert success_count == 49, f"Only {success_count}/49 tasks completed" | |
| async def test_hierarchical_task_delegation(self, hundred_agents, generate_tasks): | |
| """Test hierarchical task delegation (coordinator -> managers -> workers).""" | |
| # Structure: 1 coordinator, 9 managers, 90 workers | |
| coordinator = hundred_agents[0] | |
| managers = hundred_agents[1:10] | |
| workers = hundred_agents[10:] | |
| tasks = generate_tasks(90) # 10 tasks per manager | |
| # Distribute tasks to managers | |
| manager_tasks = [] | |
| for i, manager in enumerate(managers): | |
| manager_task_list = tasks[i * 10 : (i + 1) * 10] | |
| manager_tasks.append( | |
| { | |
| "action": "distribute_to_workers", | |
| "tasks": manager_task_list, | |
| "workers": [w.agent_id for w in workers[i * 10 : (i + 1) * 10]], | |
| } | |
| ) | |
| # Coordinator delegates to managers | |
| await asyncio.gather( | |
| *[ | |
| coordinator.execute_task( | |
| { | |
| "action": "delegate", | |
| "to_agent": manager.agent_id, | |
| "task": mt, | |
| } | |
| ) | |
| for manager, mt in zip(managers, manager_tasks) | |
| ] | |
| ) | |
| # Managers delegate to workers | |
| all_worker_results = [] | |
| for i, manager in enumerate(managers): | |
| worker_results = await asyncio.gather( | |
| *[workers[i * 10 + j].execute_task(task) for j, task in enumerate(tasks[i * 10 : (i + 1) * 10])] | |
| ) | |
| all_worker_results.extend(worker_results) | |
| success_count = sum(1 for r in all_worker_results if r["status"] == "completed") | |
| assert success_count == 90, f"Only {success_count}/90 tasks completed" | |
| # ============================================================================ | |
| # Shared Resource Tests | |
| # ============================================================================ | |
| class TestSharedResourceAccess: | |
| """Tests for shared resource access between agents.""" | |
| async def test_shared_cache_read_write(self, ten_agents, cache): | |
| """Test agents reading and writing to shared cache.""" | |
| # Agent 0 writes to cache | |
| await cache.set("shared_key", "shared_value") | |
| # All agents read from cache | |
| read_results = await asyncio.gather( | |
| *[ | |
| agent.execute_task( | |
| { | |
| "action": "cache_read", | |
| "key": "shared_key", | |
| "cache": cache, | |
| } | |
| ) | |
| for agent in ten_agents | |
| ] | |
| ) | |
| # All should see the same value | |
| values = [r.get("value") for r in read_results] | |
| assert all(v == "shared_value" for v in values), "Cache consistency issue" | |
| async def test_concurrent_cache_writes(self, fifty_agents, cache): | |
| """Test concurrent cache writes from multiple agents.""" | |
| # Each agent writes a unique key | |
| write_results = await asyncio.gather( | |
| *[ | |
| agent.execute_task( | |
| { | |
| "action": "cache_write", | |
| "key": f"agent_{agent.agent_id}_key", | |
| "value": f"agent_{agent.agent_id}_value", | |
| "cache": cache, | |
| } | |
| ) | |
| for agent in fifty_agents | |
| ] | |
| ) | |
| success_count = sum(1 for r in write_results if r["status"] == "completed") | |
| assert success_count == 50, f"Only {success_count}/50 writes succeeded" | |
| # Verify all values are readable | |
| for agent in fifty_agents: | |
| value = await cache.get(f"agent_{agent.agent_id}_key") | |
| assert value == f"agent_{agent.agent_id}_value" | |
| async def test_shared_database_access(self, hundred_agents, database): | |
| """Test shared database access from 100 agents.""" | |
| # Each agent inserts a record | |
| insert_results = await asyncio.gather( | |
| *[ | |
| agent.execute_task( | |
| { | |
| "action": "db_insert", | |
| "table": "agent_records", | |
| "data": { | |
| "agent_id": agent.agent_id, | |
| "status": "active", | |
| }, | |
| "database": database, | |
| } | |
| ) | |
| for agent in hundred_agents | |
| ] | |
| ) | |
| success_count = sum(1 for r in insert_results if r["status"] == "completed") | |
| assert success_count == 100, f"Only {success_count}/100 inserts succeeded" | |
| # Query all records | |
| records = await database.query("agent_records") | |
| assert len(records) == 100, f"Only {len(records)}/100 records in database" | |
| # ============================================================================ | |
| # Consensus Tests | |
| # ============================================================================ | |
| class TestConsensusMechanisms: | |
| """Tests for distributed consensus between agents.""" | |
| async def test_simple_majority_consensus(self, ten_agents): | |
| """Test simple majority consensus voting.""" | |
| proposal = {"action": "execute_scan", "target": "example.com"} | |
| # Each agent votes | |
| votes = [] | |
| for agent in ten_agents: | |
| # Simulate voting (7 yes, 3 no) | |
| vote = "yes" if len(votes) < 7 else "no" | |
| result = await agent.execute_task({"action": "vote", "proposal": proposal, "vote": vote}) | |
| votes.append(result) | |
| # Count votes | |
| yes_votes = sum(1 for v in votes if v.get("vote") == "yes") | |
| # Majority achieved | |
| assert yes_votes >= 6, f"Majority not achieved: {yes_votes}/10" | |
| async def test_distributed_consensus_50_agents(self, fifty_agents): | |
| """Test distributed consensus with 50 agents.""" | |
| proposal = {"action": "coordinated_scan", "scope": "full_network"} | |
| # Simulate Byzantine fault-tolerant consensus | |
| # 33 agents vote yes, 12 vote no, 5 are faulty | |
| votes = [] | |
| for i, agent in enumerate(fifty_agents): | |
| if i < 33: | |
| vote = "yes" | |
| elif i < 45: | |
| vote = "no" | |
| else: | |
| vote = "faulty" # Simulates Byzantine fault | |
| result = await agent.execute_task({"action": "vote", "proposal": proposal, "vote": vote}) | |
| votes.append(result) | |
| yes_votes = sum(1 for v in votes if v.get("vote") == "yes") | |
| no_votes = sum(1 for v in votes if v.get("vote") == "no") | |
| # With 50 agents, need 34 for 2/3 majority | |
| assert yes_votes >= 34 or no_votes >= 34, "Consensus not reached" | |
| async def test_leader_election(self, hundred_agents): | |
| """Test leader election among 100 agents.""" | |
| # Each agent proposes a leader | |
| proposals = await asyncio.gather( | |
| *[agent.execute_task({"action": "propose_leader", "candidate": agent.agent_id}) for agent in hundred_agents] | |
| ) | |
| # Count proposals | |
| proposal_counts = {} | |
| for p in proposals: | |
| candidate = p.get("candidate") | |
| proposal_counts[candidate] = proposal_counts.get(candidate, 0) + 1 | |
| # Find leader with most votes | |
| leader = max(proposal_counts.keys(), key=lambda k: proposal_counts[k]) | |
| leader_votes = proposal_counts[leader] | |
| # Leader should have majority | |
| assert leader_votes > 50, f"Leader only has {leader_votes}/100 votes" | |
| # ============================================================================ | |
| # Coordination Tests | |
| # ============================================================================ | |
| class TestAgentCoordination: | |
| """Tests for agent coordination patterns.""" | |
| async def test_barrier_synchronization(self, ten_agents): | |
| """Test barrier synchronization between agents.""" | |
| barrier_results = [] | |
| async def reach_barrier(agent, barrier_id): | |
| result = await agent.execute_task({"action": "reach_barrier", "barrier_id": barrier_id}) | |
| return result | |
| # All agents reach barrier | |
| results = await asyncio.gather(*[reach_barrier(agent, "sync_point_1") for agent in ten_agents]) | |
| # All should have reached | |
| reached_count = sum(1 for r in results if r["status"] == "completed") | |
| assert reached_count == 10, f"Only {reached_count}/10 agents reached barrier" | |
| async def test_work_stealing_pattern(self, fifty_agents, generate_tasks): | |
| """Test work stealing pattern for load balancing.""" | |
| # Create uneven workload | |
| tasks = generate_tasks(100) | |
| # First 10 agents get all tasks initially | |
| busy_agents = fifty_agents[:10] | |
| idle_agents = fifty_agents[10:] | |
| task_queue = list(tasks) | |
| # Simulate work stealing | |
| stolen_work = [] | |
| for idle_agent in idle_agents[:20]: # 20 idle agents steal work | |
| if task_queue: | |
| stolen_task = task_queue.pop() | |
| result = await idle_agent.execute_task(stolen_task) | |
| stolen_work.append(result) | |
| # Verify work was stolen | |
| assert len(stolen_work) > 0, "No work was stolen" | |
| assert all(r["status"] == "completed" for r in stolen_work) | |
| async def test_map_reduce_pattern(self, hundred_agents): | |
| """Test map-reduce pattern with 100 agents.""" | |
| # Data to process | |
| data_chunks = [{"id": i, "data": f"chunk_{i}"} for i in range(100)] | |
| # Map phase: 90 workers process data | |
| workers = hundred_agents[:90] | |
| map_results = await asyncio.gather( | |
| *[worker.execute_task({"action": "map", "data": chunk}) for worker, chunk in zip(workers, data_chunks)] | |
| ) | |
| # Shuffle phase: intermediate results | |
| intermediate = {} | |
| for result in map_results: | |
| key = result.get("key", "default") | |
| if key not in intermediate: | |
| intermediate[key] = [] | |
| intermediate[key].append(result.get("value")) | |
| # Reduce phase: 10 reducers aggregate results | |
| reducers = hundred_agents[90:] | |
| reduce_results = await asyncio.gather( | |
| *[ | |
| reducer.execute_task({"action": "reduce", "key": key, "values": values}) | |
| for reducer, (key, values) in zip(reducers, list(intermediate.items())[:10]) | |
| ] | |
| ) | |
| # Verify results | |
| assert len(map_results) == 90 | |
| assert len(reduce_results) == min(10, len(intermediate)) | |
| # ============================================================================ | |
| # Integration with Orchestrator | |
| # ============================================================================ | |
| class TestOrchestratorIntegration: | |
| """Tests for orchestrator integration with multiple agents.""" | |
| async def test_orchestrator_task_assignment(self, orchestrator, mock_agent_factory, generate_tasks): | |
| """Test orchestrator assigning tasks to agents.""" | |
| # Spawn agents | |
| agents = await orchestrator.spawn_agents(mock_agent_factory, 10) | |
| # Create tasks | |
| tasks = generate_tasks(10) | |
| # Orchestrator assigns tasks | |
| assignment_results = [] | |
| for agent, task in zip(agents, tasks): | |
| result = await orchestrator.distribute_task(task) | |
| assignment_results.extend(result) | |
| # Verify assignments | |
| assert len(assignment_results) == 10 | |
| assert all(r["status"] == "completed" for r in assignment_results) | |
| async def test_orchestrator_load_balancing(self, orchestrator, mock_agent_factory, generate_tasks): | |
| """Test orchestrator load balancing across 50 agents.""" | |
| # Spawn 50 agents | |
| agents = await orchestrator.spawn_agents(mock_agent_factory, 50) | |
| # Create 100 tasks | |
| tasks = generate_tasks(100) | |
| # Distribute tasks | |
| results = [] | |
| for task in tasks: | |
| result = await orchestrator.distribute_task(task) | |
| results.extend(result) | |
| # Verify load distribution | |
| agent_task_counts = {} | |
| for r in results: | |
| agent_id = r.get("agent_id") | |
| agent_task_counts[agent_id] = agent_task_counts.get(agent_id, 0) + 1 | |
| # Check load is somewhat balanced (each agent should have 1-3 tasks) | |
| for count in agent_task_counts.values(): | |
| assert 1 <= count <= 3, f"Uneven load distribution: {count} tasks on one agent" | |
| async def test_orchestrator_full_workflow(self, orchestrator, mock_agent_factory, generate_tasks): | |
| """Test complete orchestrator workflow with 100 agents.""" | |
| # 1. Spawn 100 agents | |
| agents = await orchestrator.spawn_agents(mock_agent_factory, 100) | |
| assert len(agents) == 100 | |
| # 2. Collect initial metrics | |
| initial_metrics = await orchestrator.get_all_metrics() | |
| assert initial_metrics["total_agents"] == 100 | |
| # 3. Distribute 200 tasks | |
| tasks = generate_tasks(200) | |
| task_results = [] | |
| for task in tasks: | |
| results = await orchestrator.distribute_task(task) | |
| task_results.extend(results) | |
| # 4. Verify task completion | |
| success_count = sum(1 for r in task_results if r["status"] == "completed") | |
| assert success_count == 200, f"Only {success_count}/200 tasks completed" | |
| # 5. Collect final metrics | |
| final_metrics = await orchestrator.get_all_metrics() | |
| assert final_metrics["total_agents"] == 100 | |
| # 6. Graceful shutdown | |
| await orchestrator.terminate_all() | |
| assert len(orchestrator.agents) == 0 | |
| # ============================================================================ | |
| # Error Handling Tests | |
| # ============================================================================ | |
| class TestMultiAgentErrorHandling: | |
| """Tests for error handling in multi-agent scenarios.""" | |
| async def test_agent_failure_recovery(self, ten_agents): | |
| """Test recovery when an agent fails.""" | |
| # Simulate agent failure | |
| failed_agent = ten_agents[0] | |
| failed_agent.status = "failed" | |
| # Redistribute failed agent's work | |
| remaining_agents = ten_agents[1:] | |
| task = { | |
| "type": "recovered_task", | |
| "original_agent": failed_agent.agent_id, | |
| } | |
| recovery_results = await asyncio.gather(*[agent.execute_task(task) for agent in remaining_agents[:3]]) | |
| # Work should be recovered | |
| assert any(r["status"] == "completed" for r in recovery_results) | |
| async def test_partial_failure_handling(self, fifty_agents): | |
| """Test handling partial failures in agent pool.""" | |
| # Simulate 10% failure rate | |
| failed_indices = list(range(0, 50, 10)) # 5 agents fail | |
| for idx in failed_indices: | |
| fifty_agents[idx].status = "failed" | |
| # Try to execute tasks on all agents | |
| tasks = [{"type": "test", "id": i} for i in range(50)] | |
| results = await asyncio.gather( | |
| *[ | |
| (agent.execute_task(task) if agent.status != "failed" else {"status": "agent_failed"}) | |
| for agent, task in zip(fifty_agents, tasks) | |
| ], | |
| return_exceptions=True, | |
| ) | |
| # Count successes and failures | |
| successes = sum(1 for r in results if isinstance(r, dict) and r.get("status") == "completed") | |
| failures = sum(1 for r in results if isinstance(r, dict) and r.get("status") in ["failed", "agent_failed"]) | |
| # Should complete on non-failed agents | |
| assert successes >= 45, f"Only {successes} successes with {failures} failures" | |
| async def test_cascade_failure_prevention(self, hundred_agents): | |
| """Test prevention of cascade failures.""" | |
| # Simulate initial failure | |
| hundred_agents[0].status = "failed" | |
| # Circuit breaker should prevent cascade | |
| circuit_open = False | |
| affected_agents = [] | |
| for agent in hundred_agents[1:20]: | |
| if circuit_open: | |
| affected_agents.append(agent.agent_id) | |
| continue | |
| result = await agent.execute_task({"type": "check_circuit"}) | |
| if result.get("circuit_status") == "open": | |
| circuit_open = True | |
| # Circuit should open to prevent cascade | |
| # (In a real implementation, this would prevent further failures) | |
| assert len(affected_agents) < 19, "Circuit breaker didn't prevent cascade" | |
| # ============================================================================ | |
| # Performance Integration Tests | |
| # ============================================================================ | |
| class TestMultiAgentPerformance: | |
| """Performance tests for multi-agent interactions.""" | |
| async def test_100_agent_communication_latency(self, hundred_agents): | |
| """Test communication latency with 100 agents.""" | |
| message = {"type": "ping", "timestamp": time.time()} | |
| start = time.time() | |
| # Send message to all agents | |
| results = await asyncio.gather( | |
| *[agent.execute_task({"action": "receive_message", "message": message}) for agent in hundred_agents] | |
| ) | |
| elapsed = time.time() - start | |
| avg_latency = elapsed / 100 | |
| print("\n100-Agent Communication:") | |
| print(f" Total time: {elapsed * 1000:.2f}ms") | |
| print(f" Avg latency: {avg_latency * 1000:.2f}ms per agent") | |
| assert avg_latency < 0.01, f"Average latency too high: {avg_latency * 1000:.2f}ms" | |
| async def test_task_throughput_scaling(self, mock_agent_factory): | |
| """Test how task throughput scales with agent count.""" | |
| agent_counts = [10, 50, 100] | |
| throughputs = [] | |
| for count in agent_counts: | |
| agents = [mock_agent_factory() for _ in range(count)] | |
| await asyncio.gather(*[a.start() for a in agents]) | |
| tasks = [{"type": "benchmark", "id": i} for i in range(count)] | |
| start = time.time() | |
| await asyncio.gather(*[agent.execute_task(task) for agent, task in zip(agents, tasks)]) | |
| elapsed = time.time() - start | |
| throughput = count / elapsed | |
| throughputs.append((count, throughput)) | |
| await asyncio.gather(*[a.stop() for a in agents]) | |
| print("\nThroughput Scaling:") | |
| for count, throughput in throughputs: | |
| print(f" {count} agents: {throughput:.2f} tasks/s") | |
| # Throughput should increase with agent count | |
| assert throughputs[-1][1] > throughputs[0][1], "Throughput didn't scale" | |
Xet Storage Details
- Size:
- 26 kB
- Xet hash:
- 2d9843b3f119c82d2e595e6ab96b30f3ea40fa42659d556b0cd4645511cfc973
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.