{"record":{"id":"5551befe9b2e8e5a","repo":"BerriAI/litellm","slug":"error-retrieving-usage-data-e","errorCode":null,"errorMessage":"Error retrieving usage data: {e}","messagePattern":"Error retrieving usage data: (.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"litellm/integrations/cloudzero/database.py","lineNumber":101,"sourceCode":"        params: Final[list[Any]] = [\n            start_time_utc,\n            end_time_utc,\n        ]\n\n        if limit is not None:\n            try:\n                params.append(int(limit))\n            except (TypeError, ValueError):\n                raise ValueError(\"limit must be an integer\")\n            query += \" LIMIT $3\"\n\n        try:\n            db_response: Final = await client.db.query_raw(query, *params)\n            # Convert the response to polars DataFrame with full schema inference\n            # This prevents schema mismatch errors when data types vary across rows\n            return pl.DataFrame(db_response, infer_schema_length=None)\n        except Exception as e:\n            raise Exception(f\"Error retrieving usage data: {e}\")\n","sourceCodeStart":83,"sourceCodeEnd":102,"githubUrl":"https://github.com/BerriAI/litellm/blob/6c2dcb801bf2b75c18f1bb24140e7cf57465cc4d/litellm/integrations/cloudzero/database.py#L83-L102","documentation":"Catch-all Exception from LiteLLMDatabase.get_usage_data wrapping the prisma query_raw call or the polars DataFrame construction. The message embeds the underlying error string, which can be a Prisma query error (bad parameter binding, SQL syntax from malformed timestamps), a Postgres connectivity error, or a polars schema-inference failure on the returned rows.","triggerScenarios":"Postgres unreachable or credentials rotated; start/end timestamps in a format Prisma cannot bind as $1/$2 parameters; the daily-user-spend table missing because the proxy schema was never migrated; polars failing infer_schema_length=None on inconsistent column types.","commonSituations":"Database credentials rotated without updating the proxy; running export against a fresh database with no spend table; passing tz-naive vs tz-aware datetimes inconsistently; very old rows with different column types breaking schema inference.","solutions":["Read the embedded error text — it distinguishes auth/connection ('password authentication failed', 'connection refused') from schema issues ('relation does not exist')","Run prisma migration / let the proxy create tables by starting it once with the database connected before exporting","Pass timezone-aware UTC datetimes for start_time_utc/end_time_utc","Retry on transient connection errors with backoff; fix data/schema issues instead of retrying those"],"exampleFix":"# before\ndf = await db.get_usage_data(limit=100, start_time_utc=\"2026-01-01\")  # str not datetime\n\n# after\nfrom datetime import datetime, timezone\ndf = await db.get_usage_data(\n    limit=100,\n    start_time_utc=datetime(2026, 1, 1, tzinfo=timezone.utc),\n)","handlingStrategy":"retry","validationCode":"from datetime import datetime\n\ndef valid_utc(dt) -> bool:\n    return dt is None or isinstance(dt, datetime)","typeGuard":"from datetime import datetime\n\ndef is_valid_export_window(start, end) -> bool:\n    ok = (start is None or isinstance(start, datetime)) and (end is None or isinstance(end, datetime))\n    if isinstance(start, datetime) and isinstance(end, datetime):\n        ok = ok and start <= end\n    return ok","tryCatchPattern":"import asyncio\n\nasync def export_with_retry(db, **kw):\n    for attempt in range(3):\n        try:\n            return await db.get_usage_data(**kw)\n        except Exception as e:\n            msg = str(e)\n            transient = any(s in msg for s in (\"connection\", \"timeout\", \"terminating\"))\n            if transient and attempt < 2:\n                await asyncio.sleep(2 ** attempt)\n                continue\n            raise","preventionTips":["Pass timezone-aware datetime objects, never strings","Ensure the proxy has run migrations so spend tables exist before export","Retry only transient DB errors; escalate schema errors immediately"],"tags":["cloudzero","database","postgres","prisma"],"backgroundTag":null,"analyzedSha":"6c2dcb801bf2b75c18f1bb24140e7cf57465cc4d","analyzedAt":"2026-08-15T07:12:03.035Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}