# ADR-0101: Double-Dose Lock and Family Sync Arbitration

The repository's architectural decision, rationale and consequences.

# ADR-0101: Double-Dose Lock and Family Sync Arbitration

## Status [#status]

Accepted (2026-12-02)

## Context [#context]

Fofo's core promise is that every family member knows whether a pet has already eaten or received medication, with zero accidental double doses — even when two caregivers tap "Gave it now" within milliseconds or while one device is offline.

## Decision [#decision]

1. **Deterministic dose window key.** Every scheduled medication administration computes a canonical `windowKey` (`YYYY-MM-DD#<slotIndex>` in the family's timezone, or a configurable minimum interval bucket for interval-based schedules).
2. **Database-enforced uniqueness with explicit exception path.** The `dose_log` table enforces a partial unique index on `(organization_id, medication_id, window_key) WHERE is_exception = false`.
   - The first caregiver transaction inserts cleanly and records `givenByUserId`, `givenByName`, and `givenAt`.
   - Any concurrent or subsequent attempt for the same `(medication_id, window_key)` with `is_exception = false` hits either the pre-check or the unique constraint, rolls back safely, and returns a structured `DoubleDoseBlocked` error carrying who gave the dose and when.
   - A caregiver can override the block only by submitting a non-empty written `exceptionReason`, which inserts with `is_exception = true` and records an audit event.
3. **Duplicate meal confirmation.** `meal_log` checks whether a meal for the same `(pet_id, meal_slot, meal_date)` already exists. Unless `confirmDuplicate: true` is passed, the API returns a structured `MealAlreadyLogged` response naming who fed the pet and when.
4. **Offline queue and sync.** Mobile stores pets, plans, and pending logs locally via the encrypted SQLite/storage queue and flushes idempotently when online. Server arbitration wins on dose-window conflicts; rejected offline duplicate doses surface a visible conflict notice rather than silently merging.
5. **Near-realtime family updates.** Caregivers receive updates within 2 seconds via lightweight cursor polling (`sync_cursor` / `realtime`) combined with TanStack Query invalidation on mutations, keeping Cloudflare Worker costs predictable while meeting the 2-second target.

## Consequences [#consequences]

- 100 concurrent dose requests against the same medication window deterministically yield 1 committed dose and 99 blocked responses.
- Works identically on PostgreSQL 16–19 with RLS enabled and without external coordination services.
