-- Migration 002: add per-inbox delivery sequence numbers. -- -- Adds a `seq` column to the deliveries table and a separate counter table -- that tracks the next sequence number per (recipient_key, channel_id) inbox. -- The counter is atomically incremented on each enqueue via an UPSERT so -- sequence numbers are gapless even under concurrent inserts. -- -- Requires SQLite >= 3.35 (RETURNING clause support; available on Ubuntu 22.04+). ALTER TABLE deliveries ADD COLUMN seq INTEGER NOT NULL DEFAULT 0; CREATE TABLE IF NOT EXISTS delivery_seq_counters ( recipient_key BLOB NOT NULL, channel_id BLOB NOT NULL, next_seq INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (recipient_key, channel_id) ); -- Index lets ORDER BY seq queries use an index scan instead of a sort. CREATE INDEX IF NOT EXISTS idx_del_seq ON deliveries (recipient_key, channel_id, seq);