Spaces:
Sleeping
Sleeping
Add llm implementation and hybrid model implementation
Browse files
changes.md
CHANGED
|
@@ -2,32 +2,34 @@
|
|
| 2 |
|
| 3 |
## Summary of recent changes
|
| 4 |
|
| 5 |
-
- Updated `feature-flag-agent-env/agents/llm_agent.py`
|
| 6 |
-
-
|
| 7 |
-
-
|
| 8 |
-
-
|
| 9 |
-
- Updated `feature-flag-agent-env/
|
| 10 |
-
-
|
| 11 |
-
-
|
| 12 |
-
-
|
| 13 |
-
|
| 14 |
-
-
|
| 15 |
-
-
|
| 16 |
-
-
|
| 17 |
-
|
| 18 |
-
-
|
|
|
|
|
|
|
| 19 |
|
| 20 |
## Current repository state
|
| 21 |
|
| 22 |
- Modified files:
|
| 23 |
-
- `COMPLETE_SETUP_AND_REFERENCE_GUIDE.md`
|
| 24 |
-
- `feature-flag-agent-env/agents/llm_agent.py`
|
| 25 |
-
- `feature-flag-agent-env/examples/run_llm_agent.py`
|
| 26 |
-
- New files created but not yet tracked by git:
|
| 27 |
- `changes.md`
|
|
|
|
|
|
|
| 28 |
- `feature-flag-agent-env/tests/test_llm_agent.py`
|
|
|
|
| 29 |
|
| 30 |
## Notes
|
| 31 |
|
| 32 |
-
-
|
| 33 |
-
-
|
|
|
|
|
|
| 2 |
|
| 3 |
## Summary of recent changes
|
| 4 |
|
| 5 |
+
- Updated `feature-flag-agent-env/agents/llm_agent.py`:
|
| 6 |
+
- improved `.env` discovery so `GROQ_API_KEY` can load from the working directory and parent repo paths
|
| 7 |
+
- preserved Groq client initialization when the API key is present
|
| 8 |
+
- ensured `LLMAgent.decide()` increments `api_calls` for real Groq requests
|
| 9 |
+
- Updated `feature-flag-agent-env/agents/hybrid_agent.py`:
|
| 10 |
+
- added stronger unsafe action detection for `FULL_ROLLOUT` and `INCREASE_ROLLOUT`
|
| 11 |
+
- automatically falls back to baseline actions when LLM output is unsafe
|
| 12 |
+
- preserves the original LLM reason in the safety override message
|
| 13 |
+
- Updated `feature-flag-agent-env/tests/test_llm_agent.py`:
|
| 14 |
+
- added a real Groq integration assertion: `agent.api_calls >= 1`
|
| 15 |
+
- added hybrid agent pass-through safety tests
|
| 16 |
+
- added hybrid backend integration validation with `EnvironmentClient`
|
| 17 |
+
- Added scenario-based environment tests in `feature-flag-agent-env/tests/test_simulation.py`:
|
| 18 |
+
- `test_agents_on_high_error_scenario`
|
| 19 |
+
- `test_agents_on_latency_degradation_scenario`
|
| 20 |
+
- `test_agents_on_good_scenario_scaling_fast`
|
| 21 |
|
| 22 |
## Current repository state
|
| 23 |
|
| 24 |
- Modified files:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
- `changes.md`
|
| 26 |
+
- `feature-flag-agent-env/agents/llm_agent.py`
|
| 27 |
+
- `feature-flag-agent-env/agents/hybrid_agent.py`
|
| 28 |
- `feature-flag-agent-env/tests/test_llm_agent.py`
|
| 29 |
+
- `feature-flag-agent-env/tests/test_simulation.py`
|
| 30 |
|
| 31 |
## Notes
|
| 32 |
|
| 33 |
+
- `cd feature-flag-agent-env && python -m pytest tests/test_llm_agent.py -q` β `17 passed`
|
| 34 |
+
- `cd feature-flag-agent-env && python -m pytest tests/test_simulation.py -q` β `10 passed`
|
| 35 |
+
- Groq API usage now reports actual calls in `agent.api_calls` when `GROQ_API_KEY` is configured.
|
feature-flag-agent-env/agents/hybrid_agent.py
CHANGED
|
@@ -25,19 +25,36 @@ class HybridAgent:
|
|
| 25 |
self.api_calls = 0
|
| 26 |
self.safety_overrides = 0
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
def decide(self, observation, history):
|
| 29 |
proposed = self.llm.decide(observation, history)
|
| 30 |
self.api_calls = self.llm.api_calls
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
self.safety_overrides += 1
|
| 37 |
if self.debug:
|
| 38 |
print(
|
| 39 |
f"[HYBRID DEBUG] override#{self.safety_overrides} "
|
| 40 |
-
f"
|
|
|
|
|
|
|
| 41 |
)
|
| 42 |
return safe_action
|
| 43 |
|
|
|
|
| 25 |
self.api_calls = 0
|
| 26 |
self.safety_overrides = 0
|
| 27 |
|
| 28 |
+
def _is_unsafe(self, proposed, observation):
|
| 29 |
+
if proposed.action_type in {"FULL_ROLLOUT", "INCREASE_ROLLOUT"}:
|
| 30 |
+
if observation.error_rate > 0.10:
|
| 31 |
+
return True
|
| 32 |
+
if observation.system_health_score < 0.70:
|
| 33 |
+
return True
|
| 34 |
+
if proposed.target_percentage > observation.current_rollout_percentage + 20:
|
| 35 |
+
return True
|
| 36 |
+
|
| 37 |
+
if proposed.action_type == "FULL_ROLLOUT" and observation.error_rate > 0.05:
|
| 38 |
+
return True
|
| 39 |
+
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
def decide(self, observation, history):
|
| 43 |
proposed = self.llm.decide(observation, history)
|
| 44 |
self.api_calls = self.llm.api_calls
|
| 45 |
+
safe_action = self.safe.decide(observation, history)
|
| 46 |
|
| 47 |
+
if self._is_unsafe(proposed, observation):
|
| 48 |
+
safe_action.reason = (
|
| 49 |
+
f"Safety override: {proposed.reason or 'LLM action was unsafe'}"
|
| 50 |
+
)
|
| 51 |
self.safety_overrides += 1
|
| 52 |
if self.debug:
|
| 53 |
print(
|
| 54 |
f"[HYBRID DEBUG] override#{self.safety_overrides} "
|
| 55 |
+
f"proposed={proposed.action_type}({proposed.target_percentage}) "
|
| 56 |
+
f"error={observation.error_rate*100:.2f}% "
|
| 57 |
+
f"health={observation.system_health_score:.2f}"
|
| 58 |
)
|
| 59 |
return safe_action
|
| 60 |
|
feature-flag-agent-env/agents/llm_agent.py
CHANGED
|
@@ -12,12 +12,17 @@ from feature_flag_env.models import FeatureFlagAction, FeatureFlagObservation
|
|
| 12 |
|
| 13 |
|
| 14 |
if load_dotenv is not None:
|
| 15 |
-
# Load
|
| 16 |
load_dotenv()
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
class LLMAgent:
|
|
|
|
| 12 |
|
| 13 |
|
| 14 |
if load_dotenv is not None:
|
| 15 |
+
# Load environment variables from common .env locations.
|
| 16 |
load_dotenv()
|
| 17 |
+
env_candidates = [
|
| 18 |
+
Path.cwd() / ".env",
|
| 19 |
+
Path(__file__).resolve().parents[1] / ".env",
|
| 20 |
+
Path(__file__).resolve().parents[2] / ".env",
|
| 21 |
+
Path(__file__).resolve().parents[3] / ".env",
|
| 22 |
+
]
|
| 23 |
+
for env_path in env_candidates:
|
| 24 |
+
if env_path.exists():
|
| 25 |
+
load_dotenv(dotenv_path=env_path)
|
| 26 |
|
| 27 |
|
| 28 |
class LLMAgent:
|
feature-flag-agent-env/tests/test_llm_agent.py
CHANGED
|
@@ -160,6 +160,40 @@ def test_decide_with_real_groq_api():
|
|
| 160 |
assert 0.0 <= action.target_percentage <= 100.0
|
| 161 |
assert action.reason
|
| 162 |
assert action.reason != "LLM decision"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
|
| 165 |
def test_decide_recovery_on_api_error(monkeypatch):
|
|
@@ -206,3 +240,62 @@ def test_hybrid_agent_safety_override(monkeypatch):
|
|
| 206 |
assert action.action_type != "INCREASE_ROLLOUT"
|
| 207 |
assert action.reason.startswith("Safety override")
|
| 208 |
assert hybrid.safety_overrides == 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
assert 0.0 <= action.target_percentage <= 100.0
|
| 161 |
assert action.reason
|
| 162 |
assert action.reason != "LLM decision"
|
| 163 |
+
assert agent.api_calls >= 1
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_decide_with_real_groq_api_multiple_calls():
|
| 167 |
+
api_key = os.getenv("GROQ_API_KEY")
|
| 168 |
+
if not api_key:
|
| 169 |
+
pytest.skip("GROQ_API_KEY not set in environment")
|
| 170 |
+
|
| 171 |
+
try:
|
| 172 |
+
import groq # noqa: F401
|
| 173 |
+
except ImportError:
|
| 174 |
+
pytest.skip("groq package is not installed")
|
| 175 |
+
|
| 176 |
+
agent = LLMAgent()
|
| 177 |
+
if agent.use_baseline:
|
| 178 |
+
pytest.skip("LLMAgent is using baseline fallback despite GROQ_API_KEY")
|
| 179 |
+
|
| 180 |
+
for idx in range(5):
|
| 181 |
+
obs = make_observation(
|
| 182 |
+
current_rollout_percentage=40.0 + idx * 5.0,
|
| 183 |
+
error_rate=0.02 + idx * 0.005,
|
| 184 |
+
)
|
| 185 |
+
action = agent.decide(obs, history=[])
|
| 186 |
+
assert action.action_type in {
|
| 187 |
+
"INCREASE_ROLLOUT",
|
| 188 |
+
"DECREASE_ROLLOUT",
|
| 189 |
+
"MAINTAIN",
|
| 190 |
+
"HALT_ROLLOUT",
|
| 191 |
+
"FULL_ROLLOUT",
|
| 192 |
+
"ROLLBACK",
|
| 193 |
+
}
|
| 194 |
+
assert 0.0 <= action.target_percentage <= 100.0
|
| 195 |
+
|
| 196 |
+
assert agent.api_calls == 5
|
| 197 |
|
| 198 |
|
| 199 |
def test_decide_recovery_on_api_error(monkeypatch):
|
|
|
|
| 240 |
assert action.action_type != "INCREASE_ROLLOUT"
|
| 241 |
assert action.reason.startswith("Safety override")
|
| 242 |
assert hybrid.safety_overrides == 1
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def test_hybrid_agent_passes_safe_llm_action(monkeypatch):
|
| 246 |
+
hybrid = HybridAgent()
|
| 247 |
+
|
| 248 |
+
monkeypatch.setattr(
|
| 249 |
+
hybrid.llm,
|
| 250 |
+
"decide",
|
| 251 |
+
lambda observation, history: FeatureFlagAction(
|
| 252 |
+
action_type="INCREASE_ROLLOUT",
|
| 253 |
+
target_percentage=50.0,
|
| 254 |
+
reason="Safe rollout increase"
|
| 255 |
+
),
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
obs = make_observation(error_rate=0.03, current_rollout_percentage=40.0)
|
| 259 |
+
action = hybrid.decide(obs, history=[])
|
| 260 |
+
|
| 261 |
+
assert action.action_type == "INCREASE_ROLLOUT"
|
| 262 |
+
assert action.target_percentage == 50.0
|
| 263 |
+
assert action.reason == "Safe rollout increase"
|
| 264 |
+
assert hybrid.safety_overrides == 0
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def test_hybrid_agent_integration_with_environment(monkeypatch):
|
| 268 |
+
from inference import EnvironmentClient
|
| 269 |
+
|
| 270 |
+
hybrid = HybridAgent()
|
| 271 |
+
|
| 272 |
+
monkeypatch.setattr(
|
| 273 |
+
hybrid.llm,
|
| 274 |
+
"decide",
|
| 275 |
+
lambda observation, history: FeatureFlagAction(
|
| 276 |
+
action_type="FULL_ROLLOUT",
|
| 277 |
+
target_percentage=100.0,
|
| 278 |
+
reason="Force full rollout"
|
| 279 |
+
),
|
| 280 |
+
)
|
| 281 |
+
|
| 282 |
+
env_client = EnvironmentClient(task="task3")
|
| 283 |
+
obs = env_client.reset()
|
| 284 |
+
action = hybrid.decide(obs, history=[])
|
| 285 |
+
|
| 286 |
+
assert action.action_type in {
|
| 287 |
+
"INCREASE_ROLLOUT",
|
| 288 |
+
"DECREASE_ROLLOUT",
|
| 289 |
+
"MAINTAIN",
|
| 290 |
+
"HALT_ROLLOUT",
|
| 291 |
+
"FULL_ROLLOUT",
|
| 292 |
+
"ROLLBACK",
|
| 293 |
+
}
|
| 294 |
+
assert 0.0 <= action.target_percentage <= 100.0
|
| 295 |
+
assert action.reason
|
| 296 |
+
|
| 297 |
+
next_obs, reward, done, info = env_client.step(action)
|
| 298 |
+
assert isinstance(next_obs, FeatureFlagObservation)
|
| 299 |
+
assert isinstance(reward, float)
|
| 300 |
+
assert isinstance(done, bool)
|
| 301 |
+
assert isinstance(info, dict)
|
feature-flag-agent-env/tests/test_simulation.py
CHANGED
|
@@ -9,7 +9,38 @@ import sys
|
|
| 9 |
import os
|
| 10 |
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
| 11 |
|
|
|
|
|
|
|
|
|
|
| 12 |
from feature_flag_env.server.simulation_engine import FeatureFlagSimulator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
def test_basic_simulation():
|
|
@@ -53,7 +84,6 @@ def test_basic_simulation():
|
|
| 53 |
assert 0.0 <= metrics['system_health_score'] <= 1.0, "Health out of range"
|
| 54 |
|
| 55 |
print(" β
All metrics in valid ranges")
|
| 56 |
-
return True
|
| 57 |
|
| 58 |
|
| 59 |
def test_error_scaling():
|
|
@@ -81,7 +111,6 @@ def test_error_scaling():
|
|
| 81 |
# (allowing for some noise)
|
| 82 |
assert error_rates[-1] > error_rates[0], "Errors should increase with rollout"
|
| 83 |
print(" β
Errors scale with rollout percentage")
|
| 84 |
-
return True
|
| 85 |
|
| 86 |
|
| 87 |
def test_incident_zones():
|
|
@@ -110,7 +139,6 @@ def test_incident_zones():
|
|
| 110 |
assert metrics_45['error_rate'] > metrics_35['error_rate'], \
|
| 111 |
"Error should spike in incident zone"
|
| 112 |
print(" β
Incident zones trigger error spikes")
|
| 113 |
-
return True
|
| 114 |
|
| 115 |
|
| 116 |
def test_adoption_growth():
|
|
@@ -136,7 +164,6 @@ def test_adoption_growth():
|
|
| 136 |
# Adoption should increase over time (gradual growth)
|
| 137 |
assert adoption_rates[-1] > adoption_rates[0], "Adoption should grow over time"
|
| 138 |
print(" β
Adoption grows gradually")
|
| 139 |
-
return True
|
| 140 |
|
| 141 |
|
| 142 |
def test_revenue_calculation():
|
|
@@ -162,7 +189,6 @@ def test_revenue_calculation():
|
|
| 162 |
print(f" Revenue at high adoption: ${metrics['revenue_impact']:.2f}")
|
| 163 |
assert metrics['revenue_impact'] > 0, "Revenue should be positive"
|
| 164 |
print(" β
Revenue calculated correctly")
|
| 165 |
-
return True
|
| 166 |
|
| 167 |
|
| 168 |
def test_health_score():
|
|
@@ -202,7 +228,156 @@ def test_health_score():
|
|
| 202 |
assert good_metrics['system_health_score'] > bad_metrics['system_health_score'], \
|
| 203 |
"Good scenario should have higher health"
|
| 204 |
print(" β
Health score reflects system state")
|
| 205 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
|
| 207 |
|
| 208 |
def test_reproducibility():
|
|
@@ -229,7 +404,6 @@ def test_reproducibility():
|
|
| 229 |
print(f" Run 1 error rate: {metrics1['error_rate']:.6f}")
|
| 230 |
print(f" Run 2 error rate: {metrics2['error_rate']:.6f}")
|
| 231 |
print(" β
Results are reproducible with same seed")
|
| 232 |
-
return True
|
| 233 |
|
| 234 |
|
| 235 |
def main():
|
|
|
|
| 9 |
import os
|
| 10 |
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
|
| 11 |
|
| 12 |
+
import random
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
from feature_flag_env.server.simulation_engine import FeatureFlagSimulator
|
| 16 |
+
from feature_flag_env.server.feature_flag_environment import FeatureFlagEnvironment
|
| 17 |
+
from feature_flag_env.models import FeatureFlagAction
|
| 18 |
+
from agents.baseline_agent import BaselineAgent
|
| 19 |
+
from agents.hybrid_agent import HybridAgent
|
| 20 |
+
from agents.llm_agent import LLMAgent
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _run_agent_episode(agent, scenario_config, max_steps=None):
|
| 24 |
+
env = FeatureFlagEnvironment(scenario_config=scenario_config)
|
| 25 |
+
observation = env.reset()
|
| 26 |
+
history = []
|
| 27 |
+
|
| 28 |
+
while not observation.done and env.state().step_count < (max_steps or env.state().max_steps):
|
| 29 |
+
action = agent.decide(observation, history)
|
| 30 |
+
response = env.step(action)
|
| 31 |
+
history.append({"action": action, "observation": response.observation, "reward": response.reward})
|
| 32 |
+
observation = response.observation
|
| 33 |
+
|
| 34 |
+
return {
|
| 35 |
+
"steps": env.state().step_count,
|
| 36 |
+
"total_reward": env.state().total_reward,
|
| 37 |
+
"final_rollout": observation.current_rollout_percentage,
|
| 38 |
+
"final_error_rate": observation.error_rate,
|
| 39 |
+
"final_latency": observation.latency_p99_ms,
|
| 40 |
+
"history": history,
|
| 41 |
+
"rollbacks": sum(1 for step in history if step["action"].action_type == "ROLLBACK"),
|
| 42 |
+
"done_reason": response.info.get("done_reason", ""),
|
| 43 |
+
}
|
| 44 |
|
| 45 |
|
| 46 |
def test_basic_simulation():
|
|
|
|
| 84 |
assert 0.0 <= metrics['system_health_score'] <= 1.0, "Health out of range"
|
| 85 |
|
| 86 |
print(" β
All metrics in valid ranges")
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
def test_error_scaling():
|
|
|
|
| 111 |
# (allowing for some noise)
|
| 112 |
assert error_rates[-1] > error_rates[0], "Errors should increase with rollout"
|
| 113 |
print(" β
Errors scale with rollout percentage")
|
|
|
|
| 114 |
|
| 115 |
|
| 116 |
def test_incident_zones():
|
|
|
|
| 139 |
assert metrics_45['error_rate'] > metrics_35['error_rate'], \
|
| 140 |
"Error should spike in incident zone"
|
| 141 |
print(" β
Incident zones trigger error spikes")
|
|
|
|
| 142 |
|
| 143 |
|
| 144 |
def test_adoption_growth():
|
|
|
|
| 164 |
# Adoption should increase over time (gradual growth)
|
| 165 |
assert adoption_rates[-1] > adoption_rates[0], "Adoption should grow over time"
|
| 166 |
print(" β
Adoption grows gradually")
|
|
|
|
| 167 |
|
| 168 |
|
| 169 |
def test_revenue_calculation():
|
|
|
|
| 189 |
print(f" Revenue at high adoption: ${metrics['revenue_impact']:.2f}")
|
| 190 |
assert metrics['revenue_impact'] > 0, "Revenue should be positive"
|
| 191 |
print(" β
Revenue calculated correctly")
|
|
|
|
| 192 |
|
| 193 |
|
| 194 |
def test_health_score():
|
|
|
|
| 228 |
assert good_metrics['system_health_score'] > bad_metrics['system_health_score'], \
|
| 229 |
"Good scenario should have higher health"
|
| 230 |
print(" β
Health score reflects system state")
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def test_agents_on_high_error_scenario(monkeypatch):
|
| 234 |
+
"""Baseline and hybrid agents should stay safe when the environment spikes errors."""
|
| 235 |
+
monkeypatch.setattr(random, "randint", lambda a, b: 123)
|
| 236 |
+
scenario_config = {
|
| 237 |
+
"name": "high_error_feature",
|
| 238 |
+
"base_error_rate": 0.15,
|
| 239 |
+
"error_variance": 0.02,
|
| 240 |
+
"latency_per_10pct_rollout": 12.0,
|
| 241 |
+
"adoption_speed": 0.08,
|
| 242 |
+
"revenue_per_user": 0.10,
|
| 243 |
+
"total_users": 10000,
|
| 244 |
+
"incident_zones": [
|
| 245 |
+
{"min": 20, "max": 55, "probability": 1.0, "spike": 0.20}
|
| 246 |
+
],
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
+
env_base = FeatureFlagEnvironment(scenario_config=scenario_config)
|
| 250 |
+
env_hybrid = FeatureFlagEnvironment(scenario_config=scenario_config)
|
| 251 |
+
env_base.reset()
|
| 252 |
+
env_hybrid.reset()
|
| 253 |
+
|
| 254 |
+
warmup_action = FeatureFlagAction(
|
| 255 |
+
action_type="INCREASE_ROLLOUT",
|
| 256 |
+
target_percentage=80.0,
|
| 257 |
+
reason="Warm-up to high-error state"
|
| 258 |
+
)
|
| 259 |
+
base_warmup = env_base.step(warmup_action)
|
| 260 |
+
hybrid_warmup = env_hybrid.step(warmup_action)
|
| 261 |
+
|
| 262 |
+
baseline_agent = BaselineAgent()
|
| 263 |
+
hybrid_agent = HybridAgent()
|
| 264 |
+
|
| 265 |
+
monkeypatch.setattr(
|
| 266 |
+
hybrid_agent.llm,
|
| 267 |
+
"decide",
|
| 268 |
+
lambda observation, history: FeatureFlagAction(
|
| 269 |
+
action_type="FULL_ROLLOUT",
|
| 270 |
+
target_percentage=100.0,
|
| 271 |
+
reason="Unsafe LLM push"
|
| 272 |
+
),
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
baseline_action = baseline_agent.decide(base_warmup.observation, history=[])
|
| 276 |
+
hybrid_action = hybrid_agent.decide(hybrid_warmup.observation, history=[])
|
| 277 |
+
|
| 278 |
+
assert baseline_action.action_type in {"ROLLBACK", "DECREASE_ROLLOUT", "MAINTAIN"}
|
| 279 |
+
assert hybrid_action.action_type != "FULL_ROLLOUT"
|
| 280 |
+
assert hybrid_agent.safety_overrides == 1
|
| 281 |
+
assert hybrid_action.reason.startswith("Safety override")
|
| 282 |
+
assert hybrid_action.action_type == baseline_action.action_type
|
| 283 |
+
|
| 284 |
+
base_response = env_base.step(baseline_action)
|
| 285 |
+
hybrid_response = env_hybrid.step(hybrid_action)
|
| 286 |
+
|
| 287 |
+
assert base_response.observation.error_rate <= 0.25
|
| 288 |
+
assert hybrid_response.observation.error_rate <= 0.25
|
| 289 |
+
print(" β
High-error scenario: both baseline and hybrid avoid unsafe rollout")
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def test_agents_on_latency_degradation_scenario(monkeypatch):
|
| 293 |
+
"""A high-latency scenario should degrade performance as rollout progresses."""
|
| 294 |
+
monkeypatch.setattr(random, "randint", lambda a, b: 123)
|
| 295 |
+
scenario_config = {
|
| 296 |
+
"name": "latency_degradation_feature",
|
| 297 |
+
"base_error_rate": 0.02,
|
| 298 |
+
"error_variance": 0.002,
|
| 299 |
+
"latency_per_10pct_rollout": 30.0,
|
| 300 |
+
"adoption_speed": 0.05,
|
| 301 |
+
"revenue_per_user": 0.10,
|
| 302 |
+
"total_users": 10000,
|
| 303 |
+
"incident_zones": [],
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
baseline_agent = BaselineAgent()
|
| 307 |
+
metrics = _run_agent_episode(baseline_agent, scenario_config, max_steps=5)
|
| 308 |
+
|
| 309 |
+
assert metrics["final_rollout"] >= 40.0
|
| 310 |
+
assert metrics["final_latency"] > 200.0
|
| 311 |
+
assert metrics["final_error_rate"] < 0.10
|
| 312 |
+
print(" β
Latency degradation scenario: baseline rollout drives latency above acceptable threshold")
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def test_agents_on_good_scenario_scaling_fast(monkeypatch):
|
| 316 |
+
"""A stable scenario should allow fast rollout for both baseline and hybrid agents."""
|
| 317 |
+
monkeypatch.setattr(random, "randint", lambda a, b: 123)
|
| 318 |
+
scenario_config = {
|
| 319 |
+
"name": "good_feature",
|
| 320 |
+
"base_error_rate": 0.005,
|
| 321 |
+
"error_variance": 0.001,
|
| 322 |
+
"latency_per_10pct_rollout": 2.0,
|
| 323 |
+
"adoption_speed": 0.30,
|
| 324 |
+
"revenue_per_user": 0.10,
|
| 325 |
+
"total_users": 10000,
|
| 326 |
+
"incident_zones": [],
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
baseline_agent = BaselineAgent()
|
| 330 |
+
hybrid_agent = HybridAgent()
|
| 331 |
+
monkeypatch.setattr(
|
| 332 |
+
hybrid_agent.llm,
|
| 333 |
+
"decide",
|
| 334 |
+
lambda observation, history: baseline_agent.decide(observation, history),
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
baseline_metrics = _run_agent_episode(baseline_agent, scenario_config)
|
| 338 |
+
hybrid_metrics = _run_agent_episode(hybrid_agent, scenario_config)
|
| 339 |
+
|
| 340 |
+
assert baseline_metrics["final_rollout"] == 100.0
|
| 341 |
+
assert baseline_metrics["steps"] <= 10
|
| 342 |
+
assert baseline_metrics["final_error_rate"] < 0.10
|
| 343 |
+
assert hybrid_metrics["final_rollout"] == 100.0
|
| 344 |
+
assert hybrid_metrics["steps"] <= baseline_metrics["steps"]
|
| 345 |
+
print(" β
Good scenario: baseline and hybrid complete rollout quickly")
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def test_simulation_with_real_groq_llm_if_available():
|
| 349 |
+
api_key = os.getenv("GROQ_API_KEY")
|
| 350 |
+
if not api_key:
|
| 351 |
+
pytest.skip("GROQ_API_KEY not set in environment")
|
| 352 |
+
|
| 353 |
+
try:
|
| 354 |
+
import groq # noqa: F401
|
| 355 |
+
except ImportError:
|
| 356 |
+
pytest.skip("groq package is not installed")
|
| 357 |
+
|
| 358 |
+
llm_agent = LLMAgent()
|
| 359 |
+
if llm_agent.use_baseline:
|
| 360 |
+
pytest.skip("LLMAgent is using baseline fallback despite GROQ_API_KEY")
|
| 361 |
+
|
| 362 |
+
scenario_config = {
|
| 363 |
+
"name": "real_groq_simulation",
|
| 364 |
+
"base_error_rate": 0.02,
|
| 365 |
+
"error_variance": 0.005,
|
| 366 |
+
"latency_per_10pct_rollout": 10.0,
|
| 367 |
+
"adoption_speed": 0.10,
|
| 368 |
+
"revenue_per_user": 0.10,
|
| 369 |
+
"total_users": 10000,
|
| 370 |
+
"incident_zones": [],
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
metrics = _run_agent_episode(llm_agent, scenario_config, max_steps=3)
|
| 374 |
+
|
| 375 |
+
assert llm_agent.api_calls >= 1
|
| 376 |
+
assert metrics["steps"] >= 1
|
| 377 |
+
assert 0.0 <= metrics["final_rollout"] <= 100.0
|
| 378 |
+
assert metrics["final_error_rate"] >= 0.0
|
| 379 |
+
|
| 380 |
+
print(" β
Real Groq LLM simulation exercised actual API calls")
|
| 381 |
|
| 382 |
|
| 383 |
def test_reproducibility():
|
|
|
|
| 404 |
print(f" Run 1 error rate: {metrics1['error_rate']:.6f}")
|
| 405 |
print(f" Run 2 error rate: {metrics2['error_rate']:.6f}")
|
| 406 |
print(" β
Results are reproducible with same seed")
|
|
|
|
| 407 |
|
| 408 |
|
| 409 |
def main():
|