File size: 12,143 Bytes
001717c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
feature_engineering.py
======================

Feature pipeline for the CYB008 baseline classifier.

Predicts `resolution_outcome` (5-class triage outcome) from per-alert
features on the CYB008 sample dataset.

CSV inputs:
    soc_alerts.csv          (primary, one row per alert, 9,200 alerts)
    soc_topology.csv        (per-analyst registry; reserved for future
                             work - 25 analysts is too small to be a
                             useful join target beyond the analyst_tier
                             column already on soc_alerts)
    incident_summary.csv    (per-incident aggregates; reserved - only
                             9% of alerts link to an incident)
    alert_events.csv        (discrete alert event log; reserved)

Target classes (5):
    auto_resolved_soar, duplicate_merged, false_positive_closed,
    true_positive_escalated, true_positive_remediated

Grouping decision
-----------------
There is no natural row-level group key for CYB008:
- 25 analysts -> group-aware split would yield ~4 test analysts
- 5 SOCs     -> group-aware split would yield ~1 test SOC
- 589 incidents -> only 9% of alerts have a non-null incident_id

This baseline uses STRATIFIED random splitting (like CYB001 for network
flows), which is the right choice when alerts are independent given
features. The model card documents this rationale.

Leakage audit
-------------
Three columns are structural oracles for resolution_outcome and are
DROPPED from the feature set:

1. `alert_lifecycle_phase` (4 values: auto_closed, escalated, resolved,
   suppressed_duplicate): three of the four values map deterministically
   to specific resolution_outcome classes. Drop.

2. `automation_resolved` (binary): exactly 1:1 with auto_resolved_soar
   outcome. Drop.

3. `escalation_flag` (binary): near-1:1 with true_positive_escalated
   outcome (1319 escalation flags = 1319 escalated outcomes). Drop.

With all three dropped, accuracy drops from 100% to 79% - confirming
they were structural oracles, not real predictive signal.

`soar_playbook_triggered` is a PARTIAL oracle (one-way necessary
condition: auto_resolved_soar => soar_playbook_triggered=1, but
soar_playbook_triggered=1 also yields 32% non-auto-resolve outcomes).
This is a legitimate observable - a SOAR playbook actually executing
is part of how the alert is triaged. KEPT.

`mitre_technique_id` is a perfect oracle for mitre_tactic (every T-
number belongs to one tactic by ATT&CK design) but has no relationship
to resolution_outcome. It is high-cardinality (36 values from a small
sample of a 600+-value enterprise space) and contributes nothing to
this task. Dropped for parsimony.

`detection_rule_id` has 656 unique values - too high-cardinality for
one-hot encoding. Dropped.

Identifier / non-feature columns
--------------------------------
Dropped: alert_id, incident_id (mostly null), analyst_id, soc_id,
shift_id, alert_timestamp_min, soar_playbook_id (high cardinality).

Public API
----------
    build_features(alerts_path) -> (X, y, ids, meta)
    transform_single(record, meta) -> np.ndarray
    save_meta(meta, path) / load_meta(path)

License
-------
Ships with the public model on Hugging Face under CC-BY-NC-4.0,
matching the dataset license. See README.md.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import numpy as np
import pandas as pd

# ---------------------------------------------------------------------------
# Label space
# ---------------------------------------------------------------------------

# Ordered by triage spectrum: auto -> dup -> FP -> TP-remediate -> TP-escalate
LABEL_ORDER = [
    "auto_resolved_soar",
    "duplicate_merged",
    "false_positive_closed",
    "true_positive_remediated",
    "true_positive_escalated",
]
LABEL_TO_INT = {lbl: i for i, lbl in enumerate(LABEL_ORDER)}
INT_TO_LABEL = {i: lbl for lbl, i in LABEL_TO_INT.items()}

# ---------------------------------------------------------------------------
# Identifier and target columns
# ---------------------------------------------------------------------------

ID_COLUMNS = [
    "alert_id", "incident_id", "analyst_id", "soc_id", "shift_id",
    "alert_timestamp_min", "soar_playbook_id",
]
TARGET_COLUMN = "resolution_outcome"

# Structural oracle columns - dropped from features.
ORACLE_COLUMNS = [
    "alert_lifecycle_phase",  # deterministically maps to 3 of 5 outcomes
    "automation_resolved",    # 1:1 with auto_resolved_soar outcome
    "escalation_flag",        # 1:1 with true_positive_escalated outcome
]

# High-cardinality categorical columns - dropped for tractability.
HIGH_CARDINALITY_COLUMNS = [
    "mitre_technique_id",  # 36 values; no relationship to outcome
    "detection_rule_id",   # 656 values; one-hot explosion
]

DROPPED_FROM_FEATURES = ORACLE_COLUMNS + HIGH_CARDINALITY_COLUMNS

# ---------------------------------------------------------------------------
# Per-alert numeric features
# ---------------------------------------------------------------------------

DIRECT_NUMERIC_FEATURES = [
    "raw_score",
    "enriched_score",
    "time_in_phase_minutes",
    "queue_depth_at_ingestion",
    "soar_playbook_triggered",  # partial oracle, kept as observable
    "sla_breached_flag",
    "mttd_minutes",
    "mttr_minutes",
    "fatigue_score_at_alert",
]

CATEGORICAL_FEATURES = [
    "alert_severity",      # 7 values
    "alert_source",        # 8 values
    "mitre_tactic",        # 12 values
    "analyst_tier",        # 3 values (alerts) / 4 (topology) -- 3 here
    "siem_platform",       # 8 values
]


# ---------------------------------------------------------------------------
# Engineered features
# ---------------------------------------------------------------------------

def _add_engineered_features(df: pd.DataFrame) -> pd.DataFrame:
    """
    Six engineered features encoding triage-outcome hypotheses.
    Each composite is a quantity a SOC analyst would compute by hand
    to assess an alert's likely disposition.
    """
    df = df.copy()

    # 1. Enrichment lift: how much enrichment improved the raw score.
    #    Positive lift = enrichment increased confidence (often -> TP).
    df["enrichment_lift"] = (
        df["enriched_score"] - df["raw_score"]
    ).astype(float)

    # 2. Log-scaled MTTR. MTTR is heavy-tailed (auto-resolves seconds,
    #    escalations hours). log1p compresses for both XGBoost and MLP.
    df["log_mttr"] = np.log1p(df["mttr_minutes"].clip(lower=0)).astype(float)

    # 3. Log-scaled MTTD. Same heavy-tail shape.
    df["log_mttd"] = np.log1p(df["mttd_minutes"].clip(lower=0)).astype(float)

    # 4. Queue pressure: queue depth times analyst fatigue. High =
    #    overloaded analyst, more likely to auto-resolve or escalate.
    df["queue_pressure"] = (
        df["queue_depth_at_ingestion"] * df["fatigue_score_at_alert"]
    ).astype(float)

    # 5. Triage time efficiency: enrichment_score per minute in phase.
    df["enrichment_per_minute"] = (
        df["enriched_score"] / df["time_in_phase_minutes"].clip(lower=0.1)
    ).astype(float)

    # 6. Is high-confidence alert: enriched score above 0.7 typically
    #    indicates a strong signal that warrants escalation.
    df["is_high_confidence"] = (df["enriched_score"] > 0.7).astype(int)

    return df


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def build_features(
    alerts_path: str | Path,
) -> tuple[pd.DataFrame, pd.Series, pd.Series, dict[str, Any]]:
    """
    Load soc_alerts.csv, drop target + identifiers + oracle columns,
    engineer features, one-hot encode, return (X, y, ids, meta).

    `ids` is a Series of alert_id values aligned with X (used for
    round-tripping; not a group label since this task uses stratified
    random splitting).
    """
    alerts = pd.read_csv(alerts_path)

    y = alerts[TARGET_COLUMN].map(LABEL_TO_INT)
    if y.isna().any():
        bad = alerts.loc[y.isna(), TARGET_COLUMN].unique()
        raise ValueError(f"Unknown resolution_outcome values: {bad}")
    y = y.astype(int)
    ids = alerts["alert_id"].copy()

    alerts = alerts.drop(
        columns=ID_COLUMNS + [TARGET_COLUMN] + DROPPED_FROM_FEATURES,
        errors="ignore",
    )

    alerts = _add_engineered_features(alerts)

    numeric_features = (
        DIRECT_NUMERIC_FEATURES
        + [
            "enrichment_lift", "log_mttr", "log_mttd",
            "queue_pressure", "enrichment_per_minute", "is_high_confidence",
        ]
    )
    numeric_features = [c for c in numeric_features if c in alerts.columns]
    X_numeric = alerts[numeric_features].astype(float)

    categorical_levels: dict[str, list[str]] = {}
    blocks: list[pd.DataFrame] = []
    for col in CATEGORICAL_FEATURES:
        if col not in alerts.columns:
            continue
        levels = sorted(alerts[col].dropna().unique().tolist())
        categorical_levels[col] = levels
        block = pd.get_dummies(
            alerts[col].astype("category").cat.set_categories(levels),
            prefix=col, dummy_na=False,
        ).astype(int)
        blocks.append(block)

    X = pd.concat(
        [X_numeric.reset_index(drop=True)]
        + [b.reset_index(drop=True) for b in blocks],
        axis=1,
    ).fillna(0.0)

    meta = {
        "feature_names": X.columns.tolist(),
        "numeric_features": numeric_features,
        "categorical_levels": categorical_levels,
        "label_to_int": LABEL_TO_INT,
        "int_to_label": INT_TO_LABEL,
        "oracle_excluded": ORACLE_COLUMNS,
        "high_cardinality_excluded": HIGH_CARDINALITY_COLUMNS,
    }
    return X, y, ids, meta


def transform_single(
    record: dict | pd.DataFrame,
    meta: dict[str, Any],
) -> np.ndarray:
    """Encode a single alert record for inference."""
    if isinstance(record, dict):
        df = pd.DataFrame([record.copy()])
    else:
        df = record.copy()

    df = _add_engineered_features(df)

    numeric = pd.DataFrame({
        col: df.get(col, pd.Series([0.0] * len(df))).astype(float).values
        for col in meta["numeric_features"]
    })
    blocks: list[pd.DataFrame] = [numeric]
    for col, levels in meta["categorical_levels"].items():
        val = df.get(col, pd.Series([None] * len(df)))
        block = pd.get_dummies(
            val.astype("category").cat.set_categories(levels),
            prefix=col, dummy_na=False,
        ).astype(int)
        for lvl in levels:
            cname = f"{col}_{lvl}"
            if cname not in block.columns:
                block[cname] = 0
        block = block[[f"{col}_{lvl}" for lvl in levels]]
        blocks.append(block)

    X = pd.concat(blocks, axis=1).fillna(0.0)
    X = X.reindex(columns=meta["feature_names"], fill_value=0.0)
    return X.values.astype(np.float32)


def save_meta(meta: dict[str, Any], path: str | Path) -> None:
    serializable = {
        "feature_names": meta["feature_names"],
        "numeric_features": meta["numeric_features"],
        "categorical_levels": meta["categorical_levels"],
        "label_to_int": meta["label_to_int"],
        "int_to_label": {str(k): v for k, v in meta["int_to_label"].items()},
        "oracle_excluded": meta.get("oracle_excluded", []),
        "high_cardinality_excluded": meta.get("high_cardinality_excluded", []),
    }
    with open(path, "w") as f:
        json.dump(serializable, f, indent=2)


def load_meta(path: str | Path) -> dict[str, Any]:
    with open(path) as f:
        meta = json.load(f)
    meta["int_to_label"] = {int(k): v for k, v in meta["int_to_label"].items()}
    return meta


if __name__ == "__main__":
    import sys
    base = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("/mnt/user-data/uploads")
    X, y, ids, meta = build_features(base / "soc_alerts.csv")
    print(f"X shape: {X.shape}")
    print(f"y shape: {y.shape}")
    print(f"n_features: {len(meta['feature_names'])}")
    print(f"label distribution:\n{y.map(INT_TO_LABEL).value_counts()}")
    print(f"X has NaN: {X.isnull().any().any()}")