TL;DR
An AI-generated check for an account's shared monthly session limit looked at the wrong scope, still counted cancelled sessions, and let two simultaneous bookings both slip through. Accounts were booking past their limit for future months. I replaced it with one live, account-wide count under row locks, made the monthly reset survive bad records, and proved it with 18 regression tests and against production data.
What was broken
- Wrong scope: for future months, the account-wide limit was checked per client–counsellor pair, so an account could exceed its shared cap simply by spreading bookings across counsellors.
- Cancellations counted: the per-client check had no cancellation filter and no year bound on the month.
- Two code paths: the current month compared a cached counter instead of counting live, so the two paths could disagree.
- A race: two bookings arriving at the same moment could both read "under the limit" and both succeed.
The fix
- One path, one live count: every booking goes through the same check, which counts non-cancelled sessions in a half-open month window, scoped either to the client or to the whole account.
- Race closed: inside a transaction, the account row and then the client row are locked in a fixed order (avoiding deadlocks), counted, compared and saved. Simultaneous bookings now queue behind each other, and the second sees the first.
- Resilient monthly reset: previously one failure aborted the whole run; now each account and client is reset independently, a bad record is logged and skipped, and counts are recalculated from real bookings.
How I proved it
- 18 regression tests covering the original bug (an account cap across several clients in a future month), current- and future-month success and limit cases, cancellations freeing capacity, counsellor resets not leaking into future months, the limit email firing once, and the reset command surviving a bad record.
- Verified against production data, where the over-limit future-month bookings had originally shown up.
Result
The shared monthly limit is enforced account-wide, cancellations free capacity again, simultaneous bookings can't both pass, and one bad record no longer stops the monthly reset.