{"record":{"id":"87c8cba0c32a0e12","repo":"BerriAI/litellm","slug":"gcs-upload-failed-status-response-status-code-b","errorCode":null,"errorMessage":"GCS upload failed: status={response.status_code} body={response.text}","messagePattern":"GCS upload failed: status=(.+?) body=(.+?)","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"litellm/integrations/focus/destinations/gcs_destination.py","lineNumber":53,"sourceCode":"\n    async def deliver(\n        self,\n        *,\n        content: bytes,\n        time_window: FocusTimeWindow,\n        filename: str,\n    ) -> None:\n        object_name: Final = self._build_object_key(time_window=time_window, filename=filename)\n        headers: Final = await self.construct_request_headers(service_account_json=self.path_service_account_json)\n        headers[\"Content-Type\"] = \"application/octet-stream\"\n        encoded_name: Final = encode_gcs_object_name_for_url(object_name)\n        url: Final = (\n            f\"https://storage.googleapis.com/upload/storage/v1/b/\"\n            f\"{self.BUCKET_NAME}/o?uploadType=media&name={encoded_name}\"\n        )\n        response: Final = await self.async_httpx_client.post(url=url, headers=headers, data=content)\n        if response.status_code != 200:\n            raise RuntimeError(f\"GCS upload failed: status={response.status_code} body={response.text}\")\n        verbose_logger.debug(\n            \"Focus GCS: uploaded %d bytes to gs://%s/%s\",\n            len(content),\n            self.BUCKET_NAME,\n            object_name,\n        )\n\n    def _build_object_key(self, *, time_window: FocusTimeWindow, filename: str) -> str:\n        start_utc: Final = time_window.start_time.astimezone(timezone.utc)\n        date_component: Final = f\"date={start_utc.strftime('%Y-%m-%d')}\"\n        parts: Final = [self.prefix, date_component]\n        if time_window.frequency == \"hourly\":\n            parts.append(f\"hour={start_utc.strftime('%H')}\")\n        key_prefix: Final = \"/\".join(filter(None, parts))\n        return f\"{key_prefix}/{filename}\" if key_prefix else filename\n","sourceCodeStart":35,"sourceCodeEnd":69,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/integrations/focus/destinations/gcs_destination.py#L35-L69","documentation":"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).","triggerScenarios":"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.","commonSituations":"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.","solutions":["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)","404 -> confirm the bucket exists and BUCKET_NAME has no gs:// prefix, trailing slash, or typo","401 -> fix the service_account_json path/contents or unset conflicting GOOGLE_APPLICATION_CREDENTIALS","429/5xx -> retry on the next export cycle; the FOCUS logger backfills missed time windows"],"exampleFix":"# before: bucket name taken from env with scheme\nexport FOCUS_GCS_BUCKET_NAME=gs://litellm-focus\n\n# after: bare bucket name\nexport FOCUS_GCS_BUCKET_NAME=litellm-focus","handlingStrategy":"retry","validationCode":"import asyncio\nfrom urllib.parse import quote\n\nasync def preflight_gcs_upload(destination) -> None:\n    \"\"\"Verify bucket access before the export window opens.\"\"\"\n    headers = await destination.construct_request_headers(service_account_json=destination.path_service_account_json)\n    resp = await destination.async_httpx_client.get(\n        f\"https://storage.googleapis.com/storage/v1/b/{destination.BUCKET_NAME}\", headers=headers\n    )\n    if resp.status_code >= 400:\n        raise PermissionError(f\"GCS preflight failed ({resp.status_code}): {resp.text[:200]}\")","typeGuard":null,"tryCatchPattern":"import asyncio, re\n\nasync def deliver_with_retry(destination, *, content, time_window, filename, attempts=3):\n    for i in range(attempts):\n        try:\n            await destination.deliver(content=content, time_window=time_window, filename=filename)\n            return\n        except RuntimeError as e:\n            m = re.search(r\"status=(\\d+)\", str(e))\n            status = int(m.group(1)) if m else 0\n            if i < attempts - 1 and (status == 429 or status >= 500):\n                await asyncio.sleep(2**i)\n                continue\n            raise","preventionTips":["Run a preflight bucket-access check at startup (list/get bucket metadata) to catch IAM mistakes before data is at stake","Alert on the embedded status code: 4xx needs a fix, 5xx/429 only needs a retry","Keep the FOCUS catch-up enabled so missed windows are re-exported after transient failures"],"tags":["gcs","upload","http","permissions","focus-export"],"backgroundTag":"cloud-storage-upload-failed","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}