Spring › Feature

Building a human-in-the-loop AI review and approval pipeline

Design a human-in-the-loop admin workflow in Spring Boot and Thymeleaf to review, correct, and safely import AI-discovered records with optimistic locking.

Building a human-in-the-loop AI review and approval pipeline

LLM-powered discovery pipelines can surface newsworthy records far faster than keyword crawlers, but writing unverified AI output directly to a production database invites data corruption. This post walks through the human-in-the-loop (HITL) admin review and approval system I built with Spring Boot and Thymeleaf—covering state transitions, optimistic locking against background batches, transaction isolation around external APIs, and safe ingestion into an existing pipeline.


Background: why AI discovery still needs a human gate

In my court-judgment aggregation project (demo-backend-server), a scheduled AI discovery batch (judgment-discovery-job) pairs Google Search grounding with an LLM to scan daily news and flag high-profile court rulings.

Running that job against real news articles quickly exposed three hard limits of full automation:

  1. Imprecise reporting: News articles rarely print full case numbers (like 2026GoHap518291). They say “Seoul Central District Court criminal panel” and “yesterday” or “late last month.”
  2. Hallucination risk: If an LLM guesses a plausible case number or sentence length and the system writes it straight into the core database, the legal reliability of the entire service breaks.
  3. Strict source-of-truth rule: My system follows one non-negotiable rule: news articles are only discovery signals; official court records come strictly from the National Law Information Center public API. When a single character in a case number is off, automated API matching fails and valuable rulings slip through the cracks.
1
[Rule] News articles are only discovery signals; judgments are finalized strictly from official source text.

Instead of asking the LLM to be 100% accurate, I narrowed its job to candidate discovery and issue summarization, and built a human-in-the-loop (HITL) admin console where an operator can correct missing identifiers, re-verify against the official API, and approve import into the production pipeline with a single click. (For the broader conceptual framing of HITL checkpoints and agent safety, see my earlier note on human-in-the-loop design and agent safety.)

Admin dashboard listing AI-discovered judgment candidates by status Figure 1. Admin judgment discovery dashboard (/admin/judgment-discoveries) showing status tabs, priority, case-number identification state, and independent source count.


Candidate lifecycle and state machine

Every candidate moves through a six-state lifecycle from initial AI discovery to official database ingestion:

stateDiagram-v2
    direction LR
    [*] --> NEW: AI discovery batch
    NEW --> AWAITING_SOURCE: Waiting for official API match
    AWAITING_SOURCE --> NEEDS_REVIEW: 14-day timeout or missing ID
    AWAITING_SOURCE --> VERIFIED: Matched official precSerial

    state "Human-in-the-Loop (Admin)" as HITL {
        NEEDS_REVIEW --> NEW: Admin corrects metadata (correct)
        NEEDS_REVIEW --> REJECTED: Admin rejects (reject)
    }
    VERIFIED --> IMPORTED: Admin approves import (approve)
    IMPORTED --> [*]

Status definitions (DiscoveryStatus)

  • NEW: Freshly discovered by the AI batch or just corrected by an admin. Queued immediately for official API verification.
  • AWAITING_SOURCE: The ruling hit the news, but the official court API often lags by several days before publishing the full text. The verifier retries periodically in this state.
  • NEEDS_REVIEW: Missing a case number, or still unmatched after 14 days. Surfaced to operators for manual correction or rejection.
  • VERIFIED: Matched 1:1 to an official precedent serial number (precSerial). Ready for one-click approval.
  • IMPORTED: Passed through the official ingestion pipeline and persisted as a production Judgment entity.
  • REJECTED: Excluded by an operator with a recorded reason (for example, an already closed case or a non-judgment news item).

Domain entity: JudgmentDiscovery

The JudgmentDiscovery entity tracks extracted identifiers, independent news source counts, priority scoring reasons, model/prompt metadata, and a corrected flag that protects human edits from future batch runs.

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
// src/main/kotlin/com/example/server/discovery/domain/JudgmentDiscovery.kt
package com.example.server.discovery.domain

import com.example.server.common.BaseEntity
import com.example.server.common.BusinessException
import jakarta.persistence.*
import java.time.Instant
import java.time.LocalDate
import org.hibernate.Length
import org.hibernate.annotations.ColumnDefault

enum class DiscoveryStatus(val label: String) {
    NEW("Pending Check"),
    NEEDS_REVIEW("Needs Review"),
    AWAITING_SOURCE("Awaiting Source"),
    VERIFIED("Verified"),
    IMPORTED("Imported"),
    REJECTED("Rejected"),
}

@Entity
@Table(
    name = "judgment_discoveries",
    uniqueConstraints = [UniqueConstraint(name = "uk_judgment_discovery_key", columnNames = ["dedup_key"])],
    indexes = [Index(name = "idx_judgment_discovery_status_next", columnList = "status,next_verify_at")]
)
class JudgmentDiscovery(
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long = 0,
    @Column(name = "dedup_key", nullable = false) var dedupKey: String,
    @Column(nullable = false) var title: String,
    @Column(nullable = false, length = Length.LONG32) var issueSummary: String,
    @Column(length = Length.LONG32) var issueEvidence: String? = null,
    var caseNumber: String? = null,
    var courtName: String? = null,
    var sentenceDate: LocalDate? = null,
    @Enumerated(EnumType.STRING) @Column(nullable = false) var instance: DiscoveryInstance = DiscoveryInstance.UNKNOWN,
    @Enumerated(EnumType.STRING) @Column(nullable = false) var recency: DiscoveryRecency = DiscoveryRecency.UNKNOWN,
    @Enumerated(EnumType.STRING) @Column(nullable = false) var status: DiscoveryStatus = DiscoveryStatus.NEW,
    @Column(length = Length.LONG32) var statusReason: String? = null,
    @ColumnDefault("0") var priority: Int = 0,
    @Column(length = 500) var priorityReasons: String? = null,
    @ColumnDefault("0") var independentSourceCount: Int = 0,
    var precSerial: Long? = null,
    @Column(length = 100) var officialDataSourceName: String? = null,
    var judgmentId: Long? = null,
    @Column(nullable = false) var firstDiscoveredAt: Instant = Instant.now(),
    @Column(nullable = false) var lastDiscoveredAt: Instant = Instant.now(),
    @ColumnDefault("1") var discoveryCount: Int = 1,
    var lastRunId: Long? = null,
    @Column(nullable = false, length = 100) var modelName: String,
    @Column(nullable = false, length = 50) var promptVersion: String,
    @Column(name = "next_verify_at") var nextVerifyAt: Instant? = Instant.now(),
    @ColumnDefault("0") var verifyAttempts: Int = 0,
    var lastVerifiedAt: Instant? = null,
    /** Once an admin corrects identifiers, later AI re-discoveries must not overwrite them. */
    @ColumnDefault("false") var corrected: Boolean = false,
    @ElementCollection
    @CollectionTable(name = "judgment_discovery_sources", joinColumns = [JoinColumn(name = "discovery_id")])
    @OrderColumn(name = "position")
    val sources: MutableList<DiscoverySource> = mutableListOf(),
) : BaseEntity() {

    val identified: Boolean get() = caseNumber != null && courtName != null && sentenceDate != null
    val open: Boolean get() = status in setOf(DiscoveryStatus.NEW, DiscoveryStatus.NEEDS_REVIEW, DiscoveryStatus.AWAITING_SOURCE)

    /** Applies admin corrections, clears stale official matches, and requeues for immediate verification. */
    fun correct(
        title: String,
        caseNumber: String?,
        courtName: String?,
        sentenceDate: LocalDate?,
        instance: DiscoveryInstance,
        recency: DiscoveryRecency
    ) {
        if (status == DiscoveryStatus.IMPORTED) throw BusinessException(DiscoveryErrorCode.ALREADY_IMPORTED)
        this.title = title
        this.caseNumber = caseNumber
        this.courtName = courtName
        this.sentenceDate = sentenceDate
        this.instance = instance
        this.recency = recency
        this.corrected = true
        requestVerification()
    }

    fun requestVerification(now: Instant = Instant.now()) {
        if (status == DiscoveryStatus.IMPORTED) throw BusinessException(DiscoveryErrorCode.ALREADY_IMPORTED)
        status = DiscoveryStatus.NEW
        statusReason = null
        precSerial = null
        officialDataSourceName = null
        judgmentId = null
        nextVerifyAt = now
    }
}

The corrected = true flag is a key idempotency guard. When the discovery batch finds a follow-up article on the same case the next day and runs an upsert, it checks corrected so incomplete AI extractions never overwrite the verified case number and court name entered by an operator.


Isolating external API calls and blocking batch races

Both reverify() and approve() call the external National Law Information Center API, which regularly takes 1–3 seconds per request. Wrapping those HTTP calls inside @Transactional would hold a HikariCP database connection idle for the entire round trip.

AdminDiscoveryService keeps the orchestration methods non-transactional: it reads the target metadata, calls the external API outside any transaction, and then delegates the state write to a short @Transactional method on JudgmentDiscoveryService.

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
// src/main/kotlin/com/example/server/admin/application/AdminDiscoveryService.kt
package com.example.server.admin.application

import com.example.server.admin.dto.AdminDiscoveryDetail
import com.example.server.admin.dto.AdminDiscoveryForm
import com.example.server.admin.dto.AdminDiscoveryRow
import com.example.server.common.BusinessException
import com.example.server.discovery.application.DiscoveryVerifier
import com.example.server.discovery.application.JudgmentDiscoveryService
import com.example.server.discovery.domain.DiscoveryStatus
import com.example.server.discovery.domain.JudgmentDiscoveryRepository
import com.example.server.judgment.application.LawPrecedentClient
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class AdminDiscoveryService(
    private val discoveries: JudgmentDiscoveryRepository,
    private val service: JudgmentDiscoveryService,
    private val verifier: DiscoveryVerifier,
    private val client: LawPrecedentClient,
    private val audits: AdminAuditService,
) {
    @Transactional(readOnly = true)
    fun page(status: DiscoveryStatus?, q: String?, pageable: Pageable): Page<AdminDiscoveryRow> =
        discoveries.search(status, q.orEmpty(), pageable).map(AdminDiscoveryRow::from)

    @Transactional(readOnly = true)
    fun detail(id: Long): AdminDiscoveryDetail {
        val d = find(id)
        return AdminDiscoveryDetail(
            row = AdminDiscoveryRow.from(d),
            issueSummary = d.issueSummary,
            issueEvidence = d.issueEvidence,
            precSerial = d.precSerial,
            judgmentId = d.judgmentId,
            firstDiscoveredAt = d.firstDiscoveredAt,
            modelName = d.modelName,
            promptVersion = d.promptVersion,
            verifyAttempts = d.verifyAttempts,
            nextVerifyAt = d.nextVerifyAt,
            lastVerifiedAt = d.lastVerifiedAt,
            corrected = d.corrected,
            sources = d.sources.map { AdminDiscoverySourceRow(it.url, it.domain, it.title, it.reportedDate, it.observedAt) },
            version = d.version,
            audit = audits.of(d)
        )
    }

    /** 1. Correct identifiers with optimistic lock version check */
    fun correct(id: Long, form: AdminDiscoveryForm) =
        service.correct(
            id = id,
            version = form.version,
            title = form.title.trim(),
            caseNumber = form.caseNumber.trim().ifEmpty { null },
            courtName = form.courtName.trim().ifEmpty { null },
            sentenceDate = form.sentenceDate,
            instance = form.instance
        )

    /** 2. Re-verify immediately: external API lookup runs outside the DB transaction */
    fun reverify(id: Long): DiscoveryStatus {
        val target = service.target(id)
        // [External API] Search official precedent listing (non-transactional)
        val outcome = verifier.verify(target)
        // [DB Transaction] Persist verification result
        service.applyVerification(id, outcome, reopen = true, expected = target)
        return find(id).status
    }

    /** 3. Approve and import: fetch official full text outside the transaction, then ingest */
    fun approve(id: Long): String? {
        val target = service.importTarget(id)
        if (target.judgmentId != null) {
            // Already imported by another path; just link the foreign key
            service.link(id, target.precSerial)
            return null
        }
        // [External API] Fetch full precedent payload (non-transactional)
        val detail = client.detail(target.precSerial)
        // [DB Transaction] Delegate to the official ingestion pipeline (raw archive -> parse -> save)
        return service.importRaw(id, target.precSerial, detail.rawJson)
    }

    private fun find(id: Long) =
        discoveries.findByIdOrNull(id) ?: throw BusinessException(DiscoveryErrorCode.NOT_FOUND)
}

Preventing batch-vs-admin race conditions with optimistic locking

While an operator has the detail page open looking up a case number, the background discovery batch might attach a new article link, or the verifier batch might transition the status.

Because JudgmentDiscovery inherits @Version from BaseEntity, the form submits form.version as a hidden field and JudgmentDiscoveryService.correct() checks it before applying updates (the same two-stage pattern I documented in preventing lost updates with JPA @Version):

1
2
3
4
5
6
7
8
9
// JudgmentDiscoveryService.kt
@Transactional
fun correct(id: Long, version: Long, title: String, caseNumber: String?, ...) {
    val discovery = find(id)
    if (discovery.version != version) {
        throw ObjectOptimisticLockingFailureException(JudgmentDiscovery::class.java, id)
    }
    // ...
}

If a background job or another operator modified the candidate first, OptimisticLockingFailureException surfaces a clear reload prompt without clobbering the latest state.


Admin controller and correction UI

AdminDiscoveryController maps the four lifecycle actions—correct, reject, reverify, and approve—and translates domain errors or lock conflicts into inline form errors and flash messages.

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
// src/main/kotlin/com/example/server/admin/presentation/AdminDiscoveryController.kt
package com.example.server.admin.presentation

import com.example.server.admin.application.AdminDiscoveryService
import com.example.server.admin.dto.AdminDiscoveryForm
import com.example.server.admin.dto.AdminDiscoveryRejectForm
import com.example.server.common.BusinessException
import jakarta.validation.Valid
import org.springframework.dao.OptimisticLockingFailureException
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.validation.BindingResult
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.mvc.support.RedirectAttributes

@Controller
@RequestMapping("/admin/judgment-discoveries")
class AdminDiscoveryController(private val discoveries: AdminDiscoveryService) {

    @GetMapping("/{id}")
    fun detail(@PathVariable id: Long, model: Model): String {
        if (!model.containsAttribute("form")) model.addAttribute("form", discoveries.form(id))
        if (!model.containsAttribute("rejectForm")) model.addAttribute("rejectForm", AdminDiscoveryRejectForm())
        model.addAttribute("detail", discoveries.detail(id))
        return "admin/judgment-discovery-detail"
    }

    @PostMapping("/{id}")
    fun correct(
        @PathVariable id: Long,
        @Valid @ModelAttribute("form") form: AdminDiscoveryForm,
        binding: BindingResult,
        model: Model,
        redirect: RedirectAttributes
    ): String {
        if (!binding.hasErrors()) {
            try {
                discoveries.correct(id, form)
                redirect.addFlashAttribute("message", "Identifiers updated. Queued for immediate official verification.")
                return "redirect:/admin/judgment-discoveries/$id"
            } catch (e: BusinessException) {
                binding.reject(e.errorCode.code, e.errorCode.message)
            } catch (e: OptimisticLockingFailureException) {
                binding.reject("version", "Another admin or background job updated this candidate. Please reload.")
            }
        }
        return detail(id, model)
    }

    @PostMapping("/{id}/approve")
    fun approve(@PathVariable id: Long, redirect: RedirectAttributes): String = operation(id, redirect) {
        discoveries.approve(id)?.let { throw ImportHeld(it) }
        "Official judgment imported successfully."
    }

    @PostMapping("/{id}/reverify")
    fun reverify(@PathVariable id: Long, redirect: RedirectAttributes): String = operation(id, redirect) {
        "Re-verified against official registry: ${discoveries.reverify(id).label}"
    }

    private fun operation(id: Long, redirect: RedirectAttributes, action: () -> String): String {
        try {
            redirect.addFlashAttribute("message", action())
        } catch (e: BusinessException) {
            redirect.addFlashAttribute("error", e.errorCode.message)
        } catch (e: ImportHeld) {
            redirect.addFlashAttribute("error", "Raw payload archived, but import was held: ${e.message}")
        } catch (e: OptimisticLockingFailureException) {
            redirect.addFlashAttribute("error", "Another job updated this candidate first. Please try again.")
        }
        return "redirect:/admin/judgment-discoveries/$id"
    }

    private class ImportHeld(message: String) : RuntimeException(message)
}

Candidate detail view and identifier correction form Figure 2. Candidate detail and correction screen (/admin/judgment-discoveries/103). The left panel shows the AI issue summary and news sources; the right panel lets an operator fill in a missing case number (2026GuHap4812) and trigger immediate re-verification.


Reusing the official ingestion pipeline on approval

Writing a second, parallel code path to create Judgment entities just for AI-discovered candidates is an anti-pattern. Whether a record arrives from a scheduled crawler or an AI discovery approval, it should pass through the exact same validation, raw-payload archival, and parsing pipeline.

importRaw() delegates directly to the existing JudgmentImportService.collect() pipeline (following the raw data immutability and reparsing pattern):

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
// JudgmentDiscoveryService.kt
@Transactional
fun importRaw(id: Long, precSerial: Long, rawJson: String): String? {
    val discovery = verifiedFor(id, precSerial)

    val listing = JudgmentListing(
        precSerial = precSerial,
        caseNumber = discovery.caseNumber,
        courtName = discovery.courtName,
        sentenceDate = discovery.sentenceDate?.format(DateTimeFormatter.ofPattern("yyyy.MM.dd"))
    )

    // Reuse the official ingestion pipeline (archive raw JSON -> parse -> save Judgment)
    val result = importer.collect(
        precSerial = precSerial,
        rawJson = rawJson,
        listing = listing,
        dataSourceName = discovery.officialDataSourceName
    )

    // If structured parsing fails, keep the archived raw JSON and send back to review
    if (result.error != null || result.judgmentId == null) {
        discovery.needsReview("Import held: ${result.error}. Inspect the raw archive for details.")
        return result.error
    }

    discovery.imported(result.judgmentId)
    return null
}

Fallback when structured parsing fails

Public API payloads occasionally use unusual formatting that trips the structured parser (ruling summary, holdings, reasoning). Rather than rolling back the entire approval, importer.collect() keeps the immutable raw JSON archived in the database and transitions the candidate back to NEEDS_REVIEW so an operator can inspect the raw record and finish structuring it manually.

Post-approval view showing linked official serial and judgment ID Figure 3. Approved candidate linked to official serial 249811 and production judgment #2841, with the full state transition recorded in the audit log on the right.


Trade-offs and production checklist

A human approval gate is not free. If your pipeline ingests tens of thousands of low-stakes records per day where an occasional formatting error is acceptable, putting an operator in front of every item creates an unmanageable backlog—in that case, rely on automated schema validation plus sampled audits instead. HITL pays off when precision matters more than raw throughput (legal, medical, financial, or canonical master data).

Production checklist:

  • Keep AI scoped to discovery and summarization; source canonical records from an authoritative API or database.
  • Protect human edits with a sticky corrected flag so repeat batch runs never overwrite verified fields.
  • Run external API verification and payload fetches outside @Transactional to protect your DB connection pool.
  • Guard admin edits against concurrent batch updates with @Version optimistic locking.
  • Reuse your existing ingestion pipeline on approval, and archive raw payloads even if downstream parsing fails.
This post is licensed under CC BY 4.0 by the author.