-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
3948 lines (3423 loc) · 177 KB
/
Copy pathapi.py
File metadata and controls
3948 lines (3423 loc) · 177 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
# ============================================================
# 🚀 DFE-AutoML Streaming Backend v17.0
# ------------------------------------------------------------
# Research-aligned stack:
# RL • Explainability • Two-Speed Fairness • Mapper • Drift
# + Fairness Scope Manager • Streaming Fairness Measurement
# + Dynamic Fairness Envelope • Chunked Streaming Execution
# + Hard Thread Safety • CO2 Tracking (CodeCarbon)
#
# v17.0 upgrades:
# ✅ Fixed controller fairness control mismatch
# ✅ Controller now uses SFM-aligned fairness control signal
# ✅ Added DynamicFairnessEnvelope integration
# ✅ Added SFM telemetry to controller + response contract
# ✅ Added DFE telemetry to controller + response contract
# ✅ Preserved legacy outputs during transition
# ✅ Preserved scope-aware end-to-end decision_context propagation
# ============================================================
from __future__ import annotations
import copy
import inspect
import logging
import os
import platform
import threading
import time
import traceback
import uuid
from collections import deque
from dataclasses import MISSING, dataclass, field, fields as dataclass_fields
from typing import Any, Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
from flask import Flask, jsonify, request
from river import drift, metrics
from autostream_core import AutoStreamCore
from adaptive_controller import AdaptiveFairnessController
from dynamic_fairness_envelope import DynamicFairnessEnvelope, DynamicFairnessEnvelopeConfig
from explainability_engine import StreamingExplainabilityEngine
from fairness_engine import FairnessEngineConfig, StreamingFairnessEngine
from metrics_stream import StreamingFairnessMetric
from topological_bias_engine import TopologicalBiasEngine
from llm_auditor import StreamingLLMAuditor
from fairness_scope_manager import FairnessScopeManager
from config_space import ConfigSpaceSettings, StreamingConfigSpace
from candidate_evaluator import CandidateEvaluationResult, CandidateEvaluator, CandidateEvaluatorConfig
from osmac_optimizer import OSMACOptimizer, OSMACOptimizerConfig
from offline_benchmarks import (
StreamingBenchmarkSpec,
run_streaming_fairbo_baseline,
)
# ============================================================
# Version + Schema
# ============================================================
BACKEND_VERSION = "17.0"
SCHEMA_VERSION = "v17.0"
# ============================================================
# Limits / Constants
# ============================================================
MAX_HISTORY = int(os.getenv("FAIRASML_MAX_HISTORY", "5000") or "5000")
DEFAULT_CHUNK_SIZE = int(os.getenv("FAIRASML_DEFAULT_CHUNK", "200") or "200")
MAPPER_UPDATE_FREQUENCY = int(os.getenv("FAIRASML_MAPPER_FREQ", "100") or "100")
LLM_COOLDOWN = int(os.getenv("FAIRASML_LLM_COOLDOWN", "300") or "300")
# Ollama
OLLAMA_MODEL = os.getenv("FAIRASML_OLLAMA_MODEL", "llama3:latest")
OLLAMA_URL = os.getenv("FAIRASML_OLLAMA_URL", "http://localhost:11434/api/generate")
OLLAMA_TIMEOUT_SECONDS = float(os.getenv("FAIRASML_OLLAMA_TIMEOUT", "300") or "300")
OLLAMA_MAX_RETRIES = int(os.getenv("FAIRASML_OLLAMA_MAX_RETRIES", "2") or "2")
OLLAMA_CALL_COOLDOWN = int(os.getenv("FAIRASML_OLLAMA_CALL_COOLDOWN", "15") or "15")
OLLAMA_UNAVAILABLE_COOLDOWN = int(os.getenv("FAIRASML_OLLAMA_UNAVAILABLE_COOLDOWN", "120") or "120")
STABILITY_WARNING_THRESHOLD = float(os.getenv("FAIRASML_STABILITY_WARN", "0.15") or "0.15")
PERF_DRIFT_LATCH_STEPS = int(os.getenv("FAIRASML_PERF_LATCH", "40") or "40")
PERF_DRIFT_DELTA = float(os.getenv("FAIRASML_PERF_DRIFT_DELTA", "0.002") or "0.002")
MAX_RISE_PER_GROUP = int(os.getenv("FAIRASML_MAX_RISE_PER_GROUP", "500") or "500")
MAX_GROUPS_RISE = int(os.getenv("FAIRASML_MAX_GROUPS_RISE", "64") or "64")
EXPERIMENT_TTL_SECONDS = int(os.getenv("FAIRASML_EXPERIMENT_TTL", "0") or "0")
MAX_DATASET_ROWS = int(os.getenv("FAIRASML_MAX_DATASET_ROWS", "200000") or "200000")
MAX_DATASET_COLS = int(os.getenv("FAIRASML_MAX_DATASET_COLS", "500") or "500")
SCOPE_REEVAL_FREQUENCY = int(os.getenv("FAIRASML_SCOPE_REEVAL_FREQ", "50") or "50")
OSMAC_MIN_WINDOW = int(os.getenv("FAIRASML_OSMAC_MIN_WINDOW", "25") or "25")
OSMAC_MAX_WINDOW = int(os.getenv("FAIRASML_OSMAC_MAX_WINDOW", "250") or "250")
OSMAC_HISTORY_TAIL = int(os.getenv("FAIRASML_OSMAC_HISTORY_TAIL", "40") or "40")
MAX_OPTIMIZER_CANDIDATE_HISTORY = int(
os.getenv("FAIRASML_OPTIMIZER_CANDIDATE_HISTORY", "2048") or "2048"
)
DEFAULT_STATIC_BENCHMARK_BUDGET = int(os.getenv("FAIRASML_STATIC_BENCHMARK_BUDGET", "12") or "12")
DEFAULT_STATIC_BENCHMARK_POOL = int(os.getenv("FAIRASML_STATIC_BENCHMARK_POOL", "96") or "96")
# ============================================================
# Logging
# ============================================================
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("fairasml.api")
# ============================================================
# Flask + Global Registry
# ============================================================
app = Flask(__name__)
EXPERIMENTS: Dict[str, "ExperimentState"] = {}
EXPERIMENTS_LOCK = threading.Lock()
# ============================================================
# Optional: CodeCarbon
# ============================================================
try:
from codecarbon import EmissionsTracker # type: ignore
CODECARBON_AVAILABLE = True
except Exception:
EmissionsTracker = None # type: ignore
CODECARBON_AVAILABLE = False
# ============================================================
# Utilities
# ============================================================
def _now() -> float:
return float(time.time())
def safe_float(x: Any, default: float = 0.0) -> float:
try:
if x is None:
return default
v = float(x)
if np.isnan(v) or np.isinf(v):
return default
return v
except Exception:
return default
def safe_int(x: Any, default: int = 0) -> int:
try:
if x is None:
return default
if isinstance(x, bool):
return int(x)
if isinstance(x, (np.integer, int)):
return int(x)
return int(float(x))
except Exception:
return default
def safe_bool(x: Any, default: bool = False) -> bool:
if x is None:
return bool(default)
if isinstance(x, bool):
return bool(x)
if isinstance(x, (int, np.integer)):
return bool(int(x))
if isinstance(x, (float, np.floating)):
return bool(safe_float(x, 1.0 if default else 0.0) >= 0.5)
s = str(x).strip().lower()
if s in {"1", "true", "yes", "y", "on"}:
return True
if s in {"0", "false", "no", "n", "off"}:
return False
return bool(default)
def safe_str(x: Any, default: str = "") -> str:
if x is None:
return str(default)
return str(x)
def bounded_append(lst: List[Any], value: Any, max_len: int = MAX_HISTORY) -> None:
lst.append(value)
if len(lst) > max_len:
del lst[0]
def make_json_safe(obj: Any) -> Any:
if obj is None:
return None
if isinstance(obj, dict):
return {str(k): make_json_safe(v) for k, v in obj.items()}
if isinstance(obj, (list, tuple, set, deque)):
return [make_json_safe(v) for v in obj]
if isinstance(obj, np.ndarray):
return obj.tolist()
if isinstance(obj, np.generic):
obj = obj.item()
if isinstance(obj, (np.floating, float)):
return safe_float(obj)
if isinstance(obj, (np.integer, int)):
return int(obj)
if isinstance(obj, (str, bool)):
return obj
return str(obj)
def _err_payload(
code: str,
message: str,
http_status: int = 400,
details: Optional[Dict[str, Any]] = None,
):
payload: Dict[str, Any] = {
"status": "error",
"error": code,
"message": message,
"backend_version": BACKEND_VERSION,
"schema_version": SCHEMA_VERSION,
}
if details:
payload["details"] = make_json_safe(details)
return jsonify(payload), http_status
def _normalize_value(v: Any) -> Any:
if v is None:
return "unknown"
if isinstance(v, (np.integer, int)):
return int(v)
if isinstance(v, (np.floating, float)):
fv = safe_float(v, 0.0)
if abs(fv - round(fv)) < 1e-9:
return int(round(fv))
return fv
return str(v)
def _normalize_sensitive_dict(xi_full: Dict[str, Any], sensitive_cols: List[str]) -> Dict[str, Any]:
out: Dict[str, Any] = {}
for s in sensitive_cols:
out[s] = _normalize_value(xi_full.get(s, None))
return out
def _coerce_binary_target(v: Any) -> int:
if v is None:
return 0
if isinstance(v, bool):
return int(v)
if isinstance(v, (int, np.integer)):
return 1 if int(v) == 1 else 0
if isinstance(v, (float, np.floating)):
fv = safe_float(v, 0.0)
return 1 if fv >= 1.0 else 0
s = str(v).strip().lower()
if s in {"1", "true", "yes", "y", ">50k", "positive", "pos", "good", "approved", "accept"}:
return 1
if s in {"0", "false", "no", "n", "<=50k", "negative", "neg", "bad", "rejected", "reject"}:
return 0
return 0
def _build_encoded_feature_matrix(
df: pd.DataFrame,
target_col: str,
sensitive_cols: List[str],
) -> Tuple[List[Dict[str, float]], Dict[str, Any]]:
excluded = set([target_col] + list(sensitive_cols))
base_cols = [c for c in df.columns if c not in excluded]
feature_df = df[base_cols].copy()
numeric_cols: List[str] = []
categorical_cols: List[str] = []
dropped_cols: List[str] = []
for col in list(feature_df.columns):
s = feature_df[col]
if pd.api.types.is_bool_dtype(s):
feature_df[col] = s.astype(int)
numeric_cols.append(str(col))
continue
if pd.api.types.is_numeric_dtype(s):
feature_df[col] = pd.to_numeric(s, errors="coerce")
numeric_cols.append(str(col))
continue
try:
feature_df[col] = s.astype("string").fillna("__MISSING__")
categorical_cols.append(str(col))
except Exception:
dropped_cols.append(str(col))
usable_cols = [c for c in feature_df.columns if c not in dropped_cols]
feature_df = feature_df[usable_cols]
if categorical_cols:
encoded = pd.get_dummies(
feature_df,
columns=[c for c in categorical_cols if c in feature_df.columns],
dummy_na=False,
)
else:
encoded = feature_df.copy()
encoded = encoded.replace([np.inf, -np.inf], np.nan).fillna(0.0)
for c in encoded.columns:
encoded[c] = pd.to_numeric(encoded[c], errors="coerce").fillna(0.0).astype(float)
X_model = encoded.to_dict(orient="records")
feature_manifest = {
"base_feature_columns": [str(c) for c in base_cols],
"numeric_feature_columns": numeric_cols,
"categorical_feature_columns": categorical_cols,
"encoded_feature_columns": [str(c) for c in encoded.columns],
"dropped_feature_columns": dropped_cols,
"excluded_columns": sorted(list(excluded)),
"encoded_feature_count": int(len(encoded.columns)),
}
return X_model, feature_manifest
def _get_proba_1(proba: Dict[Any, float]) -> float:
if not isinstance(proba, dict) or not proba:
return 0.5
normalized: Dict[str, float] = {}
raw_numeric_one: Optional[float] = None
raw_numeric_zero: Optional[float] = None
for k, v in proba.items():
pv = float(np.clip(safe_float(v, 0.0), 0.0, 1.0))
if k == 1:
raw_numeric_one = pv
elif k == 0:
raw_numeric_zero = pv
elif k is True:
raw_numeric_one = pv
elif k is False:
raw_numeric_zero = pv
ks = str(k).strip().lower()
normalized[ks] = pv
positive_aliases = {"1", "true", "yes", "positive", "pos"}
negative_aliases = {"0", "false", "no", "negative", "neg"}
if raw_numeric_one is not None:
return float(np.clip(raw_numeric_one, 0.0, 1.0))
for key in positive_aliases:
if key in normalized:
return float(np.clip(normalized[key], 0.0, 1.0))
if raw_numeric_zero is not None:
return float(np.clip(1.0 - raw_numeric_zero, 0.0, 1.0))
for key in negative_aliases:
if key in normalized:
return float(np.clip(1.0 - normalized[key], 0.0, 1.0))
vals = [float(np.clip(safe_float(v, 0.0), 0.0, 1.0)) for v in proba.values()]
if len(vals) == 2:
s = sum(vals)
if 0.95 <= s <= 1.05:
return 0.5
return 0.5
def _get_control_fairness_value(snapshot: Dict[str, Any], default: float = 0.0) -> float:
if not isinstance(snapshot, dict):
return default
return safe_float(snapshot.get("primary_metric", snapshot.get("ddsp", default)), default)
def _get_sfm_payload(snapshot: Dict[str, Any]) -> Dict[str, Any]:
if not isinstance(snapshot, dict):
return {}
sfm = snapshot.get("sfm_payload", {})
if isinstance(sfm, dict) and sfm:
return sfm
if any(k in snapshot for k in ("fm_raw", "fm_smooth", "fm_uncertainty")):
return {
"fm_raw": safe_float(snapshot.get("fm_raw", snapshot.get("primary_metric", 0.0)), 0.0),
"fm_smooth": safe_float(snapshot.get("fm_smooth", snapshot.get("primary_metric", 0.0)), 0.0),
"fm_drift": safe_float(snapshot.get("fm_drift", 0.0), 0.0),
"fm_smooth_drift": safe_float(snapshot.get("fm_smooth_drift", snapshot.get("fm_drift", 0.0)), 0.0),
"fm_uncertainty": safe_float(snapshot.get("fm_uncertainty", 1.0), 1.0),
"confidence": safe_float(snapshot.get("confidence", 0.0), 0.0),
"is_reliable": bool(snapshot.get("is_reliable", False)),
"insufficient_support": bool(snapshot.get("insufficient_support", True)),
"metric_name": str(snapshot.get("primary_metric_name", "ddsp@global")),
"metric_key": str(snapshot.get("metric_key", "ddsp")),
"metric_target": str(snapshot.get("metric_target", "global")),
"window_support": safe_int(snapshot.get("window_support", 0), 0),
"effective_support": safe_int(snapshot.get("effective_support", 0), 0),
"eligible_groups": safe_int(snapshot.get("eligible_groups", 0), 0),
"groups_tracked": safe_int(snapshot.get("groups_tracked", 0), 0),
"group_counts": dict(snapshot.get("group_support", {})) if isinstance(snapshot.get("group_support"), dict) else {},
"low_support_groups": list(snapshot.get("low_support_groups", [])) if isinstance(snapshot.get("low_support_groups"), list) else [],
"sfm": snapshot.get("sfm", None),
"sfm_state": copy.deepcopy(snapshot.get("sfm_state", {})) if isinstance(snapshot.get("sfm_state"), dict) else {},
"value": safe_float(snapshot.get("fm_smooth", snapshot.get("primary_metric", 0.0)), 0.0),
"primary_metric": safe_float(snapshot.get("fm_smooth", snapshot.get("primary_metric", 0.0)), 0.0),
}
return {}
def _normalize_primary_metric_key(metric_key: Any) -> str:
key = str(metric_key or "ddsp").strip().lower()
alias = {
"eo": "eopp",
"equal_opportunity": "eopp",
"equalized_odds": "eodds",
"equalized_odds_proxy": "eodds",
"ppv": "predictive_parity",
"predictive_parity_gap": "predictive_parity",
}
key = alias.get(key, key)
if key not in {"ddsp", "error_rate", "eopp", "eodds", "predictive_parity"}:
return "ddsp"
return key
def _parse_primary_metric_name(metric_name: Any) -> Tuple[str, str]:
raw = str(metric_name or "").strip()
if not raw:
return "ddsp", "global"
metric_key, _, metric_target = raw.partition("@")
return _normalize_primary_metric_key(metric_key), (metric_target or "global").strip()
def _select_metric_diagnostic(
metrics_snapshot: Dict[str, Any],
metric_key: str,
metric_target: str,
) -> Dict[str, Any]:
if not isinstance(metrics_snapshot, dict):
return {}
global_key_map = {
"ddsp": "ddsp",
"error_rate": "error_rate",
"eopp": "equal_opportunity",
"eodds": "equalized_odds_proxy",
"predictive_parity": "predictive_parity",
}
scoped_key_map = {
"ddsp": "ddsp",
"error_rate": "error_rate",
"eopp": "eopp",
"eodds": "eodds",
"predictive_parity": "predictive_parity",
}
metric_key = _normalize_primary_metric_key(metric_key)
metric_target = str(metric_target or "global").strip()
if metric_target.startswith("attribute:"):
attr = metric_target.split(":", 1)[1].strip()
attr_metrics = metrics_snapshot.get("attribute_metrics", {})
if isinstance(attr_metrics, dict):
attr_payload = attr_metrics.get(attr, {})
if isinstance(attr_payload, dict):
diag = attr_payload.get("diagnostic_uncertainty", {})
if isinstance(diag, dict):
sel = diag.get(scoped_key_map[metric_key], {})
return sel if isinstance(sel, dict) else {}
if metric_target.startswith("intersection:"):
inter = metric_target.split(":", 1)[1].strip()
inter_metrics = metrics_snapshot.get("intersection_metrics", {})
if isinstance(inter_metrics, dict):
inter_payload = inter_metrics.get(inter, {})
if isinstance(inter_payload, dict):
diag = inter_payload.get("diagnostic_uncertainty", {})
if isinstance(diag, dict):
sel = diag.get(scoped_key_map[metric_key], {})
return sel if isinstance(sel, dict) else {}
diag = metrics_snapshot.get("diagnostic_uncertainty", {})
if not isinstance(diag, dict):
return {}
sel = diag.get(global_key_map[metric_key], {})
return sel if isinstance(sel, dict) else {}
def _build_sfm_payload(
fairness_snapshot: Dict[str, Any],
metrics_snapshot: Dict[str, Any],
prev_fm_smooth: Optional[float] = None,
smooth_alpha: float = 0.35,
) -> Dict[str, Any]:
fairness_snapshot = fairness_snapshot if isinstance(fairness_snapshot, dict) else {}
metrics_snapshot = metrics_snapshot if isinstance(metrics_snapshot, dict) else {}
existing = _get_sfm_payload(fairness_snapshot)
if existing:
return existing
metric_key, metric_target = _parse_primary_metric_name(fairness_snapshot.get("primary_metric_name", "ddsp@global"))
metric_name = f"{metric_key}@{metric_target}"
fm_raw = safe_float(
fairness_snapshot.get("primary_metric", fairness_snapshot.get("ddsp", 0.0)),
0.0,
)
prev_smooth = None if prev_fm_smooth is None else safe_float(prev_fm_smooth, fm_raw)
if prev_smooth is None:
fm_smooth = fm_raw
fm_drift = 0.0
else:
alpha = float(np.clip(smooth_alpha, 0.0, 1.0))
fm_smooth = (alpha * fm_raw) + ((1.0 - alpha) * prev_smooth)
fm_drift = fm_smooth - prev_smooth
diag = _select_metric_diagnostic(metrics_snapshot, metric_key=metric_key, metric_target=metric_target)
diag_support = diag.get("group_support", {})
group_counts = dict(diag_support) if isinstance(diag_support, dict) else {}
low_support_groups = list(diag.get("low_support_groups", [])) if isinstance(diag.get("low_support_groups"), list) else []
uncertainty_default = 1.0 if not diag else 0.0
fm_uncertainty = float(np.clip(safe_float(diag.get("uncertainty", uncertainty_default), uncertainty_default), 0.0, 1.0))
confidence = float(np.clip(
safe_float(diag.get("confidence", 1.0 - min(1.0, fm_uncertainty)), 1.0 - min(1.0, fm_uncertainty)),
0.0,
1.0,
))
is_reliable = bool(diag.get("is_reliable", False))
insufficient_support = bool(diag.get("insufficient_support", not is_reliable))
effective_support = safe_int(diag.get("effective_support", 0), 0)
eligible_groups = safe_int(diag.get("eligible_groups", 0), 0)
groups_tracked = safe_int(diag.get("groups_tracked", len(group_counts)), len(group_counts))
window_support = safe_int(diag.get("window_support", fairness_snapshot.get("groups_tracked", 0)), 0)
sfm_triplet = [
float(fm_smooth),
float(fm_drift),
float(fm_uncertainty),
]
return {
"metric_name": metric_name,
"metric_key": metric_key,
"metric_target": metric_target,
"fm_raw": float(fm_raw),
"fm_smooth": float(fm_smooth),
"fm_drift": float(fm_drift),
"fm_smooth_drift": float(fm_drift),
"fm_uncertainty": float(fm_uncertainty),
"confidence": float(confidence),
"is_reliable": bool(is_reliable),
"insufficient_support": bool(insufficient_support),
"window_support": int(window_support),
"effective_support": int(effective_support),
"eligible_groups": int(eligible_groups),
"groups_tracked": int(groups_tracked),
"group_counts": group_counts,
"low_support_groups": low_support_groups,
"sfm": sfm_triplet,
"sfm_state": {
"fm_stable": float(fm_smooth),
"delta_fm": float(fm_drift),
"sigma": float(fm_uncertainty),
"confidence": float(confidence),
"is_reliable": bool(is_reliable),
},
"value": float(fm_smooth),
"primary_metric": float(fm_smooth),
}
def _update_y_prob_debug(exp: "ExperimentState", y_prob: float) -> None:
bounded_append(
exp.y_prob_history,
float(np.clip(safe_float(y_prob, 0.5), 0.0, 1.0)),
max_len=MAX_HISTORY,
)
arr = np.asarray(exp.y_prob_history, dtype=float)
if arr.size == 0:
exp.y_prob_debug_snapshot = {
"count": 0,
"mean": 0.0,
"std": 0.0,
"min": 0.0,
"max": 0.0,
"share_gt_05": 0.0,
"share_near_05_pm_005": 0.0,
}
return
exp.y_prob_debug_snapshot = {
"count": int(arr.size),
"mean": safe_float(arr.mean(), 0.0),
"std": safe_float(arr.std(), 0.0),
"min": safe_float(arr.min(), 0.0),
"max": safe_float(arr.max(), 0.0),
"share_gt_05": safe_float(np.mean(arr > 0.5), 0.0),
"share_near_05_pm_005": safe_float(np.mean(np.abs(arr - 0.5) <= 0.05), 0.0),
}
def _detector_drift_flag(detector: Any) -> bool:
for attr in ("drift_detected", "change_detected"):
if hasattr(detector, attr):
try:
return bool(getattr(detector, attr))
except Exception:
return False
if hasattr(detector, "warning_detected"):
try:
return bool(getattr(detector, "warning_detected"))
except Exception:
return False
return False
def _cleanup_expired_experiments() -> None:
if EXPERIMENT_TTL_SECONDS <= 0:
return
now = _now()
expired: List[str] = []
with EXPERIMENTS_LOCK:
for eid, exp in list(EXPERIMENTS.items()):
if (now - float(exp.last_poll_ts)) > EXPERIMENT_TTL_SECONDS:
expired.append(eid)
for eid in expired:
EXPERIMENTS.pop(eid, None)
if expired:
logger.info("Evicted %s experiments (TTL=%ss).", len(expired), EXPERIMENT_TTL_SECONDS)
def _call_with_optional_kwargs(fn: Any, *args: Any, **kwargs: Any) -> Any:
try:
return fn(*args, **kwargs)
except TypeError:
pass
try:
sig = inspect.signature(fn)
allowed = {k: v for k, v in kwargs.items() if k in sig.parameters}
return fn(*args, **allowed)
except Exception:
pass
return fn(*args)
def _build_dataclass_config(config_cls: Any, payload: Any) -> Any:
if not isinstance(payload, dict):
return config_cls()
kwargs: Dict[str, Any] = {}
for f in dataclass_fields(config_cls):
if f.name not in payload:
continue
raw = payload.get(f.name)
default = None if f.default is MISSING else f.default
if isinstance(default, bool):
kwargs[f.name] = safe_bool(raw, default)
elif isinstance(default, int) and not isinstance(default, bool):
kwargs[f.name] = safe_int(raw, default)
elif isinstance(default, float):
kwargs[f.name] = safe_float(raw, default)
elif isinstance(default, str):
kwargs[f.name] = str(raw)
else:
kwargs[f.name] = raw
return config_cls(**kwargs)
# ============================================================
# Fairness scope helpers
# ============================================================
def _default_scope_config(
sensitive_attr: List[str],
window_size: int,
) -> Dict[str, Any]:
return {
"mode": "manual" if sensitive_attr else "adaptive",
"approved_candidates": list(sensitive_attr),
"blocked_candidates": [],
"max_active_attributes": max(1, min(2, len(sensitive_attr) if sensitive_attr else 1)),
"allow_intersections": True,
"fairness_threshold": 0.05,
"window_size": window_size,
}
def _resolve_scope_config(
payload_scope_cfg: Any,
sensitive_attr: List[str],
window_size: int,
) -> Dict[str, Any]:
cfg = _default_scope_config(sensitive_attr, window_size)
if not isinstance(payload_scope_cfg, dict):
return cfg
mode = str(payload_scope_cfg.get("mode", cfg["mode"])).strip().lower()
if mode not in {"manual", "assisted", "adaptive"}:
mode = cfg["mode"]
approved_candidates = payload_scope_cfg.get("approved_candidates", cfg["approved_candidates"])
if approved_candidates and not isinstance(approved_candidates, list):
approved_candidates = [approved_candidates]
approved_candidates = [str(x) for x in approved_candidates] if approved_candidates else list(cfg["approved_candidates"])
blocked_candidates = payload_scope_cfg.get("blocked_candidates", [])
if blocked_candidates and not isinstance(blocked_candidates, list):
blocked_candidates = [blocked_candidates]
blocked_candidates = [str(x) for x in blocked_candidates] if blocked_candidates else []
return {
"mode": mode,
"approved_candidates": approved_candidates,
"blocked_candidates": blocked_candidates,
"max_active_attributes": max(
1,
safe_int(payload_scope_cfg.get("max_active_attributes", cfg["max_active_attributes"]), cfg["max_active_attributes"]),
),
"allow_intersections": bool(payload_scope_cfg.get("allow_intersections", cfg["allow_intersections"])),
"fairness_threshold": float(np.clip(
safe_float(payload_scope_cfg.get("fairness_threshold", cfg["fairness_threshold"]), cfg["fairness_threshold"]),
0.0,
1.0,
)),
"window_size": max(10, safe_int(payload_scope_cfg.get("window_size", window_size), window_size)),
}
def _default_optimizer_runtime_config(window_size: int) -> Dict[str, Any]:
eval_window = max(OSMAC_MIN_WINDOW, min(OSMAC_MAX_WINDOW, int(window_size)))
return {
"enabled": True,
"window_size": int(eval_window),
"min_samples": int(max(OSMAC_MIN_WINDOW, min(eval_window, 50))),
"step_frequency": int(eval_window),
"include_incumbent": True,
"force_exploration_on_violation": True,
"history_tail": int(max(5, min(OSMAC_HISTORY_TAIL, 200))),
}
def _resolve_optimizer_runtime_config(
runtime_payload: Any,
window_size: int,
) -> Dict[str, Any]:
cfg = _default_optimizer_runtime_config(window_size)
incoming = runtime_payload if isinstance(runtime_payload, dict) else {}
cfg["enabled"] = safe_bool(incoming.get("enabled", cfg["enabled"]), cfg["enabled"])
cfg["window_size"] = max(
OSMAC_MIN_WINDOW,
min(OSMAC_MAX_WINDOW, safe_int(incoming.get("window_size", cfg["window_size"]), cfg["window_size"])),
)
cfg["min_samples"] = max(
2,
min(cfg["window_size"], safe_int(incoming.get("min_samples", cfg["min_samples"]), cfg["min_samples"])),
)
cfg["step_frequency"] = max(
1,
safe_int(incoming.get("step_frequency", cfg["step_frequency"]), cfg["step_frequency"]),
)
cfg["include_incumbent"] = safe_bool(
incoming.get("include_incumbent", cfg["include_incumbent"]),
cfg["include_incumbent"],
)
cfg["force_exploration_on_violation"] = safe_bool(
incoming.get("force_exploration_on_violation", cfg["force_exploration_on_violation"]),
cfg["force_exploration_on_violation"],
)
cfg["history_tail"] = max(
5,
min(200, safe_int(incoming.get("history_tail", cfg["history_tail"]), cfg["history_tail"])),
)
return cfg
def _build_envelope_config(
fairness_scope_config: Dict[str, Any],
) -> DynamicFairnessEnvelopeConfig:
threshold = float(np.clip(safe_float(fairness_scope_config.get("fairness_threshold", 0.05), 0.05), 0.02, 0.10))
min_upper = float(threshold)
max_upper = float(np.clip(max(threshold, threshold * 2.0), threshold, 0.10))
beta_relax = float(min(0.003, max(0.001, threshold * 0.05)))
max_lower = float(min(0.02, threshold * 0.5))
enforce_lower_bound = safe_bool(fairness_scope_config.get("enforce_lower_bound", False), False)
return DynamicFairnessEnvelopeConfig(
initial_upper=threshold,
initial_lower=0.0,
min_lower=0.0,
max_lower=max_lower,
min_upper=min_upper,
max_upper=max_upper,
alpha_drift=0.25,
alpha_uncertainty=0.15,
alpha_violation=0.35,
alpha_lower_drift=0.05,
alpha_lower_uncertainty=0.03,
beta_relax=beta_relax,
beta_lower_relax=0.0005,
warning_margin_ratio=0.10,
trend_alert_ratio=0.08,
repeat_violation_tighten_bonus=0.015,
consecutive_warning_tighten_bonus=0.003,
enforce_lower_bound=enforce_lower_bound,
)
def _resolve_streaming_optimizer_method(value: Any) -> str:
method = safe_str(value, "").strip().lower()
aliases = {
"dfe-automl": "online_fairbo_ensemble",
"dfe_automl": "online_fairbo_ensemble",
"dfeautoml": "online_fairbo_ensemble",
"onlinefairbo": "online_fairbo_basic",
"online_fairbo": "online_fairbo_basic",
"onlinefairbo-basic": "online_fairbo_basic",
"online_fairbo_basic": "online_fairbo_basic",
"onlinefairbo_basic": "online_fairbo_basic",
"onlinefairbobasic": "online_fairbo_basic",
"adaptivefairbo": "online_fairbo_ensemble",
"adaptive_fairbo": "online_fairbo_ensemble",
"onlinefairbo-ensemble": "online_fairbo_ensemble",
"online_fairbo_ensemble": "online_fairbo_ensemble",
"onlinefairbo_ensemble": "online_fairbo_ensemble",
"onlinefairboensemble": "online_fairbo_ensemble",
}
return aliases.get(method, "online_fairbo_ensemble")
def _initial_scope_state(
scope_manager: Optional[FairnessScopeManager],
scope_cfg: Dict[str, Any],
sensitive_attr: List[str],
) -> Dict[str, Any]:
active_attributes: List[str] = []
active_intersections: List[Tuple[str, ...]] = []
scores: Dict[str, float] = {}
selection_reason = "bootstrap"
if scope_cfg.get("mode") == "manual":
active_attributes = list(sensitive_attr)
if scope_cfg.get("allow_intersections", True) and len(active_attributes) >= 2:
active_intersections = [tuple(active_attributes[:2])]
selection_reason = "manual"
elif scope_manager is not None and getattr(scope_manager, "profiles", None):
ranked = sorted(
scope_manager.profiles.values(),
key=lambda p: (
safe_float(getattr(p, "static_score", 0.0), 0.0),
-safe_int(getattr(p, "unique_vals", 0), 0),
),
reverse=True,
)
active_attributes = [p.name for p in ranked[: max(1, safe_int(scope_cfg.get("max_active_attributes", 1), 1))]]
if scope_cfg.get("allow_intersections", True) and len(active_attributes) >= 2:
active_intersections = [tuple(active_attributes[:2])]
scores = {p.name: safe_float(getattr(p, "static_score", 0.0), 0.0) for p in ranked}
selection_reason = "static_bootstrap"
primary = active_attributes[0] if active_attributes else (sensitive_attr[0] if sensitive_attr else "sensitive_attribute")
return {
"mode": scope_cfg.get("mode", "manual"),
"active_attributes": active_attributes,
"active_intersections": active_intersections,
"primary_attribute": primary,
"scores": scores,
"selection_reason": selection_reason,
"last_rescore_step": 0,
}
def _active_sensitive_from_scope(
xi_full: Dict[str, Any],
all_sensitive_dict: Dict[str, Any],
scope_state: Dict[str, Any],
) -> Dict[str, Any]:
active_attrs = scope_state.get("active_attributes", []) if isinstance(scope_state, dict) else []
if not active_attrs:
return dict(all_sensitive_dict)
out: Dict[str, Any] = {}
for attr in active_attrs:
if attr in all_sensitive_dict:
out[attr] = all_sensitive_dict[attr]
else:
out[attr] = _normalize_value(xi_full.get(attr, None))
return out
def _safe_scope_snapshot(scope_manager: Any) -> Dict[str, Any]:
if scope_manager is None:
return {}
try:
snap = scope_manager.snapshot()
return snap if isinstance(snap, dict) else {}
except Exception:
return {}
def _build_decision_context(
xi_full: Dict[str, Any],
all_sensitive_dict: Dict[str, Any],
active_sensitive_dict: Dict[str, Any],
scope_state: Dict[str, Any],
scope_snapshot: Dict[str, Any],
active_mitigation: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
primary_attr = scope_state.get("primary_attribute", "sensitive_attribute") if isinstance(scope_state, dict) else "sensitive_attribute"
active_intersections = scope_state.get("active_intersections", []) if isinstance(scope_state, dict) else []
primary_value = active_sensitive_dict.get(primary_attr, all_sensitive_dict.get(primary_attr, "unknown"))
intersection_values: Dict[str, Any] = {}
if active_intersections:
for inter in active_intersections:
if isinstance(inter, (list, tuple)):
key = "|".join(map(str, inter))
intersection_values[key] = "|".join(str(all_sensitive_dict.get(a, "unknown")) for a in inter)
mitigation = active_mitigation if isinstance(active_mitigation, dict) else {}
mitigation_params = mitigation.get("params", {}) if isinstance(mitigation.get("params", {}), dict) else {}
routing: Dict[str, Any] = {
"mode": "scope_aware",
"prediction_mode": mitigation_params.get("prediction_mode"),
"candidate_weights": mitigation_params.get("candidate_weights", {}),
"explore_boost": mitigation_params.get("explore_boost", 1.0),
}
active_scope = {
"mode": scope_state.get("mode", "unknown"),
"primary_attribute": primary_attr,
"active_attributes": copy.deepcopy(scope_state.get("active_attributes", [])),
"active_intersections": copy.deepcopy(active_intersections),
}
ctx = {
"primary_attribute": primary_attr,
"primary_group_value": primary_value,
"all_sensitive_dict": dict(all_sensitive_dict),
"active_sensitive_dict": dict(active_sensitive_dict),
"active_intersections": copy.deepcopy(active_intersections),
"intersection_values": intersection_values,
"raw_row_sensitive_view": {k: xi_full.get(k) for k in all_sensitive_dict.keys()},
"scope_state": copy.deepcopy(scope_state),
"fairness_scope_snapshot": copy.deepcopy(scope_snapshot),
"active_scope": active_scope,
"mitigation": copy.deepcopy(mitigation),
"routing": routing,
}
if mitigation_params:
if "fairness_weight" in mitigation_params:
ctx["fairness_weight"] = safe_float(mitigation_params.get("fairness_weight", 1.0), 1.0)
if "performance_weight" in mitigation_params:
ctx["performance_weight"] = safe_float(mitigation_params.get("performance_weight", 1.0), 1.0)
if "sample_weight" in mitigation_params: