Two workers can receive the same inspection-file inventory and still produce different review queues. One sees files in filename order, another sees database arrival order, and a third processes several partitions concurrently. Adding a fixed random seed does not make those input sequences identical. A reproducible review needs an explicit rule that assigns priority to each eligible item independently of its arrival position.
This tutorial develops that rule for an offline file-review workflow associated with a proposed UNITED UAV UIS400 inspection configuration. UNITED UAV publishes this article and the linked listing. The aircraft provides the inspection context; the algorithm assumes no standard camera, onboard API or automatic defect detector. The identifiers and examples below are synthetic. A review subset is a software routing decision, not evidence that an inspection has passed.
Start with a frozen eligible set
Define the unit of selection before choosing any files. A photograph, a video frame, a physical asset and a reviewed finding are different units. Selecting ten images does not select ten assets when one component has hundreds of photographs and another has only one. The worked implementation selects inventory identifiers. It makes no assertion about how many physical components those identifiers represent.
Build and validate an inventory first. Every identifier must refer unambiguously to one accepted file version. The inventory should retain the original filename, a file-content digest, capture context where available, and an explicit eligibility decision. Keep rejected or unresolved items in a separate exception inventory. Quietly discarding them before counting the review universe makes the resulting subset hard to interpret.
Freeze that eligible inventory under a revision identifier. A directory listing taken while an upload is still running is not a stable population. If a late file must be included, create a new revision and describe the change. The selector cannot distinguish an intentional revision from an incomplete transfer; it sees only the identifiers its caller supplies.
Understand what a seed does and does not fix
A stateful random generator produces a sequence of values. When an application assigns those values to records as they arrive, the assignment depends on record order. The same generator state can therefore assign a low value to one file in one run and a different file in another. Parallel workers add another variable because their partitions and completion order can change.
Python's random documentation describes state and seeding. Here the relevant engineering distinction is between reproducing the generator's sequence and reproducing the mapping from files to priorities. A seed alone addresses the former. Sorting a frozen inventory before sampling can address the latter in a single process, but every distributed consumer must still agree on the same ordering and population.
Instead, calculate an item's priority directly from its stable identifier and the declared review seed. The same item then receives the same priority wherever it is processed. No worker consumes a shared sequence, and a task retry does not advance hidden generator state. This makes the selection rule easier to compare across independent implementations.
Specify the bytes behind a priority
The priority protocol needs more detail than “hash the filename.” Filenames can change during export, repeat across directories, or use different Unicode representations. Use the validated inventory identifier, preserving its exact characters. If normalization is required, define and apply it while creating the inventory. The selector should not silently decide that two different identifiers denote the same observation.
The implementation serializes a three-element JSON array containing a protocol label, the review seed and the identifier. This avoids ambiguous concatenations: two string fields containing delimiters cannot accidentally become the same message simply because a separator was chosen poorly. Explicit compact separators and ASCII escaping make this Python implementation's encoding reproducible. The JSON documentation describes these encoder controls.
SHA-256 supplies the primary ordering value. The hashlib documentation defines the byte-input and digest interface used here. An identifier's UTF-8 bytes provide a secondary comparison when two primary values tie. This explicit tie rule makes the order total for distinct valid identifiers, instead of relying on whichever worker returned first.
Implement the selector as a set operation
from hashlib import sha256 from itertools import chain import json def checked_text(value, name): if type(value) is not str or not value: raise ValueError(f"{name} must be a nonempty string") value.encode("utf-8") # Reject lone surrogate code points. return value def priority(uid, seed): encoded = json.dumps( ["uis400-review-v1", seed, uid], ensure_ascii=True, separators=(",", ":"), ).encode("ascii") return sha256(encoded).digest(), uid.encode("utf-8") def choose(ids, k, seed): if type(k) is not int or k < 0: raise ValueError("k must be a nonnegative integer") seed = checked_text(seed, "seed") unique = {checked_text(uid, "uid") for uid in ids} return sorted(unique, key=lambda uid: priority(uid, seed))[:k] def merge(partial_selections, k, seed): return choose(chain.from_iterable(partial_selections), k, seed) The public selection function validates the count, seed and every identifier. Boolean counts are rejected even though Python treats booleans as integers in some contexts. A count of zero is permitted, but the function still validates its input rather than hiding invalid records behind an empty result. Lone surrogate code points are rejected because the tie-order encoding requires valid UTF-8.
Repeated identifiers collapse into one set member. This is deliberate: receiving the same inventory identifier twice should not give it two chances to occupy the subset. However, the function accepts identifiers only. It cannot detect two different files incorrectly assigned the same identifier. That ambiguity must already have been rejected by the inventory builder.
The implementation materializes the unique set and sorts it. For n distinct identifiers, its simplified storage cost is O(n), with O(n log n) sorting comparisons; identifier lengths and encoding work also matter. It is a readable reference implementation, not a constant-memory streaming service. For larger inventories, a heap or database ordering can reduce working storage, provided it preserves the exact priority protocol.
Prove why local selections can be merged
Let the target size be k, and order the complete eligible set by the priority function. Suppose an identifier belongs to the first k positions globally. In any partition containing that identifier, fewer than k distinct identifiers can precede it: every local predecessor is also a global predecessor. Consequently, the identifier survives that partition's local selection of its first k members.
The union of those local selections therefore contains every global winner. Selecting the first k identifiers from the union returns the same result as selecting from the full eligible set. This argument does not require balanced partitions or a particular worker completion order. It requires a shared total ordering, the same eligible universe and sufficiently large local selections.
Requesting a small quota from each worker is a different procedure. If the first three global winners all belong to one partition, asking that worker for only one identifier permanently removes two necessary candidates. No clever merge can reconstruct discarded identifiers it never receives. Each worker needs up to the global target k, rather than a fraction computed from the worker count.
Exercise both the valid merge and its counterexample
ids = [f"example-job/image-{i:03d}" for i in range(12)] seed = "review-plan-17" k = 3 expected = choose(ids, k, seed) shards = [ids[::3], ids[1::3], ids[2::3]] partial = [choose(shard, k, seed) for shard in shards] assert merge(partial, k, seed) == expected assert choose(reversed(ids), k, seed) == expected assert choose(ids + ids, k, seed) == expected assert merge(partial + partial, k, seed) == expected # Construct a counterexample to requesting too few IDs per shard. ranked = choose(ids, len(ids), seed) uneven = [ranked[:k], ranked[k:]] too_short = [choose(shard, 1, seed) for shard in uneven] assert merge(too_short, k, seed) != expected The final assertion constructs an intentionally unfavorable partition rather than hoping a random fixture exposes the problem. All three global winners are placed in the first shard. Keeping only one item from each shard cannot preserve that global result. The failure is about information loss before merging, not about the quality of the hash function.
The other assertions check separate properties. Reversing input order must preserve the subset. Repeating inventory identifiers must not increase their representation. Repeating a worker's complete partial result must also preserve the merged subset. These checks describe the selector's set behavior; they do not establish that a file-transfer system has delivered every required partition.
A production receiver should validate partial-result envelopes before calling the merge function. Include the protocol version, inventory revision, review seed, target count and partition identity. Reject mismatched plans and verify that every expected partition has reported. The compact merge function intentionally does not implement that surrounding delivery protocol.
Keep identity distinct from file content
An inventory identifier answers which selectable observation this record represents. A content digest answers whether some file bytes match the accepted version. These identities can coincide in a particular design, but they need not. Two separate capture events can produce identical bytes, and a single observation can have an original file plus an explicitly linked preview.
Do not switch between those meanings halfway through a review. Selecting by file digest merges byte-identical observations; selecting by observation identifier retains them as separate members. Either behavior changes the selection universe and can affect representation. Write the intended unit into the plan and test it with deliberately repeated bytes under different identifiers.
The code hashes an encoding of the seed and identifier to assign priority. It does not hash or open the image file itself. A matching priority therefore says nothing about file integrity. Before presenting a selected image, the retrieval layer should verify its bytes against the frozen inventory and retain a clear error when the expected version is missing.
Decide how revisions affect membership
For a fixed seed and identifier, the priority remains unchanged when unrelated records are added. The selected set can still change: a new identifier with a sufficiently low priority displaces the previous last winner. This is a useful predictable property, but it does not mean a subset is permanent across inventory revisions.
If the requirement is to preserve an already assigned queue, save its selected identifiers as a separate result tied to the original revision. Do not regenerate the queue against today's directory and call it the same review. A supplementary review can cover newly admitted items without rewriting the record of what the earlier reviewer actually saw.
Changing the seed changes priorities and generally creates a different subset. Record why a new seed is needed. Repeatedly trying seeds until the selected pictures look convenient undermines a predeclared review rule, even though every individual run is reproducible. Commit the plan before examining its winners when independent review of the selection procedure matters.
Handle coverage requirements explicitly
A global subset can leave small groups unrepresented. If a job contains several asset classes, sites or capture periods, first decide whether each group requires a separate review allocation. The selector cannot infer those obligations from a photograph's identifier. Group membership must come from validated inventory fields, not from guessing meaning inside a filename.
For a declared per-group allocation, run the same selector independently within each disjoint group and record the requested and available counts. A group with fewer eligible items than requested returns all its members; that shortfall should remain visible. If groups overlap, an item may appear in several group results, so define whether the final review treats those appearances as one task or several obligations.
A fixed hash order is useful for repeatable routing. It is not, by itself, a defensible statistical acceptance design or a calculation of defect prevalence. Selection units, eligibility, clustering, group allocation and the treatment of unreadable files all affect interpretation. If a formal estimate or confidence statement is required, design and justify that procedure separately rather than attaching one to this code.
Preserve unsuccessful retrievals in the result
A selected identifier can fail to open because its bytes are missing, corrupt or unauthorized for the receiving application. Replacing it silently with the next convenient picture changes the selection and hides a data-delivery failure. The result should retain the selected identifier, the attempted file version and the actual retrieval outcome.
If replacement is part of the agreed procedure, predeclare it. One option is to preserve the full priority order for an eligible group, then record each rejected candidate and the next admitted identifier. Keep the original requested selection and the delivered review queue distinguishable. Otherwise, a later reader cannot tell whether the subset changed because of a new plan or because files were unavailable.
This separation is particularly helpful when a review result says “three items completed.” That number could mean three selected files opened, three valid observations were examined, or three findings were accepted. These are separate stages with different denominators. Return counts and unresolved identifiers for each stage rather than compressing them into one success flag.
Test properties across changes in execution
Example assertions are useful, but distributed correctness deserves broader fixtures. For a small inventory, compare the global result with merged local results over many partitions, including empty partitions, one large partition and more workers than records. Permute both the record order and the order in which partial results are delivered.
Test identifier behavior separately. Include non-ASCII text, leading zeros, embedded delimiters and strings that resemble paths. Confirm that the exact protocol bytes are stable for a known fixture. Verify that distinct identifiers remain distinct, even when their associated file bytes are equal. Do not let a convenience normalization step slip into one worker implementation.
Then exercise malformed inputs: a negative count, a boolean count, an empty seed, an empty identifier and text that cannot be encoded under the declared rules. The reference function should reject those inputs deterministically. Its successful empty result should remain different from an error. These tests make the selection boundary inspectable without inventing a measured aircraft or camera capability.
Make partial results auditable
Save the selected identifiers in their final priority order, not merely as an unordered set. Retain the inventory revision, eligibility-rule version, seed, protocol label, requested count and actual distinct count. If local results were merged, record the expected and received partition identities and the check that their plan fields agreed.
The plan should also say which implementation and encoding rules produced the result. JSON output from another language is not automatically byte-identical to Python's ASCII-escaped representation, even when both decode to the same strings. A port needs shared test vectors for its priority input bytes and final comparison order. Human-readable equality of displayed JSON is insufficient for digest equality.
None of these records authenticate an inspection or establish that a reviewer reached the correct conclusion. They explain which files were assigned and why that assignment can be reproduced. Keeping that limited purpose clear makes the selection useful to both developers debugging a pipeline and specialists responsible for interpreting the actual imagery.
Apply the method to the proposed inspection deliverable
For a UIS400 procurement or integration discussion, first agree on the actual payload, source-image outputs and handoff inventory with the supplier. The catalog's inspection context does not establish that a particular camera, file schema or review application is included. Ask for a representative export package and run the selector against a controlled inventory built from that package.
A practical demonstration should reproduce one selected subset from a single process and from several differently partitioned workers. It should also expose a missing partition, an ambiguous image identifier and a selected file that fails its content check. Those exercises evaluate the proposed data handoff; they do not replace payload configuration checks or specialist inspection judgment.
The useful deliverable is a small, explicit agreement: the same validated inventory and plan produce the same ordered review identifiers, regardless of worker order, while missing or changed evidence remains visible. That is a narrower and more testable promise than a dashboard that simply displays a few plausible photographs.
Written with AI assistance; the example is an offline, synthetic software exercise.

