File size: 10,752 Bytes
dc8501a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Submission inference script for the honest narrow incident environment."""

from __future__ import annotations

import json
import os
from typing import Any

from openai import OpenAI

from unified_incident_env.client import UnifiedIncidentEnv
from unified_incident_env.models import UnifiedIncidentAction, UnifiedIncidentObservation
from unified_incident_env.server.challenge import DEFAULT_SCENARIO_ID, SCENARIOS

API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct:novita")
HF_TOKEN = os.getenv("HF_TOKEN")
ENV_BASE_URL = os.getenv("ENV_BASE_URL") or UnifiedIncidentEnv.DEFAULT_BASE_URL
ENV_NAME = "unified-incident-env"
MAX_TOKENS = 260


def create_client() -> OpenAI | None:
    if not HF_TOKEN:
        return None
    return OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)


def log_start(*, task: str, env: str, model: str) -> None:
    print(f"[START] task={task} env={env} model={model}", flush=True)


def log_step(*, step: int, action: str, reward: float, done: bool, error: str | None) -> None:
    print(
        f"[STEP] step={step} action={action} reward={reward:.2f} done={str(done).lower()} error={error or 'null'}",
        flush=True,
    )


def log_end(*, success: bool, steps: int, score: float, rewards: list[float]) -> None:
    rewards_text = ",".join(f"{reward:.2f}" for reward in rewards)
    print(f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={rewards_text}", flush=True)


def _service_order(observation: UnifiedIncidentObservation) -> list[str]:
    services = list(observation.service_health.items())
    services.sort(key=lambda item: (item[1].status != "crashed", item[1].status != "degraded", -item[1].error_rate_pct))
    return [name for name, _payload in services]


def _default_action_for_type(action_type: str, observation: UnifiedIncidentObservation) -> dict[str, Any]:
    services = _service_order(observation)
    service = services[0] if services else "database"
    if action_type in {"query_logs", "query_dependencies", "query_deploys", "rollback_deploy", "restart_service", "isolate_service"}:
        if action_type == "rollback_deploy":
            service = "worker"
        return {"action_type": action_type, "service": service}
    if action_type == "query_metrics":
        return {"action_type": action_type, "service": service, "metric": "cpu"}
    if action_type == "run_check":
        check_name = "database_recovery"
        if observation.service_health.get("database") and observation.service_health["database"].status == "healthy":
            check_name = "end_to_end"
        return {"action_type": action_type, "check_name": check_name}
    if action_type == "submit_hypothesis":
        return {
            "action_type": "submit_hypothesis",
            "hypothesis": {
                "root_cause": "bad_worker_deploy",
                "affected_services": ["worker", "database"],
                "confidence": 0.5,
                "recommended_next_action": "query_deploys",
            },
        }
    return {"action_type": action_type}


def parse_action(raw: str, observation: UnifiedIncidentObservation) -> UnifiedIncidentAction | None:
    text = raw.strip()
    if not text:
        return None
    try:
        data = json.loads(text)
    except Exception:
        return None
    if not isinstance(data, dict):
        return None
    if "action" in data and "action_type" not in data and isinstance(data["action"], str):
        data = {**data, "action_type": data["action"]}
        data.pop("action", None)
    action_type = data.get("action_type")
    if action_type not in observation.allowed_actions:
        return None
    try:
        return UnifiedIncidentAction(**data)
    except Exception:
        return None


def build_user_prompt(observation: UnifiedIncidentObservation) -> str:
    required_lines = []
    for action, fields in observation.required_fields_by_action.items():
        required_lines.append(f"- {action}: {', '.join(fields) if fields else '(no extra fields)'}")
    checks = "\n".join(
        f"- {check.name}: {'passed' if check.passed else 'pending'} - {check.detail}"
        for check in observation.checks
    ) or "- none"
    return (
        "Return exactly one JSON object representing the next action.\n"
        f"Current stage: {observation.workflow_stage}\n"
        f"Incident summary: {observation.incident_summary}\n"
        f"Current score: {observation.final_score:.4f}\n"
        f"Last action result: {observation.last_action_result or 'none'}\n"
        f"Tool output: {observation.tool_output or 'none'}\n"
        f"Failure: {observation.failure_type or 'none'}\n"
        f"Why failed: {observation.why_failed or 'none'}\n"
        f"User impact: {observation.user_impact:.2f}\n"
        f"SLO burn rate: {observation.slo_burn_rate:.2f}\n"
        "Allowed actions:\n"
        + "\n".join(f"- {action}" for action in observation.allowed_actions)
        + "\nRequired fields:\n"
        + "\n".join(required_lines)
        + "\nChecks:\n"
        + checks
    )


def _schema(observation: UnifiedIncidentObservation) -> dict[str, Any]:
    properties: dict[str, Any] = {
        "action_type": {"type": "string", "enum": observation.allowed_actions},
        "service": {"type": "string", "enum": sorted(observation.service_health)},
        "metric": {"type": "string", "enum": ["cpu", "error_rate", "latency"]},
        "check_name": {"type": "string", "enum": ["database_recovery", "end_to_end"]},
        "hypothesis": {
            "type": "object",
            "properties": {
                "root_cause": {"type": "string", "enum": ["bad_worker_deploy", "database_only_failure", "api_gateway_fault"]},
                "affected_services": {
                    "type": "array",
                    "items": {"type": "string", "enum": sorted(observation.service_health)},
                    "minItems": 1,
                },
                "confidence": {"type": "number", "minimum": 0.0, "maximum": 1.0},
                "recommended_next_action": {
                    "type": "string",
                    "enum": [
                        "query_logs",
                        "query_metrics",
                        "query_dependencies",
                        "query_deploys",
                        "rollback_deploy",
                        "restart_service",
                        "run_check",
                        "isolate_service",
                        "escalate",
                        "declare_resolved",
                    ],
                },
            },
            "required": ["root_cause", "affected_services", "confidence", "recommended_next_action"],
            "additionalProperties": False,
        },
    }
    required = ["action_type"]
    for action, fields in observation.required_fields_by_action.items():
        if action in observation.allowed_actions:
            for field in fields:
                if field not in required:
                    required.append(field)
    return {
        "type": "object",
        "properties": properties,
        "required": required,
        "additionalProperties": False,
    }


def request_action(client: OpenAI, observation: UnifiedIncidentObservation) -> str:
    completion = client.chat.completions.create(
        model=MODEL_NAME,
        messages=[
            {"role": "system", "content": "You are an incident responder. Respond with JSON only."},
            {"role": "user", "content": build_user_prompt(observation)},
        ],
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "incident_action",
                "strict": True,
                "schema": _schema(observation),
            },
        },
        max_tokens=MAX_TOKENS,
        temperature=0.0,
    )
    return (completion.choices[0].message.content or "").strip()


def build_fallback_action(observation: UnifiedIncidentObservation) -> UnifiedIncidentAction:
    services = _service_order(observation)
    if "query_deploys" in observation.allowed_actions and "worker" in observation.service_health:
        return UnifiedIncidentAction(action_type="query_deploys", service="worker")
    if "query_logs" in observation.allowed_actions:
        return UnifiedIncidentAction(action_type="query_logs", service=services[0] if services else "database")
    if "query_metrics" in observation.allowed_actions:
        return UnifiedIncidentAction(action_type="query_metrics", service=services[0] if services else "database", metric="cpu")
    action_type = observation.allowed_actions[0]
    return UnifiedIncidentAction(**_default_action_for_type(action_type, observation))


def get_model_action(client: OpenAI | None, observation: UnifiedIncidentObservation) -> tuple[UnifiedIncidentAction, str | None]:
    if client is None:
        return build_fallback_action(observation), "model_unavailable"
    try:
        parsed = parse_action(request_action(client, observation), observation)
        if parsed is not None:
            return parsed, None
    except Exception:
        pass
    return build_fallback_action(observation), "fallback_used"


def run_scenario(client: OpenAI | None, scenario_id: str) -> dict[str, Any]:
    with UnifiedIncidentEnv(base_url=ENV_BASE_URL).sync() as env:
        observation = env.reset(scenario_id=scenario_id).observation
        rewards: list[float] = []
        step = 0
        log_start(task=scenario_id, env=ENV_NAME, model=MODEL_NAME)
        while not observation.done:
            step += 1
            action, error = get_model_action(client, observation)
            result = env.step(action)
            observation = result.observation
            rewards.append(float(result.reward))
            log_step(
                step=step,
                action=json.dumps(action.model_dump(exclude_none=True), separators=(",", ":")),
                reward=float(result.reward),
                done=bool(result.done),
                error=error or observation.failure_type,
            )
        log_end(
            success=bool(observation.done and observation.incident_resolved),
            steps=step,
            score=observation.final_score,
            rewards=rewards,
        )
        return {
            "success": bool(observation.done and observation.incident_resolved),
            "score": observation.final_score,
            "steps": step,
            "rewards": rewards,
        }


def main() -> None:
    client = create_client()
    for scenario_id in SCENARIOS:
        run_scenario(client, scenario_id)


if __name__ == "__main__":
    main()