micro / faisi /src /runner /rollout_engine.py
ppJustin's picture
Add files using upload-large-folder tool
c5f5de4 verified
Raw History Blame Contribute Delete
16.4 kB
"""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()