-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvaluationService.ts
More file actions
1360 lines (1201 loc) · 48.4 KB
/
EvaluationService.ts
File metadata and controls
1360 lines (1201 loc) · 48.4 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
/**
* Evaluation Service
*
* Implements hybrid evaluation approach:
* 1. Deterministic Core (replayable, verifiable)
* 2. Statistical/Probabilistic Edges (multiple outputs, weighted scoring)
* 3. Human-in-the-loop (optional, controlled)
*
* First Principles:
* - Verification > Reputation
* - Determinism where possible, consensus where not
* - Cost > Rules (risky evaluation costs more)
*/
import { ILogger } from './utils/ILogger';
import { createHash } from 'crypto';
import {
StatisticalDistributionService,
MonteCarloOutput,
ContributionScore,
UserPreference,
ValidatorMethodConfig,
EmbeddingMethod,
ClusteringAlgorithm
} from './StatisticalDistributionService';
import {
DeterministicReplayService,
ReplayValidationResult,
} from './DeterministicReplayService';
/**
* Evaluation Mode
*/
export type EvaluationMode =
| 'deterministic' // Pure deterministic (code, math, proofs)
| 'statistical' // Statistical consensus (images, text, creative)
| 'human-in-the-loop'; // Human selection from top-N
/**
* Task Output (from miner)
*/
/**
* Replay Bundle for Deterministic Tasks
* Contains all information needed to replay execution exactly
*/
export interface ReplayBundle {
taskInputHash: string; // Hash of task input
modelId: string; // Model identifier
modelVersionHash: string; // Hash of model version/weights
inferenceParameters: { // Inference parameters
temperature: number; // Must be 0 for deterministic
maxTokens?: number;
topP?: number;
topK?: number;
[key: string]: any; // Other parameters
};
randomSeed: string; // Fixed random seed (required for deterministic)
executionEnvHash: string; // Hash of execution environment
}
/**
* Execution Environment
* Describes the execution environment for reproducibility
*/
export interface ExecutionEnvironment {
os: string; // Operating system
runtime: string; // Runtime (e.g., Python 3.11, Node.js 20)
modelBinary: string; // Model binary identifier/hash
inferenceLibrary: string; // Inference library (e.g., transformers, torch)
inferenceLibraryVersion: string; // Version of inference library
dependencies?: { // Optional: dependency versions
[key: string]: string;
};
}
/**
* Intermediate Step Hash
* Hash of intermediate state during generation
*/
export interface IntermediateStepHash {
stepIndex: number; // Step index (0, 1, 2, ...)
stepHash: string; // Hash of step state
stepType?: string; // Type of step (token, AST, reasoning, etc.)
}
/**
* Step Trace Hash
* Root hash of all intermediate step hashes
*/
export interface StepTraceHash {
traceHash: string; // H(h1 || h2 || ... || hn)
stepHashes: IntermediateStepHash[]; // Individual step hashes
}
export interface TaskOutput {
outputId: string; // Deterministic hash of output
output: any; // The actual output
minerAddress: string; // Miner who produced this
timestamp: number; // When produced
metadata?: {
seed?: string; // Fixed seed (for stochastic tasks)
intermediateHashes?: string[]; // Hashes of intermediate steps (legacy)
executionProof?: string; // Proof of execution (if available)
// NEW: Deterministic replay bundle
replayBundle?: ReplayBundle;
stepTraceHash?: StepTraceHash; // Intermediate step hashes
executionEnv?: ExecutionEnvironment; // Execution environment
};
}
/**
* Validator Evaluation
*/
export interface ValidatorEvaluation {
validatorAddress: string;
outputId: string; // Which output they evaluated
score: number; // Score (0-100)
confidence: number; // Confidence level (0-1)
timestamp: number;
signature: string; // Signature of evaluation
evidence?: string; // Evidence for score (optional)
// NEW: Validator method configuration (for distribution-based evaluation)
methodConfig?: ValidatorMethodConfig;
// NEW: Distribution analysis results from this validator
distributionAnalysis?: import('./StatisticalDistributionService').DistributionAnalysis;
contributions?: import('./StatisticalDistributionService').ContributionScore[];
}
/**
* Statistical Evaluation Result
*/
export interface StatisticalEvaluation {
outputId: string;
weightedScore: number; // Weighted average score
agreementScore: number; // How much validators agree (0-1)
validatorCount: number; // Number of validators who evaluated
confidence: number; // Overall confidence (0-1)
evaluations: ValidatorEvaluation[];
}
/**
* Extended Statistical Result (with distribution analysis)
*/
export interface ExtendedStatisticalResult {
topOutputs: StatisticalEvaluation[];
consensusOutput?: string; // Top output by contribution (not consensus)
distributionAnalysis?: import('./StatisticalDistributionService').DistributionAnalysis;
contributions?: import('./StatisticalDistributionService').ContributionScore[];
}
/**
* Human-in-the-Loop Selection
*/
export interface HumanSelection {
taskId: string;
selectedOutputId: string; // User-selected output
userAddress: string; // User who selected
timestamp: number;
preFilteredOutputs: string[]; // Top-N outputs from validators
}
/**
* Evaluation Result
*/
export interface EvaluationResult {
taskId: string;
mode: EvaluationMode;
// Deterministic result
deterministicResult?: {
outputId: string;
score: number;
replayable: boolean;
replayHash: string; // Hash of inputs + seed for replay
};
// Statistical result
statisticalResult?: {
topOutputs: StatisticalEvaluation[];
consensusOutput?: string; // Best output by consensus (or contribution for distribution-based)
distributionAnalysis?: import('./StatisticalDistributionService').DistributionAnalysis;
contributions?: import('./StatisticalDistributionService').ContributionScore[];
};
// Human-in-the-loop result
humanSelection?: HumanSelection;
// Final decision
winningOutputId: string;
finalScore: number;
validators: string[]; // Validators who participated
}
import {
ValidatorReputationService,
ValidationResult as ReputationValidationResult,
} from './ValidatorReputationService';
import { AdversarialTestingService } from './AdversarialTestingService';
import { RiskScoringService } from './RiskScoringService';
import { NetworkState, RiskVector, NetworkManifest } from './types';
import { NetworkStateCalculator } from './NetworkStateCalculator';
export class EvaluationService {
private logger: ILogger;
private statisticalDistributionService?: StatisticalDistributionService;
private validatorCalibrationService?: ValidatorCalibrationService;
private deterministicReplayService?: DeterministicReplayService;
private validatorReputationService?: ValidatorReputationService;
private adversarialTestingService?: AdversarialTestingService;
private riskScoringService?: RiskScoringService;
private networkStateCalculator?: NetworkStateCalculator;
constructor(logger?: Logger) {
this.logger = logger || new Logger('EvaluationService');
// Initialize statistical distribution service (only used for non-deterministic tasks)
this.statisticalDistributionService = new StatisticalDistributionService(this.logger);
// Initialize validator calibration service (for epistemic decentralization)
// Initialize validator reputation service (Option 1: Rejection without slashing)
this.validatorReputationService = new ValidatorReputationService(this.logger);
// Initialize deterministic replay service (only used for deterministic tasks)
this.deterministicReplayService = new DeterministicReplayService(this.logger);
this.validatorCalibrationService = new ValidatorCalibrationService(this.logger);
// Initialize adversarial testing service (for risk score gaming prevention)
this.adversarialTestingService = new AdversarialTestingService(undefined, this.logger);
// Initialize risk scoring service (for correlation detection and relative risk)
this.riskScoringService = new RiskScoringService(this.logger);
// Initialize network state calculator (for adaptive risk weighting)
this.networkStateCalculator = new NetworkStateCalculator(this.logger);
}
/**
* Validate and filter evaluations using reputation service
*
* Option 1: Rejection without slashing
* - Invalid evaluations are rejected (no payment)
* - Reputation is updated
* - No funds are taken
*/
private async validateAndFilterEvaluations(
evaluations: ValidatorEvaluation[],
consensusResult: {
accepted: boolean;
consensusReached: boolean;
majorityScore: number;
}
): Promise<{
validEvaluations: ValidatorEvaluation[];
rejectedEvaluations: Array<{ evaluation: ValidatorEvaluation; reason: string }>;
reputationUpdates: Map<string, ReputationValidationResult>;
}> {
if (!this.validatorReputationService) {
// If reputation service not available, return all as valid
return {
validEvaluations: evaluations,
rejectedEvaluations: [],
reputationUpdates: new Map(),
};
}
const validEvaluations: ValidatorEvaluation[] = [];
const rejectedEvaluations: Array<{ evaluation: ValidatorEvaluation; reason: string }> = [];
const reputationUpdates = new Map<string, ReputationValidationResult>();
for (const evaluation of evaluations) {
// Validate evaluation
const validationResult = this.validatorReputationService.validateEvaluation(
evaluation,
consensusResult
);
// Check if should reject
if (validationResult.shouldReject) {
// REJECT (Option 1: No payment, no slashing)
rejectedEvaluations.push({
evaluation,
reason: validationResult.reason || 'Invalid evaluation',
});
// Update reputation
const updateResult = await this.validatorReputationService.updateReputation(
evaluation.validatorAddress,
validationResult,
false // Not successful
);
reputationUpdates.set(evaluation.validatorAddress, updateResult);
this.logger.warn('Validator evaluation rejected (no payment, no slashing)', {
validatorAddress: evaluation.validatorAddress,
outputId: evaluation.outputId,
reason: validationResult.reason,
reputationChange: updateResult.reputationChange,
});
} else {
// Valid evaluation
validEvaluations.push(evaluation);
// Update reputation (success or failure)
const wasSuccessful = validationResult.valid && !validationResult.reputationPenalty;
const updateResult = await this.validatorReputationService.updateReputation(
evaluation.validatorAddress,
validationResult,
wasSuccessful
);
// NEW: Update risk vector
if (this.validatorReputationService) {
const surprisal = this.validatorReputationService.calculateSurprisal(
evaluation.validatorAddress,
evaluation,
manifest?.taskFormat?.inputSchema?.type || 'general' // Use task type from manifest if available
);
this.validatorReputationService.updateRiskVector(
evaluation.validatorAddress,
{
wasSuccessful,
surprisal,
}
);
}
// NEW: Track risk for correlation detection
if (this.riskScoringService) {
const riskScore = updateResult.newReputation / 100; // Normalize to 0-1
this.riskScoringService.trackValidatorRisk(
evaluation.validatorAddress,
riskScore
);
}
// NEW: Check for adversarial test injection
if (this.adversarialTestingService && wasSuccessful) {
const metrics = this.validatorReputationService.getReputation(
evaluation.validatorAddress
);
const reputationChange = updateResult.reputationChange;
const isCorrelated = this.riskScoringService?.hasHighCorrelation(
evaluation.validatorAddress,
0.8
) || false;
const shouldTest = this.adversarialTestingService.shouldInjectTest(
evaluation.validatorAddress,
updateResult.newReputation,
reputationChange,
isCorrelated
);
if (shouldTest.isAdversarial && shouldTest.testType) {
// Inject adversarial test (would be handled in next evaluation cycle)
this.logger.info('Adversarial test scheduled', {
validatorAddress: evaluation.validatorAddress,
testType: shouldTest.testType,
});
}
}
reputationUpdates.set(evaluation.validatorAddress, updateResult);
}
}
return {
validEvaluations,
rejectedEvaluations,
reputationUpdates,
};
}
/**
* Evaluate deterministic task
* Pure replayable evaluation (code, math, proofs)
*
* Uses DeterministicReplayService to validate replay bundles.
* Option 1: Rejection without slashing - invalid submissions are rejected (no payment).
*/
async evaluateDeterministic(
taskId: string,
input: any,
outputs: TaskOutput[],
evaluations: ValidatorEvaluation[],
scoringModuleHash: string,
deterministicReplayConfig?: {
required?: boolean;
seedRequired?: boolean;
intermediateHashing?: boolean;
executionEnvRequired?: boolean;
}
): Promise<EvaluationResult> {
// For deterministic tasks, all outputs should be identical if correct
// Validators verify by replaying using the replay bundle
if (!this.deterministicReplayService) {
throw new Error('DeterministicReplayService not initialized');
}
// Validate replay for each output
const validOutputs: TaskOutput[] = [];
const invalidOutputs: Array<{ outputId: string; reason: string }> = [];
for (const output of outputs) {
// Check if replay bundle is provided
if (!output.metadata?.replayBundle) {
if (deterministicReplayConfig?.required) {
invalidOutputs.push({
outputId: output.outputId,
reason: 'Replay bundle required but not provided',
});
continue;
}
// If replay not required, skip validation
validOutputs.push(output);
continue;
}
// Validate replay
// Get execution environment and task input from output metadata
const executionEnv = output.metadata?.executionEnv;
const taskInput = input; // Use the actual task input passed to this method
const replayValidation = await this.deterministicReplayService.validateReplay(
output.output,
output.outputId,
output.metadata.replayBundle,
output.metadata.stepTraceHash,
executionEnv,
taskInput
);
if (!replayValidation.valid) {
// REJECT (Option 1: No slashing, just rejection)
invalidOutputs.push({
outputId: output.outputId,
reason: replayValidation.reason || 'Replay validation failed',
});
this.logger.warn('Output rejected due to replay validation failure', {
taskId,
outputId: output.outputId,
reason: replayValidation.reason,
});
continue;
}
// Valid output
validOutputs.push(output);
}
// If no valid outputs, return rejection
if (validOutputs.length === 0) {
this.logger.warn('All outputs rejected for deterministic task', {
taskId,
totalOutputs: outputs.length,
invalidOutputs: invalidOutputs.length,
});
return {
taskId,
mode: 'deterministic',
deterministicResult: {
outputId: '',
score: 0,
replayable: false,
replayHash: '',
},
winningOutputId: '',
finalScore: 0,
validators: evaluations.map(e => e.validatorAddress),
};
}
// Group evaluations by output (only for valid outputs and valid evaluations)
const outputEvaluations = new Map<string, ValidatorEvaluation[]>();
for (const eval_ of filteredEvaluations) {
if (validOutputs.some(o => o.outputId === eval_.outputId)) {
if (!outputEvaluations.has(eval_.outputId)) {
outputEvaluations.set(eval_.outputId, []);
}
outputEvaluations.get(eval_.outputId)!.push(eval_);
}
}
// Find output with highest consensus (from valid outputs only)
let bestOutputId = '';
let bestScore = 0;
let bestReplayHash = '';
for (const [outputId, evals] of outputEvaluations.entries()) {
const avgScore = evals.reduce((sum, e) => sum + e.score, 0) / evals.length;
const consensus = evals.length / evaluations.length; // How many validators agree
// For deterministic tasks, consensus matters more than score
if (consensus > 0.5 && avgScore > bestScore) {
bestOutputId = outputId;
bestScore = avgScore;
// Generate replay hash (input + seed + scoring module)
const output = validOutputs.find(o => o.outputId === outputId);
const seed = output?.metadata?.seed || '';
bestReplayHash = this.generateReplayHash(input, seed, scoringModuleHash);
}
}
return {
taskId,
mode: 'deterministic',
deterministicResult: {
outputId: bestOutputId,
score: bestScore,
replayable: true,
replayHash: bestReplayHash,
},
winningOutputId: bestOutputId,
finalScore: bestScore,
validators: filteredEvaluations.map(e => e.validatorAddress),
};
}
/**
* Calculate consensus for reputation validation
*/
private calculateConsensus(evaluations: ValidatorEvaluation[]): {
accepted: boolean;
consensusReached: boolean;
majorityScore: number;
} {
if (evaluations.length === 0) {
return {
accepted: false,
consensusReached: false,
majorityScore: 0,
};
}
// Calculate average score
const avgScore = evaluations.reduce((sum, e) => sum + e.score, 0) / evaluations.length;
// Check if consensus reached (simple majority threshold)
const consensusThreshold = 0.5;
const consensusReached = evaluations.length >= 2; // At least 2 validators
return {
accepted: avgScore >= 50, // Average score >= 50 is considered accepted
consensusReached,
majorityScore: avgScore,
};
}
/**
* Evaluate statistical/probabilistic task
*
* For non-deterministic tasks: Uses Monte Carlo distribution-based evaluation
* For deterministic tasks: Falls back to consensus-based (should not happen)
*
* This method is ONLY called when evaluationMode === 'statistical' (non-deterministic)
*/
async evaluateStatistical(
taskId: string,
outputs: TaskOutput[],
evaluations: ValidatorEvaluation[],
validatorReputations: Map<string, number>, // Validator address -> reputation (0-1)
distributionBased: boolean = true, // Use Monte Carlo approach by default
taskType: string = 'general',
manifest?: NetworkManifest,
taskInput?: any
): Promise<EvaluationResult> {
// Check if we should use distribution-based evaluation
if (distributionBased && this.statisticalDistributionService) {
const result = await this.evaluateStatisticalDistribution(
taskId,
outputs,
evaluations,
validatorReputations,
taskType
);
// Calculate aggregated distribution for network state
const aggregatedDistribution = this.aggregateDistributions(
result.aggregatedContributionsMap ? new Map() : new Map() // Will be calculated from validator distributions
);
// Update network state in result if needed
return result;
}
// Fallback to consensus-based evaluation (legacy, for backward compatibility)
return await this.evaluateStatisticalConsensus(
taskId,
outputs,
evaluations,
validatorReputations,
manifest,
taskInput
);
}
/**
* Distribution-based evaluation (Monte Carlo approach)
* ONLY used for non-deterministic tasks
*
* Supports validator pluralism: each validator can use different methods
*/
private async evaluateStatisticalDistribution(
taskId: string,
outputs: TaskOutput[],
evaluations: ValidatorEvaluation[],
validatorReputations: Map<string, number>,
taskType: string
): Promise<EvaluationResult> {
if (!this.statisticalDistributionService || !this.validatorCalibrationService) {
throw new Error('StatisticalDistributionService or ValidatorCalibrationService not initialized');
}
this.logger.info('Using Monte Carlo distribution-based evaluation with validator pluralism', {
taskId,
outputCount: outputs.length,
validatorCount: evaluations.length
});
// Convert TaskOutput to MonteCarloOutput
const monteCarloOutputs: MonteCarloOutput[] = outputs.map(o => ({
outputId: o.outputId,
output: o.output,
minerAddress: o.minerAddress,
timestamp: o.timestamp,
generationParams: {
seed: o.metadata?.seed,
temperature: (o.metadata as any)?.temperature,
model: (o.metadata as any)?.model,
promptStyle: (o.metadata as any)?.promptStyle,
},
intent: (o.metadata as any)?.intent,
}));
// Group evaluations by validator to get their method configs
const validatorMethods = new Map<string, ValidatorMethodConfig>();
for (const eval_ of evaluations) {
if (eval_.methodConfig) {
validatorMethods.set(eval_.validatorAddress, eval_.methodConfig);
}
}
// If no validators have method configs, use defaults (backward compatibility)
const hasMethodConfigs = validatorMethods.size > 0;
// Process each validator's evaluation with their chosen method
const validatorDistributions = new Map<string, DistributionAnalysis>();
const validatorContributions = new Map<string, Map<string, ContributionScore>>();
if (hasMethodConfigs) {
// Validator pluralism: each validator uses their own method
for (const [validatorAddress, methodConfig] of validatorMethods.entries()) {
try {
// 1. Embed outputs using validator's chosen method
// Get embedding config from manifest (custom embeddings with user-provided API keys)
const embeddingConfig = manifest.statisticalEvaluation?.embeddingConfig;
const embeddings = await this.statisticalDistributionService.embedOutputs(
monteCarloOutputs,
taskType,
methodConfig.embeddingMethod,
embeddingConfig
);
// 2. Estimate distribution using validator's chosen algorithm
const distribution = await this.statisticalDistributionService.estimateDistribution(
embeddings,
monteCarloOutputs,
methodConfig.clusteringAlgorithm
);
// 3. Calculate contributions using validator's chosen weights
const contributions = await this.statisticalDistributionService.calculateContributions(
monteCarloOutputs,
distribution,
embeddings,
methodConfig.contributionWeights
);
validatorDistributions.set(validatorAddress, distribution);
validatorContributions.set(validatorAddress, contributions);
} catch (error) {
this.logger.warn('Validator method evaluation failed', {
validatorAddress,
error: error instanceof Error ? error.message : String(error),
});
}
}
} else {
// Fallback: use default method (backward compatibility)
// Get embedding config from manifest (custom embeddings with user-provided API keys)
const embeddingConfig = manifest.statisticalEvaluation?.embeddingConfig;
const embeddings = await this.statisticalDistributionService.embedOutputs(
monteCarloOutputs,
taskType,
embeddingConfig?.provider === 'openai' ? 'openai' :
embeddingConfig?.provider === 'xenova' ? 'sentence-transformers' :
'hash-based',
embeddingConfig
);
const distribution = await this.statisticalDistributionService.estimateDistribution(
embeddings,
monteCarloOutputs,
'simple'
);
const contributions = await this.statisticalDistributionService.calculateContributions(
monteCarloOutputs,
distribution,
embeddings
);
// Assign to all validators (for backward compatibility)
for (const eval_ of evaluations) {
validatorDistributions.set(eval_.validatorAddress, distribution);
validatorContributions.set(eval_.validatorAddress, contributions);
}
}
// 4. Calibrate validators based on estimator quality (NOT agreement)
const calibrations = this.validatorCalibrationService.calibrateValidators(
evaluations,
validatorDistributions,
validatorContributions
);
// 5. Aggregate contributions across validators (weighted by calibration)
const aggregatedContributions = this.aggregateContributions(
validatorContributions,
calibrations
);
// 6. Convert aggregated contributions to statistical results format
const statisticalResults: StatisticalEvaluation[] = Array.from(aggregatedContributions.values())
.map(contrib => {
// Find evaluations for this output
const outputEvals = evaluations.filter(e => e.outputId === contrib.outputId);
// Calculate weighted score based on aggregated contribution
const weightedScore = contrib.totalContribution * 100; // Normalize to 0-100
// Method diversity score (not agreement score)
const methodDiversity = this.calculateMethodDiversityScore(outputEvals, calibrations);
// Confidence based on calibration quality, not agreement
const avgCalibration = outputEvals.length > 0
? outputEvals.reduce((sum, e) => {
const cal = calibrations.get(e.validatorAddress);
return sum + (cal?.calibrationScore || 0.5);
}, 0) / outputEvals.length
: 0.5;
return {
outputId: contrib.outputId,
weightedScore,
agreementScore: methodDiversity, // Actually method diversity, not agreement
validatorCount: outputEvals.length,
confidence: avgCalibration, // Based on calibration, not agreement
evaluations: outputEvals,
};
})
.sort((a, b) => b.weightedScore - a.weightedScore);
// 7. Top output by aggregated contribution (not consensus)
const topOutput = statisticalResults[0];
// 8. Aggregate distribution (average across validators)
const aggregatedDistribution = this.aggregateDistributions(validatorDistributions);
return {
taskId,
mode: 'statistical',
statisticalResult: {
topOutputs: statisticalResults,
consensusOutput: topOutput?.outputId || '', // Top by contribution, not consensus
// NEW: Include aggregated distribution analysis and calibrations
distributionAnalysis: aggregatedDistribution,
contributions: Array.from(aggregatedContributions.values()),
validatorCalibrations: Array.from(calibrations.values()),
// Store for human-in-the-loop preference-based pre-filtering
aggregatedContributionsMap: aggregatedContributions, // Keep Map for preference sampling
monteCarloOutputs: monteCarloOutputs, // Keep for preference sampling
} as any, // Extended type
winningOutputId: topOutput?.outputId || '',
finalScore: topOutput?.weightedScore || 0,
validators: Array.from(new Set(evaluations.map(e => e.validatorAddress))),
};
}
/**
* Pre-filter top-N outputs for human-in-the-loop using user preference
*
* If user preference is specified, uses StatisticalDistributionService.sampleByPreference()
* Otherwise, uses top-N by total contribution score
*/
async preFilterForHumanSelection(
evaluationResult: EvaluationResult,
topN: number,
userPreference?: {
type?: 'safe' | 'novel' | 'diverse' | 'balanced';
customPreference?: {
alpha: number;
beta: number;
gamma: number;
};
}
): Promise<string[]> {
if (!evaluationResult.statisticalResult) {
throw new Error('Pre-filtering requires statistical evaluation result');
}
// If user preference is specified, use preference-based sampling
if (userPreference && this.statisticalDistributionService) {
const statisticalResult = evaluationResult.statisticalResult as any;
const contributions = statisticalResult.aggregatedContributionsMap as Map<string, ContributionScore>;
const monteCarloOutputs = statisticalResult.monteCarloOutputs as MonteCarloOutput[];
if (contributions && monteCarloOutputs) {
// Build user preference vector
let preferenceVector: { alpha: number; beta: number; gamma: number };
if (userPreference.customPreference) {
// Use custom preference
const { alpha, beta, gamma } = userPreference.customPreference;
const sum = alpha + beta + gamma;
// Normalize to sum to 1
preferenceVector = {
alpha: alpha / sum,
beta: beta / sum,
gamma: gamma / sum,
};
} else {
// Use pre-defined preference types
switch (userPreference.type) {
case 'safe':
preferenceVector = { alpha: 0.7, beta: 0.15, gamma: 0.15 }; // High robustness
break;
case 'novel':
preferenceVector = { alpha: 0.2, beta: 0.7, gamma: 0.1 }; // High novelty
break;
case 'diverse':
preferenceVector = { alpha: 0.2, beta: 0.2, gamma: 0.6 }; // High diversity
break;
case 'balanced':
default:
preferenceVector = { alpha: 0.4, beta: 0.3, gamma: 0.3 }; // Balanced
break;
}
}
const userPreferenceObj: UserPreference = {
userId: 'system', // System-level preference for pre-filtering
preferenceVector,
normalized: true,
};
// Sample outputs by preference
const preferenceBasedOutputs = await this.statisticalDistributionService.sampleByPreference(
monteCarloOutputs,
contributions,
userPreferenceObj
);
// Return top-N from preference-based sampling
return preferenceBasedOutputs.slice(0, topN);
}
}
// Fallback: Use top-N by total contribution score
const topOutputs = evaluationResult.statisticalResult.topOutputs
.sort((a, b) => b.weightedScore - a.weightedScore)
.slice(0, topN);
return topOutputs.map(o => o.outputId);
}
/**
* Aggregate contributions across validators (weighted by calibration)
*/
private aggregateContributions(
validatorContributions: Map<string, Map<string, ContributionScore>>,
calibrations: Map<string, ValidatorCalibrationMetrics>
): Map<string, ContributionScore> {
const aggregated = new Map<string, ContributionScore>();
// Collect all output IDs
const allOutputIds = new Set<string>();
for (const contributions of validatorContributions.values()) {
for (const outputId of contributions.keys()) {
allOutputIds.add(outputId);
}
}
// Aggregate each output's contribution across validators
for (const outputId of allOutputIds) {
let totalRobustness = 0;
let totalNovelty = 0;
let totalDiversity = 0;
let totalWeight = 0;
let constraintValid = true;
for (const [validatorAddress, contributions] of validatorContributions.entries()) {
const contrib = contributions.get(outputId);
if (!contrib) continue;
const calibration = calibrations.get(validatorAddress);
const weight = calibration?.calibrationScore || 0.5; // Weight by calibration quality
totalRobustness += contrib.robustnessContribution * weight;
totalNovelty += contrib.noveltyContribution * weight;
totalDiversity += contrib.diversityContribution * weight;
totalWeight += weight;
if (!contrib.constraintValid) {
constraintValid = false;
}
}
if (totalWeight > 0) {
const aggregatedContrib: ContributionScore = {
outputId,
robustnessContribution: totalRobustness / totalWeight,
noveltyContribution: totalNovelty / totalWeight,
diversityContribution: totalDiversity / totalWeight,
constraintValid,
totalContribution: (totalRobustness + totalNovelty + totalDiversity) / totalWeight,
};
aggregated.set(outputId, aggregatedContrib);
}
}
return aggregated;
}
/**
* Aggregate distributions across validators
*/
private aggregateDistributions(
validatorDistributions: Map<string, DistributionAnalysis>
): DistributionAnalysis {
if (validatorDistributions.size === 0) {
return {
modes: [],
entropy: 0,
coverage: 0,
diversity: 0,
stabilityScore: 0,
modeCount: 0,
};
}
// Average metrics across validators
let totalEntropy = 0;
let totalCoverage = 0;
let totalDiversity = 0;
let totalStability = 0;
let totalModes = 0;
for (const distribution of validatorDistributions.values()) {
totalEntropy += distribution.entropy;
totalCoverage += distribution.coverage;
totalDiversity += distribution.diversity;
totalStability += distribution.stabilityScore;
totalModes += distribution.modeCount;
}
const count = validatorDistributions.size;
return {
modes: [], // Modes are validator-specific, don't aggregate
entropy: totalEntropy / count,
coverage: totalCoverage / count,
diversity: totalDiversity / count,
stabilityScore: totalStability / count,
modeCount: Math.round(totalModes / count),
};
}
/**
* Calculate method diversity score (replaces agreement score)
*/
private calculateMethodDiversityScore(
evaluations: ValidatorEvaluation[],
calibrations: Map<string, ValidatorCalibrationMetrics>
): number {
if (evaluations.length === 0) return 0;
// Count unique methods
const methods = new Set<string>();
for (const eval_ of evaluations) {
if (eval_.methodConfig) {
methods.add(eval_.methodConfig.methodId);
}
}