Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install google-cloud-storage-fuse@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin google-cloud-storage-fuse v1.0.0 follows the Agent Plugins spec.
gh skills-hub install google-cloud-storage-fuse Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/google-cloud-storage-fuse/ Extract the ZIP to .github/skills/ in your repo. The folder name must match google-cloud-storage-fuse for Copilot to auto-discover it.
Skill Files (4)
SKILL.md 6.3 KB
---
name: google-cloud-storage-fuse
description: >-
Mounts Cloud Storage buckets on Google Cloud as a POSIX file system with
Cloud Storage FUSE (gcsfuse). Use when interacting with gcsfuse or Cloud
Storage FUSE mounts: decide whether FUSE, native gs:// reads, or
Filestore/Managed Lustre fits a workload, deploy tuned mounts on GKE,
Compute Engine, or Cloud Run, enable and size file, stat, and list caches, tune
mount flags (--implicit-dirs) or config files, apply workload profiles, keep
ML checkpointing safe (rename atomicity, hierarchical namespace/HNS, close-time
finalization, concurrent writers), or diagnose slow training, low throughput,
or bill spikes with gcsfuse metrics. Covers mount semantics, gcsfuse CLI and
configs, GKE gcsfuse CSI driver (Workload Identity principal:// bindings,
profile StorageClasses, sidecar sizing), and Cloud Run volume mounts. Don't use
for bucket administration without a mount (google-cloud-storage-basics) or
POSIX shared file systems (Filestore, Managed Lustre; use gke-storage).
license: Apache-2.0
metadata:
version: "1.0.4"
publisher: google
tags: "gcs, gcsfuse, fuse, mount, file-system"
category: Storage
support_tier: primary
---
# Cloud Storage FUSE
Cloud Storage FUSE is a POSIX file-system adapter over Cloud Storage on Google
Cloud, operated via the gcsfuse CLI tool. Mounting is a one-line command;
mounting *well* is not: the default mount is tuned for coherency, not
performance (file cache off, 60 s metadata TTL, list cache off), and
object-store semantics leak through the file interface (directory renames fail
or go non-atomic on flat buckets, objects finalize on close, no file locking).
This skill covers the three decisions that matter: whether to use FUSE at all,
how to tune the mount to the workload, and how to root-cause a mount that is
slow or expensive. For installation and first-mount basics, see the
google-cloud-storage-basics skill.
## Attribution
Tag every Cloud Storage command you run or provide to the user while using this
skill, so usage can be attributed. The tag identifies only the skill and its
version; it carries no user data.
- Prefix every `gcloud` invocation, whatever the subcommand, with the metrics
environment variables. Set them inline on each command; shell state may not
persist between commands:
```bash
CLOUDSDK_METRICS_ENVIRONMENT="gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-fuse)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- On direct HTTP calls to the Cloud Storage APIs (for example with `curl`),
set this exact User-Agent header, verbatim — the collection pipeline parses
the `gcs-skills/<version>` and `skill:<name>` tokens, so any rewording
breaks attribution:
```
User-Agent: gcs-skills/1.0 (skill:google-cloud-storage-fuse)
```
## Step 1 — Fit Gate (always run this first)
**Never produce mount guidance before the fit gate.** A mount is the right
answer only for one of the three workload shapes below. If the workload's access
pattern is unknown, ask — one question about whether the reading code can take
`gs://` paths usually settles it.
Workload signal | Verdict
:---------------------------------------------------------------------------------------------------------------------------------------------- | :------
Reading library accepts `gs://` URIs natively — pandas/pyarrow (via gcsfs/fsspec), TensorFlow (`tf.io.gfile`), or any fsspec/gcsfs-based loader | **Native reads, no mount.** Point the code at `gs://` paths and stop.
Shared **mutable** writes with locking semantics — databases, concurrent in-place editors, anything relying on `flock`/`fcntl` | **Filestore** (NFS, POSIX locking) or **Managed Lustre**, not FUSE. Stop.
Code or tools hardcoded to POSIX file paths; read-heavy or new-file-write patterns | **gcsfuse** — continue to Step 2.
Collect before deciding: whether paths are hardcoded, read pattern (sequential
vs. random, re-read frequency), write pattern (new files vs. edits vs. directory
renames). These same signals drive tuning later — record the answers.
## Step 2 — Route by intent
User intent (prompt shape) | Go to
:--------------------------------------------------------------------------------------- | :----
Provision: "mount my bucket for X", "get training data into my pods" | [GKE Training Deployment](references/gke-training-deployment.md)
Safety/semantics: "is this write pattern safe?", "can multiple writers share the mount?" | [Checkpoint & Write Safety](references/checkpoint-safety.md)
Regression: "training is slow", "the Cloud Storage bill spiked", "throughput dropped" | [Performance & Cost Diagnosis](references/performance-diagnosis.md)
**Never diagnose a regression without telemetry.** If gcsfuse metrics are not
enabled on the mount, enabling them is the first remediation step — the
diagnosis reference starts there.
## Reference Directory
- [GKE Training Deployment](references/gke-training-deployment.md): Fit-gated,
performance-tuned mounts for training workloads — GKE CSI version gates,
Workload Identity `principal://` IAM bindings, profile StorageClasses vs.
static PVs, file cache sizing on Local SSD, sidecar resource annotations,
complete KSA/PVC/Job manifests, and the Compute Engine and Cloud Run
variants.
- [Checkpoint & Write Safety](references/checkpoint-safety.md): Verdicts on
write patterns — file vs. directory rename atomicity on flat vs.
hierarchical namespace (HNS) buckets, close-vs-fsync finalization,
concurrent-writer (`ESTALE`) semantics, streaming-write memory budgets, HNS
migration, and the `aiml-checkpointing` profile.
- [Performance & Cost Diagnosis](references/performance-diagnosis.md):
Telemetry-first runbook for slow mounts and bill spikes — enabling and
reading gcsfuse metrics, mapping cache-hit and request-mix signatures to
misconfigurations, the coherency-tuned defaults, tuned config keys with
their staleness caveats, and billing-line (Class A/B) attribution.
checkpoint-safety.md 9.3 KB
# Checkpoint & Write Safety
Verdicts on write patterns through a gcsfuse mount — above all the standard
checkpoint publish pattern (write `ckpt.tmp/`, rename to the final name) that
must survive preemption.
## Verdict table (lead with this)
Write pattern | Flat-namespace bucket | HNS bucket
:--------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------- | :---------
Rename a **file** to finalize | Safe — atomic MoveObject since v3.2.0 | Safe — atomic since v3.1.0
Rename a **directory** to finalize | **Fails by default** (`rename-dir-limit: 0`); raising the limit makes it a **non-atomic** per-object copy+delete | Safe — atomic `RenameFolder`, metadata-only
`fsync()` for durability | **Not durable** under streaming writes (the default for new files) — rely on `close()` | Same — rely on `close()`
Concurrent writers, same object | First to close wins; later writers get `ESTALE`. No file locking exists. | Same
Kernel list cache (`kernel-list-cache-ttl-secs: -1`) | **Dangerous** on mutable mounts (directory ghosting, missing files, `rmdir` failures) | Same — keep list cache off or low TTL; `-1` is strictly for read-only mounts
So the temp-then-rename pattern is **safe if and only if** the bucket has
hierarchical namespace (HNS) enabled, or the framework renames individual files
rather than directories. On a flat bucket the directory rename fails outright by
default — and "fixing" it by raising `rename-dir-limit` converts a visible
failure into silent corruption risk: preemption mid-rename leaves a
partially-renamed "final" checkpoint.
**Never** describe file renames as "copy + delete, slow but works" — that is
outdated. Files rename atomically via the MoveObject API since v3.1.0 (HNS) and
v3.2.0 (flat buckets); only *directory* renames on *flat* buckets use the
non-atomic per-object path, and only when force-enabled.
**Never** recommend `fsync()` for checkpoint durability. Under streaming writes
(default since v3.0), `fsync()` does not finalize the object; data is guaranteed
on Cloud Storage only after `close()`. This is documented in the gcsfuse GitHub
semantics doc, not on cloud.google.com — cite
[semantics.md](https://github.com/GoogleCloudPlatform/gcsfuse/blob/master/docs/semantics.md)
when the user asks for a source.
**Never** enable `kernel-list-cache-ttl-secs: -1` on mutable or checkpointing
mounts. Client-side kernel list caching does not invalidate when files are added
or deleted during training runs, causing phantom files, missing checkpoint
shards, and `rmdir`/`unlink` errors across distributed workers. `-1` is strictly
for read-only training and serving mounts.
**Never** present `rename-dir-limit` as the fix without stating the
non-atomicity. It is a fallback with a corruption window, not a remedy.
## Diagnosis inputs
Collect before giving a verdict:
```bash
# Namespace type - the deciding signal. Prints "True" for HNS buckets;
# empty output means flat namespace. --raw is required: without it the
# describe output omits the hierarchical namespace field entirely.
CLOUDSDK_METRICS_ENVIRONMENT="gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-fuse)" \
gcloud storage buckets describe gs://BUCKET --raw --format="value(hierarchicalNamespace.enabled)"
```
Also determine from the user or the mount config: does the framework rename a
directory or individual files (Orbax and `torch.distributed.checkpoint` finalize
by renaming a checkpoint directory; a plain `torch.save` to a temp name renames
a single file); how many shard writers run concurrently per step; the effective
`write: global-max-blocks` and `file-system: rename-dir-limit`.
## Durability and finalization semantics
- Objects are visible to readers only after finalization. Under streaming
writes (default since v3.0, sequential writes to new files), finalization
happens at `close()` — not at `fsync()`.
- A read during write, a downward truncate, or a rename during write finalizes
the object early, and subsequent writes to that handle fall back to staged
writes.
- Staged writes (the fallback path: editing existing files, out-of-order
writes, block-budget exhaustion) buffer the whole file in `file-system:
temp-dir` (default `/tmp`) and upload on close/flush — an undersized temp
dir breaks large staged writes.
## Concurrency: first writer wins
There is no file locking (`flock`/`fcntl` are not honored across mounts). When
two mounts write the same object, the first flush/close wins by generation
precondition; the loser's `close()` fails with `ESTALE` (stale file handle).
Design for **one writer per object** — e.g. one shard writer per checkpoint
shard file. `ESTALE` in training logs almost always means two workers wrote the
same path.
## Memory budget for concurrent shard writers
Streaming writes hold one 32 MiB block per actively-written file, capped
globally by `write: global-max-blocks` — default **4** on ordinary machines (128
MiB total; A2/A3/A4-series autoconfigure to 1600). Each streaming file consumes
~96 MiB RAM during upload. When the block budget is exhausted, additional
concurrent writers degrade to staged writes — the only signal is a trace-level
log line, invisible at the default `info` severity, so it looks like an
unexplained slowdown. With N concurrent shard writers, set `write:
global-max-blocks` ≥ N (e.g. `global-max-blocks: 64` for 16 shard writers with
headroom).
## Remediation
**Recommended: move checkpoints to an HNS bucket** — directory renames become
atomic metadata-only `RenameFolder` operations (executed as long-running
operations: reads and lists work during the rename, writes to the affected
folders are blocked until it completes), which is what makes temp-then-rename
safe. HNS buckets also start with up to 8× the initial QPS of flat buckets
(40,000 initial object reads/s and 8,000 writes/s vs. 5,000 and 1,000). HNS can
only be chosen at bucket creation — existing flat buckets cannot be converted,
so plan a new bucket + data copy. Uniform bucket-level access is required for
HNS buckets.
```bash
# Create the HNS checkpoint bucket (--uniform-bucket-level-access is required)
CLOUDSDK_METRICS_ENVIRONMENT="gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-fuse)" \
gcloud storage buckets create gs://CKPT_BUCKET --location=LOCATION \
--uniform-bucket-level-access --enable-hierarchical-namespace
# Copy existing checkpoints if migrating
CLOUDSDK_METRICS_ENVIRONMENT="gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-fuse)" \
gcloud storage cp -r gs://OLD_BUCKET/checkpoints gs://CKPT_BUCKET/
```
Mount tuned for checkpointing:
```bash
# Compute Engine / self-managed (profile requires gcsfuse ≥ v3.4.0)
gcsfuse --profile=aiml-checkpointing CKPT_BUCKET /mnt/ckpt
```
On GKE use the `gcsfusecsi-checkpointing` StorageClass (GKE ≥
1.35.1-gke.1616000) — see [GKE Training Deployment](gke-training-deployment.md)
for the PV/PVC pattern; profiles cannot be passed as raw mount options on GKE.
The `aiml-checkpointing` profile sets `implicit-dirs`, infinite metadata TTL and
unlimited stat cache (`ttl-secs: -1`, `stat-cache-max-size-mb: -1`,
`negative-ttl-secs: 0`), `file-cache: cache-file-for-range-read: true` (for
restore-time range reads), and `file-system: rename-dir-limit: 200000`. Note the
rename-dir-limit entry exists for flat-bucket compatibility; on an HNS bucket
directory renames are atomic and need no limit. The profile does **not** enable
the file cache (enable it explicitly if restores should be served from local
media), and keeps the kernel list cache off (`kernel-list-cache-ttl-secs: 0`)
for write safety. Also state the close-time finalization semantics to the user
whenever recommending this setup: checkpoints are durable when the writer closes
the file, not before.
**Fallback (user cannot migrate to HNS):** raise the directory-rename limit on
the flat bucket, stating the risk explicitly —
```yaml
file-system:
rename-dir-limit: 200000
```
This makes directory renames *possible* but **non-atomic**: each object is
copied and deleted individually, the operation is O(objects) and expensive, and
preemption mid-rename leaves both directories in an inconsistent state. If the
job runs on preemptible/spot capacity, prefer file-level publish patterns (write
shards to temp *names*, rename each file, then write a final manifest file) —
file renames are atomic even on flat buckets.
## Documentation
- [Cloud Storage FUSE semantics (GitHub)](https://github.com/GoogleCloudPlatform/gcsfuse/blob/master/docs/semantics.md)
- [Profile-based configurations](https://docs.cloud.google.com/storage/docs/cloud-storage-fuse/profile-based-configurations.md.txt)
- [Config file reference](https://docs.cloud.google.com/storage/docs/cloud-storage-fuse/config-file.md.txt)
- [Hierarchical namespace overview](https://docs.cloud.google.com/storage/docs/hns-overview.md.txt)
- [GKE profiles for Cloud Storage FUSE](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/persistent-volumes/gcsfuse-profiles.md.txt)
gke-training-deployment.md 13.3 KB
# GKE Training Deployment (Fit-Gated, Tuned Mount)
Provision a performance-tuned gcsfuse mount for training workloads whose code is
hardcoded to POSIX paths (run the SKILL.md fit gate first). GKE version gates
are noted inline.
## Decision table: pick the mount mechanism
Environment | Mechanism
:----------------------- | :--------
GKE ≥ 1.35.1-gke.1616000 | PV/PVC on a pre-installed **profile StorageClass** (`gcsfusecsi-training`) — preferred; auto-tunes cache, media, and prefetch from node telemetry.
GKE < 1.35.1-gke.1616000 | Static PV/PVC with **explicit mount options replicating the profile** (see manifest B). Profiles are unavailable.
Compute Engine VM | `gcsfuse --profile=aiml-training` with ADC from the attached service account.
Cloud Run | Native Cloud Storage volume mounts (`--add-volume type=cloud-storage`).
**Never** pass `profile:aiml-*` as a mount option yourself on GKE: Cloud Storage
FUSE CSI volumes do not support the `profile` field or `--profile` option on any
volume type (ephemeral or PV/PVC). The pre-installed StorageClasses are the only
supported way to use profiles on GKE; on older clusters, set the profile's
individual options explicitly instead (manifest B).
**Never** use the legacy Workload Identity flow (Google service account +
`roles/iam.workloadIdentityUser` + `iam.gke.io/gcp-service-account` KSA
annotation). The current flow is a direct `principal://` IAM binding on the
bucket — no GSA, no JSON keys (step 2).
## Step 1 — Verify cluster gates
```bash
CLOUDSDK_METRICS_ENVIRONMENT="gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-fuse)" \
gcloud container clusters describe CLUSTER --location=LOCATION \
--format="value(currentMasterVersion, addonsConfig.gcsFuseCsiDriverConfig.enabled, workloadIdentityConfig.workloadPool)"
```
Requirements: `GcsFuseCsiDriver` addon enabled, a Workload Identity pool set,
and the cluster version against these gates:
- **Volume-scoped gcsfuse metrics (`k8s_gcs_fuse_volume`,
`gcsfusecsi/volume/*`):** ≥ 1.37.2-gke.1467000
- **Profile StorageClasses (`gcsfusecsi-*`):** ≥ 1.35.1-gke.1616000
- **Pod-scoped gcsfuse metrics (`k8s_pod`, `gcsfusecsi/*`):**
1.33.0-gke.2248000 to < 1.37.2-gke.1467000
- **`gcsfuseMetadataPrefetchOnMount`:** ≥ 1.32.1-gke.1357001
Check node cache media (drives step 4):
```bash
kubectl describe node NODE_NAME | grep "cloud.google.com/gke-ephemeral-storage-local-ssd"
```
## Step 2 — Authentication: direct principal:// binding
Grant the workload's Kubernetes ServiceAccount access on the bucket directly.
Use `roles/storage.objectViewer` for read-only training data;
`roles/storage.objectUser` if the workload also writes.
```bash
CLOUDSDK_METRICS_ENVIRONMENT="gcs-skills gcs-skills/1.0 (skill:google-cloud-storage-fuse)" \
gcloud storage buckets add-iam-policy-binding gs://BUCKET \
--member="principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/PROJECT_ID.svc.id.goog/subject/ns/NAMESPACE/sa/KSA_NAME" \
--role="roles/storage.objectViewer"
```
The KSA itself is a plain ServiceAccount with no annotations (manifest A).
For **cross-project mounts** (GKE cluster in Project A, bucket in Project B):
GKE's storage profile controller attempts an upfront bucket scan using the GKE
control-plane service agent
(`service-PROJECT_A_NUM@container-engine-robot.iam.gserviceaccount.com`). To
prevent Pods getting stuck in `SchedulingGated`
(`gke-gcsfuse/bucket-scan-pending`) with `403 Forbidden`, either set
`skipCSIBucketAccessCheck: "true"` on the PV (Manifests A & B) to skip the
control-plane pre-scan, or grant `roles/storage.bucketViewer` and
`roles/storage.objectViewer` to the cluster's GKE service agent on Project B's
bucket. The Step 2 `principal://` binding likewise goes on the bucket in Project
B, not in the cluster project: the member string still references Project A's
Workload Identity pool (`PROJECT_NUMBER` and `PROJECT_ID` are the cluster
project's), but the IAM policy must be granted in the bucket-owning project.
## Step 3 — What the training profile does (and does not do)
The `gcsfusecsi-training` StorageClass layers two things:
- **Client profile `aiml-training`** sets: `implicit-dirs`, `metadata-cache:
negative-ttl-secs: 0`, `metadata-cache: ttl-secs: -1`, `metadata-cache:
stat-cache-max-size-mb: -1`. It does **not** enable the file cache — no
client profile does.
- **GKE CSI automation** (StorageClass parameters) adds:
`gcsfuseMetadataPrefetchOnMount: "true"`, `skipCSIBucketAccessCheck:
"true"`, and dynamic file-cache sizing — the driver picks cache capacity and
medium from node resources, bucket size, and sidecar limits
(`fuseFileCacheMediumPriority:
"gpu:ram|lssd,tpu:ram,general_purpose:ram|lssd"`, memory budget 0.7 of
allocatable, ephemeral-storage budget 0.85). So on the profile path the file
cache **is** auto-enabled and auto-sized — verify it actually engaged (step
6), because the driver silently disables it when no medium has enough space.
List the pre-installed classes: `kubectl get sc -l gke-gcsfuse/profile=true`
(`gcsfusecsi-training`, `gcsfusecsi-checkpointing`, `gcsfusecsi-serving`).
To tune or customize mount options on the PV:
- **Scope massive namespaces (10M+ files):** Add `mountOptions:
["only-dir=<subfolder>"]` (or config `only-dir: <subfolder>`) to restrict
FUSE tracking to the active dataset partition (e.g. `train/`). This avoids
populating stat cache entries for the full namespace (~1.5 GiB RAM per 1M
files) and accelerates directory traversal.
- **Override profile defaults:** Set `spec.mountOptions` or
`spec.csi.volumeAttributes` on the PV. If you set `file-cache: max-size-mb`
manually, dynamic sizing is overridden for that component and you must also
configure a custom read cache volume (`gke-gcsfuse-cache`).
## Step 4 — File cache on the manual path (older clusters)
For multi-epoch training that re-reads the dataset, the file cache is the single
highest-impact knob; without the profile automation you must enable and size it
explicitly:
- Size `file-cache: max-size-mb` (or the `fileCacheCapacity` volume attribute)
to hold the working dataset.
- Media, in order of preference: Local SSD (A3/GPU nodes with the
`cloud.google.com/gke-ephemeral-storage-local-ssd: "true"` label; A3+ is set
up automatically), RAM disk for TPU v6+ nodes, `pd-ssd`/ `pd-balanced`
otherwise. Avoid the boot disk.
- The cache lands on the sidecar's emptyDir by default, so the pod annotation
`gke-gcsfuse/ephemeral-storage-limit` must exceed the cache capacity.
## Step 5 — Manifests
Every pod consuming a gcsfuse volume requires the sidecar-injection annotation
`gke-gcsfuse/volumes: "true"` — PV/PVC and ephemeral volumes alike.
**Sidecar sizing and resource limits:**
- `gke-gcsfuse/ephemeral-storage-limit`: Must exceed the file cache capacity
when using emptyDir.
- `gke-gcsfuse/cpu-limit` and `gke-gcsfuse/memory-limit`: Leave unset (or
`"0"`, the default on GKE ≥ 1.29.1-gke.1670000). Setting conservative CPU
limits causes aggressive CFS throttling during multi-threaded prefetching;
setting tight memory limits causes the sidecar to be OOMKilled (`ExitCode
137`) when stat cache or streaming buffers fill. If limits are mandated,
size memory well above the combined stat cache (~1.5 GiB / 1M files) and
streaming block budget.
**Manifest A — KSA + profile-path PV/PVC (GKE ≥ 1.35.1-gke.1616000):**
```yaml
# ksa.yaml - no GSA annotation; access comes from the principal:// binding
apiVersion: v1
kind: ServiceAccount
metadata:
name: KSA_NAME
namespace: NAMESPACE
---
# pv.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
name: training-data-pv
spec:
storageClassName: gcsfusecsi-training
capacity:
storage: 1Ti # placeholder; not enforced for gcsfuse
accessModes:
- ReadOnlyMany
mountOptions:
- ro # training data is read-only for the pods
csi:
driver: gcsfuse.csi.storage.gke.io
volumeHandle: BUCKET # the bucket name
volumeAttributes:
skipCSIBucketAccessCheck: "true" # prevents SchedulingGated 403 on cross-project mounts
---
# pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: training-data-pvc
namespace: NAMESPACE
spec:
storageClassName: gcsfusecsi-training
volumeName: training-data-pv
accessModes:
- ReadOnlyMany
resources:
requests:
storage: 1Ti
```
**Manifest B — older clusters: replicate the profile as explicit options.** Same
PV/PVC as above, but `storageClassName: ""` and:
```yaml
mountOptions:
- ro
- implicit-dirs
- metadata-cache:negative-ttl-secs:0
- metadata-cache:ttl-secs:-1
- metadata-cache:stat-cache-max-size-mb:-1
- file-cache:max-size-mb:512000 # size to the dataset
- file-cache:cache-file-for-range-read:true
# - only-dir=data/train # optional: scope namespace to save stat-cache RAM
csi:
driver: gcsfuse.csi.storage.gke.io
volumeHandle: BUCKET
volumeAttributes:
gcsfuseMetadataPrefetchOnMount: "true" # GKE ≥ 1.32.1-gke.1357001
skipCSIBucketAccessCheck: "true" # prevents SchedulingGated 403 on cross-project mounts
```
The infinite metadata TTL and unlimited stat cache assume the dataset is
immutable during training; budget ~1.5 GiB RAM per million files for the stat
cache.
**Manifest C — training Job:**
```yaml
apiVersion: batch/v1
kind: Job
metadata:
name: training-job
namespace: NAMESPACE
spec:
template:
metadata:
annotations:
gke-gcsfuse/volumes: "true" # required for sidecar injection
gke-gcsfuse/ephemeral-storage-limit: 600Gi # > file cache capacity
# gke-gcsfuse/cpu-limit: "0" # default unlimited; do not set tight limits
# gke-gcsfuse/memory-limit: "0" # default unlimited; avoid OOMKill (Exit 137)
spec:
serviceAccountName: KSA_NAME
nodeSelector:
cloud.google.com/gke-ephemeral-storage-local-ssd: "true"
containers:
- name: trainer
image: TRAINING_IMAGE
volumeMounts:
- name: training-data
mountPath: /data
readOnly: true
volumes:
- name: training-data
persistentVolumeClaim:
claimName: training-data-pvc
restartPolicy: Never
```
## Step 6 — Apply and verify
```bash
kubectl apply -f ksa.yaml -f pv.yaml -f pvc.yaml -f training-job.yaml
kubectl exec POD -c trainer -- ls /data | head # mount works, data visible
```
Then confirm the cache engaged and troubleshoot common blockers:
- **`SchedulingGated` (`gke-gcsfuse/bucket-scan-pending`):** Upfront bucket
access check failed (common on cross-project mounts). Fix by setting
`skipCSIBucketAccessCheck: "true"` in `spec.csi.volumeAttributes` or
granting `bucketViewer`/`objectViewer` to the cluster's GKE service agent.
- **Sidecar OOMKilled (`ExitCode 137`) / CPU throttling:** Sidecar limits
throttled prefetching or ran out of memory under stat/file cache load.
Remove `gke-gcsfuse/cpu-limit` and `gke-gcsfuse/memory-limit` (or set
`"0"`).
- **Profile cache verification:** Check the `GCSFuseCSIRecommendation` log
entry for the `decision` block (`fileCacheBytes`, `fileCacheMedium`); the
warning "No suitable file cache medium found" means the cache was silently
disabled — fix node media or sidecar limits.
- **Cache hit rate (Cloud Monitoring):** Exported by default on GKE ≥
1.33.0-gke.2248000 (disable via the `disableMetrics: "true"` volume
attribute). After the first epoch, `cache_hit="true"` reads should approach
100% from epoch 2 onward (see
[Performance & Cost Diagnosis](performance-diagnosis.md) for the full metric
map):
- **GKE ≥ 1.37.2-gke.1467000:** `gcsfusecsi/volume/file_cache_read_count`
on monitored resource `k8s_gcs_fuse_volume`
- **GKE < 1.37.2-gke.1467000:** `gcsfusecsi/file_cache_read_count` on
monitored resource `k8s_pod`
## Non-GKE variants
Environment | Command
:------------- | :------
Compute Engine | `gcsfuse --profile=aiml-training --config-file=cache.yaml BUCKET /mnt/data` — profile works directly (≥ v3.4.0); still enable the file cache in the config file. ADC comes from the attached service account.
Cloud Run | `gcloud run services update SERVICE --add-volume=name=data,type=cloud-storage,bucket=BUCKET --add-volume-mount=volume=data,mount-path=/data`
## Documentation
- [GKE profiles for Cloud Storage FUSE](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/persistent-volumes/gcsfuse-profiles.md.txt)
- [CSI driver setup and Workload Identity](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/cloud-storage-fuse-csi-driver-setup.md.txt)
- [Static PV/PVC provisioning](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/cloud-storage-fuse-csi-driver-pv.md.txt)
- [Sidecar configuration](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/cloud-storage-fuse-csi-driver-sidecar.md.txt)
- [CSI performance tuning](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/cloud-storage-fuse-csi-driver-perf.md.txt)
- [Volume attributes reference](https://docs.cloud.google.com/kubernetes-engine/docs/reference/cloud-storage-fuse-csi-driver/volume-attr.md.txt)
- [Profile-based configurations](https://docs.cloud.google.com/storage/docs/cloud-storage-fuse/profile-based-configurations.md.txt)
performance-diagnosis.md 11.8 KB
# Performance & Cost Diagnosis
Telemetry-driven root-causing for "training through the mount is slow" and "the
Cloud Storage bill spiked after we mounted the bucket". The core insight: **the
default mount is coherency-tuned, not performance-tuned** — most regressions on
untuned mounts are the defaults doing exactly what they promise.
**Never hypothesize before reading telemetry.** If client metrics are not
enabled, enabling them is the first remediation step; while waiting for a
remount window, the server-side `storage.googleapis.com/api/request_count`
metric is always available and needs no mount change.
## The coherency-tuned defaults (the usual suspects)
Knob | Default | Effect on a re-read workload
:---------------------------------------- | :----------------------- | :---------------------------
File cache (`cache-dir`) | Off | Every epoch re-downloads every byte.
`metadata-cache: ttl-secs` | 60 | All metadata re-fetched every minute.
`metadata-cache: stat-cache-max-size-mb` | 34 (~20k files) | Silently evicts on large file counts → constant re-stats.
`metadata-cache: negative-ttl-secs` | 5 | "Not found" results re-checked every 5 s.
List cache (`kernel-list-cache-ttl-secs`) | 0 (off) | Every `ls`/directory walk hits the API.
`implicit-dirs` | false (true in profiles) | When on (flat buckets), lookups issue extra List calls.
A ~5M-small-file dataset re-read each epoch against these defaults produces
exactly the classic symptom pair: throughput far below local disk, and an
operations-dominated bill.
## Step 1 — Establish telemetry
- **GKE ≥ 1.37.2-gke.1467000:** `gcsfusecsi/volume/*` metrics (monitored
resource `k8s_gcs_fuse_volume`) are in Cloud Monitoring by default — no
action.
- **GKE 1.33.0-gke.2248000 to < 1.37.2-gke.1467000:** `gcsfusecsi/*` metrics
(monitored resource `k8s_pod`) are in Cloud Monitoring by default — no
action.
- **Self-managed mount → Cloud Monitoring:** Remount with
`--cloud-metrics-export-interval-secs=60` (needs
`roles/monitoring.metricWriter` on the mount's service account; native
metrics are Preview).
- **Self-managed mount → local scrape:** Remount with
`--prometheus-port=9920`, then `curl -s localhost:9920/metrics`.
- **No remount possible yet:** Server-side:
`storage.googleapis.com/api/request_count` grouped by the `method` label.
```bash
# Self-managed: remount with metrics, reproduce the workload, then inspect
gcsfuse --prometheus-port=9920 BUCKET /mnt/data
curl -s localhost:9920/metrics | grep -E "file_cache_read_count|gcs_request_count|fs_ops_count"
```
Client metrics only accumulate from mount time — reproduce at least one epoch
(or a representative slice) after enabling before reading the numbers.
Also capture the effective mount configuration (the misconfig surface): the
running `gcsfuse` command line and `--config-file` contents on self-managed
hosts; on GKE, `kubectl get pv PV_NAME -o yaml` (check `spec.mountOptions` and
`spec.csi.volumeAttributes`) plus the pod's `gke-gcsfuse/*` annotations.
## Step 2 — Read the signals
Metric (Cloud Monitoring / Prometheus form) | What it tells you
:----------------------------------------------------------------------------------------- | :----------------
`file_cache/read_count`, by `cache_hit` label (`file_cache_read_count{cache_hit="false"}`) | Cache hit rate — the headline signal.
`gcs/request_count` (`gcs_request_count`) | Requests actually sent to Cloud Storage.
`gcs/request_latencies`, `gcs/retry_count` | Per-request latency and retry pressure.
`fs/ops_count` by `fs_op` (`fs_ops_count{fs_op="LookUpInode"}`) | Operation mix the app drives (stat-heavy? list-heavy?).
`fs/ops_error_count` by `fs_error_category` | Errors surfacing to the app.
Server-side `api/request_count` by `method` (e.g. `ReadObject`) | Request mix without any mount change; also the bridge to billing.
On GKE (≥ 1.33.0-gke.2248000), the same client metrics appear prefixed and
underscored in Cloud Monitoring according to your cluster version:
- **GKE ≥ 1.37.2-gke.1467000:**
- **Monitored resource:** `k8s_gcs_fuse_volume`
- **Resource labels:** `project_id`, `location`, `cluster_name`,
`namespace_name`, `pod_name`, `volume_name`, `bucket_name` (promotes
`volume_name` and `bucket_name` to resource labels while retaining
`pod_name`)
- **Metric prefix:** `kubernetes.io/gcsfusecsi/volume/`
- **File system latency metric:** `gcsfusecsi/volume/fs_ops_latencies`
- **Workload aggregation labels:** `k8s_controller_type` and
`k8s_controller_name` metric labels — populated only for supported
workload controllers (`deployment`, `replicaset`, `statefulset`,
`daemonset`, `jobset`, `leaderworkerset`), and emitted as empty strings
(`""`) for standalone Pods and unsupported controllers (such as
standalone `Job`s)
- **Metric-specific labels:** `cache_hit` (`file_cache_read_count`,
`file_cache_read_latencies`), `read_type` (`file_cache_read_count`,
`file_cache_read_bytes_count`, `gcs_download_bytes_count`,
`gcs_read_count`), `fs_op` (`fs_ops_count`, `fs_ops_error_count`,
`fs_ops_latencies`), `fs_error_category` (`fs_ops_error_count`),
`gcs_method` (`gcs_request_count`, `gcs_request_latencies`), and
`io_method` (`gcs_reader_count`)
- **`pod_uid` label:** Removed from schema
- **Sample period and latency units:** `60 s` `sample_period` (up from
`10 s` on `k8s_pod`), and `gcs_request_latencies` unit metadata changes
from `ms` to `us` (`fs_ops_latencies` and `file_cache_read_latencies`
remain in `us`)
- **GKE 1.33.0-gke.2248000 to < 1.37.2-gke.1467000:**
- **Monitored resource:** `k8s_pod`
- **Resource labels:** `project_id`, `location`, `cluster_name`,
`namespace_name`, `pod_name`
- **Metric prefix:** `kubernetes.io/gcsfusecsi/`
- **File system latency metric:** `gcsfusecsi/fs_ops_latencies`
- **`volume_name` and `bucket_name`:** Metric labels on `k8s_pod`
- **Metric-specific labels:** Same per-metric labels as
`k8s_gcs_fuse_volume` (`cache_hit`, `read_type`, `fs_op`,
`fs_error_category`, `gcs_method`, `io_method`)
- **Workload aggregation labels:** Not available
- **`pod_uid` label:** Metric label on `k8s_pod` (empty string `""` in ≥
1.35.2-gke.1442000; per-Pod UID in earlier 1.33–1.35 builds)
- **Sample period and latency units:** `10 s` `sample_period`, with
`gcs_request_latencies` unit metadata in `ms` (`fs_ops_latencies` and
`file_cache_read_latencies` in `us`)
## Step 3 — Map the signature to the misconfiguration
Signature | Root cause | Fix (exact keys)
:----------------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------- | :---------------
`cache_hit="false"` on ~all reads; download volume ≈ dataset × epochs | File cache off (no `cache-dir`) or undersized | `cache-dir` + `file-cache: max-size-mb` sized to the dataset (`-1` = fill the cache dir). Parallel downloads auto-enable with the cache.
Stat/metadata-dominated request mix; `fs_ops_count` LookUpInode-heavy; slowness scales with file count | 60 s TTL expiring + 34 MiB stat cache (~20k entries) thrashing against a large file count | `metadata-cache: ttl-secs: -1` and `stat-cache-max-size-mb: -1` — **immutable data only**; budget ~1.5 GiB RAM per million files (~1,720 bytes/file). Scope with `only-dir` if only a subset of the bucket is needed.
List-dominated mix (`objects.list` / ListObjects methods); directory walks slow | List cache off; or `implicit-dirs` on a flat bucket adding List calls per lookup | `file-system: kernel-list-cache-ttl-secs: -1` — **read-only mounts only**; prefer buckets with hierarchical namespace (HNS) enabled over `implicit-dirs`.
Sidecar OOMKilled (Exit 137) or severe CPU throttling during reads | Sidecar memory or CPU limits set too low on GKE | Leave limits unset (default "0" on GKE ≥ 1.29.1); or set memory limit > stat/file cache budget.
Attribution logic for the bill: no file cache → every epoch re-reads all objects
(`objects.get`, Class B, billed per operation); expiring metadata + evicting
stat cache → re-stats (`objects.get` metadata, Class B); list cache off /
implicit-dirs → repeated `objects.list` (Class A, ~12.5× the per-op price of
Class B on standard buckets). Deletes are free.
## Step 4 — Apply the fix
```yaml
# tuned.yaml - read-heavy, immutable dataset re-read across epochs
cache-dir: /mnt/local-ssd/gcsfuse-cache
file-cache:
max-size-mb: -1 # or size to the dataset
metadata-cache:
ttl-secs: -1 # immutable data only
stat-cache-max-size-mb: -1 # ~1.5 GiB RAM per 1M files
file-system:
kernel-list-cache-ttl-secs: -1 # read-only mounts only
# only-dir: dataset/train # optional: scope namespace on 10M+ object buckets
```
```bash
gcsfuse --config-file=tuned.yaml BUCKET /mnt/data
```
> [!WARNING]
>
> **Staleness trade-off:** `-1` TTLs mean this mount never sees changes made to
> the bucket by other clients. Apply only to data that is immutable for the life
> of the mount, and prefer mounting read-only (`-o ro`). If the bucket is
> mutable, size TTLs to the acceptable staleness window instead.
Config hygiene while editing: `metadata-cache: type-cache-max-size-mb` is a
no-op since v3.8.0 (type cache merged into stat cache) — delete it from any
config that still sets it. On GKE, apply the same keys as PV `mountOptions`
entries (`file-cache:max-size-mb:...` colon syntax) — see
[GKE Training Deployment](gke-training-deployment.md). On Rapid (zonal) buckets
the file cache and buffered reads are no-ops by default (the kernel read path
replaces them) — this runbook's cache fixes apply to standard buckets.
## Step 5 — Verify and state the expected billing delta
Re-run one epoch, then check:
- `file_cache_read_count{cache_hit="true"}` ≈ 100% of reads from epoch 2
onward (first epoch populates the cache).
- `gcs/request_count` drops to roughly one GET per object per mount lifetime
(plus the initial listing) instead of per epoch.
- On the bill: the **Class B line** (`objects.get` — data reads and metadata
stats) drops roughly in proportion to the former epoch count; the **Class A
line** (`objects.list`) drops if list caching or HNS addressed a list-heavy
signature. Confirm server-side with `api/request_count` by `method`
before/after.
## Documentation
- [Cloud Storage FUSE metrics](https://docs.cloud.google.com/storage/docs/cloud-storage-fuse/metrics.md.txt)
- [Config file reference](https://docs.cloud.google.com/storage/docs/cloud-storage-fuse/config-file.md.txt)
- [File caching](https://docs.cloud.google.com/storage/docs/cloud-storage-fuse/file-caching.md.txt)
- [Performance tuning](https://docs.cloud.google.com/storage/docs/cloud-storage-fuse/performance.md.txt)
- [Cloud Storage pricing (operation classes)](https://cloud.google.com/storage/pricing)
- [Google Cloud metrics list (api/request_count)](https://docs.cloud.google.com/monitoring/api/metrics_gcp_p_z.md.txt)
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE