Cyber / impl /src /pipeline /step05_duplicates.py
pramodkachare's picture
Upload project files (excluding raw/derived dataset and venv)
aefa98b verified
Raw History Blame Contribute Delete
5.17 kB
"""STEP 05: duplicates, cross-source overlap and label-conflicting duplicates.
Keys: 64-bit hash of feature set A (53 features incl. IPs/ports/timestamps) and of feature set B (47, without
IPs, ports, timestamps). Expected hash collisions among 67M rows ~1e-4, i.e. negligible.
Outputs: data/dedup_keys.parquet (row_id, hA, hB, is_first_A, is_first_B, conflictA, conflictB, xsrcA, xsrcB)
artifacts/step05/{summary.json, by_class.csv, by_source.csv}
is_first_X = first occurrence (lowest row_id) of its (X-hash, Attack) pair: the deduplicated population for variant X.
(Keyed on the label too: dedup by features alone would silently delete one label of every conflicting group.)
conflictX = the X-hash appears with more than one label (irreducible ambiguity for that feature set).
xsrcX = the X-hash appears in more than one source.
"""
import csv
from .common import *
NAME = "step05"
KEYS = os.path.join(DATA, "dedup_keys.parquet")
S = f"read_parquet('{PARQUET_SRC}')"
def run(force=False):
out = step_dir(NAME); con = connect()
A, B = features_A(con), features_B(con)
assert len(A) == 53 and len(B) == 47, (len(A), len(B))
if force or not os.path.exists(KEYS):
with timed("hash keys"):
con.execute(f"CREATE TABLE k AS SELECT row_id, source, Attack, hash({qlist(A)}) hA, hash({qlist(B)}) hB FROM {S}")
with timed("group A"):
con.execute("CREATE TABLE ga AS SELECT hA, min(row_id) first_row, count(DISTINCT Attack) nl, count(DISTINCT source) ns FROM k GROUP BY hA")
con.execute("CREATE TABLE fa AS SELECT hA, Attack, min(row_id) first_row FROM k GROUP BY hA, Attack")
with timed("group B"):
con.execute("CREATE TABLE gb AS SELECT hB, min(row_id) first_row, count(DISTINCT Attack) nl, count(DISTINCT source) ns FROM k GROUP BY hB")
con.execute("CREATE TABLE fb AS SELECT hB, Attack, min(row_id) first_row FROM k GROUP BY hB, Attack")
with timed("write keys"):
con.execute(f"""COPY (SELECT k.row_id, k.hA, k.hB, (k.row_id = fa.first_row) is_first_A, (k.row_id = fb.first_row) is_first_B,
(ga.nl > 1) conflictA, (gb.nl > 1) conflictB, (ga.ns > 1) xsrcA, (gb.ns > 1) xsrcB
FROM k JOIN ga USING (hA) JOIN gb USING (hB) JOIN fa ON fa.hA = k.hA AND fa.Attack = k.Attack JOIN fb ON fb.hB = k.hB AND fb.Attack = k.Attack ORDER BY k.row_id) TO '{KEYS}' (FORMAT PARQUET, COMPRESSION ZSTD, ROW_GROUP_SIZE 1000000)""")
con.execute("DROP TABLE k; DROP TABLE ga; DROP TABLE gb; DROP TABLE fa; DROP TABLE fb")
K = f"read_parquet('{KEYS}')"
n = con.execute(f"SELECT count(*) FROM {K}").fetchone()[0]
r = con.execute(f"""SELECT sum((NOT is_first_A)::INT), sum((NOT is_first_B)::INT), sum(conflictA::INT), sum(conflictB::INT),
sum(xsrcA::INT), sum(xsrcB::INT), count(DISTINCT hA), count(DISTINCT hB), sum(is_first_A::INT), sum(is_first_B::INT) FROM {K}""").fetchone()
summ = {"n_rows": n,
"A": {"duplicate_rows": r[0], "duplicate_share": round(r[0] / n, 4), "unique_feature_vectors": r[6], "rows_in_label_conflicting_groups": r[2],
"rows_in_cross_source_groups": r[4], "population_unique_feature_label_pairs": r[8]},
"B": {"duplicate_rows": r[1], "duplicate_share": round(r[1] / n, 4), "unique_feature_vectors": r[7], "rows_in_label_conflicting_groups": r[3],
"rows_in_cross_source_groups": r[5], "population_unique_feature_label_pairs": r[9]}}
rows = con.execute(f"""SELECT s.source, count(*), sum((NOT k.is_first_A)::INT), sum((NOT k.is_first_B)::INT), sum(k.conflictA::INT), sum(k.conflictB::INT),
sum(k.xsrcA::INT), sum(k.xsrcB::INT) FROM {S} s JOIN {K} k USING (row_id) GROUP BY 1 ORDER BY 2 DESC""").fetchall()
with open(os.path.join(out, "by_source.csv"), "w", newline="") as f:
w = csv.writer(f); w.writerow(["source", "rows", "dup_A", "dup_B", "conflict_A", "conflict_B", "cross_source_A", "cross_source_B", "dup_A_share", "dup_B_share", "conflict_B_share"])
for x in rows: w.writerow(list(x) + [round(x[2] / x[1], 4), round(x[3] / x[1], 4), round(x[5] / x[1], 4)])
rows = con.execute(f"""SELECT s.Attack, count(*), sum((NOT k.is_first_A)::INT), sum((NOT k.is_first_B)::INT), sum(k.conflictA::INT), sum(k.conflictB::INT),
sum(k.xsrcB::INT), count(*) FILTER (WHERE k.is_first_A), count(*) FILTER (WHERE k.is_first_B)
FROM {S} s JOIN {K} k USING (row_id) GROUP BY 1 ORDER BY 2 DESC""").fetchall()
with open(os.path.join(out, "by_class.csv"), "w", newline="") as f:
w = csv.writer(f); w.writerow(["Attack", "rows", "dup_A", "dup_B", "conflict_A", "conflict_B", "cross_source_B", "unique_A", "unique_B", "dup_A_share", "dup_B_share", "conflict_B_share"])
for x in rows: w.writerow(list(x[:7]) + [x[7], x[8], round(x[2] / x[1], 4), round(x[3] / x[1], 4), round(x[5] / x[1], 4)])
summ["classes_with_fewer_than_100_unique_A"] = [x[0] for x in rows if x[7] < 100]
summ["classes_with_fewer_than_100_unique_B"] = [x[0] for x in rows if x[8] < 100]
save_json(summ, os.path.join(out, "summary.json"))
print(json.dumps(summ, indent=1))