diff --git a/quota/db.py b/quota/db.py index a6b0750..0c3cdca 100644 --- a/quota/db.py +++ b/quota/db.py @@ -357,6 +357,15 @@ class VpnRoutingRule: PRIMARY KEY (device_id, date) ); +-- Idempotency receipts for usage deltas. Retained briefly so an in-process +-- retry after an uncertain SQLite commit cannot apply the same bytes twice. +CREATE TABLE IF NOT EXISTS usage_batch_receipts ( + batch_id TEXT PRIMARY KEY, + created_at REAL NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_usage_batch_receipts_created_at + ON usage_batch_receipts(created_at); + -- Daily quota: the cap of each person's day, computed once when the day starts -- (or when the plan/allowance changes) and then frozen. See quota/daily_plan.py. CREATE TABLE IF NOT EXISTS daily_caps ( @@ -530,6 +539,7 @@ def __init__(self, path: str | Path) -> None: #: set by QuotaService while free mode is on: new usage is also recorded #: in free_usage so it can be excluded from the quota maths. self.free_mode = False + self._last_usage_receipt_prune = 0.0 async def connect(self) -> None: if self._conn is not None: @@ -1493,6 +1503,71 @@ async def add_usage_batch(self, records: list[tuple[int, str, int, int]]) -> Non await self.conn.executemany(self._FREE_UPSERT, records) await self.conn.commit() + async def add_usage_batch_once( + self, batch_id: str, records: list[tuple[int, str, int, int]], *, + free_mode: bool, + ) -> None: + """Atomically apply a usage batch once, even if commit acknowledgement is lost. + + A private connection isolates this transaction from the application's + shared aiosqlite connection. Receipt retention is bounded to 30 days; + pending batches live only in process memory, so this is an in-process + retry guarantee, not crash recovery for drained kernel counters. + """ + if not records: + return + # A literal in-memory DB cannot be reopened. Use its existing connection + # in that case; file-backed production DBs use an isolated connection. + shared_memory = self.path == ":memory:" + conn = self._conn if shared_memory else await aiosqlite.connect( + self.path, timeout=30) + if conn is None: + raise RuntimeError("database is not connected") + try: + await conn.execute("PRAGMA foreign_keys=ON") + await conn.execute("BEGIN IMMEDIATE") + cur = await conn.execute( + "INSERT OR IGNORE INTO usage_batch_receipts(batch_id, created_at) VALUES (?, ?)", + (batch_id, time.time()), + ) + if cur.rowcount: + # Deleted devices retain usage only while their owner remains + # attributable. Check each row with fixed bind count so very + # wide snapshots do not hit SQLite's variable limit. + eligible = [] + for record in records: + cur = await conn.execute( + """SELECT EXISTS(SELECT 1 FROM devices WHERE id=?) + OR EXISTS(SELECT 1 FROM removed_devices r + JOIN users u ON u.id=r.user_id + WHERE r.device_id=? AND r.user_id IS NOT NULL)""", + (record[0], record[0]), + ) + if (await cur.fetchone())[0]: + eligible.append(record) + records = eligible + await conn.executemany( + """INSERT INTO usage_daily(device_id,date,up_bytes,down_bytes) + VALUES(?,?,?,?) ON CONFLICT(device_id,date) DO UPDATE SET + up_bytes=up_bytes+excluded.up_bytes, + down_bytes=down_bytes+excluded.down_bytes""", records) + if free_mode: + await conn.executemany(self._FREE_UPSERT, records) + now = time.time() + if now - self._last_usage_receipt_prune >= 86400: + await conn.execute( + "DELETE FROM usage_batch_receipts WHERE created_at < ?", + (now - 30 * 86400,), + ) + self._last_usage_receipt_prune = now + await conn.commit() + except BaseException: + await conn.rollback() + raise + finally: + if not shared_memory: + await conn.close() + async def add_lan_usage_batch(self, records: list[tuple[int, str, int, int]]) -> None: """Add LOCAL (LAN) byte deltas per (device, day). Monitoring only.""" if not records: diff --git a/run.py b/run.py index 261444a..719eaf8 100644 --- a/run.py +++ b/run.py @@ -39,6 +39,7 @@ import socket import subprocess import time +import uuid from ipaddress import ip_address from pathlib import Path from typing import Any, Callable, Optional @@ -459,6 +460,9 @@ def __init__(self, cfg: cfg_mod.Config, self._empty_sweeps = 0 #: monotonic time of the previous counter flush (live-speed window). self._last_flush_mono: float | None = None + #: Kernel counters are drained before SQLite commits. Keep one failed + #: batch (including its capture day and free-mode state) for retry. + self._pending_usage_batch: tuple[str, list[tuple[int, str, int, int]], bool] | None = None #: set when _persist_lease creates a new device — _sync_dnsmasq_leases #: resets _last_latency_sweep so the ARP probe runs in the same tick, #: turning the new device's LED blue immediately instead of waiting up @@ -1577,6 +1581,11 @@ async def _maintenance_tick(self) -> None: live_lan_by_ip: dict[str, object] = {} flush_interval = 15.0 if self.engine is not None: + if self._pending_usage_batch is not None: + batch_id, batch_records, batch_free_mode = self._pending_usage_batch + await self.database.add_usage_batch_once( + batch_id, batch_records, free_mode=batch_free_mode) + self._pending_usage_batch = None snap = await asyncio.to_thread(self.engine.flush) _mono = time.monotonic() if self._last_flush_mono is not None: @@ -1616,7 +1625,12 @@ async def _maintenance_tick(self) -> None: usage_records.append((box.id, today, snap.gateway.up, snap.gateway.down)) if usage_records: - await self.database.add_usage_batch(usage_records) + pending = (uuid.uuid4().hex, usage_records, + bool(self.database.free_mode)) + self._pending_usage_batch = pending + await self.database.add_usage_batch_once( + pending[0], pending[1], free_mode=pending[2]) + self._pending_usage_batch = None # LOCAL (LAN) traffic: stored apart from the metered usage, never # part of quota math - purely for the dashboard's LAN monitor. diff --git a/tests/test_run_wiring.py b/tests/test_run_wiring.py index 55a6355..2074cb2 100644 --- a/tests/test_run_wiring.py +++ b/tests/test_run_wiring.py @@ -987,6 +987,59 @@ def test_flush_counts_usage(tmp_path): _get_loop().run_until_complete(gw.shutdown()) +@pytest.mark.parametrize("commit_then_raise", [False, True]) +def test_failed_usage_batch_retries_same_delta_once(tmp_path, monkeypatch, + commit_then_raise): + """A failed or ambiguously acknowledged batch is retried before later deltas.""" + cfg = _cfg(tmp_path) + gw = Gateway(cfg) + _get_loop().run_until_complete(gw.startup()) + _cancel_maintenance(gw) + try: + mac = "aa:bb:cc:dd:ee:fa" + ip = "192.168.1.199" + _get_loop().run_until_complete(gw._persist_lease(mac, ip)) + dev = _get_loop().run_until_complete(gw.database.get_device(mac=mac)) + + class _FakeEngine: + deltas = [1000, 300] + def flush(self): + amount = self.deltas.pop(0) if self.deltas else 0 + return EngineSnapshot(by_ip={ip: EngineCounters(up=amount)}, + ip_to_mac={ip: mac}, blocked={}) + def update_state(self, ip_to_mac, blocked): pass + def set_gateway_blocked(self, blocked): pass + def stop(self): pass + gw.engine = _FakeEngine() # type: ignore[assignment] + + original = gw.database.add_usage_batch_once + calls = [] + async def fail_once(batch_id, records, *, free_mode): + calls.append((batch_id, records, free_mode)) + if len(calls) == 1 and not commit_then_raise: + raise OSError("pre-commit failure") + await original(batch_id, records, free_mode=free_mode) + if len(calls) == 1: + raise OSError("commit acknowledgement lost") + monkeypatch.setattr(gw.database, "add_usage_batch_once", fail_once) + + with pytest.raises(OSError): + _get_loop().run_until_complete(gw._maintenance_tick()) + assert gw._pending_usage_batch is not None + first_id = gw._pending_usage_batch[0] + # The next tick first retries the saved 1000 bytes, then flushes the + # new 300-byte delta, preserving the original batch date and identity. + _get_loop().run_until_complete(gw._maintenance_tick()) + usage = _get_loop().run_until_complete(gw.database.get_usage(dev.id)) + assert usage["up_bytes"] == 1300 + assert calls[0][0] == first_id and calls[1][0] == first_id + assert calls[0][1] == calls[1][1] + assert calls[0][1][0][1] == time.strftime("%Y-%m-%d") + assert gw._pending_usage_batch is None + finally: + _get_loop().run_until_complete(gw.shutdown()) + + def test_make_engine_selects_nftables_backend(tmp_path): """The Linux gateway always uses NftablesEngine, whatever the config says.""" from run import _make_engine diff --git a/tests/test_usage_batch_retry.py b/tests/test_usage_batch_retry.py new file mode 100644 index 0000000..b5dc7c1 --- /dev/null +++ b/tests/test_usage_batch_retry.py @@ -0,0 +1,70 @@ +import asyncio +import time + +from quota.db import Database + + +def test_usage_batch_receipt_makes_ambiguous_retry_idempotent(tmp_path): + db = Database(tmp_path / "usage.db") + async def run(): + await db.connect() + device = await db.upsert_device("aa:bb:cc:dd:ee:fa", "retry") + await db.add_usage_batch_once("stable-batch", [(device.id, "2026-11-23", 1000, 0)], free_mode=True) + # Models a commit whose acknowledgement was lost: caller retries same ID. + await db.add_usage_batch_once("stable-batch", [(device.id, "2026-11-23", 1000, 0)], free_mode=False) + usage = await db.get_usage(device.id) + cur = await db.conn.execute("SELECT up_bytes FROM free_usage WHERE device_id=?", (device.id,)) + free = await cur.fetchone() + assert usage["up_bytes"] == 1000 + assert free["up_bytes"] == 1000 + await db.close() + asyncio.run(run()) + + +def test_usage_batch_retry_supports_in_memory_database(): + db = Database(":memory:") + async def run(): + await db.connect() + device = await db.upsert_device("aa:bb:cc:dd:ee:fd", "memory") + await db.add_usage_batch_once("memory-batch", [(device.id, "2026-11-23", 7, 0)], free_mode=False) + assert (await db.get_usage(device.id))["up_bytes"] == 7 + await db.close() + asyncio.run(run()) + + +def test_usage_batch_keeps_deleted_device_usage_for_existing_owner(tmp_path): + db = Database(tmp_path / "usage-deleted.db") + async def run(): + await db.connect() + removed = await db.upsert_device("aa:bb:cc:dd:ee:fb", "removed") + live = await db.upsert_device("aa:bb:cc:dd:ee:fc", "live") + await db.delete_device(removed.id) + rows = [(removed.id, time.strftime("%Y-%m-%d"), 700, 0), + (live.id, time.strftime("%Y-%m-%d"), 300, 0)] + await db.add_usage_batch_once("mixed-batch", rows, free_mode=False) + await db.add_usage_batch_once("mixed-batch", rows, free_mode=False) + assert (await db.get_usage(removed.id))["up_bytes"] == 700 + assert (await db.get_usage(live.id))["up_bytes"] == 300 + by_user = await db.get_period_usage_by_user() + assert by_user[removed.user_id]["up"] == 700 + cur = await db.conn.execute("SELECT up_bytes FROM free_usage WHERE device_id=?", (live.id,)) + assert await cur.fetchone() is None + await db.close() + asyncio.run(run()) + + +def test_usage_batch_skips_unknown_and_purged_device_ids(tmp_path): + db = Database(tmp_path / "usage-purged.db") + async def run(): + await db.connect() + user = await db.create_user("erased") + device = await db.upsert_device("aa:bb:cc:dd:ee:fe", "erased", user_id=user.id) + await db.delete_device(device.id) + await db.delete_user(user.id) + rows = [(device.id, time.strftime("%Y-%m-%d"), 700, 0), + (999999, time.strftime("%Y-%m-%d"), 900, 0)] + await db.add_usage_batch_once("purged-batch", rows, free_mode=True) + assert (await db.get_usage(device.id))["up_bytes"] == 0 + assert await db.get_period_usage_by_user() == {} + await db.close() + asyncio.run(run())