BerriAI/litellm · error · RuntimeError

GCS upload failed: status=

Error message

GCS upload failed: status={response.status_code} body={response.text}

What it means

RuntimeError raised in FocusGCSDestination.deliver() when the POST to the GCS JSON API upload endpoint (https://storage.googleapis.com/upload/storage/v1/b/{bucket}/o?uploadType=media&name=...) returns any status other than 200. The message embeds the HTTP status code and the full GCS response body, which states the exact Google-side reason (auth, permissions, missing bucket, rate limit).

Solutions

  1. Read the status in the message: 403 -> grant roles/storage.objectCreator on the bucket to the service account (gcloud storage buckets add-iam-policy-binding gs://my-bucket --member=serviceAccount:sa@project.iam.gserviceaccount.com --role=roles/storage.objectCreator)
  2. 404 -> confirm the bucket exists and BUCKET_NAME has no gs:// prefix, trailing slash, or typo
  3. 401 -> fix the service_account_json path/contents or unset conflicting GOOGLE_APPLICATION_CREDENTIALS
  4. 429/5xx -> retry on the next export cycle; the FOCUS logger backfills missed time windows

Example fix

# before: bucket name taken from env with scheme
export FOCUS_GCS_BUCKET_NAME=gs://litellm-focus

# after: bare bucket name
export FOCUS_GCS_BUCKET_NAME=litellm-focus
Defensive patterns

Strategy: retry

Validate before calling

import asyncio
from urllib.parse import quote

async def preflight_gcs_upload(destination) -> None:
    """Verify bucket access before the export window opens."""
    headers = await destination.construct_request_headers(service_account_json=destination.path_service_account_json)
    resp = await destination.async_httpx_client.get(
        f"https://storage.googleapis.com/storage/v1/b/{destination.BUCKET_NAME}", headers=headers
    )
    if resp.status_code >= 400:
        raise PermissionError(f"GCS preflight failed ({resp.status_code}): {resp.text[:200]}")

Try / catch

import asyncio, re

async def deliver_with_retry(destination, *, content, time_window, filename, attempts=3):
    for i in range(attempts):
        try:
            await destination.deliver(content=content, time_window=time_window, filename=filename)
            return
        except RuntimeError as e:
            m = re.search(r"status=(\d+)", str(e))
            status = int(m.group(1)) if m else 0
            if i < attempts - 1 and (status == 429 or status >= 500):
                await asyncio.sleep(2**i)
                continue
            raise

Prevention

When it happens

Trigger: A scheduled FOCUS export calling deliver(): 401/403 when the service account is missing, expired, or lacks storage.objects.create on the bucket; 404 when BUCKET_NAME does not exist; 400 for malformed object names; 429/5xx under Google API throttling or transient conditions.

Common situations: service_account_json path wrong (FOCUS_GCS_PATH_SERVICE_ACCOUNT pointing at a missing file), bucket name copied with the gs:// prefix, IAM role revoked after exports had been working, ADC picking the wrong identity on GKE/Cloud Run, or a large backfill tripping rate limits.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/87c8cba0c32a0e12. Report an issue: GitHub.

Appendix: source

Thrown at litellm/integrations/focus/destinations/gcs_destination.py:53

    async def deliver(
        self,
        *,
        content: bytes,
        time_window: FocusTimeWindow,
        filename: str,
    ) -> None:
        object_name: Final = self._build_object_key(time_window=time_window, filename=filename)
        headers: Final = await self.construct_request_headers(service_account_json=self.path_service_account_json)
        headers["Content-Type"] = "application/octet-stream"
        encoded_name: Final = encode_gcs_object_name_for_url(object_name)
        url: Final = (
            f"https://storage.googleapis.com/upload/storage/v1/b/"
            f"{self.BUCKET_NAME}/o?uploadType=media&name={encoded_name}"
        )
        response: Final = await self.async_httpx_client.post(url=url, headers=headers, data=content)
        if response.status_code != 200:
            raise RuntimeError(f"GCS upload failed: status={response.status_code} body={response.text}")
        verbose_logger.debug(
            "Focus GCS: uploaded %d bytes to gs://%s/%s",
            len(content),
            self.BUCKET_NAME,
            object_name,
        )

    def _build_object_key(self, *, time_window: FocusTimeWindow, filename: str) -> str:
        start_utc: Final = time_window.start_time.astimezone(timezone.utc)
        date_component: Final = f"date={start_utc.strftime('%Y-%m-%d')}"
        parts: Final = [self.prefix, date_component]
        if time_window.frequency == "hourly":
            parts.append(f"hour={start_utc.strftime('%H')}")
        key_prefix: Final = "/".join(filter(None, parts))
        return f"{key_prefix}/{filename}" if key_prefix else filename

View on GitHub (pinned to 77b7c6c40c)