#!/usr/bin/env python3 """Deterministic Byzantine attack reference for QuantInvBench. The clean dataset remains the canonical artifact. This module creates an attacked view in *replace* mode: the population stays fixed at ten strategies, and a seed-selected, static subset of ``f`` strategy identities is replaced. Attack labels are returned separately from the attacked records so benchmark methods do not need to receive the malicious identities. Frozen v1 attacks (``h`` is the mean proposal of the honest identities): * Reverse: ``(1 - h) / (d - 1)``. * Bias: ``0.9 * h + 0.1 * one_hot(BTC)``. * Drift: keep the selected strategy's clean proposal for rounds 1--20, then interpolate toward a seed-and-identity-specific Dirichlet(1) target with ``alpha_t = min(1, 0.02 * (t - 20))``. * Mixed: assign Reverse, Bias, and Drift cyclically to the static malicious identities. The public API is :func:`apply_attacks`. Run ``python attacks.py --help`` for the JSONL command-line interface. """ from __future__ import annotations import argparse import copy import hashlib import json import math from dataclasses import dataclass from pathlib import Path from typing import Mapping, Sequence try: # Package import and direct-script execution are both supported. from .common import ( ASSETS, ATTACK_PROTOCOL_VERSION, read_jsonl, validated_weights, write_jsonl, ) except ImportError: # pragma: no cover - exercised by the CLI invocation from common import ( ASSETS, ATTACK_PROTOCOL_VERSION, read_jsonl, validated_weights, write_jsonl, ) PROTOCOL_VERSION = ATTACK_PROTOCOL_VERSION POPULATION_SIZE = 10 ATTACKS = ("reverse", "bias", "drift", "mixed") MIXED_ROLES = ("reverse", "bias", "drift") BIAS_DELTA = 0.1 BIAS_ASSET = "BTC" DRIFT_WARMUP_ROUNDS = 20 DRIFT_RATE = 0.02 SIMPLEX_TOLERANCE = 1e-6 @dataclass(frozen=True) class AttackBatch: """An attacked dataset view and its evaluator-only audit metadata.""" records: list[dict] audit: dict def _stable_digest(*parts: object) -> bytes: payload = "\x1f".join(str(part) for part in parts).encode("utf-8") return hashlib.sha256(payload).digest() def _stable_identity_order(strategy_ids: Sequence[str], seed: int) -> list[str]: """Return a seed-dependent ordering that is stable across Python versions.""" return sorted( strategy_ids, key=lambda strategy_id: ( _stable_digest(PROTOCOL_VERSION, "identity", seed, strategy_id), strategy_id, ), ) def select_malicious_ids( strategy_ids: Sequence[str], *, f: int, seed: int, ) -> tuple[str, ...]: """Select the static malicious identities for a benchmark run.""" ids = list(strategy_ids) if len(ids) != POPULATION_SIZE or len(set(ids)) != POPULATION_SIZE: raise ValueError( f"expected {POPULATION_SIZE} unique strategy identities, got {len(ids)}" ) _validate_f(f) return tuple(_stable_identity_order(ids, seed)[:f]) def assign_attack_roles( malicious_ids: Sequence[str], *, attack: str, ) -> dict[str, str]: """Assign one frozen role to each malicious identity.""" if attack not in ATTACKS: raise ValueError(f"unknown attack {attack!r}; expected one of {ATTACKS}") if len(set(malicious_ids)) != len(malicious_ids): raise ValueError("malicious identities must be unique") if attack == "mixed": return { strategy_id: MIXED_ROLES[index % len(MIXED_ROLES)] for index, strategy_id in enumerate(malicious_ids) } return {strategy_id: attack for strategy_id in malicious_ids} def _validate_f(f: int) -> None: if isinstance(f, bool) or not isinstance(f, int): raise ValueError("f must be an integer") if f < 0 or POPULATION_SIZE <= 2 * f: raise ValueError( f"f must satisfy 0 <= f < {POPULATION_SIZE}/2 for n={POPULATION_SIZE}" ) def _validate_seed(seed: int) -> None: if isinstance(seed, bool) or not isinstance(seed, int): raise ValueError("seed must be an integer") def _record_proposals(record: Mapping[str, object], index: int) -> list[dict]: proposals = record.get("strategy_proposals") if not isinstance(proposals, list): raise ValueError(f"record {index}: strategy_proposals must be a list") if len(proposals) != POPULATION_SIZE: raise ValueError( f"record {index}: replace mode requires exactly {POPULATION_SIZE} " f"proposals, got {len(proposals)}" ) checked: list[dict] = [] seen: set[str] = set() for proposal_index, proposal in enumerate(proposals): if not isinstance(proposal, dict): raise ValueError( f"record {index} proposal {proposal_index}: expected an object" ) strategy_id = proposal.get("strategy") if not isinstance(strategy_id, str) or not strategy_id or strategy_id in seen: raise ValueError( f"record {index} proposal {proposal_index}: invalid or duplicate strategy" ) seen.add(strategy_id) weights = proposal.get("weights") if not isinstance(weights, (list, tuple)): raise ValueError( f"record {index} strategy {strategy_id}: weights must be a sequence" ) validated_weights( weights, label=f"record {index} strategy {strategy_id}", ) checked.append(proposal) return checked def _validate_records(records: Sequence[dict]) -> tuple[str, ...]: if not records: raise ValueError("cannot attack an empty dataset") if not isinstance(records[0], dict): raise ValueError("record 0: expected an object") first_proposals = _record_proposals(records[0], 0) roster = tuple(proposal["strategy"] for proposal in first_proposals) roster_set = set(roster) for index, record in enumerate(records): if not isinstance(record, dict): raise ValueError(f"record {index}: expected an object") identifier = record.get("id") if not isinstance(identifier, str) or not identifier: raise ValueError(f"record {index}: id must be a non-empty string") assets = record.get("assets") if assets != list(ASSETS): raise ValueError( f"record {index}: assets must use the fixed order {list(ASSETS)}" ) proposals = _record_proposals(record, index) current_roster = {proposal["strategy"] for proposal in proposals} if current_roster != roster_set: raise ValueError(f"record {index}: strategy roster differs from record 0") return roster def _resolve_malicious_ids( roster: Sequence[str], *, f: int, seed: int, malicious_ids: Sequence[str] | None, ) -> tuple[str, ...]: if malicious_ids is None: return select_malicious_ids(roster, f=f, seed=seed) selected = tuple(malicious_ids) if len(selected) != f: raise ValueError( f"expected exactly f={f} explicit malicious identities, got {len(selected)}" ) if len(set(selected)) != len(selected): raise ValueError("explicit malicious identities must be unique") unknown = set(selected) - set(roster) if unknown: raise ValueError(f"unknown malicious identities: {sorted(unknown)}") return selected def _honest_mean(proposals: Sequence[dict], malicious_ids: set[str]) -> list[float]: honest = [ validated_weights( proposal["weights"], label=f"honest proposal {proposal['strategy']}" ) for proposal in proposals if proposal["strategy"] not in malicious_ids ] if not honest: raise ValueError("at least one honest proposal is required") return [sum(values) / len(honest) for values in zip(*honest)] def _dirichlet_one_target(seed: int, strategy_id: str) -> list[float]: """Generate a stable Dirichlet(1) draw without mutable global RNG state.""" draws = [] for asset in ASSETS: digest = _stable_digest( PROTOCOL_VERSION, "drift-target", seed, strategy_id, asset ) integer = int.from_bytes(digest[:8], byteorder="big", signed=False) uniform = (integer + 0.5) / (2**64) draws.append(-math.log(uniform)) total = sum(draws) return validated_weights( [draw / total for draw in draws], label=f"drift target {strategy_id}" ) def _reverse(honest_mean: Sequence[float]) -> list[float]: dimension = len(honest_mean) if dimension < 2: raise ValueError("reverse attack requires at least two dimensions") return validated_weights( [(1.0 - value) / (dimension - 1) for value in honest_mean], label="reverse attack", ) def _bias(honest_mean: Sequence[float]) -> list[float]: btc_index = ASSETS.index(BIAS_ASSET) biased = [(1.0 - BIAS_DELTA) * value for value in honest_mean] biased[btc_index] += BIAS_DELTA return validated_weights(biased, label="bias attack") def _drift( clean_weights: Sequence[float], *, target: Sequence[float], round_number: int, ) -> list[float]: clean = validated_weights(clean_weights, label="drift clean proposal") alpha = min( 1.0, DRIFT_RATE * max(0, round_number - DRIFT_WARMUP_ROUNDS), ) if alpha == 0.0: # The frozen protocol says the warmup proposal is the agent's clean # proposal, including its serialized floating-point representation. return [float(value) for value in clean_weights] return validated_weights( [ (1.0 - alpha) * clean_value + alpha * target_value for clean_value, target_value in zip(clean, target) ], label="drift attack", ) def _attack_weights( role: str, *, clean_weights: Sequence[float], honest_mean: Sequence[float], drift_target: Sequence[float] | None, round_number: int, ) -> list[float]: if role == "reverse": return _reverse(honest_mean) if role == "bias": return _bias(honest_mean) if role == "drift": if drift_target is None: # Defensive: roles and targets are built together. raise ValueError("drift target is required for the drift attack") return _drift( clean_weights, target=drift_target, round_number=round_number, ) raise ValueError(f"unsupported attack role: {role}") def _assert_simplex(weights: Sequence[float], label: str) -> None: if len(weights) != len(ASSETS): raise AssertionError(f"{label}: wrong dimension") if any(not math.isfinite(value) or value < -SIMPLEX_TOLERANCE for value in weights): raise AssertionError(f"{label}: weights are not finite and non-negative") if abs(sum(weights) - 1.0) > SIMPLEX_TOLERANCE: raise AssertionError(f"{label}: weights do not sum to one") def apply_attacks( records: Sequence[dict], *, attack: str = "mixed", f: int = 3, seed: int = 42, malicious_ids: Sequence[str] | None = None, ) -> AttackBatch: """Create a deterministic attacked view of clean QuantInvBench records. Args: records: Chronologically ordered clean benchmark records. attack: One of ``reverse``, ``bias``, ``drift``, or ``mixed``. f: Number of replaced strategy identities. Must satisfy ``10 > 2f``. seed: Selects the static identities and fixed Drift targets. malicious_ids: Optional explicit identities. When omitted, ``seed`` deterministically selects them once for the complete run. Returns: :class:`AttackBatch`; ``records`` contain no malicious labels, while ``audit`` contains the evaluator-only identities, roles, and protocol parameters. """ _validate_f(f) _validate_seed(seed) if attack not in ATTACKS: raise ValueError(f"unknown attack {attack!r}; expected one of {ATTACKS}") clean_records = list(records) roster = _validate_records(clean_records) selected = _resolve_malicious_ids( roster, f=f, seed=seed, malicious_ids=malicious_ids, ) roles = assign_attack_roles(selected, attack=attack) selected_set = set(selected) drift_targets = { strategy_id: _dirichlet_one_target(seed, strategy_id) for strategy_id, role in roles.items() if role == "drift" } attacked_records: list[dict] = [] for record_index, clean_record in enumerate(clean_records): round_number = record_index + 1 clean_proposals = clean_record["strategy_proposals"] honest_mean = _honest_mean(clean_proposals, selected_set) attacked_record = copy.deepcopy(clean_record) for proposal in attacked_record["strategy_proposals"]: strategy_id = proposal["strategy"] role = roles.get(strategy_id) if role is None: continue proposal["weights"] = _attack_weights( role, clean_weights=proposal["weights"], honest_mean=honest_mean, drift_target=drift_targets.get(strategy_id), round_number=round_number, ) _assert_simplex( proposal["weights"], f"record {clean_record['id']} strategy {strategy_id}", ) attacked_records.append(attacked_record) audit = { "protocol_version": PROTOCOL_VERSION, "population_mode": "replace", "n": POPULATION_SIZE, "f": f, "seed": seed, "attack": attack, "malicious_ids": list(selected), "attack_roles": roles, "parameters": { "reverse": "(1 - honest_mean) / (d - 1)", "bias": { "formula": "(1 - delta) * honest_mean + delta * one_hot(asset)", "delta": BIAS_DELTA, "asset": BIAS_ASSET, }, "drift": { "formula": ( "(1 - alpha_t) * clean_agent_proposal_t + " "alpha_t * fixed_dirichlet_target" ), "warmup_rounds": DRIFT_WARMUP_ROUNDS, "rate": DRIFT_RATE, "alpha": "min(1, rate * max(0, round_number - warmup_rounds))", "target_distribution": "Dirichlet(1)", }, }, "drift_targets": drift_targets, "sample_ids": [record["id"] for record in clean_records], } return AttackBatch(records=attacked_records, audit=audit) def _synthetic_records(rounds: int = 25) -> list[dict]: records = [] strategies = [f"strategy_{index}" for index in range(POPULATION_SIZE)] for round_index in range(rounds): proposals = [] for strategy_index, strategy_id in enumerate(strategies): raw = [ 1.0 + ((strategy_index + asset_index + round_index) % len(ASSETS)) for asset_index in range(len(ASSETS)) ] total = sum(raw) proposals.append( { "strategy": strategy_id, "weights": [value / total for value in raw], } ) records.append( { "id": f"synthetic_{round_index:04d}", "assets": list(ASSETS), "strategy_proposals": proposals, } ) return records def run_self_test() -> None: """Exercise determinism, replace semantics, audit separation, and simplex.""" clean = _synthetic_records() first = apply_attacks(clean, attack="mixed", f=3, seed=17) second = apply_attacks(clean, attack="mixed", f=3, seed=17) if first != second: raise AssertionError("same seed did not reproduce identical output") if first.records == clean: raise AssertionError("mixed attack did not modify the dataset") if "attack_roles" in first.records[0] or "malicious_ids" in first.records[0]: raise AssertionError("attack labels leaked into method-facing records") roles = first.audit["attack_roles"] if sorted(roles.values()) != sorted(MIXED_ROLES): raise AssertionError("mixed attack did not assign one of each role for f=3") drift_id = next(strategy_id for strategy_id, role in roles.items() if role == "drift") malicious = set(first.audit["malicious_ids"]) for record_index, (clean_record, attacked_record) in enumerate( zip(clean, first.records) ): if len(attacked_record["strategy_proposals"]) != POPULATION_SIZE: raise AssertionError("replace mode changed the population size") clean_by_id = { proposal["strategy"]: proposal for proposal in clean_record["strategy_proposals"] } for proposal in attacked_record["strategy_proposals"]: _assert_simplex(proposal["weights"], proposal["strategy"]) if proposal["strategy"] not in malicious: if proposal != clean_by_id[proposal["strategy"]]: raise AssertionError("an honest proposal was modified") attacked_by_id = { proposal["strategy"]: proposal for proposal in attacked_record["strategy_proposals"] } drift_clean = clean_by_id[drift_id]["weights"] drift_attacked = attacked_by_id[drift_id]["weights"] if record_index < DRIFT_WARMUP_ROUNDS and drift_attacked != drift_clean: raise AssertionError("drift modified a proposal during its warmup") if record_index == DRIFT_WARMUP_ROUNDS and drift_attacked == drift_clean: raise AssertionError("drift did not begin after its warmup") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--data", type=Path, default=Path(__file__).resolve().parents[1] / "data" / "test.jsonl", help="Clean QuantInvBench JSONL (default: data/test.jsonl)", ) parser.add_argument("--output", type=Path, help="Method-facing attacked JSONL") parser.add_argument( "--audit-output", type=Path, help="Evaluator-only attack identities, roles, and parameters JSON", ) parser.add_argument("--attack", choices=ATTACKS, default="mixed") parser.add_argument("--f", type=int, default=3) parser.add_argument("--seed", type=int, default=42) parser.add_argument( "--malicious-id", action="append", dest="malicious_ids", help="Explicit static malicious strategy ID; repeat exactly f times", ) parser.add_argument( "--self-test", action="store_true", help="Run built-in deterministic invariants without reading data", ) return parser.parse_args() def main() -> None: args = parse_args() if args.self_test: run_self_test() print(json.dumps({"self_test": "passed", "protocol": PROTOCOL_VERSION})) return if args.output is None or args.audit_output is None: raise SystemExit("--output and --audit-output are required unless --self-test is used") data_path = args.data.resolve() output_path = args.output.resolve() audit_path = args.audit_output.resolve() if len({data_path, output_path, audit_path}) != 3: raise ValueError("data, output, and audit-output must be three different paths") batch = apply_attacks( read_jsonl(data_path), attack=args.attack, f=args.f, seed=args.seed, malicious_ids=args.malicious_ids, ) write_jsonl(output_path, batch.records) audit_path.parent.mkdir(parents=True, exist_ok=True) with audit_path.open("w", encoding="utf-8", newline="\n") as handle: json.dump(batch.audit, handle, indent=2, ensure_ascii=False, allow_nan=False) handle.write("\n") print( json.dumps( { "records": len(batch.records), "output": str(output_path), "audit_output": str(audit_path), "malicious_ids": batch.audit["malicious_ids"], "attack_roles": batch.audit["attack_roles"], }, indent=2, allow_nan=False, ) ) if __name__ == "__main__": main()