Naufal Arhab commited on
Commit
21f6df4
·
1 Parent(s): 4316915

fix(db): prevent DDL deadlock on concurrent serverless cold starts with advisory lock and schema check

Browse files
Files changed (2) hide show
  1. backend/database/db.py +66 -40
  2. backend/main.py +13 -8
backend/database/db.py CHANGED
@@ -79,46 +79,72 @@ def _format_row(row: dict | None) -> dict | None:
79
 
80
 
81
  def init_db() -> None:
82
- """Create all tables in Neon PostgreSQL if they do not exist yet, and run schema migrations."""
83
- with get_connection() as conn:
84
- with conn.cursor() as cur:
85
- for ddl in ALL_TABLES:
86
- cur.execute(ddl)
87
- try:
88
- cur.execute("""
89
- ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_okx BOOLEAN DEFAULT FALSE;
90
- ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_hyperliquid BOOLEAN DEFAULT FALSE;
91
- ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_count INTEGER DEFAULT 0;
92
- ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_direction TEXT DEFAULT 'NEUTRAL';
93
- ALTER TABLE pairs ADD COLUMN IF NOT EXISTS last_conviction INTEGER DEFAULT 0;
94
- """)
95
- except Exception as e:
96
- logger.warning("Postgres schema add column note: %s", e)
97
- try:
98
- cur.execute("""
99
- DO $$
100
- BEGIN
101
- IF EXISTS (
102
- SELECT 1 FROM information_schema.columns
103
- WHERE table_name = 'pairs' AND column_name = 'is_active' AND data_type = 'integer'
104
- ) THEN
105
- ALTER TABLE pairs ALTER COLUMN on_binance DROP DEFAULT;
106
- ALTER TABLE pairs ALTER COLUMN on_bybit DROP DEFAULT;
107
- ALTER TABLE pairs ALTER COLUMN is_active DROP DEFAULT;
108
-
109
- ALTER TABLE pairs ALTER COLUMN on_binance TYPE BOOLEAN USING (on_binance != 0);
110
- ALTER TABLE pairs ALTER COLUMN on_bybit TYPE BOOLEAN USING (on_bybit != 0);
111
- ALTER TABLE pairs ALTER COLUMN is_active TYPE BOOLEAN USING (is_active != 0);
112
-
113
- ALTER TABLE pairs ALTER COLUMN on_binance SET DEFAULT FALSE;
114
- ALTER TABLE pairs ALTER COLUMN on_bybit SET DEFAULT FALSE;
115
- ALTER TABLE pairs ALTER COLUMN is_active SET DEFAULT TRUE;
116
- END IF;
117
- END $$;
118
- """)
119
- except Exception as e:
120
- logger.warning("Postgres schema migration note: %s", e)
121
- logger.info("Neon PostgreSQL database initialized successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
 
124
  # ---------------------------------------------------------------------------
 
79
 
80
 
81
  def init_db() -> None:
82
+ """Create all tables in Neon PostgreSQL if they do not exist yet, and run schema migrations.
83
+ Protected by PostgreSQL advisory lock and schema existence check to prevent concurrent DDL deadlocks.
84
+ """
85
+ try:
86
+ with get_connection() as conn:
87
+ with conn.cursor() as cur:
88
+ # 1. Quick check: if 'pairs' table already exists, schema is already initialized.
89
+ cur.execute("SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'pairs';")
90
+ if cur.fetchone():
91
+ logger.debug("Database schema already exists. Skipping DDL creation.")
92
+ return
93
+
94
+ # 2. Schema does not exist: acquire advisory lock so only 1 worker creates tables
95
+ cur.execute("SELECT pg_try_advisory_lock(72817001);")
96
+ got_lock = (cur.fetchone() or [False])[0]
97
+ if not got_lock:
98
+ logger.info("Another worker is currently initializing the database. Skipping.")
99
+ return
100
+
101
+ try:
102
+ cur.execute("SET lock_timeout = '5s';")
103
+ for ddl in ALL_TABLES:
104
+ cur.execute(ddl)
105
+ try:
106
+ cur.execute("""
107
+ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_okx BOOLEAN DEFAULT FALSE;
108
+ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS on_hyperliquid BOOLEAN DEFAULT FALSE;
109
+ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_count INTEGER DEFAULT 0;
110
+ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS streak_direction TEXT DEFAULT 'NEUTRAL';
111
+ ALTER TABLE pairs ADD COLUMN IF NOT EXISTS last_conviction INTEGER DEFAULT 0;
112
+ """)
113
+ except Exception as e:
114
+ logger.warning("Postgres schema add column note: %s", e)
115
+ try:
116
+ cur.execute("""
117
+ DO $$
118
+ BEGIN
119
+ IF EXISTS (
120
+ SELECT 1 FROM information_schema.columns
121
+ WHERE table_name = 'pairs' AND column_name = 'is_active' AND data_type = 'integer'
122
+ ) THEN
123
+ ALTER TABLE pairs ALTER COLUMN on_binance DROP DEFAULT;
124
+ ALTER TABLE pairs ALTER COLUMN on_bybit DROP DEFAULT;
125
+ ALTER TABLE pairs ALTER COLUMN is_active DROP DEFAULT;
126
+
127
+ ALTER TABLE pairs ALTER COLUMN on_binance TYPE BOOLEAN USING (on_binance != 0);
128
+ ALTER TABLE pairs ALTER COLUMN on_bybit TYPE BOOLEAN USING (on_bybit != 0);
129
+ ALTER TABLE pairs ALTER COLUMN is_active TYPE BOOLEAN USING (is_active != 0);
130
+
131
+ ALTER TABLE pairs ALTER COLUMN on_binance SET DEFAULT FALSE;
132
+ ALTER TABLE pairs ALTER COLUMN on_bybit SET DEFAULT FALSE;
133
+ ALTER TABLE pairs ALTER COLUMN is_active SET DEFAULT TRUE;
134
+ END IF;
135
+ END $$;
136
+ """)
137
+ except Exception as e:
138
+ logger.warning("Postgres schema migration note: %s", e)
139
+ logger.info("Neon PostgreSQL database initialized successfully.")
140
+ finally:
141
+ try:
142
+ cur.execute("SELECT pg_advisory_unlock(72817001);")
143
+ except Exception:
144
+ pass
145
+ except Exception as exc:
146
+ # Non-fatal: never crash serverless cold starts due to DDL race condition
147
+ logger.warning("init_db non-fatal notice (schema already created or lock skipped): %s", exc)
148
 
149
 
150
  # ---------------------------------------------------------------------------
backend/main.py CHANGED
@@ -271,16 +271,22 @@ async def lifespan(app: FastAPI):
271
  # ── Startup ──────────────────────────────────────────────────────────
272
  logger.info("Starting up Perps Signal Backend...")
273
 
274
- # Init DB
275
- init_db()
276
- safe_host = config.DATABASE_URL.split("@")[-1] if "@" in config.DATABASE_URL else config.DATABASE_URL
277
- logger.info("Neon PostgreSQL database initialised at: %s", safe_host)
278
 
279
- # Initial DB retention cleanup on boot
280
  try:
281
- await async_prune_old_records()
 
 
282
  except Exception as exc:
283
- logger.warning("Initial DB pruning failed: %s", exc)
 
 
 
 
 
 
 
284
 
285
  # Exchange clients
286
  binance = BinanceClient()
@@ -296,7 +302,6 @@ async def lifespan(app: FastAPI):
296
  app.state.collector = collector
297
 
298
  # Background signal loop & eager bulk warmup (only in persistent server mode, not in ephemeral serverless lambdas)
299
- is_serverless = bool(os.getenv("VERCEL") or os.getenv("AWS_LAMBDA_FUNCTION_NAME"))
300
  task = None
301
 
302
  def _task_error_callback(t: asyncio.Task) -> None:
 
271
  # ── Startup ──────────────────────────────────────────────────────────
272
  logger.info("Starting up Perps Signal Backend...")
273
 
274
+ is_serverless = bool(os.getenv("VERCEL") or os.getenv("AWS_LAMBDA_FUNCTION_NAME"))
 
 
 
275
 
276
+ # Init DB (safe, non-blocking, deadlock-protected)
277
  try:
278
+ init_db()
279
+ safe_host = config.DATABASE_URL.split("@")[-1] if "@" in config.DATABASE_URL else config.DATABASE_URL
280
+ logger.info("Neon PostgreSQL database initialised at: %s", safe_host)
281
  except Exception as exc:
282
+ logger.warning("DB init bypassed during startup: %s", exc)
283
+
284
+ # Initial DB retention cleanup on boot (persistent server mode only, avoided during serverless cold starts)
285
+ if not is_serverless:
286
+ try:
287
+ await async_prune_old_records()
288
+ except Exception as exc:
289
+ logger.warning("Initial DB pruning failed: %s", exc)
290
 
291
  # Exchange clients
292
  binance = BinanceClient()
 
302
  app.state.collector = collector
303
 
304
  # Background signal loop & eager bulk warmup (only in persistent server mode, not in ephemeral serverless lambdas)
 
305
  task = None
306
 
307
  def _task_error_callback(t: asyncio.Task) -> None: