File size: 14,258 Bytes
473de52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
"""Two frozen prompt-selection rounds and a train-dev-only mid-run refresh."""

import argparse
import asyncio
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
from pathlib import Path
import random
import re
import subprocess
import time

import httpx

SCHEMA = {
    "type": "object",
    "properties": {"text": {"type": "string"}},
    "required": ["text"],
    "additionalProperties": False,
}
CATEGORY = re.compile(
    r"(?i)(?:\b(?:case[-_][0-9a-f]{8,}|(?:SVC|INST|HOST)_\d+|EVID_[A-Z0-9]+|"
    r"openrca|trainticket|propagation_bench)\b|https?://|\b\d{1,3}(?:\.\d{1,3}){3}\b)"
)
COMMON_NOUNS = {"service", "host", "node", "instance"}
SYSTEM = """Write ONLY a general-purpose operational playbook for a diagnosis agent using anonymous tools.
Return JSON with one text field. Aim for 180 to 300 tokens; 400 is the hard limit.
Use only generic words for entities such as service, instance, and host. Never name real or anonymous
components, datasets, software products, cases, infrastructure addresses, or trace evidence IDs.
The observations below are examples from training cases. Extract general evidence-gathering
strategies and do not imitate identities, precise measurements, or example outcomes.
Use the six public tool names when useful. The call graph is not the fault propagation direction.
The agent has at most 20 normal turns; include a defensible way to finish with a rooted acyclic chain.
Prefer concrete decision rules about metrics, onset order, caller/callee evidence and rival explanations.
Keep the baseline tool and submission protocol intact. Never claim to know the hidden diagnosis.
"""
ANGLES = (
    "Prioritize detecting when the most severe alert is a downstream symptom.",
    "Prioritize confirming earliest observed anomalies while accounting for noisy onset signals.",
    "Prioritize cross-service edge evidence and latency attribution.",
    "Prioritize inspecting a small set of competing cause hypotheses efficiently.",
    "Prioritize distinguishing host, instance, and service effects through ownership and topology.",
    "Prioritize integrating metrics and event evidence with a short defensible propagation chain.",
)


def assemble(spec, index, attempt):
    rng = random.Random(42 + 1000 * spec["round"] + 17 * index + attempt)
    sample = rng.sample(spec["examples"], min(2, len(spec["examples"])))
    paragraphs = [ANGLES[index]]
    if spec["incumbent"]:
        paragraphs.extend(
            (
                "Revise this current playbook using the evidence below.",
                spec["incumbent"],
            )
        )
    if attempt:
        paragraphs.append(
            "Use plain generic nouns and short sentences. Remove all names or identifier-like examples."
        )
    paragraphs.append(json.dumps(sample, separators=(",", ":")))
    return "\n".join(paragraphs)


async def generate(model_name, round_dir, attempt, indexes):
    if any(
        Path(p).exists()
        for p in (
            "/data/snapshots",
            "/data/vault",
            "/data/train_roots.json",
            "/verified",
        )
    ):
        raise ValueError("unexpected_synthesis_mounts")
    spec = json.loads(Path("/state/data/evolution.json").read_bytes())
    transport = httpx.AsyncHTTPTransport(uds="/model_server.sock")
    async with httpx.AsyncClient(
        transport=transport, base_url="http://local", timeout=180
    ) as client:

        async def one(index):
            payload = {
                "model": model_name,
                "messages": [
                    {"role": "system", "content": SYSTEM},
                    {"role": "user", "content": assemble(spec, index, attempt)},
                ],
                "temperature": 0.7,
                "top_p": 0.95,
                "top_k": 20,
                "repetition_penalty": 1.05,
                "max_tokens": 640,
                "seed": 42000 + 100 * spec["round"] + 10 * attempt + index,
                "response_format": {
                    "type": "json_schema",
                    "json_schema": {
                        "name": "playbook",
                        "strict": True,
                        "schema": SCHEMA,
                    },
                },
            }
            response = (
                (await client.post("/v1/chat/completions", json=payload))
                .raise_for_status()
                .json()
            )
            choice = response["choices"][0]
            text = None
            if choice["finish_reason"] == "stop":
                try:
                    text = json.loads(choice["message"]["content"])["text"]
                except (json.JSONDecodeError, KeyError, TypeError):
                    pass
            (round_dir / f"draft-{index}.json").write_text(
                json.dumps(
                    {
                        "text": text,
                        "finish": choice["finish_reason"],
                        "seed": payload["seed"],
                    }
                )
                + "\n"
            )

        await asyncio.gather(*(one(i) for i in indexes))


def check_text(text, names, tokenizers):
    if not isinstance(text, str) or not text.strip() or CATEGORY.search(text):
        return None
    if any(not ch.isprintable() and ch not in "\n\t" for ch in text):
        return None
    normalized = text.casefold()

    # Require token boundaries so a known short entity does not match a longer word.
    def found(name):
        return name in normalized and re.search(
            r"(?<![\w/-])" + re.escape(name) + r"(?![\w/-])", normalized
        )

    if any(found(name) for name in names if name not in COMMON_NOUNS):
        return None
    counts = [len(t.encode(text, add_special_tokens=False).ids) for t in tokenizers]
    return max(counts) if 1 <= max(counts) <= 400 else None


def score_dev(stage, expected):
    rows = [
        json.loads(l)
        for l in (stage / "trainhome/episodes.jsonl").read_bytes().splitlines()
    ]
    inventory = {(r["dataset"], r["case_id"]) for r in rows}
    if (
        inventory != expected
        or len(rows) != len(expected)
        or any(r["phase"] != "train" or r["seed"] != 42 for r in rows)
    ):
        raise ValueError("wrong_dev_cohort")
    return sum(r["root_hit"] for r in rows), rows


def refresh_examples(rows):
    from baselines.prepare import compact
    from checkers.context_api import TrajectoryContext

    bad = [r for r in rows if r["root_hit"] is False]
    good = [r for r in rows if r["root_hit"] is True]
    rng = random.Random(42)
    rng.shuffle(bad)
    rng.shuffle(good)
    if not bad:
        return [{"hit": compact(TrajectoryContext.from_trace(r))} for r in good[:12]]
    return [
        {
            "miss": compact(TrajectoryContext.from_trace(row)),
            **(
                {"hit": compact(TrajectoryContext.from_trace(good[i % len(good)]))}
                if good
                else {}
            ),
        }
        for i, row in enumerate(bad[:24])
    ]


def optimize(
    base, module, models_root, scorer_model, scorer_socket, coder_socket, phase
):
    from tokenizers import Tokenizer

    base = base.resolve(strict=True)
    expected = {
        tuple(case)
        for case in json.loads((base / "views/dev/allowlists.json").read_bytes())[
            "train"
        ]
    }
    private = base / "private"
    tokenizer = [
        Tokenizer.from_file(
            str(models_root / f"Qwen2.5-{size}-Instruct" / "tokenizer.json")
        )
        for size in ("7B", "14B")
    ]
    names = json.loads((private / "disallowed_entity_names.json").read_bytes())
    rounds = base / "prompt_rounds"
    rounds.mkdir(exist_ok=True)
    results = []
    winner_text = ""
    incumbent_hits = -1

    def evaluate(path, text):
        path.mkdir(parents=True, exist_ok=True)
        data = path / "data"
        data.mkdir(exist_ok=True)
        (data / "playbook.txt").write_text(text + "\n")
        log = path / "launcher.log"
        with log.open("w") as stream:
            subprocess.run(
                [
                    "bash",
                    str(module / "run_baseline.sh"),
                    str(base),
                    str(path),
                    str(scorer_model),
                    "dev",
                    str(scorer_socket),
                    "26" if phase == "refresh" else "0",
                    "--concurrency",
                    "48",
                ],
                stdout=stream,
                stderr=subprocess.STDOUT,
                check=True,
            )
        return score_dev(path, expected)

    if phase == "refresh":
        winner_text = (private / "playbook_p1.txt").read_text().strip()
        incumbent_hits, rows = evaluate(rounds / "refresh" / "incumbent", winner_text)
        samples = refresh_examples(rows)
        n_rounds = (3,)
    else:
        samples = json.loads((private / "induction.json").read_bytes())
        n_rounds = (1, 2)
    for index in n_rounds:
        stage = rounds / f"round{index}"
        stage.mkdir(exist_ok=True)
        (stage / "data").mkdir(exist_ok=True)
        (stage / "trainhome").mkdir(exist_ok=True)
        previous = incumbent_hits
        spec = {"round": index, "examples": samples, "incumbent": winner_text}
        (stage / "data/evolution.json").write_text(
            json.dumps(spec, separators=(",", ":"))
        )
        accepted = {}
        started = time.monotonic()
        for attempt in range(8):
            missing = [n for n in range(6) if n not in accepted]
            if not missing:
                break
            with (stage / "generation.log").open("a") as stream:
                subprocess.run(
                    [
                        "bash",
                        str(module / "generate_playbook.sh"),
                        str(stage),
                        str(coder_socket),
                        str(attempt),
                        *map(str, missing),
                    ],
                    stdout=stream,
                    stderr=subprocess.STDOUT,
                    check=True,
                )
            for n in missing:
                draft = json.loads((stage / f"trainhome/draft-{n}.json").read_bytes())
                text = draft["text"]
                if not isinstance(text, str):
                    continue
                text = text.strip()
                count = check_text(text, names, tokenizer)
                if count is not None and text not in {
                    entry["text"] for entry in accepted.values()
                }:
                    accepted[n] = {
                        "text": text,
                        "tokens": count,
                        "seed": draft["seed"],
                        "retry": attempt,
                    }
            print(
                json.dumps(
                    {"round": index, "validated_candidate_slots": len(accepted)}
                ),
                flush=True,
            )
        if len(accepted) != 6:
            raise ValueError("incomplete_sanitized_playbook_round")

        def evaluate_candidate(key):
            draft = accepted[key]
            hits, rows = evaluate(stage / f"candidate-{key}", draft["text"])
            return {
                "slot": key,
                "tokens": draft["tokens"],
                "seed": draft["seed"],
                "retry": draft["retry"],
                "dev_hits": hits,
                "invalid_count": sum(r["submission"] is None for r in rows),
                "sha256": hashlib.sha256((draft["text"] + "\n").encode()).hexdigest(),
            }

        with ThreadPoolExecutor(max_workers=2) as pool:
            stats = list(pool.map(evaluate_candidate, sorted(accepted)))
        best = max(stats, key=lambda r: (r["dev_hits"], -r["slot"]))
        selected = None
        if best["dev_hits"] > incumbent_hits:
            selected = best["slot"]
            incumbent_hits = best["dev_hits"]
            winner_text = accepted[selected]["text"]
        results.append(
            {
                "round": index,
                "dev_cases": 124,
                "incumbent_dev_hits": None if previous < 0 else previous,
                "candidates": stats,
                "winning_candidate_slot": selected,
                "selected_dev_hits": incumbent_hits,
                "elapsed_s": time.monotonic() - started,
            }
        )
        print(json.dumps(results[-1]), flush=True)
    output = "p2" if phase == "refresh" else "p1"
    (private / f"playbook_{output}.txt").write_text(winner_text + "\n")
    (base / f"{output}_selection.json").write_text(
        json.dumps(
            {
                "rounds": results,
                "token_count": check_text(winner_text, names, tokenizer),
                "dev_hits": incumbent_hits,
                "evolution_test_payloads_read": 0,
                "evolution_ground_truth_vault_reads": 0,
                "scope": "post_step26_dev_errors"
                if phase == "refresh"
                else "497 historical induction cases",
            },
            indent=2,
            allow_nan=False,
        )
        + "\n"
    )


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    sub = p.add_subparsers(dest="command", required=True)
    g = sub.add_parser("generate")
    g.add_argument("model_name")
    g.add_argument("attempt", type=int)
    g.add_argument("indexes", type=int, nargs="+")
    o = sub.add_parser("optimize")
    for name in (
        "base",
        "module",
        "models-root",
        "scorer-model",
        "scorer-socket",
        "coder-socket",
    ):
        o.add_argument("--" + name, type=Path, required=True)
    o.add_argument("--phase", choices=("frozen", "refresh"), required=True)
    a = p.parse_args()
    if a.command == "generate":
        asyncio.run(generate(a.model_name, Path("/state/train"), a.attempt, a.indexes))
    else:
        optimize(
            a.base,
            a.module.resolve(),
            a.models_root,
            a.scorer_model,
            a.scorer_socket,
            a.coder_socket,
            a.phase,
        )