Retry and Scheduling Utilities
Thirty original Python problems on retry evidence, completion budgets, exact quotas, fenced timers and leases, hedged attempts, virtual queues, periodic work and shutdown choices. Implement deterministic witnesses for explicitly supplied scheduling models.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Check retry outcome, budget and safety evidence
Write
retry_policy(rows,max_attempts),max_attempts>=1. Rows[read/write,outcome,key_or_None,used_attempts], used>=1; outcome ok/fatal/retry. Return[eligible,reason]per row, priority: ok->complete, fatal->fatal, used>=max->budget, write with absent/empty key->unsafe, otherwise[True,None]. Read needs no key. Nonempty keys are literal, not trimmed. Supplied policy only; no requests/mutation.2.Admit whole attempts within a completion deadline
Write
deadline_attempts(now,deadline,attempts,waits). Attempts[nonnegative_duration,success_bool]; waits nonnegative, lengthmax(0,n-1). First start=now; after failure next start=finish+its wait. Admit ONLY if the whole attempt finishes<=deadline; stop on first nonfit or success. Return [admitted_[start,finish]_pairs,success_index_or_None]. Empty plan has no success. No mutation.3.Intersect jitter, not-before and deadline bounds
Write
retry_time_bounds(now,low_delay,high_delay,server_floor,deadline,duration). Integer 0<=low_delay<=high_delay, duration>0;server_flooris an absolute integer time orNone. Allowed starts are[now+low_delay,now+high_delay], at/afterserver_floorif supplied, finishing<=deadline. Return inclusive[earliest,latest], orNoneif empty. Do not sample jitter, execute work or mutate.4.Compute exact outcome and work moments for a retry sequence
Write
retry_moments(costs,probabilities), equal-length lists. Costs nonnegative integers; probability[num,den], 0<=num<=den, den>0, is success CONDITIONAL on reaching that attempt. Stop on success or list end. Return[success_probability,expected_attempts,expected_cost], each reduced[num,positive_den]. Charge only reached costs. Empty plan gives three zero fractions. No mutation.5.Replay one-use retry reservations without inventing refunds
Write
retry_reservations(capacity,events), capacity>=0. Events[reserve/consume/refund,string_id,amount], integers>=0. Reserve if ID never reserved successfully and amount<=remaining; subtract/activate. Consume removes active reservation without credit; refund removes it and restores amount. Inactive consume/refund fail; amount ignored. Return[accepted_indices,remaining,sorted_active_pairs].6.Refill and spend a bounded bucket with exact rational tokens
Write
token_bucket(capacity,rate_num,rate_den,events), nonnegative integer capacity/rate_num,rate_den>0. Start full at time 0. Events[nondecreasing_nonnegative_integer_time,nonnegative_cost]. Refill atrate_num/rate_denper time unit, capped at capacity BEFORE each event. Accept iff balance>=cost, subtract only accepted cost. Return[accepted_booleans,final_reduced_fraction]. No mutation.7.Charge only accepted work inside a sliding quota window
Write
sliding_quota(events,limits,window), window>0. Events[nondecreasing_integer_time,string_key,nonnegative_cost]; limits key->nonnegative capacity, absent key capacity 0. Accept iff cost plus accepted same-key costs with time>current_time-window is <=capacity. Equal-time events are sequential. Rejections never consume quota. Return acceptance booleans. No mutation.8.Admit virtual work without charging rejected queue time
Write
virtual_wait(events,max_wait),max_wait>=0. Events[nondecreasing_nonnegative_arrival,positive_duration]. One nonpreemptive virtual worker starts free at 0. Proposed start=max(arrival,last_accepted_finish). Accept iff start-arrival<=max_wait; set finish=start+duration. Rejection reserves NO time. Return[start,finish]orNoneper event. Supplied planning model only; no execution/mutation.9.Replay a sequential circuit breaker with cooldown trials
Write
breaker_history(events,threshold,cooldown), positive threshold/cooldown. Events[nondecreasing_integer_time,success_bool]are instantaneous sequential attempts. Follow starter state rules; rejected outcomes are ignored. Return[admitted_bool,state_after]per event, closed/open. Cooldown equality admits a trial. No overlapping requests, real network actions or mutation.10.Assign permitted retry times under shared slot capacity
Write
jitter_slots(requests,capacity). requests maps names to nonnegative integer allowed delays; distinct-option product<=4096. Capacity rows[unique_delay,nonnegative_count], absent delay capacity 0. Assign each request one allowed delay within caps. Minimize latest delay, then lexical delay vector in sorted-name order. Return sorted[name,delay], orNone. Empty requests returns []. No mutation.11.Coalesce work only while distinct subscribers remain
Write
coalesced_subscriptions(events),[subscribe/unsubscribe,key,subscriber], strings. Maintain subscriber SETS per key. First subscription to empty key emits[index,"enqueue",key]; removing last subscriber emits[index,"dequeue",key]. Duplicate subscribe/absent unsubscribe is a no-op. Return [emissions,sorted_[key,sorted_subscribers]], omitting empty keys. No execution/mutation.12.Retain first successful results and report conflicts
Write
idempotent_results(events),[string_key,success_bool,string_or_None_payload]. Only successful events populate the cache; FIRST success wins, even null/empty string. Later success with unequal payload reports its index, without replacing cache. Failed outcomes never populate or conflict. Return[cache,conflict_indices]. Missing key differs from cached null. No requests or mutation.13.Fence timer cancellation and firing by generation
Write
fenced_timers(events),[time,schedule/cancel/fire,key,generation,delay], nondecreasing integer time, generation/delay>=0. Apply starter rules. Return [fired_[index,key,generation],sorted_active_[key,generation,due],rejected_indices]. Delays matter only for schedule. Cancel/fire must match the active generation; fire also needs time>=due and consumes it. No actual timers or mutation.14.Replay an expiring lease with monotone fencing tokens
Write
lease_history(events),[time,acquire/renew/release,owner,token,ttl], nondecreasing integer time, ttl>0; acquire ignores input token. Use starter rules. Return[responses,final_lease_or_None], response[accepted,granted_or_matched_token_or_None], lease[owner,token,expiry]. Expiry equality means expired. Supplied sequential model only; no real locks or mutation.15.Find a hedged attempt winner and actual launch support
Write
hedged_winner(attempts,cancel),[nonnegative_start,positive_duration,success_bool], cancel absolute time orNone. Earliest successful finish STRICTLY before cancel wins, ties input index. Stop time=winner finish, else cancel if supplied. Only starts STRICTLY before stop launch; with no stop all launch. Return[winner_or_None,finish_or_None,launched_indices]. No execution/mutation.16.Dispatch ready jobs by earliest deadline
Write
edf_dispatch(jobs), [unique_name,nonnegative_release,positive_duration,integer_deadline]. One nonpreemptive worker starts free at 0. Choose among READY jobs by earliest deadline, then name; if none ready, jump to next release. Run late jobs too. Return[name,start,finish,finish>deadline]in dispatch order. This is the stated policy, not an optimal-feasibility solver. No mutation.17.Dispatch using elapsed-wait priority and deterministic ties
Write
aging_dispatch(jobs,rate), rate>=0 integer. Jobs [unique_name,nonnegative_release,positive_duration,integer_base_priority]. One nonpreemptive worker starts free at 0. Among ready jobs maximize base+rate*(now-release), ties earlier release then name; idle jumps to next release. Return[name,start,finish]in execution order. Priority changes only affect the next selection. No mutation.19.Serve FIFO flow queues using retained weighted round credits
Write
deficit_service(queues,weights,quantum), quantum>0; known flows have positive integer weight; FIFO jobs have positive cost<=30. Start credit 0. Each round visits sorted flows, adds quantum*weight, serves heads while cost<=credit, subtracting cost. Retain unspent credit; empty queue resets it to 0. Return[round_number,flow,job_index]per job; rounds start 1. No actual service/mutation.20.Choose an exact maximum on-time admission subset
Write
deadline_subset(jobs), <=12[positive_duration,integer_deadline], all released at 0. A selected subset runs by (deadline,input_index), nonpreemptively. Feasible iff every cumulative finish<=its deadline. Maximize count, then minimize total duration, then lexical sorted index list. Return those indices, including [] if none fit. Only this supplied model is covered. No mutation.21.Handle periodic missed ticks under an explicit policy
Write
missed_ticks(next_due,period,now,mode,limit), integer period/limit>0. Due ticks:next_due+k*period<=now. Catchup emits earliest <=limit ticks, retaining first un-emittednext_due. Skip emits none; coalesce only latest overdue tick; both advancenext_duepast now. Limit ignored outside catchup. No due ticks leavesnext_dueunchanged. Return[emitted_times,new_next_due]. No timers/mutation.22.Merge periodic calendars with all same-time source witnesses
Write
merge_calendars(calendars,start,count). Calendars[nonnegative_anchor,positive_period]; each produces anchor+k*period for k>=0. start/count nonnegative integers. Return earliest count DISTINCT times>=start as[time,sorted_calendar_indices], listing every source producing that time. Duplicate calendars remain separate witnesses. Empty calendars returns []. No actual scheduling or mutation.23.Jump periodic ticks past finite half-open blackout windows
Write
next_unblocked(anchor,period,now,blackouts), nonnegative integer anchor/now, period>0; blackout integer intervals [a,b), a<b, arbitrary order. Find earliest anchor+k*period>=now, k>=0, outside every blackout. Return its time. Finite blackouts guarantee an answer. Do NOT enumerate each skipped tick; jump to the first periodic occurrence at/after an excluding interval end. No mutation.24.Reuse the lowest free worker for fixed intervals
Write
assign_workers(jobs), integer half-open [start,end), start<end. Process by (start,end,input_index). Release workers with previous end<=start; reuse smallest free worker ID, else allocate next ID from 0. Return[worker_count,worker_ID_per_input_job]. No overlapping jobs may share a worker. Empty jobs gives [0,[]]. Fixed intervals only; no actual workers or mutation.25.Find complete lexical unit-slot assignments
Write
match_slots(tasks,capacities). tasks maps names to integer allowed-slot lists; distinct-option product<=4096. Capacities rows[unique_slot,nonnegative_capacity], absent slot capacity 0. Each task consumes one slot unit. Return sorted[name,slot]for the lexicographically smallest full slot vector in sorted-name order, orNoneif infeasible. Empty tasks returns []. No mutation.26.Allocate shared retries using per-service gain prefixes
Write
retry_allocation(gains,budget), <=5 names mapping to <=4 integer marginal gains; budget>=0. Assign each service k=0..len(gains), consuming k attempts and earning sum of its FIRST k gains. Total attempts<=budget. Maximize total gain, then minimize attempts, then lexical k-vector in sorted-name order. Return [sorted_[name,k],total_gain]. Negative marginal gains allowed. No execution/mutation.27.Buffer sequence gaps and emit first-arrival completions
Write
ordered_completions(start,events), start>=0; events[nonnegative_sequence,JSON_payload], arrival order. First result per sequence wins. Ignore sequences below next required; never overwrite buffered duplicates. After each arrival emit all contiguous buffered sequences from next required, advancing it. Return detached [emitted_[seq,payload],sorted_pending_pairs]. No invented gaps or mutation.28.Build quota-complete retry targets without adjacent repeats
Write
retry_targets(quotas),string_host->nonnegative_integer_count, total<=14. Use EACH host exactly its count, with no identical consecutive hosts. Return the lexicographically smallest complete host sequence, orNoneif impossible. Zero quotas add no work; empty/all-zero quotas return []. Do not omit attempts, insert an unsupported host or mutate.29.Choose a bounded shutdown wait using completion breakpoints
Write
shutdown_choice(jobs,horizon,rate),[unique_name,positive_remaining,checkpoint_cost_or_None]; integer costs/horizon/rate>=0. Wait integer t in[0,horizon]. Unfinished jobs (remaining>t) need numeric checkpoint support. Score=rate*t+their checkpoint costs. Minimize score then t. Return[t,score,sorted_unfinished], orNone. Use completion breakpoints; no unit-time scan. No shutdown/mutation.30.Classify deadline support under bounded clock offsets
Write
clock_deadline(local_now,remote_deadline,offset_low,offset_high,duration), integer low<=high, duration>0. Remote clock=local+offset. Remaining[deadline-now-offset_high,deadline-now-offset_low]. Priority: max<=0 ->expired; max<duration ->insufficient; min>=duration ->enough; else uncertain. Return[min,max,label]. Completion equality allowed. Supplied offsets only; no mutation.