jtlevine Claude Opus 4.6 (1M context) commited on
Commit
d224e47
·
1 Parent(s): f02f32b

Harden serverless DB checks, CORS, cursor lifecycle, and healing JSON parse

Browse files

Replace the process.env.DATABASE_URL! bang assertion across every
Vercel serverless function with an explicit check that returns 500,
removing a silent crash path. Make src/api.py CORS origins configurable
via ALLOWED_ORIGINS. Fix a cursor leak in PgConnection by closing the
previously-returned cursor before opening the next one, and add a
bulk insert_daily_readings_batch() helper using executemany. Catch
JSONDecodeError on Claude healing responses and return an empty
assessment list rather than crashing mid-heal. Update CLAUDE.md to
the new extreme-heat-insurance.jeff-levine.com custom domain.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

CLAUDE.md CHANGED
@@ -6,7 +6,7 @@ Parametric heat insurance for outdoor workers in Dar es Salaam. Chronos-Bolt fou
6
 
7
  **3-tier deployment:**
8
  - **HF Spaces** (`jtlevine/climate-risk-engine`): Runs pipeline weekly (writes to Neon), then sleeps. Docker, FastAPI, port 7860.
9
- - **Vercel** (`climate-risk-engine.vercel.app`): Frontend + serverless API functions reading from Neon. Always on. Serverless functions in `frontend/api/*.ts` using `@neondatabase/serverless`.
10
  - **Neon** (`withered-salad-81435132`): PostgreSQL in `aws-us-west-2`. Sync psycopg2 with SimpleConnectionPool.
11
 
12
  **Data flow:**
 
6
 
7
  **3-tier deployment:**
8
  - **HF Spaces** (`jtlevine/climate-risk-engine`): Runs pipeline weekly (writes to Neon), then sleeps. Docker, FastAPI, port 7860.
9
+ - **Vercel** (`https://extreme-heat-insurance.jeff-levine.com`): Frontend + serverless API functions reading from Neon. Always on. Serverless functions in `frontend/api/*.ts` using `@neondatabase/serverless`.
10
  - **Neon** (`withered-salad-81435132`): PostgreSQL in `aws-us-west-2`. Sync psycopg2 with SimpleConnectionPool.
11
 
12
  **Data flow:**
config.py CHANGED
@@ -190,6 +190,9 @@ ZONES: list[UrbanZone] = [
190
  [1, 2, 8, 9], "Dense residential. Hillside construction workers, market sellers."),
191
  ]
192
 
 
 
 
193
  ZONE_MAP: dict[str, UrbanZone] = {z.zone_id: z for z in ZONES}
194
 
195
  # Cities for grouping
 
190
  [1, 2, 8, 9], "Dense residential. Hillside construction workers, market sellers."),
191
  ]
192
 
193
+ # Built once at import time from ZONES. If ZONES is ever mutated at runtime
194
+ # (e.g. hot-reloaded from a new fork config), this map must be rebuilt —
195
+ # nothing watches ZONES for changes.
196
  ZONE_MAP: dict[str, UrbanZone] = {z.zone_id: z for z in ZONES}
197
 
198
  # Cities for grouping
frontend/api/basis-risk.ts CHANGED
@@ -2,7 +2,10 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
6
 
7
  const reports = await sql`
8
  SELECT br.zone_id, z.name AS zone_name, z.city, z.settlement_type,
 
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
+ if (!process.env.DATABASE_URL) {
6
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
7
+ }
8
+ const sql = neon(process.env.DATABASE_URL)
9
 
10
  const reports = await sql`
11
  SELECT br.zone_id, z.name AS zone_name, z.city, z.settlement_type,
frontend/api/coverage-recommendation.ts CHANGED
@@ -49,7 +49,10 @@ function getEnrollment(zone_id: string, gender: Gender, settlement_type: string,
49
  }
50
 
51
  export default async function handler(req: VercelRequest, res: VercelResponse) {
52
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
53
  const gender = (req.query.gender as Gender) || 'all'
54
  const settlement = (req.query.settlement as Settlement) || 'all'
55
 
 
49
  }
50
 
51
  export default async function handler(req: VercelRequest, res: VercelResponse) {
52
+ if (!process.env.DATABASE_URL) {
53
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
54
+ }
55
+ const sql = neon(process.env.DATABASE_URL)
56
  const gender = (req.query.gender as Gender) || 'all'
57
  const settlement = (req.query.settlement as Settlement) || 'all'
58
 
frontend/api/disbursements.ts CHANGED
@@ -14,7 +14,10 @@ const ZONE_WORKERS: Record<string, number> = {
14
  }
15
 
16
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
17
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
18
 
19
  // Get current conditions + neural pricing for all Dar zones
20
  const zones = await sql`
 
14
  }
15
 
16
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
17
+ if (!process.env.DATABASE_URL) {
18
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
19
+ }
20
+ const sql = neon(process.env.DATABASE_URL)
21
 
22
  // Get current conditions + neural pricing for all Dar zones
23
  const zones = await sql`
frontend/api/enrolled-workers.ts CHANGED
@@ -2,7 +2,10 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
6
 
7
  const zones = await sql`
8
  SELECT zone_id, worker_population_est,
 
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
+ if (!process.env.DATABASE_URL) {
6
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
7
+ }
8
+ const sql = neon(process.env.DATABASE_URL)
9
 
10
  const zones = await sql`
11
  SELECT zone_id, worker_population_est,
frontend/api/indices.ts CHANGED
@@ -2,7 +2,10 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
6
 
7
  // Get zones with their latest heat index + 90-day history
8
  const zones = await sql`SELECT DISTINCT zone_id FROM heat_indices ORDER BY zone_id`
 
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
+ if (!process.env.DATABASE_URL) {
6
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
7
+ }
8
+ const sql = neon(process.env.DATABASE_URL)
9
 
10
  // Get zones with their latest heat index + 90-day history
11
  const zones = await sql`SELECT DISTINCT zone_id FROM heat_indices ORDER BY zone_id`
frontend/api/notifications.ts CHANGED
@@ -2,7 +2,10 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
6
 
7
  const notifications = await sql`
8
  SELECT n.id, n.zone_id, z.name AS zone_name, z.city,
 
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
+ if (!process.env.DATABASE_URL) {
6
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
7
+ }
8
+ const sql = neon(process.env.DATABASE_URL)
9
 
10
  const notifications = await sql`
11
  SELECT n.id, n.zone_id, z.name AS zone_name, z.city,
frontend/api/pipeline/runs.ts CHANGED
@@ -2,7 +2,10 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
6
 
7
  const runs = await sql`
8
  SELECT run_id, started_at, finished_at, status,
 
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
+ if (!process.env.DATABASE_URL) {
6
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
7
+ }
8
+ const sql = neon(process.env.DATABASE_URL)
9
 
10
  const runs = await sql`
11
  SELECT run_id, started_at, finished_at, status,
frontend/api/pipeline/stats.ts CHANGED
@@ -2,7 +2,10 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
6
 
7
  const [stats] = await sql`
8
  SELECT
 
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
+ if (!process.env.DATABASE_URL) {
6
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
7
+ }
8
+ const sql = neon(process.env.DATABASE_URL)
9
 
10
  const [stats] = await sql`
11
  SELECT
frontend/api/triggers.ts CHANGED
@@ -2,7 +2,10 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
6
 
7
  const triggers = await sql`
8
  SELECT te.zone_id, z.name AS zone_name, z.city, te.trigger_level,
 
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
+ if (!process.env.DATABASE_URL) {
6
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
7
+ }
8
+ const sql = neon(process.env.DATABASE_URL)
9
 
10
  const triggers = await sql`
11
  SELECT te.zone_id, z.name AS zone_name, z.city, te.trigger_level,
frontend/api/zones.ts CHANGED
@@ -2,7 +2,10 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
- const sql = neon(process.env.DATABASE_URL!)
 
 
 
6
 
7
  const zones = await sql`
8
  SELECT z.zone_id, z.name, z.city, z.country, z.latitude, z.longitude,
 
2
  import { neon } from '@neondatabase/serverless'
3
 
4
  export default async function handler(_req: VercelRequest, res: VercelResponse) {
5
+ if (!process.env.DATABASE_URL) {
6
+ return res.status(500).json({ error: 'DATABASE_URL not set' })
7
+ }
8
+ const sql = neon(process.env.DATABASE_URL)
9
 
10
  const zones = await sql`
11
  SELECT z.zone_id, z.name, z.city, z.country, z.latitude, z.longitude,
src/api.py CHANGED
@@ -76,9 +76,17 @@ async def lifespan(app: FastAPI):
76
 
77
  app = FastAPI(title="Extreme Heat Risk Engine", version="1.0.0", lifespan=lifespan)
78
 
 
 
 
 
 
 
 
 
79
  app.add_middleware(
80
  CORSMiddleware,
81
- allow_origins=["*"],
82
  allow_credentials=True,
83
  allow_methods=["*"],
84
  allow_headers=["*"],
 
76
 
77
  app = FastAPI(title="Extreme Heat Risk Engine", version="1.0.0", lifespan=lifespan)
78
 
79
+ # CORS origins configurable via ALLOWED_ORIGINS (comma-separated).
80
+ # Defaults to "*" so local dev and HF Spaces preview stay permissive.
81
+ _allowed_origins_env = os.environ.get("ALLOWED_ORIGINS", "*").strip()
82
+ if _allowed_origins_env == "*" or not _allowed_origins_env:
83
+ _allowed_origins = ["*"]
84
+ else:
85
+ _allowed_origins = [o.strip() for o in _allowed_origins_env.split(",") if o.strip()]
86
+
87
  app.add_middleware(
88
  CORSMiddleware,
89
+ allow_origins=_allowed_origins,
90
  allow_credentials=True,
91
  allow_methods=["*"],
92
  allow_headers=["*"],
src/database/crud.py CHANGED
@@ -75,6 +75,7 @@ class PgConnection:
75
  self._conn = pool.getconn()
76
  self._conn.autocommit = True
77
  self._pool = pool
 
78
  self._refresh_conn()
79
 
80
  def _refresh_conn(self):
@@ -93,13 +94,33 @@ class PgConnection:
93
  self._conn.autocommit = True
94
 
95
  def execute(self, sql: str, params=None):
96
- """Execute SQL with %s placeholders. Returns cursor."""
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  cur = self._conn.cursor()
98
  cur.execute(sql, params)
 
99
  return cur
100
 
101
  def close(self):
102
  """Return connection to pool."""
 
 
 
 
 
 
103
  if self._pool and self._conn:
104
  self._pool.putconn(self._conn)
105
  self._conn = None
@@ -283,6 +304,44 @@ def insert_daily_reading(conn, reading: dict) -> Optional[int]:
283
  return row[0] if row else None
284
 
285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  def get_daily_readings(conn, zone_id: str, limit: int = 90) -> list[dict]:
287
  """Fetch recent daily readings for a zone."""
288
  cur = conn.execute(
 
75
  self._conn = pool.getconn()
76
  self._conn.autocommit = True
77
  self._pool = pool
78
+ self._last_cur = None
79
  self._refresh_conn()
80
 
81
  def _refresh_conn(self):
 
94
  self._conn.autocommit = True
95
 
96
  def execute(self, sql: str, params=None):
97
+ """Execute SQL with %s placeholders. Returns cursor.
98
+
99
+ To avoid leaking server-side cursor resources over long-lived
100
+ connections (e.g. during a pipeline run with hundreds of inserts),
101
+ we close the previously-returned cursor before creating a new one.
102
+ Callers that need to keep two cursors open simultaneously must use
103
+ ``self._conn.cursor()`` directly.
104
+ """
105
+ if self._last_cur is not None:
106
+ try:
107
+ self._last_cur.close()
108
+ except Exception:
109
+ pass
110
+ self._last_cur = None
111
  cur = self._conn.cursor()
112
  cur.execute(sql, params)
113
+ self._last_cur = cur
114
  return cur
115
 
116
  def close(self):
117
  """Return connection to pool."""
118
+ if self._last_cur is not None:
119
+ try:
120
+ self._last_cur.close()
121
+ except Exception:
122
+ pass
123
+ self._last_cur = None
124
  if self._pool and self._conn:
125
  self._pool.putconn(self._conn)
126
  self._conn = None
 
304
  return row[0] if row else None
305
 
306
 
307
+ def insert_daily_readings_batch(conn, readings: list[dict]) -> int:
308
+ """Bulk-insert daily readings with a single round-trip per chunk.
309
+
310
+ Uses psycopg2's executemany (single statement, many rows). Much faster
311
+ than insert_daily_reading() in a loop during pipeline runs. Does not
312
+ return row IDs — use insert_daily_reading() if you need the ID.
313
+ """
314
+ if not readings:
315
+ return 0
316
+ rows = [
317
+ (r["zone_id"], _to_date(r["date"]),
318
+ r.get("temp_mean_c"), r.get("temp_max_c"),
319
+ r.get("temp_min_c"), r.get("humidity_pct"),
320
+ r.get("wind_speed_ms"), r.get("solar_rad_wm2"),
321
+ r.get("precip_mm"),
322
+ r.get("source", "unknown"),
323
+ r.get("data_quality", 0.0))
324
+ for r in readings
325
+ ]
326
+ cur = conn._conn.cursor()
327
+ try:
328
+ cur.executemany(
329
+ """
330
+ INSERT INTO daily_readings (zone_id, date, temp_mean_c, temp_max_c,
331
+ temp_min_c, humidity_pct, wind_speed_ms, solar_rad_wm2,
332
+ precip_mm, source, data_quality)
333
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
334
+ ON CONFLICT (zone_id, date) DO UPDATE SET
335
+ temp_max_c = EXCLUDED.temp_max_c,
336
+ data_quality = EXCLUDED.data_quality
337
+ """,
338
+ rows,
339
+ )
340
+ return len(rows)
341
+ finally:
342
+ cur.close()
343
+
344
+
345
  def get_daily_readings(conn, zone_id: str, limit: int = 90) -> list[dict]:
346
  """Fetch recent daily readings for a zone."""
347
  cur = conn.execute(
src/healing/healer.py CHANGED
@@ -526,14 +526,27 @@ class HealingAgent:
526
  return SYSTEM_PROMPT_TEMPLATE.format(n_zones=n_zones)
527
 
528
  def _parse_assessments(self, text: str) -> list[dict[str, Any]]:
529
- """Extract JSON assessment array from Claude's response."""
 
 
 
 
 
 
530
  match = re.search(r'```json\s*([\s\S]*?)```', text)
531
  if match:
532
- return json.loads(match.group(1))
 
 
 
533
 
534
  match = re.search(r'\[[\s\S]*\]', text)
535
  if match:
536
- return json.loads(match.group(0))
 
 
 
 
537
 
538
  raise ValueError("Could not find JSON assessment array in response")
539
 
 
526
  return SYSTEM_PROMPT_TEMPLATE.format(n_zones=n_zones)
527
 
528
  def _parse_assessments(self, text: str) -> list[dict[str, Any]]:
529
+ """Extract JSON assessment array from Claude's response.
530
+
531
+ Claude occasionally returns malformed JSON (trailing commas, partial
532
+ fences, truncated output). We catch JSONDecodeError on both regex
533
+ groups and fall back to an empty assessment list so the pipeline
534
+ continues rather than crashing mid-heal.
535
+ """
536
  match = re.search(r'```json\s*([\s\S]*?)```', text)
537
  if match:
538
+ try:
539
+ return json.loads(match.group(1))
540
+ except json.JSONDecodeError as exc:
541
+ log.warning("Failed to parse fenced JSON assessments: %s", exc)
542
 
543
  match = re.search(r'\[[\s\S]*\]', text)
544
  if match:
545
+ try:
546
+ return json.loads(match.group(0))
547
+ except json.JSONDecodeError as exc:
548
+ log.warning("Failed to parse bracketed JSON assessments: %s", exc)
549
+ return []
550
 
551
  raise ValueError("Could not find JSON assessment array in response")
552
 
src/pipeline.py CHANGED
@@ -34,6 +34,7 @@ from src.notification.sender import create_sender
34
  # Database CRUD (imported lazily to keep pipeline usable without DB)
35
  from src.database.crud import (
36
  insert_daily_reading,
 
37
  insert_healed_reading,
38
  insert_healing_log,
39
  insert_heat_index,
@@ -254,22 +255,28 @@ class HeatRiskPipeline:
254
  ok_count = sum(1 for r in results if r.completeness > 0.5)
255
  total_readings = sum(len(r.readings) for r in results)
256
 
257
- # DB: write daily readings
258
- for r in results:
259
- for reading in r.readings:
260
- self._db_write(insert_daily_reading, self.db, {
261
- "zone_id": reading.zone_id,
262
- "date": reading.date,
263
- "temp_mean_c": reading.temp_mean_c,
264
- "temp_max_c": reading.temp_max_c,
265
- "temp_min_c": reading.temp_min_c,
266
- "humidity_pct": reading.humidity_pct,
267
- "wind_speed_ms": reading.wind_speed_ms,
268
- "solar_rad_wm2": None,
269
- "precip_mm": reading.precip_mm,
270
- "source": reading.source,
271
- "data_quality": reading.data_quality,
272
- })
 
 
 
 
 
 
273
 
274
  status = "ok" if ok_count == len(DAR_ZONES) else "partial" if ok_count > 0 else "failed"
275
  return StepResult(
 
34
  # Database CRUD (imported lazily to keep pipeline usable without DB)
35
  from src.database.crud import (
36
  insert_daily_reading,
37
+ insert_daily_readings_batch,
38
  insert_healed_reading,
39
  insert_healing_log,
40
  insert_heat_index,
 
255
  ok_count = sum(1 for r in results if r.completeness > 0.5)
256
  total_readings = sum(len(r.readings) for r in results)
257
 
258
+ # DB: write daily readings (batched — single executemany instead
259
+ # of one cursor per row, which matters when DAR_ZONES * days_back
260
+ # can easily run into the hundreds of inserts).
261
+ readings_payload = [
262
+ {
263
+ "zone_id": reading.zone_id,
264
+ "date": reading.date,
265
+ "temp_mean_c": reading.temp_mean_c,
266
+ "temp_max_c": reading.temp_max_c,
267
+ "temp_min_c": reading.temp_min_c,
268
+ "humidity_pct": reading.humidity_pct,
269
+ "wind_speed_ms": reading.wind_speed_ms,
270
+ "solar_rad_wm2": None,
271
+ "precip_mm": reading.precip_mm,
272
+ "source": reading.source,
273
+ "data_quality": reading.data_quality,
274
+ }
275
+ for r in results
276
+ for reading in r.readings
277
+ ]
278
+ if readings_payload:
279
+ self._db_write(insert_daily_readings_batch, self.db, readings_payload)
280
 
281
  status = "ok" if ok_count == len(DAR_ZONES) else "partial" if ok_count > 0 else "failed"
282
  return StepResult(