-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython_jit.py
More file actions
4646 lines (4026 loc) · 155 KB
/
python_jit.py
File metadata and controls
4646 lines (4026 loc) · 155 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import ctypes
import hashlib
import os
import random
import threading
import time
from ctypes import (
c_void_p,
c_int,
c_char_p,
c_ubyte,
c_uint32,
POINTER,
cast,
byref,
memmove,
)
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Optional, Any, Dict, Tuple
from monero_job import MoneroJob
from python_usage import PythonUsage
from randomx_ctypes import RandomX
import sys
import heapq
class PythonJITError(RuntimeError):
pass
@dataclass
class JITThunk:
handle: int
address: int
kind: str
_callback_ref: Any
class PythonJIT:
# Exact native callback signature from the header:
# typedef int (__cdecl* PJIT_TargetInt1)(void* user_data);
# typedef void(__cdecl* PJIT_TargetVoid1)(void* user_data);
INT_TARGET = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_void_p)
VOID_TARGET = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
def __init__(self, dll_path: str = "PythonJIT.dll") -> None:
self.dll_path = self._resolve_dll_path(dll_path)
self._dll_dir_handle = None
self._dll = self._load_dll(self.dll_path)
self._configure()
self._thunks: list[JITThunk] = []
def _resolve_dll_path(self, raw: str) -> str:
candidates: list[Path] = []
p = Path(raw)
candidates.append(p)
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
candidates.append(Path(meipass) / raw)
candidates.append(Path(__file__).resolve().parent / raw)
candidates.append(Path.cwd() / raw)
candidates.append(Path(sys.executable).resolve().parent / raw)
for cand in candidates:
try:
if cand.exists():
return str(cand.resolve())
except Exception:
continue
return str(p)
def _load_dll(self, path: str):
if not os.path.exists(path):
raise FileNotFoundError(f"PythonJIT.dll not found: {path}")
dll_dir = os.path.dirname(path)
if os.name == "nt":
try:
if dll_dir and os.path.isdir(dll_dir):
self._dll_dir_handle = os.add_dll_directory(dll_dir)
except Exception:
self._dll_dir_handle = None
# Header uses __cdecl exports, so CDLL is correct.
return ctypes.CDLL(path)
def _configure(self) -> None:
L = self._dll
L.PJIT_GetVersion.argtypes = []
L.PJIT_GetVersion.restype = ctypes.c_int
L.PJIT_GetLastErrorA.argtypes = []
L.PJIT_GetLastErrorA.restype = ctypes.c_char_p
L.PJIT_ClearLastError.argtypes = []
L.PJIT_ClearLastError.restype = None
# Use ctypes-friendly raw address variants from the header.
L.PJIT_CreateIntThunk0FromAddress.argtypes = [ctypes.c_size_t, ctypes.c_size_t]
L.PJIT_CreateIntThunk0FromAddress.restype = ctypes.c_void_p
L.PJIT_CreateVoidThunk0FromAddress.argtypes = [ctypes.c_size_t, ctypes.c_size_t]
L.PJIT_CreateVoidThunk0FromAddress.restype = ctypes.c_void_p
# Optional helpers for smoke testing Python callback addresses directly.
L.PJIT_CallInt1Address.argtypes = [ctypes.c_size_t, ctypes.c_size_t]
L.PJIT_CallInt1Address.restype = ctypes.c_int
L.PJIT_CallVoid1Address.argtypes = [ctypes.c_size_t, ctypes.c_size_t]
L.PJIT_CallVoid1Address.restype = None
L.PJIT_IsProbablyExecutableAddress.argtypes = [ctypes.c_size_t]
L.PJIT_IsProbablyExecutableAddress.restype = ctypes.c_int
L.PJIT_GetThunkAddress.argtypes = [ctypes.c_void_p]
L.PJIT_GetThunkAddress.restype = ctypes.c_void_p
L.PJIT_InvokeIntThunk0.argtypes = [ctypes.c_void_p]
L.PJIT_InvokeIntThunk0.restype = ctypes.c_int
L.PJIT_InvokeVoidThunk0.argtypes = [ctypes.c_void_p]
L.PJIT_InvokeVoidThunk0.restype = None
L.PJIT_DestroyThunk.argtypes = [ctypes.c_void_p]
L.PJIT_DestroyThunk.restype = ctypes.c_int
L.PJIT_DestroyAllThunks.argtypes = []
L.PJIT_DestroyAllThunks.restype = None
def version(self) -> int:
return int(self._dll.PJIT_GetVersion())
def last_error(self) -> str:
msg = self._dll.PJIT_GetLastErrorA()
if not msg:
return ""
return msg.decode("utf-8", errors="replace")
@staticmethod
def _ptr_value(p: Any) -> int:
return int(ctypes.cast(p, ctypes.c_void_p).value or 0)
def _require_handle(self, handle: Any) -> int:
value = self._ptr_value(handle)
if not value:
raise PythonJITError(self.last_error() or "JIT call failed")
return value
def _validate_python_target_addr(self, target_addr: int, *, user_data: int = 0) -> None:
if target_addr == 0:
raise PythonJITError("target callback address is null")
try:
is_exec = int(self._dll.PJIT_IsProbablyExecutableAddress(ctypes.c_size_t(target_addr)))
except Exception:
is_exec = 1
if not is_exec:
raise PythonJITError("Python callback address is not executable/committed")
# Smoke test the raw callback address directly first.
# This gives a much clearer failure point than creating a thunk immediately.
rc = int(self._dll.PJIT_CallInt1Address(ctypes.c_size_t(target_addr), ctypes.c_size_t(user_data)))
# If the callback ran and returned 1/0/etc that's fine. If native side trapped,
# last_error() will be populated and rc is usually 0.
err = self.last_error()
if err:
raise PythonJITError(err)
def create_int_thunk0(self, func: Callable[[Any], int], user_data: Optional[int] = None) -> JITThunk:
cb = self.INT_TARGET(func)
target_addr = self._ptr_value(cb)
user_data_addr = int(user_data or 0)
self._dll.PJIT_ClearLastError()
self._validate_python_target_addr(target_addr, user_data=user_data_addr)
handle = self._require_handle(
self._dll.PJIT_CreateIntThunk0FromAddress(
ctypes.c_size_t(target_addr),
ctypes.c_size_t(user_data_addr),
)
)
addr = self._require_handle(self._dll.PJIT_GetThunkAddress(ctypes.c_void_p(handle)))
thunk = JITThunk(handle=handle, address=addr, kind="int0", _callback_ref=cb)
self._thunks.append(thunk)
return thunk
def create_void_thunk0(self, func: Callable[[Any], None], user_data: Optional[int] = None) -> JITThunk:
cb = self.VOID_TARGET(func)
target_addr = self._ptr_value(cb)
user_data_addr = int(user_data or 0)
self._dll.PJIT_ClearLastError()
handle = self._require_handle(
self._dll.PJIT_CreateVoidThunk0FromAddress(
ctypes.c_size_t(target_addr),
ctypes.c_size_t(user_data_addr),
)
)
addr = self._require_handle(self._dll.PJIT_GetThunkAddress(ctypes.c_void_p(handle)))
thunk = JITThunk(handle=handle, address=addr, kind="void0", _callback_ref=cb)
self._thunks.append(thunk)
return thunk
def invoke_int0(self, thunk: JITThunk) -> int:
self._dll.PJIT_ClearLastError()
result = int(self._dll.PJIT_InvokeIntThunk0(ctypes.c_void_p(thunk.handle)))
err = self.last_error()
if err:
raise PythonJITError(err)
return result
def invoke_void0(self, thunk: JITThunk) -> None:
self._dll.PJIT_ClearLastError()
self._dll.PJIT_InvokeVoidThunk0(ctypes.c_void_p(thunk.handle))
err = self.last_error()
if err:
raise PythonJITError(err)
def destroy(self, thunk: JITThunk) -> None:
rc = int(self._dll.PJIT_DestroyThunk(ctypes.c_void_p(thunk.handle)))
if rc != 0:
raise PythonJITError(self.last_error() or f"DestroyThunk failed: {rc}")
self._thunks = [x for x in self._thunks if x.handle != thunk.handle]
def close(self) -> None:
try:
self._dll.PJIT_DestroyAllThunks()
finally:
self._thunks.clear()
if self._dll_dir_handle is not None:
try:
self._dll_dir_handle.close()
except Exception:
pass
self._dll_dir_handle = None
def __del__(self):
try:
self.close()
except Exception:
pass
class _ClassEventLogMixin:
"""
Shared sparse natural-event logger for runtime classes.
"""
def _evt_init(
self,
*,
class_prefix: str,
logger: Optional[Callable[[str], None]],
cooldowns: Optional[dict[str, float]] = None,
phrases: Optional[dict[str, list[str]]] = None,
) -> None:
self.logger = logger or (lambda s: None)
self._evt_prefix = str(class_prefix)
self._evt_last_at: dict[str, float] = {}
self._evt_last_phrase: dict[str, str] = {}
self._evt_rng = random.Random(
int(time.time() * 1_000_000) ^ id(self) ^ hash(self._evt_prefix)
)
self._evt_cooldowns = dict(cooldowns or {})
self._evt_phrases = dict(phrases or {})
def _evt_write(self, text: str) -> None:
try:
self.logger(text)
except Exception:
pass
def _evt_allowed(self, key: str, cooldown: Optional[float] = None) -> bool:
now = time.perf_counter()
cd = float(
self._evt_cooldowns.get(
key,
45.0 if cooldown is None else cooldown,
)
)
last = float(self._evt_last_at.get(key, 0.0))
if (now - last) < cd:
return False
self._evt_last_at[key] = now
return True
def _evt_pick(self, key: str, phrases: Optional[list[str]] = None) -> str:
pool = list(phrases or self._evt_phrases.get(key, []))
if not pool:
return key
last = self._evt_last_phrase.get(key, "")
if len(pool) > 1 and last in pool:
pool = [p for p in pool if p != last]
picked = self._evt_rng.choice(pool)
self._evt_last_phrase[key] = picked
return picked
def _evt_emit(
self,
key: str,
*,
details: str = "",
phrases: Optional[list[str]] = None,
cooldown: Optional[float] = None,
force: bool = False,
) -> None:
if not force and not self._evt_allowed(key, cooldown):
return
phrase = self._evt_pick(key, phrases)
if details:
self._evt_write(f"[{self._evt_prefix}] {phrase} | {details}")
else:
self._evt_write(f"[{self._evt_prefix}] {phrase}")
class _RxHashAdvanceLane(_ClassEventLogMixin):
"""
Advanced worker-local RandomX lane.
Optimized for maximum HPS (Hashes Per Second) and reduced Python overhead.
"""
BEGIN_LOG_EVERY_N_ROUNDS = 6
BEGIN_LOG_MIN_EXPECTED_HASHES = 128
BEGIN_LOG_FORCE_EXPECTED_HASHES = 4096
FINISH_LOG_MIN_HASHES = 262144
HIT_LOG_MIN_IMPROVEMENT_RATIO = 0.95
__slots__ = (
"worker_index", "owner_key", "_hash_into", "_vm", "_blob_buf", "_out_buf",
"_job_id", "_generation", "_target64", "_expected_hashes", "_hashes",
"_hits", "_failures", "_consecutive_failures", "_best_tail64", "_best_nonce_u32",
"_last_error", "_opened_at", "_active", "_summary_enabled", "_warmed",
"_last_logged_job", "_last_logged_generation", "_last_logged_bucket",
"_seen_any_begin", "_logged_begin_for_current_round", "_last_hit_logged_tail64",
)
# Class-level static data for threading safety
_GLOBAL_EVT_MU = threading.RLock()
_GLOBAL_SCOPE_NEXT_AT: Dict[Tuple, float] = {}
_GLOBAL_SCOPE_SUPPRESSED: Dict[Tuple, int] = {}
def __init__(
self,
*,
worker_index: Optional[int] = None,
owner_key: Optional[str] = None,
logger: Optional[Callable[[str], None]] = None,
) -> None:
# Use fast int conversion to avoid overhead
self.worker_index = None if worker_index is None else int(worker_index)
self.owner_key = (
str(owner_key)
if owner_key is not None
else (f"worker-{self.worker_index}" if self.worker_index is not None else "rx-advance")
)
# Initialize buffers early to avoid None checks
self._hash_into = None
self._vm = None
self._blob_buf = None
self._out_buf = None
# State vars
self._job_id = ""
self._generation = 0
self._target64 = 0xFFFFFFFFFFFFFFFF
self._expected_hashes = 0
self._hashes = 0
self._hits = 0
self._failures = 0
self._consecutive_failures = 0
self._best_tail64 = 0xFFFFFFFFFFFFFFFF
self._best_nonce_u32 = -1
self._last_error = ""
self._opened_at = 0.0
self._active = False
self._summary_enabled = False
self._warmed = False
# Logging state
self._last_logged_job = ""
self._last_logged_generation = 0
self._last_logged_bucket = -1
self._seen_any_begin = False
self._logged_begin_for_current_round = False
self._last_hit_logged_tail64 = 0xFFFFFFFFFFFFFFFF
# Setup event system with minimal overhead
self._evt_init(
class_prefix="RxHashAdvance",
logger=logger,
cooldowns={
"begin": 30.0, "warmup": 40.0, "progress": 60.0, "hit": 30.0,
"error": 60.0, "finish": 30.0, "clear": 60.0,
},
phrases={
"begin": ["the advanced rx lane aligned", "a smarter hashing lane locked on"],
"warmup": ["the rx lane warmed clean", "the hashing lane primed success"],
"progress": ["the rx lane chewed steadily", "the hashing lane built distance"],
"hit": ["the lane surfaced a clean hit", "a sharper tail64 rose"],
"error": ["the advanced rx lane caught a fault", "the hashing lane tripped"],
"finish": ["the advanced rx lane wrapped a slice", "the hashing lane closed out"],
"clear": ["the advanced rx lane cooled back", "the hashing lane stepped down"],
},
)
@staticmethod
def _u32(v: int) -> int:
return int(v) & 0xFFFFFFFF
@staticmethod
def _u64(v: int) -> int:
return int(v) & 0xFFFFFFFFFFFFFFFF
# --- OPTIMIZED: Fast tail64 extraction ---
# Removed redundant int() casts as bytearray/bytes indexing returns int directly
@staticmethod
def _tail64_fast(out_buf) -> int:
# Ensure out_buf is buffer-like. If bytes/bytearray, indexing is fast.
# Optimization: Direct integer arithmetic on extracted bytes
return (
out_buf[24] |
(out_buf[25] << 8) |
(out_buf[26] << 16) |
(out_buf[27] << 24) |
(out_buf[28] << 32) |
(out_buf[29] << 40) |
(out_buf[30] << 48) |
(out_buf[31] << 56)
)
@staticmethod
def _count_bucket(count: int) -> int:
count = max(0, int(count))
if count == 0: return 0
# Simplified thresholding for fast branch prediction
if count <= 0: return 0
if count <= 8: return 8
if count <= 16: return 16
if count <= 32: return 32
if count <= 64: return 64
if count <= 128: return 128
if count <= 256: return 256
if count <= 512: return 512
if count <= 1024: return 1024
if count <= 4096: return 4096
return 16384
# --- OPTIMIZED: Scoped Event Emission (Locks & Dictionaries) ---
def _scoped_evt_emit(
self,
key: str,
*,
scope_key: tuple,
details: str = "",
cooldown: Optional[float] = None,
force: bool = False,
phrases: Optional[list[str]] = None,
) -> bool:
now = time.perf_counter()
cd = float(self._evt_cooldowns.get(key, 45.0 if cooldown is None else cooldown))
# Local scope dict lookups to minimize global access overhead
suppressed = 0
with self._GLOBAL_EVT_MU:
next_at = float(self._GLOBAL_SCOPE_NEXT_AT.get(scope_key, 0.0))
if not force and now < next_at:
curr_suppressed = self._GLOBAL_SCOPE_SUPPRESSED.get(scope_key, 0)
self._GLOBAL_SCOPE_SUPPRESSED[scope_key] = curr_suppressed + 1
return False
suppressed = int(self._GLOBAL_SCOPE_SUPPRESSED.pop(scope_key, 0))
self._GLOBAL_SCOPE_NEXT_AT[scope_key] = now + cd
phrase = self._evt_pick(key, phrases)
extra = f" suppressed={suppressed}" if suppressed > 0 else ""
if details:
self._evt_write(f"[{self._evt_prefix}] {phrase} | {details}{extra}")
else:
self._evt_write(f"[{self._evt_prefix}] {phrase}{extra}")
return True
def _job_evt_emit(self, key: str, *, details: str = "", cooldown: Optional[float] = None, force: bool = False, phrases: Optional[list[str]] = None) -> bool:
# Hoisted tuple creation slightly for speed, kept logic identical
return self._scoped_evt_emit(
key,
scope_key=(self._evt_prefix, "job", key, self._job_id, int(self._generation)),
details=details, cooldown=cooldown, force=force, phrases=phrases,
)
def _owner_evt_emit(self, key: str, *, details: str = "", cooldown: Optional[float] = None, force: bool = False, phrases: Optional[list[str]] = None) -> bool:
return self._scoped_evt_emit(
key,
scope_key=(self._evt_prefix, "owner", key, self.owner_key),
details=details, cooldown=cooldown, force=force, phrases=phrases,
)
def _class_evt_emit(self, key: str, *, details: str = "", cooldown: Optional[float] = None, force: bool = False, phrases: Optional[list[str]] = None) -> bool:
return self._scoped_evt_emit(
key,
scope_key=(self._evt_prefix, "class", key),
details=details, cooldown=cooldown, force=force, phrases=phrases,
)
def _should_sample_begin_round(
self,
*,
job_id: str,
generation: int,
expected_hashes: int,
force_log: bool,
) -> bool:
if force_log: return True
expected_hashes = max(0, int(expected_hashes))
if expected_hashes < self.BEGIN_LOG_MIN_EXPECTED_HASHES: return False
if expected_hashes >= self.BEGIN_LOG_FORCE_EXPECTED_HASHES: return True
raw = f"{job_id}|{int(generation)}".encode("utf-8", "ignore")
hv = int.from_bytes(hashlib.blake2s(raw, digest_size=8).digest(), "little", signed=False)
return (hv % int(self.BEGIN_LOG_EVERY_N_ROUNDS)) == 0
def begin(
self,
*,
hash_into, vm, blob_buf, out_buf,
job_id: str, generation: int, target64: int,
expected_hashes: int, enable_summary_log: bool = False,
force_log: bool = False,
) -> None:
# Local var hoisting for rapid state reset
self._hash_into = hash_into
self._vm = vm
self._blob_buf = blob_buf
self._out_buf = out_buf
self._job_id = str(job_id)
self._generation = int(generation)
self._target64 = self._u64(target64)
self._expected_hashes = max(0, int(expected_hashes))
# Fast reset
self._hashes = 0
self._hits = 0
self._failures = 0
self._consecutive_failures = 0
self._best_tail64 = 0xFFFFFFFFFFFFFFFF
self._best_nonce_u32 = -1
self._last_error = ""
self._opened_at = time.perf_counter()
self._active = True
self._summary_enabled = bool(enable_summary_log)
self._warmed = False
self._last_hit_logged_tail64 = 0xFFFFFFFFFFFFFFFF
# Bucket calc
bucket = self._count_bucket(self._expected_hashes)
round_changed = (
(self._job_id != self._last_logged_job) or
(self._generation != self._last_logged_generation) or
(bucket != self._last_logged_bucket)
)
if round_changed:
self._logged_begin_for_current_round = False
should_attempt_begin = (
force_log or (
round_changed and not self._logged_begin_for_current_round and
self._should_sample_begin_round(
job_id=self._job_id,
generation=self._generation,
expected_hashes=self._expected_hashes,
force_log=force_log,
)
)
)
if should_attempt_begin:
# Inline details for slightly less tuple creation overhead
details = (
f"job={self._job_id} gen={self._generation} "
f"owner={self.owner_key} expected={self._expected_hashes}"
)
emitted = self._job_evt_emit(
"begin", details=details, cooldown=60.0, force=force_log,
)
if emitted:
self._logged_begin_for_current_round = True
# Update last logged for next round
self._last_logged_job = self._job_id
self._last_logged_generation = self._generation
self._last_logged_bucket = bucket
self._seen_any_begin = True
def warmup(self) -> None:
if not self._active or self._hash_into is None:
raise RuntimeError("RxHashAdvanceLane is not active")
if self._warmed:
return
try:
self._hash_into(self._vm, self._blob_buf, self._out_buf)
except Exception as e:
self._failures += 1
self._consecutive_failures += 1
self._last_error = f"{type(e).__name__}: {e}"
# Local var cache for error details
err_msg = (
f"owner={self.owner_key} job={self._job_id} gen={self._generation} "
f"phase=warmup failures={self._failures} err={self._last_error[:220]}"
)
self._class_evt_emit("error", details=err_msg, cooldown=90.0)
raise
self._warmed = True
# Local var cache for warmup details
wmsg = f"owner={self.owner_key} job={self._job_id} gen={self._generation}"
self._owner_evt_emit("warmup", details=wmsg, cooldown=80.0)
# --- OPTIMIZED: Core Hash Function (Hot Path) ---
def hash_once(self) -> int:
if not self._active or self._hash_into is None:
raise RuntimeError("RxHashAdvanceLane is not active")
try:
self._hash_into(self._vm, self._blob_buf, self._out_buf)
except Exception as e:
self._failures += 1
self._consecutive_failures += 1
self._last_error = f"{type(e).__name__}: {e}"
err_msg = (
f"owner={self.owner_key} job={self._job_id} gen={self._generation} "
f"failures={self._failures} consecutive={self._consecutive_failures} "
f"err={self._last_error[:220]}"
)
self._class_evt_emit("error", details=err_msg, cooldown=90.0)
raise
self._hashes += 1
self._consecutive_failures = 0
# Optimized Progress Check (Minimize dot access)
if self._hashes in (262144, 1048576, 4194304, 16777216):
elapsed = max(1e-9, time.perf_counter() - self._opened_at)
# Format HPS string directly for logging
hps_str = f"{(self._hashes / elapsed):.2f}"
prog_msg = (
f"owner={self.owner_key} job={self._job_id} gen={self._generation} "
f"hashes={self._hashes} hps={hps_str}"
)
self._owner_evt_emit("progress", details=prog_msg, cooldown=120.0)
return self._tail64_fast(self._out_buf)
# --- OPTIMIZED: Main Loop (Critical for Profit) ---
def hash_loop(
self,
*,
count: int, write_next_nonce, batch, stop_flag,
stale_mask: int, is_current, job_id: str,
generation: int,
) -> int:
done = 0
target64 = int(self._target64) & 0xFFFFFFFFFFFFFFFF
out_buf = self._out_buf
hash_into = self._hash_into
best_tail64 = int(self._best_tail64) & 0xFFFFFFFFFFFFFFFF
best_nonce = int(self._best_nonce_u32)
hits = int(self._hits)
last_hit = int(self._last_hit_logged_tail64)
owner = self.owner_key
j_id = self._job_id
j_gen = int(self._generation)
if hash_into is None or out_buf is None:
self._last_error = "hash_loop called while lane is not active"
return 0
safe_count = max(0, int(count or 0))
safe_stale_mask = int(stale_mask or 0)
for i in range(safe_count):
if stop_flag.is_set():
break
if safe_stale_mask >= 0 and (i & safe_stale_mask) == 0:
if not is_current(job_id, generation):
break
nonce_u32 = write_next_nonce()
if nonce_u32 is None:
break
# IMPORTANT:
# randomx.hash_into usually writes the hash into out_buf and returns None.
# So do not trust its return value as tail64.
maybe_tail64 = hash_into(self._vm, self._blob_buf, out_buf)
if maybe_tail64 is None:
tail64 = self._tail64_fast(out_buf)
else:
tail64 = int(maybe_tail64) & 0xFFFFFFFFFFFFFFFF
done += 1
if tail64 < target64:
hits += 1
if tail64 < best_tail64:
old_best = best_tail64
best_tail64 = tail64
best_nonce = int(nonce_u32) & 0xFFFFFFFF
should_log_hit = False
if self._summary_enabled:
if last_hit == 0xFFFFFFFFFFFFFFFF:
should_log_hit = True
elif old_best < 0xFFFFFFFFFFFFFFFF:
if float(tail64) <= float(old_best) * self.HIT_LOG_MIN_IMPROVEMENT_RATIO:
should_log_hit = True
if should_log_hit:
hit_msg = (
f"owner={owner} job={j_id} gen={j_gen} "
f"hits={hits} best_nonce={best_nonce} best_tail64={int(tail64)}"
)
emitted = self._owner_evt_emit("hit", details=hit_msg, cooldown=60.0)
if emitted:
last_hit = int(tail64)
batch.offer(
nonce_u32=int(nonce_u32) & 0xFFFFFFFF,
hash_hex=bytes(out_buf).hex(),
tail64=int(tail64) & 0xFFFFFFFFFFFFFFFF,
)
# Write local hot-loop state back to the object.
self._hashes += int(done)
self._hits = int(hits)
self._best_tail64 = int(best_tail64) & 0xFFFFFFFFFFFFFFFF
self._best_nonce_u32 = int(best_nonce)
self._last_hit_logged_tail64 = int(last_hit) & 0xFFFFFFFFFFFFFFFF
self._consecutive_failures = 0
return done
def finish(self, *, done_hashes: Optional[int] = None) -> None:
done = self._hashes if done_hashes is None else max(0, int(done_hashes))
elapsed = max(0.0, time.perf_counter() - self._opened_at)
hps = (float(done) / elapsed) if elapsed > 0.0 else 0.0
# Optimized finish check
should_log_finish = (
self._summary_enabled and (
self._hits > 0 or self._failures > 0 or done >= self.FINISH_LOG_MIN_HASHES
)
)
if should_log_finish:
finish_msg = (
f"job={self._job_id} gen={self._generation} "
f"owner={self.owner_key} done={done} hits={self._hits} failures={self._failures} "
f"best_nonce={self._best_nonce_u32} best_tail64={self._best_tail64} "
f"elapsed={elapsed:.6f}s hps={hps:.2f}"
)
self._job_evt_emit("finish", details=finish_msg, cooldown=60.0)
self._active = False
def clear(self) -> None:
had_state = self._active or self._hashes > 0 or self._failures > 0
old_job = self._job_id
old_generation = self._generation
old_hashes = self._hashes
old_hits = self._hits
old_failures = self._failures
# Fast state reset
self._hash_into = None
self._vm = None
self._blob_buf = None
self._out_buf = None
self._job_id = ""
self._generation = 0
self._target64 = 0xFFFFFFFFFFFFFFFF
self._expected_hashes = 0
self._hashes = 0
self._hits = 0
self._failures = 0
self._consecutive_failures = 0
self._best_tail64 = 0xFFFFFFFFFFFFFFFF
self._best_nonce_u32 = -1
self._last_error = ""
self._opened_at = 0.0
self._active = False
self._summary_enabled = False
self._warmed = False
self._last_hit_logged_tail64 = 0xFFFFFFFFFFFFFFFF
# Clear log if significant work done
if had_state and (old_hashes >= 1048576 or old_failures > 0 or old_hits > 0):
clear_msg = (
f"owner={self.owner_key} last_job={old_job} "
f"last_gen={old_generation} hashes={old_hashes} "
f"hits={old_hits} failures={old_failures}"
)
self._owner_evt_emit("clear", details=clear_msg, cooldown=120.0)
def snapshot(self) -> dict:
elapsed = max(0.0, time.perf_counter() - self._opened_at) if self._opened_at > 0.0 else 0.0
hps = (float(self._hashes) / elapsed) if elapsed > 0.0 else 0.0
return {
"owner_key": self.owner_key, "worker_index": self.worker_index,
"job_id": self._job_id, "generation": self._generation,
"expected_hashes": self._expected_hashes, "hashes": self._hashes,
"hits": self._hits, "failures": self._failures,
"consecutive_failures": self._consecutive_failures,
"best_tail64": self._best_tail64, "best_nonce_u32": self._best_nonce_u32,
"last_error": self._last_error, "elapsed_sec": elapsed,
"hps_est": hps, "active": self._active,
}
class _Tail64Probe(_ClassEventLogMixin):
"""
Hot-path-safe tail64 reader for RandomX output buffers.
Design goals:
- take tail64 extraction out of the callback body
- do not blow up logs
- avoid bytes(out_buf[24:32]) allocation in the hot loop
- keep logging limited to rare anomalies / rare summaries
- preserve a clean per-worker object model like the other helpers
Intended usage:
probe.begin(job_id=..., generation=..., target64=...)
read_tail64 = probe.read_tail64
for ...:
rx_hash_into(...)
tail64 = read_tail64(out_buf)
if tail64 < target64:
probe.note_hit(nonce_u32=nonce_u32, tail64=tail64)
...
probe.finish(done_hashes=done)
"""
__slots__ = (
"worker_index",
"owner_key",
"_job_id",
"_generation",
"_target64",
"_reads",
"_hits",
"_bad_reads",
"_best_tail64",
"_best_nonce_u32",
"_best_logged_tail64",
"_summary_enabled",
"_active",
)
_GLOBAL_EVT_MU = threading.RLock()
_GLOBAL_EVT_NEXT_AT: dict[tuple[str, str], float] = {}
_GLOBAL_EVT_SUPPRESSED: dict[tuple[str, str], int] = {}
def __init__(
self,
*,
worker_index: Optional[int] = None,
owner_key: Optional[str] = None,
logger: Optional[Callable[[str], None]] = None,
) -> None:
self.worker_index = None if worker_index is None else int(worker_index)
self.owner_key = (
str(owner_key)
if owner_key is not None
else (f"worker-{self.worker_index}" if self.worker_index is not None else "tail64-probe")
)
self._job_id = ""
self._generation = 0
self._target64 = 0xFFFFFFFFFFFFFFFF
self._reads = 0
self._hits = 0
self._bad_reads = 0
self._best_tail64 = 0xFFFFFFFFFFFFFFFF
self._best_nonce_u32 = -1
self._best_logged_tail64 = 0xFFFFFFFFFFFFFFFF
self._summary_enabled = False
self._active = False
self._evt_init(
class_prefix="Tail64Probe",
logger=logger,
cooldowns={
"bad_read": 120.0,
"best_hit": 30.0,
"summary": 60.0,
"clear": 120.0,
},
phrases={
"bad_read": [
"the tail reader stepped around a malformed buffer",
"tail64 extraction hit an unexpected buffer shape",
"the tail probe caught a bad output frame",
"a broken tail64 read was safely discarded",
],
"best_hit": [
"a sharper tail64 surfaced on this lane",
"the worker found a better tail64 than before",
"a cleaner tail64 rose to the top of this run",
"the tail probe saw a new personal best",
],
"summary": [
"the tail reader wrapped up a useful run",
"tail64 tracking settled out for this slice",
"the tail probe finished a productive pass",
"this tail64 pass came in with useful signal",
],
"clear": [
"the tail probe cooled back to idle",
"tail64 tracking was released",
"the active tail reader stood down",
"tail64 state went quiet again",
],
},
)
@staticmethod
def _u32(v: int) -> int:
return int(v) & 0xFFFFFFFF
@staticmethod
def _u64(v: int) -> int:
return int(v) & 0xFFFFFFFFFFFFFFFF
def _global_evt_emit(
self,
key: str,
*,
details: str = "",
cooldown: Optional[float] = None,
phrases: Optional[list[str]] = None,
force: bool = False,
global_scope: str = "class",
) -> None:
gate = (self._evt_prefix, str(key)) if global_scope == "class" else (self.owner_key, str(key))
now = time.perf_counter()
cd = float(
self._evt_cooldowns.get(
key,
45.0 if cooldown is None else cooldown,
)
)
suppressed = 0
with self._GLOBAL_EVT_MU:
next_at = float(self._GLOBAL_EVT_NEXT_AT.get(gate, 0.0))
if not force and now < next_at:
self._GLOBAL_EVT_SUPPRESSED[gate] = int(self._GLOBAL_EVT_SUPPRESSED.get(gate, 0)) + 1
return
suppressed = int(self._GLOBAL_EVT_SUPPRESSED.pop(gate, 0))
self._GLOBAL_EVT_NEXT_AT[gate] = now + cd
phrase = self._evt_pick(key, phrases)
extra = f" suppressed={suppressed}" if suppressed > 0 else ""
if details:
self._evt_write(f"[{self._evt_prefix}] {phrase} | {details}{extra}")
else:
self._evt_write(f"[{self._evt_prefix}] {phrase}{extra}")
def begin(
self,
*,
job_id: str,
generation: int,
target64: int,