Browse documentation
Domains
View Markdown
On this page

Finance: payment disputes

What you will learn: how a harness races its stages against deadlines taken from the brief, waits weeks for an answer from an outside system, chases it when it is late, and moves money only once and only with a person's approval above a threshold. You will run one dispute to a win and watch a deadline beat a late approval in another.

Read first: Domains, for what every harness here is made of; Education, the previous domain page; and the concept pages Time (timers and stage deadlines), Asking a person (an Inquiry that parks until someone outside answers) and Errands.

Time: about 25 minutes.

finance/payment_dispute (module gvn_domains.finance.disputes) is the harness about deadlines and answers from outside.

Where this harness fits

Every harness in gvn-domains is made of the same parts (see What a domain harness is made of): a plan, which is a workflow whose states are stages; tools and a policy that check every call before it has an effect; ports, small abstract classes for the outside world that you implement; a brief, the data a run starts with; and the Launcher, which runs the harness on a Governor. For a payment dispute they look like this:

flowchart LR
    brief(["brief: the dispute and its deadlines"])
    approver(["a person who approves moving money"])
    scheme(["the card scheme's webhook: the ruling"])
    scheduler(["a scheduler: wake when due"])
    subgraph harness ["payment_dispute"]
        plan["<b>DisputeRun</b> plan<br/>gather · respond · await · remind · book"]
        policy["policy and tools<br/>check every call"]
        plan -- "tool calls" --> policy
    end
    ports[("your ports<br/>Evidence · Scheme · Ledger")]
    launcher["<b>Launcher</b>"]
    brief --> launcher
    launcher -- "drives" --> plan
    policy -- "cleared calls" --> ports
    launcher -- "asks" --> approver
    approver -- "approve or deny" --> launcher
    scheme -- "answer" --> launcher
    scheduler -- "wake" --> launcher

What sets this harness apart: two callers from outside besides people, a scheduler that wakes a run when a deadline passes and an outside system that answers, and every stage raced against a deadline taken from the brief.

The problem

A cardholder disputes a payment. The merchant has a few days to gather evidence, a few more to contest the chargeback (the reversal of the payment the cardholder asked for) or accept it, and then waits, sometimes for weeks, for the ruling of the card scheme (the card network that arbitrates the dispute), which may never come without a reminder. Missing a deadline concedes the dispute, and both the submission and the booking move money, so each must happen once.

The plan

A run is a DisputeRun workflow. Its working stages host errands (small actors that make fixed tool calls with no model), one agent, and an Inquiry (an actor that asks someone outside a question and parks until they answer). It moves through these states:

  • idle: not started;
  • gathering: errands read each evidence source, until the evidence_by deadline;
  • responding: a caseworker agent contests (submit_response) or concedes, until respond_by;
  • awaiting: an inquiry waits for the scheme's ruling, until a deadline;
  • reminding: errands chase an overdue ruling, then back to awaiting;
  • booking_won, booking_lost, conceding: an errand books the result;
  • won, lost, conceded, unresolved or failed: the run is over.

The plan as gvn draws it from the code (a docs test checks that it still matches). Each box is a state, emits names the work it asks for, and each arrow is labelled with the input that moves the run along it; otherwise: stay means any input not drawn leaves the run where it is:

stateDiagram-v2
    awaiting : emits await
    booking_lost : emits book
    booking_won : emits book
    conceded : emits conceded
    conceding : emits book
    failed : emits failed
    gathering : emits gather
    idle : emits idle
    lost : emits lost
    reminding : emits remind
    responding : emits respond
    unresolved : emits unresolved
    won : emits won
    [*] --> idle
    awaiting --> booking_lost : lost
    awaiting --> reminding : overdue
    awaiting --> unresolved : unruled
    awaiting --> booking_won : won
    booking_lost --> lost : booked
    booking_lost --> failed : booking_failed
    booking_won --> won : booked
    booking_won --> failed : booking_failed
    conceding --> conceded : booked
    conceding --> failed : booking_failed
    gathering --> responding : gathered
    gathering --> conceding : late
    idle --> gathering : started
    reminding --> awaiting : reminded
    reminding --> unresolved : unruled
    responding --> conceding : concede
    responding --> conceding : lapsed
    responding --> failed : respond_failed
    responding --> awaiting : submitted
    conceded --> [*]
    failed --> [*]
    lost --> [*]
    unresolved --> [*]
    won --> [*]
    note right of idle
        otherwise: stay
    end note

In the table, a stage with several children at once is a fan-out, and a judge is a Decision that reads what a stage's child did and picks the stage's result (Judges). A deadline on a stage is a time at which the stage is ended, whatever its children are doing (Time); visit counts how many times the run has been in the stage.

Stage Who How it ends
gathering a fan-out of errands, one fetch_evidence read per source; deadline evidence_by gathered once every read returned; late at the deadline (reads still running are dropped; finished ones keep their results)
responding an agent: submit_response, concede; deadline respond_by submitted, concede, respond_failed; lapsed at the deadline, when the caseworker (or an approver) was still busy
awaiting an Inquiry to the scheme, choices won and lost; deadline ruling_due + (visit - 1) * remind_every won or lost from the ruling's choice; overdue at the deadline; unruled if the channel withdrew
reminding errands: chase_ruling, none after 2 reminders reminded, back to awaiting; unruled once the reminders are spent (unresolved, for a person)
booking_won, booking_lost, conceding an errand: book_outcome booked, or booking_failed

late and lapsed are the declared accept-by-default paths: missing a deadline concedes the dispute.

The same plan as a table, also rendered from the code: > marks the initial state, * the final states, and each row lists the state's output and its transitions.

   state         output      transitions
   awaiting      await       lost -> booking_lost, overdue -> reminding, unruled -> unresolved, won -> booking_won
   booking_lost  book        booked -> lost, booking_failed -> failed
   booking_won   book        booked -> won, booking_failed -> failed
*  conceded      conceded    -
   conceding     book        booked -> conceded, booking_failed -> failed
*  failed        failed      -
   gathering     gather      gathered -> responding, late -> conceding
>  idle          idle        started -> gathering
*  lost          lost        -
   reminding     remind      reminded -> awaiting, unruled -> unresolved
   responding    respond     concede -> conceding, lapsed -> conceding, respond_failed -> failed, submitted -> awaiting
*  unresolved    unresolved  -
*  won           won         -
otherwise: stay

Walking through a run

The blocks below run in order as one program, as part of the docs tests.

1. The outside world: three ports

Port Methods
Evidence fetch(source, dispute)
Scheme submit(dispute, evidence, summary, key), chase(dispute, key); rulings arrive through the webhook, as answers
Ledger book(dispute, result, amount, currency, key)

The harness reaches the outside world only through these three ports; you implement them. The scheme and the ledger move money, so both keep one effect per key, an idempotency key: a repeat of the same request with the same key changes nothing.

from gvn_domains.finance.disputes import Evidence, Ledger, Scheme


class MerchantFiles(Evidence):
    async def fetch(self, source: str, dispute: str) -> list[dict[str, str]]:
        return [{"id": f"{source}-1", "summary": f"The {source} record for {dispute}."}]


class CardScheme(Scheme):
    def __init__(self) -> None:
        self.submitted = {}  # key -> (submission id, dispute, evidence ids)
        self.chased = {}  # key -> dispute

    async def submit(self, dispute: str, evidence: list[str], summary: str, key: str) -> str:
        self.submitted.setdefault(key, (f"S-{len(self.submitted) + 1}", dispute, tuple(evidence)))
        return self.submitted[key][0]

    async def chase(self, dispute: str, key: str) -> None:
        self.chased.setdefault(key, dispute)


class Books(Ledger):
    def __init__(self) -> None:
        self.entries = {}  # key -> (entry id, dispute, result, amount, currency)

    async def book(self, dispute: str, result: str, amount: int, currency: str, key: str) -> str:
        self.entries.setdefault(key, (f"E-{len(self.entries) + 1}", dispute, result, amount, currency))
        return self.entries[key][0]

2. The brief carries the deadlines

A run starts with a brief holding the dispute id, merchant, amount (an integer in minor units), currency, reason, the evidence sources to read, the deadlines evidence_by, respond_by and ruling_due (absolute times), remind_every, and approval_over, the amount above which moving money needs a person. The clock is a ManualClock that only moves when you move it, so the example can jump days ahead without waiting:

from gvn.testing.fakes import ManualClock
from gvn_domains.catalog import Ports
from gvn_domains.directory import catalog

DAY = 24 * 3600.0
OPENED = 1_790_000_000.0  # when the dispute was opened

scheme, books = CardScheme(), Books()
clock = ManualClock(start=OPENED)
disputes = catalog().harness(
    path="finance/payment_dispute", ports=Ports.of(MerchantFiles(), scheme, books)
)
dispute_brief = {
    "dispute": "dp_17",
    "merchant": "Acme",
    "amount": 4200,
    "currency": "EUR",
    "reason": "fraudulent: cardholder does not recognise the payment",
    "sources": ["orders", "shipping"],
    "evidence_by": OPENED + 5 * DAY,
    "respond_by": OPENED + 7 * DAY,
    "ruling_due": OPENED + 60 * DAY,
    "remind_every": 14 * DAY,
    "approval_over": 1000,
}

The catalog built the harness by its path from your ports (see The catalog). Every deadline is a stage deadline, At(t) (end the stage at time t) with t taken from the brief, never from a clock read. A run recovered after a crash asks for the same wake-up at the same time, so a deadline is neither lost nor moved.

3. Evidence, then the caseworker asks to submit

The only model in this harness is the caseworker. No real model is used: the function below plays it. A fake model, FunctionModel, calls it with the exchange, everything the model would be shown, and it returns a Reply, the model's answer; a ToolCall in it asks for a tool, and a message with role TOOL carries results back. This one contests every dispute:

from gvn.harness.messages import TOOL, Message, ToolCall
from gvn.harness.ports import Exchange, Reply
from gvn.testing.fakes import FunctionModel


def caseworker(exchange: Exchange) -> Reply:
    if any(message.role() == TOOL for message in exchange.messages()):
        return Reply(message=Message.assistant(text="Submitted."))
    rebuttal = {"summary": "Paid with 3-D Secure and delivered."}
    call = ToolCall(call_id="c1", name="submit_response", arguments=rebuttal)
    return Reply(message=Message.assistant(text="", calls=[call]))

The Launcher takes the harness, the model, the clock and two more test fakes (Testing your harness): MemoryJournal keeps the journal in memory and RecordingOutput keeps what would be shown. start drives the run until it finishes or must wait; pending() lists the requests it waits on, and origin() names the actor that asked (dp-17/responding.1: the first visit of stage responding).

Starting the run reads both sources (errands, no model), then the caseworker asks to call submit_response. The amount, 4200, is above approval_over, so the policy asks a person and the run waits:

import asyncio

from gvn.testing.fakes import MemoryJournal, RecordingOutput
from gvn_domains.launcher import Launcher

launcher = Launcher(
    harness=disputes,
    model=FunctionModel(respond=caseworker),
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=clock,
)
waiting = asyncio.run(launcher.start(run_id="dp-17", brief=dispute_brief))
approval = waiting.pending()[0]
print(waiting.status(), approval.kind().name(), approval.origin())
waiting request_approval dp-17/responding.1

4. Approved: the run parks on the scheme for weeks

A person approves (approve). The submission goes out once, and the run moves to awaiting, where an inquiry asks the scheme for its ruling with a request_input request. Nothing else runs and the deadline is far, so the run parks: it is saved in the journal and no process holds it. Result.due() says when a scheduler should wake it:

waiting = asyncio.run(launcher.approve(run_id="dp-17", request=approval))
ruling_request = waiting.pending()[0]
print(ruling_request.kind().name(), ruling_request.origin())
print(ruling_request.payload()["question"], ruling_request.payload()["choices"])
print("due on day", (waiting.due() - OPENED) / DAY)
print(scheme.submitted)
request_input dp-17/awaiting.1
How did the scheme rule on dp_17? ['won', 'lost']
due on day 60.0
{'dp_17#submit': ('S-1', 'dp_17', ('orders-1', 'shipping-1'))}

The submission is keyed by the dispute ("dp_17#submit"), not by the call: it happens once per dispute whatever re-runs the call.

5. A deadline passes: the ruling is chased

While other work is in flight, the Governor sleeps on a deadline however far away it is, so it cuts a read or a submission that never returns. Once nothing else runs, it sleeps only on a deadline due within sleep_within seconds (60 by default); a farther one parks the run, as here. In a deployment a scheduler calls Launcher.wake once result.due() has passed. Here we move the clock to day 60 and wake the run ourselves:

clock.advance(waiting.due() - clock.now())
waiting = asyncio.run(launcher.wake(run_id="dp-17"))
ruling_request = waiting.pending()[0]
print(ruling_request.origin(), "due on day", (waiting.due() - OPENED) / DAY)
print(list(scheme.chased.values()))
dp-17/awaiting.2 due on day 74.0
['dp_17']

At the stage's deadline the inquiry was dropped, reminding chased the ruling, and awaiting asked again with the next deadline, remind_every (14 days) later. After 2 reminders the next visit chases nothing and the run ends unresolved, for a person.

6. The ruling arrives from outside

The scheme's webhook answers the request the run is parked on with answered {"choice": ruling, "text", "data": {"reference"}}. Only choice routes, through the stage's judge; text and data are untrusted and never enter a context.

from gvn.harness.events import Event

ruling = Event(
    name="answered",
    payload={"text": "Ruled for the merchant.", "choice": "won", "data": {"reference": "CB-1"}},
)
waiting = asyncio.run(launcher.reply(run_id="dp-17", request=ruling_request, event=ruling))
booking = waiting.pending()[0]
print(booking.kind().name(), booking.origin())
request_approval dp-17/booking_won.1

Booking moves money too, and the amount is above the threshold, so a person approves it as well. grade then checks the finished run against the harness's evaluation, its statement of what a good run looks like (Replay and evaluation):

finished = asyncio.run(launcher.approve(run_id="dp-17", request=booking))
print(finished.outcome().state(), books.entries)
print(asyncio.run(launcher.grade(run_id="dp-17")).passed())
State('won') {'dp_17#book': ('E-1', 'dp_17', 'won', 4200, 'EUR')}
True

The evaluation: finishes won, lost or conceded; nothing rejected; money moved above the threshold only with a person's approval (Gated(MONEY, when=above_threshold), a check on the recorded run, see checking a safety rule; MONEY is the pair of tools that move money, SUBMIT_RESPONSE and BOOK_OUTCOME, and the check sees the agent's calls and the errands' alike); submit_response requested by respond_by (By(SUBMIT_RESPONSE, respond_by)); at most 30 events. The two when functions are part of the module:

from gvn_domains.finance.disputes import above_threshold, respond_by

sample_context = {"dispute": "dp_17", "amount": 4200, "approval_over": 1000, "respond_by": 1_700_000_000}
print(above_threshold(call=None, context=sample_context), respond_by(context=sample_context))
True 1700000000

7. When the deadline beats the approver

A deadline already past is applied before any answer, so an answer or an approval that arrives after it is refused as stale, even if no scheduler has woken the run yet: a late approval never sends the submission. A second dispute, opened now (day 60 on our clock), shows it. Its approver waits eight days, one past respond_by:

from gvn.harness import TooLate

now = clock.now()
late_brief = dict(
    dispute_brief,
    dispute="dp_18",
    evidence_by=now + 5 * DAY,
    respond_by=now + 7 * DAY,
    ruling_due=now + 60 * DAY,
)
waiting = asyncio.run(launcher.start(run_id="dp-18", brief=late_brief))
late_approval = waiting.pending()[0]
clock.advance(8 * DAY)
try:
    asyncio.run(launcher.approve(run_id="dp-18", request=late_approval))
except TooLate:
    print("TooLate")
print(launcher.actor("dp-18").state(), "dp_18#submit" in scheme.submitted)
TooLate
State('conceding') False

The deadline was applied first: the caseworker was dropped, the stage ended lapsed, and the run moved on to conceding. Nothing was submitted.

"Possibly submitted." When respond_by passes, the caseworker is dropped, and what it was doing matters. The workflow's Memo (its record of every finished stage visit) notes what a deadline cut. If the stage's memo.abandoned lists invoke_tools among the caseworker's pending kinds, the submission may have reached the scheme; if it was waiting for the model or for an approval, as here, it did not. Each booking errand's trusted context carries response: "yes" (submitted), "no" (never sent) or "maybe" (cut while acting), and book_outcome echoes it, so the concession record says which. The booking itself happens once, keyed by the dispute; a later ruling on a "maybe" finds the run finished, is refused by reply, and goes to a person.

A deployment has two outside callers, a scheduler and the scheme's webhook. Their shape, which needs real processes, is:

# not runnable: the shape of a deployment with a scheduler and a webhook.
launcher = Launcher(
    harness=dispute, model=model, journal=journal, output=output, clock=clock,
    entitlement=dispute_entitlement,
)
result = await launcher.start(run_id="dp-17", brief=brief)
# a scheduler, once result.due() has passed (from any process, after recover):
result = await launcher.wake(run_id="dp-17")
# the scheme's webhook, for the request_input the run is parked on:
scheme = verified_webhook_principal(headers, body)
ruling = Event(name="answered", payload={"choice": "won", "text": "..."})
result = await launcher.reply(run_id="dp-17", request=request, event=ruling, by=scheme)

The webhook verifies the sender before constructing its Principal. The entitlement rule checks whether that scheme can answer for the dispute. The run parks on request_input while the scheme considers the ruling.

Ports, tools and policy

The module names each of its five tools with a constant (FETCH_EVIDENCE, CONCEDE, SUBMIT_RESPONSE, CHASE_RULING, BOOK_OUTCOME, together TOOLS), built without its port: it names the tool and refuses to run. The plan declares them (Plan(..., tools=TOOLS)), the errands make their calls with them (FixedCall("fetch", FETCH_EVIDENCE, {"source": ...})), and the policy and the evaluation match calls against them by identity; the harness's toolbox() holds the same tools over your ports (see how a harness names its tools).

The policy gives every call one of three verdicts: cleared (it runs), needs_approval (a person is asked first) or forbidden (it never runs). concede and chase_ruling are cleared; fetch_evidence only for a source named in the brief; submit_response and book_outcome need a person's approval when the amount exceeds approval_over, and are cleared at or below it. submit_response is forbidden without gathered evidence in the context and book_outcome without a result; anything else is forbidden. Each call of a reply gets its own verdict.

What is enforced before any effect

  • Amounts and ids come from the brief. submit_response and book_outcome are irreversible and take no amount and no dispute id: both are read from the run context. The ruling carries no amount either.
  • Approval depends on the amount. The policy reads the amount from the context, so the same tool is cleared for a small dispute and gated for a large one.
  • Effects are keyed by dispute. The scheme and ledger adapters must apply each effect at most once under "<dispute>#submit" or "<dispute>#book". The harness supplies the same keys after a crash, an interrupt, or a deadline.

What this harness uses from gvn

The dispute harness is the package's example of deadlines. It uses gvn's time: a machine never reads a clock, stages carry deadlines with At/After, the Governor sleeps or parks by sleep_within, a scheduler wakes a parked run with Launcher.wake, and the By check holds recorded runs to their deadlines. The scheme's ruling is the answer to an Inquiry, delivered with Launcher.reply. The deadlines are hard: a far deadline fires while other work is stuck; a deadline already past is applied before a late answer; a deadline and an answer that arrive together are ordered by rule; and after a late answer is refused the run carries on. The domains overview lists these parts of gvn across all the harnesses.

What the business rules decide

A deadline concedes, and a response that may or may not have reached the scheme is recorded as such for a person. Its own tests are in packages/gvn-domains/tests/test_dom_finance_disputes*.py.

Recap

  • Deadlines come from the brief, so a crash or replay neither loses nor moves them.
  • A far deadline parks the run; a scheduler wakes it with Launcher.wake once due() has passed.
  • An outside system answers an Inquiry with Launcher.reply; only its choice routes.
  • A deadline already past is applied before any answer, so a late approval is refused.
  • Money moves once per dispute, keyed by the dispute, and above a threshold only with approval.

Next: Meta, a harness that improves other harnesses.