-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhitl.service.ts
More file actions
751 lines (663 loc) · 23.3 KB
/
Copy pathhitl.service.ts
File metadata and controls
751 lines (663 loc) · 23.3 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
import { getErrorMessage } from "@ai-di/shared-logging";
import {
CorrectionAction,
Document,
DocumentStatus,
OcrResult,
Prisma,
ReviewSession,
ReviewStatus,
} from "@generated/client";
import {
ConflictException,
ForbiddenException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { ModuleRef } from "@nestjs/core";
import { AuditService } from "@/audit/audit.service";
import { DocumentField, ExtractedFields } from "@/ocr/azure-types";
import { GroundTruthGenerationService } from "../benchmark/ground-truth-generation.service";
import { DocumentService } from "../document/document.service";
import { AppLoggerService } from "../logging/app-logger.service";
import { AnalyticsService } from "./analytics.service";
import { EscalateDto, SubmitCorrectionsDto } from "./dto/correction.dto";
import { AnalyticsFilterDto, QueueFilterDto } from "./dto/queue-filter.dto";
import { ReviewSessionDto } from "./dto/review-session.dto";
import {
DocumentStatusFilter,
ReviewStatusFilter,
} from "./dto/status-constants.dto";
import { ReviewDbService } from "./review-db.service";
import type { ReviewSessionData } from "./review-db.types";
interface DocumentWithOcrResult extends Document {
ocr_result: OcrResult | null;
review_sessions?: Array<{
id: string;
reviewer_id: string;
status: ReviewStatus;
completed_at: Date | null;
corrections?: unknown[];
}>;
}
interface ReviewSessionWithDocument extends ReviewSession {
document: DocumentWithOcrResult;
}
function readTemplateModelIdFromMetadata(
metadata: unknown,
): string | undefined {
if (
metadata === null ||
metadata === undefined ||
typeof metadata !== "object" ||
Array.isArray(metadata)
) {
return undefined;
}
const raw = (metadata as Record<string, unknown>).templateModelId;
if (typeof raw !== "string") return undefined;
const trimmed = raw.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
@Injectable()
export class HitlService {
constructor(
private readonly documentService: DocumentService,
private readonly reviewDb: ReviewDbService,
private readonly analyticsService: AnalyticsService,
private readonly logger: AppLoggerService,
private readonly auditService: AuditService,
private readonly moduleRef: ModuleRef,
) {}
async getQueue(
filters: QueueFilterDto,
groupIds?: string[],
currentReviewerId?: string,
) {
this.logger.debug("Getting review queue with filters", { ...filters });
const maxConfidence = filters.maxConfidence ?? 0.9;
const reviewStatusFilter =
filters.reviewStatus === ReviewStatusFilter.ALL
? "all"
: filters.reviewStatus === ReviewStatusFilter.REVIEWED
? "reviewed"
: "pending";
const statuses: DocumentStatus[] =
filters.status === DocumentStatusFilter.EXTRACTED
? [DocumentStatus.extracted]
: filters.status === DocumentStatusFilter.ALL
? [DocumentStatus.extracted, DocumentStatus.awaiting_review]
: [DocumentStatus.awaiting_review];
const documents = (await this.reviewDb.findReviewQueue({
statuses,
modelId: filters.modelId,
maxConfidence: filters.maxConfidence ?? 0.9,
limit: filters.limit ?? 50,
offset: filters.offset ?? 0,
reviewStatus: reviewStatusFilter,
groupIds,
currentReviewerId,
})) as DocumentWithOcrResult[];
// Filter by confidence if OCR results exist
const filtered = documents.filter((doc) => {
if (!doc.ocr_result) return false;
const fields = doc.ocr_result
.keyValuePairs as unknown as ExtractedFields | null;
if (!fields) return false;
if (typeof fields !== "object") return false;
// Check if any field has confidence below threshold
const hasLowConfidence = Object.values(fields).some(
(field: DocumentField) => {
if (field?.confidence !== undefined) {
return field.confidence < maxConfidence;
}
return false;
},
);
return hasLowConfidence;
});
return {
documents: filtered.map((doc) => ({
id: doc.id,
original_filename: doc.original_filename,
status: doc.status,
model_id: doc.model_id,
created_at: doc.created_at,
updated_at: doc.updated_at,
ocr_result: {
fields: doc.ocr_result?.keyValuePairs || {},
},
lastSession: doc.review_sessions?.[0]
? {
id: doc.review_sessions[0].id,
reviewer_id: doc.review_sessions[0].reviewer_id,
status: doc.review_sessions[0].status,
completed_at: doc.review_sessions[0].completed_at,
corrections_count:
doc.review_sessions[0].corrections?.length || 0,
}
: undefined,
})),
total: filtered.length,
};
}
async getQueueStats(reviewStatus?: ReviewStatusFilter, groupIds?: string[]) {
this.logger.debug("Getting queue statistics");
const reviewStatusFilter =
reviewStatus === ReviewStatusFilter.ALL
? "all"
: reviewStatus === ReviewStatusFilter.REVIEWED
? "reviewed"
: "pending";
const allDocs = (await this.reviewDb.findReviewQueue({
statuses: [DocumentStatus.awaiting_review],
limit: 1000,
reviewStatus: reviewStatusFilter,
groupIds,
})) as DocumentWithOcrResult[];
const lowConfidenceDocs = allDocs.filter((doc) => {
if (!doc.ocr_result?.keyValuePairs) return false;
const fields = doc.ocr_result.keyValuePairs as unknown as ExtractedFields;
if (typeof fields !== "object") return false;
return Object.values(fields).some((field: DocumentField) => {
if (field?.confidence !== undefined) {
return field.confidence < 0.9;
}
return false;
});
});
const analytics = await this.analyticsService.getAnalytics({}, groupIds);
return {
totalDocuments: allDocs.length,
requiresReview: lowConfidenceDocs.length,
averageConfidence: analytics.averageConfidence,
reviewedToday: analytics.reviewedDocuments,
};
}
async startSession(dto: ReviewSessionDto, reviewerId: string) {
this.logger.debug(
`Starting review session for document: ${dto.documentId}`,
);
// Verify document exists
const document = await this.documentService.findDocument(dto.documentId);
if (!document) {
throw new NotFoundException(`Document ${dto.documentId} not found`);
}
// Check for existing lock
const existingLock = await this.reviewDb.findActiveLock(dto.documentId);
if (existingLock) {
if (existingLock.reviewer_id === reviewerId) {
// Same reviewer — return existing session
return this.getSession(existingLock.session_id);
}
throw new ConflictException(
"Document is currently locked by another reviewer",
);
}
// Create review session
const session = await this.reviewDb.createReviewSession(
dto.documentId,
reviewerId,
);
// Acquire document lock with 10-minute TTL
const lockTtlMs = 10 * 60 * 1000;
await this.reviewDb.acquireDocumentLock({
document_id: dto.documentId,
reviewer_id: reviewerId,
session_id: session.id,
expires_at: new Date(Date.now() + lockTtlMs),
});
const doc = session.document as {
group_id?: string;
workflow_execution_id?: string;
};
await this.auditService.recordEvent({
event_type: "review_session_started",
resource_type: "review_session",
resource_id: session.id,
actor_id: reviewerId,
document_id: session.document_id,
workflow_execution_id: doc.workflow_execution_id ?? undefined,
group_id: doc.group_id ?? undefined,
payload: { document_id: session.document_id },
});
return {
id: session.id,
documentId: session.document_id,
reviewerId: session.actor_id,
status: session.status,
startedAt: session.started_at,
document: {
id: session.document.id,
original_filename: session.document.original_filename,
storage_path: session.document.file_path,
ocr_result: {
fields:
(session.document as ReviewSessionWithDocument["document"])
.ocr_result?.keyValuePairs || {},
},
},
};
}
/**
* Returns a raw review session for authorization checks (e.g. group membership).
* @param id - The review session ID.
* @param tx - Optional transaction client for atomic operations.
* @returns The review session data, or null if not found.
*/
async findReviewSession(
id: string,
tx?: Prisma.TransactionClient,
): Promise<ReviewSessionData | null> {
return this.reviewDb.findReviewSession(id, tx);
}
/**
* Returns raw documents from the review queue for data access needs.
* @param filters - Filtering options for the queue.
* @param tx - Optional transaction client for atomic operations.
* @returns Array of documents matching the filters.
*/
async findReviewQueue(
filters: {
statuses: DocumentStatus[];
modelId?: string;
minConfidence?: number;
maxConfidence?: number;
limit?: number;
offset?: number;
reviewStatus?: "pending" | "reviewed" | "all";
groupIds?: string[];
},
tx?: Prisma.TransactionClient,
): Promise<Document[]> {
return this.reviewDb.findReviewQueue(filters, tx);
}
async getSession(id: string) {
this.logger.debug(`Getting session: ${id}`);
const session = await this.reviewDb.findReviewSession(id);
if (!session) {
throw new NotFoundException(`Review session ${id} not found`);
}
const doc = session.document as ReviewSessionWithDocument["document"];
// Fetch field definitions for format-aware HITL validation. Prefer the exact
// template model recorded on the document (a Group can hold many templates;
// only one was actually used). Fall back to the group lookup for older docs.
const templateModelId = readTemplateModelIdFromMetadata(
session.document.metadata,
);
const fieldDefinitions =
templateModelId || session.document.group_id
? await this.reviewDb.findFieldDefinitionsForDocument({
templateModelId,
groupId: session.document.group_id,
})
: [];
return {
id: session.id,
documentId: session.document_id,
reviewerId: session.actor_id,
status: session.status,
startedAt: session.started_at,
completedAt: session.completed_at,
document: {
id: session.document.id,
original_filename: session.document.original_filename,
storage_path: session.document.file_path,
ocr_result: {
fields: doc.ocr_result?.keyValuePairs || {},
enrichment_summary: doc.ocr_result?.enrichment_summary ?? undefined,
},
},
corrections: session.corrections,
fieldDefinitions,
};
}
async submitCorrections(sessionId: string, dto: SubmitCorrectionsDto) {
this.logger.debug(`Submitting corrections for session: ${sessionId}`);
const session = await this.reviewDb.findReviewSession(sessionId);
if (!session) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
// Save all corrections
const savedCorrections = await Promise.all(
dto.corrections.map((correction) =>
this.reviewDb.createFieldCorrection(sessionId, {
field_key: correction.field_key,
original_value: correction.original_value,
corrected_value: correction.corrected_value,
original_conf: correction.original_conf,
action: correction.action,
}),
),
);
const doc = session.document as {
group_id?: string;
workflow_execution_id?: string;
};
await this.auditService.recordEvent({
event_type: "review_corrections_submitted",
resource_type: "review_session",
resource_id: sessionId,
document_id: session.document_id,
workflow_execution_id: doc.workflow_execution_id ?? undefined,
group_id: doc.group_id ?? undefined,
payload: { correction_count: savedCorrections.length },
});
return {
sessionId,
corrections: savedCorrections,
message: `Saved ${savedCorrections.length} corrections`,
};
}
async approveSession(sessionId: string) {
this.logger.debug(`Approving session: ${sessionId}`);
const session = await this.reviewDb.findReviewSession(sessionId);
if (!session) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
const updated = await this.reviewDb.updateReviewSession(sessionId, {
status: ReviewStatus.approved,
completed_at: new Date(),
});
// Transition document to 'complete' status after HITL approval
await this.documentService.updateDocument(session.document_id, {
status: DocumentStatus.complete,
});
await this.reviewDb.releaseDocumentLock(sessionId);
const doc = session.document as {
group_id?: string;
workflow_execution_id?: string;
};
await this.auditService.recordEvent({
event_type: "review_session_approved",
resource_type: "review_session",
resource_id: sessionId,
document_id: session.document_id,
workflow_execution_id: doc.workflow_execution_id ?? undefined,
group_id: doc.group_id ?? undefined,
payload: { document_id: session.document_id },
});
if (!updated) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
// Post-approval hook: complete ground truth job if this document is part of GT generation.
// ModuleRef.get() lazily resolves GroundTruthGenerationService at runtime to avoid a circular
// module dependency between HitlModule and BenchmarkModule. The call is one-directional
// (HITL notifies Benchmark) and non-critical (approval succeeds even if the service is unavailable).
try {
const gtService = this.moduleRef.get(GroundTruthGenerationService, {
strict: false,
});
if (gtService) {
const job = await gtService.getJobByDocumentId(session.document_id);
if (job) {
await gtService.completeJob(job.id, sessionId);
this.logger.log(
`Ground truth generated for job ${job.id} via session ${sessionId}`,
);
}
}
} catch (error) {
// Non-critical: log but don't fail the approval
this.logger.warn(
`Ground truth post-approval hook error: ${getErrorMessage(error)}`,
);
}
return {
id: updated.id,
status: updated.status,
completedAt: updated.completed_at,
message: "Review session approved",
};
}
async escalateSession(sessionId: string, dto: EscalateDto) {
this.logger.debug(`Escalating session: ${sessionId}`);
const session = await this.reviewDb.findReviewSession(sessionId);
if (!session) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
// Create a correction record to track the escalation reason
await this.reviewDb.createFieldCorrection(sessionId, {
field_key: "_escalation",
original_value: dto.reason,
action: CorrectionAction.flagged,
});
const updated = await this.reviewDb.updateReviewSession(sessionId, {
status: ReviewStatus.escalated,
completed_at: new Date(),
});
if (!updated) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
await this.reviewDb.releaseDocumentLock(sessionId);
const doc = session.document as {
group_id?: string;
workflow_execution_id?: string;
};
await this.auditService.recordEvent({
event_type: "review_session_escalated",
resource_type: "review_session",
resource_id: sessionId,
document_id: session.document_id,
workflow_execution_id: doc.workflow_execution_id ?? undefined,
group_id: doc.group_id ?? undefined,
payload: { document_id: session.document_id, reason: dto.reason },
});
return {
id: updated.id,
status: updated.status,
reason: dto.reason,
message: "Review session escalated",
};
}
async skipSession(sessionId: string) {
this.logger.debug(`Skipping session: ${sessionId}`);
const session = await this.reviewDb.findReviewSession(sessionId);
if (!session) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
const updated = await this.reviewDb.updateReviewSession(sessionId, {
status: ReviewStatus.skipped,
completed_at: new Date(),
});
if (!updated) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
await this.reviewDb.releaseDocumentLock(sessionId);
const doc = session.document as {
group_id?: string;
workflow_execution_id?: string;
};
await this.auditService.recordEvent({
event_type: "review_session_skipped",
resource_type: "review_session",
resource_id: sessionId,
document_id: session.document_id,
workflow_execution_id: doc.workflow_execution_id ?? undefined,
group_id: doc.group_id ?? undefined,
payload: { document_id: session.document_id },
});
return {
id: updated.id,
status: updated.status,
message: "Review session skipped",
};
}
async getCorrections(sessionId: string) {
this.logger.debug(`Getting corrections for session: ${sessionId}`);
const session = await this.reviewDb.findReviewSession(sessionId);
if (!session) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
const corrections = await this.reviewDb.findSessionCorrections(sessionId);
return {
sessionId,
corrections: corrections.map((c) => ({
id: c.id,
fieldKey: c.field_key,
originalValue: c.original_value,
correctedValue: c.corrected_value,
originalConfidence: c.original_conf,
action: c.action,
createdAt: c.created_at,
})),
};
}
async getAnalytics(filters: AnalyticsFilterDto, groupIds?: string[]) {
this.logger.debug("Getting analytics");
return this.analyticsService.getAnalytics(filters, groupIds);
}
async heartbeat(sessionId: string) {
const lockTtlMs = 10 * 60 * 1000;
const newExpiry = new Date(Date.now() + lockTtlMs);
const refreshed = await this.reviewDb.refreshLockHeartbeat(
sessionId,
newExpiry,
);
if (!refreshed) {
throw new ConflictException("Lock expired or session not found");
}
return { ok: true, expiresAt: newExpiry };
}
async deleteCorrection(sessionId: string, correctionId: string) {
const session = await this.reviewDb.findReviewSession(sessionId);
if (!session) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
const deleted = await this.reviewDb.deleteCorrection(
correctionId,
sessionId,
);
if (!deleted) {
throw new NotFoundException(`Correction ${correctionId} not found`);
}
return { deleted: true };
}
async reopenSession(sessionId: string, reviewerId: string) {
const session = await this.reviewDb.findReviewSession(sessionId);
if (!session) {
throw new NotFoundException(`Review session ${sessionId} not found`);
}
if (session.actor_id !== reviewerId) {
throw new ForbiddenException(
"Only the original reviewer can reopen this session",
);
}
if (session.status === ReviewStatus.in_progress) {
throw new ConflictException("Session is already in progress");
}
// Determine reopen eligibility based on workflow type
const groundTruthJob = session.document.groundTruthJob;
if (groundTruthJob) {
// Dataset labeling workflow: block if dataset version is frozen
if (groundTruthJob.datasetVersion.frozen) {
throw new ConflictException("Cannot reopen: dataset version is frozen");
}
} else {
// Regular workflow: allow within 5 minutes of completion
const fiveMinutesMs = 5 * 60 * 1000;
if (
!session.completed_at ||
Date.now() - session.completed_at.getTime() > fiveMinutesMs
) {
throw new ConflictException("Cannot reopen: reopen window has expired");
}
}
// Update session to in_progress
await this.reviewDb.updateReviewSession(sessionId, {
status: ReviewStatus.in_progress,
completed_at: null,
});
// Re-acquire document lock
const lockTtlMs = 10 * 60 * 1000;
await this.reviewDb.acquireDocumentLock({
document_id: session.document_id,
reviewer_id: reviewerId,
session_id: sessionId,
expires_at: new Date(Date.now() + lockTtlMs),
});
const doc = session.document as {
group_id?: string;
workflow_execution_id?: string;
};
await this.auditService.recordEvent({
event_type: "review_session_reopened",
resource_type: "review_session",
resource_id: sessionId,
actor_id: reviewerId,
document_id: session.document_id,
workflow_execution_id: doc.workflow_execution_id ?? undefined,
group_id: doc.group_id ?? undefined,
payload: { document_id: session.document_id },
});
// Revert ground truth job to awaiting_review if this document is part of GT generation
let gtService: GroundTruthGenerationService | undefined;
try {
gtService = this.moduleRef.get(GroundTruthGenerationService, {
strict: false,
});
} catch {
// Service not available (e.g. test environment)
}
if (gtService) {
const job = await gtService.getJobByDocumentId(session.document_id);
if (job) {
await gtService.reopenJob(job.id);
this.logger.log(
`Ground truth job ${job.id} reverted for reopened session ${sessionId}`,
);
}
}
return {
id: sessionId,
status: ReviewStatus.in_progress,
message: "Review session reopened",
};
}
async getNextSession(
filters: {
modelId?: string;
maxConfidence?: number;
reviewStatus?: ReviewStatusFilter;
group_id?: string;
},
reviewerId: string,
groupIds: string[],
) {
const maxConfidence = filters.maxConfidence ?? 0.9;
const reviewStatusFilter =
filters.reviewStatus === ReviewStatusFilter.ALL
? "all"
: filters.reviewStatus === ReviewStatusFilter.REVIEWED
? "reviewed"
: "pending";
const documents = (await this.reviewDb.findReviewQueue({
statuses: [DocumentStatus.awaiting_review],
modelId: filters.modelId,
maxConfidence,
limit: 10,
reviewStatus: reviewStatusFilter,
groupIds,
currentReviewerId: reviewerId,
})) as DocumentWithOcrResult[];
// Filter by confidence — same logic as getQueue
const eligible = documents.filter((doc: DocumentWithOcrResult) => {
if (!doc.ocr_result) return false;
const fields = doc.ocr_result
.keyValuePairs as unknown as ExtractedFields | null;
if (!fields) return false;
if (typeof fields !== "object") return false;
return Object.values(fields).some((field: DocumentField) => {
if (field?.confidence !== undefined) {
return field.confidence < maxConfidence;
}
return false;
});
});
if (eligible.length === 0) {
return null;
}
const firstDoc = eligible[0];
return this.startSession({ documentId: firstDoc.id }, reviewerId);
}
}