At a US merchandise team's engraving handoff, the card printer and the bottle engraver both have files beginning at 000100. Each file looks orderly. Together, they break the buyer's promise of one project-wide serial number per finished gift. Before either vendor receives approval, the merchandise lead needs to decide which numbers belong to each production batch.

Allocate integer ranges in one shared project ledger, check the inclusive endpoints, and approve the resulting version before releasing artwork. The reusable Python model below makes those calculations reproducible. It separates numeric identity from printed zeros and shows why two individually correct calculations can still create a collision when people approve them independently.
Decide what one number identifies
Start with the promise on the purchase brief. If one finished gift consists of a bottle, a card and a box, do all three components repeat that gift's number, or does each component require its own identity? Both arrangements are possible, but they produce different counts. A run of 40 gift sets requires 40 identities when the same number appears on each set's components; allocating 120 unique numbers would change the promise.
This model allocates an internal serial namespace for an agreed project. It does not assign recipients, reserve stock, authenticate a voucher or establish regulatory traceability. Write the namespace name beside the ledger, such as PROJECT-DEC26. Integer 105 in that project has no implied relationship to integer 105 in another project. If a buyer wants organization-wide uniqueness, the owner must define and operate that larger namespace before using the model.
Define a batch by the production file that receives an approved contiguous range. A vendor may have multiple batches, and two vendors may work on components carrying the same gift-level identities. In the latter case, share the approved range as a component instruction rather than requesting another allocation. Otherwise, a team can accidentally count the bottle and its matching card as two finished gifts.
Physical suitability is a separate decision. The corporate gift inventory aging guide addresses what to do with existing stock, while the remaining shelf-life guide addresses food-lot eligibility at delivery. Neither supplies serialization logic. A valid interval cannot make unavailable or unsuitable merchandise ready for production.
Keep integer identity separate from printed display
The ledger stores integer 7. The artwork may display 000007. These are two representations of the same identity, so a second file cannot claim 7 is available merely because the first file prints six characters. Keep the integer endpoints and display width in separate fields. Apply padding only after the range is approved.
The helper below accepts a display width from one through 12. Width is a minimum, not a cutting instruction: displaying 1234567 with width six returns all seven digits. If the decoration area permits exactly six characters, separately reject any approved endpoint above 999999 before releasing artwork. Do not truncate the leftmost digit to make a number fit; that could turn two different integers into the same printed label.
Microsoft's US guidance on leading zeros and large numbers explains how Excel can remove leading zeros during conversion and how text imports or formatting can preserve them. Its automatic-conversion controls apply to specified editions, so confirm the actual version used by each vendor. A workbook that looks correct on screen is insufficient evidence that a downstream export retained its display strings.
For a production export, retain numeric start and end in the approval record and inspect the actual exported display column. Reopen the delivered file using the vendor's agreed import method. Check 000105 as six characters, rather than accepting a preview that happens to format numeric 105 with zeros. This is a handoff check, not a claim that Excel or Giftpack runs the allocator.
Freeze the inputs before running the model
Version 1.0 uses three inputs: existing reservations, new requests and the smallest permitted integer, called base. Every run uses one frozen project snapshot. Include consumed, voided and previously released intervals in reservations because those numbers must remain unavailable. Cancellation changes a reservation's operational status; it does not erase the historical allocation.
| Input field | Required value | Practical decision |
|---|---|---|
| Reserved row | Three-item tuple: batch ID, inclusive start, inclusive end | Include every approved interval that cannot be reused |
| Request row | Two-item tuple: batch ID, quantity | Count identities, using the agreed finished-gift definition |
| Base | Exact integer from 0 through 999999999999 | Choose 1 if the vendor cannot process serial zero |
| Batch ID | Uppercase ASCII letter first; up to 32 allowed characters | Use letters, digits, underscore or hyphen after the first letter |
| Quantity | Exact integer from 0 through 999999999999 | Zero means no interval, not a one-number reservation |
| Display width | Exact integer from 1 through 12 | Confirm both padding and actual decoration capacity |
The function accepts lists containing Python tuples. JSON arrays are not Python tuples. When building an importer, validate required fields and construct the tuples explicitly; do not pass unexamined nested arrays into this function. Missing values, floats, numeric strings, booleans and negative numbers fail. Rejecting True matters because Python otherwise treats booleans as an integer subtype.
IDs must match [A-Z][A-Z0-9_-]{0,31} and remain unique across reservations and requests, including zero-quantity requests. Put human-readable names in separate display metadata. Lowercase, spaces, Unicode characters and formula-like identifiers are rejected rather than automatically normalized. Silently changing an ID could conceal that two departments submitted the same job under different spellings.
Keep the reservation list complete even when old intervals fall below the chosen base. The checker still needs to establish that the authoritative ledger is internally consistent. Base changes where new searches begin; it does not excuse historical overlaps or erase reservations. Where two source spreadsheets disagree, pause allocation and have the ledger owner reconcile their records before selecting either as authoritative.
Likewise, keep quantities tied to a dated order revision. If the decoration supplier asks for three spare pieces, determine whether those pieces need new gift identities or are unnumbered setup material. Adding three to the quantity without resolving that question changes the population the buyer approved. Record the decision beside the batch rather than burying it in a vendor email.
These limits, the ID grammar and the allocation order are operating choices in this model, not US legal requirements. A merchandise operations lead owns the method and must review it when the number domain, batch policy or production workflow changes. Quantity, base, reservation or namespace changes require a fresh calculation against the current ledger.
Use the complete allocator and collision checker
Copy the following model into a Python environment. It returns proposed rows; it does not save them, lock a ledger or commit an approval. The supplied reservations remain unchanged. Positive results contain batch ID, inclusive start, inclusive end and quantity. A zero request returns the ID, two None endpoints and zero.
import re
MAX_SERIAL = 999_999_999_999
ID = re.compile(r'[A-Z][A-Z0-9_-]{0,31}', re.ASCII)
def number(x):
if type(x) is not int or not 0 <= x <= MAX_SERIAL:
raise ValueError('integer domain')
return x
def identity(x):
if type(x) is not str or ID.fullmatch(x) is None:
raise ValueError('batch identifier')
return x
def check_ranges(rows):
if type(rows) is not list:
raise ValueError('range list')
clean, seen = [], set()
for row in rows:
if type(row) is not tuple or len(row) != 3:
raise ValueError('range tuple')
key, lo, hi = row
identity(key); number(lo); number(hi)
if key in seen or lo > hi:
raise ValueError('duplicate or reversed')
seen.add(key); clean.append((key, lo, hi))
clean.sort(key=lambda r: (r[1], r[2], r[0]))
for left, right in zip(clean, clean[1:]):
if right[1] <= left[2]:
raise ValueError('inclusive collision')
return clean
def allocate(requests, reserved, base=0):
number(base)
occupied = check_ranges(reserved)
if type(requests) is not list:
raise ValueError('request list')
seen = {r[0] for r in occupied}
jobs = []
for row in requests:
if type(row) is not tuple or len(row) != 2:
raise ValueError('request tuple')
key, count = row
identity(key); number(count)
if key in seen:
raise ValueError('duplicate batch identifier')
seen.add(key); jobs.append((key, count))
out = []
for key, count in sorted(jobs):
if count == 0:
out.append((key, None, None, 0)); continue
lo = base
for _, a, b in occupied:
hi = lo + count - 1
if hi < a:
break
if lo <= b:
lo = b + 1
hi = lo + count - 1
if hi > MAX_SERIAL:
raise ValueError('serial capacity')
occupied = check_ranges(occupied + [(key, lo, hi)])
out.append((key, lo, hi, count))
return out
def display(value, width=6):
number(value)
if type(width) is not int or not 1 <= width <= 12:
raise ValueError('display width')
return str(value).zfill(width)
The collision rule is inclusive. After sorting by start, a later interval collides when its start is less than or equal to the earlier interval's end. Thus 1–3 and 4–5 are adjacent and valid; 1–3 and 3–5 both contain 3 and fail. Checking existing reservations first prevents a new calculation from quietly inheriting a broken ledger.
Requests sort by exact ASCII ID. Each positive request searches again from base for the first contiguous gap large enough, jumping past occupied intervals. This deterministic first-fit policy never splits a batch across holes. It also does not promise that numbers increase with batch ID: a later small request may fit in a gap that an earlier larger request could not use.
Endpoints in this article are inclusive. The Python 3.12 range documentation, checked December 6, 2026, describes an exclusive stop. When expanding an approved interval into individual production rows, use range(lo, hi + 1). Using range(lo, hi) would omit the final number. Expand only approved, reasonably sized production batches; the allocator itself avoids building a list of every possible serial.
Resolve the two-vendor handoff with one allocation
Assume the old reservation is authoritative, both new files remain unissued and each requested unit needs one project identity. The inputs are base 100, reservation OLD 100–104, request LASER-B for three identities and request LASER-A for four. Request order in the submission does not determine allocation order.
reserved = [('OLD', 100, 104)]
requests = [('LASER-B', 3), ('LASER-A', 4)]
result = allocate(requests, reserved, base=100)
# [('LASER-A', 105, 108, 4), ('LASER-B', 109, 111, 3)]
LASER-A searches from 100, encounters OLD and moves to 105. Its end is 105 + 4 − 1 = 108. LASER-B then encounters both occupied intervals and starts at 109; its end is 109 + 3 − 1 = 111. The total is four plus three, or seven new identities. The inclusive check independently confirms (108 − 105 + 1) + (111 − 109 + 1) = 7.
| Batch ID | Quantity | Integer start | Integer end | Printed display | Ledger version |
|---|---|---|---|---|---|
| OLD | 5 | 100 | 104 | 000100–000104 | v1, retained in v2 |
| LASER-A | 4 | 105 | 108 | 000105–000108 | v2 |
| LASER-B | 3 | 109 | 111 | 000109–000111 | v2 |
The merchandise lead approves v2, records both new intervals and sends each vendor its corresponding range and artwork revision. The printer does not restart at 000100, and the engraver does not independently choose another starting point. This resolves the opening conflict before either file is released.
Acceptance has two layers. The combined ledger must pass the collision checker, and the actual artwork exports must contain the correct sequences. For LASER-A, inspect first 000105, interior 000106 or 000107, and last 000108. Inspect the corresponding positions in LASER-B. Those samples support file review; they do not prove every physical gift was engraved correctly. Agree the production inspection separately.
If LASER-A changes to five before approval, rerun both requests against v1: LASER-A becomes 105–109 and LASER-B becomes 110–112. After approval, do not overwrite v2 with this new calculation. Hold the change and issue a documented replacement decision against the current reservations, preserving any already released numbers.
Give simultaneous approvals a single commit boundary
Now assume ledger v1 contains only OLD 100–104. Coordinator X requests A with quantity two; coordinator Y independently requests B with quantity two. Both use base 100 and both calculate 105–106. Each calculation is correct for its own input snapshot. Together, the proposed intervals collide.
One designated ledger owner must serialize approval. X submits first and the owner records A 105–106 in v2. Y's proposal still names v1, so the owner refuses that stale proposal and asks for recalculation. Against v2, B receives 107–108. The approved new population is (106 − 105 + 1) + (108 − 107 + 1) = 4 identities, with no shared endpoint.
A real multiuser application would need its own atomic transaction or version check around this step. This standalone function provides neither. A filename containing “final” is not a commit boundary, and a successful collision check performed before another approval cannot establish that the ledger is still current afterward.
If both original outputs have already been printed, checking A 105–106 alongside B 105–106 raises an inclusive-collision error. Hold both affected files and identify which numbers have reached physical production or recipients. The project owner decides which unissued file to regenerate. Do not renumber gifts already released or silently assign the same number to a replacement gift.
Rollback means restoring a controlled operational state, not deleting evidence. Keep the rejected proposal, the ledger version it used and the superseding decision. If a reserved range is canceled, retain it as voided in the reservation input. A retry of an approved job uses its saved approved range; submitting a new batch ID would request additional identities rather than resume the original job.
Check gaps, zero quantities and invalid boundaries
A gap example explains why first fit can surprise a team. With base 100, OLD1 reserved at 100–104 and OLD2 at 108–110, request A needs four and request B needs two. The gap 105–107 has only three identities, so A receives 111–114. B searches again from base and fits at 105–106. There are six new identities, although the ranges are not numerically ordered by ID.
That result is useful when conserving small gaps matters. If production instead needs every new batch to follow the previous batch numerically, adopt and version a different allocation policy. Do not manually move B after calculation and keep calling the result this model's deterministic output.
| Input | Action | Expected output | Failure reason |
|---|---|---|---|
| ZERO quantity 0; no reservations | Allocate from base 0 | ZERO, no endpoints, count 0 | None; zero occupies no interval |
| ONE quantity 1; no reservations | Allocate from base 0 | ONE 0–0, count 1 | None; zero is a valid identity |
| Reservation A 0–0; B quantity 1 | Allocate from base 0 | B 1–1, count 1 | None; adjacency is allowed |
| A 1–3 and B 3–4 | Check reservations | ValueError | Shared inclusive endpoint 3 |
| A 1–9 and B 3–4 | Check reservations | ValueError | Nested interval overlaps |
| A 9–8 | Check reservations | ValueError | Reversed interval |
| Reserved A plus request A | Allocate | ValueError | Batch ID already exists |
| Quantity True, 1.0 or string “1” | Allocate | ValueError | Input is not an exact integer |
| Empty, spaced, lowercase or formula-like ID | Allocate | ValueError | Identifier grammar fails |
| Quantity 2; base 999999999999 | Allocate | ValueError | End exceeds serial ceiling |
A zero request still consumes its batch identifier for that run's validation. Keep the zero-result row in the approval record if it explains an omitted job, but do not insert None endpoints into the numeric reservation list. Separately retain the project’s batch register if zero-work jobs must remain historically unique across later runs; this function knows only the requests and reservations supplied to it.
If any input fails, correct the source record and rerun the full proposal. Do not distribute an earlier subset from a failed call. The function raises rather than returning a partial result, and it does not modify the caller's reservations. That behavior makes error handling clearer, but the calling application remains responsible for avoiding partial external writes.
Make the approved output usable in production
Keep one handoff record containing project namespace, input ledger version, method version, base, batch quantities, approved integer endpoints, display width and artwork version. Add the approver and approval time. Attach the actual production file to that record so a vendor can identify which export the approval covers.
Before release, confirm every positive row satisfies end − start + 1 = quantity. Confirm zero rows have no endpoints. Combine the proposed positive intervals with existing reservations and run the checker again. Then confirm the ledger version has not changed since the proposal was calculated. These checks connect the arithmetic to the approval decision.
For the seven-identity example, an explicit acceptance record could read: “PROJECT-DEC26; ledger v2; LASER-A; quantity 4; integers 105 through 108 inclusive; display width 6; artwork revision A3.” A separate LASER-B record specifies quantity three, integers 109 through 111 and its own artwork revision. Both records point to the same v2 ledger. This is enough information to challenge a vendor proof starting at 000100 without reconstructing the allocation from memory.
If the vendor returns a file containing four rows but the sequence is 000105, 000106, 000106, 000108, the endpoints and row count look correct while one identity repeats and another is missing. For small runs, compare every exported numeric identity with the approved expanded sequence; for larger runs, use a complete machine comparison plus the visual proofs. Check both row count and set membership, since set membership alone can conceal duplicates when extra rows are present.
A vendor acknowledgement should repeat the batch ID, namespace, endpoints, display width and file revision. Ask for proof of the first, last and one interior label using the actual decoration treatment. If a laser font makes 0 and O difficult to distinguish, numeric uniqueness alone does not resolve readability. Review the physical sample or suitable production proof before authorizing the agreed run.
After production, reconcile the serial manifest with reported good units, rejected units and any rework. A correct range does not detect a skipped piece, a copied recipient row or two objects bearing the same label. Record rejected or voided numbers without returning them to the available pool. Decide explicitly whether a replacement carries the original gift's identity or needs a newly allocated identity under the project policy.
Preserve version 1.0 of the method with the approved inputs and outputs. The merchandise operations lead should revisit it whenever quantity rules, reserved-number treatment, display capacity or approval ownership changes. A future improvement must explain its changed behavior and rerun relevant boundary examples before it replaces the version supporting an active project.
Bring the approved range brief to Giftpack
Take the range decision into the production conversation. Giftpack's custom merchandise and production service describes artwork and sample approval, manufacturing coordination and quality checks around an agreed specification. Those are relevant places to discuss numbered decoration; the page does not establish that this allocator runs inside Giftpack or that every product supports serial engraving.
Share the approved batch quantities, namespace, integer endpoints, display width, artwork version and proof requirements. Ask whether the specific number treatment is feasible on the selected product and how the vendor will receive and verify the sequence. Keep the ledger owner responsible for approving identities, and make serial accuracy part of the agreed production brief before releasing the files.

