-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeepseek_python_controller.py
More file actions
2022 lines (1768 loc) · 84.1 KB
/
deepseek_python_controller.py
File metadata and controls
2022 lines (1768 loc) · 84.1 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
#!/usr/bin/env python3
"""
Bitaxe Controller - Advanced tuning automation for Bitaxe miners
Features:
- Rule-based and AI-assisted decision making
- Learning from historical performance
- Adaptive cooldown periods
- Circuit breaker for API failures
- Prometheus metrics export
- Configuration validation
- Thread-safe status file handling
"""
import argparse
import fcntl
import json
import logging
import os
import sys
import time
import re
from contextlib import contextmanager
from dataclasses import asdict, dataclass, field
from datetime import datetime, timedelta
from enum import Enum, auto
from typing import Any, Dict, List, Optional, Tuple
from urllib import error, request
from functools import wraps
from collections import defaultdict
# Optional imports with fallbacks
try:
from prometheus_client import Counter, Gauge, Histogram, start_http_server
PROMETHEUS_AVAILABLE = True
except ImportError:
PROMETHEUS_AVAILABLE = False
try:
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
TENACITY_AVAILABLE = True
except ImportError:
TENACITY_AVAILABLE = False
# ============================================================================
# Utility Functions
# ============================================================================
def app_base_dir() -> str:
"""Get application base directory (works with PyInstaller)"""
if getattr(sys, "frozen", False):
return os.path.dirname(os.path.abspath(sys.executable))
return os.path.dirname(os.path.abspath(__file__))
def env_bool(name: str, default: bool) -> bool:
"""Parse boolean from environment variable"""
value = os.getenv(name)
if value is None:
return default
return value.strip().lower() in {"1", "true", "yes", "on"}
def env_int(name: str, default: int) -> int:
"""Parse integer from environment variable"""
value = os.getenv(name)
return int(value) if value is not None else default
def env_float(name: str, default: float) -> float:
"""Parse float from environment variable"""
value = os.getenv(name)
return float(value) if value is not None else default
def mask_sensitive_data(data: Dict[str, Any]) -> Dict[str, Any]:
"""Mask sensitive information for logging"""
masked = data.copy()
sensitive_keys = ['api_key', 'password', 'secret', 'token', 'AI_API_KEY', 'OPENAI_API_KEY']
for key in sensitive_keys:
if key in masked:
masked[key] = '***MASKED***'
key_lower = key.lower()
for data_key in list(masked.keys()):
if key_lower in data_key.lower():
masked[data_key] = '***MASKED***'
return masked
def openai_safe_config(config: 'Config') -> Dict[str, Any]:
"""Return only the config fields the model needs for a tuning decision."""
return {
"mode": config.mode,
"dry_run": config.dry_run,
"min_frequency": config.min_frequency,
"max_frequency": config.max_frequency,
"absolute_max_frequency": config.absolute_max_frequency,
"freq_step": config.freq_step,
"min_voltage": config.min_voltage,
"max_voltage": config.max_voltage,
"absolute_max_voltage": config.absolute_max_voltage,
"voltage_step": config.voltage_step,
"target_temp_c": config.target_temp_c,
"hot_temp_c": config.hot_temp_c,
"emergency_temp_c": config.emergency_temp_c,
"max_vr_temp_c": config.max_vr_temp_c,
"min_input_voltage_mv": config.min_input_voltage_mv,
"max_power_w": config.max_power_w,
"climb_power_ratio": config.climb_power_ratio,
"climb_power_gate_w": config.max_power_w * config.climb_power_ratio,
"min_fan_percent": config.min_fan_percent,
"max_fan_percent": config.max_fan_percent,
"max_error_percentage": config.max_error_percentage,
"max_domain_spread_percentage": config.max_domain_spread_percentage,
"critical_domain_spread_percentage": config.critical_domain_spread_percentage,
"step_cooldown_seconds": config.step_cooldown_seconds,
"adaptive_cooldown_enabled": config.adaptive_cooldown_enabled,
}
@contextmanager
def locked_file(path: str, mode: str = 'w'):
"""Context manager for thread-safe file operations"""
with open(path, mode) as f:
try:
fcntl.flock(f, fcntl.LOCK_EX)
yield f
finally:
fcntl.flock(f, fcntl.LOCK_UN)
# ============================================================================
# Custom Exceptions
# ============================================================================
class BitaxeError(Exception):
"""Base exception for Bitaxe controller"""
pass
class BitaxeConnectionError(BitaxeError):
"""Raised when connection to Bitaxe fails"""
pass
class BitaxeInvalidStateError(BitaxeError):
"""Raised when miner state is invalid"""
pass
class BitaxeConfigurationError(BitaxeError):
"""Raised when configuration is invalid"""
pass
class CircuitBreakerOpenError(BitaxeError):
"""Raised when circuit breaker is open"""
pass
# ============================================================================
# Circuit Breaker
# ============================================================================
class CircuitBreaker:
"""Circuit breaker pattern for API calls"""
def __init__(self, failure_threshold: int = 3, recovery_timeout: int = 60):
self.failure_threshold = failure_threshold
self.recovery_timeout = recovery_timeout
self.failures = 0
self.last_failure_time: Optional[datetime] = None
self.state = "closed" # closed, open, half-open
def call(self, func, *args, **kwargs):
"""Execute function with circuit breaker protection"""
if self.state == "open":
if datetime.now() - self.last_failure_time > timedelta(seconds=self.recovery_timeout):
self.state = "half-open"
logging.info("Circuit breaker transitioned to half-open")
else:
raise CircuitBreakerOpenError(
f"Circuit breaker is open (failed {self.failures} times)"
)
try:
result = func(*args, **kwargs)
if self.failures:
self.failures = 0
self.last_failure_time = None
if self.state == "half-open":
self.state = "closed"
logging.info("Circuit breaker closed after successful call")
return result
except Exception as e:
self.failures += 1
self.last_failure_time = datetime.now()
if self.failures >= self.failure_threshold:
self.state = "open"
logging.warning(
f"Circuit breaker opened after {self.failures} failures"
)
raise e
def reset(self):
"""Reset circuit breaker"""
self.failures = 0
self.last_failure_time = None
self.state = "closed"
logging.info("Circuit breaker reset")
# ============================================================================
# Metrics Collection
# ============================================================================
@dataclass
class Metrics:
"""Performance metrics collector"""
decisions: Dict[str, int] = field(default_factory=lambda: defaultdict(int))
actions_taken: Dict[str, int] = field(default_factory=lambda: defaultdict(int))
api_latencies: List[float] = field(default_factory=list)
errors: List[Tuple[str, str]] = field(default_factory=list) # (error_type, timestamp)
start_time: float = field(default_factory=time.time)
def record_decision(self, decision_type: str):
"""Record a decision made by the controller"""
self.decisions[decision_type] += 1
def record_action(self, action: str):
"""Record an action taken"""
self.actions_taken[action] += 1
def record_api_latency(self, latency: float):
"""Record API call latency"""
self.api_latencies.append(latency)
# Keep only last 1000 samples
if len(self.api_latencies) > 1000:
self.api_latencies = self.api_latencies[-1000:]
def record_error(self, error_type: str):
"""Record an error occurrence"""
self.errors.append((error_type, datetime.now().isoformat()))
# Keep only last 100 errors
if len(self.errors) > 100:
self.errors = self.errors[-100:]
def get_summary(self) -> Dict[str, Any]:
"""Get metrics summary"""
total_decisions = sum(self.decisions.values())
return {
"total_decisions": total_decisions,
"decision_breakdown": dict(self.decisions),
"action_breakdown": dict(self.actions_taken),
"avg_api_latency": sum(self.api_latencies) / len(self.api_latencies) if self.api_latencies else 0,
"error_count": len(self.errors),
"error_rate": len(self.errors) / total_decisions if total_decisions > 0 else 0,
"uptime_seconds": time.time() - self.start_time,
}
# ============================================================================
# Prometheus Metrics (Optional)
# ============================================================================
class PrometheusExporter:
"""Export metrics to Prometheus"""
def __init__(self, port: int = 8000):
self.port = port
self.enabled = PROMETHEUS_AVAILABLE
self.metrics = {}
if self.enabled:
self._init_metrics()
start_http_server(port)
logging.info(f"Prometheus metrics available on port {port}")
def _init_metrics(self):
"""Initialize Prometheus metrics"""
self.metrics['temperature'] = Gauge('bitaxe_temperature_celsius', 'ASIC temperature')
self.metrics['vr_temperature'] = Gauge('bitaxe_vr_temperature_celsius', 'Voltage regulator temperature')
self.metrics['hashrate'] = Gauge('bitaxe_hashrate_gh', 'Current hashrate in GH/s')
self.metrics['hashrate_10m'] = Gauge('bitaxe_hashrate_10m_gh', '10-minute average hashrate in GH/s')
self.metrics['power'] = Gauge('bitaxe_power_watts', 'Power consumption in watts')
self.metrics['frequency'] = Gauge('bitaxe_frequency_mhz', 'Core frequency in MHz')
self.metrics['voltage'] = Gauge('bitaxe_voltage_mv', 'Core voltage in mV')
self.metrics['fan_speed'] = Gauge('bitaxe_fan_percent', 'Fan speed percentage')
self.metrics['error_percentage'] = Gauge('bitaxe_error_percentage', 'Hardware error percentage')
self.metrics['performance_score'] = Gauge('bitaxe_performance_score', 'Performance score')
self.metrics['decisions_total'] = Counter('bitaxe_decisions_total', 'Total decisions made', ['type'])
self.metrics['actions_total'] = Counter('bitaxe_actions_total', 'Total actions taken', ['action'])
self.metrics['decision_latency'] = Histogram('bitaxe_decision_latency_seconds', 'Decision latency')
def update_state(self, state: 'MinerState', score: float):
"""Update metrics from miner state"""
if not self.enabled:
return
self.metrics['temperature'].set(state.temperature_c)
self.metrics['vr_temperature'].set(state.vr_temperature_c)
self.metrics['hashrate'].set(state.hashrate_gh)
self.metrics['hashrate_10m'].set(state.hashrate_10m_gh)
self.metrics['power'].set(state.power_w)
self.metrics['frequency'].set(state.frequency_mhz)
self.metrics['voltage'].set(state.voltage_mv)
self.metrics['fan_speed'].set(state.fan_percent)
self.metrics['error_percentage'].set(state.error_percentage)
self.metrics['performance_score'].set(score)
def record_decision(self, decision_type: str):
"""Record a decision"""
if self.enabled:
self.metrics['decisions_total'].labels(type=decision_type).inc()
def record_action(self, action: str):
"""Record an action"""
if self.enabled:
self.metrics['actions_total'].labels(action=action).inc()
def record_latency(self, latency: float):
"""Record decision latency"""
if self.enabled:
self.metrics['decision_latency'].observe(latency)
# ============================================================================
# Configuration
# ============================================================================
@dataclass
class Config:
"""Controller configuration with validation"""
bitaxe_url: str
loop_seconds: int = 30
mode: str = "rules"
dry_run: bool = False
auto_fan: bool = False
min_frequency: int = 425
max_frequency: int = 600
absolute_max_frequency: int = 625
freq_step: int = 25
min_voltage: int = 1100
max_voltage: int = 1300
absolute_max_voltage: int = 1150
voltage_step: int = 10
target_temp_c: float = 58.0
hot_temp_c: float = 64.0
emergency_temp_c: float = 70.0
absolute_max_emergency_temp_c: float = 70.0
cool_temp_c: float = 52.0
max_vr_temp_c: float = 90.0
absolute_max_vr_temp_c: float = 75.0
min_input_voltage_mv: int = 4800
max_power_w: float = 18.0
absolute_max_power_w: float = 18.0
climb_power_ratio: float = 0.90
min_fan_percent: int = 50
max_fan_percent: int = 100
step_cooldown_seconds: int = 180
min_hashrate_gh: float = 0.0
use_asic_options: bool = False
max_error_percentage: float = 20.0
max_domain_spread_percentage: float = 10.0
critical_domain_spread_percentage: float = 18.0
domain_spread_polls: int = 2
learning_enabled: bool = True
learning_min_samples: int = 3
learning_bad_limit: int = 2
learning_restore_margin: float = 0.03
learning_efficiency_weight: float = 0.25
adaptive_cooldown_enabled: bool = True
adaptive_min_cooldown_seconds: int = 45
adaptive_max_cooldown_seconds: int = 240
adaptive_stable_samples: int = 8
status_file: str = os.path.join(app_base_dir(), "status.json")
learning_file: str = os.path.join(app_base_dir(), "learning.json")
ai_api_url: Optional[str] = None
ai_api_key: Optional[str] = None
ai_model: Optional[str] = None
prometheus_port: int = 8000
enable_prometheus: bool = False
circuit_breaker_threshold: int = 3
circuit_breaker_timeout: int = 60
@classmethod
def from_env(cls) -> "Config":
"""Create configuration from environment variables"""
bitaxe_url = os.getenv("BITAXE_URL")
if not bitaxe_url:
raise SystemExit("BITAXE_URL is required")
config = cls(
bitaxe_url=bitaxe_url.rstrip("/"),
loop_seconds=env_int("BITAXE_LOOP_SECONDS", 30),
mode=os.getenv("BITAXE_MODE", "rules").strip().lower(),
dry_run=env_bool("BITAXE_DRY_RUN", False),
auto_fan=env_bool("BITAXE_AUTO_FAN", False),
min_frequency=env_int("BITAXE_MIN_FREQUENCY", 425),
max_frequency=env_int("BITAXE_MAX_FREQUENCY", 600),
absolute_max_frequency=env_int("BITAXE_ABSOLUTE_MAX_FREQUENCY", 625),
freq_step=env_int("BITAXE_FREQ_STEP", 25),
min_voltage=env_int("BITAXE_MIN_VOLTAGE", 1100),
max_voltage=env_int("BITAXE_MAX_VOLTAGE", 1300),
absolute_max_voltage=env_int("BITAXE_ABSOLUTE_MAX_VOLTAGE", 1150),
voltage_step=env_int("BITAXE_VOLTAGE_STEP", 10),
target_temp_c=env_float("BITAXE_TARGET_TEMP_C", 58.0),
hot_temp_c=env_float("BITAXE_HOT_TEMP_C", 64.0),
emergency_temp_c=env_float("BITAXE_EMERGENCY_TEMP_C", 70.0),
absolute_max_emergency_temp_c=env_float("BITAXE_ABSOLUTE_MAX_EMERGENCY_TEMP_C", 70.0),
cool_temp_c=env_float("BITAXE_COOL_TEMP_C", 52.0),
max_vr_temp_c=env_float("BITAXE_MAX_VR_TEMP_C", 90.0),
absolute_max_vr_temp_c=env_float("BITAXE_ABSOLUTE_MAX_VR_TEMP_C", 75.0),
min_input_voltage_mv=env_int("BITAXE_MIN_INPUT_VOLTAGE_MV", 4800),
max_power_w=env_float("BITAXE_MAX_POWER_W", 18.0),
absolute_max_power_w=env_float("BITAXE_ABSOLUTE_MAX_POWER_W", 18.0),
climb_power_ratio=env_float("BITAXE_CLIMB_POWER_RATIO", 0.90),
min_fan_percent=env_int("BITAXE_MIN_FAN_PERCENT", 50),
max_fan_percent=env_int("BITAXE_MAX_FAN_PERCENT", 100),
step_cooldown_seconds=env_int("BITAXE_STEP_COOLDOWN_SECONDS", 180),
min_hashrate_gh=env_float("BITAXE_MIN_HASHRATE_GH", 0.0),
use_asic_options=env_bool("BITAXE_USE_ASIC_OPTIONS", False),
max_error_percentage=env_float("BITAXE_MAX_ERROR_PERCENTAGE", 20.0),
max_domain_spread_percentage=env_float("BITAXE_MAX_DOMAIN_SPREAD_PERCENTAGE", 10.0),
critical_domain_spread_percentage=env_float("BITAXE_CRITICAL_DOMAIN_SPREAD_PERCENTAGE", 18.0),
domain_spread_polls=env_int("BITAXE_DOMAIN_SPREAD_POLLS", 2),
learning_enabled=env_bool("BITAXE_LEARNING_ENABLED", True),
learning_min_samples=env_int("BITAXE_LEARNING_MIN_SAMPLES", 3),
learning_bad_limit=env_int("BITAXE_LEARNING_BAD_LIMIT", 2),
learning_restore_margin=env_float("BITAXE_LEARNING_RESTORE_MARGIN", 0.03),
learning_efficiency_weight=env_float("BITAXE_LEARNING_EFFICIENCY_WEIGHT", 0.25),
adaptive_cooldown_enabled=env_bool("BITAXE_ADAPTIVE_COOLDOWN_ENABLED", True),
adaptive_min_cooldown_seconds=env_int("BITAXE_ADAPTIVE_MIN_COOLDOWN_SECONDS", 45),
adaptive_max_cooldown_seconds=env_int("BITAXE_ADAPTIVE_MAX_COOLDOWN_SECONDS", 240),
adaptive_stable_samples=env_int("BITAXE_ADAPTIVE_STABLE_SAMPLES", 8),
status_file=os.getenv("BITAXE_STATUS_FILE", os.path.join(app_base_dir(), "status.json")),
learning_file=os.getenv("BITAXE_LEARNING_FILE", os.path.join(app_base_dir(), "learning.json")),
ai_api_url=os.getenv("AI_API_URL", "https://api.openai.com/v1/responses"),
ai_api_key=os.getenv("AI_API_KEY") or os.getenv("OPENAI_API_KEY"),
ai_model=os.getenv("AI_MODEL"),
prometheus_port=env_int("PROMETHEUS_PORT", 8000),
enable_prometheus=env_bool("ENABLE_PROMETHEUS", False),
circuit_breaker_threshold=env_int("CIRCUIT_BREAKER_THRESHOLD", 3),
circuit_breaker_timeout=env_int("CIRCUIT_BREAKER_TIMEOUT", 60),
)
config.validate()
return config
def validate(self) -> None:
"""Validate configuration consistency"""
if self.mode not in {"rules", "openai"}:
raise BitaxeConfigurationError(f"Invalid mode: {self.mode}. Must be 'rules' or 'openai'")
if self.mode == "openai":
if not self.ai_api_key:
raise BitaxeConfigurationError("AI mode requires AI_API_KEY")
if not self.ai_model:
raise BitaxeConfigurationError("AI mode requires AI_MODEL")
if self.min_frequency > self.max_frequency:
raise BitaxeConfigurationError(
f"min_frequency ({self.min_frequency}) > max_frequency ({self.max_frequency})"
)
if self.min_voltage > self.max_voltage:
raise BitaxeConfigurationError(
f"min_voltage ({self.min_voltage}) > max_voltage ({self.max_voltage})"
)
if self.target_temp_c >= self.hot_temp_c:
raise BitaxeConfigurationError(
f"target_temp_c ({self.target_temp_c}) must be < hot_temp_c ({self.hot_temp_c})"
)
if self.hot_temp_c >= self.emergency_temp_c:
raise BitaxeConfigurationError(
f"hot_temp_c ({self.hot_temp_c}) must be < emergency_temp_c ({self.emergency_temp_c})"
)
if self.min_fan_percent > self.max_fan_percent:
raise BitaxeConfigurationError(
f"min_fan_percent ({self.min_fan_percent}) > max_fan_percent ({self.max_fan_percent})"
)
# Apply bounds after validation
self._apply_bounds()
def _apply_bounds(self) -> None:
"""Apply absolute bounds to configuration values"""
self.absolute_max_frequency = min(self.absolute_max_frequency, 625)
self.absolute_max_voltage = min(self.absolute_max_voltage, 1150)
self.absolute_max_emergency_temp_c = min(self.absolute_max_emergency_temp_c, 70.0)
self.absolute_max_vr_temp_c = min(self.absolute_max_vr_temp_c, 75.0)
self.absolute_max_power_w = min(self.absolute_max_power_w, 18.0)
self.max_frequency = min(self.max_frequency, self.absolute_max_frequency)
self.max_voltage = min(self.max_voltage, self.absolute_max_voltage)
self.emergency_temp_c = min(self.emergency_temp_c, self.absolute_max_emergency_temp_c)
self.max_vr_temp_c = min(self.max_vr_temp_c, self.absolute_max_vr_temp_c)
self.max_power_w = min(self.max_power_w, self.absolute_max_power_w)
self.climb_power_ratio = max(0.50, min(0.99, self.climb_power_ratio))
self.min_frequency = min(self.min_frequency, self.max_frequency)
self.min_voltage = min(self.min_voltage, self.max_voltage)
self.hot_temp_c = min(self.hot_temp_c, self.emergency_temp_c)
self.target_temp_c = min(self.target_temp_c, self.hot_temp_c)
self.cool_temp_c = min(self.cool_temp_c, self.target_temp_c)
# ============================================================================
# Data Models
# ============================================================================
@dataclass
class MinerState:
"""Current miner state"""
temperature_c: float
vr_temperature_c: float
frequency_mhz: int
voltage_mv: int
frequency_options: List[int]
voltage_options: List[int]
fan_percent: int
hashrate_gh: float
hashrate_10m_gh: float
error_percentage: float
domain_spread_percentage: float
offline_domain_count: int
power_w: float
input_voltage_mv: int
raw: Dict[str, Any]
timestamp: float = field(default_factory=time.time)
@dataclass
class LearningRecord:
"""Learning record for a specific frequency/voltage combination"""
frequency_mhz: int
voltage_mv: int
samples: int = 0
stable_samples: int = 0
unstable_samples: int = 0
best_hashrate_gh: float = 0.0
avg_hashrate_gh: float = 0.0
best_hashrate_10m_gh: float = 0.0
avg_hashrate_10m_gh: float = 0.0
best_efficiency_gh_per_w: float = 0.0
avg_efficiency_gh_per_w: float = 0.0
best_score: float = 0.0
avg_score: float = 0.0
min_score: float = 0.0
max_total_penalty: float = 0.0
max_temperature_c: float = 0.0
max_power_w: float = 0.0
max_error_percentage: float = 0.0
max_domain_spread_percentage: float = 0.0
last_seen_at: str = ""
last_unstable_at: str = ""
@property
def key(self) -> str:
return f"{self.frequency_mhz}:{self.voltage_mv}"
class ControllerState(Enum):
"""Controller state machine states"""
NORMAL = auto()
COOLDOWN = auto()
EMERGENCY = auto()
LEARNING = auto()
RECOVERY = auto()
# ============================================================================
# Helper Functions
# ============================================================================
def get_first_number(data: Dict[str, Any], *keys: str, default: float = 0.0) -> float:
"""Get first numeric value from dictionary using multiple keys"""
for key in keys:
if key in data and data[key] not in (None, ""):
try:
return float(data[key])
except (TypeError, ValueError):
continue
return default
def clamp(value: int, low: int, high: int) -> int:
"""Clamp integer value between low and high"""
return max(low, min(high, value))
def parse_int_list(value: Any) -> List[int]:
"""Parse list of integers from various formats"""
if not isinstance(value, list):
return []
out = []
for item in value:
try:
out.append(int(item))
except (TypeError, ValueError):
continue
return sorted(set(out))
def parse_domain_metrics(data: Dict[str, Any]) -> Tuple[float, int]:
"""Parse domain spread percentage and offline domain count"""
domains = data.get("hashrateMonitor", {}).get("asics", [{}])[0].get("domains", [])
if not isinstance(domains, list):
return 0.0, 0
numeric_domains: List[float] = []
for item in domains:
try:
numeric_domains.append(float(item))
except (TypeError, ValueError):
numeric_domains.append(0.0)
if not numeric_domains:
return 0.0, 0
active_domains = [value for value in numeric_domains if value > 0]
offline_count = len(numeric_domains) - len(active_domains)
if not active_domains:
return 100.0, offline_count
average = sum(active_domains) / len(active_domains)
weakest = min(active_domains)
spread = ((average - weakest) / average) * 100 if average > 0 else 0.0
return spread, offline_count
def prev_setting(current: int, minimum: int, step: int, options: List[int], use_options: bool) -> int:
"""Get previous valid setting (decrease)"""
if use_options and options:
allowed = [value for value in options if minimum <= value < current]
return allowed[-1] if allowed else max(minimum, min(options))
return clamp(current - step, minimum, current)
def next_setting(current: int, maximum: int, step: int, options: List[int], use_options: bool) -> int:
"""Get next valid setting (increase)"""
if use_options and options:
allowed = [value for value in options if current < value <= maximum]
return allowed[0] if allowed else min(maximum, max(options))
return clamp(current + step, current, maximum)
def efficiency_gh_per_w(state: MinerState) -> float:
"""Calculate efficiency in GH/s per watt"""
return state.hashrate_10m_gh / state.power_w if state.power_w > 0 else 0.0
def performance_metrics(state: MinerState, config: Config) -> Dict[str, float]:
"""Calculate detailed performance metrics"""
stable_hashrate = state.hashrate_10m_gh or state.hashrate_gh
efficiency = efficiency_gh_per_w(state)
power_ratio = state.power_w / config.max_power_w if config.max_power_w and state.power_w else 0.0
temp_ratio = state.temperature_c / config.hot_temp_c if config.hot_temp_c else 1.0
fan_ratio = state.fan_percent / config.max_fan_percent if config.max_fan_percent else 1.0
error_ratio = state.error_percentage / config.max_error_percentage if config.max_error_percentage else 1.0
domain_ratio = (
state.domain_spread_percentage / config.max_domain_spread_percentage
if config.max_domain_spread_percentage
else 1.0
)
base_score = stable_hashrate + (efficiency * config.learning_efficiency_weight)
power_penalty = max(0.0, power_ratio - 0.92) * stable_hashrate * 2.0
temp_penalty = max(0.0, temp_ratio - 0.90) * 120.0
fan_penalty = max(0.0, fan_ratio - 0.85) * 80.0
error_penalty = max(0.0, error_ratio - 0.20) * 80.0
domain_penalty = max(0.0, domain_ratio - 0.70) * 100.0
total_penalty = power_penalty + temp_penalty + fan_penalty + error_penalty + domain_penalty
return {
"stable_hashrate_gh": stable_hashrate,
"efficiency_gh_per_w": efficiency,
"base_score": base_score,
"power_penalty": power_penalty,
"temperature_penalty": temp_penalty,
"fan_penalty": fan_penalty,
"error_penalty": error_penalty,
"domain_spread_penalty": domain_penalty,
"total_penalty": total_penalty,
"score": base_score - total_penalty,
}
def performance_score(state: MinerState, config: Config) -> float:
"""Calculate overall performance score"""
return performance_metrics(state, config)["score"]
def guardrail_metrics(state: MinerState, config: Config) -> Dict[str, Any]:
"""Summarize guardrail headroom and climb eligibility for prompts/status."""
climb_power_gate = config.max_power_w * config.climb_power_ratio
power_ratio = state.power_w / config.max_power_w if config.max_power_w and state.power_w else 0.0
temp_ratio = state.temperature_c / config.hot_temp_c if config.hot_temp_c else 1.0
vr_ratio = state.vr_temperature_c / config.max_vr_temp_c if config.max_vr_temp_c else 1.0
error_ratio = state.error_percentage / config.max_error_percentage if config.max_error_percentage else 1.0
domain_ratio = (
state.domain_spread_percentage / config.max_domain_spread_percentage
if config.max_domain_spread_percentage
else 1.0
)
stable = (
state.temperature_c < config.hot_temp_c
and state.vr_temperature_c < config.max_vr_temp_c
and (not state.input_voltage_mv or state.input_voltage_mv >= config.min_input_voltage_mv)
and (not state.power_w or state.power_w <= config.max_power_w)
and state.error_percentage < config.max_error_percentage
and state.offline_domain_count == 0
and state.domain_spread_percentage < config.max_domain_spread_percentage
)
can_climb = stable and state.temperature_c <= config.cool_temp_c and state.power_w < climb_power_gate
return {
"stable": stable,
"can_climb_by_power": state.power_w < climb_power_gate,
"can_climb": can_climb,
"climb_power_gate_w": climb_power_gate,
"power_ratio": power_ratio,
"temperature_ratio": temp_ratio,
"vr_temperature_ratio": vr_ratio,
"error_ratio": error_ratio,
"domain_spread_ratio": domain_ratio,
"next_frequency_mhz": next_setting(
state.frequency_mhz,
config.max_frequency,
config.freq_step,
state.frequency_options,
config.use_asic_options,
),
"next_voltage_mv": next_setting(
state.voltage_mv,
config.max_voltage,
config.voltage_step,
state.voltage_options,
config.use_asic_options,
),
}
# ============================================================================
# Learning Store
# ============================================================================
class LearningStore:
"""Persistent storage for learning data"""
def __init__(self, path: str):
self.path = path
self.records: Dict[str, LearningRecord] = {}
self._frequency_index: Dict[int, List[str]] = {}
self._voltage_index: Dict[int, List[str]] = {}
self.load()
def _update_indexes(self, record: LearningRecord):
"""Update search indexes"""
key = record.key
self._frequency_index.setdefault(record.frequency_mhz, []).append(key)
self._voltage_index.setdefault(record.voltage_mv, []).append(key)
def _remove_from_indexes(self, record: LearningRecord):
"""Remove from search indexes"""
key = record.key
if record.frequency_mhz in self._frequency_index:
self._frequency_index[record.frequency_mhz] = [
k for k in self._frequency_index[record.frequency_mhz] if k != key
]
if record.voltage_mv in self._voltage_index:
self._voltage_index[record.voltage_mv] = [
k for k in self._voltage_index[record.voltage_mv] if k != key
]
def load(self) -> None:
"""Load learning data from disk"""
if not os.path.exists(self.path):
return
try:
with open(self.path, "r", encoding="utf-8") as handle:
data = json.load(handle)
for item in data.get("records", []):
record = LearningRecord(**item)
self.records[record.key] = record
self._update_indexes(record)
except Exception as exc:
logging.warning("failed to load learning file %s: %s", self.path, exc)
def save(self) -> None:
"""Save learning data to disk"""
payload = {
"updated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"records": [asdict(record) for record in self.records.values()],
}
tmp_path = f"{self.path}.tmp"
try:
with locked_file(tmp_path, 'w') as handle:
json.dump(payload, handle, indent=2)
os.replace(tmp_path, self.path)
except Exception as exc:
logging.error("Failed to save learning data: %s", exc)
def record(self, state: MinerState, stable: bool, config: Config) -> LearningRecord:
"""Record a new sample for the current frequency/voltage"""
key = f"{state.frequency_mhz}:{state.voltage_mv}"
record = self.records.get(key)
if record is None:
record = LearningRecord(frequency_mhz=state.frequency_mhz, voltage_mv=state.voltage_mv)
self.records[key] = record
self._update_indexes(record)
record.samples += 1
if stable:
record.stable_samples += 1
else:
record.unstable_samples += 1
record.last_unstable_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
previous_total = record.samples - 1
efficiency = efficiency_gh_per_w(state)
metrics = performance_metrics(state, config)
score = metrics["score"]
# Update averages
record.avg_hashrate_gh = (
((record.avg_hashrate_gh * previous_total) + state.hashrate_gh) / record.samples
if record.samples > 1
else state.hashrate_gh
)
record.avg_hashrate_10m_gh = (
((record.avg_hashrate_10m_gh * previous_total) + state.hashrate_10m_gh) / record.samples
if record.samples > 1
else state.hashrate_10m_gh
)
record.avg_efficiency_gh_per_w = (
((record.avg_efficiency_gh_per_w * previous_total) + efficiency) / record.samples
if record.samples > 1
else efficiency
)
record.avg_score = (
((record.avg_score * previous_total) + score) / record.samples
if record.samples > 1
else score
)
# Update best values
record.best_hashrate_gh = max(record.best_hashrate_gh, state.hashrate_gh)
record.best_hashrate_10m_gh = max(record.best_hashrate_10m_gh, state.hashrate_10m_gh)
record.best_efficiency_gh_per_w = max(record.best_efficiency_gh_per_w, efficiency)
record.best_score = max(record.best_score, score)
record.min_score = score if record.samples == 1 else min(record.min_score, score)
# Update maxima
record.max_total_penalty = max(record.max_total_penalty, metrics["total_penalty"])
record.max_temperature_c = max(record.max_temperature_c, state.temperature_c)
record.max_power_w = max(record.max_power_w, state.power_w)
record.max_error_percentage = max(record.max_error_percentage, state.error_percentage)
record.max_domain_spread_percentage = max(record.max_domain_spread_percentage, state.domain_spread_percentage)
record.last_seen_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
return record
def get(self, frequency_mhz: int, voltage_mv: int) -> Optional[LearningRecord]:
"""Get record for specific frequency/voltage"""
return self.records.get(f"{frequency_mhz}:{voltage_mv}")
def get_by_frequency(self, frequency_mhz: int) -> List[LearningRecord]:
"""Get all records for a frequency"""
return [self.records[k] for k in self._frequency_index.get(frequency_mhz, [])]
def get_by_voltage(self, voltage_mv: int) -> List[LearningRecord]:
"""Get all records for a voltage"""
return [self.records[k] for k in self._voltage_index.get(voltage_mv, [])]
def best_stable(self, config: Config) -> Optional[LearningRecord]:
"""Find the best stable configuration based on learning data"""
candidates = [
record
for record in self.records.values()
if record.stable_samples >= config.learning_min_samples
and record.unstable_samples < config.learning_bad_limit
and config.min_frequency <= record.frequency_mhz <= config.max_frequency
and config.min_voltage <= record.voltage_mv <= config.max_voltage
and record.max_power_w <= config.max_power_w
and record.max_temperature_c < config.hot_temp_c
and record.max_error_percentage < config.max_error_percentage
and record.max_domain_spread_percentage < config.max_domain_spread_percentage
]
if not candidates:
return None
return max(candidates, key=lambda record: (
record.best_score, record.avg_score, record.best_hashrate_10m_gh, record.frequency_mhz
))
def is_bad_candidate(self, frequency_mhz: int, voltage_mv: int, config: Config) -> bool:
"""Check if a frequency/voltage combination is known to be bad"""
record = self.get(frequency_mhz, voltage_mv)
return bool(record and record.unstable_samples >= config.learning_bad_limit and record.stable_samples == 0)
def summary(self, config: Config) -> Dict[str, Any]:
"""Get summary of learning data"""
best = self.best_stable(config)
return {
"enabled": config.learning_enabled,
"record_count": len(self.records),
"best_stable": asdict(best) if best else None,
"bad_candidates": [
asdict(record)
for record in self.records.values()
if record.unstable_samples >= config.learning_bad_limit and record.stable_samples == 0
],
}
# ============================================================================
# Bitaxe Client
# ============================================================================
class BitaxeClient:
"""Client for interacting with Bitaxe API"""
def __init__(self, base_url: str, timeout: int = 10):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
self.circuit_breaker = CircuitBreaker()
def _request(self, method: str, path: str, payload: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Make HTTP request to Bitaxe API with retry logic"""
def _do_request():
body = None
headers = {}
if payload is not None:
body = json.dumps(payload).encode("utf-8")
headers["Content-Type"] = "application/json"
req = request.Request(f"{self.base_url}{path}", data=body, headers=headers, method=method)
start_time = time.time()
try:
with request.urlopen(req, timeout=self.timeout) as response:
latency = time.time() - start_time
text = response.read().decode("utf-8")
return json.loads(text) if text else {}
except error.HTTPError as e:
raise BitaxeConnectionError(f"HTTP {e.code}: {e.reason}") from e
except error.URLError as e:
raise BitaxeConnectionError(f"Connection failed: {e.reason}") from e
# Apply circuit breaker
return self.circuit_breaker.call(_do_request)
def get_info(self) -> Dict[str, Any]:
"""Get system info"""
return self._request("GET", "/api/system/info")
def get_asic(self) -> Dict[str, Any]:
"""Get ASIC info"""
return self._request("GET", "/api/system/asic")
def patch_system(self, payload: Dict[str, Any]) -> Dict[str, Any]:
"""Update system settings"""
return self._request("PATCH", "/api/system", payload)
def health_check(self) -> bool:
"""Check if Bitaxe is reachable"""
try:
self.get_info()
return True
except Exception:
return False
# ============================================================================
# AI Advisor
# ============================================================================
class AiAdvisor:
"""AI-powered advisor for tuning decisions"""
def __init__(self, config: Config):
self.url = config.ai_api_url
self.api_key = config.ai_api_key
self.model = config.ai_model
self.circuit_breaker = CircuitBreaker(
failure_threshold=config.circuit_breaker_threshold,
recovery_timeout=config.circuit_breaker_timeout
)
def extract_output_text(self, data: Dict[str, Any]) -> str:
"""Extract text output from various response formats"""
if data.get("status") == "incomplete":
reason = data.get("incomplete_details", {}).get("reason", "unknown")
raise RuntimeError(f"AI response incomplete: {reason}")
if data.get("output_text"):
return str(data["output_text"]).strip()