File size: 11,742 Bytes
e5310eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
"""
multi_agent_env.py β€” MultiAgentDevOpsEnv

Two agents collaborate on the same DevOps incident episode:

  Investigator  β€” gathers evidence and diagnoses
  Responder     β€” applies remediation actions

Both share one underlying DevOpsIncidentEnv. The Investigator's evidence
is visible to the Responder through the shared observation's evidence_log.
"""
from __future__ import annotations

import copy
import uuid
from dataclasses import dataclass, field
from typing import Optional

from env import DevOpsIncidentEnv
from models import Action, ActionType, Observation


# ---------------------------------------------------------------------------
# Role action sets
# ---------------------------------------------------------------------------

INVESTIGATOR_ACTIONS: frozenset[ActionType] = frozenset({
    ActionType.READ_LOGS,
    ActionType.READ_METRICS,
    ActionType.READ_RUNBOOK,
    ActionType.SEARCH_LOGS,
    ActionType.DIAGNOSE,
    ActionType.ACKNOWLEDGE,
    ActionType.NOOP,
})

RESPONDER_ACTIONS: frozenset[ActionType] = frozenset({
    ActionType.RESTART_SERVICE,
    ActionType.ROLLBACK,
    ActionType.BLOCK_IP_RANGE,
    ActionType.CREATE_INDEX,
    ActionType.FAILOVER,
    ActionType.SCALE_UP,
    ActionType.ALERT_ONCALL,
    ActionType.NOOP,
})


# ---------------------------------------------------------------------------
# Joint observation container
# ---------------------------------------------------------------------------

@dataclass
class MultiAgentObservation:
    """Holds both agents' views of the current environment state."""
    investigator_obs: Observation
    responder_obs: Observation
    step: int = 0
    done: bool = False

    def to_dict(self) -> dict:
        return {
            "investigator_obs": (
                self.investigator_obs.model_dump()
                if hasattr(self.investigator_obs, "model_dump")
                else self.investigator_obs.dict()
            ),
            "responder_obs": (
                self.responder_obs.model_dump()
                if hasattr(self.responder_obs, "model_dump")
                else self.responder_obs.dict()
            ),
            "step": self.step,
            "done": self.done,
        }


# ---------------------------------------------------------------------------
# Main class
# ---------------------------------------------------------------------------

class MultiAgentDevOpsEnv:
    """
    Multi-agent wrapper around DevOpsIncidentEnv.

    Two agents β€” Investigator and Responder β€” collaborate on the same
    incident episode.  They share one underlying environment (and thus
    one step counter) but are restricted to disjoint action sets.

    Usage::

        env = MultiAgentDevOpsEnv(task_id="bonus", seed=42)
        obs = env.reset()
        # obs is a MultiAgentObservation

        result = env.step_investigator(
            Action(action_type=ActionType.READ_LOGS, service="log-aggregator")
        )
        # result["investigator_reward"] > 0

        result = env.step_responder(
            Action(action_type=ActionType.ROLLBACK, service="ml-inference-service")
        )
        # result["responder_reward"] > 0

    Both agents may NOOP on any turn.  The episode ends when the
    underlying environment signals done (max_steps or resolution).
    """

    LEVELS = {
        "investigator": INVESTIGATOR_ACTIONS,
        "responder": RESPONDER_ACTIONS,
    }

    def __init__(self, task_id: str = "easy", seed: int = 42) -> None:
        self.task_id = task_id
        self.seed = seed
        self.session_id = str(uuid.uuid4())

        self._env = DevOpsIncidentEnv(task_id=task_id, seed=seed)
        self._obs: Optional[Observation] = None
        self._done: bool = False
        self._step: int = 0

        # Per-agent cumulative rewards
        self._investigator_reward: float = 0.0
        self._responder_reward: float = 0.0

        # History for debugging / logging
        self._investigator_actions: list[dict] = []
        self._responder_actions: list[dict] = []

    # -----------------------------------------------------------------------
    # Public API
    # -----------------------------------------------------------------------

    def reset(self) -> MultiAgentObservation:
        """Reset the environment.  Both agent views are returned."""
        self._obs = self._env.reset(seed=self.seed)
        self._done = False
        self._step = 0
        self._investigator_reward = 0.0
        self._responder_reward = 0.0
        self._investigator_actions.clear()
        self._responder_actions.clear()
        return self._make_obs()

    def step_investigator(self, action: Action) -> dict:
        """
        Investigator takes one step.

        Returns a dict with keys:
            investigator_obs   β€” updated Observation (after action)
            investigator_reward β€” float reward for this step
            done               β€” bool, episode over
            error              β€” str (only present if action was invalid)
        """
        if self._done:
            return {"error": "episode complete", "investigator_reward": 0.0, "done": True}

        if action.action_type not in INVESTIGATOR_ACTIONS:
            return {
                "error": (
                    f"Action '{action.action_type.value}' is not allowed for Investigator. "
                    f"Allowed: {[a.value for a in INVESTIGATOR_ACTIONS]}"
                ),
                "investigator_reward": 0.0,
                "done": False,
            }

        result = self._env.step(action)
        self._obs = result.observation
        self._step += 1
        if result.done:
            self._done = True

        # Investigator-specific reward scaling
        reward = self._compute_investigator_reward(action, result.reward)
        self._investigator_reward += reward
        self._investigator_actions.append({
            "step": self._step,
            "action_type": action.action_type.value,
            "service": action.service,
            "reward": reward,
        })

        return {
            "investigator_obs": (
                result.observation.model_dump()
                if hasattr(result.observation, "model_dump")
                else result.observation.dict()
            ),
            "investigator_reward": reward,
            "done": result.done,
            "info": result.info,
        }

    def step_responder(self, action: Action) -> dict:
        """
        Responder takes one step.

        Returns a dict with keys:
            responder_obs   β€” updated Observation (after action)
            responder_reward β€” float reward for this step
            done             β€” bool, episode over
            error            β€” str (only present if action was invalid)
        """
        if self._done:
            return {"error": "episode complete", "responder_reward": 0.0, "done": True}

        if action.action_type not in RESPONDER_ACTIONS:
            return {
                "error": (
                    f"Action '{action.action_type.value}' is not allowed for Responder. "
                    f"Allowed: {[a.value for a in RESPONDER_ACTIONS]}"
                ),
                "responder_reward": 0.0,
                "done": False,
            }

        result = self._env.step(action)
        self._obs = result.observation
        self._step += 1
        if result.done:
            self._done = True

        # Responder-specific reward scaling
        reward = self._compute_responder_reward(action, result.reward)
        self._responder_reward += reward
        self._responder_actions.append({
            "step": self._step,
            "action_type": action.action_type.value,
            "service": action.service,
            "reward": reward,
        })

        return {
            "responder_obs": (
                result.observation.model_dump()
                if hasattr(result.observation, "model_dump")
                else result.observation.dict()
            ),
            "responder_reward": reward,
            "done": result.done,
            "info": result.info,
        }

    # -----------------------------------------------------------------------
    # Reward accessors
    # -----------------------------------------------------------------------

    def get_investigator_reward(self) -> float:
        """Cumulative reward earned by the Investigator so far."""
        return self._investigator_reward

    def get_responder_reward(self) -> float:
        """Cumulative reward earned by the Responder so far."""
        return self._responder_reward

    def get_joint_reward(self) -> float:
        """Mean of both agents' cumulative rewards."""
        return (self._investigator_reward + self._responder_reward) / 2.0

    def get_state(self) -> dict:
        """Full environment state for logging / debugging."""
        s = self._env.state()
        return {
            "session_id": self.session_id,
            "task_id": self.task_id,
            "seed": self.seed,
            "step": self._step,
            "done": self._done,
            "investigator_reward": self._investigator_reward,
            "responder_reward": self._responder_reward,
            "joint_reward": self.get_joint_reward(),
            "investigator_actions": self._investigator_actions,
            "responder_actions": self._responder_actions,
            "ground_truth_root_cause": s.ground_truth_root_cause,
            "ground_truth_fix": s.ground_truth_fix,
            "incident_resolved": s.incident_resolved,
        }

    # -----------------------------------------------------------------------
    # Internal helpers
    # -----------------------------------------------------------------------

    def _make_obs(self) -> MultiAgentObservation:
        """Build a MultiAgentObservation from the current env state."""
        assert self._obs is not None
        # Both agents see the full observation; role is distinguished by
        # which step_*() method they call, not by observation filtering.
        return MultiAgentObservation(
            investigator_obs=self._obs,
            responder_obs=self._obs,
            step=self._step,
            done=self._done,
        )

    @staticmethod
    def _compute_investigator_reward(action: Action, raw: float) -> float:
        """
        Scale raw env reward for the Investigator role.

        The Investigator is credited for gathering evidence and diagnosing.
        Remediation rewards are not credited to them (they'll be ≀0 anyway
        since the env penalises remediation without diagnosis).
        """
        if action.action_type == ActionType.READ_LOGS:
            return max(raw, 0.0)          # keep positive signal
        if action.action_type == ActionType.READ_METRICS:
            return max(raw, 0.0)
        if action.action_type == ActionType.READ_RUNBOOK:
            return max(raw * 0.5, 0.0)   # lower weight for runbook reads
        if action.action_type == ActionType.DIAGNOSE:
            return raw                    # full credit β€” can be negative too
        if action.action_type == ActionType.NOOP:
            return min(raw, 0.0)          # noop penalised as normal
        return max(raw, 0.0)

    @staticmethod
    def _compute_responder_reward(action: Action, raw: float) -> float:
        """
        Scale raw env reward for the Responder role.

        The Responder is credited for correct remediation and penalised for
        collateral damage.
        """
        if action.action_type == ActionType.NOOP:
            return min(raw, 0.0)
        # Pass through raw reward (includes collateral damage penalties)
        return raw