Review the prerequisites
Suitable for: Backend developers learning Agent applications.
- Committed effects and conditional compensation in sagas
- Compensation is another business action that may charge, fail, or be irreversible, not erase history. First confirm the positive results, and then decide whether to compensate according to the terms, dependencies and authorization. The compensation itself must also be recoverable.
How does the mechanism work?
Step-by-step explanation
- If I cancel a hotel, I will be deducted. Will the original approval cover it?
Move from deciding whether to compensate to checking the compensation action's own authorization and economic conditions.
- What should I do if the compensation request also times out?
Compensation also has a window where the remote action succeeds but remains unconfirmed locally, in addition to unknown forward-action outcomes.
- Do all compensations have to be in reverse order?
Compensation requires reasoning about dependencies, beyond simply reversing a stack of actions.
Implementation · Build it
Implement and check the complete contract
Objectives of this level: Implement reverse-order compensation and original-key ledger dedup.
Visual guide · Compensation starts from facts
The planner emits commands only. Unknown effects freeze compensation; completed shipment requires review. Compensation needs its own authority and receipt. Select the figure to open it at full size.
Read the full contract before coding
The following preserves the existing local function, exact shape rules, output precedence and fixed inputs. Implement it in your own module, retain the first failed report, then explain what the adapter must additionally prove in a real deployment.
Derive the invariant
A failed multi-service transaction cannot be rolled back by undoing local variables. Plan compensations from known receipts in reverse business order. An unknown remote result is a reconciliation gate, and a completed shipment may require human handling.
Executable entry and responsibility
Same after-sales project: ticket-1 belongs to tenant A. Junior responsibility derives input/failure boundaries; intermediate responsibility implements and repairs the function; senior responsibility owns integration facts and recovery tradeoffs. These are responsibilities, not the four tracks or a calibrated hiring ladder. Python3.9+ standard library; extract the package and keep lab_runner.py beside cases/. Scaffold refuses overwrites.
- https://ai.lwkjob.com/lab/extended-practice/README.md
- https://ai.lwkjob.com/lab/extended-practice/lab_runner.py
- https://ai.lwkjob.com/lab/extended-practice/cases/agent-saga-compensation.json
- https://ai.lwkjob.com/downloads/extended-agent-practice-v1.zip
python3 lab_runner.py scaffold --course agent-saga-compensation --out plan_compensation_student.py
python3 lab_runner.py grade --course agent-saga-compensation --module plan_compensation_student.py --out agent-saga-compensation-report.json
def plan_compensation(payload):
"""Implement the public contract; disclose assistance used."""
raise NotImplementedError("agent-saga-compensation")
Complete function contract
plan_compensation(payload) accepts exactly task_id/tenant (nonempty strings), steps and compensated (lists). steps contains exactly one reserve, one charge and one ship, in any input order. Each step has exactly name, operation_key (nonempty string; all three unique), outcome (not_started/succeeded/failed/unknown), receipt (nonempty string only for succeeded; null otherwise). compensated contains unique nonempty original operation keys. Validate shape first: ValueError("input_shape"). A compensated key must belong to a succeeded reserve/charge step, otherwise ValueError("compensation_key").
If any step is unknown, return status reconcile, actions empty, manual empty and reconcile rows {name, operation_key} ordered reserve/charge/ship. Freeze every automatic compensation until those results are known; unknown takes precedence even if ship is succeeded. Otherwise, if ship succeeded, return manual_review, no actions/reconcile, and one manual ship row with name/operation_key/receipt. Do not assume delivery can be automatically undone.
Otherwise consider charge then reserve. For each succeeded step not already in compensated, emit exactly kind (refund_charge/release_reservation), tenant, original operation_key, receipt. status is ready if actions exist, complete if none; reconcile/manual are empty. The original key and receipt are retained; an action is a planned command, not an executed refund. Ledger/receipt facts are trusted input fixtures, not verified remote signatures. This function neither records compensation completion nor makes service calls, validates business step causality, or supplies a distributed transaction.
Three public inputs and exact expectations
reverse-compensation
{
"input": {
"task_id": "ticket-1",
"tenant": "A",
"steps": [
{
"name": "reserve",
"operation_key": "op-reserve",
"outcome": "succeeded",
"receipt": "reserve-r1"
},
{
"name": "charge",
"operation_key": "op-charge",
"outcome": "succeeded",
"receipt": "charge-r1"
},
{
"name": "ship",
"operation_key": "op-ship",
"outcome": "failed",
"receipt": null
}
],
"compensated": []
},
"expected": {
"status": "ready",
"actions": [
{
"kind": "refund_charge",
"tenant": "A",
"operation_key": "op-charge",
"receipt": "charge-r1"
},
{
"kind": "release_reservation",
"tenant": "A",
"operation_key": "op-reserve",
"receipt": "reserve-r1"
}
],
"reconcile": [],
"manual": []
},
"error": null
}
unknown-write-freezes
{
"input": {
"task_id": "ticket-1",
"tenant": "A",
"steps": [
{
"name": "reserve",
"operation_key": "op-reserve",
"outcome": "succeeded",
"receipt": "reserve-r1"
},
{
"name": "charge",
"operation_key": "op-charge",
"outcome": "unknown",
"receipt": null
},
{
"name": "ship",
"operation_key": "op-ship",
"outcome": "failed",
"receipt": null
}
],
"compensated": []
},
"expected": {
"status": "reconcile",
"actions": [],
"reconcile": [
{
"name": "charge",
"operation_key": "op-charge"
}
],
"manual": []
},
"error": null
}
all-compensated
{
"input": {
"task_id": "ticket-1",
"tenant": "A",
"steps": [
{
"name": "reserve",
"operation_key": "op-reserve",
"outcome": "succeeded",
"receipt": "reserve-r1"
},
{
"name": "charge",
"operation_key": "op-charge",
"outcome": "succeeded",
"receipt": "charge-r1"
},
{
"name": "ship",
"operation_key": "op-ship",
"outcome": "failed",
"receipt": null
}
],
"compensated": [
"op-charge",
"op-reserve"
]
},
"expected": {
"status": "complete",
"actions": [],
"reconcile": [],
"manual": []
},
"error": null
}
Scope and evidence
All cases are public fixed local simulations. The grader imports and calls your function, checks exact JSON types (bool is not int), immutable input and no dict/list aliases in the return. Return0 only when all cases pass; return1 for contract failures; malformed CLI/overwrite returns2. It records input, expected/actual/error, source/module/case hashes and Python version. Five seconds is a hang guard, not performance evidence. No model, remote tool, production load, cryptographic receipt validation or real learner outcomes were measured. Submit your source, initial red report, personal diff, rerun report and a short tradeoff note; published expected values and author calibration do not prove independent mastery.
code example
Implement the function contract · unknown-write-freezes
A failed multi-service transaction cannot be rolled back by undoing local variables. Plan compensations from known receipts in reverse business order. An unknown remote result is a reconciliation gate, and a completed shipment may require human handling.
{
"input": {
"task_id": "ticket-1",
"tenant": "A",
"steps": [
{
"name": "reserve",
"operation_key": "op-reserve",
"outcome": "succeeded",
"receipt": "reserve-r1"
},
{
"name": "charge",
"operation_key": "op-charge",
"outcome": "unknown",
"receipt": null
},
{
"name": "ship",
"operation_key": "op-ship",
"outcome": "failed",
"receipt": null
}
],
"compensated": []
},
"expected": {
"status": "reconcile",
"actions": [],
"reconcile": [
{
"name": "charge",
"operation_key": "op-charge"
}
],
"manual": []
},
"error": null
}
Acceptance task for this level
Implement plan_compensation in plan_compensation_student.py without copying a public solver; run every fixed case and retain the first failed report before repair.
Reading this browser’s record…
Hide the answer and check your understanding
What makes repeated planning stable?
Expand reference derivation
The trusted compensated ledger removes already-finished original keys; planning itself must not consume or rewrite that ledger.
Further explanations and practice
When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.
All linked explanations and exercises (1 )
Sources and verification scope
The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.