Skip to content

Review routing and audit

Triage of extracted fields by confidence, and an audit trail of what was processed. Neither is called by the built-in pipelines; wire them in where you need them.

ConfidenceRouter

Routes extracted fields based on per-field confidence scores.

The default thresholds are calibrated for typical IDP use-cases:

  • accept_threshold = 0.80 — require high confidence before automation
  • reject_threshold = 0.40 — discard clearly unreliable extractions

For safety-critical fields (passport number, date-of-birth) you should tighten per-field thresholds::

router = ConfidenceRouter(
    field_thresholds={
        "passport_number": (0.95, 0.75),
        "date_of_birth":   (0.90, 0.60),
    }
)

Parameters:

Name Type Description Default
accept_threshold float

Global minimum confidence for auto-accept.

0.8
reject_threshold float

Global maximum confidence for auto-reject.

0.4
field_thresholds dict[str, tuple[float, float]] | None

Per-field overrides {field: (accept, reject)}.

None

Raises:

Type Description
ValueError

If reject_threshold >= accept_threshold, globally or for a field.

route_field(field_name: str, value: Any, confidence: float, document_id: str | None = None, source_span: SourceSpan | None = None) -> ReviewItem

Route a single (field_name, value, confidence) triple.

Returns a ReviewItem with the routing decision and its rationale.

route_document(document: LegalDocument | LegalDoc) -> RoutingResult

Route all extracted fields of a LegalDoc (extracted) or a legacy LegalDocument (extracted_fields).

Populates result.accepted, result.review_queue, and result.rejected. The review queue is sorted by confidence ascending so reviewers see the least-certain items first.

route_dict(fields: dict[str, Any], confidences: dict[str, float], document_id: str | None = None) -> RoutingResult

Route a plain {field_name: value} dict.

Useful when integrating the router into pipelines that produce raw dicts before constructing a LegalDocument.

Parameters:

Name Type Description Default
fields dict[str, Any]

Extracted field values.

required
confidences dict[str, float]

Per-field confidence scores (default 0.0 for missing).

required
document_id str | None

Optional parent document identifier.

None

RoutingResult

Bases: BaseModel

The outcome of routing all fields in a document or dict.

Attributes:

Name Type Description
document_id str | None

Identifier of the document being routed.

accepted dict[str, Any]

Fields that cleared the auto-accept threshold {field_name: value}.

review_queue list[ReviewItem]

Fields requiring human review (ordered by confidence asc).

rejected list[ReviewItem]

Fields that fell below the auto-reject threshold.

acceptance_rate: float property

Fraction of total fields that were auto-accepted.

review_field_names: list[str] property

Names of fields in the review queue.

rejected_field_names: list[str] property

Names of rejected fields.

RoutingDecision

Bases: str, Enum

The routing outcome for a single extracted field.

ReviewItem

Bases: BaseModel

A single field that has been routed (to any queue).

AuditLogger

Thread-safe facade that records AuditEvents via a pluggable backend.

Failures (an invalid field value, a backend error) are caught and re-emitted via the standard logging module so they never interrupt the calling pipeline.

Factories

  • AuditLogger.from_jsonl(path) — JSONL file backend
  • AuditLogger.from_postgres(dsn) — PostgreSQL backend
  • AuditLogger.null() — no-op backend (testing)

Example::

with AuditLogger.from_jsonl("audit/pipeline.jsonl") as al:
    al.log_ingestion("doc-1", source_url="https://docs.test/doc.pdf")
    al.log_extraction("doc-1", ["name", "dob"], overall_confidence=0.91)

from_jsonl(path: str | Path) -> AuditLogger classmethod

Create an AuditLogger backed by a JSONL file.

from_postgres(dsn: str) -> AuditLogger classmethod

Create an AuditLogger backed by PostgreSQL.

null() -> AuditLogger classmethod

Create a no-op logger (useful in tests).

log(event: AuditEvent) -> None

Write a pre-built AuditEvent. Failures are logged, not raised.

log_ingestion(document_id: str, source_url: str | None = None, session_id: str | None = None, user_id: str | None = None, **metadata: Any) -> None

Record that a document was ingested into the pipeline.

log_extraction(document_id: str, fields_extracted: list[str], fields_rejected: list[str] | None = None, overall_confidence: float | None = None, session_id: str | None = None, **metadata: Any) -> None

Record the outcome of a field-extraction step.

log_review_request(document_id: str, fields: list[str], session_id: str | None = None, **metadata: Any) -> None

Record that fields were routed to the human-review queue.

log_review_completion(document_id: str, session_id: str | None = None, **metadata: Any) -> None

Record that human review was completed for a document.

log_deletion(document_id: str, user_id: str | None = None, session_id: str | None = None, **metadata: Any) -> None

Record a GDPR-right-to-erasure deletion event.

log_error(document_id: str | None, error_message: str, session_id: str | None = None, **metadata: Any) -> None

Record a pipeline error.

close() -> None

Close the underlying backend.

AuditEvent

Bases: BaseModel

A single auditable event. All fields are serialisable to JSON.

to_jsonl_line() -> str

Serialise to a single JSON line (no trailing newline in model_dump_json).

AuditEventType

Bases: str, Enum

Taxonomy of auditable pipeline events.

AuditBackend

Bases: ABC

Abstract backend for persisting AuditEvents.

write(event: AuditEvent) -> None abstractmethod

Persist event.

close() -> None abstractmethod

Release resources held by this backend.

NullAuditBackend

Bases: AuditBackend

No-op sink — for tests or when auditing is explicitly disabled.

JSONLAuditBackend

Bases: AuditBackend

Append-only JSONL (newline-delimited JSON) file backend.

Each event occupies exactly one line, making the log trivially ingestible by log aggregators (Splunk, Loki, BigQuery, jq, etc.).

Thread-safe via an internal threading.Lock.

Parameters:

Name Type Description Default
path str | Path

Path to the audit log file. Parent directories are created automatically.

required

read_all(path: str | Path) -> list[AuditEvent] classmethod

Read and deserialise all events from a JSONL file (for inspection / tests).

PostgresAuditBackend

Bases: AuditBackend

PostgreSQL audit backend.

Requires the storage extra::

pip install contractex[storage]

The table is created automatically on first use (ensure_table=True). Each write uses autocommit mode to guarantee durability without wrapping the caller's transaction. A dropped connection (server restart, idle timeout) is re-opened once per write.

Raises ContractExError when a table named audit_log with other columns already exists, instead of failing on every insert.

DDL::

CREATE TABLE IF NOT EXISTS audit_log (
    event_id           UUID PRIMARY KEY,
    timestamp          TIMESTAMPTZ NOT NULL,
    event_type         TEXT NOT NULL,
    document_id        TEXT,
    session_id         TEXT,
    user_id            TEXT,
    source_url         TEXT,
    fields_extracted   TEXT[],
    fields_rejected    TEXT[],
    overall_confidence NUMERIC(4,3),
    error_message      TEXT,
    metadata           JSONB
);