-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTaskService.ts
More file actions
2460 lines (2191 loc) · 84.5 KB
/
TaskService.ts
File metadata and controls
2460 lines (2191 loc) · 84.5 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
/**
* Task Service
*
* Handles complete task lifecycle:
* 1. Task submission
* 2. Miner work (output generation)
* 3. Validator evaluation
* 4. Consensus building
* 5. Human-in-the-loop selection (if enabled)
* 6. Payment settlement
*
* Integrates EvaluationService with contract settlement
*/
import { ILogger } from './utils/ILogger';
import { EvaluationService, TaskOutput, ValidatorEvaluation, HumanSelection, EvaluationResult } from './EvaluationService';
import { NetworkManifest } from './types';
import { ethers } from 'ethers';
import { PrismaClient } from '@prisma/client';
import { SybilResistanceService } from './SybilResistanceService';
// P2PCoordinationService removed from top-level import - libp2p is ESM-only and causes CommonJS import errors
// Will be lazy-loaded if needed
import { OnChainValidatorService } from './OnChainValidatorService';
import { TaskStateIPFSService } from './TaskStateIPFSService';
import { CollusionTrackingService } from './CollusionTrackingService';
import { CollusionPreventionService } from './CollusionPreventionService';
import { BootstrapModeService, BootstrapModeConfig } from './BootstrapModeService';
import { SignatureVerificationService } from './SignatureVerificationService';
import { JSONSchemaValidator } from './JSONSchemaValidator';
import { TaskCompletionService } from '../services/TaskCompletionService';
// Type definitions for P2P (without importing the service)
interface TaskAnnouncement {
taskId: string;
networkId: string;
taskType: string;
requiredValidators: number;
deadline: number;
reward: string;
manifestCid: string;
}
/**
* Task Submission
*/
export interface TaskSubmission {
taskId: string;
networkId: string;
input: any;
depositorAddress: string;
depositAmount: string;
depositTxHash?: string;
timestamp: number;
}
/**
* Task Status
*/
export type TaskStatus =
| 'submitted' // Task submitted, waiting for miners
| 'mining' // Miners producing outputs
| 'evaluating' // Validators evaluating outputs
| 'pre-filtering' // Human-in-the-loop: validators pre-filtering top-N
| 'user-selecting' // Human-in-the-loop: waiting for user selection
| 'consensus-reached' // Consensus reached, ready for payment
| 'user-rejected' // User rejected result, requesting redo
| 'paid' // Payment released
| 'challenged' // Task is challenged
| 'timed-out'; // Task timed out
/**
* Task State
*/
export interface TaskState {
taskId: string;
networkId: string;
status: TaskStatus;
submission: TaskSubmission;
outputs: TaskOutput[]; // Miner outputs
evaluations: ValidatorEvaluation[]; // Validator evaluations
evaluationResult?: EvaluationResult; // Final evaluation result
humanSelection?: HumanSelection; // User selection (if human-in-the-loop)
preFilteredOutputs?: string[]; // Top-N outputs (if human-in-the-loop)
consensusReached: boolean;
winningOutputId?: string;
paymentReleased: boolean;
paymentTxHash?: string;
userRejected?: boolean; // User rejected result
redoCount?: number; // Number of times user requested redo
rejectedValidators?: string[]; // Validators who approved rejected result (encrypted)
collusionPattern?: string; // Encrypted pattern hash for tracking
createdAt: number;
updatedAt: number;
}
export class TaskService {
private logger: ILogger;
private evaluationService: EvaluationService;
private prisma: PrismaClient;
private sybilResistanceService: SybilResistanceService;
private p2pService?: any; // P2PCoordinationService | null - lazy-loaded to avoid ESM import issues
private onChainValidatorService: OnChainValidatorService;
private taskStateIPFSService: TaskStateIPFSService;
private collusionTrackingService: CollusionTrackingService;
private bootstrapModeService: BootstrapModeService;
private collusionPreventionService: CollusionPreventionService;
private signatureVerificationService: SignatureVerificationService;
private jsonSchemaValidator: JSONSchemaValidator;
private taskCompletionService: TaskCompletionService;
constructor(
prisma: PrismaClient,
logger?: Logger,
p2pService?: any // P2PCoordinationService | null - lazy-loaded
) {
this.prisma = prisma;
this.logger = logger || new Logger('TaskService');
this.evaluationService = new EvaluationService(logger);
this.sybilResistanceService = new SybilResistanceService(prisma, logger);
this.p2pService = p2pService;
this.onChainValidatorService = new OnChainValidatorService(logger);
this.taskStateIPFSService = new TaskStateIPFSService(logger);
this.collusionTrackingService = new CollusionTrackingService(prisma, logger);
this.collusionPreventionService = new CollusionPreventionService(prisma, logger);
this.bootstrapModeService = new BootstrapModeService(logger, prisma, this.onChainValidatorService);
this.signatureVerificationService = new SignatureVerificationService(this.logger);
this.jsonSchemaValidator = new JSONSchemaValidator(this.logger);
this.taskCompletionService = new TaskCompletionService(prisma, this.logger);
}
/**
* Submit a new task
* CRITICAL FIX: Now persists to database and assigns validators
*/
async submitTask(
taskId: string,
networkId: string,
input: any,
depositorAddress: string,
depositAmount: string,
manifest: NetworkManifest
): Promise<TaskState> {
// Validate input against schema
this.validateInput(input, manifest.taskFormat.inputSchema);
// Create task state object
const submission: TaskSubmission = {
taskId,
networkId,
input,
depositorAddress,
depositAmount,
timestamp: Date.now(),
};
const taskState: TaskState = {
taskId,
networkId,
status: 'submitted',
submission,
outputs: [],
evaluations: [],
consensusReached: false,
paymentReleased: false,
createdAt: Date.now(),
updatedAt: Date.now(),
};
// CRITICAL: IPFS FIRST (primary source of truth)
// Task submission should not fail if IPFS fails, but we should retry
let ipfsCid: string | null = null;
let ipfsUploadAttempts = 0;
const maxIPFSAttempts = 3;
while (!ipfsCid && ipfsUploadAttempts < maxIPFSAttempts) {
try {
ipfsCid = await this.taskStateIPFSService.uploadTaskState(taskState);
this.logger.info('Task state uploaded to IPFS (primary storage)', { taskId, ipfsCid, attempts: ipfsUploadAttempts + 1 });
// Anchor on-chain (if contract available) - non-blocking
if (manifest.settlement.contractAddress && ipfsCid) {
this.taskStateIPFSService.anchorTaskStateOnChain(
taskId,
ipfsCid,
manifest
).then(() => {
this.logger.info('Task state anchor prepared for on-chain', { taskId });
}).catch(error => {
this.logger.warn('Failed to anchor task state on-chain (non-critical)', { taskId, error });
});
}
break; // Success, exit retry loop
} catch (error) {
ipfsUploadAttempts++;
if (ipfsUploadAttempts >= maxIPFSAttempts) {
this.logger.error('Failed to upload task state to IPFS after all retries', {
taskId,
error,
attempts: ipfsUploadAttempts
});
// Continue anyway - database will be used as fallback
// Task submission should not fail due to IPFS issues
} else {
this.logger.warn('IPFS upload failed, retrying', {
taskId,
attempt: ipfsUploadAttempts,
maxAttempts: maxIPFSAttempts,
error
});
// Wait before retry (exponential backoff)
await new Promise(resolve => setTimeout(resolve, 1000 * ipfsUploadAttempts));
}
}
}
// OPTIONAL: Cache to database (async, non-blocking) - only if IPFS succeeded
// Database is a cache, not primary storage
if (ipfsCid) {
this.cacheTaskStateToDb(taskState, ipfsCid).catch(err => {
this.logger.warn('Failed to cache task state to database (non-critical)', { taskId, err });
// Database cache failure is not critical - IPFS is primary
});
} else {
// If IPFS failed, still cache to database as emergency fallback
// But mark it as needing IPFS upload
this.cacheTaskStateToDb(taskState, null).catch(err => {
this.logger.warn('Failed to cache task state to database fallback', { taskId, err });
});
this.logger.warn('Task state stored in database only (IPFS upload failed) - will retry IPFS upload later', { taskId });
}
// PHASE 3: Validator selection happens on-chain when deposit is made
// After deposit, query contract for selected validators
// NEW: Full P2P task propagation (not just announcement)
if (this.p2pService) {
try {
// 1. Announce task via pubsub (broadcast)
const announcement: TaskAnnouncement = {
taskId,
networkId,
taskType: (manifest.taskFormat.inputSchema as any)?.type || 'unknown',
requiredValidators: manifest.validatorConfig.minValidators,
deadline: Date.now() + (manifest.taskFormat.timeout || 3600000), // Default 1 hour
reward: depositAmount,
manifestCid: manifest.registry.ipfsCid || '',
};
await this.p2pService.announceTask(announcement);
// 2. Propagate task to validator network (direct + relay)
const taskData = {
taskId,
networkId,
input: taskState.submission.input,
manifestCid: manifest.registry.ipfsCid || '',
deadline: announcement.deadline,
reward: depositAmount,
};
const propagationResult = await this.p2pService.propagateTask(
taskId,
networkId,
taskData
);
this.logger.info('Task propagated via P2P', {
taskId,
networkId,
propagated: propagationResult.propagated,
failed: propagationResult.failed,
relayed: propagationResult.relayed,
});
} catch (error) {
this.logger.error('Failed to propagate task via P2P', { taskId, error });
// Don't fail task submission if P2P propagation fails (graceful degradation)
}
}
this.logger.info('Task submitted (IPFS primary, database cached)', { taskId, networkId, ipfsCid });
return taskState;
}
/**
* Add miner output
* CRITICAL FIX: Now persists to database
*/
async addMinerOutput(
taskId: string,
output: any,
minerAddress: string,
manifest: NetworkManifest
): Promise<TaskOutput> {
// Load task from database
const task = await this.prisma.tenseuronTask.findUnique({
where: { taskId },
include: { outputs: true, evaluations: true },
});
if (!task) {
throw new Error('Task not found');
}
// Load task state from database
const taskState = await this.loadTaskStateFromDb(task);
// Validate output against schema
this.validateOutput(output, manifest.taskFormat.outputSchema);
// Generate output ID (hash of output)
const outputId = this.hashOutput(output);
// Check if output already exists
const existingOutput = taskState.outputs.find(o => o.outputId === outputId);
if (existingOutput) {
throw new Error('Output with this ID already exists');
}
// Check if multiple outputs required (statistical mode)
if (manifest.evaluationMode === 'statistical' && manifest.statisticalEvaluation?.multipleOutputs) {
const minOutputs = manifest.statisticalEvaluation.minOutputs || 3;
// Allow multiple outputs from same or different miners
}
const metadata = {
seed: manifest.deterministicReplay?.seedRequired ? this.generateSeed(taskId, minerAddress) : undefined,
intermediateHashes: manifest.deterministicReplay?.intermediateHashing ? [] : undefined,
};
const taskOutput: TaskOutput = {
outputId,
output,
minerAddress,
timestamp: Date.now(),
metadata,
};
// Update task state
taskState.outputs.push(taskOutput);
taskState.status = taskState.outputs.length > 0 ? 'mining' : 'submitted';
taskState.updatedAt = Date.now();
// Upload updated state to IPFS (primary)
let ipfsCid: string | null = null;
try {
ipfsCid = await this.taskStateIPFSService.uploadTaskState(taskState);
this.logger.debug('Task state updated on IPFS', { taskId, ipfsCid });
} catch (error) {
this.logger.warn('Failed to update task state on IPFS (non-critical)', { taskId, error });
}
// Cache to database (async, non-blocking)
await this.cacheTaskStateToDb(taskState, ipfsCid).catch(err => {
this.logger.debug('Failed to cache task state to database (non-critical)', { taskId, err });
});
this.logger.info('Miner output added (IPFS primary, database cached)', { taskId, outputId, minerAddress });
return taskOutput;
}
/**
* Add validator evaluation
* CRITICAL FIX: Now persists to database, verifies signature, and checks Sybil resistance
*/
async addValidatorEvaluation(
taskId: string,
validatorAddress: string,
outputId: string,
score: number,
confidence: number,
signature: string,
manifest: NetworkManifest
): Promise<ValidatorEvaluation> {
// Load task from database
const task = await this.prisma.tenseuronTask.findUnique({
where: { taskId },
include: { outputs: true, evaluations: true },
});
if (!task) {
throw new Error('Task not found');
}
// Verify output exists
const output = task.outputs.find(o => o.outputId === outputId);
if (!output) {
throw new Error('Output not found');
}
// Load task state from database
const taskState = await this.loadTaskStateFromDb(task);
// CRITICAL: Check if validator already evaluated this task (prevent duplicate)
const existingEvaluation = task.evaluations.find(e => e.validatorAddress.toLowerCase() === validatorAddress.toLowerCase());
if (existingEvaluation) {
throw new Error('Validator has already evaluated this task');
}
// FIX #2: Check Sybil resistance (on-chain first, database fallback)
const validatorRegistryAddress = manifest?.settlement.validatorRegistryAddress;
const chain = manifest?.settlement.chain;
const qualification = await this.sybilResistanceService.checkValidatorQualification(
validatorAddress,
taskState.networkId,
validatorRegistryAddress,
chain
);
if (!qualification.qualified) {
throw new Error(`Validator does not meet qualification requirements: ${qualification.reasons.join(', ')}`);
}
// CRITICAL: Validate all inputs before processing
const { InputValidator } = await import('./InputValidator');
const inputValidator = new InputValidator(this.logger);
const evaluationValidation = inputValidator.validateValidatorEvaluation(
validatorAddress,
outputId,
score,
confidence,
signature
);
if (!evaluationValidation.valid) {
throw new Error(`Invalid validator evaluation: ${evaluationValidation.errors.join(', ')}`);
}
if (evaluationValidation.warnings.length > 0) {
this.logger.warn('Validator evaluation warnings', {
taskId,
validatorAddress,
warnings: evaluationValidation.warnings
});
}
// CRITICAL: Verify signature cryptographically (EIP-191)
// Message format: networkId + taskId + outputId + score + confidence + timestamp
const message = JSON.stringify({
networkId: taskState.networkId,
taskId: taskId,
outputId: outputId,
score: score,
confidence: confidence,
timestamp: Date.now(),
});
// Use SignatureVerificationService for consistent verification
const verification = this.signatureVerificationService.verifySignature(
validatorAddress,
signature,
message
);
if (!verification.valid) {
this.logger.error('Signature verification failed', {
taskId,
validatorAddress,
errors: verification.errors,
warnings: verification.warnings,
});
throw new Error(
`Signature verification failed: ${verification.errors.join('; ')}`
);
}
const evaluation: ValidatorEvaluation = {
validatorAddress,
outputId,
score,
confidence,
timestamp: Date.now(),
signature,
};
// CRITICAL FIX: Persist evaluation to database
await this.prisma.tenseuronTaskEvaluation.create({
data: {
taskId: task.id,
validatorAddress,
outputId,
score,
confidence,
signature,
timestamp: new Date(),
},
});
// Update task status
await this.prisma.tenseuronTask.update({
where: { taskId },
data: {
status: 'evaluating',
},
});
this.logger.info('Validator evaluation added and persisted', { taskId, outputId, validatorAddress, score });
return evaluation;
}
/**
* Process evaluations and build consensus
* CRITICAL FIX: Now loads from database and integrates validator selection
*/
async processEvaluations(
taskId: string,
manifest: NetworkManifest,
validatorReputations: Map<string, number> = new Map()
): Promise<EvaluationResult> {
// CRITICAL FIX: Load from database
const task = await this.prisma.tenseuronTask.findUnique({
where: { taskId },
include: {
outputs: true,
evaluations: true,
},
});
if (!task) {
throw new Error('Task not found');
}
// Convert database records to TaskState format
const taskState = await this.loadTaskStateFromDb(task);
// Check minimum validators
if (taskState.evaluations.length < manifest.validatorConfig.minValidators) {
throw new Error(`Insufficient validators: need ${manifest.validatorConfig.minValidators}, got ${taskState.evaluations.length}`);
}
// CRITICAL: Verify ALL validator signatures cryptographically before processing
this.logger.info('Verifying all validator signatures before processing', {
taskId,
evaluationCount: taskState.evaluations.length,
});
const signatureVerification = this.signatureVerificationService.verifyTaskEvaluationSignatures(
taskState.networkId,
taskId,
taskState.evaluations.map((eval_) => ({
validatorAddress: eval_.validatorAddress,
outputId: eval_.outputId,
score: eval_.score,
confidence: eval_.confidence,
signature: eval_.signature,
timestamp: eval_.timestamp,
}))
);
if (!signatureVerification.allValid) {
const invalidCount = signatureVerification.invalidEvaluations.length;
const errorMessage = `Signature verification failed: ${invalidCount} of ${taskState.evaluations.length} signatures are invalid. Invalid validators: ${signatureVerification.invalidEvaluations.map(e => e.validatorAddress).join(', ')}`;
this.logger.error('Signature verification failed', {
taskId,
invalidCount,
totalCount: taskState.evaluations.length,
invalidValidators: signatureVerification.invalidEvaluations.map(e => e.validatorAddress),
errors: signatureVerification.invalidEvaluations.flatMap(e => e.errors),
});
// Filter out invalid evaluations
const validEvaluations = taskState.evaluations.filter(
(eval_) => !signatureVerification.invalidEvaluations.some(
(invalid) => invalid.validatorAddress.toLowerCase() === eval_.validatorAddress.toLowerCase()
)
);
if (validEvaluations.length < manifest.validatorConfig.minValidators) {
throw new Error(
`${errorMessage} After filtering invalid signatures, only ${validEvaluations.length} valid evaluations remain, but ${manifest.validatorConfig.minValidators} are required.`
);
}
// Update taskState with only valid evaluations
taskState.evaluations = validEvaluations;
this.logger.warn('Filtered out invalid signatures, continuing with valid evaluations', {
taskId,
originalCount: taskState.evaluations.length + invalidCount,
validCount: validEvaluations.length,
invalidCount,
});
} else {
this.logger.info('All validator signatures verified successfully', {
taskId,
signatureCount: taskState.evaluations.length,
});
}
let evaluationResult: EvaluationResult;
// Process based on evaluation mode
if (manifest.evaluationMode === 'deterministic') {
evaluationResult = await this.evaluationService.evaluateDeterministic(
taskId,
taskState.submission.input,
taskState.outputs,
taskState.evaluations,
manifest.scoringLogic.hash,
manifest.deterministicReplay
);
} else if (manifest.evaluationMode === 'statistical') {
// Use distribution-based evaluation for non-deterministic tasks
const distributionBased = manifest.statisticalEvaluation?.distributionBased !== false; // Default to true
const taskType = manifest.category || 'general';
evaluationResult = await this.evaluationService.evaluateStatistical(
taskId,
taskState.outputs,
taskState.evaluations,
validatorReputations,
distributionBased,
taskType,
manifest,
taskState.submission.input
);
// For human-in-the-loop, pre-filter top-N outputs
// Pattern: Validators pre-filter → User selects → Reward calculated
if (manifest.humanInTheLoop?.enabled) {
const topN = manifest.humanInTheLoop.topN || 3;
// Use preference-based pre-filtering if user preference is specified
// Otherwise, use top-N by contribution score
const preFilteredOutputIds = await this.evaluationService.preFilterForHumanSelection(
evaluationResult,
topN,
manifest.humanInTheLoop.userPreference
);
taskState.preFilteredOutputs = preFilteredOutputIds;
taskState.status = 'pre-filtering';
// Get output details for logging
const preFilteredOutputs = evaluationResult.statisticalResult?.topOutputs.filter(
o => preFilteredOutputIds.includes(o.outputId)
) || [];
this.logger.info('Top-N outputs pre-filtered for human selection', {
taskId,
topN,
outputs: taskState.preFilteredOutputs,
preferenceType: manifest.humanInTheLoop.userPreference?.type || 'default',
scores: preFilteredOutputs.map(o => ({
outputId: o.outputId,
score: o.weightedScore,
agreement: o.agreementScore
}))
});
// Transition to user-selecting status
taskState.status = 'user-selecting';
}
} else {
// Default to deterministic
evaluationResult = await this.evaluationService.evaluateDeterministic(
taskId,
taskState.submission.input,
taskState.outputs,
taskState.evaluations,
manifest.scoringLogic.hash,
manifest.deterministicReplay
);
}
// NEW: Coordinate validators via P2P for consensus building
if (this.p2pService && taskState.evaluations.length >= manifest.validatorConfig.minValidators) {
try {
// Coordinate validators for consensus building
await this.p2pService.coordinateValidators(
taskId,
manifest.networkId,
'consensus-proposal',
{
evaluations: taskState.evaluations,
outputs: taskState.outputs,
},
'system' // System-initiated coordination
);
this.logger.info('Validator coordination initiated via P2P', {
taskId,
evaluationCount: taskState.evaluations.length,
});
} catch (error) {
this.logger.warn('P2P validator coordination failed (non-critical)', {
taskId,
error: error instanceof Error ? error.message : String(error),
});
// Don't fail evaluation if coordination fails
}
}
// NEW: Coordinate validators via P2P for consensus building
if (this.p2pService && taskState.evaluations.length >= manifest.validatorConfig.minValidators) {
try {
// Coordinate validators for consensus building
await this.p2pService.coordinateValidators(
taskId,
manifest.networkId,
'consensus-proposal',
{
evaluations: taskState.evaluations,
outputs: taskState.outputs,
},
'system' // System-initiated coordination
);
this.logger.info('Validator coordination initiated via P2P', {
taskId,
evaluationCount: taskState.evaluations.length,
});
} catch (error) {
this.logger.warn('P2P validator coordination failed (non-critical)', {
taskId,
error: error instanceof Error ? error.message : String(error),
});
// Don't fail evaluation if coordination fails
}
}
// CRITICAL FIX: Persist evaluation result and update status
const consensus = this.checkConsensus(taskState, manifest);
let newStatus: TaskStatus = taskState.status;
// FIX #4: Detect collusion patterns before consensus
if (taskState.evaluations.length >= manifest.validatorConfig.minValidators) {
const suspiciousAgreements = await this.collusionPreventionService.detectSuspiciousAgreement(
manifest.networkId,
taskState.evaluations.map(e => ({
validatorAddress: e.validatorAddress,
outputId: e.outputId,
score: e.score,
taskId,
}))
);
if (suspiciousAgreements.length > 0) {
this.logger.warn('Suspicious validator agreement detected', {
taskId,
networkId: manifest.networkId,
suspiciousPairs: suspiciousAgreements.length,
});
// Penalize suspicious validators
await this.collusionPreventionService.penalizeSuspiciousValidators(
manifest.networkId,
suspiciousAgreements
);
}
}
if (consensus.reached) {
// If human-in-the-loop, wait for user selection
if (manifest.humanInTheLoop?.enabled && taskState.status === 'pre-filtering') {
newStatus = 'user-selecting';
this.logger.info('Waiting for user selection', { taskId, preFilteredOutputs: taskState.preFilteredOutputs });
} else {
newStatus = 'consensus-reached';
this.logger.info('Consensus reached', { taskId, winningOutputId: evaluationResult.winningOutputId });
}
}
// Persist to database
await this.prisma.tenseuronTask.update({
where: { taskId },
data: {
evaluationResult: JSON.stringify(evaluationResult),
winningOutputId: evaluationResult.winningOutputId,
consensusReached: consensus.reached,
status: newStatus,
preFilteredOutputs: taskState.preFilteredOutputs ? JSON.stringify(taskState.preFilteredOutputs) : null,
},
});
// TASK COMPLETION HOOK: Record task execution for module reputation tracking
// Only record if consensus is reached (task is completed)
const moduleId = manifest.moduleId || manifest.module?.moduleId;
if (consensus.reached && moduleId && evaluationResult.winningOutputId) {
try {
// Calculate average validator score for success rate
const winningEvaluations = taskState.evaluations.filter(
e => e.outputId === evaluationResult.winningOutputId
);
const avgScore = winningEvaluations.length > 0
? winningEvaluations.reduce((sum, e) => sum + e.score, 0) / winningEvaluations.length
: 0;
// Task is successful if consensus reached (validators accepted it)
await this.taskCompletionService.handleTaskCompletion({
moduleId: moduleId,
networkId: taskState.networkId,
taskId: taskId,
status: 'success', // Consensus reached = success
successRate: avgScore, // Average validator score (0-100)
completedAt: new Date(),
});
this.logger.info('Task completion recorded for module reputation', {
moduleId: moduleId,
taskId,
status: 'success',
avgScore,
});
} catch (error) {
// Don't fail task processing if reputation update fails
this.logger.warn('Failed to record task completion (non-critical)', {
moduleId: moduleId,
taskId,
error: error instanceof Error ? error.message : String(error),
});
}
} else if (!consensus.reached && moduleId) {
// Task failed if consensus not reached
try {
await this.taskCompletionService.handleTaskCompletion({
moduleId: moduleId,
networkId: taskState.networkId,
taskId: taskId,
status: 'failed',
successRate: 0,
completedAt: new Date(),
});
this.logger.info('Task completion recorded (failed - no consensus)', {
moduleId: moduleId,
taskId,
});
} catch (error) {
this.logger.warn('Failed to record task completion (non-critical)', {
moduleId: moduleId,
taskId,
error: error instanceof Error ? error.message : String(error),
});
}
}
// FULLY IMPLEMENTED: Automatically upload task state to IPFS after processing evaluations (coordinator execution)
// This ensures task state is always persisted to IPFS when validators/coordinators process evaluations
try {
const ipfsCid = await this.taskStateIPFSService.uploadTaskState(taskState);
if (ipfsCid) {
// Anchor on-chain if manifest has contract address
if (manifest.settlement?.contractAddress) {
await this.taskStateIPFSService.anchorTaskStateOnChain(taskId, ipfsCid, manifest).catch(err => {
this.logger.debug('Failed to anchor task state on-chain (non-critical)', { taskId, err });
});
}
// Update database with IPFS CID
await this.prisma.tenseuronTask.update({
where: { taskId },
data: { taskStateIpfsCid: ipfsCid },
}).catch(err => {
this.logger.debug('Failed to update IPFS CID in database (non-critical)', { taskId, err });
});
this.logger.info('Task state automatically uploaded to IPFS by coordinator', { taskId, ipfsCid });
}
} catch (error) {
this.logger.warn('Failed to automatically upload task state to IPFS (non-critical)', {
taskId,
error: error instanceof Error ? error.message : String(error),
});
// Don't fail evaluation processing if IPFS upload fails
}
return evaluationResult;
}
/**
* Human-in-the-loop: User selects from top-N outputs
* CRITICAL FIX: Now loads from and persists to database
*/
async addHumanSelection(
taskId: string,
selectedOutputId: string,
userAddress: string,
manifest: NetworkManifest
): Promise<EvaluationResult> {
// CRITICAL FIX: Load from database
const task = await this.prisma.tenseuronTask.findUnique({
where: { taskId },
include: {
outputs: true,
evaluations: true,
},
});
if (!task) {
throw new Error('Task not found');
}
if (!manifest.humanInTheLoop?.enabled) {
throw new Error('Human-in-the-loop not enabled for this network');
}
if (task.status !== 'user-selecting') {
throw new Error('Task is not in user-selecting status');
}
// Verify selected output is in pre-filtered list
const preFilteredOutputs = task.preFilteredOutputs ? JSON.parse(task.preFilteredOutputs) : [];
if (!preFilteredOutputs.includes(selectedOutputId)) {
throw new Error('Selected output must be from pre-filtered top-N outputs');
}
const taskState = await this.loadTaskStateFromDb(task);
// Create human selection
const humanSelection: HumanSelection = {
taskId,
selectedOutputId,
userAddress,
timestamp: Date.now(),
preFilteredOutputs: taskState.preFilteredOutputs,
};
// Re-evaluate with human selection
if (!taskState.evaluationResult) {
throw new Error('Evaluation result not found. Process evaluations first.');
}
// Verify we have statistical result (human-in-the-loop requires statistical mode)
if (!taskState.evaluationResult.statisticalResult) {
throw new Error('Human-in-the-loop requires statistical evaluation mode');
}
// Get user selection weight from manifest (default 10%)
const userSelectionWeight = manifest.humanInTheLoop?.userSelectionWeight || 0.1;
const finalResult = this.evaluationService.evaluateHumanInTheLoop(
taskId,
taskState.evaluationResult,
humanSelection,
manifest.humanInTheLoop.topN || 3,
userSelectionWeight
);
// CRITICAL FIX: Persist to database
await this.prisma.tenseuronTask.update({
where: { taskId },
data: {
humanSelection: JSON.stringify(humanSelection),
evaluationResult: JSON.stringify(finalResult),
winningOutputId: selectedOutputId,
consensusReached: true,
status: 'consensus-reached',
},
});
const selectedOutput = finalResult.statisticalResult?.topOutputs.find(
o => o.outputId === selectedOutputId
);
const baseScore = selectedOutput?.weightedScore || 0;
const userBoost = baseScore * (manifest.humanInTheLoop?.userSelectionWeight || 0.1);
this.logger.info('Human selection added and persisted', {
taskId,
selectedOutputId,
userAddress,
baseScore,
userBoost,
finalScore: finalResult.finalScore,
userSelectionWeight: manifest.humanInTheLoop?.userSelectionWeight || 0.1
});
// TASK COMPLETION HOOK: Record task execution for module reputation tracking
// Human selection = task completed successfully
const moduleId = manifest.moduleId || manifest.module?.moduleId;
if (moduleId) {
try {
// Calculate success rate from final score
const successRate = finalResult.finalScore || baseScore;
await this.taskCompletionService.handleTaskCompletion({
moduleId: moduleId,
networkId: task.networkId,
taskId: taskId,
status: 'success', // Human selection = success
successRate: successRate, // Final score from human-in-the-loop evaluation
completedAt: new Date(),
});
this.logger.info('Task completion recorded (human selection)', {
moduleId: moduleId,
taskId,
successRate,
});
} catch (error) {
// Don't fail human selection if reputation update fails
this.logger.warn('Failed to record task completion (non-critical)', {
moduleId: moduleId,
taskId,
error: error instanceof Error ? error.message : String(error),
});
}
}