File size: 16,401 Bytes
c5f5de4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
"""Stream anonymous tool interaction trajectories from two local vLLM endpoints."""
import argparse
import asyncio
from collections import defaultdict
from copy import deepcopy
from dataclasses import asdict
import fcntl
import hashlib
import json
from pathlib import Path
import re
import time

import httpx

from sandbox.query_tools import Sandbox, TOOLS, json_text
from .protocol import MAX_TURNS, MODELS, MODES, PORTS, load_plan, row_key, samples, trajectory_path

SYSTEM = """Diagnose a distributed-system fault from anonymized telemetry. Only use evidence in this session.
Call one tool at a time. Aim to finish in 3 to 6 evidence queries. Inspect a plausible root with metrics or events.
Use topology and relative onset times to distinguish cause and symptom. Query call edges only between known
caller and callee services in their observed direction. Never repeat the same query after an error.
Anomaly and metric rows are positional arrays defined by their fields. Missing data is not evidence.
Submit the single most likely root entity, a short generic fault category, and ordered directed edges
from cause to affected entity. Edges must form a DAG reachable from the root. Use [] if propagation
is unsupported. Copy evidence IDs exactly from tool responses, or use [] when none apply.
Fix tool errors promptly. If a path is rejected and you cannot repair it, resubmit with []. Submit once you have enough evidence."""
INITIAL = "Diagnose this case. Initial symptom overview follows."
FORCE = ("Submit your best diagnosis now using submit_diagnosis. Copy an observed entity ID. "
         "Give a short generic fault category. Give at most one directed edge starting at the root and at most one evidence ID. Use [] if unsupported.")
SUBMIT = "submit_diagnosis"
TOOL_NAMES = {tool["function"]["name"] for tool in TOOLS}
ANON = re.compile(r"(?:SVC|INST|HOST)_[0-9]{2,}\Z")
EVIDENCE = re.compile(r"EV_[0-9a-f]{12}\Z")
RETRYABLE_STATUS = {408, 429, 500, 502, 503, 504}


def identifiers(value, pattern):
    if isinstance(value, str):
        if pattern.fullmatch(value):
            yield value
    elif isinstance(value, dict):
        for subvalue in value.values():
            yield from identifiers(subvalue, pattern)
    elif isinstance(value, list):
        for subvalue in value:
            yield from identifiers(subvalue, pattern)


def forced_tool(observations, overview):
    tool = deepcopy(TOOLS[-1])
    base = tool["function"]["parameters"]
    queried = (row[key] for row in reversed(observations) for key in ("entity_id", "caller_id", "callee_id")
               if key in row)
    roots = list(dict.fromkeys([*identifiers(overview, ANON), *queried, *identifiers(observations, ANON)]))[:8]
    if not roots:
        roots = [f"{prefix}_01" for layer, prefix in (
            ("services", "SVC"), ("instances", "INST"), ("hosts", "HOST")
        ) if overview.get("graph", {}).get(layer, 0) > 0]

    evidence = list(dict.fromkeys(identifiers(observations[::-1], EVIDENCE)))[:12]
    if evidence:
        base["properties"]["key_evidence_ids"].update(
            {"maxItems": 1, "items": {"type": "string", "enum": evidence}}
        )
    else:
        base["properties"]["key_evidence_ids"]["maxItems"] = 0
    if not roots:
        return tool

    # The recovery round accepts zero or one observed edge anchored at the chosen root.
    links = defaultdict(set)
    for row in observations:
        if "caller_id" in row and "callee_id" in row:
            links[row["caller_id"]].add(row["callee_id"])
        entity = row.get("entity_id")
        if entity and "structure" in row:
            for key in ("downstream", "instances", "hosts", "services"):
                for item, _ in row.get(key, ()):
                    if item != entity:
                        links[entity].add(item)
            for item, _ in row.get("upstream", ()):
                if item != entity:
                    links[item].add(entity)

    variants = []
    for root in roots:
        variant = deepcopy(base)
        props = variant["properties"]
        props["root_entity_id"] = {"type": "string", "enum": [root]}
        targets = sorted(links[root])[:12]
        props["propagation_path"] = {"type": "array", "maxItems": int(bool(targets))}
        if targets:
            props["propagation_path"]["items"] = {
                "type": "array", "prefixItems": [
                    {"type": "string", "enum": [root]}, {"type": "string", "enum": targets},
                ], "minItems": 2, "maxItems": 2,
            }
        variants.append(variant)
    tool["function"]["parameters"] = {"anyOf": variants}
    return tool


def deterministic_seed(sample, turn):
    text = f"{sample.dataset}/{sample.case_id}/{sample.session_seed}/{turn}".encode()
    return int.from_bytes(hashlib.blake2s(text, digest_size=4).digest(), "big") & 0x7fffffff


def bounded_json(content):
    if not isinstance(content, str) or len(content) > 8192:
        return None
    def reject_constant(value):
        raise ValueError(value)
    try:
        value = json.loads(content, parse_constant=reject_constant)
        json_text(value)
    except (ValueError, OverflowError, RecursionError):
        return None
    return value if isinstance(value, dict) else None


def usage_counts(payload):
    usage = payload.get("usage") or {}
    cached = (usage.get("prompt_tokens_details") or {}).get("cached_tokens")
    return {
        "prompt_tokens": usage.get("prompt_tokens", 0),
        "completion_tokens": usage.get("completion_tokens", 0),
        "total_tokens": usage.get("total_tokens", 0),
        "cached_prompt_tokens": cached,
    }


async def completion(client, params):
    for attempt in range(3):
        try:
            response = await client.post("/v1/chat/completions", json=params)
            if response.status_code not in RETRYABLE_STATUS:
                response.raise_for_status()
                return response.json(), attempt
        except (httpx.TransportError, ValueError):
            pass
        await asyncio.sleep(0.25 * (2 ** attempt))
    raise RuntimeError("model_request_retries_exhausted")


def accepted(result):
    return result.get("status") == "accepted" and result.get("terminal") is True


async def rollout(client, sandbox, model, sample, plan_hash):
    started = time.perf_counter()
    session = await asyncio.to_thread(sandbox.open_session, sample.dataset, sample.case_id, sample.session_seed)
    overview = session.call("get_initial_symptom_overview", {})
    observations = [overview]
    messages = [{"role": "system", "content": SYSTEM},
                {"role": "user", "content": INITIAL + "\n" + json_text(overview)}]
    steps = []
    submission = None
    outcome = "turn_limit"
    failures = set()
    _, _, temperature, top_p = MODES[sample.mode]

    for turn in range(1, MAX_TURNS + 2):
        force = turn > MAX_TURNS
        if force:
            messages.append({"role": "user", "content": FORCE})
        params = {
            "model": model, "messages": messages,
            "tools": [forced_tool(observations, overview)] if force else TOOLS,
            "tool_choice": {"type": "function", "function": {"name": SUBMIT}} if force else "required",
            "parallel_tool_calls": False, "temperature": temperature, "top_p": top_p,
            "max_completion_tokens": 384, "seed": deterministic_seed(sample, turn),
        }
        try:
            payload, retries = await completion(client, params)
        except httpx.HTTPStatusError as exc:
            outcome = f"http_{exc.response.status_code}"
            break
        except RuntimeError:
            outcome = "transport_error"
            break
        choice = payload["choices"][0]
        calls = choice["message"].get("tool_calls") or []
        step = {"turn": turn, "forced": force, "usage": usage_counts(payload),
                "request_retries": retries, "finish_reason": choice.get("finish_reason"), "tool_calls": []}
        steps.append(step)
        if not calls:
            result = {"error": "tool_call_required"}
            step["tool_calls"].append({"name": None, "arguments": None, "result": result})
            messages.append({"role": "user", "content": json_text(result)})
            continue

        # Request one call, but always answer every tool-call ID emitted by the API.
        requests = []
        replies = []
        hints = []
        for index, call in enumerate(calls):
            function = call.get("function", {})
            name = function.get("name")
            arguments = bounded_json(function.get("arguments"))
            if submission:
                result = {"error": "session_already_submitted"}
            elif arguments is None:
                result = {"error": "invalid_arguments"}
            elif force and name != SUBMIT:
                result = {"error": "submit_diagnosis_required"}
            else:
                result = session.call(name, arguments)
            if "error" not in result:
                observations.append(result)
            if name == SUBMIT and accepted(result):
                submission = arguments
                outcome = "accepted"
            call_id = f"call_{turn}_{index}"
            requests.append({"id": call_id, "type": "function", "function": {
                "name": name if name in TOOL_NAMES else "unknown_tool",
                "arguments": json_text(arguments) if arguments is not None else "{}"}})
            replies.append({"role": "tool", "tool_call_id": call_id, "content": json_text(result)})
            step["tool_calls"].append({"name": name, "arguments": arguments, "result": result})
            if not force and "error" in result:
                key = (name, json_text(arguments))
                repeated = key in failures
                failures.add(key)
                if result["error"] == "invalid_propagation_path":
                    hints.append("The first edge must start at the submitted root. Use [] if no directed chain is verified.")
                elif repeated:
                    hints.append("This tool call already failed with these arguments. Choose a different query or submit.")
        messages.append({"role": "assistant", "content": None, "tool_calls": requests})
        messages.extend(replies)
        if hints and not submission:
            step["controller_hint"] = " ".join(dict.fromkeys(hints))
            messages.append({"role": "user", "content": step["controller_hint"]})
        if submission:
            break

    return {
        "schema_version": 1, "model": model, **asdict(sample), "session_seed": sample.session_seed,
        "worklist_sha256": plan_hash, "initial_observation": {
            "turn": 0, "name": "get_initial_symptom_overview", "arguments": {}, "result": overview,
            "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0},
        },
        "turns": steps, "num_turns": len(steps), "submission": submission, "termination": outcome,
        "elapsed_s": round(time.perf_counter() - started, 6),
    }


class JsonlWriter:
    def __init__(self, path):
        self.path = path

    def __enter__(self):
        self.stream = self.path.open("a+b")
        try:
            fcntl.flock(self.stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            self.stream.close()
            raise
        return self

    def __exit__(self, *exc):
        self.stream.close()

    def existing_keys(self, model, expected, plan_hash):
        done = set()
        self.stream.seek(0)
        while True:
            offset = self.stream.tell()
            line = self.stream.readline()
            if not line:
                return done
            if not line.endswith(b"\n"):
                self.stream.truncate(offset)
                print(json_text({"recovered_partial_tail": self.path.name}), flush=True)
                return done
            item = json.loads(line)
            key = row_key(item)
            if (item["schema_version"] != 1 or item["model"] != model or key not in expected
                    or key in done or item["worklist_sha256"] != plan_hash):
                raise ValueError("invalid_existing_trajectory")
            done.add(key)

    def append(self, row):
        self.stream.write((json_text(row) + "\n").encode())
        self.stream.flush()


def assert_no_vault():
    if Path("/data/vault").exists() or Path("/proc/1/root").exists():
        raise RuntimeError("runner_isolation_required")


async def run_model(model, args, plan, plan_hash, sandbox):
    batches = [samples(plan, mode, args.smoke) for mode in MODES]
    expected = set(sum(batches, []))
    completed = 0
    t0 = time.perf_counter()
    metrics = {"model": model, "cohorts": [], "parallel_models": len(args.models)}
    with JsonlWriter(trajectory_path(args.output, model, args.smoke)) as writer:
        done = writer.existing_keys(model, expected, plan_hash)
        completed = len(done)
        async with httpx.AsyncClient(
            base_url=f"http://127.0.0.1:{PORTS[model]}", trust_env=False, timeout=httpx.Timeout(180.0),
            limits=httpx.Limits(max_connections=args.concurrency, max_keepalive_connections=args.concurrency),
        ) as client:
            await wait_for_model(client)
            for batch in batches:
                mode = batch[0].mode
                size = 100 * MODES[mode][0]
                for start in range(0, len(batch), size):
                    section = batch[start:start+size]
                    pending = iter(item for item in section if item not in done)
                    cohort_started = time.perf_counter()
                    before = completed
                    bad = 0

                    async def worker():
                        nonlocal completed, bad
                        for item in pending:
                            row = await rollout(client, sandbox, model, item, plan_hash)
                            writer.append(row)
                            completed += 1
                            bad += row["termination"] != "accepted"
                            if completed % 32 == 0:
                                print(json_text({"model": model, "mode": mode, "completed": completed,
                                                 "total": len(expected), "cohort_invalid": bad,
                                                 "elapsed_s": round(time.perf_counter()-t0, 1)}), flush=True)

                    await asyncio.gather(*(worker() for _ in range(min(args.concurrency, len(section)))))
                    entry = {"model": model, "mode": mode, "cohort": start//size,
                             "planned": len(section), "new_trajectories": completed-before,
                             "invalid": bad, "elapsed_s": round(time.perf_counter()-cohort_started, 6)}
                    print(json_text(entry), flush=True)
                    if entry["new_trajectories"]:
                        metrics["cohorts"].append(entry)
    metrics["run_wall_s"] = round(time.perf_counter()-t0, 3)
    metrics["total_rows"] = completed
    metrics["worklist_sha256"] = plan_hash
    timing = args.output / f"{'smoke-' if args.smoke else ''}{model}.timing.jsonl"
    with timing.open("a", encoding="utf-8") as stream:
        stream.write(json_text(metrics) + "\n")


async def wait_for_model(client):
    response = await client.get("/health", timeout=5.0)
    response.raise_for_status()


async def run(args):
    assert_no_vault()
    plan, plan_hash = load_plan("/data/worklist.json")
    sandbox = Sandbox("/data/snapshots", "/data/windows.json", "/data/tokenizer.json")
    await asyncio.gather(*(run_model(model, args, plan, plan_hash, sandbox) for model in args.models))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--models", nargs="+", choices=MODELS, default=list(MODELS))
    parser.add_argument("--concurrency", type=int, default=128, help="Concurrent sessions per model")
    parser.add_argument("--output", type=Path, default=Path("/output"))
    parser.add_argument("--smoke", action="store_true")
    args = parser.parse_args()
    if args.concurrency < 1 or len(args.models) != len(set(args.models)):
        parser.error("Use positive concurrency and distinct model names")
    asyncio.run(run(args))


if __name__ == "__main__":
    main()