State Machines and Concurrent Histories
Thirty original Python problems on observable machine behavior, legal interleavings, transaction provenance, causal delivery and finite recovery logs. Produce exact counts, complete witnesses and explicit rejection evidence while preserving state and identity.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Reject an undefined transition without leaking batch effects
Write
machine_batches(initial,table,batches).table[state][token]=[next_state,output], all strings. Replay each token list from current state; any undefined transition rejects the WHOLE batch, including outputs. Accept empty batches. Return [final_state,accepted[batch_index,outputs],rejected_indices]. Do not mutate inputs.2.Restore checkpoint identities without consuming saved state
Write
checkpoint_replay(initial,events), integer state. Events:[add,integer_delta],[save,id],[restore,id],[drop,id]. Save requires absent ID; restore/drop require present ID. Invalid events reject unchanged. Restore retains the saved checkpoint; saves copy current state. Return [final_state,sorted[id,saved_state],rejected_indices]. No input mutation.3.Count nondeterministic state paths and retain a full witness
Write
belief_paths(starts,table,tokens). starts are distinct strings;table[state][token]lists distinct next states, missing means none. Count every state path consuming ALL tokens; return[sorted_final_states,path_count,lexical_smallest_state_path]or []/0/Nonefor no path. Witness includes its start. Empty tokens retain distinct starts. No mutation.4.Refine Mealy states by all observable future behavior
Write
mealy_classes(states,table), distinct state strings; transitionstable[state][token]=[declared_next,output_string], possibly missing. Group states producing identical output/undefined behavior for EVERY finite token word. Undefined stops a run and is observable. Return sorted groups, each sorted. Include unreachable states. No mutation.5.Find a shortest input that synchronizes every possible state
Write
reset_word(states,table), distinct state strings;table[state][token]=declared_next. Find shortest token list mapping ALL states to one state; tie lexical token list. Every token must be defined on every state still possible. ReturnNoneif impossible. Empty/singleton state sets return []. No mutation.6.Find the shortest observable difference between two starts
Write
distinguish_word(table,left,right), partial Mealytable[state][token]=[next,output_string]. Return shortest lexical token list whose runs differ in output or exactly one is undefined. If both become undefined together, that word and extensions cannot distinguish. ReturnNoneif no word distinguishes. No mutation.7.Find a jointly enabled trace reaching a forbidden state pair
Write
safety_word(first,second,start,bad), deterministic partial tables[state][token]=next_state, start=[left,right], bad lists forbidden state pairs. Only jointly defined tokens may advance. Return shortest lexical token list reaching bad, [] if initially bad, orNoneif unreachable. No mutation.8.Serve issued identities in FIFO order through cancellations
Write
ticket_replay(events):[issue,id],[cancel,id], or[serve]. Issue requires an ID never issued before; cancel requires currently waiting ID. Invalid issue/cancel rejects unchanged. Serve returns oldest uncanceled waiting ID, orNoneif empty. Canceled/served IDs cannot be reissued. Return[serve_results,rejected_indices,remaining_FIFO_IDs]. No mutation.9.Require each action return to commute along with state
Write
commuting_pairs(states,actions,table), distinct strings. Totaltable[state][action]=[next_state,output_string]. Return sorted unordered distinct action pairs[a,b], a<b, such that executing a;b versus b;a from EVERY state gives equal final state AND equal return for each same action. Preserve action identity when comparing outputs. No mutation.10.Enumerate register outcomes with complete read ledgers
Write
register_outcomes(initial,clients), integer register; clients maps client ID to ordered[set,integer]or[get]operations, <=8 total. Enumerate complete interleavings preserving each client order. Return sorted unique[final_value,reads], reads sorted[client,local_index,value]. Different histories with the same full result count once. No mutation.11.Linearize returned counter values under real-time precedence
Write
counter_order(initial,ops), <=9[unique_id,start,end,kind,arg,observed], integer start<end. add increments integer counter by arg and returns NEW value; read returns current value (arg ignored). If A.end<=B.start, A must precede B. Return lexical smallest valid complete ID order orNone. Every returned value must match. No mutation.12.Choose a minimum pending completion before full-order ties
Write
pending_order(initial,done,pending), integer register, <=8 total. done[id,start,end,kind,arg,result], start<end; pending[id,start,kind,arg]. set writes arg, returnsNone; read returns value. IDs unique. Choose pending subset; chosen pending end after all done. Enforce A.end<=B.start only for done A. Minimize (chosen_count,full_ID_order). Return[order,sorted_omitted]orNone. No mutation.13.Find a register witness respecting each client sequence
Write
consistent_order(initial,ops), <=8[unique_id,client,sequence,kind,value]. Sequences unique per client; order each client by sequence, regardless of input order. write sets integer value; read requires current register==value. Return lexical smallest complete ID order orNone. There are no cross-client real-time constraints. No mutation.14.Find a FIFO history witness without consuming future values
Write
fifo_order(initial,ops), initial integer queue; <=8[unique_id,start,end,kind,value], start<end. enqueue appends value; dequeue must return value, withNonemeaning empty. All queued values integers. Enforce A.end<=B.start => A before B. Return lexical smallest valid complete ID order orNone. Empty dequeue leaves queue empty. No mutation.15.Build transaction precedence from read-write conflicts
Write
conflict_order(transactions,trace), declared distinct transaction IDs; trace rows[transaction,kind,key], kind read/write, in observed order. Earlier/later DIFFERENT transactions conflict on equal key if either access writes. Return [lexical_smallest_topological_order_or_None,sorted_unique[earlier,later]edges]. Include inactive declared transactions. No mutation.16.Preserve read sources and final writers in serial views
Write
view_orders(transactions,trace,final), <=7 distinct transaction IDs excluding @. Trace rows[tx,write,key]or[tx,read,key,source_tx_or_@]; preserve within-tx order only. Initially every key has writer @. final maps selected keys to required final writer. Return ALL sorted serial tx orders reproducing every read source and final constraint. No mutation.17.Check each snapshot against one strict commit cutoff
Write
snapshot_mismatches(initial_keys,commits,reads). commits[unique_id,integer_time,written_keys], IDs exclude @; reads[tx,snapshot_time,key,observed_writer_or_None]. Expected writer is latest (time,id) commit with time<snapshot writing key; else @ if initially present, elseNone. Return sorted mismatches[tx,key,expected,observed], sorting by tx/key; pairs unique. No mutation.18.Reject stale reads before incrementing any written version
Write
optimistic_replay(initial,transactions), nonnegative integer key versions, missing version 0. Transactions[unique_id,expected_reads_dict,written_keys]commit in input order. Any mismatched read rejects whole transaction. Accepted commits increment each DISTINCT written key once, including unread keys. Return [accepted_IDs,rejected[ID,sorted_stale_keys],final_versions]. No mutation.19.Replay nonreentrant shared and exclusive ownership
Write
lock_replay(events),[actor,acquire,resource,mode](mode S/X) or[actor,release,resource]. Acquire rejects if actor already holds that resource, or if any existing/new holder is X. Multiple distinct S holders allowed. Release requires ownership. Rejections leave state unchanged. Return [rejected_indices,sorted [resource,sorted[actor,mode]holders]], omitting empty resources. No mutation.20.Separate deadlock cores from waiters blocked behind them
Write
deadlock_groups(holders,requests), holders maps resource to exclusive actor; requests[actor,resource]. Waiting on another holder adds actor->holder; free/self-held resources add none. Return [sorted cyclic strongly connected actor groups,sorted noncyclic actors that can reach any cycle]. Repeated requests do not duplicate actors/edges. No mutation.21.Merge message clocks before incrementing the receiving actor
Write
vector_replay(actors,events), distinct actors define component order. Events[actor,local],[actor,send,id],[actor,receive,id]. Send ID is never reusable; receive consumes an available message once. Invalid send/receive yieldsNonewithout changes. Valid event increments actor component; receive first merges message componentwise. Return per-event clock copies orNone. No mutation.22.Return maximal vector representatives and dominance evidence
Write
clock_frontier(vectors), nonnegative integer vectors of one common length. Keep componentwise maximal vectors, using earliest input index for duplicates. Return [sorted_kept_indices,sorted[removed_index,smallest_kept_index_that_dominates_it]]. Dominates means >= in every component, allowing equality. Empty vector components allowed. No mutation.23.Count complete causal deliveries with sender sequencing
Write
delivery_orders(messages), <=10[unique_id,sender,sequence,dependency_IDs], sequences unique per sender, dependencies declared. Deliver after every dependency and every listed lower-sequence same-sender message. Return[number_of_complete_orders,lexical_smallest_ID_order_or_None]. Cycles yield[0,None]; empty input [1,[]]. No mutation.24.Drain ready arrivals while retaining unresolved blockers
Write
causal_buffer(arrivals),[unique_id,dependency_IDs]in arrival order; dependencies may arrive later, be absent, or self-reference. After each arrival repeatedly deliver lexical smallest buffered ID whose dependencies are ALL delivered. Return [per_arrival_delivery_lists,sorted_final[buffered_ID,sorted_undelivered_dependencies]]. Repeated dependency names count once. No mutation.25.Merge stamped values with tombstones and conflicts
Write
stamped_merge(replicas), maps key->[counter,actor,deleted,value]; counter nonnegative integer, actor string, deleted bool, JSON numbers integers; deleted value must beNone. Per key choose largest (counter,actor). ANY equal stamp with unequal typed payload is a global conflict, even below the winner. Return merged map retaining tombstones, orNone. Deep detach; no mutation.26.Retain removal tombstones before a tagged add arrives
Write
tag_replay(events),[add,tag,value_string]or[remove,tag_list]. First add binds tag forever; equal repeated add is idempotent, different value rejects unchanged. Remove tombstones every named tag, including unknown tags; later add cannot revive that tag. Return [sorted_distinct_live_values,rejected_indices,sorted_tombstones]. No mutation.27.Bind cached replies to typed requests without aliases
Write
cached_replies(requests),[id,payload,proposed_response], JSON numbers integers. First ID binds typed structural payload and response. Equal-payload repeats return the FIRST response; ignore new proposed response. Different payload rejects unchanged. Return[answers,conflict_indices], each answer[response,reused_bool], orNoneon conflict. Deep detach all returned trees. No mutation.28.Commit outbox identities atomically across crash and ack
Write
outbox_replay(events):[stage,tx,id,value_string],[commit,tx],[ack,id],[crash]. Stage rejects duplicate ID in that tx. Commit needs staged tx; reject whole if any ID was EVER committed, else persist all and clear tx. Rejected commit retains staging. Ack needs durable unacked ID. Crash loses staging only. Return [sorted_unacked[id,value],rejected_indices]. No mutation.29.Recover only durable winners in original log order
Write
recover_log(initial,records,durable_lsn). Unique increasing integer LSN records[lsn,tx,set,key,integer_value],[lsn,tx,commit]or[lsn,tx,abort]. Per tx, sets precede at most one terminal record. Only LSN<=durable_lsnsurvives. Redo surviving sets ONLY for tx with surviving commit, in LSN order. Return[state,sorted_winners,sorted_nonwinning_seen_tx]. No mutation.30.Find a final-state violation with minimum context switches
Write
race_schedule(initial,programs,expected), integer shared maps, <=8 steps.programs[actor]:[read,key,local],[add,local,delta],[write,key,local]. Missing shared/local values 0. Preserve actor order; read copies shared to actor-local, add changes local, write copies local to shared. Find final!=expected; minimize (actor switches,actor list). Return[switches,list,final]orNone. No mutation.