sample-grpo-openenv / observation_generator.py
Sumitwarrior7's picture
Add files using upload-large-folder tool
8308777 verified
Raw History Blame Contribute Delete
8.32 kB
"""
ObservationGenerator — derives partial, role-specific observations from
the hidden world state.
Defender observation (partial + noisy):
- Transaction velocity per account
- Refund ratio per account
- Device reuse count
- Merchant anomaly scores
- Freeze/flag status
- Active alerts
- Noisy risk signals (ground truth hidden)
Fraudster observation (partial + operational):
- Available fraud routes (not frozen)
- Detection pressure per route
- Account balances on mule accounts
- Cashout readiness signal
- Frozen/blocked status of their resources
"""
from __future__ import annotations
import random
from typing import Any, Dict, List
from scam_detection.constants import OBSERVATION_NOISE_LEVEL
from scam_detection.hidden_world_state import HiddenWorldState
class ObservationGenerator:
"""
Produces role-specific partial observations from the hidden world state.
Neither observation reveals ground-truth fraud labels directly.
The defender sees noisy risk signals; the fraudster sees the
operational state of their own resources.
"""
def __init__(self, noise_level: float = OBSERVATION_NOISE_LEVEL) -> None:
self._noise = noise_level
# =========================================================================
# Defender observation
# =========================================================================
def defender_observation(self, world: HiddenWorldState) -> Dict[str, Any]:
"""
Build the defender's partial, noisy observation.
Returns a dict with graph-like features derived from recent
transactions, account history, and device usage.
"""
rng = random.Random(world.seed ^ world.step ^ 0xDEF)
# Per-account transaction velocity (last 5 steps)
recent_cutoff = max(0, world.step - 5)
velocity: Dict[str, int] = {}
refund_counts: Dict[str, int] = {}
for tx in world.transactions:
if tx.timestamp >= recent_cutoff:
velocity[tx.from_user_id] = velocity.get(tx.from_user_id, 0) + 1
if tx.is_refunded:
refund_counts[tx.from_user_id] = (
refund_counts.get(tx.from_user_id, 0) + 1
)
# Account-level features (noisy risk scores)
accounts = []
for uid, user in world.users.items():
v = velocity.get(uid, 0)
r = refund_counts.get(uid, 0)
dev = world.devices.get(user.device_id)
dev_reuse = dev.reuse_count if dev else 0
# Add noise to risk_score to prevent direct leakage of ground truth
noisy_risk = self._add_noise(user.risk_score, rng)
accounts.append({
"id": uid,
"transaction_velocity": v,
"refund_count": r,
"refund_ratio": round(r / max(1, user.transaction_count), 3),
"device_reuse_count": dev_reuse,
"is_frozen": user.is_frozen,
"is_challenged": user.is_challenged,
"is_monitored": user.is_monitored,
"risk_score": round(noisy_risk, 3),
"balance_range": self._bucket_balance(user.balance),
})
# Merchant-level features
merchants = []
for mid, merchant in world.merchants.items():
noisy_anomaly = self._add_noise(merchant.anomaly_score, rng)
merchants.append({
"id": mid,
"transaction_count": merchant.transaction_count,
"refund_rate": round(merchant.refund_rate, 3),
"anomaly_score": round(noisy_anomaly, 3),
"is_blocked": merchant.is_blocked,
"is_monitored": merchant.is_monitored,
})
# Active alerts generated by the environment
alerts = list(world.defender_alerts[-10:]) # show last 10 alerts
# Step budget and aggregate stats
return {
"step": world.step,
"fraud_family_hint": self._family_hint(world.fraud_family, rng),
"accounts": accounts,
"merchants": merchants,
"alerts": alerts,
"aggregate": {
"total_frozen": sum(1 for u in world.users.values() if u.is_frozen),
"total_monitored": len(world.monitored_accounts),
"total_flagged": len(world.flagged_accounts),
"blocked_merchants": sum(
1 for m in world.merchants.values() if m.is_blocked
),
"recent_transaction_count": sum(velocity.values()),
},
}
# =========================================================================
# Fraudster observation
# =========================================================================
def fraudster_observation(self, world: HiddenWorldState) -> Dict[str, Any]:
"""
Build the fraudster's partial operational observation.
The fraudster knows about their own routes, mule accounts, and
resources, but sees the defender's detection pressure as a signal.
"""
routes_obs = []
for route in world.fraud_routes:
if not route.is_active:
continue
mule_status = []
for mid in route.mule_ids:
user = world.users.get(mid)
if user:
mule_status.append({
"id": mid,
"is_frozen": user.is_frozen,
"is_challenged": user.is_challenged,
"balance": round(user.balance, 2),
"device_id": user.device_id,
})
merchant_blocked = False
if route.merchant_id:
m = world.merchants.get(route.merchant_id)
merchant_blocked = m.is_blocked if m else False
cashout_ready = (
any(not s["is_frozen"] for s in mule_status)
and not merchant_blocked
and world.fraudster_delayed_steps == 0
)
routes_obs.append({
"id": route.id,
"family": route.family,
"detection_pressure": round(route.detection_pressure, 3),
"mule_status": mule_status,
"merchant_blocked": merchant_blocked,
"total_laundered": round(route.total_laundered, 2),
"cashout_ready": cashout_ready,
"steps_active": route.steps_active,
})
# Available actions summary
any_route_ready = any(r["cashout_ready"] for r in routes_obs)
active_mules = [
uid for uid, u in world.users.items()
if u.is_mule and not u.is_frozen and u.is_fraudster_controlled
]
return {
"step": world.step,
"alert_level": round(world.fraudster_alert_level, 3),
"delayed_steps_remaining": world.fraudster_delayed_steps,
"active_routes": routes_obs,
"available_mule_ids": active_mules,
"any_cashout_ready": any_route_ready,
"total_laundered_so_far": round(world.total_laundered, 2),
"available_fraud_families": [world.fraud_family],
}
# =========================================================================
# Helpers
# =========================================================================
def _add_noise(self, value: float, rng: random.Random) -> float:
noise = rng.gauss(0, self._noise)
return max(0.0, min(1.0, value + noise))
def _bucket_balance(self, balance: float) -> str:
if balance < 100:
return "very_low"
if balance < 500:
return "low"
if balance < 2000:
return "medium"
return "high"
def _family_hint(self, family: str, rng: random.Random) -> str:
"""Return a noisy hint about the fraud family type."""
families = ["refund_abuse", "mule_cashout", "merchant_collusion", "account_takeover"]
if rng.random() < 0.8:
return family # correct hint 80% of the time
return rng.choice([f for f in families if f != family])