import psycopg def claim_next(conn: psycopg.Connection) -> str | None: """Atomically claim the oldest queued job. Returns its id or None.""" with conn.cursor() as cur: cur.execute( """ SELECT id FROM "Job" WHERE state = 'requested' ORDER BY "createdAt" ASC FOR UPDATE SKIP LOCKED LIMIT 1 """ ) row = cur.fetchone() if row is None: conn.rollback() return None job_id = row[0] cur.execute( """ UPDATE "Job" SET state = 'matching', "currentStage" = 'match', "claimedAt" = now(), attempts = attempts + 1, "updatedAt" = now() WHERE id = %s """, (job_id,), ) conn.commit() return job_id