Scenario: a retry duplicates an operation
A client times out after creating a remote order, then retries with a new identifier. The server had committed the first order, so the customer sees two orders. The timeout alone could not tell the client whether the first write happened.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 18 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Build a diagnosis from evidence
- Compare a repair with its trade-offs
- Test the changed behaviour
Follow the evidence.
A client times out after creating a remote order, then retries with a new identifier. The server had committed the first order, so the customer sees two orders. The timeout alone could not tell the client whether the first write happened.
Observed evidence
- Server logs show the first commit before the response was lost.
- The retry used a different request identity.
- There is no endpoint for recovering the original operation's result.
Investigation sequence
- Distinguish a failed transport response from a failed business operation.
- Define a stable request ID bound to the original payload.
- Have the authority store/recover the committed outcome and reject incompatible ID reuse.
Challenge the repair
- Add a test rejecting reuse of request-a with a different value.
- How would two concurrent requests atomically share the same receipt in PostgreSQL?
Read the incident, not just the error
A lost response does not reveal whether the server committed the operation. Retrying with a new identity can repeat a side effect that already happened.
Understand first
The incident has a committed order and a lost response. Separate transport evidence from business outcome before retrying a create operation.
Words you will see
- Commit
- Making a business change authoritative at its owner.
- Transport failure
- Failure to receive a usable response, not necessarily failure of the business operation.
- Uncertain outcome
- The caller lacks enough evidence to classify the operation as committed or not committed.
Reproduce the ambiguity without a network
The model supplies a known server commit but no received response. From the caller's response evidence alone the outcome is unknown. The model exposes the server flag for teaching; a real caller does not gain that knowledge merely from a timeout.
A new request ID would tell a server to treat the retry as a new operation unless another policy prevents it. Reuse an identity for the same intended request, or reconcile with the authority. Never manufacture a successful receipt because the response is missing.
Distinguish recovery from blind repetition
Recovering a stored result can answer the original operation's question without repeating its side effect. A status lookup or provider idempotency contract must define scope, payload matching and retention. Ordinary read-only operations have different replay risks from create or charge.
This Boolean model uses fixed local state and no sockets, timers or sleeps. It explains an information gap, not the probability of timeout or an exactly-once delivery guarantee. Real evidence comes from authority logs and stored operation state.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
committed_at_server = TrueSupply the authority's state for this teaching case.
response_received = FalseThe caller has no usable response.
caller_outcome = 'known' if response_received else 'unknown'Classify only the available response evidence.
print(caller_outcome)Report uncertainty rather than invent failure or success.
A client times out after creating a remote order, then retries with a new identifier. The server had committed the first order, so the customer sees two orders. The timeout alone could not tell the client whether the first write happened.
Conceptual uncertain-outcome path
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- CommitThe authority creates an order.
- LoseThe response fails to reach the caller.
- RecoverUse the original operation identity to query or replay its stored result.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Model a known response.
Try: Set response_received = True.
The model labels the outcome known; a real response must still carry a valid result.
Model failure before commit.
Try: Set committed_at_server = False while response_received stays False.
The caller still sees unknown, demonstrating that response absence cannot distinguish the two server cases.
Before you move on
If the server committed but the client timed out, does generating a fresh ID make the original intent safer?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. It can create a second operation. Recover the original result or use the same stable identity under the authority's declared idempotency policy.
Investigate before changing code
An idempotency policy binds a stable request identity to the intended payload and its stored result. Equal identity alone is not enough if the payload changes.
Understand first
A retry must mean 'the same intent again', not 'reuse any old result'. Compare the payload before replaying a receipt and reject incompatible reuse.
Words you will see
- Idempotency key
- A stable identity used to recognize repeated attempts at one intended operation.
- Payload binding
- Recording which request data belongs to that identity.
- Conflict
- The same identity used with different intended request data.
Compare identity and payload together
The fixture stores request r with value 20 and a result. Incoming value 25 does not match the stored payload, so the decision is conflict. Returning the old result would falsely answer a request the authority never accepted.
Payload equality must be defined by the business contract. Currency, amount, account and operation kind may all matter. Comparing only a friendly label or omitting tenant scope can accidentally treat different intents as one operation.
Make key lifetime explicit
The client retains the stable identity across retries. The authority owns the receipt and defines how long it remains recoverable. Once a receipt expires, replay may no longer be safely deduplicated; the client needs a reconciliation rule instead of assuming unlimited retention.
The local dictionary lookup illustrates one decision and small fixed storage. Durable retention grows with stored operations and requires expiry, account isolation and careful cleanup. This model performs no write and supplies no atomic concurrency guarantee.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
receipts = {'r': (20, 'order-1')}Bind one identity to its accepted payload and result.
request_id = 'r'Reuse that identity.
value = 25Supply a different intended payload.
previous, result = receipts[request_id]Read the recorded binding before deciding whether to replay.
print('replay' if previous == value else 'conflict')Reject changed intent rather than reuse an unrelated result.
Distinguish a failed transport response from a failed business operation. Define a stable request ID bound to the original payload. Have the authority store/recover the committed outcome and reject incompatible ID reuse.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Model a real replay.
Try: Change value to 20.
The decision is replay because identity and payload agree.
Test a falsy payload.
Try: Change value to 0.
It remains conflict; truthiness is not payload equality.
Before you move on
If request r originally represented 20, should retry r with 0 return the old success just because 0 is falsy?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Zero is a concrete changed payload, not absence. Exact declared payload matching should classify this reuse as conflict.
A repair you can explain
A receipt lookup can return the prior result for a matching repeated request and raise a conflict for a different payload. This local pattern illustrates the decision, not a production idempotency service.
Understand first
The preserved original makes payload binding visible in one process. It has no durable transaction, account scope, simultaneous callers or recovery after restart.
Words you will see
- Receipt
- Stored evidence connecting an accepted request payload to its result.
- Replay
- Returning the result already stored for the same intent.
- Authority
- The component whose durable state decides whether the business operation happened.
Walk through the original creation and replay
The empty dictionary has no request-a entry, so the first call creates order 1 with value 20. It stores a pair containing the accepted payload and result. The second call finds that pair, compares value and returns the same result object.
The two printed dictionaries are equal and there is only one receipt. A different value under request-a raises ValueError. Another request ID creates a new entry even if its value is also 20: equal payloads alone do not prove equal intent.
Identify what remains to be engineered
The returned dictionary is shared with the stored receipt, so caller mutation can corrupt future replay. The model's len(receipts) + 1 numbering also relies on this tiny no-deletion fixture. Neither behavior is an appropriate general order-ID or ownership guarantee.
Two concurrent callers can both miss an ordinary lookup. Production storage must coordinate identity uniqueness, payload comparison and committed result with the actual operation. Retain receipts durably, scope them to the authority and account, and define retention before promising safe replay.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
if request_id in receipts:Look for a prior accepted operation.
previous, result = receipts[request_id]Recover its bound payload and result.
if previous != value:Detect incompatible identity reuse.
receipts[request_id] = (value, result)Store the new binding in this local model.
print(len(receipts))Both attempts used one identity, so only one receipt exists.
This single-process in-memory model illustrates identity and payload binding. Real servers need durable atomic storage and concurrency control; this dict is not a production idempotency service.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Test conflict.
Try: Change the second call's value to 21.
ValueError is raised instead of replaying or overwriting the first payload.
Test distinct intent.
Try: Change the second request ID to 'request-b'.
A second order and receipt are created, even though its value is also 20.
Before you move on
If two calls use different IDs but both value 20, how many entries does this model create?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Two. Distinct identities represent distinct operations in this model. Matching payload alone is not a reason to deduplicate separate intentional orders.
Reproduce the uncertain-outcome window
Model an order committed by the authority followed by loss of the response. The client sees a timeout, retries with a new request identifier, and creates a second order. Preserve this sequence in a controlled test rather than relying on random network loss. The key observation is that a transport failure says the client lacks a result, not that the business operation failed. More aggressive retries can therefore worsen the original incident.
Collect safe request identities and server-side commit evidence to distinguish rejection before application, failure during application, and response loss after commit. If the authority is unavailable, the correct state may remain unknown. Do not invent success or failure to make the client interface simpler. An operator needs a reconciliation path that can recover the authoritative outcome without creating a new operation with a fresh identity.
Trace identity and payload binding in the reference
The reference receipts dictionary associates request-a with the value 20 and the resulting order. Calling create twice with that same identity and value returns the same recorded outcome and leaves one receipt. Reusing the identity with another value raises ValueError instead of silently treating a different request as equivalent. This is an instructional single-process model of the contract, not durable idempotency or a safe concurrent server implementation.
The required authority owns both the operation and its receipt. A client-side map or an idempotency header alone cannot guarantee that relationship. If the process crashes after applying the operation but before storing the receipt, a replay can duplicate it. If it stores a successful receipt before the operation commits, a replay can report work that never happened. Atomic storage or an explicitly designed recovery protocol must close those inconsistent-state windows.
Repair retry policy around an authoritative outcome
Generate one stable operation identity before the first attempt and reuse it for eligible retries with the same semantic payload. Scope identity to the appropriate authenticated account or resource boundary. Define which payload representation is compared, how conflicts are reported, how long receipts remain recoverable, and what happens after expiration. Normalizing payloads requires care: removing a field that affects behavior can accidentally classify two different operations as identical.
On a durable database authority, a unique scoped request key can coordinate competing attempts, with the operation and receipt committed in the same transaction. A loser must recover the committed result or observe a documented in-progress state rather than race through another write. Database-specific locking and isolation need integration tests. If an external provider performs the effect, its own identity and recovery guarantees determine what the local service can safely promise.
Verify conflicts, concurrency and bounded recovery
Test repeated identical calls, incompatible payload reuse, two concurrent same-key attempts, crash-like interruption before commit, and lost acknowledgment after commit. Verify one authoritative effect under the declared protocol, not merely equal-looking response dictionaries. Add cross-account key reuse and receipt-retention cases. Keep attempts and total elapsed budget bounded, and do not retry permanent validation or authorization failures just because the generic wrapper can catch their exceptions.
Recovery also has resource costs: receipts consume storage, replay lookups add load, and indefinite backoff can retain client work forever. Set retention and retry budgets consistent with the business reconciliation window. If outcome recovery is impossible, surface an explicit uncertain state and direct the caller toward safe reconciliation. This is more honest than advertising universal exactly-once delivery from a local dictionary or assuming all remote providers honor the same header.
Transfer question: How should two concurrent PostgreSQL requests with the same scoped identity avoid creating two orders?
Use a database-enforced unique key for the scoped identity and coordinate receipt creation with the order in one transaction. One attempt becomes the owner; a competing attempt must wait or receive a documented in-progress response, then read the committed receipt and verify payload compatibility. On rollback, no successful receipt should remain. Test the actual isolation and conflict behavior against PostgreSQL rather than extrapolating from a dictionary. Include same-key different-payload requests and a connection loss after commit. The recovered receipt can make replay safe within its contract, but it cannot atomically govern an unrelated external side effect without additional protocol.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Recreate the repair independently
Add a test rejecting reuse of request-a with a different value. Start from the symptoms and write your own regression assertion before opening the reference.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: classify new, replay and conflict
Read a receipt table without writing it, then return an honest decision label.
The contract
- receipts maps string request IDs to (integer payload, integer order number) tuples. request_id is a string and value is an integer.
- Return the exact string 'new' if absent, 'replay' if present with equal payload, or 'conflict' if present with different payload.
- Do not mutate receipts. Zero and negative payloads are ordinary values. An empty table means new; matching another ID's payload does not imply replay.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- absent
r = retry_decision({}, 'r', 20) assert type(r) is str and r == 'new' - replay
assert retry_decision({'r': (20, 1)}, 'r', 20) == 'replay' - conflict
assert retry_decision({'r': (20, 1)}, 'r', 21) == 'conflict' - zero payload
assert retry_decision({'r': (0, 1)}, 'r', 0) == 'replay' and retry_decision({'r': (0, 1)}, 'r', 1) == 'conflict' - distinct identities
assert retry_decision({'a': (20, 1)}, 'b', 20) == 'new' - preserve receipts
x = {'r': (-2, 4)} r = retry_decision(x, 'r', -3) assert type(r) is str and r == 'conflict' and x == {'r': (-2, 4)}
What does this classifier establish, and what does it not?
It models one read-only policy decision with average dictionary lookup behavior and no output collection. It does not reserve a key, commit an order, authenticate a caller or coordinate concurrent writes.
Guided: return independent receipt state
Model one sequential receipt transition with immutable tuple results and separate outer ownership.
The contract
- state maps string IDs to (integer payload, positive integer number) tuples. Existing numbers are unique. key is a string; value is an integer.
- Return (new dict, receipt tuple). Replay matching key/value unchanged; new key gets max existing number + 1, or 1 for empty state. A conflicting value raises ValueError.
- Always return a new outer dict, including on replay. Preserve input. Tuple receipts contain only immutable integers. This is a pure sequential model, not durable atomic storage.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- new empty state
r = record_receipt({}, 'a', 20) assert type(r) is tuple and r == ({'a': (20, 1)}, (20, 1)) and type(r[0]) is dict and type(r[1]) is tuple and all(type(v) is int for v in r[1]) - replay ownership
x = {'a': (20, 1)} r = record_receipt(x, 'a', 20) assert type(r) is tuple and r == (x, (20, 1)) and r[0] is not x - conflict preservation
x = {'a': (20, 1)} raised = False try: record_receipt(x, 'a', 21) except ValueError: raised = True assert raised and x == {'a': (20, 1)} - gapped numbering
assert record_receipt({'old': (7, 9)}, 'new', 0) == ({'old': (7, 9), 'new': (0, 10)}, (0, 10)) - same payload different intent
assert record_receipt({'a': (20, 1)}, 'b', 20) == ({'a': (20, 1), 'b': (20, 2)}, (20, 2)) - new state isolation
x = {'a': (0, 2)} r = record_receipt(x, 'b', -1) assert type(r) is tuple and r == ({'a': (0, 2), 'b': (-1, 3)}, (-1, 3)) and r[0] is not x r[0]['a'] = (99, 2) assert x == {'a': (0, 2)}
Why do immutable tuples make a shallow state copy sufficient here?
Receipts contain only immutable integers, so sharing those tuples cannot expose nested mutation. Copying n entries and finding a maximum costs O(n) time and new outer storage. Real authority commits still need durability and concurrency control.
Transfer: same raw key, different accounts
Change identity to (account, key) so one account's retry never replays another account's receipt.
The contract
- state maps (string account, string key) tuples to (integer payload, positive integer number) tuples; numbers are unique globally in the supplied state.
- Return (new dict, receipt tuple), binding by both account and key. Matching scoped payload replays; changed scoped payload raises ValueError. A new scoped identity gets global max number + 1, or 1 when empty.
- Preserve input and always copy outer state, even on replay. Empty account/key strings are permitted identifiers. No authentication, concurrency or durable writes are modeled.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- new scoped identity
r = scoped_receipt({}, 'A', 'r', 20) assert type(r) is tuple and r == ({('A', 'r'): (20, 1)}, (20, 1)) and type(r[0]) is dict and type(r[1]) is tuple and all(type(v) is int for v in r[1]) - cross account same key
x = {('A', 'r'): (20, 4)} r = scoped_receipt(x, 'B', 'r', 20) assert r == ({('A', 'r'): (20, 4), ('B', 'r'): (20, 5)}, (20, 5)) s = scoped_receipt(x, 'B', 'r', 25) assert s == ({('A', 'r'): (20, 4), ('B', 'r'): (25, 5)}, (25, 5)) and x == {('A', 'r'): (20, 4)} - scoped replay ownership
x = {('A', 'r'): (0, 2)} r = scoped_receipt(x, 'A', 'r', 0) assert type(r) is tuple and r == (x, (0, 2)) and r[0] is not x - scoped conflict
x = {('A', 'r'): (20, 1)} raised = False try: scoped_receipt(x, 'A', 'r', 21) except ValueError: raised = True assert raised and x == {('A', 'r'): (20, 1)} - empty identifiers
r = scoped_receipt({}, '', '', 0) assert type(r) is tuple and r == ({('', ''): (0, 1)}, (0, 1)) - distinct key and isolation
x = {('A', 'r'): (20, 8)} r = scoped_receipt(x, 'A', 's', 20) assert type(r) is tuple and r == ({('A', 'r'): (20, 8), ('A', 's'): (20, 9)}, (20, 9)) and r[0] is not x r[0][('A', 'r')] = (99, 8) assert x == {('A', 'r'): (20, 8)}
Does adding account to the tuple authenticate the caller?
No. It changes lookup scope only. The authority must separately authorize the account and atomically persist receipts with operations. The pure transition copies and scans n entries in O(n) time and space, preserving immutable tuple values.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneThe underlying mechanism
Receipt state and the business effect need one coordinated authority. Separate writes can leave a committed effect without a recoverable receipt.
Understand first
A crash between the effect and receipt writes recreates the original uncertainty. A local state model can expose the gap without claiming to transact real resources.
Words you will see
- Durable
- Retained across the authority's intended restart and failure boundaries.
- Atomic coordination
- Ensuring related authoritative changes cannot be observed as a partially committed combination.
- Crash window
- A point where interruption can leave inconsistent state.
Find the dangerous intermediate state
The fixture explicitly sets effect_committed to True while receipt_committed is False. A replay decision that consults receipts alone might now execute the effect again. The final False says the two modeled facts are inconsistent, not that Python suffered a real crash.
Writing the receipt first is not automatically safer: a crash might leave a success receipt for an effect that never occurred. If both are in one transactional database, commit them in one transaction with a unique scoped operation identity. Remote effects may require provider support or reconciliation.
Do not promise exactly-once from a header
A client header conveys intent; only the authority can enforce the binding against committed state. Concurrent requests require atomic uniqueness and conflict handling. A process-local cache disappears on restart and cannot coordinate several server processes.
Durable coordination has storage, contention and cleanup costs. An outbox can coordinate local state and delivery intent but does not magically make every remote effect exactly once. Explain the provider's duplicate-handling and recovery contract explicitly.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
effect_committed = TrueSupply a model where the business write happened.
receipt_committed = FalseSupply a missing stored outcome.
consistent = effect_committed == receipt_committedDetect the mismatched pair of modeled facts.
print('reconcile' if not consistent else 'recover receipt')Escalate the inconsistent state instead of claiming safe replay.
Distributed systems permit an uncertain outcome when a response is lost after commit. A durable receipt must be committed with the operation or coordinated through a suitable transactional design. A header or client-side cache alone cannot establish exactly-once effects.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Model a coordinated commit.
Try: Set receipt_committed = True.
The flags agree and the modeled action is recover receipt.
Model neither write happening.
Try: Set both flags to False.
The flags agree but this does not itself mean success; a real state machine must distinguish not-started from committed.
Before you move on
Would writing a success receipt before the effect remove every crash window?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Failure between those writes can publish success for an absent effect. Coordinate the real effect and receipt or supply an honest recoverable intermediate state.
Alternatives and operational trade-offs
Returning an independent result snapshot protects the stored receipt from caller edits. Isolation must include account scope as well as mutable ownership.
Understand first
The original shares a result dictionary. A hardened pure policy task can return fresh state and a fresh receipt, while a transfer task changes identity to (account, key).
Words you will see
- Caller ownership
- The values a caller may change without editing the authority's stored state.
- Scope
- The account or operation domain in which a key is unique.
- Shallow copy
- A new outer container that still refers to the same nested values.
Protect the intended mutable boundary
The example copies a flat result dictionary containing integers. Editing shown['value'] then leaves stored['value'] unchanged. A shallow copy is sufficient for these scalar fields; a result with nested mutable lists would need a deeper explicit ownership rule.
The exercises use immutable tuple receipts and return a new outer state dictionary even for replay. That separates state ownership without needless deep copying. It is a deterministic transition function, not a concurrent persistence implementation.
Change scope deliberately
If account A and account B both use key r, each may legitimately create its own first operation. Index state by (account, key), and compare payload within that scope. A global raw-key lookup could replay another account's receipt or produce a false conflict.
Copying n outer entries costs O(n) time and space under ordinary dictionary behavior; it does not copy immutable tuples recursively. Real authentication, durable atomic writes and receipt expiry remain authority responsibilities outside the browser policy model.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
stored = {'order': 1, 'value': 20}Create one flat stored result.
shown = stored.copy()Give the caller a separate outer dictionary.
shown['value'] = 99Edit only the caller's container.
print(stored['value'])The stored payload still reads 20.
print(shown is stored)Different outer identity makes the ownership boundary observable.
Bound receipt retention, prevent cross-account replay and decide which payload differences conflict. Some providers offer idempotency keys; verify their scope and lifetime. If recovery is unavailable, show uncertainty and require a safe reconciliation path rather than inventing success.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Remove the ownership boundary.
Try: Replace shown = stored.copy() with shown = stored.
The stored value becomes 99 and identity becomes True.
Expose nested sharing.
Try: Use a list value, copy the dict, then append through shown's list.
Both dictionaries observe the changed nested list because the copy is shallow.
Before you move on
If shown contains a list copied from stored, would shown.copy() also make that nested list independent?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. A shallow dictionary copy retains references to nested values. Define which nested levels need separate ownership and copy those levels or use immutable receipt data.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.