Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /unit /test_agent_concurrency.py
| import asyncio | |
| import time | |
| from typing import List | |
| import pytest | |
| import pytest_asyncio | |
| # Mark all tests in this module | |
| pytestmark = [ | |
| pytest.mark.unit, | |
| pytest.mark.agents, | |
| pytest.mark.concurrency, | |
| ] | |
| # ============================================================================ | |
| # Single Agent Tests | |
| # ============================================================================ | |
| class TestSingleAgent: | |
| # Tests for single agent behavior. | |
| async def test_agent_start_stop(self, single_agent): | |
| # Test basic agent start and stop lifecycle. | |
| assert single_agent.status == "running" | |
| await single_agent.stop() | |
| assert single_agent.status == "stopped" | |
| async def test_agent_execute_task(self, single_agent, sample_task): | |
| # Test agent can execute a single task. | |
| result = await single_agent.execute_task(sample_task) | |
| assert result["status"] == "completed" | |
| assert result["agent_id"] == single_agent.agent_id | |
| assert single_agent.tasks_completed == 1 | |
| async def test_agent_metrics(self, single_agent): | |
| # Test agent metrics collection. | |
| metrics = await single_agent.get_metrics() | |
| assert "agent_id" in metrics | |
| assert "memory_usage" in metrics | |
| assert "cpu_usage" in metrics | |
| assert "uptime" in metrics | |
| assert metrics["agent_id"] == single_agent.agent_id | |
| async def test_agent_multiple_tasks_sequential(self, single_agent, generate_tasks): | |
| # Test agent executing multiple tasks sequentially. | |
| tasks = generate_tasks(10) | |
| for task in tasks: | |
| result = await single_agent.execute_task(task) | |
| assert result["status"] == "completed" | |
| assert single_agent.tasks_completed == 10 | |
| # ============================================================================ | |
| # 10 Agent Concurrency Tests | |
| # ============================================================================ | |
| class TestTenAgents: | |
| # Tests for 10 concurrent agents. | |
| async def test_ten_agents_start_simultaneously(self, mock_agent_factory): | |
| # Test starting 10 agents simultaneously. | |
| agents = [mock_agent_factory() for _ in range(10)] | |
| start_time = time.perf_counter() | |
| await asyncio.gather(*[agent.start() for agent in agents]) | |
| elapsed = time.perf_counter() - start_time | |
| # All agents should be running | |
| assert all(agent.status == "running" for agent in agents) | |
| # Should complete within reasonable time | |
| assert elapsed < 5.0, f"Agent startup took {elapsed:.2f}s" | |
| # Cleanup | |
| await asyncio.gather(*[agent.stop() for agent in agents]) | |
| async def test_ten_agents_execute_tasks_concurrently(self, ten_agents, generate_tasks): | |
| # Test 10 agents executing tasks concurrently. | |
| tasks = generate_tasks(10) | |
| # Assign one task per agent | |
| start_time = time.perf_counter() | |
| results = await asyncio.gather(*[agent.execute_task(task) for agent, task in zip(ten_agents, tasks)]) | |
| elapsed = time.perf_counter() - start_time | |
| # All tasks should complete | |
| assert len(results) == 10 | |
| assert all(r["status"] == "completed" for r in results) | |
| # Should complete quickly with parallel execution | |
| assert elapsed < 3.0, f"Concurrent tasks took {elapsed:.2f}s" | |
| async def test_ten_agents_metrics_collection(self, ten_agents): | |
| # Test collecting metrics from 10 agents concurrently. | |
| start_time = time.perf_counter() | |
| metrics = await asyncio.gather(*[agent.get_metrics() for agent in ten_agents]) | |
| elapsed = time.perf_counter() - start_time | |
| assert len(metrics) == 10 | |
| assert all("agent_id" in m for m in metrics) | |
| # Metrics collection should be fast | |
| assert elapsed < 1.0, f"Metrics collection took {elapsed:.2f}s" | |
| async def test_ten_agents_stop_simultaneously(self, ten_agents): | |
| # Test stopping 10 agents simultaneously. | |
| start_time = time.perf_counter() | |
| await asyncio.gather(*[agent.stop() for agent in ten_agents]) | |
| elapsed = time.perf_counter() - start_time | |
| assert all(agent.status == "stopped" for agent in ten_agents) | |
| assert elapsed < 3.0, f"Agent shutdown took {elapsed:.2f}s" | |
| # ============================================================================ | |
| # 50 Agent Concurrency Tests | |
| # ============================================================================ | |
| class TestFiftyAgents: | |
| # Tests for 50 concurrent agents. | |
| async def test_fifty_agents_spawn_rate(self, mock_agent_factory): | |
| # Test agent spawning rate for 50 agents. | |
| agents = [] | |
| spawn_rate = 10 # agents per second | |
| batch_size = 10 | |
| start_time = time.perf_counter() | |
| for i in range(0, 50, batch_size): | |
| batch = [mock_agent_factory() for _ in range(batch_size)] | |
| await asyncio.gather(*[agent.start() for agent in batch]) | |
| agents.extend(batch) | |
| # Rate limiting delay | |
| await asyncio.sleep(1.0 / spawn_rate * batch_size) | |
| elapsed = time.perf_counter() - start_time | |
| assert len(agents) == 50 | |
| assert all(agent.status == "running" for agent in agents) | |
| # Should spawn within reasonable time with rate limiting | |
| assert elapsed < 15.0, f"50 agent spawn took {elapsed:.2f}s" | |
| # Cleanup | |
| await asyncio.gather(*[agent.stop() for agent in agents]) | |
| async def test_fifty_agents_task_distribution(self, fifty_agents, generate_tasks): | |
| # Test task distribution across 50 agents. | |
| tasks = generate_tasks(100) # 2 tasks per agent on average | |
| # Distribute tasks round-robin | |
| start_time = time.perf_counter() | |
| results = [] | |
| for i, task in enumerate(tasks): | |
| agent = fifty_agents[i % len(fifty_agents)] | |
| result = await agent.execute_task(task) | |
| results.append(result) | |
| elapsed = time.perf_counter() - start_time | |
| assert len(results) == 100 | |
| assert all(r["status"] == "completed" for r in results) | |
| # Verify task distribution | |
| tasks_per_agent = [agent.tasks_completed for agent in fifty_agents] | |
| assert sum(tasks_per_agent) == 100 | |
| # Each agent should have 1 or 2 tasks | |
| assert all(1 <= t <= 2 for t in tasks_per_agent) | |
| async def test_fifty_agents_memory_usage(self, fifty_agents): | |
| # Test memory usage with 50 agents. | |
| metrics = await asyncio.gather(*[agent.get_metrics() for agent in fifty_agents]) | |
| total_memory = sum(m.get("memory_usage", 0) for m in metrics) | |
| avg_memory = total_memory / len(metrics) if metrics else 0 | |
| # Memory per agent should be reasonable (adjust threshold as needed) | |
| assert avg_memory < 100, f"Average memory per agent: {avg_memory:.2f}MB" | |
| total_memory_mb = total_memory | |
| assert total_memory_mb < 5000, f"Total memory: {total_memory_mb:.2f}MB" | |
| async def test_fifty_agents_concurrent_shutdown(self, fifty_agents): | |
| # Test graceful shutdown of 50 agents. | |
| start_time = time.perf_counter() | |
| # Stop agents in batches to avoid overwhelming system | |
| batch_size = 10 | |
| for i in range(0, len(fifty_agents), batch_size): | |
| batch = fifty_agents[i : i + batch_size] | |
| await asyncio.gather(*[agent.stop() for agent in batch]) | |
| elapsed = time.perf_counter() - start_time | |
| assert all(agent.status == "stopped" for agent in fifty_agents) | |
| assert elapsed < 10.0, f"50 agent shutdown took {elapsed:.2f}s" | |
| # ============================================================================ | |
| # 100 Agent Concurrency Tests (Main PoC Tests) | |
| # ============================================================================ | |
| class TestHundredAgents: | |
| # Tests for 100 concurrent agents - Main PoC validation. | |
| async def test_hundred_agents_startup_time(self, mock_agent_factory): | |
| # Test 100 agents startup completes within 30 seconds. | |
| agents = [mock_agent_factory() for _ in range(100)] | |
| start_time = time.perf_counter() | |
| # Start with rate limiting | |
| batch_size = 10 | |
| for i in range(0, len(agents), batch_size): | |
| batch = agents[i : i + batch_size] | |
| await asyncio.gather(*[agent.start() for agent in batch]) | |
| await asyncio.sleep(0.1) # Small delay between batches | |
| elapsed = time.perf_counter() - start_time | |
| assert len(agents) == 100 | |
| running_count = sum(1 for a in agents if a.status == "running") | |
| assert running_count == 100, f"Only {running_count}/100 agents running" | |
| # PoC requirement: startup within 30 seconds | |
| assert elapsed < 30.0, f"100 agent startup took {elapsed:.2f}s (target: <30s)" | |
| # Cleanup | |
| await asyncio.gather(*[agent.stop() for agent in agents]) | |
| async def test_hundred_agents_spawn_rate(self, mock_agent_factory): | |
| # Test agent spawn rate exceeds 10 agents/second. | |
| agents = [] | |
| batch_size = 10 | |
| start_time = time.perf_counter() | |
| for i in range(0, 100, batch_size): | |
| batch = [mock_agent_factory() for _ in range(batch_size)] | |
| await asyncio.gather(*[agent.start() for agent in batch]) | |
| agents.extend(batch) | |
| elapsed = time.perf_counter() - start_time | |
| spawn_rate = len(agents) / elapsed | |
| # PoC requirement: >10 agents/second | |
| assert spawn_rate > 10, f"Spawn rate: {spawn_rate:.2f} agents/s (target: >10/s)" | |
| # Cleanup | |
| await asyncio.gather(*[agent.stop() for agent in agents]) | |
| async def test_hundred_agents_concurrent_task_execution(self, hundred_agents, generate_tasks): | |
| # Test 100 agents executing tasks concurrently. | |
| tasks = generate_tasks(200) # 2 tasks per agent | |
| # Create task-agent pairs | |
| task_agent_pairs = [(hundred_agents[i % len(hundred_agents)], task) for i, task in enumerate(tasks)] | |
| start_time = time.perf_counter() | |
| # Execute all tasks concurrently | |
| results = await asyncio.gather(*[agent.execute_task(task) for agent, task in task_agent_pairs]) | |
| elapsed = time.perf_counter() - start_time | |
| assert len(results) == 200 | |
| success_count = sum(1 for r in results if r["status"] == "completed") | |
| assert success_count == 200, f"Only {success_count}/200 tasks completed" | |
| # Should complete within reasonable time | |
| assert elapsed < 60.0, f"200 tasks took {elapsed:.2f}s" | |
| async def test_hundred_agents_resource_efficiency(self, hundred_agents): | |
| # Test resource efficiency with 100 agents. | |
| metrics = await asyncio.gather(*[agent.get_metrics() for agent in hundred_agents]) | |
| # Calculate resource usage | |
| total_memory = sum(m.get("memory_usage", 0) for m in metrics) | |
| avg_memory = total_memory / len(metrics) | |
| # PoC requirement: <50MB per agent | |
| assert avg_memory < 50, f"Avg memory per agent: {avg_memory:.2f}MB (target: <50MB)" | |
| # Total memory should be under 5GB | |
| assert total_memory < 5120, f"Total memory: {total_memory:.2f}MB (target: <5GB)" | |
| async def test_hundred_agents_graceful_shutdown(self, hundred_agents): | |
| # Test graceful shutdown of 100 agents. | |
| start_time = time.perf_counter() | |
| # Stop in batches to avoid overwhelming system | |
| batch_size = 20 | |
| for i in range(0, len(hundred_agents), batch_size): | |
| batch = hundred_agents[i : i + batch_size] | |
| await asyncio.gather(*[agent.stop() for agent in batch]) | |
| elapsed = time.perf_counter() - start_time | |
| stopped_count = sum(1 for a in hundred_agents if a.status == "stopped") | |
| assert stopped_count == 100, f"Only {stopped_count}/100 agents stopped" | |
| # Should shutdown within reasonable time | |
| assert elapsed < 15.0, f"100 agent shutdown took {elapsed:.2f}s" | |
| async def test_hundred_agents_orchestrator_integration(self, orchestrator, mock_agent_factory): | |
| # Test orchestrator managing 100 agents. | |
| # Spawn 100 agents via orchestrator | |
| start_time = time.perf_counter() | |
| agents = await orchestrator.spawn_agents(mock_agent_factory, 100) | |
| spawn_elapsed = time.perf_counter() - start_time | |
| assert len(agents) == 100 | |
| assert len(orchestrator.agents) == 100 | |
| assert spawn_elapsed < 30.0, f"Orchestrator spawn took {spawn_elapsed:.2f}s" | |
| # Test task distribution | |
| task = {"type": "test", "data": "sample"} | |
| results = await orchestrator.distribute_task(task) | |
| assert len(results) == 100 | |
| # Test metrics collection | |
| metrics = await orchestrator.get_all_metrics() | |
| assert metrics["total_agents"] == 100 | |
| # Cleanup | |
| await orchestrator.terminate_all() | |
| assert len(orchestrator.agents) == 0 | |
| # ============================================================================ | |
| # Agent Pool Tests (Variable Size) | |
| # ============================================================================ | |
| class TestAgentPool: | |
| # Tests for variable-sized agent pools. | |
| async def test_agent_pool_scalability(self, mock_agent_factory, pool_size): | |
| # Test agent pool scalability at different sizes. | |
| agents = [mock_agent_factory() for _ in range(pool_size)] | |
| start_time = time.perf_counter() | |
| await asyncio.gather(*[agent.start() for agent in agents]) | |
| elapsed = time.perf_counter() - start_time | |
| # Startup time should scale roughly linearly | |
| expected_max = pool_size * 0.5 # 0.5s per agent max | |
| assert elapsed < expected_max, f"{pool_size} agents took {elapsed:.2f}s" | |
| assert all(agent.status == "running" for agent in agents) | |
| # Cleanup | |
| await asyncio.gather(*[agent.stop() for agent in agents]) | |
| async def test_agent_pool_task_throughput(self, mock_agent_factory, pool_size, generate_tasks): | |
| # Test task throughput at different pool sizes. | |
| agents = [mock_agent_factory() for _ in range(pool_size)] | |
| await asyncio.gather(*[agent.start() for agent in agents]) | |
| tasks = generate_tasks(pool_size * 2) # 2x tasks per agent | |
| start_time = time.perf_counter() | |
| # Execute tasks | |
| task_idx = 0 | |
| for agent in agents: | |
| for _ in range(2): | |
| await agent.execute_task(tasks[task_idx]) | |
| task_idx += 1 | |
| elapsed = time.perf_counter() - start_time | |
| throughput = len(tasks) / elapsed | |
| # Throughput should increase with pool size | |
| assert throughput > 1.0, f"Throughput: {throughput:.2f} tasks/s" | |
| # Cleanup | |
| await asyncio.gather(*[agent.stop() for agent in agents]) | |
| # ============================================================================ | |
| # Concurrent Task Execution Tests | |
| # ============================================================================ | |
| class TestConcurrentTaskExecution: | |
| # Tests for concurrent task execution patterns. | |
| async def test_concurrent_same_task_multiple_agents(self, ten_agents, sample_task): | |
| # Test same task executed by multiple agents concurrently. | |
| start_time = time.perf_counter() | |
| results = await asyncio.gather(*[agent.execute_task(sample_task) for agent in ten_agents]) | |
| elapsed = time.perf_counter() - start_time | |
| assert len(results) == 10 | |
| assert all(r["status"] == "completed" for r in results) | |
| # Parallel execution should be faster than sequential | |
| assert elapsed < 5.0 | |
| async def test_staggered_task_execution(self, fifty_agents, generate_tasks): | |
| tasks = generate_tasks(500) # 5 tasks per agent | |
| # Create semaphore to limit concurrent execution | |
| semaphore = asyncio.Semaphore(50) # Max 50 concurrent | |
| async def execute_with_limit(agent, task): | |
| async with semaphore: | |
| return await agent.execute_task(task) | |
| # Distribute tasks | |
| task_agent_pairs = [(fifty_agents[i % len(fifty_agents)], tasks[i]) for i in range(len(tasks))] | |
| start_time = time.perf_counter() | |
| results = await asyncio.gather(*[execute_with_limit(agent, task) for agent, task in task_agent_pairs]) | |
| elapsed = time.perf_counter() - start_time | |
| assert len(results) == 500 | |
| success_rate = sum(1 for r in results if r["status"] == "completed") / len(results) | |
| assert success_rate >= 0.99, f"Success rate: {success_rate * 100:.1f}%" | |
| assert elapsed < 120.0, f"500 tasks took {elapsed:.2f}s" | |
| # ============================================================================ | |
| # Performance Benchmark Tests | |
| # ============================================================================ | |
| class TestAgentPerformanceBenchmarks: | |
| # Performance benchmarks for agent operations. | |
| async def test_agent_startup_benchmark(self, benchmark, mock_agent_factory): | |
| # Benchmark agent startup performance. | |
| async def startup_100(): | |
| agents = [mock_agent_factory() for _ in range(100)] | |
| await asyncio.gather(*[agent.start() for agent in agents]) | |
| return agents | |
| agents = await benchmark.measure("startup_100", startup_100()) | |
| await asyncio.gather(*[agent.stop() for agent in agents]) | |
| print(benchmark.get_report()) | |
| async def test_task_throughput_benchmark(self, benchmark, hundred_agents, generate_tasks): | |
| # Benchmark task throughput. | |
| tasks = generate_tasks(100) | |
| async def execute_100_tasks(): | |
| return await asyncio.gather(*[agent.execute_task(task) for agent, task in zip(hundred_agents, tasks)]) | |
| await benchmark.measure("execute_100_tasks", execute_100_tasks()) | |
| print(benchmark.get_report()) | |
| async def test_metrics_collection_benchmark(self, benchmark, hundred_agents): | |
| # Benchmark metrics collection performance | |
| async def collect_all_metrics(): | |
| return await asyncio.gather(*[agent.get_metrics() for agent in hundred_agents]) | |
| await benchmark.measure("collect_100_metrics", collect_all_metrics()) | |
| print(benchmark.get_report()) | |
Xet Storage Details
- Size:
- 19.7 kB
- Xet hash:
- bde5c3139167235c44442aefc33fba107ecbf4ff7b5aa8f7cb7b4345fc0e2168
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.