import json
from concurrent.futures import ThreadPoolExecutor

from ai_testing_swarm.agents import learning_agent as learning_module
from ai_testing_swarm.agents.learning_agent import LearningAgent


def test_learning_agent_parallel_writes_keep_valid_json(tmp_path, monkeypatch):
    db_path = tmp_path / "failure_memory.json"
    monkeypatch.setattr(learning_module, "DB", str(db_path))

    agent = LearningAgent()

    with ThreadPoolExecutor(max_workers=8) as pool:
        list(pool.map(lambda i: agent.learn(f"t{i}", {"type": "unknown"}), range(40)))

    data = json.loads(db_path.read_text(encoding="utf-8"))
    assert isinstance(data, list)
    assert len(data) == 40
