okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cc86ad90d
main
1"""Read-only Windows processor group / NUMA / affinity probe. 2Runs only in this helper process; affinity is changed only on its own temporary test threads. 3""" 4import ctypes as C 5import json 6import os 7import platform 8import sys 9import struct 10import threading 11import time 12from pathlib import Path 13 14OUT = Path (__file__ ).resolve ().parent 15k32 = C .WinDLL ("kernel32" ,use_last_error = True ) 16DWORD = C .c_uint32 17WORD = C .c_uint16 18BYTE = C .c_ubyte 19KAFFINITY = C .c_size_t 20ALL_PROCESSOR_GROUPS = 0xFFFF 21 22class GROUP_AFFINITY (C .Structure ): 23_fields_ = [("Mask" ,KAFFINITY ), ("Group" ,WORD ), ("Reserved" ,WORD * 3 )] 24 25class PROCESSOR_NUMBER (C .Structure ): 26_fields_ = [("Group" ,WORD ), ("Number" ,BYTE ), ("Reserved" ,BYTE )] 27 28# Declare only APIs used by the probe; all processor IDs are group-relative. 29k32 .GetActiveProcessorGroupCount .restype = WORD 30k32 .GetActiveProcessorCount .argtypes = [WORD ] 31k32 .GetActiveProcessorCount .restype = DWORD 32k32 .GetCurrentThread .restype = C .c_void_p 33k32 .GetCurrentProcessorNumberEx .argtypes = [C .POINTER (PROCESSOR_NUMBER )] 34k32 .SetThreadAffinityMask .argtypes = [C .c_void_p ,KAFFINITY ] 35k32 .SetThreadAffinityMask .restype = KAFFINITY 36k32 .GetThreadGroupAffinity .argtypes = [C .c_void_p ,C .POINTER (GROUP_AFFINITY )] 37k32 .GetThreadGroupAffinity .restype = C .c_int 38k32 .SetThreadGroupAffinity .argtypes = [C .c_void_p ,C .POINTER (GROUP_AFFINITY ),C .POINTER (GROUP_AFFINITY )] 39k32 .SetThreadGroupAffinity .restype = C .c_int 40k32 .GetLogicalProcessorInformationEx .argtypes = [DWORD ,C .c_void_p ,C .POINTER (DWORD )] 41k32 .GetLogicalProcessorInformationEx .restype = C .c_int 42 43 44def api_error (name ): 45raise OSError (C .get_last_error (),f" { name } failed" ) 46 47 48def masks (records_relation ): 49needed = DWORD (0 ) 50C .set_last_error (0 ) 51ok = k32 .GetLogicalProcessorInformationEx (records_relation ,None ,C .byref (needed )) 52if ok or needed .value == 0 : 53api_error ("GetLogicalProcessorInformationEx(size query)" ) 54buf = C .create_string_buffer (needed .value ) 55if not k32 .GetLogicalProcessorInformationEx (records_relation ,C .cast (buf ,C .c_void_p ),C .byref (needed )): 56api_error ("GetLogicalProcessorInformationEx(data query)" ) 57records = [] 58pos = 0 59while pos < needed .value : 60relationship ,size = struct .unpack_from ("=II" ,buf .raw ,pos ) 61if size < 8 or pos + size > needed .value : 62raise RuntimeError (f"invalid relation record at offset { pos } : size= { size } , length= { needed . value } " ) 63# RelationNumaNodeEx is requested with 6 but, on this Windows build, 64# the returned record's Relationship field is RelationNumaNode (1). 65if relationship == records_relation or (records_relation == 6 and relationship == 1 ): 66records .append ((pos ,size )) 67pos += size 68if pos != needed .value : 69raise RuntimeError (f"record sequence ended at { pos } , expected { needed . value } " ) 70return buf ,records 71 72 73def parse_affinities (buf ,offset ,count ): 74out = [] 75for i in range (count ): 76mask ,group = struct .unpack_from ("=QH" ,buf .raw ,offset + i * C .sizeof (GROUP_AFFINITY )) 77processors = [bit for bit in range (64 )if mask & (1 << bit )] 78out .append ({"group" :group ,"mask_hex" :f"0x { mask :016X } " ,"processors" :processors }) 79return out 80 81 82def parse_cores (): 83buf ,records = masks (0 )# RelationProcessorCore 84cores = [] 85for ordinal , (pos ,size )in enumerate (records ): 86# SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX union starts at byte 8; 87# PROCESSOR_RELATIONSHIP.GroupCount is byte 22 in that union, first GROUP_AFFINITY byte 24. 88count = struct .unpack_from ("=H" ,buf .raw ,pos + 30 )[0 ] 89groups = parse_affinities (buf ,pos + 32 ,count ) 90cores .append ({"core_record" :ordinal ,"groups" :groups }) 91return cores 92 93 94def parse_numa (): 95buf ,records = masks (6 )# RelationNumaNodeEx; full masks span processor groups 96nodes = [] 97for pos ,size in records : 98node = struct .unpack_from ("=I" ,buf .raw ,pos + 8 )[0 ] 99count = struct .unpack_from ("=H" ,buf .raw ,pos + 30 )[0 ] 100groups = parse_affinities (buf ,pos + 32 ,count ) 101nodes .append ({"node" :node ,"groups" :groups ,"record_size" :size }) 102return nodes 103 104 105def affinity_snapshot (handle ): 106ga = GROUP_AFFINITY () 107if not k32 .GetThreadGroupAffinity (handle ,C .byref (ga )): 108api_error ("GetThreadGroupAffinity" ) 109pn = PROCESSOR_NUMBER () 110k32 .GetCurrentProcessorNumberEx (C .byref (pn )) 111return {"group" :int (ga .Group ),"mask_hex" :f"0x { ga . Mask :016X } " , 112"mask_processors" : [i for i in range (64 )if ga .Mask & (1 << i )], 113"current_processor" : {"group" :int (pn .Group ),"number" :int (pn .Number )}} 114 115 116def legacy_test (target_group ,target_processor ,move_group_first ): 117done = threading .Event () 118result = {} 119def body (): 120handle = k32 .GetCurrentThread () 121original = GROUP_AFFINITY () 122moved = False 123previous_mask = 0 124try : 125if move_group_first : 126ga = GROUP_AFFINITY () 127ga .Mask = KAFFINITY (1 << target_processor ).value 128ga .Group = target_group 129if not k32 .SetThreadGroupAffinity (handle ,C .byref (ga ),C .byref (original )): 130api_error ("SetThreadGroupAffinity(test setup)" ) 131moved = True 132result ["before" ]= affinity_snapshot (handle ) 133requested = KAFFINITY (1 << target_processor ).value 134C .set_last_error (0 ) 135previous_mask = k32 .SetThreadAffinityMask (handle ,requested ) 136result ["set_thread_affinity_mask" ]= {"requested_hex" :f"0x { requested :016X } " , 137"succeeded" :bool (previous_mask ),"returned_previous_hex" :f"0x { previous_mask :016X } " , 138"error" :None if previous_mask else C .get_last_error ()} 139if previous_mask : 140# Give the scheduler time to honor the single-processor mask before sampling current CPU. 141end = time .perf_counter ()+ 0.02 142while time .perf_counter ()< end : 143pass 144result ["after" ]= affinity_snapshot (handle ) 145except Exception as exc : 146result ["error" ]= f" { type ( exc ). __name__ } : { exc } " 147finally : 148# Restore only this probe thread's temporary affinity before it exits. 149if previous_mask : 150k32 .SetThreadAffinityMask (handle ,previous_mask ) 151if moved : 152k32 .SetThreadGroupAffinity (handle ,C .byref (original ),None ) 153done .set () 154t = threading .Thread (target = body ,name = f"affinity-probe-g { target_group } -p { target_processor } " ) 155t .start () 156done .wait (5 ) 157t .join (5 ) 158if t .is_alive (): 159raise RuntimeError ("affinity test thread did not finish" ) 160result ["expected_processor" ]= {"group" :target_group ,"number" :target_processor } 161return result 162 163 164def main (): 165group_count = int (k32 .GetActiveProcessorGroupCount ()) 166group_counts = [int (k32 .GetActiveProcessorCount (i ))for i in range (group_count )] 167cores = parse_cores () 168numa = parse_numa () 169by_group = {g : []for g in range (group_count )} 170for core in cores : 171for entry in core ["groups" ]: 172by_group .setdefault (entry ["group" ], []).append (entry ["processors" ]) 173summaries = {} 174for group ,core_lists in by_group .items (): 175summaries [str (group )]= { 176"physical_core_records" :len (core_lists ), 177"logical_processors_in_core_records" :sum (len (x )for x in core_lists ), 178"representative_physical_core_logical_ids" : [x [0 ]for x in core_lists ], 179"first_4_core_smt_masks" :core_lists [:4 ], 180"last_2_core_smt_masks" :core_lists [- 2 :], 181 } 182tests = [] 183# The first test requests a group-0 flat CPU ID on a newly created thread, 184# which inherits this process's primary group. The second sets group 1 185# explicitly, showing that the legacy mask is group-relative once the group 186# is selected. The default engine path has no SetThreadGroupAffinity call. 187reps = {g : (core_lists [0 ][0 ]if core_lists and core_lists [0 ]else 0 ) 188for g ,core_lists in by_group .items ()} 189if 0 in reps : 190tests .append ({"case" :"legacy_mask_for_flattened_group0_core_on_inherited_primary_group" , 191"target_group" :0 ,"target_processor" :reps [0 ], 192"move_group_first" :False ,"result" :legacy_test (0 ,reps [0 ],False )}) 193if 1 in reps : 194tests .append ({"case" :"group1_explicit_group_affinity_then_legacy_mask" ,"target_group" :1 , 195"target_processor" :reps [1 ],"move_group_first" :True , 196"result" :legacy_test (1 ,reps [1 ],True )}) 197result = { 198"probe" :"windows_processor_groups_affinity_probe.py" , 199"safety" :"Separate helper process. Affinity modified only on its own short-lived Python test threads; no Strata/model/server/process affinity was queried or changed." , 200"timestamp_local" :time .strftime ("%Y-%m-%d %H:%M:%S %Z" ), 201"os" : {"platform" :platform .platform (),"version" :platform .version (),"python" :sys .version , 202"pointer_bits" :C .sizeof (C .c_void_p )* 8 ,"processor_count" :os .cpu_count ()}, 203"helper_main_thread_affinity" :affinity_snapshot (k32 .GetCurrentThread ()), 204"groups" : {"active_group_count" :group_count ,"active_processors_per_group" :group_counts , 205"total_active_processors_api" :int (k32 .GetActiveProcessorCount (ALL_PROCESSOR_GROUPS )), 206"physical_core_records" :len (cores ),"cores_by_group" :summaries }, 207"numa_nodes_relation_numa_node_ex" :numa , 208"legacy_set_thread_affinity_tests" :tests , 209"source_notes" : { 210"core_mask_parsing" :"SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX RelationProcessorCore; all GROUP_AFFINITY records read." , 211"numa_mask_parsing" :"RelationNumaNodeEx (relationship 6); variable GroupCount and full per-group masks read." , 212"affinity_scope" :"SetThreadGroupAffinity and SetThreadAffinityMask applied only to test threads created by this script. GetThreadGroupAffinity and GetCurrentProcessorNumberEx read back their placement." , 213 }, 214 } 215 (OUT / "probe-results.json" ).write_text (json .dumps (result ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 216json .dumps (result ,indent = 2 )) 217 218if __name__ == "__main__" : 219main ()