File size: 15,859 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
"""Source-specific projections. Runtime inputs are selected from telemetry only."""
from collections import defaultdict
import csv
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import hashlib
import json
from pathlib import Path
import re
import xml.etree.ElementTree as ET
from zipfile import ZipFile

V1_SYSTEMS = ("Bank", "Market/cloudbed-1", "Market/cloudbed-2", "Telecom")
LOCAL_TZ = timezone(timedelta(hours=8))
PACK_KINDS = ("metrics", "metrics_sum", "metrics_histogram", "traces", "logs")
INPUT_STAGES = ("normal", "abnormal")
PACK_STEMS = tuple(f"{stage}_{kind}" for stage in INPUT_STAGES for kind in PACK_KINDS)


@dataclass(frozen=True)
class Case:
    case_id: str
    start: float
    boundary: float
    end: float
    truth: dict


@dataclass(frozen=True)
class Batch:
    key: str
    source: str
    systems: str
    cases: tuple[Case, ...]
    files: tuple[Path, ...]
    deployment: dict | None = None
    postmortem: Path | None = None


def case_id(dataset, key):
    return "case-" + hashlib.sha256(f"{dataset}/{key}".encode()).hexdigest()[:24]


def epoch(value):
    try:
        stamp = float(value)
        if abs(stamp) >= 1e17:
            return stamp / 1e9
        if abs(stamp) >= 1e14:
            return stamp / 1e6
        if abs(stamp) >= 1e11:
            return stamp / 1e3
        return stamp
    except (TypeError, ValueError):
        text = str(value).replace("Z", "+00:00")
        # Python 3.10 accepts three or six fractional digits only.
        text = re.sub(r"\.(\d+)", lambda match: "." + match.group(1).ljust(6, "0")[:6], text, count=1)
        dt = datetime.fromisoformat(text)
        return (dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)).timestamp()


def item(case, system, t0, roots, category, path, coverage=None):
    start, boundary, end = t0 - 1800, t0 - 300, t0 + 300
    if coverage is not None:
        lower, upper = coverage
        if not lower < upper:
            raise ValueError("Invalid observation window")
        start, end = max(start, lower), min(end, upper)
        if end <= start:
            raise ValueError("Case window does not intersect observations")
        if end - start < 2100:
            if upper - lower < 2100:
                start, end = lower, upper
            boundary = start + 0.7 * (end - start)
    return Case(
        case, start, boundary, end,
        {"case_id": case, "system_name": system,
         "fault_timestamp": datetime.fromtimestamp(t0, timezone.utc).isoformat(),
         "root_cause_entities": sorted(set(roots)), "fault_category": category,
         "ground_truth_causal_path": path},
    )


def telecom_deployment(path):
    uri = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
    ns = {"x": uri}
    relation = {}
    with ZipFile(path) as workbook:
        strings = ["".join(s.itertext()) for s in ET.fromstring(workbook.read("xl/sharedStrings.xml"))]
        sheet = ET.fromstring(workbook.read("xl/worksheets/sheet1.xml"))
        for row in sheet.findall(".//x:row", ns)[1:]:
            values = {}
            for cell in row.findall("x:c", ns):
                raw = cell.findtext("x:v", namespaces=ns)
                if raw is not None:
                    col = re.match(r"[A-Z]+", cell.attrib["r"]).group()
                    values[col] = strings[int(raw)].strip() if cell.attrib.get("t") == "s" else raw
            name, host = values.get("D"), values.get("C")
            if name and host and re.fullmatch(r"(?:os|node)[_-]\d+", host, re.I):
                relation[name] = host
    return relation


def v1_batches(raw):
    deployment_path = raw / "AppTelecomDeploymentList.xlsx"
    deployment = telecom_deployment(deployment_path) if deployment_path.is_file() else {}
    for system in V1_SYSTEMS:
        directory = raw / system
        if not (directory / "record.csv").is_file():
            continue
        with (directory / "record.csv").open(encoding="utf-8-sig", newline="") as handle:
            records = list(csv.DictReader(handle))
        by_day = defaultdict(list)
        tele_root = directory / "telemetry"
        for idx, row in enumerate(records):
            t0 = epoch(row["timestamp"])
            key = case_id("openrca_v1", f"{system}/{idx}")
            local = datetime.fromtimestamp(t0, LOCAL_TZ)
            midnight = local.replace(hour=0, minute=0, second=0, microsecond=0)
            day = midnight.strftime("%Y_%m_%d")
            previous, following = midnight - timedelta(days=1), midnight + timedelta(days=1)
            start = previous if (tele_root / previous.strftime("%Y_%m_%d")).is_dir() else midnight
            end = following
            if (tele_root / following.strftime("%Y_%m_%d")).is_dir():
                end += timedelta(days=1)
            coverage = start.timestamp(), end.timestamp()
            by_day[day].append(item(key, system, t0, [row["component"]], row["reason"],
                                    None, coverage))
        for day, cases in sorted(by_day.items()):
            dates = {day}
            for case in cases:
                for ts in (case.start, case.end):
                    dates.add(datetime.fromtimestamp(ts, LOCAL_TZ).strftime("%Y_%m_%d"))
            files = tuple(sorted(path for d in dates for path in (tele_root / d).glob("*/*.csv")
                                 if path.parent.name in {"metric", "trace", "log"}))
            yield Batch(f"{system}/{day}", "openrca_v1", system, tuple(cases), files, deployment)


def load_json(path, default=None):
    return json.loads(path.read_text(encoding="utf-8"), strict=False) if path.is_file() else default


def roots_in(value):
    if isinstance(value, str):
        return [value] if value else []
    if isinstance(value, list):
        return [root for part in value for root in roots_in(part)]
    if isinstance(value, dict):
        if isinstance(value.get("component"), str):
            return [value["component"]]
        return [root for name in ("service", "services", "root_services", "node", "host", "pod", "container", "function", "span")
                for root in roots_in(value.get(name))]
    return []


def graph_edges(graph):
    edges = []
    for edge in (graph or {}).get("edges", []):
        if isinstance(edge, dict):
            a, b = edge.get("source", edge.get("src")), edge.get("target", edge.get("dst"))
        elif isinstance(edge, list) and len(edge) >= 2:
            a, b = edge[:2]
        else:
            continue
        if a is not None and b is not None:
            edges.append({"src": str(a), "dst": str(b)})
    return edges or None


def normalize_pack(dataset, base, directory, manifest):
    env = load_json(directory / "env.json")
    injection = load_json(directory / "injection.json")
    if env is None or injection is None:
        raise ValueError("Missing window or official fault record")
    files = tuple(sorted(p for p in directory.glob("*.parquet") if p.stem in PACK_STEMS))
    if not files:
        raise ValueError("No telemetry files")
    graph = load_json(directory / "causal_graph.json", {})
    t0 = epoch(injection.get("start_time") or env["ABNORMAL_START"])
    coverage = epoch(env["NORMAL_START"]), epoch(env["ABNORMAL_END"])
    system = (manifest.get("system") or injection.get("pedestal_name") or
              injection.get("category") or env.get("NAMESPACE") or "train-ticket")
    if dataset == "propagation_bench" and re.fullmatch(r"ts\d*", str(system), re.I):
        system = "TrainTicket"
    metadata = injection.get("ground_truth", injection.get("groundtruth"))
    roots = roots_in(manifest.get("root_services")) or roots_in(graph.get("root_causes")) or roots_in(metadata)
    if not roots:
        raise ValueError("No official root entity")
    kind = graph.get("fault_type") or manifest.get("primary_kind") or injection.get("fault_type")
    key = case_id(dataset, directory.relative_to(base).as_posix())
    case = item(key, str(system), t0, roots, kind, graph_edges(graph), coverage)
    postmortem = directory / "conclusion.parquet" if dataset == "propagation_bench" else None
    return Batch(directory.name, dataset, str(system), (case,), files, postmortem=postmortem)


def pack_batches(raw, dataset):
    base = raw / ("datapacks" if dataset == "propagation_bench" else "cases")
    manifest_path = raw / "manifest.jsonl"
    manifests = {}
    if manifest_path.is_file():
        for line in manifest_path.read_text().splitlines():
            if line.strip():
                entry = json.loads(line)
                manifests[entry["name"]] = entry
    markers = ("injection.json", "env.json", "normal_traces.parquet", "abnormal_traces.parquet")
    directories = sorted({p.parent for name in markers for p in base.rglob(name)})
    for directory in directories:
        if dataset == "propagation_bench" and (directory / ".invalid").is_file():
            continue
        yield directory, manifests.get(directory.name, {}), base


def sql_str(string):
    return "'" + str(string).replace("'", "''") + "'"


def identifier(string):
    return '"' + string.replace('"', '""') + '"'


def columns(conn, source):
    return {name for name, *_ in conn.execute(f"DESCRIBE SELECT * FROM {source}").fetchall()}


def select_csv(conn, paths):
    items = ", ".join(sql_str(p) for p in paths)
    return (
        f"read_csv([{items}], header=true, all_varchar=true, union_by_name=false, "
        "sample_size=2048, strict_mode=false, null_padding=true, store_rejects=true)"
    )


def select_parquet(paths):
    return "read_parquet([" + ", ".join(sql_str(p) for p in paths) + "], union_by_name=true)"


def pick(names, keys):
    return next((identifier(key) for key in keys if key in names), "NULL")


def value(names, *keys):
    exprs = [f"nullif(trim(cast({identifier(key)} as varchar)), '')" for key in keys if key in names]
    if not exprs:
        return "NULL::varchar"
    return exprs[0] if len(exprs) == 1 else f"coalesce({', '.join(exprs)})"


def time_sql(expr, csv_input):
    if not csv_input:
        return f"epoch(try_cast({expr} AS timestamptz))"
    stamp = f"try_cast({expr} AS double)"
    return (
        f"case when abs({stamp}) >= 1e17 then {stamp}/1e9 "
        f"when abs({stamp}) >= 1e14 then {stamp}/1e6 "
        f"when abs({stamp}) >= 1e11 then {stamp}/1e3 else {stamp} end"
    )


def group_files(files):
    groups = defaultdict(list)
    for path in files:
        key = path.stem
        if key.startswith(("abnormal_", "normal_")):
            key = key.split("_", 1)[1]
        groups[key].append(path)
    return groups


def metric_sql(conn, batch, groups):
    csv_input = batch.source == "openrca_v1"
    for kind, paths in sorted(groups.items()):
        if not kind.startswith("metric"):
            continue
        source = select_csv(conn, paths) if csv_input else select_parquet(paths)
        names = columns(conn, source)
        t = time_sql(pick(names, ("timestamp", "startTime", "time")), csv_input)
        host = value(names, "attr.k8s.node.name")
        pod = value(names, "attr.k8s.pod.name")
        svc = value(names, "service_name", "attr.k8s.service.name")
        if csv_input:
            entity = value(names, "cmdb_id", "serviceName", "service", "tc")
            layer = "'host'" if kind == "metric_node" else "'service'"
        else:
            entity = f"coalesce({pod}, {svc}, {host})"
            layer = f"case when {pod} is not null then 'instance' when {svc} is not null then 'service' else 'host' end"
        if kind == "metrics_histogram":
            # The source exposes summaries only. A sample mean is defined, a p99 is not.
            yield (f"select {t} t, {entity} entity, {layer} layer, {svc} svc, {host} host, "
                   f"{value(names, 'metric')} || '.mean' metric, "
                   f"try_cast({pick(names, ('sum',))} as double) / nullif(try_cast({pick(names, ('count',))} as double),0) val "
                   f"from {source}")
        elif "value" in names:
            metric = value(names, "kpi_name", "name", "metric")
            yield (f"select {t} t, {entity} entity, {layer} layer, {svc} svc, {host} host, "
                   f"{metric} metric, try_cast(\"value\" as double) val from {source}")
        else:
            render = []
            for field in ("rr", "sr", "cnt", "mrt", "count", "avg_time", "num", "succee_num", "succee_rate"):
                if field not in names:
                    continue
                name, expr = field, f"try_cast({identifier(field)} as double)"
                if field in ("sr", "succee_rate"):
                    name = f"error_rate_from_{field}"
                    expr = f"1 - {expr}" if field == "succee_rate" else f"1 - {expr}/100"
                render.append(f"({sql_str(name)}, {expr})")
            if render:
                yield (f"select {t} t, {entity} entity, {layer} layer, {svc} svc, {host} host, "
                       f"v.metric, v.val from {source}, lateral (values {', '.join(render)}) v(metric,val)")


def traces_sql(conn, batch, groups):
    csv_input = batch.source == "openrca_v1"
    paths = groups.get("trace_span" if csv_input else "traces")
    if not paths:
        return None
    source = select_csv(conn, paths) if csv_input else select_parquet(paths)
    names = columns(conn, source)
    t = time_sql(pick(names, ("timestamp", "startTime", "time")), csv_input)
    ent = value(names, "cmdb_id", "service_name", "attr.k8s.service.name")
    pod = value(names, "attr.k8s.pod.name")
    if not csv_input:
        service = value(names, "service_name", "attr.k8s.service.name")
        duration = f'try_cast({pick(names, ("duration",))} as double)/1000000'
    else:
        service = ent
        if batch.systems.startswith("Market"):
            service = f"regexp_replace(regexp_replace({ent}, '^node-[0-9]+\\.', ''), '-[0-9]+$', '')"
        duration = f'try_cast({pick(names, ("duration", "elapsedTime"))} as double)'
    flag = f"lower({value(names, 'attr.span_kind', 'span_kind', 'type', 'callType')})"
    code = f"lower({value(names, 'attr.status_code', 'status_code')})"
    http = f"try_cast({pick(names, ('attr.http.response.status_code', 'http.status_code'))} as double)"
    success = f"lower({value(names, 'success')})"
    err = (f"case when {success} in ('false','0') or {code} in ('error','status_code_error','2') "
           f"or try_cast({code} as double) >= 400 or {http} >= 400 then 1 "
           f"when {success} is not null or {code} is not null or {http} is not null then 0 end")
    return f"""select {t} t, {service} service, {ent} entity, {pod} pod, {duration} duration,
                      {flag} kind, {err} failed, {value(names, 'trace_id', 'traceId')} trace_id,
                      {value(names, 'span_id', 'id')} span_id,
                      {value(names, 'parent_id', 'parent_span', 'parent_span_id', 'pid')} parent_id,
                      {value(names, 'span_name', 'operation_name')} span_name,
                      {value(names, 'dsName')} destination
               from {source}"""


def logs_sql(conn, batch, groups):
    csv_input = batch.source == "openrca_v1"
    for kind, paths in sorted(groups.items()):
        if not kind.startswith("log"):
            continue
        source = select_csv(conn, paths) if csv_input else select_parquet(paths)
        names = columns(conn, source)
        t = time_sql(pick(names, ("timestamp", "time")), csv_input)
        msg = value(names, "value", "message")
        svc = value(names, "service_name", "attr.k8s.service.name")
        pod = value(names, "attr.k8s.pod.name")
        ent = value(names, "cmdb_id") if csv_input else f"coalesce({pod}, {svc})"
        level = value(names, "level", "severity")
        yield f"select {t} t, {ent} entity, {pod} pod, {svc} svc, {msg} msg, {level} severity from {source}"