Shipmind Labs

Redrawing a shift plan: ownership by claim, not by identity

· 8 min read

A weekly courier plan never stays still: a pattern moves an hour, a holiday is added, a worker switches depot. So the second draw has to remove whatever the first one put into the roster, and by then the roster also holds shifts nobody planned, like a swap agreed over the phone or a line a supervisor typed in before the morning wave. The entire problem is deciding which shifts the redraw owns, and the usual answer, tagging rows with the plan that created them, is the one that quietly breaks.

We hit this shape every time we build dispatch for field work. Courier, warehouse and store-side apps all read the same roster, and they disagree about who is allowed to change it. In shift-planner we settled the question inside the library rather than in each caller, and the rest of this post is the reasoning and the code.

A replace needs two pure functions, not one#

An operation that replaces part of a collection answers two questions: what goes in, and what comes out. Most implementations only make the first one a function. The second is bookkeeping, a plan_id column, or the list of identifiers the previous run returned. Bookkeeping works until the tag is lost in an import, or the identifier list is stale because a row was edited after it was written, or two plans both believe they own the same tag. Then the redraw either leaves duplicates behind or deletes something a human put there on purpose, and nobody can reconstruct which.

So the removal set has to be derivable from the plan alone, the same way the addition set is. Plan.shifts() is the addition set: it walks the Horizon day by day, skips anything in Holidays, applies the per-worker limits, and builds each Shift through ShiftPattern.shift_on. Plan.claims is the removal set, expressed as a predicate over a single shift. Plan.applied_to puts them together: it keeps every shift the plan does not claim, appends the shifts the plan draws, and builds a new Roster from the two.

Both sides are functions of the plan, not of the roster's history and not of what a previous run happened to write. That is what makes redrawing idempotent:

python
from datetime import date, time, timedelta, timezone

from shift_planner import Horizon, Plan, Roster, ShiftPattern

UTC = timezone.utc
EIGHT = timedelta(hours=8)

plan = Plan(
    horizon=Horizon(date(2026, 5, 4), days=7),
    patterns=(
        ShiftPattern("anna", "depot-north", time(8), EIGHT, {0, 1, 2, 3, 4}),
        ShiftPattern("zoe", "depot-south", time(16), EIGHT, {0, 2, 4}),
    ),
    rest=EIGHT,
)

roster = plan.applied_to(Roster())
assert plan.applied_to(roster) == roster

That assertion is the property we actually care about. A redraw that runs twice (a retried request, a job that fired on two workers, an operator who clicked the button again because the page was slow) must not produce a roster with every shift doubled. Nothing in the call looks at how the roster got its contents, so there is no state to get out of step. The same reasoning covers the input: Plan.__post_init__ deduplicates equal patterns while keeping their order, so a plan assembled from two sources that both name the same weekly pattern draws it once.

The claim is a worker and a local date#

A shift is claimed when two things hold. Its worker is in Plan.workers, the frozenset of workers the plan's patterns name. And the date of shift.start.astimezone(self.zone) is covered by the horizon:

python
@dataclass(frozen=True)
class Horizon:
    """The span a plan is drawn for: the half-open range ``[start, start + days)``."""

    start: date
    days: int = 7

    @property
    def end(self) -> date:
        return self.start + timedelta(days=days)

    def covers(self, day: date) -> bool:
        return self.start <= day < self.end

Note what the claim leaves out: location, length, capacity, window, or any identity the shift might carry. That is deliberate. A supervisor who moved a planned courier from depot-north to depot-east for one afternoon produced a shift that the plan still claims (same worker, same local day), and the redraw overwrites it. We would rather that be loud and documented than have the plan's output silently merge with hand edits it cannot reconcile.

The zone matters because the day boundary is drawn in the plan's zone, not in UTC and not in the zone the shift happens to be stored with. The same wall-clock hour lands on different instants depending on which zone reads it:

python
pattern = ShiftPattern("anna", "depot-north", time(8), EIGHT, {0})

in_utc = pattern.shift_on(date(2026, 5, 4))
in_east = pattern.shift_on(date(2026, 5, 4), timezone(timedelta(hours=3)))

in_utc.start                      # 2026-05-04 08:00+00:00
in_east.start.astimezone(UTC)     # 2026-05-04 05:00+00:00

ShiftPattern.at is a plain time (the constructor refuses one with a tzinfo) and the plan supplies the zone, so you can reuse a pattern across plans that read it differently. The flip side is the one real limitation of the design: two plans with different zones over the same workers will not cleanly overwrite each other. A shift drawn by an east-zone plan at 01:00 local starts at 22:00 UTC the day before, and a UTC plan whose horizon begins on the local Monday does not claim it. Redraw with the UTC plan and the east plan's edge shift stays, a stranger neither plan will ever remove. If two plans share workers, they have to share a zone; if they must not share a zone, they must not share workers.

Rest merges upward#

A Plan carries rest, and so does a Roster. When the plan draws into a roster, the rebuilt roster gets max(roster.rest, self.rest). A plan can therefore tighten a roster's rest rule, and it has no way to loosen one.

This is not symmetry for its own sake. Rest is a rule about people, and in the systems we build it usually traces back to something outside the scheduler: an agreement, a policy, a statutory minimum someone else owns. A plan is a convenience, a weekly shape somebody drew to save typing. Letting the convenience relax the rule, as a side effect of a redraw nobody was watching, is the wrong default. Raising it is safe in the other direction, because a stricter rule only ever rejects. If you genuinely need a shorter rest, you build the Roster yourself and say so.

The seam is where it fails, and it fails loudly#

The redraw does not validate only the shifts it drew. It hands everything, kept shifts and new ones together, to the Roster constructor, which sorts by start and checks each worker's consecutive pair. So the interesting failure sits at the boundary of the horizon, where a kept shift meets a drawn one:

python
from datetime import datetime

from shift_planner import InsufficientRestError, Shift

sundays = ShiftPattern("zoe", "depot-south", time(16), EIGHT, {6})
plan = Plan(horizon=Horizon(date(2026, 5, 4), days=7), patterns=(sundays,), rest=EIGHT)

# Monday 2026-05-11 is past the horizon's end, so the plan does not claim this one.
monday_early = Shift("zoe", "depot-south", datetime(2026, 5, 11, 4, tzinfo=UTC), timedelta(hours=4))

try:
    plan.applied_to(Roster([monday_early]))
except InsufficientRestError as error:
    print(error)

The Sunday pattern ends at 00:00 on Monday; the kept shift starts at 04:00. Four hours of rest against a rule of eight, and the error names both shifts and the rule it broke. Notice that the roster it was applied to had the default rest of zero: that pair was legal before the redraw and is illegal after, which is what merging rest upward means. An outright clash raises OverlappingShiftError, which subclasses InsufficientRestError because an overlap is the zero-rest case of the same rule, while keeping its own name so you can still catch a clash on its own.

The alternative, validating only the drawn shifts and trusting the rest of the roster because it was valid yesterday, is how a courier ends up with a four-hour turnaround that no single operation ever approved.

What it costs to run#

Three costs, all of them visible.

You must store the plan, not just the roster it produced. The removal set is computed from the plan, so a plan you have thrown away owns shifts you can no longer identify. In practice the plan is the record and the roster is a projection of it plus whatever was added by hand outside the claim.

Every redraw revalidates the whole roster rather than a diff: a sort plus one comparison per worker's consecutive pair. For a planning horizon of days or weeks that is nothing, and it buys the seam check above. If a roster ever grew large enough for this to matter, the fix is probably narrower rosters per location, not a cheaper check.

And hand edits inside the claim are lost on redraw. That is a product decision rather than a bug, and it has to reach the person making the edit. To keep an edit you put it outside the claim (a worker the plan does not name, or a date the horizon does not cover), or you re-apply it after the redraw with Roster.add, which carries the merged rest rule and will tell you if the edit no longer fits.

The library is pre-alpha and the public API is not stable yet, but this part we consider settled. Replacement by claim is the only version of the operation we have found that survives being run twice.

Was this useful?

Building something similar?

or email hello@shipmindlabs.com