Partition and Backfill Utilities
Original Python data engineer interviews on pinned partition revisions, manifest evidence, resumable loads, routing, backfill activation, retry budgets and recovery replay plans.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Group requested partitions missing the pinned revision
Write
revision_gaps(desired, available). Both list[integer_partition,integer_revision], unique partitions per list. A desired partition needs work iff absent from available or its revision differs, including a higher revision. Return maximal half-open[start,end]runs of consecutive IDs needing work, sorted. IDs absent from desired must not be filled into a run. No mutation.2.Count file evidence once and reject conflicting identities
Write
manifest_counts(files). Rows[partition,file_id,row_count], IDs strings, count integer>=0. File identity is (partition,file_id). Repeated identical counts are replay evidence counted once. Conflicting counts for an identity reject its entire partition. Return{"counts":[[partition,total]],"conflicts":partitions}, both sorted by partition. Include zero-row accepted partitions. No mutation.3.Advance a load cursor through contiguous committed spans
Write
commit_frontier(cursor, spans). cursor integer; spans unordered integer[start,end], start<=end, representing committed half-open offsets. Return the farthest cursor reachable by continuous committed coverage starting at cursor. Overlap and exact adjacency can extend it; a hole stops progress even if later spans exist. Spans entirely before the cursor add no progress. No mutation.4.Resume a deterministic page of partition and file keys
Write
page_files(rows, cursor, limit). rows lists[integer_partition,string_file_id], duplicates allowed. cursorNoneor a key pair; limit integer>=0. Deduplicate and sort keys lexicographically, select up to limit strictly greater than cursor (all ifNone). Return{"rows":selected_pairs,"cursor":last_selected_or_old_cursor}. An empty page leaves cursor unchanged. No mutation.5.Keep empty replacements distinct from untouched partitions
Write
replacement_diff(current, updates). Maps string partition to unique string file-ID lists. Each updates key replaces that entire partition, including an empty list; absent keys are untouched. Return[partition,added,removed,kept]for every updates key sorted by partition; each file list sorted. A missing current partition starts empty. Include no-change updates. No mutation.6.Validate complete staging and optimistic revision guards
Write
activation_errors(expected, live, staged). expected maps string partition to old integer revision orNone(must be absent); live maps present partitions to integer revisions. staged lists names, duplicates ignored. Require staged exactly expected keys andlive.get(p)==expected[p]. Return {"activate":bool,"missing":sorted_names,"unexpected":sorted_names,"stale":sorted_names}. No mutation.7.Redistribute retired ownership within a movement budget
Write
retire_rebalance(owners, weights, active, budget). owners: partition->worker strings; weights same keys, integers>=0; active nonempty unique workers, budget integer>=0. Keep active owners. Sort retired partitions by (-weight,partition); move up to budget to minimum (active_load,worker), updating loads. Return{"owners":map,"moved":[[partition,old,new]],"pending":sorted_unmoved}. No mutation.8.Pack backfill waves without overlapping write partitions
Write
conflict_waves(jobs, budget). jobs:[partition_names,cost], names unique strings per job, cost integer>=0; budget integer>0. In input order, reject cost>budget as oversize. Otherwise use the earliest existing wave with disjoint partition union and total cost<=budget, or create a wave. Return{"waves":job_index_lists,"oversize":indices}. Preserve assignment order. No mutation.9.Route integer ranges through unequal partition boundaries
Write
range_partitions(ranges, cuts). cuts strictly increasing integers; partition 0 is belowcuts[0], partition i lies [cuts[i-1],cuts[i]), last extends upward. With no cuts all integers use partition 0. For each integer [start,end), start<=end, return ascending partition IDs containing at least one included integer. Empty ranges return []. No mutation.10.Audit owner changes on successor-token partition rings
Write
ring_movements(hashes, old, new). hashes integer list. Each nonempty ring lists[integer_token,string_owner], unique tokens. Ownership uses the smallest token>=hash, wrapping to the smallest token if none; token input order irrelevant. Return[hash_index,old_owner,new_owner]only where owners differ, in hash order. Moving a token without changing its owner is not a movement. No mutation.11.Prune only provably irrelevant partition metadata
Write
prune_candidates(parts, low, high, include_null), low<high integers. parts:[rows,nulls,min,max], integer counts 0<=nulls<=rows; bounds integer/None(unknown). Keep iff rows>0 AND eitherinclude_nullwith nulls>0, or rows>nulls with (min unknown or min<high) AND (max unknown or max>=low). Return indices in input order. Bounds may be independently unknown. No mutation.12.Roll up counts sums and supported partition extrema
Write
partition_rollup(rows). Rows[string_partition,count,total,min,max]. count integer>=0; total integer. At count 0 total=0 and extremaNone; otherwise extrema integers. Aggregate all rows per partition into[partition,count_sum,total_sum,min_nonempty,max_nonempty], sorted by partition. A partition with only empty inputs has extremaNone. Repeated input rows all contribute. No mutation.13.Compare modular partition signatures as diagnostics
Write
signature_differences(old, new, modulus), integer modulus>=2. Maps string partition to integer lists. Signature=[count,sum%modulus,sum_of_squares%modulus]; count not reduced. Return[partition,old_signature_or_None,new_signature_or_None]for differences, sorted. Present empty differs from absent. Equal signatures may conceal different rows; compare only this diagnostic. No mutation.14.Reject stale and expired backfill commit proposals
Write
fence_commits(leases, proposals, now). leases maps string partition to[integer_epoch,string_owner,integer_expiry]; proposals lists[partition,epoch,owner]. now integer. Report[proposal_index,reason]only for invalid proposals: first applicable"missing","stale"(epoch differs),"owner","expired"(now>=expiry). Preserve proposal order. Future epochs also differ. No mutation.15.Resolve attempt events before preferring durable success
Write
attempt_summary(events). Rows[string_partition,integer_attempt,integer_sequence,status], status"running"/"failed"/"success"; sequence unique per attempt. Resolve attempts by largest sequence, ignoring arrival order. Per partition choose highest successful resolved attempt if any, otherwise highest attempt. Return[partition,attempt,status]sorted by partition. No mutation.16.Classify new jobs replays and conflicting identity reuse
Write
idempotent_jobs(ledger, jobs). ledger: string ID->[string_partition,integer_revision]; jobs[id,partition,revision]. An ID with differing payloads across ledger and the whole batch makes all its batch indices conflict. Otherwise known IDs replay; unknown IDs have one new first index and replay later ones. Return{"new":indices,"replay":indices,"conflict":indices}, input order. No mutation.17.Apply only the CDC interval after a frozen snapshot
Write
snapshot_cdc(snapshot, log, cutoff, end), integer cutoff<=end. snapshot maps string ID to JSON value at cutoff. log rows[id,integer_sequence,op,value], globally unique sequences, unordered; op"set"/"delete". Apply only cutoff<sequence<=end in sequence order. setNonestores null; delete removes ID if present. Return[id,value]sorted by ID. No mutation.18.Retain the changed-source causes for every affected target
Write
refresh_causes(changed, targets, before, after). Integer partition-ID lists, duplicates ignored; before/after integers>=0. Target q reads source IDs in inclusive[q-before,q+after]. Return[target,sorted_changed_causes]only for targets affected by at least one changed ID, sorted by target. Do not invent targets outside targets. No mutation.19.Balance a minimum number of bounded contiguous row slices
Write
balanced_slices(rows, cap). rows integer>=0, cap integer>=1. Use the minimum number of nonempty contiguous half-open offset slices covering [0,rows), each length<=cap. Balance their lengths to differ by at most one, placing all longer slices first. Return offset pairs in order; rows=0 returns []. No mutation.20.Recover a generation manifest with empty and absent states
Write
rollback_manifest(history, generation). Rows[string_partition,integer_generation,files], files unique string-ID list orNone(absent). Generations unique per partition. Choose largest generation<=requested per partition; omit if none or selected filesNone. Return[partition,sorted_files]sorted by partition. Empty files remains present; input may be unordered. No mutation.21.Distinguish inspected empty partitions from unknown scans
Write
scan_support(expected, scanned, rows). expected unique integer partition IDs; scanned IDs, repeats ignored; rows lists each observed record's partition ID. Return{"ready":[[partition,row_count]],"unknown":partitions,"unexpected":row_indices}. ready: expected AND scanned, sorted; unknown: expected not scanned, sorted. A row is unexpected if not expected OR not scanned. No mutation.22.Respect capped retry delay and a fixed completion deadline
Write
retry_queue(jobs, base, cap, now). jobs[unique_string_id,attempt,failed_at,deadline], integer attempt 0..30, clocks integers; base/cap positive integers. Retry time=failed_at+min(cap,base*2**attempt). Exhausted iff retry>deadline OR now>deadline; otherwise due iff retry<=now, else waiting. Return{"due":ids_by_retry_then_id,"waiting":sorted_ids,"exhausted":sorted_ids}. No mutation.23.Measure progress against pinned partition weights
Write
frozen_progress(weights, statuses). weights maps string partition to integer weight>=0; statuses lists[partition,"done"/"pending"], last row per partition wins. Only declared weights count; absent status is pending. Return {"done":sorted_ids,"pending":sorted_ids,"weight_done":sum,"weight_total":sum,"fraction":done_weight/total_or_None}. No mutation.24.Select the most row work within a grouped byte budget
Write
io_selection(jobs, budget). <=12 jobs[string_partition,rows,bytes], rows integer>=0, bytes integer>0; budget integer>=0. Select at most one job per partition, total bytes<=budget. Return ascending selected indices minimizing (-total_rows,total_bytes,index_list) lexicographically. Empty selection allowed. Alternatives for one partition cannot both be selected. No mutation.25.Merge sorted shards with stable indexed duplicate witnesses
Write
merge_shards(shards, limit). Each shard is sorted[integer_key,string_row_id]rows, including repeats. limit integer>=0. Globally rank rows by (key,row_id,shard_index,row_index). Return[shard_index,row_index]for the first limit rows, retaining duplicate occurrences. Empty shards contribute nothing. No mutation.26.Map refined spans to both original partition schemes
Write
refine_boundaries(left, right). Both strictly increasing integer boundary lists, length>=2, same first and last boundaries. Partition i is [bounds[i],bounds[i+1]). Return[start,end,left_partition,right_partition]for every adjacent pair in the sorted union of boundaries. A boundary belongs to the partition on its right. No mutation.27.Salt data occurrences and replicate lookup witnesses exactly
Write
salt_inputs(data, lookup, factors). data/lookup string key lists; factors maps key to positive integer bucket count, default 1. Data occurrences use a separate per-key counter starting 0, salt=counter%factor. Return{"data":[[index,key,salt]],"lookup":[[index,key,salt]]}; replicate each lookup occurrence to all salts 0..factor-1 in order, even if key absent from data. No mutation.28.Charge every smallest-first compaction rewrite explicitly
Write
rewrite_ledger(sizes, max_live). sizes nonnegative integer list, initial file IDs are indices;max_liveinteger>=1. While live count>max_live, remove two minimum (size,id), merge into next ID startinglen(sizes), size=sum, charge that size, and reinsert. Return {"merges":[[new_id,left_id,right_id,size]],"cost":total,"live":[[id,size]] sorted by ID}. Zero sizes still merge. No mutation.29.Require expiry and absence of every supplied retirement hold
Write
retirement_checks(parts, references, leases, pinned, now). parts: string ID->expiry integer/None; leases: ID->integer expiry; references/pinned list IDs. Return{"eligible":sorted_ids,"blocked":[[id,reasons]] sorted by ID}. Reason order:"unknown"if expiryNoneelse"young"if now<expiry, then"reference","lease"if lease>now,"pinned". Eligible iff no reason. Ignore extras. No mutation.30.Choose exact minimum-cost recovery replay coverage
Write
replay_cover(required, options). required unique string checkpoint tokens; <=12 options[positive_integer_cost,token_list], token repeats allowed. Choose options whose union contains every required token; extra tokens harmless. Return ascending selected indices minimizing (total_cost,number_selected,index_list) lexicographically, orNoneif impossible. Empty required returns []. No mutation.