Download faisi/src/sandbox/query_tools.py from ppJustin/micro: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/datasets/ppJustin/micro/resolve/main/faisi/src/sandbox/query_tools.py
- Command line
-
hf download hf://datasets/ppJustin/micro/faisi/src/sandbox/query_tools.py
-
curl -L -o query_tools.py https://huggingface.co/datasets/ppJustin/micro/resolve/main/faisi/src/sandbox/query_tools.py
15.3 kB
| """Deterministic JSON tool dispatcher. All public values are anonymized.""" | |
| from collections import defaultdict, deque | |
| import json | |
| from pathlib import Path | |
| from tokenizers import Tokenizer | |
| from .id_mapper import IdMapper | |
| from .snapshot import CASE_ID, DATASETS, GROUPS, Window, load_snapshot, rounded | |
| TOKEN_LIMIT = 400 | |
| METRIC_FIELDS = ["median_base", "mean_detect", "robust_z", "anomaly_count", "onset_offset_sec"] | |
| OVERVIEW_FIELDS = [ | |
| "entity_id", "layer", "in_degree_quantile", "out_degree_quantile", | |
| "multi_tenant_host", "metric_group", "robust_z", | |
| ] | |
| NEIGHBOR_KEYS = ("upstream", "downstream", "services", "instances", "hosts", "co_located_entities") | |
| EDGE_FIELDS = ( | |
| "baseline_call_count", "detection_call_count", "call_volume_change_rate", | |
| "baseline_error_rate", "detection_error_rate", "error_rate_change", | |
| "caller_p99_ms", "callee_p99_ms", "span_gap_ms", "onset_offset_sec", | |
| ) | |
| EVENT_FIELDS = ["event_template", "count", "first_offset_sec", "sample_message", "evidence_id"] | |
| def json_text(value): | |
| """Canonical compact serialization for the API token budget.""" | |
| return json.dumps(value, separators=(",", ":"), ensure_ascii=False, allow_nan=False) | |
| def error(code): | |
| return {"error": code} | |
| def structure(entity): | |
| return { | |
| "layer": entity.layer, "in_degree_quantile": entity.in_rank, | |
| "out_degree_quantile": entity.out_rank, "multi_tenant_host": entity.multi_tenant, | |
| } | |
| class TokenBudget: | |
| __slots__ = ("__tokenizer",) | |
| def __init__(self, tokenizer_path): | |
| self.__tokenizer = Tokenizer.from_file(str(tokenizer_path)) | |
| def count(self, result): | |
| return len(self.__tokenizer.encode(json_text(result), add_special_tokens=False).ids) | |
| def checked(self, result): | |
| return result if self.count(result) <= TOKEN_LIMIT else error("response_budget_exceeded") | |
| def fit(self, make, size): | |
| """Select the largest tested prefix that is within the measured budget.""" | |
| current = make(size) | |
| if self.count(current) <= TOKEN_LIMIT: | |
| return current | |
| lo, hi = 0, size - 1 | |
| best = make(0) | |
| while lo <= hi: | |
| middle = (lo + hi) // 2 | |
| candidate = make(middle) | |
| if self.count(candidate) <= TOKEN_LIMIT: | |
| best, lo = candidate, middle + 1 | |
| else: | |
| hi = middle - 1 | |
| return self.checked(best) | |
| class Sandbox: | |
| """Trusted factory. Paths, selectors and seeds are outside the tool surface.""" | |
| __slots__ = ("__root", "__windows", "__budget") | |
| def __init__(self, snapshot_root, window_index, tokenizer_path): | |
| self.__root = Path(snapshot_root).resolve() | |
| data = json.loads(Path(window_index).read_bytes()) | |
| if data.get("version") != 1: | |
| raise ValueError("unsupported_window_index") | |
| self.__windows = data["windows"] | |
| self.__budget = TokenBudget(tokenizer_path) | |
| def open_session(self, dataset, case_id, session_seed): | |
| if dataset not in DATASETS or not isinstance(case_id, str) or not CASE_ID.fullmatch(case_id): | |
| raise ValueError("invalid_case_selector") | |
| try: | |
| window = Window.from_values(self.__windows[dataset][case_id]) | |
| snapshot = load_snapshot(self.__root, dataset, case_id, window) | |
| except (KeyError, OSError, ValueError) as exc: | |
| raise ValueError("snapshot_unavailable") from exc | |
| return SandboxSession(snapshot, session_seed, self.__budget) | |
| class SandboxSession: | |
| """Immutable observations with a private per-session ID permutation.""" | |
| __slots__ = ("__snapshot", "__mapper", "__budget", "__evidence_ids") | |
| def __init__(self, snapshot, seed, budget): | |
| self.__snapshot = snapshot | |
| self.__budget = budget | |
| self.__mapper = IdMapper({name: row.layer for name, row in snapshot.entities.items()}, seed, snapshot.key) | |
| known = {self.__mapper._evidence("overview")} | |
| for real in snapshot.entities: | |
| anon = self.__mapper._mask(real) | |
| known.update(self.__mapper._evidence(kind, anon) for kind in ("topology", "metrics")) | |
| known.update(self.__mapper._evidence("event", anon, str(i)) | |
| for i in range(min(15, len(snapshot.events.get(real, ()))))) | |
| for caller, callee in snapshot.edges: | |
| if caller in snapshot.entities and callee in snapshot.entities: | |
| known.add(self.__mapper._evidence("edge", self.__mapper._mask(caller), self.__mapper._mask(callee))) | |
| self.__evidence_ids = frozenset(known) | |
| def call(self, tool_name, arguments=None): | |
| if type(tool_name) is not str or tool_name not in TOOL_NAMES: | |
| return error("unknown_tool") | |
| if arguments is not None and type(arguments) is not dict: | |
| return error("invalid_arguments") | |
| try: | |
| return getattr(self, tool_name)(**(arguments or {})) | |
| except TypeError: | |
| return error("invalid_arguments") | |
| def get_initial_symptom_overview(self) -> dict: | |
| d = self.__snapshot | |
| mapper = self.__mapper | |
| rows = sorted(((-z, real, group) for real, (group, z) in d.peak.items() | |
| if z >= 3 and real in d.entities)) | |
| anomalies = [] | |
| for z, real, group in rows[:6]: | |
| entity = d.entities[real] | |
| anomalies.append([mapper._mask(real), entity.layer, entity.in_rank, entity.out_rank, | |
| entity.multi_tenant, group, rounded(-z)]) | |
| graph = dict(zip(("services", "instances", "hosts", "call_edges", "own_edges", "host_edges"), | |
| d.dimensions)) | |
| return self.__budget.fit(lambda n: { | |
| "fields": OVERVIEW_FIELDS.copy(), "anomalies": anomalies[:n], | |
| "anomaly_count": len(rows), "omitted": len(rows)-n, "graph": graph, | |
| "evidence_id": mapper._evidence("overview"), | |
| }, len(anomalies)) | |
| def __walk(self, roots, graph, hops): | |
| visited = set(roots) | |
| frontier = set(roots) | |
| for _ in range(hops): | |
| frontier = set().union(*(graph.get(name, ()) for name in frontier)) - visited | |
| visited.update(frontier) | |
| return visited - roots | |
| def __rank_neighbors(self, nodes): | |
| peaks = self.__snapshot.peak | |
| order = sorted(nodes, key=lambda name: (-peaks.get(name, (None, float("-inf")))[1], name)) | |
| return [[self.__mapper._mask(name), rounded(peaks[name][1]) if name in peaks else None] | |
| for name in order] | |
| def get_topology_neighbors(self, entity_id: str, hop: int = 1) -> dict: | |
| real = self.__mapper._resolve(entity_id) | |
| if real is None: | |
| return error("invalid_entity_id") | |
| if type(hop) is not int or hop not in (1, 2): | |
| return error("invalid_hop") | |
| d = self.__snapshot | |
| node = d.entities[real] | |
| roots = {real} | |
| if node.parent is not None: | |
| roots.add(node.parent) | |
| instances = {n for n in d.belongs.get(real, ()) if d.entities[n].layer == "instance"} | |
| services = {node.parent} if node.parent else set() | |
| hosts = {node.host} if node.host else set() | |
| if node.layer == "host": | |
| residents = d.hosted.get(real, ()) | |
| instances.update(n for n in residents if d.entities[n].layer == "instance") | |
| services.update(d.entities[n].parent or n for n in residents | |
| if d.entities[n].parent or d.entities[n].layer == "service") | |
| else: | |
| hosts.update(d.entities[n].host for n in instances if d.entities[n].host) | |
| co_located = {n for host in hosts for n in d.hosted.get(host, ()) | |
| if n != real and d.entities[n].layer == "instance"} | |
| groups = dict(zip(NEIGHBOR_KEYS, ( | |
| self.__walk(roots, d.incoming, hop), self.__walk(roots, d.outgoing, hop), | |
| services, instances, hosts, co_located, | |
| ))) | |
| ranked = {key: self.__rank_neighbors(group) for key, group in groups.items()} | |
| order = [(key, rows[rank]) for rank in range(12) | |
| for key, rows in ranked.items() if rank < len(rows)][:12] | |
| def candidate(n): | |
| output = {key: [] for key in NEIGHBOR_KEYS} | |
| for key, row in order[:n]: | |
| output[key].append(row) | |
| omitted = {key: len(ranked[key]) - len(output[key]) for key in NEIGHBOR_KEYS | |
| if len(ranked[key]) != len(output[key])} | |
| return {"entity_id": entity_id, "hop": hop, "structure": structure(node), | |
| "fields": ["entity_id", "highest_robust_z"], **output, | |
| "omitted": omitted, "evidence_id": self.__mapper._evidence("topology", entity_id)} | |
| return self.__budget.fit(candidate, len(order)) | |
| def query_entity_metrics(self, entity_id: str) -> dict: | |
| real = self.__mapper._resolve(entity_id) | |
| if real is None: | |
| return error("invalid_entity_id") | |
| values = self.__snapshot.metrics.get(real, {}) | |
| slots = {group: list(values[group]) if group in values else None for group in GROUPS} | |
| return self.__budget.checked({ | |
| "entity_id": entity_id, "fields": METRIC_FIELDS.copy(), "slots": slots, | |
| "evidence_id": self.__mapper._evidence("metrics", entity_id), | |
| }) | |
| def query_call_edge_detail(self, caller_id: str, callee_id: str) -> dict: | |
| caller, callee = self.__mapper._resolve(caller_id), self.__mapper._resolve(callee_id) | |
| if caller is None or callee is None: | |
| return error("invalid_entity_id") | |
| values = self.__snapshot.edges.get((caller, callee)) | |
| if values is None: | |
| return error("call_edge_not_found") | |
| return self.__budget.checked({ | |
| "caller_id": caller_id, "callee_id": callee_id, **dict(zip(EDGE_FIELDS, values)), | |
| "evidence_id": self.__mapper._evidence("edge", caller_id, callee_id), | |
| }) | |
| def query_entity_events(self, entity_id: str, top_k: int = 5) -> dict: | |
| real = self.__mapper._resolve(entity_id) | |
| if real is None: | |
| return error("invalid_entity_id") | |
| if type(top_k) is not int or top_k < 1: | |
| return error("invalid_top_k") | |
| events = self.__snapshot.events.get(real, ()) | |
| mapper = self.__mapper | |
| selected = [[mapper._visible_text(template, max_chars=95), count, first, | |
| mapper._visible_text(sample), mapper._evidence("event", entity_id, str(i))] | |
| for i, (template, sample, count, first) in enumerate(events[:min(15, top_k)])] | |
| return self.__budget.fit(lambda n: { | |
| "entity_id": entity_id, "fields": EVENT_FIELDS.copy(), "events": selected[:n], | |
| "template_count": len(events), "omitted": len(events)-n, | |
| }, len(selected)) | |
| def submit_diagnosis(self, root_entity_id: str, fault_category: str, | |
| propagation_path: list[list[str]], key_evidence_ids: list[str]) -> dict: | |
| if self.__mapper._resolve(root_entity_id) is None: | |
| return error("invalid_entity_id") | |
| if (type(fault_category) is not str or len(fault_category) > 80 or not fault_category.strip() | |
| or any(not c.isprintable() for c in fault_category)): | |
| return error("invalid_fault_category") | |
| if type(propagation_path) is not list or len(propagation_path) > 80: | |
| return error("invalid_propagation_path") | |
| edges = set() | |
| for pair in propagation_path: | |
| if type(pair) is not list or len(pair) != 2 or any( | |
| self.__mapper._resolve(item) is None for item in pair | |
| ) or pair[0] == pair[1]: | |
| return error("invalid_propagation_path") | |
| edges.add(tuple(pair)) | |
| if len(edges) != len(propagation_path) or not rooted_dag(root_entity_id, edges): | |
| return error("invalid_propagation_path") | |
| if type(key_evidence_ids) is not list or len(key_evidence_ids) > 40 or any( | |
| type(item) is not str or item not in self.__evidence_ids for item in key_evidence_ids | |
| ) or len(set(key_evidence_ids)) != len(key_evidence_ids): | |
| return error("invalid_evidence_ids") | |
| return {"status": "accepted", "terminal": True, "root_entity_id": root_entity_id, | |
| "path_edge_count": len(edges), "evidence_count": len(key_evidence_ids)} | |
| def rooted_dag(root, edges): | |
| if not edges: | |
| return True | |
| outgoing = defaultdict(set) | |
| indegree = {root: 0} | |
| for src, dst in edges: | |
| outgoing[src].add(dst) | |
| indegree.setdefault(src, 0) | |
| indegree[dst] = indegree.get(dst, 0) + 1 | |
| if indegree[root]: | |
| return False | |
| pending = deque([root]) | |
| visited = 0 | |
| while pending: | |
| node = pending.popleft() | |
| visited += 1 | |
| for dest in outgoing[node]: | |
| indegree[dest] -= 1 | |
| if indegree[dest] == 0: | |
| pending.append(dest) | |
| return visited == len(indegree) | |
| def make_schema(name, description, properties, required=None): | |
| return {"type": "function", "function": { | |
| "name": name, "description": description, | |
| "parameters": {"type": "object", "properties": properties, | |
| "required": list(properties) if required is None else required, | |
| "additionalProperties": False}, | |
| "strict": False, | |
| }} | |
| def entity_schema(): | |
| return {"type": "string", "pattern": r"^(SVC|INST|HOST)_[0-9]{2,}$"} | |
| TOOLS = [ | |
| make_schema("get_initial_symptom_overview", | |
| "Summarize anomalous anonymous entities and graph dimensions.", {}), | |
| make_schema("get_topology_neighbors", | |
| "Return ranked call and deployment neighbors within 1 or 2 hops.", | |
| {"entity_id": entity_schema(), "hop": {"type": "integer", "enum": [1, 2], "default": 1}}, | |
| required=["entity_id"]), | |
| make_schema("query_entity_metrics", "Return nine normalized metric slots with baseline, detection and anomaly summaries.", | |
| {"entity_id": entity_schema()}), | |
| make_schema("query_call_edge_detail", "Return baseline/detection call statistics for one directed observed edge.", | |
| {"caller_id": entity_schema(), "callee_id": entity_schema()}), | |
| make_schema("query_entity_events", "Return the highest-frequency sanitized event templates for one entity.", | |
| {"entity_id": entity_schema(), | |
| "top_k": {"type": "integer", "minimum": 1, "default": 5}}, | |
| required=["entity_id"]), | |
| make_schema("submit_diagnosis", "Submit the terminal anonymous diagnosis and supporting evidence IDs.", | |
| {"root_entity_id": entity_schema(), | |
| "fault_category": {"type": "string", "minLength": 1, "maxLength": 80}, | |
| "propagation_path": {"type": "array", "maxItems": 80, | |
| "items": {"type": "array", "minItems": 2, "maxItems": 2, | |
| "items": entity_schema()}}, | |
| "key_evidence_ids": {"type": "array", "maxItems": 40, | |
| "items": {"type": "string", "pattern": r"^EV_[0-9a-f]{12}$"}}}), | |
| ] | |
| TOOL_NAMES = frozenset(item["function"]["name"] for item in TOOLS) | |