Oversight, Appeals, and Escalation › Implementation
Language AI HandbookAll chapters Setup
We need a little randomness with a fixed seed so results are reproducible, plus the plotting helpers used throughout the book. We'll keep the whole system dependency-light: standard library, numpy for sampling, pandas for the audit table.
PythonIn [2]Expand
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
import numpy as np
import pandas as pd
RNG = np.random.default_rng(7)
pd.set_option("display.width", 140)
pd.set_option("display.max_columns", 20)The decision record and its states
A decision record stores the recommendation, evidence, current owner, and event history. This example uses mutable in-memory Python objects. Production records need access controls and a persistent, append-only way to preserve the evidence and reasoning available at each step.
The reviewer needs to see what evidence was available when the initial decision was made. The audit record should preserve those inputs and separate any later corrections. The example keeps an ordered list of transition notes for this purpose. It can be edited by a caller with access to the object, so it demonstrates the record layout without implementing storage integrity.
PythonIn [4]Expand
class Status(Enum):
PROPOSED = "proposed"
AUTO_APPROVED = "auto_approved"
PENDING_REVIEW = "pending_review"
DENIAL_COMMUNICATED = "denial_communicated"
ESCALATED = "escalated"
APPEALED = "appealed"
UNDER_APPEAL_REVIEW = "under_appeal_review"
OVERTURNED = "overturned"
UPHELD = "upheld"
@dataclass
class Decision:
decision_id: str
subject_id: str
model_label: str # model output: "credit", "decline", "adjuster"
model_score: float # toy routing score in [0, 1]
evidence: list[str] # inputs the model saw
owner: str # accountable role, not a team alias
status: Status = Status.PROPOSED
created_at: int = 0
history: list[tuple[int, str]] = field(default_factory=list)
def transition(self, new_status: Status, at_time: int, note: str = ""):
# Record every transition, with the time and a note, for audit.
allowed = {
Status.PROPOSED: {Status.AUTO_APPROVED, Status.PENDING_REVIEW},
Status.PENDING_REVIEW: {
Status.DENIAL_COMMUNICATED,
Status.ESCALATED,
},
Status.ESCALATED: {Status.DENIAL_COMMUNICATED, Status.ESCALATED},
Status.DENIAL_COMMUNICATED: {Status.APPEALED},
Status.APPEALED: {Status.UNDER_APPEAL_REVIEW},
Status.UNDER_APPEAL_REVIEW: {Status.OVERTURNED, Status.UPHELD},
}
if new_status not in allowed.get(self.status, ()):
raise ValueError("The requested transition is not allowed.")
previous_hour = self.history[-1][0] if self.history else self.created_at
if at_time < previous_hour:
raise ValueError("Events must be recorded in time order.")
self.status = new_status
self.history.append(
(at_time, f"{new_status.value}: {note}".strip(": "))
)ConsoleOut [5]Expand
t= 0h pending_review: decline recommendation queued t= 2h denial_communicated: initial reviewer notified customer t= 48h appealed: customer contested decline t= 49h under_appeal_review: assigned independent reviewer t= 60h overturned: second charge confirmed, credit issued final status: overturned
The record shows the queue entry, notice, appeal, and reversal in time order. The assigned reviewer and remedy here are test data. A live system would verify the reviewer assignment and confirm that the billing system applied the credit.
Routing: review queue, auto-approve, and sampling
The toy desk accepts only the three declared recommendation labels. It sends decline and adjuster recommendations to a reviewer, regardless of the score. It also routes credits with scores below 0.60 and samples some of the remaining credits. These scores are fictional routing signals on a zero-to-one scale. They carry no calibrated probability interpretation.
In this desk, a mistaken decline can leave a duplicate charge in place. The model can also explicitly request an adjuster. Sampling the otherwise eligible credits gives the desk a set it can verify against the ledger. A population error estimate requires consistent sampling and reliable adjudication, both beyond the routing counts presented here.
PythonIn [6]Expand
def route(decision: Decision, rng, sample_rate: float = 0.05) -> Decision:
"""Apply the review-routing policy to a proposed decision."""
if decision.model_label not in {"credit", "decline", "adjuster"}:
raise ValueError("Unrecognized recommendation label.")
risky = decision.model_label in {"decline", "adjuster"}
low_conf = decision.model_score < 0.60
sampled = rng.random() < sample_rate
if risky or low_conf or sampled:
reason = (
"risky"
if risky
else "low_confidence"
if low_conf
else "random_sample"
)
decision.transition(Status.PENDING_REVIEW, decision.created_at, reason)
else:
decision.transition(Status.AUTO_APPROVED, decision.created_at, "policy")
return decisionConsoleOut [7]Expand
pending_review 8 auto_approved 4 Name: count, dtype: int64
The composition of this small batch is easier to read as a chart than as a raw count. Each bar is one routing bucket, and the pending-review cases are broken out by the rule that caught them.
VisualizationOut [9]Expand

The bars report how cases were routed under this policy. If more than one review condition holds, the recorded bucket reflects the first applicable rule. These counts do not measure how many routing decisions or recommendations were correct.
Escalation
Escalation happens when the first-line reviewer cannot resolve a case. Reasons include: insufficient authority, conflicting evidence, a claim type outside the reviewer's remit, or simply a case the reviewer believes is miscategorized. We model escalation as an explicit transition with a recorded reason and a handoff to a higher-authority role.
Record the reason for each transfer. For example, “authority insufficient” can distinguish a permissions gap from a case waiting on additional evidence.
PythonIn [10]Expand
ESCALATION_LADDER = ["claims-reviewer", "claims-ops-lead", "compliance-officer"]
def escalate(decision: Decision, at_time: int, reason: str) -> Decision:
"""Move a pending review up one rung of the escalation ladder."""
if decision.status not in {Status.PENDING_REVIEW, Status.ESCALATED}:
raise ValueError("Only an unresolved review can escalate.")
idx = ESCALATION_LADDER.index(decision.owner)
if idx == len(ESCALATION_LADDER) - 1:
raise ValueError("Top role must resolve or start an exception process.")
next_owner = ESCALATION_LADDER[idx + 1]
decision.transition(Status.ESCALATED, at_time, f"{reason} → {next_owner}")
decision.owner = next_owner
return decisionConsoleOut [11]Expand
t= 3h owner -> claims-ops-lead t= 9h owner -> compliance-officer history: t= 0h pending_review: risky decline t= 3h escalated: reviewer authority insufficient → claims-ops-lead t= 9h escalated: policy ambiguity → compliance-officer
The owner handoffs trace a path up the ladder. Plotting the role index against time makes the escalation trajectory obvious: each step moves to a strictly higher authority, and the record pins each move to a timestamp and a reason.
VisualizationOut [13]Expand

The case moves from the reviewer to the operations lead and then to the compliance officer. The example records the destination in each escalation event. Define an exception process for the final role when available evidence is inadequate.
Appeals with independence
Once a denial has been communicated, the person can file an appeal. The example records a nonblank specialist identifier that differs from the decision’s current owner. The reviewer is stored on the appeal and in the decision history, while the decision keeps its existing owner. The assessment receives structured evidence. A production service has to authenticate the assigned reviewer and enforce its conflict-of-interest policy.
PythonIn [14]Expand
@dataclass
class Appeal:
appeal_id: str
decision_id: str
claim: str # the person's stated basis for the challenge
new_evidence: list[
str
] # verifier results the initial pipeline did not have
submitted_at: int
reviewer: str # must be independent of the original decision-maker
resolved_at: Optional[int] = None
outcome: Optional[str] = None
def file_appeal(
decision: Decision,
claim: str,
new_evidence: list[str],
at_time: int,
reviewer: str,
) -> Appeal:
if decision.status is not Status.DENIAL_COMMUNICATED:
raise ValueError("An appeal requires a communicated denial.")
reviewer = reviewer.strip()
if not reviewer or reviewer == decision.owner.strip():
raise ValueError("The appeal requires a different reviewer.")
decision.transition(Status.APPEALED, at_time, claim)
decision.transition(
Status.UNDER_APPEAL_REVIEW, at_time, f"reviewer={reviewer}"
)
return Appeal(
appeal_id=f"A{decision.decision_id}",
decision_id=decision.decision_id,
claim=claim,
new_evidence=new_evidence,
submitted_at=at_time,
reviewer=reviewer,
)PythonIn [15]Expand
def assess_duplicate(verified_records: tuple[str, ...]) -> bool:
"""Use structured results from the fictional ledger verifier."""
return "verified duplicate debit" in verified_records
def review_appeal(appeal: Appeal, decision: Decision, at_time: int) -> Appeal:
if appeal.decision_id != decision.decision_id:
raise ValueError("Appeal and decision must identify the same case.")
if decision.status is not Status.UNDER_APPEAL_REVIEW:
raise ValueError("The appeal must be open for review.")
if assess_duplicate(tuple(appeal.new_evidence)):
outcome = "overturned"
decision.transition(
Status.OVERTURNED, at_time, "verified duplicate debit"
)
else:
outcome = "upheld"
decision.transition(
Status.UPHELD, at_time, "no verified duplicate debit"
)
appeal.resolved_at = at_time
appeal.outcome = outcome
return appealConsoleOut [16]Expand
appeal outcome: overturned time to resolve: 24 hours final decision status: overturned
The appeal overturns the denial because the fictional ledger verifier confirmed the duplicate debit. A bank reference with no match does not change the outcome. The assessment receives a structured verifier result so it can distinguish supporting records from a customer's assertion. The toy rule stands in for a reviewer who can examine the evidence and apply the billing policy.
The assessment function receives only the structured evidence. The workflow function receives the wider case record to make and record the authorized transition. Keeping those calls separate lets us control which fields appear in the assessment interface. Independence also depends on reviewer identity, conflict of interest, and authority. A caller could change these objects in memory, so production needs to enforce each check at its own authorization boundary.
Measuring whether oversight works
Resolution time and the fraction of resolved appeals that overturn the initial decision measure different aspects of the process. Use the metrics alongside open case ages and an audit of outcomes against verified records.
A percentile over completed appeals can look healthy while unresolved cases get older. A low overturn fraction may reflect accurate initial decisions or barriers to getting a mistake reversed. A high fraction may reflect a biased initial process or effective targeting by people who choose to appeal. The rates alone cannot distinguish those explanations.
PythonIn [17]Expand
def simulate_case(i, rng):
label = str(
rng.choice(["credit", "decline", "adjuster"], p=[0.55, 0.30, 0.15])
)
score = float(rng.uniform(0.4, 0.99))
dec = Decision(
f"D{i:05d}",
f"S{i:04d}",
label,
score,
[f"message_{i}"],
owner="claims-reviewer",
created_at=0,
)
route(dec, rng)
routed_status = dec.status.value
if label == "decline":
dec.transition(
Status.DENIAL_COMMUNICATED, 2, "initial reviewer notified customer"
)
record = {
"decision_id": dec.decision_id,
"model_label": label,
"model_score": score,
"routed_status": routed_status,
}
# Only communicated denials can enter this fictional appeal path.
appealed = label == "decline" and rng.random() < 0.45
if not appealed:
record.update(appeal=None, appeal_latency=None, outcome=None)
return record
submit = int(rng.integers(2, 50))
gave_evidence = rng.random() < 0.5
new_ev = []
if gave_evidence:
verified = rng.random() < 0.60
new_ev = [
"verified duplicate debit"
if verified
else "unmatched bank reference"
]
reviewer = f"reviewer_{rng.integers(0, 6)}"
ap = file_appeal(dec, "billing error", new_ev, submit, reviewer)
latency = int(rng.integers(4, 72))
ap = review_appeal(ap, dec, submit + latency)
record.update(
appeal=ap.appeal_id,
appeal_latency=latency,
outcome=ap.outcome,
new_evidence_count=len(new_ev),
)
return record
rows = [simulate_case(i, RNG) for i in range(600)]
audit = pd.DataFrame(rows)ConsoleOut [18]Expand
total decisions: 600 appealed: 70 (12%) median appeal latency (h): 37.0 p90 appeal latency (h): 64.2 overturn rate: 37%
The next chart groups completed appeals by whether any new record arrived. The outcome depends on verified records in this toy rule. The simulated difference reflects how the outcomes were assigned.
VisualizationOut [20]Expand

The median is the midpoint of completed-appeal latencies. The 90th percentile describes the upper end and can reveal delays that the median hides. These values are computed over completed cases, and the sampling distribution was specified in advance. The example estimates neither the length of a real backlog nor the effect of an escalation policy.
VisualizationOut [21]Expand

Every simulated wait is below 72 hours by construction. To evaluate a service target, measure open case ages and how many cases resolve by the deadline. A live queue should schedule escalation independently of resolution so a reviewer can receive a case that is still waiting.
From documentation to contestability
The audit table serves staff who need to trace the decision. The appeal path serves people who need to challenge it. The workflow brings these tasks together through a few observable requirements.
- the affected person can discover the decision and the basis for it;
- an appeal accepts evidence the original pipeline did not have;
- the appeal reviewer is independent and sees evidence before verdict;
- the reviewer can reach
overturned, and the reversal is recorded; - the resolution is bounded in time and owned by a named role.
Test discovery, comprehension, submission, review, and delivery of the remedy with people who use the service. An inaccessible form or a reviewer who lacks access to the billing ledger can stop the workflow even when each stage is represented in the database.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!