fix: BUG-20 clamp trips sequence after recompute + renumber migration

This commit is contained in:
Mathieu Moran
2026-08-14 21:45:26 -04:00
parent 25f57603c6
commit 01c7fdf0c4
5 changed files with 52 additions and 0 deletions
+1
View File
@@ -14,6 +14,7 @@ services:
- ./sql/migrate_phase25_5a.sql:/docker-entrypoint-initdb.d/migrate_phase25_5a.sql:ro
- ./sql/migrate_phase25_5c.sql:/docker-entrypoint-initdb.d/migrate_phase25_5c.sql:ro
- ./sql/migrate_phase26_deleted_trips.sql:/docker-entrypoint-initdb.d/migrate_phase26_deleted_trips.sql:ro
- ./sql/migrate_phase29_trip_ids.sql:/docker-entrypoint-initdb.d/migrate_phase29_trip_ids.sql:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-yarisobd}"]
interval: 10s
+7
View File
@@ -509,6 +509,13 @@ def compute_trips_for_device(device_id):
""",
{"device_id": device_id, **t},
)
# BIGSERIAL consumes a sequence value on every INSERT attempt, even when
# the ON CONFLICT (DO UPDATE) path is taken. Clamp the sequence back to the
# real max id so trip IDs don't inflate by trip_count on every recompute.
cur.execute(
"SELECT setval(pg_get_serial_sequence('trips','id'), "
"(SELECT COALESCE(MAX(id), 0) FROM trips))"
)
return len(trips)
+26
View File
@@ -0,0 +1,26 @@
-- Phase 29 (BUG-20): compact trip IDs and stop BIGSERIAL inflation.
-- trips.id has no foreign-key references (deleted_trip_markers keys on
-- (device_id, start_time)), so renumbering is purely cosmetic.
BEGIN;
-- Shift all ids up first so the compact ids (1..N) can't collide with any
-- id that still exists during the renumber.
UPDATE trips SET id = id + 1000000;
-- Renumber compactly in start_time order.
WITH renumbered AS (
SELECT id, row_number() OVER (ORDER BY start_time, id) AS new_id
FROM trips
)
UPDATE trips t
SET id = r.new_id
FROM renumbered r
WHERE t.id = r.id;
-- Reset the sequence to the real max id so the next insert gets MAX(id) + 1.
SELECT setval(
pg_get_serial_sequence('trips', 'id'),
(SELECT COALESCE(MAX(id), 0) FROM trips)
);
COMMIT;