Credit days freed by the same sync before checking the balance

A sync deleted the rows a re-plan had dropped only after apply_proposed_days
had already validated, so capacity being freed in the very same call was
never counted. Shortening one period and lengthening another while near the
pool cap read as pure net-new demand and was refused outright, writing
nothing and losing the edit silently.

apply_proposed_days now takes the keys it should delete, credits those rows
back to their tier and to the dubbeldagar quota during the up-front checks,
and performs the deletions in its own write phase. Validation still runs
fully before any write, which is what SQLite's lack of a cross-request
transaction requires.
This commit is contained in:
2026-09-17 18:12:31 +02:00
parent 6cd60887d5
commit c1aa4ae0b0
4 changed files with 505 additions and 31 deletions
+109 -31
View File
@@ -84,6 +84,7 @@ class PlanApplyResult:
skipped_identical_count: int = 0
skipped_free_count: int = 0
replaced_count: int = 0
deleted_count: int = 0
collisions: list[DayCollision] = field(default_factory=list)
rejections: list[Rejection] = field(default_factory=list)
@@ -277,6 +278,7 @@ class PlanningService:
workspace_id: UUID,
days: list[ProposedDayInput],
replace: bool = False,
delete_keys: set[tuple[UUID, UUID, date]] | None = None,
) -> PlanApplyResult:
"""Persist a batch of proposed days as `planned_leave_day` rows.
@@ -292,13 +294,29 @@ class PlanningService:
`replace=True` to overwrite those specific collisions (every other
collision-free day in the batch is written too).
`delete_keys` names rows (by their `(child_id, parent_personal_
data_uuid, date)` identity) to delete as part of this same call —
e.g. `sync_plan` uses it for rows the freshly-computed plan no longer
accounts for at all. A key must not also appear in `days`; that is a
structural error (a batch cannot both write and delete the same
slot). Deletions are folded into the same up-front validation as the
creates/replaces: the tier (or dubbeldagar slot) a deleted row frees
is credited back before checking whether the batch's new demand
fits, so a sync that frees N days and re-spends N days in the same
call is validated against the *post-sync* balance, not a stale
pre-write snapshot. A key with no matching row (already gone) is
silently ignored rather than treated as an error.
Validates the entire batch up front (day types, per-day dubbeldagar
window, batch-wide dubbeldagar quota, child eligibility window,
remaining sjukpenning/lagsta balance) and only writes if everything
passes — SQLite gives us no cross-request transaction here, so this
explicit validate-then-write split is what keeps a rejection from
ever leaving partial writes behind.
remaining sjukpenning/lagsta balance, credited for anything in
`delete_keys`) and only writes if everything passes — SQLite gives us
no cross-request transaction here, so this explicit validate-then-
write split is what keeps a rejection from ever leaving partial
writes behind.
"""
delete_keys = delete_keys or set()
# -- stage 1: structural validation ------------------------------
structural_errors: list[Rejection] = []
for i, d in enumerate(days):
@@ -336,17 +354,33 @@ class PlanningService:
)
deduped[key] = d
for key in delete_keys:
if key in deduped:
child_id, parent_uuid, day = key
structural_errors.append(
Rejection(
message_key="planApply.rejection.deleteKeyConflict",
data={
"date": day.isoformat(),
"child_id": str(child_id),
"parent_personal_data_uuid": str(parent_uuid),
},
)
)
if structural_errors:
return PlanApplyResult(accepted=False, rejections=structural_errors)
unique_days = list(deduped.values())
if not unique_days:
if not unique_days and not delete_keys:
return PlanApplyResult(accepted=True, skipped_free_count=skipped_free_count)
# -- stage 2: classify against existing rows (collision detection) --
by_child: dict[UUID, list[date]] = {}
for d in unique_days:
by_child.setdefault(d.child_id, []).append(d.date)
for child_id, _parent_uuid, day in delete_keys:
by_child.setdefault(child_id, []).append(day)
existing_by_key: dict[tuple[UUID, UUID, date], PlannedLeaveDay] = {}
for child_id, dates in by_child.items():
@@ -359,6 +393,12 @@ class PlanningService:
for row in existing_rows:
existing_by_key[(row.child_id, row.parent_personal_data_uuid, row.date)] = row
# Rows named by `delete_keys` that actually exist — a key with no
# matching row (already gone) is silently ignored.
delete_rows: list[PlannedLeaveDay] = [
existing_by_key[key] for key in delete_keys if key in existing_by_key
]
to_create: list[ProposedDayInput] = []
to_replace: list[tuple[PlannedLeaveDay, ProposedDayInput]] = []
to_update_metadata: list[tuple[PlannedLeaveDay, ProposedDayInput]] = []
@@ -407,7 +447,7 @@ class PlanningService:
)
pending = to_create + [new for _, new in to_replace]
if not pending and not to_update_metadata:
if not pending and not to_update_metadata and not delete_rows:
# Nothing left to write — either an empty batch or a fully
# idempotent re-apply.
return PlanApplyResult(
@@ -417,10 +457,20 @@ class PlanningService:
)
# -- stage 3: domain validation on the batch that would actually write
#
# `delete_rows` is threaded into both checks below so a row this same
# call is about to delete is credited back to its tier/quota BEFORE
# the new demand is checked against what's left — the bug this
# `delete_keys` parameter exists to fix was validating against a
# pre-write snapshot that hadn't yet had that capacity freed.
domain_errors: list[str] = []
domain_errors.extend(await self._validate_dubbeldagar_batch(pending, to_replace))
domain_errors.extend(
await self._validate_dubbeldagar_batch(pending, to_replace, delete_rows)
)
domain_errors.extend(await self._validate_eligible_range(pending))
domain_errors.extend(await self._validate_remaining_balance(pending, to_replace))
domain_errors.extend(
await self._validate_remaining_balance(pending, to_replace, delete_rows)
)
if domain_errors:
return PlanApplyResult(accepted=False, collisions=collisions, rejections=domain_errors)
@@ -429,6 +479,9 @@ class PlanningService:
for old, _ in to_replace:
await self._repo.delete(old.id)
for row in delete_rows:
await self._repo.delete(row.id)
now = datetime.now()
created: list[PlannedLeaveDay] = []
for d in pending:
@@ -459,6 +512,7 @@ class PlanningService:
skipped_identical_count=skipped_identical_count,
skipped_free_count=skipped_free_count,
replaced_count=len(to_replace),
deleted_count=len(delete_rows),
)
# -- sync (POST /api/plan/sync) ---------------------------------------
@@ -477,11 +531,16 @@ class PlanningService:
# place (the allocator never emits anything for an already-occupied
# key) -- "no collision ever arises" is a property of the allocator, not
# something this method has to special-case in the write path. The one
# extra step this method DOES own is deleting rows that fall out of the
# freshly-computed plan entirely (a wish's window moved away from a date
# it used to occupy, or the wish was deleted) -- `apply_proposed_days`
# only ever creates/replaces/updates keys present in its own batch, so
# nothing else would ever clean those up.
# extra thing this method computes beyond `proposal.days` is which rows
# fall out of the freshly-computed plan entirely (a wish's window moved
# away from a date it used to occupy, or the wish was deleted) --
# `apply_proposed_days` only ever creates/replaces/updates keys present
# in its own batch, so nothing else would identify those. Those keys are
# handed to `apply_proposed_days` as `delete_keys` rather than deleted
# here directly, so the capacity they free is credited back during that
# same call's up-front validation — deleting them first (or after) would
# let a sync that frees N days and re-spends N days read the freed days
# as still-spent net-new demand and reject the whole batch.
async def sync_plan(self, workspace_id: UUID, today: date | None = None) -> PlanSyncResult:
"""Propose, persist, and diff — the single call the direct-
@@ -523,26 +582,25 @@ class PlanningService:
and (d.child_id, d.parent_personal_data_uuid, d.date) not in pinned_keys
]
batch_keys = {(d.child_id, d.parent_personal_data_uuid, d.date) for d in batch}
# Rows the freshly-computed plan no longer accounts for at all:
# unpinned, wish-attributed, and absent from this run's batch — e.g.
# the wish was deleted, or its window moved elsewhere. Passed as
# `delete_keys` so `apply_proposed_days` validates the deletions
# together with the creates/replaces (see the comment above this
# method) rather than deleting them itself afterwards.
stale_keys = {
key
for key, row in before_by_key.items()
if not row.is_pinned and row.wish_id is not None and key not in batch_keys
}
apply_result = await self.apply_proposed_days(
workspace_id=workspace_id, days=batch, replace=True
workspace_id=workspace_id, days=batch, replace=True, delete_keys=stale_keys
)
changes: list[PlanChange] = []
if apply_result.accepted:
batch_keys = {(d.child_id, d.parent_personal_data_uuid, d.date) for d in batch}
# Rows the freshly-computed plan no longer accounts for at all:
# unpinned, wish-attributed, and absent from this run's batch —
# e.g. the wish was deleted, or its window moved elsewhere.
# `apply_proposed_days` never deletes a key it wasn't handed, so
# this is the one bit of write logic sync owns beyond it.
stale = [
row
for key, row in before_by_key.items()
if not row.is_pinned and row.wish_id is not None and key not in batch_keys
]
for row in stale:
await self._repo.delete(row.id)
after = await self._repo.list(workspace_id=workspace_id)
after_by_key: dict[tuple[UUID, UUID, date], PlannedLeaveDay] = {
(d.child_id, d.parent_personal_data_uuid, d.date): d for d in after
@@ -623,13 +681,17 @@ class PlanningService:
self,
pending: list[ProposedDayInput],
to_replace: list[tuple[PlannedLeaveDay, ProposedDayInput]],
delete_rows: list[PlannedLeaveDay],
) -> list[Rejection]:
"""Per-day window check (reused from AnalyticsService) + batch-wide quota.
`AnalyticsService.validate_dubbeldagar` only sees rows already
committed to the DB, so it cannot by itself catch a batch that
introduces more than `max_dubbeldagar` new dubbeldagar in one go —
that aggregate check is done here, on top of it.
that aggregate check is done here, on top of it. `delete_rows`
(rows this same call is about to delete, via `delete_keys`) free
their dubbeldagar slot just like a `to_replace` old row does, so
they're credited back the same way when projecting the total.
"""
errors: list[Rejection] = []
dubbeldag_days = [d for d in pending if d.is_dubbeldag]
@@ -650,6 +712,11 @@ class PlanningService:
replaced_out_dubbeldag_by_child[old.child_id] = (
replaced_out_dubbeldag_by_child.get(old.child_id, 0) + 1
)
for row in delete_rows:
if row.is_dubbeldag:
replaced_out_dubbeldag_by_child[row.child_id] = (
replaced_out_dubbeldag_by_child.get(row.child_id, 0) + 1
)
by_child: dict[UUID, int] = {}
for d in dubbeldag_days:
@@ -738,12 +805,17 @@ class PlanningService:
self,
pending: list[ProposedDayInput],
to_replace: list[tuple[PlannedLeaveDay, ProposedDayInput]],
delete_rows: list[PlannedLeaveDay],
) -> list[Rejection]:
"""The batch must not spend more sjukpenning/lagsta days than remain.
Per (parent, child, tier): net_new = (new days of that tier the batch
adds) - (days of that tier being replaced away, which free up a
slot). Rejects if net_new exceeds what's left.
adds) - (days of that tier being freed: replaced away, via
`to_replace`, or deleted outright via `delete_rows`/`delete_keys`).
Rejects if net_new exceeds what's left. Crediting `delete_rows` here
is what lets a `sync_plan` call that frees N days and re-spends N
days elsewhere pass validation against the balance *after* those
deletions, instead of rejecting against a stale pre-write snapshot.
"""
errors: list[Rejection] = []
pairs = {(d.parent_personal_data_uuid, d.child_id) for d in pending}
@@ -764,6 +836,12 @@ class PlanningService:
if new.parent_personal_data_uuid == parent_uuid
and new.child_id == child_id
and old.day_type == tier
) + sum(
1
for row in delete_rows
if row.parent_personal_data_uuid == parent_uuid
and row.child_id == child_id
and row.day_type == tier
)
net_new = added - removed
if net_new > left: