Helinity's picture
Release v0.1.0: sanitized Python security research benchmark
1340dfb
Raw History Blame Contribute Delete
6.77 kB
"""Group curated families and similar Python programs before assigning splits."""
import ast
from collections import Counter, defaultdict
from hashlib import sha256
from io import StringIO
from itertools import combinations
import keyword
import tokenize
SEED = "CodeDNA-3A-2026-11-16"
SPLITS = {"train": 6, "validation": 2, "test": 2}
SHINGLE_SIZE = 5
NEAR_THRESHOLD = 0.80
MIN_TOKENS = 18
class StructuralAST(ast.NodeTransformer):
"""Normalize local names and literal values; retain attributes and operators."""
def visit_Name(self, node):
node.id = "_name"
return node
def visit_arg(self, node):
node.arg = "_arg"
return self.generic_visit(node)
def visit_FunctionDef(self, node):
node.name = "_function"
return self.generic_visit(node)
visit_AsyncFunctionDef = visit_FunctionDef
def visit_ClassDef(self, node):
node.name = "_class"
return self.generic_visit(node)
def visit_Constant(self, node):
values = {str: "", bytes: b"", int: 0, float: 0.0, complex: 0j}
node.value = values.get(type(node.value), node.value)
return node
def normalized_tokens(source):
result = []
previous = ""
fstring_depth = 0
ignored = {
tokenize.COMMENT, tokenize.ENCODING, tokenize.ENDMARKER, tokenize.NL,
tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT,
}
for token in tokenize.generate_tokens(StringIO(source).readline):
# Python 3.11 reports an f-string as STRING. Later versions emit its parts.
token_name = tokenize.tok_name[token.type]
if token_name == "FSTRING_START":
if not fstring_depth:
result.append("STRING")
fstring_depth += 1
continue
if fstring_depth:
if token_name == "FSTRING_END":
fstring_depth -= 1
previous = "STRING"
continue
if token.type in ignored:
continue
value = token.string
if token.type == tokenize.NAME and not keyword.iskeyword(value) and previous != ".":
value = "<name>"
if token.type in (tokenize.NUMBER, tokenize.STRING):
value = token_name
result.append(value)
previous = token.string
return result
def fingerprints(files):
sources = [item["code"] for item in files]
exact_ast = tuple(ast.dump(ast.parse(code), include_attributes=False) for code in sources)
normalized_ast = tuple(
ast.dump(StructuralAST().visit(ast.parse(code)), include_attributes=False)
for code in sources
)
tokens = [token for code in sources for token in ["<file>", *normalized_tokens(code)]]
shingles = {tuple(tokens[i:i + SHINGLE_SIZE]) for i in range(len(tokens) - SHINGLE_SIZE + 1)}
return tuple(sources), exact_ast, normalized_ast, len(tokens), shingles
def similarity(rows):
features = {row["sample_id"]: fingerprints(row["code_files"]) for row in rows}
near = []
exact_text = []
exact_ast = []
for left, right in combinations(sorted(features), 2):
left_text, left_ast, left_norm, left_size, left_shingles = features[left]
right_text, right_ast, right_norm, right_size, right_shingles = features[right]
if left_text == right_text:
exact_text.append([left, right])
if left_ast == right_ast:
exact_ast.append([left, right])
if min(left_size, right_size) < MIN_TOKENS:
continue
score = len(left_shingles & right_shingles) / len(left_shingles | right_shingles)
if left_norm == right_norm or score >= NEAR_THRESHOLD:
near.append({
"left": left, "right": right, "normalized_ast_match": left_norm == right_norm,
"token_jaccard": round(score, 4),
})
return {
"candidate_comparisons": len(rows) * (len(rows) - 1) // 2,
"exact_text": exact_text,
"exact_ast": exact_ast,
"near_matches": near,
}
def grouped_assignments(rows, report):
if report["exact_text"] or report["exact_ast"]:
raise ValueError("Exact duplicate samples must be resolved before splitting")
by_id = {row["sample_id"]: row for row in rows}
parents = {row["scenario_family_id"]: row["scenario_family_id"] for row in rows}
def root(family):
while family != parents[family]:
family = parents[family]
return family
for edge in report["near_matches"]:
left = root(by_id[edge["left"]]["scenario_family_id"])
right = root(by_id[edge["right"]]["scenario_family_id"])
first, second = sorted((left, right))
parents[second] = first
groups = defaultdict(list)
for row in rows:
groups[root(row["scenario_family_id"])].append(row)
if len(groups) < len(SPLITS):
raise ValueError("Too few independent groups to produce three splits")
# Largest groups first. A stable seed breaks ordering ties between groups.
def priority(group):
key, members = group
return -len(members), sha256(f"{SEED}:{key}".encode()).hexdigest()
assignments = {}
loads = Counter()
group_counts = Counter()
for index, (group, members) in enumerate(sorted(groups.items(), key=priority)):
empty_splits = [name for name in SPLITS if not loads[name]]
remaining_groups = len(groups) - index
choices = empty_splits if remaining_groups == len(empty_splits) else SPLITS
# Assign where this group's addition creates the lowest target-relative load.
split = min(choices, key=lambda name: (loads[name] + len(members)) / SPLITS[name])
loads[split] += len(members)
group_counts[split] += 1
for row in members:
assignments[row["sample_id"]] = (split, group)
if set(loads) != set(SPLITS):
raise ValueError("A split received no independent groups")
return assignments, dict(group_counts)
def validate_split_boundaries(rows, report):
places = defaultdict(set)
by_id = {}
for row in rows:
split = row["split"]
if split not in SPLITS:
raise ValueError(f"Invalid split {split!r}")
by_id[row["sample_id"]] = split
for field in ("pair_id", "scenario_family_id", "leakage_group_id"):
if row[field] is not None:
places[(field, row[field])].add(split)
for (field, key), splits in places.items():
if len(splits) > 1:
raise ValueError(f"{field} {key!r} crosses splits")
for edge in report["near_matches"]:
if by_id[edge["left"]] != by_id[edge["right"]]:
raise ValueError(f"Near-duplicate crosses splits: {edge['left']}, {edge['right']}")