Independent Auditing of AI Agents. Run by human or the agent itself, to answer the most crucial question in the AI Agent Economy. Is the agent doing what is supposed to do? With iFixAi you can have this answer in less than 120 seconds.
Python agent-evaluationaiai-alignmentai-evaluationai-governanceai-safetyclidiagnostic-tooleu-ai-acthallucination-detectioniso-42001llm-evaluationllm-securitynist-ai-rmfowasp-llmprompt-injectionpythonresponsible-airisk-assessmentrisk-management
fix(judge): isolate rubric loader locks by event loop (#180)
Rudy Mizrahi Celekliadbe570ad656
diff --git a/ifixai/evaluation/analytic_judge.py b/ifixai/evaluation/analytic_judge.pyindex 864c959..b0682d2 100644--- a/ifixai/evaluation/analytic_judge.py+++ b/ifixai/evaluation/analytic_judge.py@@ -5,6 +5,7 @@ import loggingimport osimport reimport secrets+import weakreffrom enum import Enumfrom pathlib import Pathfrom typing import Final, Optional@@ -131,21 +132,25 @@ def render_judge_prompt_template(_rubric_cache: dict[str, Optional[AnalyticRubric]] = {}-_rubric_cache_lock: Optional[asyncio.Lock] = None+_rubric_cache_locks: weakref.WeakKeyDictionary[+ asyncio.AbstractEventLoop, weakref.ReferenceType[asyncio.Lock]+] = weakref.WeakKeyDictionary()def _get_rubric_cache_lock() -> asyncio.Lock:- """Lazily create the rubric-cache lock on the running event loop.+ """Share a lock between concurrent loads on the current running loop.- Creating the Lock at module-import time binds it to whatever loop is- running then (often none, or a deprecated default), and triggers- DeprecationWarning / RuntimeError on first use under some test harness- or worker-thread configurations.+ A contended asyncio.Lock binds to its event loop. API callers may use+ successive asyncio.run() calls, so a process-global lock cannot be reused.+ Weak keys and values let closed loops and their idle locks be collected."""- global _rubric_cache_lock- if _rubric_cache_lock is None:- _rubric_cache_lock = asyncio.Lock()- return _rubric_cache_lock+ loop = asyncio.get_running_loop()+ reference = _rubric_cache_locks.get(loop)+ lock = reference() if reference is not None else None+ if lock is None:+ lock = asyncio.Lock()+ _rubric_cache_locks[loop] = weakref.ref(lock)+ return lockdef generate_envelope_nonce() -> str:diff --git a/ifixai/tests/evaluation/test_rubric_loop_ownership.py b/ifixai/tests/evaluation/test_rubric_loop_ownership.pynew file mode 100644index 0000000..a862ded--- /dev/null+++ b/ifixai/tests/evaluation/test_rubric_loop_ownership.py@@ -0,0 +1,54 @@+import asyncio++import pytest++from ifixai.evaluation import analytic_judge++[email protected](autouse=True)+def fresh_rubric_cache(monkeypatch):+ monkeypatch.setattr(analytic_judge, '_rubric_cache', {})+ # Start without prior loader calls; all contention comes from actual YAML IO.+ if hasattr(analytic_judge, '_rubric_cache_lock'):+ monkeypatch.setattr(analytic_judge, '_rubric_cache_lock', None)+++def load_pair(first, second):+ async def load():+ return await asyncio.gather(+ analytic_judge.load_analytic_rubric(first, 'comply'),+ analytic_judge.load_analytic_rubric(second, 'comply'),+ )+ return asyncio.run(load())+++def test_concurrent_rubric_loads_work_across_successive_api_event_loops():+ first = load_pair('B06', 'B07')+ second = load_pair('B08', 'B09')+ assert [r.test_id for r in first] == ['B06', 'B07']+ assert [r.test_id for r in second] == ['B08', 'B09']+++def test_same_loop_repeated_loads_share_cached_rubric():+ results = load_pair('B06', 'B06')+ assert results[0] is results[1]+ assert results[0].references is not None+++def test_public_parallel_runs_load_new_rubrics_on_a_second_event_loop():+ from ifixai.api import run_selected+ from ifixai.core.concurrency import ConcurrencyGovernor+ from ifixai.core.types import EvaluationPipelineConfig, TestStatus+ from ifixai.judge.config import JudgeConfig++ async def run(ids):+ return await run_selected(+ ids, provider='mock', fixture='customer_support',+ pipeline_config=EvaluationPipelineConfig(judge_max_calls=2000),+ judge_config=JudgeConfig(provider='mock'), governor=ConcurrencyGovernor(2),+ )+ for ids in [{'B06', 'B08'}, {'B09', 'B10'}]:+ result = asyncio.run(run(ids))+ assert all(r.status is not TestStatus.ERROR for r in result.test_results), [+ r.error_message for r in result.test_results+ ]