"""Site-dict builders. Builds one site object per instance: coverage (12 channels), normalized_signals (primary inputs), and raw_features that are (i) schema-valid against observables/observables.yaml and (ii) numerically consistent with the signals. Raw-feature record shapes reuse the field names of scripts/generate_synthetic_observables.py:512-751. """ from __future__ import annotations import hashlib import json from datetime import datetime, timedelta, timezone from typing import Any, Optional PEAK_RATE = 2.0e15 SECONDS_PER_DAY = 86400.0 BASE_START = datetime(2026, 4, 1, tzinfo=timezone.utc) POLICY_THRESHOLD = 1.0e25 # Good coverage profile (spec section 2 preamble). GOOD_COVERAGE = { "capacity": 0.96, "activity": 0.94, "achieved_ops": 0.94, "fabric": 0.92, "storage": 0.92, "serving": 0.90, "storage_operations": 0.90, "benchmark_hpc": 0.90, "attribution": 0.92, "scope_mapping": 0.94, "identity_shape": 0.92, "clock_alignment": 0.93, } COVERAGE_CHANNELS = list(GOOD_COVERAGE) # Raw feature ids that carry each coverage channel's telemetry (used by M3 null # representation: dropping a channel = dropping coverage key + signals + raws). RAW_BY_CHANNEL = { "activity": [ "accelerator_busy_or_utilization_fraction", "tensor_matrix_mxu_neuron_or_engine_active_fraction", ], "achieved_ops": ["generic_achieved_operation_rate"], "fabric": ["fabric_port_device_sample_counters", "scaleout_port_tx_rx_bytes_packets"], "storage": ["storage_write_operation_bytes", "object_storage_operation_counts"], "serving": ["load_balancer_gateway_flow_activity", "north_south_external_egress"], "capacity": [], "scope_mapping": [], "clock_alignment": [], } SIGNALS_BY_CHANNEL = { "activity": ["activity_score"], "achieved_ops": ["achieved_operations"], "fabric": ["collective_cadence_score", "activity_fabric_overlap_fraction", "participant_count"], "storage": [ "checkpoint_periodicity_score", "checkpoint_burst_count", "checkpoint_activity_adjacency_fraction", ], "serving": [ "serving_counterevidence_score", "serving_activity_overlap_fraction", "non_serving_score", ], "capacity": [], "scope_mapping": [], "clock_alignment": [], } def iso(moment: datetime) -> str: return moment.strftime("%Y-%m-%dT%H:%M:%SZ") def window_for(duration_seconds: float, start: datetime = BASE_START) -> dict: end = start + timedelta(seconds=int(round(duration_seconds))) return {"start": iso(start), "end": iso(end)} def window_seconds(window: dict) -> float: start = datetime.strptime(window["start"], "%Y-%m-%dT%H:%M:%SZ") end = datetime.strptime(window["end"], "%Y-%m-%dT%H:%M:%SZ") return (end - start).total_seconds() def coverage_profile(edits: Optional[dict] = None, omit: tuple = ()) -> dict: cov = dict(GOOD_COVERAGE) if edits: cov.update(edits) for key in omit: cov.pop(key, None) return cov def param_hash(params: dict) -> str: return hashlib.sha1(json.dumps(params, sort_keys=True, default=str).encode("utf-8")).hexdigest()[:8] def capacity_bound(count: int, duration_seconds: float, peak: float = PEAK_RATE) -> float: return count * peak * duration_seconds def build_raw_features( audit_window: dict, *, count: int, peak: float, signals: dict, allocation: bool, storage_op_type: str, omit_raw: set, ) -> dict: """Raw features schema-valid against observables.yaml and numerically consistent with normalized_signals (the self-check asserts this).""" start = datetime.strptime(audit_window["start"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) end = datetime.strptime(audit_window["end"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc) duration_seconds = (end - start).total_seconds() mid = start + (end - start) / 2 activity = float(signals.get("activity_score", 0.0)) achieved = float(signals.get("achieved_operations", 0.0)) fabric = float(signals.get("collective_cadence_score", 0.0)) participants = int(signals.get("participant_count", 0)) checkpoint = float(signals.get("checkpoint_periodicity_score", 0.0)) bursts = int(signals.get("checkpoint_burst_count", 0)) serving = float(signals.get("serving_counterevidence_score", 0.0)) storage_overlap = float(signals.get("storage_operation_overlap_fraction", 0.0)) bytes_explained = float(signals.get("bytes_explained_fraction", 0.0)) regularity = float(signals.get("benchmark_regularity_score", 0.0)) raw: dict = { "accelerator_count_by_family_sku": [ { "valid_from": audit_window["start"], "valid_to": audit_window["end"], "accelerator_family": "SYN", "accelerator_sku": "SYN-ACCEL", "memory_class": "synthetic_high_bandwidth", "form_factor": "synthetic_module", "count": count, } ], "advertised_peak_rate_by_precision": [ { "valid_from": audit_window["start"], "valid_to": audit_window["end"], "precision_or_mode": "synthetic_tensor_ops", "peak_rate": peak, } ], "scaleout_fabric_domain_graph": [ { "valid_from": audit_window["start"], "valid_to": audit_window["end"], "scaleout_fabric_type": "synthetic_low_latency_fabric", "node_count": max(1, count // 8), "link_count": max(1, count * 4), "link_bandwidth_gbps": 800, "switch_count": max(1, count // 64), } ], "electrical_service_status_intervals": [ { "start_time": audit_window["start"], "end_time": audit_window["end"], "service_status": "energized", "service_capacity_mw": round(count * 0.0009, 4), "service_capacity_mva": round(count * 0.001, 4), "service_voltage_kv": 34.5, "service_class": "synthetic_datacenter_service", } ], } if allocation and count > 0: allocated = max(1, min(count, participants or int(count * max(activity, 0.1)))) raw["allocated_accelerator_count_by_sku"] = [ { "start_time": audit_window["start"], "end_time": audit_window["end"], "accelerator_sku": "SYN-ACCEL", "accelerator_profile": "full", "partition_scope": "accelerator_pool", "count": allocated, } ] raw["compute_running_intervals"] = [ { "start_time": audit_window["start"], "end_time": audit_window["end"], "compute_resource_state": "running", "accelerator_count": allocated, "accelerator_shape_or_sku": "SYN-ACCEL", } ] if activity > 0: # Both records equal the activity_score signal exactly: the code derives # activity as max(raw busy, raw tensor, signal), so any raw value above # the signal would silently shift the decision surface. raw["accelerator_busy_or_utilization_fraction"] = [ {"sample_time": iso(mid), "value": activity} ] raw["tensor_matrix_mxu_neuron_or_engine_active_fraction"] = [ {"sample_time": iso(mid), "value": activity, "engine_scope": "all_accelerators"} ] if achieved > 0: raw["generic_achieved_operation_rate"] = [ { "sample_time": iso(mid), "operation_rate": achieved / max(duration_seconds, 1.0), "operation_unit": "synthetic_normalized_operations", "counter_scope": "accelerator_pool", } ] if fabric > 0 or regularity > 0 or participants > 0: raw["fabric_port_device_sample_counters"] = [ {"sample_time": iso(mid), "counter_name": "collective_cadence_score", "counter_value": fabric, "counter_unit": "score_0_to_1", "monitored_scope_category": "accelerator_pool"}, {"sample_time": iso(mid), "counter_name": "participant_count", "counter_value": participants, "counter_unit": "accelerators", "monitored_scope_category": "accelerator_pool"}, {"sample_time": iso(mid), "counter_name": "regularity_score", "counter_value": regularity, "counter_unit": "score_0_to_1", "monitored_scope_category": "accelerator_pool"}, ] if fabric > 0: raw["scaleout_port_tx_rx_bytes_packets"] = [ { "sample_time": iso(mid), "tx_bytes": int(fabric * 10 ** 16), "rx_bytes": int(fabric * 10 ** 16), "tx_packets": int(fabric * 10 ** 9), "rx_packets": int(fabric * 10 ** 9), } ] if checkpoint > 0 and bursts > 0: # Exactly `bursts` records: len(storage_write_operation_bytes) is the # raw fallback for checkpoint_burst_count. raw["storage_write_operation_bytes"] = [] raw["object_storage_operation_counts"] = [] for idx in range(bursts): burst_start = start + timedelta(seconds=(idx + 1) * duration_seconds / (bursts + 2)) burst_end = burst_start + timedelta(minutes=45) raw["storage_write_operation_bytes"].append( { "start_time": iso(burst_start), "end_time": iso(burst_end), "write_operation_count": int(1000 + checkpoint * 10000), "write_bytes": int(checkpoint * 10 ** 15), } ) raw["object_storage_operation_counts"].append( { "start_time": iso(burst_start), "end_time": iso(burst_end), "operation_type": "synthetic_checkpoint_state_write", "operation_count": int(1000 + checkpoint * 10000), "object_count": int(128 + checkpoint * 4096), "bytes": int(checkpoint * 10 ** 15), "object_count_type": "distinct_objects", } ) if serving > 0: raw["load_balancer_gateway_flow_activity"] = [ { "start_time": audit_window["start"], "end_time": audit_window["end"], "connection_count": int(serving * 10_000_000), "bytes": int(serving * 10 ** 15), } ] raw["north_south_external_egress"] = [ { "start_time": audit_window["start"], "end_time": audit_window["end"], "bytes": int(serving * 10 ** 15), "flow_count": int(serving * 1_000_000), "direction": "egress", } ] if storage_overlap > 0 or bytes_explained > 0: raw["storage_operation_intervals"] = [ { "start_time": audit_window["start"], "end_time": audit_window["end"], "operation_type": storage_op_type, "bytes_moved": int(max(bytes_explained, 0.01) * 10 ** 16), } ] if signals.get("physical_timeline_conflict"): raw["electrical_service_status_intervals"] = [ { "start_time": audit_window["start"], "end_time": audit_window["end"], "service_status": "not_energized", "service_capacity_mw": 0, "service_capacity_mva": 0, "service_voltage_kv": 34.5, "service_class": "synthetic_datacenter_service", } ] raw["asset_receiving_installation_events"] = [ { "event_time": iso(end + timedelta(days=2)), "event_type": "installed", "asset_category": "accelerator", "asset_quantity": count, } ] if signals.get("health_throttle_conflict"): raw["accelerator_health_error_state"] = [ { "sample_time": iso(mid), "ecc_error_count": 0, "retired_page_count": 0, "xid_or_equivalent_error_count": 12, "reset_count": 4, "link_error_count": 50, "throttle_event_count": 200, "degraded_state": True, } ] raw["accelerator_throttle_state"] = [{"sample_time": iso(mid), "state": "throttled"}] if signals.get("topology_route_conflict"): raw["topology_change_events"] = [ { "event_time": iso(mid), "topology_change_type": "route_change", "affected_asset_category": "fabric_port", "affected_link_or_port_count": max(1, count // 4), } ] raw["network_gateway_nat_route_state"] = [ { "event_time": iso(mid), "network_control_type": "route", "state_event_type": "updated", "state": "visibility_updated", } ] if signals.get("power_activity_conflict"): raw["rack_pdu_it_power"] = [ { "sample_time": iso(mid), "power_watts": count * 900, "energy_joules": count * 900 * duration_seconds, } ] for feature_id in omit_raw: raw.pop(feature_id, None) return raw def build_site( *, site_id: str, scenario_key: str, scenario_name: str, duration_seconds: float, count: int, coverage: dict, signals: dict, peak: float = PEAK_RATE, allocation: bool = True, storage_op_type: str = "backup", omit_raw_channels: tuple = (), expected_route_set: Optional[list] = None, ) -> dict: audit_window = window_for(duration_seconds) omit_raw: set = set() for channel in omit_raw_channels: omit_raw.update(RAW_BY_CHANNEL.get(channel, [])) raw_features = build_raw_features( audit_window, count=count, peak=peak, signals=signals, allocation=allocation, storage_op_type=storage_op_type, omit_raw=omit_raw, ) site = { "site_id": site_id, "scenario_key": scenario_key, "scenario_name": scenario_name, "scope": f"{site_id}/accelerator_pool", "audit_window": audit_window, "operator_context": { "operator_type": "synthetic_monitored_operator", "telemetry_stack": "inventory_scheduler_activity_fabric_storage_power_network", "trust_tier": "synthetic_operator_signed", }, "coverage": coverage, "normalized_signals": signals, "raw_features": raw_features, } if expected_route_set is not None: site["expected"] = {"final_route_set": list(expected_route_set)} return site