Drop only the response after durable application
A local server process accepts order-7 and decrements inventory from ten to nine. It commits inventory and request identity in SQLite, then deliberately closes the first connection without a response. The client sees an empty response, which does not prove non-execution. Retrying the same ID and payload returns the stored nine. Read idempotent requests and unknown results first. This controls one application/response boundary rather than reproducing every network failure.
The third request reuses the ID with quantity two and must receive id-payload-mismatch. Returning an old success for arbitrary new content would hide a distinct user request. Here quantity is compared directly. A production extension must define principal, resource, canonical payload and retention scope. Identical ID strings from different users need not denote the same operation. Stable identity works only when its meaning and associated content are specified.
Start processes using an explicit readiness signal
Save retry.py and run it as a file with Python 3.12 or later. Spawn-based multiprocessing requires the main guard; do not paste functions individually into an interactive session. The parent is the client and the child the server. The child binds an available loopback port and reports it through a pipe. Connection begins after that signal, not an arbitrary startup sleep. No external order or payment API is contacted.
TemporaryDirectory contains the SQLite database. Inventory starts at ten; requests store ID, quantity and result. The server handles exactly three connections. Socket and join timeouts bound waits, and finally stops a surviving child on failure. A missing startup cannot leave the parent waiting indefinitely. Success requires the explicit assertions below and the final report, rather than suppressing every exception and assuming the experiment passed.
Commit identity and inventory in one local transaction
The server first looks up the ID. For a new operation, inventory decrement and request-result insertion occur in the same with-db transaction. For an existing ID, quantity matching selects either the saved result or a mismatch response. The drop flag suppresses sending only after commit. Mark transaction exit and sendall as separate boundaries when tracing the code; EOF is intentionally not evidence of non-application here.
Connections are handled sequentially, so this experiment does not test two concurrent first-time lookups racing. A concurrent implementation must verify unique constraints and transaction behavior on conflict. Do not generalize a local SQLite model into every isolation level of another database. The saved result is the original operation's nine, not a fresh inventory query after unrelated later orders. Result retrieval and current-state retrieval are separate API contracts.
import json,multiprocessing as mp,socket,sqlite3,tempfile
from pathlib import Path
def serve(path,ready):
with socket.socket() as listener:
listener.bind(('127.0.0.1',0));listener.listen()
ready.send(listener.getsockname()[1]);ready.close()
for _ in range(3):
connection,_=listener.accept()
with connection,connection.makefile('r') as stream:
request=json.loads(stream.readline())
db=sqlite3.connect(path)
try:
with db:
old=db.execute('SELECT amount,result FROM requests WHERE id=?',(request['id'],)).fetchone()
if old:
response={'stock':old[1]} if old[0]==request['amount'] else {'error':'id-payload-mismatch'}
else:
db.execute('UPDATE stock SET value=value-?',(request['amount'],))
value=db.execute('SELECT value FROM stock').fetchone()[0]
db.execute('INSERT INTO requests VALUES(?,?,?)',(request['id'],request['amount'],value))
response={'stock':value}
if not request.get('drop'):
connection.sendall((json.dumps(response)+'\n').encode())
finally: db.close()
def call(port,payload):
with socket.create_connection(('127.0.0.1',port),timeout=5) as connection:
connection.sendall((json.dumps(payload)+'\n').encode())
with connection.makefile('r') as stream:
line=stream.readline()
if not line: raise EOFError('response intentionally lost')
return json.loads(line)
if __name__=='__main__':
with tempfile.TemporaryDirectory() as directory:
path=str(Path(directory)/'orders.db')
with sqlite3.connect(path) as db:
db.executescript('CREATE TABLE stock(value INTEGER);INSERT INTO stock VALUES(10);CREATE TABLE requests(id TEXT PRIMARY KEY,amount INTEGER,result INTEGER);')
context=mp.get_context('spawn');parent,child=context.Pipe(duplex=False)
server=context.Process(target=serve,args=(path,child));server.start();child.close()
try:
assert parent.poll(10);port=parent.recv()
try: call(port,{'id':'order-7','amount':1,'drop':True})
except EOFError: pass
else: raise AssertionError('response was not dropped')
assert call(port,{'id':'order-7','amount':1})=={'stock':9}
assert call(port,{'id':'order-7','amount':2})=={'error':'id-payload-mismatch'}
server.join(10);assert server.exitcode==0
with sqlite3.connect(path) as db:
assert db.execute('SELECT value FROM stock').fetchone()==(9,)
assert db.execute('SELECT count(*) FROM requests').fetchone()==(1,)
print('applied=1 response_lost=1 retried=1 stock=9 recorded_ids=1 mismatch=rejected')
finally:
if server.is_alive():server.terminate();server.join()
parent.close()
Assert both responses and durable effects
The first call must raise the expected EOFError; another outcome fails the test. The second returns stock nine and the third a payload mismatch. Finally assert server exit zero, inventory nine and exactly one request record. The printed report summarizes one application and one lost response. Verify durable business state as well as response shape; successful receipt alone would not establish a once-only effect. The published input has been executed under these checks.
Committing the ID before inventory in a separate transaction can leave processed identity without its effect after a crash. Reversing separate transactions can leave an effect without identity. The shared atomic boundary prevents those local gaps. Adding an external payment call would place another effect outside that boundary. The current once-only inventory result does not automatically extend to a newly introduced external API.
Distinguish this run from a restart or retention test
The program starts the server once and handles three connections. It stores results in SQLite but does not itself restart that server between requests. A restart extension should reopen the same file and verify the original identity and result remain available. Replacing storage with an in-memory dictionary would change the promised recovery behavior. Name that difference instead of inferring persistence from three successful replies alone.
Retention is another independent condition. After identity is deleted, a replay can appear new. Align retention with allowed client retry duration and the principal/resource scope of identity. This short fixed-input success does not establish indefinite recognition of reused IDs. Test a changed quantity and a different principal under the chosen scope, preserving which outcome is expected to be a conflict and which is a genuinely new operation. The contract should also say whether a replay returns the original stored result or a current-state query. Here it returns the original result, which can legitimately differ from inventory after unrelated later orders. Keeping these distinctions explicit makes the local example extensible without overstating its existing execution coverage.
Solve the changed-ID and crash-position exercises
If the second request uses order-8, it is a distinct operation and can decrement inventory again to eight. The original assertions then correctly fail against the changed contract. A client generating a fresh ID for each retry prevents the server from recognizing original identity. Decide changed quantity or cancellation semantics from the business operation rather than treating any nearby request as the same retry.
Moving the drop before the transaction creates a different history: the client sees lost response, but the effect is not applied. The observations can look alike, which is the central unknown-result problem. Keep the crash positions labeled in separate evidence. On completion the child exits and temporary files are removed. If an extension adds other processes holding the database open, close those connections before cleanup too. The comparison is complete when client observation and durable server history can be explained independently.