File size: 10,384 Bytes
27cdb3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
DevOpsEnv — OpenEnv-style RL environment for terminal troubleshooting.

The agent observes broken Linux/Python environment states, issues shell commands,
and receives multi-signal rewards. Episodes are bounded by max steps, success,
or dangerous command detection.
"""

from __future__ import annotations

import random
from typing import Any, Dict, List, Optional, Tuple

from devops_env.state_manager import StateManager
from executor.docker_executor import DockerExecutor, ExecutionResult
from fingerprint.classifier import ErrorFingerprinter
from rewards.engine import RewardEngine
from scenarios.registry import Scenario, ScenarioRegistry


class DevOpsEnv:
    """OpenEnv-style environment for DevOps troubleshooting with RL.

    The agent receives an error log and command history as observations,
    outputs a shell command, and gets a reward based on whether the
    command moved toward fixing the issue.

    Attributes:
        metadata: Environment metadata dict.
        max_steps: Maximum steps per episode before truncation.
    """

    metadata = {"render_modes": ["human"]}

    def __init__(
        self,
        scenario_registry: ScenarioRegistry | None = None,
        executor: DockerExecutor | None = None,
        max_steps: int = 10,
        render_mode: str | None = None,
        target_level: int | None = None,
        target_scenario: str | None = None,
    ) -> None:
        """Initialize the DevOps environment.

        Args:
            scenario_registry: Registry of available scenarios. Creates default if None.
            executor: Docker executor for running commands. Creates default if None.
            max_steps: Maximum steps per episode.
            render_mode: Render mode.
            target_level: If set, only sample scenarios from this level.
            target_scenario: If set, always use this specific scenario.
        """
        self.max_steps = max_steps
        self.render_mode = render_mode
        self.target_level = target_level
        self.target_scenario = target_scenario

        # Initialize components
        if scenario_registry is None:
            self.registry = ScenarioRegistry()
            self.registry.register_defaults()
        else:
            self.registry = scenario_registry

        self.executor = executor or DockerExecutor(use_local_fallback=True)
        self.state_manager = StateManager()
        self.reward_engine = RewardEngine()
        self.fingerprinter = ErrorFingerprinter()

        # Episode state
        self._current_scenario: Optional[Scenario] = None
        self._step_count: int = 0
        self._episode_reward: float = 0.0
        self._episode_steps: List[Dict] = []
        self._done: bool = False

        # OpenEnv schemas (documented shape constraints for API clients)
        self.observation_schema: Dict[str, str] = {
            "error_log": "str(max=2000)",
            "command_history": "List[str](max_items=10)",
            "step_count": f"int(0..{max_steps})",
            "scenario_id": "str(max=100)",
            "error_type": "str(max=50)",
            "error_confidence": "float(0.0..1.0)",
            "is_terminal": "bool",
            "solved": "bool",
        }
        self.action_schema: Dict[str, str] = {
            "command": "str(max=500)",
        }

    def reset(
        self,
        seed: int | None = None,
        options: Dict[str, Any] | None = None,
    ) -> Tuple[Dict, Dict]:
        """Reset the environment for a new episode.

        Loads a random scenario (or the target scenario), sets up the
        Docker sandbox, and returns the initial observation.

        Args:
            seed: Random seed for reproducibility.
            options: Additional options (e.g., {"scenario_id": "missing_flask"}).

        Returns:
            Tuple of (observation, info_dict).
        """
        if seed is not None:
            random.seed(seed)

        # Select scenario
        scenario_id = None
        if options and "scenario_id" in options:
            scenario_id = options["scenario_id"]
        elif self.target_scenario:
            scenario_id = self.target_scenario

        if scenario_id:
            self._current_scenario = self.registry.get(scenario_id)
        else:
            self._current_scenario = self.registry.get_random(level=self.target_level)

        # Reset episode state
        self._step_count = 0
        self._episode_reward = 0.0
        self._episode_steps = []
        self._done = False

        # Set up Docker sandbox
        try:
            self.executor.stop_container()
            self.executor.start_container(self._current_scenario.setup_commands)
        except Exception:
            # Continue with local fallback
            pass

        # Initialize state with the scenario's error log
        obs = self.state_manager.reset(
            scenario_id=self._current_scenario.id,
            initial_error_log=self._current_scenario.initial_error_log,
        )

        info = {
            "scenario_id": self._current_scenario.id,
            "level": self._current_scenario.level,
            "description": self._current_scenario.description,
            "error_type": obs["error_type"],
        }

        return obs, info

    def step(self, action: str) -> Tuple[Dict, float, bool, bool, Dict]:
        """Execute one step in the environment.

        Args:
            action: Shell command to execute.

        Returns:
            Tuple of (observation, reward, terminated, truncated, info).
        """
        if self._done:
            raise RuntimeError("Episode is done. Call reset() first.")

        assert self._current_scenario is not None

        self._step_count += 1
        action = action.strip()

        # Execute command in sandbox
        result = self.executor.execute(action)

        # Build new error log from execution output
        if result.blocked:
            new_error_log = f"COMMAND BLOCKED: {result.block_reason}"
        elif result.timed_out:
            new_error_log = "COMMAND TIMED OUT after 30 seconds."
        else:
            new_error_log = ""
            if result.stdout:
                new_error_log += result.stdout
            if result.stderr:
                new_error_log += ("\n" if new_error_log else "") + result.stderr
            if not new_error_log:
                new_error_log = f"Command completed with exit code {result.exit_code}"

        # Get previous error log for reward computation
        prev_error_log = self.state_manager.get_prev_error_log()

        # Compute reward
        all_commands = list(self.state_manager.state.command_history) + [action]
        reward, reward_breakdown = self.reward_engine.compute_reward(
            action=action,
            result=result,
            scenario=self._current_scenario,
            step_count=self._step_count,
            command_history=all_commands,
            prev_error_log=prev_error_log,
            curr_error_log=new_error_log,
        )

        # Check termination conditions
        combined_output = f"{result.stdout}\n{result.stderr}".strip()
        solved = self._current_scenario.success_condition(combined_output)
        is_dangerous_block = result.blocked and "dangerous" in result.block_reason.lower()
        terminated = solved or is_dangerous_block
        truncated = self._step_count >= self.max_steps

        # Update state
        obs = self.state_manager.update(
            command=action,
            new_error_log=new_error_log,
            is_terminal=terminated or truncated,
            solved=solved,
        )

        # Track episode
        self._episode_reward += reward
        self._episode_steps.append({
            "step": self._step_count,
            "action": action,
            "result": {
                "stdout": result.stdout[:1000],
                "stderr": result.stderr[:1000],
                "exit_code": result.exit_code,
                "timed_out": result.timed_out,
                "blocked": result.blocked,
            },
            "reward": reward,
            "reward_breakdown": reward_breakdown,
            "error_type": obs["error_type"],
            "observation": {
                "error_log": obs["error_log"][:500],
                "command_history": obs["command_history"],
                "step_count": obs["step_count"],
            },
        })

        self._done = terminated or truncated

        info = {
            "scenario_id": self._current_scenario.id,
            "level": self._current_scenario.level,
            "solved": solved,
            "step_count": obs["step_count"],
            "episode_reward": self._episode_reward,
            "reward_breakdown": reward_breakdown,
            "error_type": obs["error_type"],
            "execution_result": {
                "exit_code": result.exit_code,
                "blocked": result.blocked,
                "timed_out": result.timed_out,
            },
        }

        if self._done:
            info["episode_steps"] = self._episode_steps

        return obs, reward, terminated, truncated, info

    def get_episode_summary(self) -> Dict:
        """Get a summary of the current/last episode.

        Returns:
            Dict with episode metadata and step details.
        """
        return {
            "scenario_id": self._current_scenario.id if self._current_scenario else None,
            "level": self._current_scenario.level if self._current_scenario else None,
            "steps": self._episode_steps,
            "total_reward": self._episode_reward,
            "solved": self.state_manager.state.solved,
            "total_steps": self._step_count,
        }

    def render(self) -> None:
        """Render the current environment state (human-readable)."""
        if self.render_mode != "human":
            return
        state = self.state_manager.state
        print(f"\n{'='*60}")
        print(f"Scenario: {state.scenario_id} | Step: {state.step_count}")
        print(f"Error Type: {state.error_type}")
        print(f"{'─'*60}")
        print(f"Error Log:\n{state.error_log[:500]}")
        print(f"{'─'*60}")
        if state.command_history:
            print(f"Commands: {state.command_history}")
        print(f"{'='*60}\n")

    def close(self) -> None:
        """Clean up resources."""
        self.executor.stop_container()