Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install pathways-workload@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin pathways-workload v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install pathways-workload

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/pathways-workload/

Extract the ZIP to .github/skills/ in your repo. The folder name must match pathways-workload for Copilot to auto-discover it.

Skill Files (5)

SKILL.md 25.8 KB
---
name: pathways-workload
description: >-
  Debugs failed, crashing or hung Pathways on Cloud workloads (JAX training or
  inference on Cloud TPU in GKE, run as a JobSet, PathwaysJob or
  LeaderWorkerSet). Reads Cloud Logging for every Pathways container (user
  workload, IFRT proxy, pathways-rm, pathways-worker, colocated Python
  sidecar), node kernel logs and GKE events, then reports the earliest real
  error, the root cause and a fix. Use when a Pathways workload fails to start,
  crashes, restarts or stops making progress, or shows errors such as IFRT
  proxy connection failures, DEADLINE_EXCEEDED lost connection to peer, host
  OOM kills, ImagePullBackOff, or JAX and Pathways version mismatches. Don't
  use for GKE workloads that don't use Pathways, or for creating clusters or
  deploying new Pathways workloads.
metadata:
  version: "1.1.0"
  category: AiAndMachineLearning
---

# Pathways on Cloud Workload Debugging Skill

This skill provides comprehensive instructions, debugging playbooks, and helper
utilities to troubleshoot Pathways on Cloud GKE workloads.

## Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).

--------------------------------------------------------------------------------

## Overview

Pathways:
[Pathways on Cloud Introduction](https://docs.cloud.google.com/ai-hypercomputer/docs/workloads/pathways-on-cloud/pathways-intro)

### Understanding Initial Setup for JAX+Pathways on Cloud

A GKE cluster is required to use Pathways. We have instructions to create one
which utilize either 1\) a one click setup like XPK or 2\) a series of gcloud
commands here:
[https\://docs.cloud.google.com/ai-hypercomputer/docs/workloads/pathways-on-cloud/create-gke-cluster](https://docs.cloud.google.com/ai-hypercomputer/docs/workloads/pathways-on-cloud/create-gke-cluster)

Advanced customers have built custom infrastructure which rolls Pathways based
JobSets and cluster creation commands. To debug their infra issues, we may want
to ask them to share their jobset YAMLs with us (redacting their main container
definition is fine).

### Parsing Important Logs

How to determine if various Pathways components have started successfully

**IFRT Proxy Server (a.k.a Pathways Client) Ready**

```
IFRT proxy server started with status OK

Pathways worker Ready: Pathways Server serving on [::]:29001
```

**RM (Resource Manager) Ready and eventually all TPU slices are ready**

```
Pathways Server serving on [::]:29001
...
...
***<num slices>/<num slices> Pathways Slices Now Ready ***
```

**Individual Pathways worker (on a TPU host) Ready**

```
Pathways Server serving on [::]:29001
```

--------------------------------------------------------------------------------

## Step 1: Metadata & Configuration Gathering

Before initiating debugging, gather critical parameters to construct accurate
queries: 1. `project` 2. `cluster_name` 3. `location` 4. the workload name and
kind (see [Identifying the Workload](#identifying-the-workload)) 5. `namespace`
(default: `default`) 6. `issue_time` (UTC, when the failure was first noticed)

Always bound log queries in time. Use the window
`[issue_time - 30m, issue_time + 30m]`, i.e. pass
`--start_time="{start_time}" --duration=1h` to the debug_workload script, where
`{start_time}` is `issue_time - 30m` in RFC 3339 (e.g. `2026-10-22T11:10:00Z`).
Unbounded queries are slow and get truncated by `--limit`. Widen the window only
if the first error is not in it.

-   If the window contains more than one failure, report each with timestamps
    and say which one matches the user's symptom.
-   Report the root cause and the workaround separately. The root cause is the
    component that logged the earliest stall or error (for example the proxy,
    the RM or a worker). A configuration change that avoids that code path
    (a different checkpoint handler, flag or topology) is a workaround or a
    contributing factor: list it under the fix, not as the root cause.
-   Do not stop at the first plausible error. List the candidate causes, then
    confirm or rule out each one with a query, and classify every finding you
    report as one of the four classes below. This is in addition to the
    preflight, the crash sweep, the container walk of Step 3 and any matching
    special scenario of Step 4, not instead of them; when a scenario matches,
    follow its steps.
    -   **Root cause**: the earliest failure that explains the symptom and its
        timing.
    -   **Contributing**: makes the failure more likely or the recovery slower,
        but does not explain it alone.
    -   **Side effect**: caused by the root cause, e.g. restarts, lost
        connections, reconnect errors, or core dumps filling the node disk
        after crashes.
    -   **Noise**: errors that also occur in healthy periods, were retried
        successfully, or do not line up in time with the failure.
-   Rule out a cause only with a check that can see it: an empty result rules
    out only what that query matches (e.g. a kernel OOM search does not see
    kubelet evictions, and `--first_per_pod` skips lines). A query that timed
    out (`[timeout]`) or failed is incomplete, not clean: say so in the report.
-   When you compare with other runs (an earlier attempt, a sibling test that
    passed, or the same test on other days), use the comparison to narrow down
    which code path is affected, not as proof of the cause. A setting that
    differs in a passing run does not explain the failure if a Pathways
    component logged the stall or error.
-   End the report with the checks you ran and their result, so the user can
    repeat them: preflight, the actions or `gcloud logging read` queries you
    used (with their time window), pod events, and node OOMs. Include checks
    that failed or could not run (e.g. no log access) and say what to run
    instead.

> [!TIP]
>
> Always check the recent chat context or shared log queries from the user.
> Often, all five fields can be directly scraped from their console links or
> queries!

### Identifying the Workload

The debug_workload script finds the workload's logs by the object that created
its pods. Use the matching flag (the examples in this skill use
`--jobset_name`):

Workload kind                                 | Flag                     | Find it with
:-------------------------------------------- | :----------------------- | :-----------
JobSet (most training workloads, XPK)         | `--jobset_name=<name>`   | `kubectl get jobsets -n {namespace}`
LeaderWorkerSet (e.g. Pathways inference)     | `--lws_name=<name>`      | `kubectl get leaderworkersets -n {namespace}`
Plain Job (not created by a JobSet)           | `--job_name=<name>`      | `kubectl get jobs -n {namespace} -l '!jobset.sigs.k8s.io/jobset-name'`
Anything else (bare pods, custom controllers) | `--pod_prefix=<prefix>`  | `kubectl get pods -n {namespace}`

For past incidents, list the pods that logged in the window and their owner
labels instead:

```bash
gcloud logging read 'resource.type="k8s_container"
  resource.labels.cluster_name="{cluster_name}"
  resource.labels.namespace_name="{namespace}"
  timestamp>="{start_time}" timestamp<="{end_time}"' \
  --project="{project}" --limit=10000 \
  --format='value(resource.labels.pod_name,labels."k8s-pod/jobset_sigs_k8s_io/jobset-name",labels."k8s-pod/leaderworkerset_sigs_k8s_io/name",labels."k8s-pod/batch_kubernetes_io/job-name")' \
  | sort -u
```

If parts of the workload run in different objects, query them together by
repeating `--workload=<kind>:<name>` (kinds: `jobset`, `lws`, `job`, `pod`).
For example, if the JAX client or the proxy runs in its own Job next to the
Pathways JobSet, debug both: `--workload=jobset:{jobset_name}
--workload=job:{client_job_name}`.

To see what else ran on the same nodes, run `scripts/debug_workload.py` with
`--action=neighbors --execute`. It lists every namespace/pod/container that
logged on the workload's nodes and marks the ones that are not part of the
workload. Use it to spot another workload sharing the hosts (e.g. a second
resource manager or proxy on the same host and port when host exclusivity is not
set) and to find the real container names of the workload's pods (e.g. a
custom-named colocated Python sidecar).

### Retrieving Active YAML Configuration

If the workload is still active/alive, run the following command to inspect how
it is structured and identify misconfigurations (use `leaderworkerset` or `job`
instead of `jobset` for those kinds):

```bash
kubectl get jobset {jobset_name} -n {namespace} -o yaml
```

If the workload has been deleted but you suspect misconfiguration, request the
user to paste or share the workload YAML in the chat.

### Recording Versions

Before reading errors, record each component's image tag (from the YAML or the
pod spec) and `Build label` (logged at startup by pathways-rm, pathways-proxy
and pathways-worker), plus the client's JAX, jaxlib and pathwaysutils versions.
Check that they are from matching releases and that the flags passed to each
component exist in its image.

--------------------------------------------------------------------------------

## Step 1.5: Quick Triage - Preflight, Then Crash Sweep

`scripts/debug_workload.py` needs only Python 3.10 or later and the `gcloud`
CLI (no Python packages to install). Without `--execute`, it prints the
`gcloud logging read` command and a Cloud Console link instead of running them.

First run the preflight check. It verifies that you can read the project's logs
and that the workload logged in the time window. An empty result from any
other action is not a clean result until preflight passes. If you cannot run
commands yourself (for example no log access) and give the user a plan or a
list of commands instead, start that plan with the preflight command:

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --action=preflight
```

Then, before reading containers one by one, run the crash and fatal-error sweep
across all containers of the workload. It looks for segfaults, `Check failed`,
Python tracebacks, OOM kills, unknown flags, permission errors, etc., and
returns the earliest hits first:

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --action=errors \
  --execute
```

The container of the earliest hit is usually where the root cause is; then use
the container-specific playbook in Step 3 for that container. Whatever the
sweep finds, also run `--action=node-ooms` (OOM kills and memory-pressure
evictions often do not appear in container logs; it needs `--execute` to
discover the workload's nodes, or `--node_names`), `--action=pod-events`, and,
for restarts or SIGTERMs, `--action=interruptions`: a host or infrastructure
event that comes before the first container error is the more likely root
cause. If the job is slow or hangs rather than crashing, first follow
[scenario 14](references/special-scenarios.md#14-the-job-hangs-without-failing):
find the last progress line of every container (user steps, RM slice state,
worker program launches and proxy requests) and the component that stopped
first. Then also sweep warnings
(`--min_severity=WARNING` on the container actions): a repeated warning can
explain the slowdown even when there is no error.

If a cascade fills the output (hundreds of pods logging the same error), you
may add `--first_per_pod=N` to keep only the first N matching log lines of each
pod/container plus its last matching line, e.g. `--first_per_pod=1` to see
which pod failed first and how the failure spread, or `--first_per_pod=3` to
also see each pod's next few lines. Use it at your discretion: it fetches up to
`--fetch_limit` lines (default 1000) before grouping, so it is slower than a
plain query and can be slow or time out when the workload has many pods. Narrow
the time window first, and prefer a plain query when only a few pods are
involved. Never conclude "no crash" from a `--first_per_pod` sweep alone: it
skips lines in the middle of each pod's log, and the fetch limit can cut off
later pods. Confirm with a plain query on the suspect container.

--------------------------------------------------------------------------------

## Step 2: GKE JobSet Lifecycle Verification

If the workload has not started or failed immediately at scheduling time:

### 1. Verify Webhook & Scheduling Status

Identify if scheduling blocks are occurring due to insufficient cluster
resources or webhook failures.

Check for webhook mutating errors, `OOMKilled` controller managers, or
Unschedulable conditions:

```bash
# Check controller manager pods in the JobSet system namespace
kubectl get pods -n jobset-system
```

### 2. Symptom: Forever Suspended JobSet

If a JobSet is created but remains in a permanently `Suspended` state and never
spawns child pods:

-   **Potential Root Causes**:
    -   The JobSet name is too long. Because JobSet appends replicated job names
        and index numbers to child resources, long prefixes fail standard
        Kubernetes resource name validation (max 63/253 chars).
    -   The JobSet YAML is malformed (e.g. invalid or missing fields, wrong
        resource requests or node selectors), so the workload is never admitted
        to the queue and stays suspended. Ask the user for the YAML (see
        [Retrieving Active YAML Configuration](#retrieving-active-yaml-configuration))
        and check it for errors.
-   **Diagnosis**: Check the JobSet controller manager logs in `jobset-system`
    namespace to find truncation, length limit, name-generation, or validation
    errors. You can use the debug_workload script to quickly query the logs:

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --action=summary \
  --execute
```

### 3. SIGTERM and Pre-emption Diagnosis

-   SIGTERMs are the most common mechanism for GKE to stop/restart workloads. A
    SIGTERM is a symptom; find out who sent it.
-   Common senders: Spot VM preemption, Compute Engine host maintenance, host
    errors, node auto-repair, or a JobSet restart triggered by another failed
    container. Check infrastructure interruptions and pod events for the time
    window:

    ```bash
    python3 scripts/debug_workload.py \
      --project="{project}" \
      --cluster_name="{cluster_name}" \
      --location="{location}" \
      --jobset_name="{jobset_name}" \
      --start_time="{start_time}" --duration=1h \
      --action=interruptions \
      --execute
    # then the same command with --action=pod-events
    ```

-   If no infrastructure event explains the SIGTERM, trace the failure back from
    the user workload to the TPU that failed first:

    1.  In the user workload logs (`--action=user-workload`), find the time of
        the first error or the last completed step.
    2.  In the RM logs (`--action=pathways-rm`) around that time, find when the
        first failure occurred or the first TPU slice/worker stopped responding
        (e.g. a slice leaving the ready state or `Job cancelled due to ...`),
        and which slice/worker it was.
    3.  Inspect that worker's logs (`--action=workers`, adding
        `--min_severity=WARNING` if needed) and its node's events
        (`--action=pod-events`, `--action=node-ooms`, `--action=interruptions`)
        to find out what happened there.
    4.  The cause can be a user code error (unlikely) or another fault, such as
        a hardware failure, an OOM, a crash in the worker, or a node
        interruption.

-   `kubectl get events -n {namespace} --field-selector
    involvedObject.name={jobset_name}` only works for live incidents: Kubernetes
    keeps events for a certain time only. For past incidents use
    `--action=pod-events` / `--action=summary`, which read the events from Cloud
    Logging.

-   For deeper analysis of restarts and interruptions, follow the public
    [gke-ai-troubleshooting-jobset-interruption](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/gke-ai-troubleshooting-jobset-interruption/SKILL.md)
    skill; for host maintenance, follow
    [gke-ai-troubleshooting-handle-disruption-gpu-tpu](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/gke-ai-troubleshooting-handle-disruption-gpu-tpu/SKILL.md).

--------------------------------------------------------------------------------

## Step 3: Container-Specific Debugging Playbook

Because Pathways is distributed, inspect logs container-by-container in logical
order to avoid cascade noise, and always chase the earliest error. Before you
query a container, read its section in
[Container Playbooks](references/container-playbooks.md): it has the log
signals, the `debug_workload.py` command and the gotchas for that container.

Order | Container | Action | Look for | Playbook
:---- | :-------- | :----- | :------- | :-------
1 | User workload (`user-workload`, `main`, `jax-tpu`) | `--action=user-workload` | The last completed step, then the first exception | [A](references/container-playbooks.md#a-user-workload-container)
2 | IFRT proxy | `--action=proxy` | `Connection refused` to the RM port (`:29001`), `Socket closed` | [B](references/container-playbooks.md#b-ifrt-proxy-server)
3 | Resource manager (`pathways-rm`) | `--action=pathways-rm` | Slice ready transitions, placement, a repeated `Build label` (restarts) | [C](references/container-playbooks.md#c-resource-manager-pathways-rm)
4 | Pathways workers (`pathways-worker`) | `--action=workers` | The first worker that failed, Megascale stall detectors (`HANG_DETECTED`) | [D](references/container-playbooks.md#d-pathways-workers-pathways-worker)
5 | Colocated Python sidecar | `--action=colocated-python-sidecar` | Workers waiting for a sidecar that died | [E](references/container-playbooks.md#e-colocated-python-sidecar)

Rules that apply to every container:

-   A client-side `Unable to initialize backend 'proxy': UNAVAILABLE: Unable to
    establish connection` is a symptom. Check whether the proxy, RM and workers
    started (see [Parsing Important Logs](#parsing-important-logs)) and find
    their earliest error before you suspect the user's code.
-   `IFRT proxy server was terminated: UNAVAILABLE: Socket closed` and
    `SLICE_FAILURE_CHIP_DRIVER_ERROR` are downstream errors: go to the RM and
    worker logs.
-   When one worker fails, the other workers of the slice fail shortly after.
    The root cause is in the logs of the first worker that failed.
-   The built-in search terms only cover known failures. If an action returns
    nothing useful, re-run it with `--min_severity=WARNING` (`DEFAULT` for the
    user workload) and add the workload's own strings with `--extra_terms`.
-   If the logs still don't explain the failure, read all logs of the
    container ([F](references/container-playbooks.md#f-all-logs-of-a-container)),
    then ask for more verbose proxy logs or XProfs
    ([G](references/container-playbooks.md#g-when-the-error-is-still-not-clear)).

--------------------------------------------------------------------------------

## Step 4: Special Scenarios

These known failures have a specific cause and fix. When an error or
symptom matches a row, read that scenario in
[Special Scenarios](references/special-scenarios.md) before you conclude:

Error or symptom | Scenario
:--------------- | :-------
`JaxRuntimeError` with `DATA_LOSS` during scale changes; elastic recovery or checkpoint restore fails | [1. Elastic training and checkpoint restore](references/special-scenarios.md#1-elastic-training-and-checkpoint-restore)
Container restarts or exit code 137 without `OOMKilled`; `Memory cgroup out of memory`, `oom-kill`, `OOMKilling`; `Evicted` with `The node was low on resource: memory`, `NodeHasInsufficientMemory` | [2. Host OOM kills and memory-pressure evictions](references/special-scenarios.md#2-host-oom-kills-and-memory-pressure-evictions)
`Unable to initialize backend 'proxy': Backend 'proxy' is not in the list of known backends` | [3. Backend proxy is not in the list of known backends](references/special-scenarios.md#3-backend-proxy-is-not-in-the-list-of-known-backends)
`SIGTERM received by PID 1`; containers stop without a clear error; a preemption or maintenance event followed by `DATA_LOSS`, proxy restarts or a client crash | [4. SIGTERM received by PID 1](references/special-scenarios.md#4-sigterm-received-by-pid-1)
`FAILED_PRECONDITION: The newly added instance does not match with the expected instances` | [5. Newly added instance does not match the expected instances](references/special-scenarios.md#5-newly-added-instance-does-not-match-the-expected-instances)
`Connection to IFRT proxy server was terminated: FAILED_PRECONDITION: GrpcClientSession: writes no longer allowed` | [6. Connection to the IFRT proxy server was terminated](references/special-scenarios.md#6-connection-to-the-ifrt-proxy-server-was-terminated)
`XlaRuntimeError: ABORTED: ... The metadata for object was edited during the operation`; `PERMISSION_DENIED` or `FAILED_PRECONDITION` from the persistent compilation cache | [7. Persistent compilation cache errors](references/special-scenarios.md#7-persistent-compilation-cache-errors)
`DEADLINE_EXCEEDED: lost connection to peer` or `DATA_LOSS: Pipe from scheduler to aggregator` | [8. Lost connection to peer](references/special-scenarios.md#8-lost-connection-to-peer)
`Status 11 from handshaker service: Input frame length is out of range` | [9. ALTS handshake error from a client outside Google Cloud](references/special-scenarios.md#9-alts-handshake-error-from-a-client-outside-google-cloud)
`Lifecycle matches_prefix cannot specify more than 50 prefixes per config` | [10. Cloud Storage lifecycle prefix limit](references/special-scenarios.md#10-cloud-storage-lifecycle-prefix-limit)
`IFRT Proxy client and server failed to agree on the protocol version`, or `Failed to deserialize the Mosaic module: ... Unsupported version` | [11. JAX and Pathways version mismatch](references/special-scenarios.md#11-jax-and-pathways-version-mismatch): compare the client's JAX, jaxlib and pathwaysutils versions with the Pathways image tags and `Build label`s
Pods in `ImagePullBackOff` or `ErrImagePull` | [12. Pods stuck in ImagePullBackOff or ErrImagePull](references/special-scenarios.md#12-pods-stuck-in-imagepullbackoff-or-errimagepull): read the pull error in the pod events, then list the registry's tags (`gcloud artifacts docker tags list`)
`Address already in use`, `Init:Error`, or `didn't have free ports` | [13. Port collisions with hostNetwork](references/special-scenarios.md#13-port-collisions-with-hostnetwork)
No error anywhere, but the job stops making progress | [14. The job hangs without failing](references/special-scenarios.md#14-the-job-hangs-without-failing)
`Still waiting to acquire semaphore`, `Recv completion error`, `GOAWAY` | [15. Proxy-to-worker transfers stall](references/special-scenarios.md#15-proxy-to-worker-transfers-stall)

--------------------------------------------------------------------------------

## Related Public Skills and Writing Your Own Queries

These public skills from
[github.com/google/skills](https://github.com/google/skills) complement this
skill. If they are installed, use them by name; otherwise read them from the
links.

Symptom                                                         | Public skill
:-------------------------------------------------------------- | :-----------
Writing a custom Cloud Logging query                            | [cloud-logging-query-generation](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/cloud-logging-query-generation/SKILL.md) (GKE examples: [query_gke.md](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/cloud-logging-query-generation/references/query_gke.md))
JobSet restarts, Spot preemption, maintenance, host termination | [gke-ai-troubleshooting-jobset-interruption](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/gke-ai-troubleshooting-jobset-interruption/SKILL.md)
Compute Engine host maintenance on TPU/GPU nodes                | [gke-ai-troubleshooting-handle-disruption-gpu-tpu](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/gke-ai-troubleshooting-handle-disruption-gpu-tpu/SKILL.md)
Multi-slice job stops responding (`HANG_DETECTED`)              | [gke-ai-troubleshooting-tpu-mxla-hang](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/gke-ai-troubleshooting-tpu-mxla-hang/SKILL.md)
Node NotReady, unresponsive node, auto-repair                   | [gke-ai-troubleshooting-node-unresponsive-timeout](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/gke-ai-troubleshooting-node-unresponsive-timeout/SKILL.md)

When you write your own queries:

-   Always use double quotes for strings, uppercase `AND`/`OR`/`NOT`, and
    parentheses to group terms.
-   Restrict `resource.type` (`k8s_container`, `k8s_pod`, `k8s_node`,
    `gke_nodepool`, `gce_instance`) and use `log_id("events")`,
    `log_id("stdout")` or `log_id("stderr")` where possible.
-   Always add a time window (`timestamp>="..."` and `timestamp<="..."`).
-   Pathways components log glog lines into `jsonPayload.message` (some
    containers) or `textPayload` (others); bare quoted terms or `SEARCH()` match
    both.
-   Pod label keys are stored with `.` replaced by `_`, e.g.
    `labels."k8s-pod/batch_kubernetes_io/job-completion-index"` and
    `labels."k8s-pod/jobset_sigs_k8s_io/jobset-name"`. Some public examples
    spell the Job label with dots (`batch.kubernetes.io/job-name`); that form
    does not match Pathways logs.
references/
attribution.md 1.8 KB
# Usage Attribution

**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.

-   **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
    subcommand, with the metrics environment variable. Set it inline on each
    command because shell state may not persist between commands:

    ```bash
    CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:pathways-workload)" \
    gcloud <command> [flags]
    ```

    Do not use `gcloud config set` for this: it would persist beyond the current
    task and mislabel unrelated usage.

-   **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
    Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
    server, include `agent-skills/1.0 (skill:pathways-workload)` in the
    `User-Agent` header. If a `User-Agent` header is already specified, append
    this string to the end of it rather than overwriting existing `User-Agent`
    data — the collection pipeline parses the `agent-skills/<version>` and
    `skill:<name>` tokens, so any rewording breaks attribution:

    ```
    User-Agent: <existing_user_agent> agent-skills/1.0 (skill:pathways-workload)
    ```

-   **Constraint for Generated Code**: The tracking prefix is strictly for
    commands you execute directly in the terminal. Do NOT include this tracking
    prefix in generated scripts, Terraform templates, or code provided to the
    user for their own repositories.

-   **User Opt-Out**: If the user asks to disable or remove tracking or
    attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
    and custom `User-Agent` suffix from all commands.
container-playbooks.md 11.7 KB
# Container Playbooks

Per-container debugging steps for Pathways on Cloud workloads, in the order
of Step 3 of SKILL.md: user workload, IFRT proxy, resource manager,
workers, then the colocated Python sidecar. Always chase the earliest
error. Run the commands from the skill directory, as in SKILL.md.

## Contents

-   [A. User workload container](#a-user-workload-container): lines 20-91
-   [B. IFRT proxy server](#b-ifrt-proxy-server): lines 92-117
-   [C. Resource manager (pathways-rm)](#c-resource-manager-pathways-rm): lines 118-139
-   [D. Pathways workers (pathways-worker)](#d-pathways-workers-pathways-worker): lines 140-186
-   [E. Colocated Python sidecar](#e-colocated-python-sidecar): lines 187-257
-   [F. All logs of a container](#f-all-logs-of-a-container): lines 258-263
-   [G. When the error is still not clear](#g-when-the-error-is-still-not-clear): lines 264-294

--------------------------------------------------------------------------------

## A. User workload container

Start with the user workload logs (container `user-workload`, `main` or
`jax-tpu`). This container runs the primary Python code.

1.  **Find the Timestamp**: Find the exact timestamp of the last completed step
    or progress trace (e.g., `"completed step"`, `"Final goodput"`).

2.  **Identify Node/Worker Faults**: Look for exceptions or node references that
    stopped responding or failed.

3.  **Common Errors**:

    -   `jax.errors.JaxRuntimeError` (with `DATA_LOSS`): elasticity failure
        (see scenario 1 in Step 4 of SKILL.md).
    -   `Dict key mismatch` or `Error opening "zarr" driver`: Orbax/checkpoint
        issues.
    -   `Fatal Python error:` or
        `CRITICAL - Timeout from watchdog 'step-timebomb'`: process hangs.

4.  **Query Logs**:

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --action=user-workload \
  --execute
```

The built-in progress strings are partly framework specific (e.g.
`"completed step"` is logged by MaxText). If the user's workload logs progress
or errors differently, add its strings with `--extra_terms` (repeatable, plain
text); they are OR-ed with the built-in list. This works for the `errors`,
`user-workload`, `proxy`, `pathways-rm` and `workers` actions:

```bash
python3 scripts/debug_workload.py ... --action=user-workload \
  --extra_terms="train_step" --extra_terms="loss is nan" --execute
```

The real error may be logged at INFO. If the RM and workers look healthy, scan
the user container at all severities, starting just before the first exception
(e.g. a narrow `--start_time` with `--duration=5m`):

```bash
python3 scripts/debug_workload.py ... --action=user-workload \
  --min_severity=DEFAULT --execute
```

If the user workload logs are inconclusive, pin the timestamp of the earliest
suspicious error in the logs and widen the filter to the proxy server, followed
by the Pathways RM, followed by the Pathways worker. Some workloads may also
have a colocated python sidecar. Always chase the earliest error. See the next
sections for more details.

Example failures:

1.  `SLICE_FAILURE_CHIP_DRIVER_ERROR`: Not a root cause; indicates something
    earlier failed.
2.  `Unable to initialize backend 'proxy': UNAVAILABLE: Unable to establish
    connection`: This is a general error saying that your JAX program was not
    able to connect to the IFRT Proxy server running on GKE. To determine the
    root cause, check for the proxy server logs to verify if the proxy started
    successfully. If it did, this could happen due to networking issues e.g.
    firewall restrictions. If your JAX container is running outside of GKE, you
    can workaround that issue by colocating your JAX client with proxy server on
    the same k8s pod.

## B. IFRT proxy server

You can use the debug_workload script to quickly query the logs:

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --action=proxy \
  --execute
```

If the proxy logs repeat `Connection refused` to the resource manager port
(`:29001`) or `not yet heard from ... :29001`, the resource manager is down or
crash-looping. The JAX client then hangs at
`Sending InitRequest and waiting for response` until the test times out. Go to
the RM section and check whether `Build label` repeats (one per RM restart).

If you see `"IFRT proxy server was terminated: UNAVAILABLE: Socket closed"`: -
This is downstream. The proxy server died because a deeper Pathways worker or
Resource Manager container crashed. Skip proxy server logs and go directly to
Worker/RM logs.

## C. Resource manager (pathways-rm)

Examines slice allocation and overall Pathways clustering.

1.  Look for slice count synchronization and ready transitions (e.g.,
    `"N/M Pathways Slices Now Ready"` or `"slice ready"`).

2.  Track assignment, placement, and unassignment events of slices.

3.  **Query Logs**:

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --action=pathways-rm \
  --execute
```

## D. Pathways workers (pathways-worker)

There are many workers; each replicated Job is a slice, and each index is a
worker.

-   **Root Cause Isolation**: When one worker fails, all other workers in the
    slice cascade-fail shortly after. The true error is only on the *first*
    failing worker's logs at the very beginning of the incident.

-   **Leader Triage**: Filter logs specifically to the **leader workers**
    (`completion-index = 0` for each slice index) to significantly reduce query
    volume and identify which sub-worker failed.

-   **Multiline Logging Gotcha**: Be aware that multiline proto or serialized
    logs often get split. Non-first lines may incorrectly show as high severity
    errors in Cloud Logging.

-   **Sanitized Images**: Note that sanitized images will not have readable
    Python stack traces.

-   **Workers that stop responding**: Pathways workers log
    `Megascale hang detected` / `Megascale detects a hang`; Megascale itself
    logs `HANG_DETECTED`. The `workers` action matches all three. For a
    multi-slice job that stops responding, follow the public
    [gke-ai-troubleshooting-tpu-mxla-hang](https://raw.githubusercontent.com/google/skills/d542604d73544bcb4bcc61322f3b25522ceba7ed/skills/cloud/gke-ai-troubleshooting-tpu-mxla-hang/SKILL.md)
    skill.

-   **Query Logs**:

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --action=workers \
  --execute
```

The built-in lists of the `pathways-rm` and `workers` actions only cover known
failures. If they return nothing useful, re-run them with
`--min_severity=WARNING` (or `ERROR`) to also get every warning/error line, and
add any other failure strings you know of with `--extra_terms`. Keep the time
window tight: with `--min_severity` the result can be noisy (see the multiline
logging gotcha above).

## E. Colocated Python sidecar

Container `colocated-python-sidecar`, or the custom name found in Step 1 of
SKILL.md. Used in some workloads for colocated dataloading or checkpointing.
Look for workers that stopped responding indefinitely waiting for colocated
Python sidecars (often because one sidecar process died quietly). A sidecar
that died without an error in its own logs was often killed for memory: the
sidecar shares the TPU host's memory with `pathways-worker`, and it can grow
while loading data or weights. Run `--action=node-ooms` for its node (see
[Special Scenarios 2](special-scenarios.md#2-host-oom-kills-and-memory-pressure-evictions)).

The sidecar container is usually named `colocated-python-sidecar`, but customer
workloads may use a different name. The sidecar always runs **in the TPU worker
pods, next to the `pathways-worker` container** (usually as a native sidecar,
i.e. an `initContainer` with `restartPolicy: Always`). Containers of the head
pod (`pathways-rm`, `pathways-proxy`, the user's JAX container) are never the
sidecar. Before querying, find the actual name unless you got it from Step 1:

-   From the JobSet YAML (see Retrieving Active YAML Configuration in Step 1
    of SKILL.md):
    in the pod template that has the `pathways-worker` container, the sidecar is
    the other container (in `containers` or `initContainers`). It typically sets
    `GRPC_SERVER_ADDRESS` (port `50051`) and
    `CLOUD_PATHWAYS_SIDECAR_SHM_DIRECTORY`, and shares a memory volume with
    `pathways-worker`.
-   If the JobSet is still running, list the containers of each pod and pick the
    non-`pathways-worker` container of the pods that have `pathways-worker`:

    ```bash
    kubectl get pods -n {namespace} \
      -l jobset.sigs.k8s.io/jobset-name={jobset_name} \
      -o jsonpath='{range .items[*]}{.metadata.name}: {.spec.initContainers[*].name} {.spec.containers[*].name}{"\n"}{end}'
    ```

-   For past incidents, list which containers logged from which pods in the time
    window, and pick the non-`pathways-worker` container of the pods that also
    log `pathways-worker`:

    ```bash
    gcloud logging read 'resource.type="k8s_container"
      resource.labels.cluster_name="{cluster_name}"
      resource.labels.namespace_name="{namespace}"
      labels."k8s-pod/jobset_sigs_k8s_io/jobset-name"="{jobset_name}"
      timestamp>="{start_time}" timestamp<="{end_time}"' \
      --project="{project}" --limit=10000 \
      --format='value(resource.labels.pod_name,resource.labels.container_name)' \
      | sort -u
    ```

    The sidecar usually logs `Registering remote Python CPU backend` or
    `Installed shared memory allocator for remote Python` at startup, which you
    can use to confirm the pick. If no container other than `pathways-worker`
    logs from the worker pods, the workload most likely does not use a colocated
    Python sidecar.

If it is not the default, pass `--sidecar_container="{sidecar_container}"` to
every debug_workload command (it also excludes the sidecar from
`--action=user-workload`):

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --sidecar_container="{sidecar_container}" \
  --action=colocated-python-sidecar \
  --execute
```

## F. All logs of a container

If the above actions didn't help, you can try to look at all the logs.
Drop the filters in the log queries to see all logs for the containers, in the
same order as above.

## G. When the error is still not clear

### Increase verbosity of proxy logs

If you suspect more proxy logs are needed, you can ask the user to increase the
verbosity of the proxy server and the JAX client as follows:

a) IFRT Proxy Client Detailed Logs: Setting the below env variable in your JAX
container would log all IFRT calls originating from JAX.

```
TF_CPP_VMODULE=grpc_host_buffer=3,rpc_helper=3,host_buffer=3,ifrt_backend=3,grpc_service_impl=3
```

b) IFRT Proxy Server Detailed Logs: Setting the below flag in the IFRT Proxy
server command line args would log all incoming IFRT calls originating from the
IFRT Proxy client.

```
spec:
  customComponents:
  - componentType: proxy_server
    customFlags:
    - --vmodule=grpc_host_buffer=3,rpc_helper=3,host_buffer=3,ifrt_backend=3,grpc_service_impl=3
```

### Getting XProfs

If you need to view the profile of the user job, proxy, RM, and workers to
understand why certain operations are taking long, ask the user to provide XProf
snapshots.
special-scenarios.md 18.7 KB
# Special Scenarios

Known Pathways on Cloud failure signatures, with their cause and fix. Step 4
of SKILL.md lists them by error and symptom. Run the commands from the skill
directory, as in SKILL.md.

## Contents

-   [1. Elastic training and checkpoint restore](#1-elastic-training-and-checkpoint-restore): lines 27-62
-   [2. Host OOM kills and memory-pressure evictions](#2-host-oom-kills-and-memory-pressure-evictions): lines 63-117
-   [3. Backend proxy is not in the list of known backends](#3-backend-proxy-is-not-in-the-list-of-known-backends): lines 118-126
-   [4. SIGTERM received by PID 1](#4-sigterm-received-by-pid-1): lines 127-187
-   [5. Newly added instance does not match the expected instances](#5-newly-added-instance-does-not-match-the-expected-instances): lines 188-202
-   [6. Connection to the IFRT proxy server was terminated](#6-connection-to-the-ifrt-proxy-server-was-terminated): lines 203-213
-   [7. Persistent compilation cache errors](#7-persistent-compilation-cache-errors): lines 214-248
-   [8. Lost connection to peer](#8-lost-connection-to-peer): lines 249-265
-   [9. ALTS handshake error from a client outside Google Cloud](#9-alts-handshake-error-from-a-client-outside-google-cloud): lines 266-281
-   [10. Cloud Storage lifecycle prefix limit](#10-cloud-storage-lifecycle-prefix-limit): lines 282-293
-   [11. JAX and Pathways version mismatch](#11-jax-and-pathways-version-mismatch): lines 294-311
-   [12. Pods stuck in ImagePullBackOff or ErrImagePull](#12-pods-stuck-in-imagepullbackoff-or-errimagepull): lines 312-328
-   [13. Port collisions with hostNetwork](#13-port-collisions-with-hostnetwork): lines 329-337
-   [14. The job hangs without failing](#14-the-job-hangs-without-failing): lines 338-351
-   [15. Proxy-to-worker transfers stall](#15-proxy-to-worker-transfers-stall): lines 352-370

--------------------------------------------------------------------------------

## 1. Elastic training and checkpoint restore

During scale transitions, JAX raises `JaxRuntimeError` with `DATA_LOSS`, and the
elastic training loop recovers from an in-memory snapshot or a persistent
checkpoint. To debug a failed recovery, rebuild its timeline from the JAX client
and pathways-rm:

```bash
python3 scripts/debug_workload.py ... --action=elastic --limit=500 --execute
```

Line up these events:

-   Slice loss and return: `Slices Now Ready`, `placed -> unplaced`,
    `Unassigning` (pathways-rm).
-   Recovery start: `Elastic attempt`, `New slices found`.
-   Snapshot path: `Restoring the in-memory snapshot`, or snapshots skipped
    because a checkpoint save was in progress.
-   Checkpoint path: `Falling back to persistent checkpoint`, `Restoring ...`
    with the step.
-   Outcome: `Resuming at step ...` or the next error. The `elastic` action also
    matches the crash and fatal-error list, so the exception that ended a
    recovery attempt shows up in the same timeline.

Then answer, in order:

1.  Which slice was lost, and when?
2.  Did a usable snapshot exist?
3.  Which restore path ran, and from which step?
4.  Was that step committed (`commit_success` / `_CHECKPOINT_METADATA` in the
    checkpoint directory)?
5.  Did the JobSet restart or tear down the job before the elastic wait
    finished? Compare JobSet and pod events (`--action=summary`,
    `--action=pod-events`) with the wait timeout.
6.  Was the proxy started in elastic mode?

## 2. Host OOM kills and memory-pressure evictions

OOMs on the head pod (python, proxy, or RM containers) and on TPU hosts (worker,
colocated Python sidecar) often **do not** appear in container logs or as an
`OOMKilled` pod event, but in the underlying node's kernel logs. A container
restart or exit code 137 without an `OOMKilled` reason also points here. Query
the node logs for OOM kills and memory-pressure evictions:

```bash
python3 scripts/debug_workload.py \
  --project="{project}" \
  --cluster_name="{cluster_name}" \
  --location="{location}" \
  --jobset_name="{jobset_name}" \
  --start_time="{start_time}" --duration=1h \
  --action=node-ooms \
  --execute
```

The node can also run out of memory without a kernel OOM kill: the kubelet
then evicts pods to free memory. Signs: an `Evicted` pod event with `The node
was low on resource: memory. Container <name> was using <N>Ki, request is
<M>...`, and `EvictionThresholdMet` or `NodeHasInsufficientMemory` node
events. An eviction for memory is host memory exhaustion, just like a kernel
OOM kill. So **no kernel OOM kill does not rule out a memory problem**: rule it
out only after the `node-ooms` action (which matches both) and
`--action=pod-events` show neither.

The pod-evictions part of `node-ooms` matches evictions for any resource, so
read the message: `low on resource: memory` is host memory exhaustion, while
`ephemeral-storage` or disk evictions that follow crashes (e.g. core dumps
filling the node disk) are usually side effects, not the root cause.

With `--execute`, `node-ooms` runs its parts one by one (node events, pod
evictions, kernel log lines, serial console), each limited by
`--query_timeout`. The kernel log search is free text and can time out on large
or old windows; if a part prints `[timeout]`, report that part as not checked
and narrow the window or pass `--node_names` to retry it.

When you find a host OOM kill (`Memory cgroup out of memory: Killed process`,
`oom-kill` or `OOMKilling`) or a memory-pressure eviction:

-   Say in the report that it is host (CPU) RAM, not TPU HBM. An HBM OOM shows
    up as `RESOURCE_EXHAUSTED` in the worker or user-workload logs instead, and
    needs different fixes (sharding, batch size), not more container memory.
-   Name the container that used the memory (the eviction message and the
    kernel OOM line both name it) and compare its usage with its memory request
    and limit. A container without a limit, or using far more than its
    request, can starve the other containers on the node, e.g. a colocated
    Python sidecar or data-loading process that grows while loading data or
    weights.
-   Line up the time of the kill or eviction with the first errors of the
    other containers: the errors that follow (lost connections, worker or
    proxy restarts) are side effects, not separate causes.

## 3. Backend proxy is not in the list of known backends

```
RuntimeError: Unable to initialize backend 'proxy': Backend 'proxy' is not in the list of known backends: ['cpu', 'tpu', 'cuda']. (set JAX_PLATFORMS='' to automatically choose an available backend)
```

The proxy backend is missing. Solution: Add pathwaysutils.initialize() at the
beginning of your program.

## 4. SIGTERM received by PID 1

This means that the GKE scheduler has sent a SIGTERM to the corresponding
pathways container and the container has exited in response to that. This can
happen due to a variety of events: GKE preempting your nodes due to lower level
defrag/maintenance events or higher level preemption events. Application errors
typically seen on proxy or RM happen before the first SIGTERM was received. K8s
decided to terminate all the pods in the jobset since the controller exiting
needs a jobset restart If no concrete error is found in the logs, check the
Kubernetes events and infrastructure interruptions with `--action=pod-events`,
`--action=summary` and `--action=interruptions` (see Step 2.3 in SKILL.md).
Check Resource Allocation: Insufficient CPU or memory allocated to the JAX,
proxy, or resource
manager (RM) containers is a leading cause of crashes without clear error
messages. To check if a container has OOMed, you should look at the GCE instance
logs which is hosting the corresponding container by searching for the string
`oom-killer`. It would describe the specific process (if any) that OOMed on the
pathways head node. The query filter to get that information is covered by
`--action=node-ooms`, which checks node-problem-detector
`OOMKilling`/`SystemOOM` events, kubelet memory-pressure evictions, kernel
`Memory cgroup out of memory` lines on the cluster's nodes, and serial-console
logs of the JobSet's nodes (discovered
automatically from the pods' `Scheduled` events, or pass
`--node_names=gke-...,gke-...`). To look at a single node manually:

```
resource.type="gce_instance"
labels."compute.googleapis.com/resource_name"="<Pathways head node>"
log_id("serialconsole.googleapis.com/serial_port_1_output")
SEARCH("oom-kill")
```

As a starting point, consider the following allocations:

Container             | Recommended Memory&nbsp;&nbsp; | Recommended CPU
:-------------------- | :----------------------------- | :--------------
JAX Client            | 100 GiB                        | 16
Pathways Proxy        | 100 GiB                        | 16
Resource Manager (RM) | 32 GiB                         | 16

**Preemption or maintenance cascade.** A node preemption or maintenance event
often produces a chain of errors across components, and the last one in the
chain is usually the most visible. A typical order:

1.  The preemption or maintenance notice (`--action=interruptions`), sometimes
    also forwarded in the pathways-rm logs.
2.  The RM or workers try to suspend or drain the slice; this can fail.
3.  The worker on the lost host is marked dead, and the others report
    `DATA_LOSS` or lost connections ([8](#8-lost-connection-to-peer)).
4.  The proxy restarts or drops its clients
    ([6](#6-connection-to-the-ifrt-proxy-server-was-terminated)).
5.  The JAX client fails, or crashes (e.g. a segmentation fault) while
    disconnecting.

Report the interruption as the root cause and steps 2-5 as its effects, with
their timestamps; do not report the client crash as a separate bug unless it
also happens without an interruption. After the restart, replacement pods may
stay `Pending` (e.g. no capacity); report that as a separate issue that delays
recovery. Side effects of the crashes, such as core dumps filling the node disk
(`DiskPressure`, ephemeral-storage evictions), are not the root cause either.

## 5. Newly added instance does not match the expected instances

```
FAILED_PRECONDITION: The newly added instance does not match with the expected instances
```

This typically occurs when there is a discrepancy between the expected TPU slice
topology by the RM and the actual instances provisioned by GKE for the worker.
[This](https://github.com/google/pathways-job/blob/c0cc7594c9d03a1d96a89110008a0f2d3c9ef189/internal/controller/pathwaysjob_controller.go#L71)
is the mapping supported by Pathways for various TPU chip generations and their
configurations. You can compare the expected and actual topologies by looking at
the proto in the RM logs for the topology that RM was expecting (indicated as
“expected topology”) and the topology that it got from the worker (indicated as
“Newly added slice topology”)

## 6. Connection to the IFRT proxy server was terminated

```
UNAVAILABLE:Connection to IFRT proxy server was terminated: FAILED_PRECONDITION: GrpcClientSession: writes no longer allowed
```

The Pathways cluster and specifically the pathways proxy container that your JAX
client was connected to has terminated or restarted since the original
connection was established. Try restarting your workload to see if the issue
goes away.

## 7. Persistent compilation cache errors

Errors about the compilation cache in Cloud Storage (often the
`--gcs_scratch_location` bucket) are common, but most of them are not fatal.
Before you report one as the root cause, check whether the job kept running
after it and whether the time of the error lines up with the failure.

**Cached executable metadata was edited during the operation:**

```
XlaRuntimeError: ABORTED: Permanent error, with a last message “” of The metadata for object was edited during the operation. Please try again
```

Possible race condition between writing and reading the cached executable object
in GCS. We
[recommend](https://docs.jax.dev/en/latest/persistent_compilation_cache.html#google-cloud)
using GCSFuse to mount your GCS bucket as a local directory. It translates the
GCS preconditions to the filesystem level to do parallel writes atomically and
prevent metadata conflicts you are seeing.

**Permission denied on the cache bucket** (`PERMISSION_DENIED`, e.g. on
`storage.buckets.update` or `storage.objects.*`, while initializing the
persistent cache): the service account cannot set up or use the cache. Pathways
usually falls back to an in-memory cache and keeps running, so this is not the
cause of a crash, but every restart recompiles from scratch, which makes
startup and recovery slower. Fix: grant the service account the missing role on
the bucket, or point the cache at a bucket it administers. Report it as a
contributing issue, and keep looking for the actual failure.

**`FAILED_PRECONDITION` on cache object updates** (e.g. updating an object's
metadata or custom time): possibly several writers updating the same cache
object at once. Like the race above, it is usually retried or skipped. If it
repeats on every startup, try the GCSFuse mount above or a separate cache
prefix per job, and compare startup time with and without the cache.

## 8. Lost connection to peer

One of these errors:

```
XlaRuntimeError: DEADLINE_EXCEEDED: lost connection to peer
DATA_LOSS: Pipe from scheduler to aggregator
```

A TPU worker likely exited either due to a hardware failure or a software fatal
error like OOMs. The GKE instance ID is generally part of the error message and
should be used to navigate to the instance logs to find more pointers for
determining the root cause. Check `--action=interruptions` and
`--action=node-ooms` for that host around the time of the error: a preemption
or host OOM there is the root cause (see the cascade in
[4](#4-sigterm-received-by-pid-1) and [2](#2-host-oom-kills-and-memory-pressure-evictions)).

## 9. ALTS handshake error from a client outside Google Cloud

```
Status 11 from handshaker service: Input frame length is out of range
```

This indicates an auth mismatch between the IFRT proxy client and the server.
IFRT Proxy uses ALTS for authentication by default. ALTS handshaker is running
on GCP VMs by default, so if your JAX client is running on a non GCP VM, this
error is expected. To fix, disable authentication on both the proxy client and
server by adding this environment variable to the JAX process and IFRT proxy
container: IFRT\_PROXY\_USE\_INSECURE\_GRPC\_CREDENTIALS="true".
This turns off authentication and encryption of the proxy traffic, so use it
only on a trusted network. To keep ALTS, run the JAX client on Google Cloud
instead, for example in the same GKE pod as the proxy.

## 10. Cloud Storage lifecycle prefix limit

```
INVALID_ARGUMENT : Permanent error, with a last message of Lifecycle matches_prefix cannot specify more than 50 prefixes per config.; Error while initializing persistent cache storage Cloud Storage
```

This error occurs if the Cloud Storage bucket passed in to the
\--gcs\_scratch\_location flag has reached the maximum lifecycle policy limit.
If this occurs, clean up Cloud Storage lifecycle policies that are no longer
being used. To avoid hitting this issue repeatedly, consider using a common
prefix across all your workloads.

## 11. JAX and Pathways version mismatch

One of these errors:

```
IFRT Proxy client and server failed to agree on the protocol version; supported versions: client = [1, 1], server = [3, 14]
ValueError: Failed to deserialize the Mosaic module: INTERNAL: Unsupported version: expected <= 7 but got 8
```

This indicates that your pathways images are incompatible with the JAX version
you are using. Please ensure that you are using a pathways image tag jax-0.x.y
matching your JAX version.

Check the versions first: compare the client's JAX, jaxlib and pathwaysutils
versions (`pip show jax jaxlib pathwaysutils`) with the Pathways server and
proxy image tags and the `Build label` they log at startup, and report both in
the answer.

## 12. Pods stuck in ImagePullBackOff or ErrImagePull

Go through these steps in order, and include each one in the report:

1.  Read the exact pull error in the pod events (`--action=pod-events` or
    `kubectl describe pod`): a missing tag or manifest (`manifest unknown`,
    `not found`), a permission error, or a network timeout.
2.  For a missing tag or manifest, list the tags that exist in the registry
    (`gcloud artifacts docker tags list <repository>/<image>` or
    `gcloud artifacts docker images list <repository>`).
3.  Switch to a published tag that matches the workload's JAX version. For a
    permission error, check that the node service account can pull from that
    repository instead.

The Pathways containers never started, so their logs are empty: do not look
for the root cause there.

## 13. Port collisions with hostNetwork

Pathways pods usually run with `hostNetwork: true`, so the Pathways ports (RM,
proxy, worker, Megascale) and any extra ports (e.g. metrics exporters enabled
with debugging flags) are shared by every container in the pod and every pod on
the node. Look for `Address already in use` or other bind errors, `Init:Error`,
or `FailedScheduling ... didn't have free ports`. Use `--action=neighbors` to
see what else ran on the node.

## 14. The job hangs without failing

When nothing reports an error, go through these steps in order:

1.  Find the last progress line of every container: user steps
    (`completed step`), RM slice state (`Slices Now Ready`, placed or unplaced
    slices), worker program launches, and proxy requests. Use
    `--order=desc --first_per_pod=1` with `--min_severity=DEFAULT` on each
    container action to get each pod's latest line.
2.  The component that stopped first is the lead.
3.  Check for pods that are Pending, missing or restarted
    (`--action=pod-events`).
4.  Check the Megascale stall detectors (`HANG_DETECTED`, `--action=workers`).

## 15. Proxy-to-worker transfers stall

The proxy repeats `Still waiting to acquire semaphore for destination ... to
send Chunk`, the workers log `Recv completion error`, and the gRPC transport
may later fail with `GOAWAY` (`ping_timeout` or `settings_timeout`). The client
usually just stops making progress, often while restoring a checkpoint or doing
another large host-to-device transfer through the proxy. This means
host-to-device transfers from the IFRT proxy to the workers stalled: it is a
Pathways runtime issue, not Orbax, Cloud Storage or user code. The `proxy` and
`workers` actions match these lines.

-   Check for an image regression: compare the server and proxy image tags and
    `Build label`s of the failing run with the last run of the same workload
    that passed. If they differ, run on the last-good images and report the
    change to Google Cloud support with the logs.
-   Workaround: avoid sending the checkpoint data through the proxy. Call
    `pathwaysutils.initialize()` before creating the Orbax checkpoint manager,
    so restores use the Pathways checkpoint handler
    (`CloudPathwaysArrayHandler`) and the workers read Cloud Storage directly.
scripts/
debug_workload.py 53.3 KB
#!/usr/bin/env python3
r"""CLI helper to filter and analyze logs for Pathways on Cloud GKE workloads.

It constructs optimized queries for GCP Cloud Logging and provides commands
to read logs from GKE containers and nodes.

This script is shared with EXTERNAL users. It only depends on the Python 3
standard library and the gcloud CLI, so it runs without installing packages.
"""

import argparse
from collections.abc import Callable, Sequence
import dataclasses
import datetime
import json
import re
import shlex
import subprocess
import sys
from typing import Any
import urllib.parse


class UsageError(Exception):
  """Raised for invalid command-line usage."""


@dataclasses.dataclass
class _Flag:
  """A command-line flag; `value` is set by `_parse_flags`."""

  name: str
  value: Any
  multi: bool = False


_PARSER = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    allow_abbrev=False,
)
_FLAGS: list[_Flag] = []


def _define(
    name: str, default: Any, help_text: str, multi: bool = False, **kwargs: Any
) -> _Flag:
  """Registers the command-line flag --<name> and returns its handle.

  Args:
    name: Flag name, without the leading dashes.
    default: Value used when the flag is not given.
    help_text: Help text shown by --help.
    multi: Whether the flag can be repeated; its value is then a list.
    **kwargs: Extra arguments for `argparse.ArgumentParser.add_argument`.

  Returns:
    The flag, whose `value` is set by `_parse_flags`.
  """
  flag = _Flag(name, default, multi)
  _FLAGS.append(flag)
  _PARSER.add_argument(
      f"--{name}",
      dest=name,
      default=None if multi else default,
      help=help_text,
      **kwargs,
  )
  return flag


def _parse_bool(value: str) -> bool:
  """Parses a boolean flag value such as true/false, yes/no or 1/0."""
  if value.lower() in ("true", "t", "1", "yes", "y"):
    return True
  if value.lower() in ("false", "f", "0", "no", "n"):
    return False
  raise argparse.ArgumentTypeError(f"invalid boolean value: {value!r}")


def _parse_list(value: str) -> list[str]:
  """Parses a comma-separated flag value into a list of non-empty items."""
  return [v.strip() for v in value.split(",") if v.strip()]


def _define_string(
    name: str, default: str | None, help_text: str, required: bool = False
) -> _Flag:
  """Defines a string flag."""
  return _define(name, default, help_text, required=required)


def _define_integer(name: str, default: int, help_text: str) -> _Flag:
  """Defines an integer flag."""
  return _define(name, default, help_text, type=int)


def _define_enum(
    name: str, default: str | None, choices: Sequence[str], help_text: str
) -> _Flag:
  """Defines a string flag restricted to `choices`."""
  return _define(name, default, help_text, choices=choices)


def _define_boolean(name: str, default: bool, help_text: str) -> _Flag:
  """Defines --<name>, --<name>=true|false and --no<name>."""
  flag = _define(
      name, default, help_text, nargs="?", const=True, type=_parse_bool
  )
  _PARSER.add_argument(
      f"--no{name}", dest=name, action="store_false", help=argparse.SUPPRESS
  )
  return flag


def _define_list(name: str, default: list[str], help_text: str) -> _Flag:
  """Defines a comma-separated list flag."""
  return _define(name, default, help_text, type=_parse_list)


def _define_multi_string(
    name: str, default: list[str], help_text: str
) -> _Flag:
  """Defines a flag that can be repeated; its value is the list of values."""
  del default  # Always [] when the flag is not given.
  return _define(name, [], help_text, multi=True, action="append")


def _parse_flags(argv: Sequence[str]) -> None:
  """Parses `argv` (without the program name) into the defined flags."""
  args = _PARSER.parse_args(argv)
  for flag in _FLAGS:
    value = getattr(args, flag.name)
    flag.value = (value or []) if flag.multi else value
  if _START_TIME.value and _END_TIME.value and _DURATION.value:
    raise UsageError(
        "At most two of --start_time, --end_time and --duration may be"
        " specified."
    )


_PROJECT = _define_string(
    "project",
    None,
    "GCP project ID. Please verify with the user if this is correct.",
    required=True,
)
_CLUSTER_NAME = _define_string(
    "cluster_name", None, "Target GKE cluster name", required=True
)
_LOCATION = _define_string(
    "location", None, "Cluster location (zone or region)", required=True
)
_JOBSET_NAME = _define_string(
    "jobset_name",
    None,
    "k8s JobSet name. Shorthand for --workload=jobset:<name>.",
)
_LWS_NAME = _define_string(
    "lws_name",
    None,
    "LeaderWorkerSet name (e.g. Pathways inference). Shorthand for"
    " --workload=lws:<name>.",
)
_JOB_NAME = _define_string(
    "job_name",
    None,
    "Plain k8s Job name (not part of a JobSet). Shorthand for"
    " --workload=job:<name>.",
)
_POD_PREFIX = _define_string(
    "pod_prefix",
    None,
    "Pod name prefix, for workloads not created by a JobSet, LeaderWorkerSet or"
    " Job (e.g. bare pods). Shorthand for --workload=pod:<prefix>.",
)
_WORKLOADS = _define_multi_string(
    "workload",
    [],
    "Workload to debug as <kind>:<name>, where <kind> is one of jobset, lws,"
    " job or pod (pod name prefix). Repeat the flag to query several workloads"
    " together, e.g. a JobSet plus a JAX client or proxy that runs in its own"
    " Job: --workload=jobset:my-pw --workload=job:my-client. Combined with"
    " --jobset_name, --lws_name, --job_name and --pod_prefix.",
)
_NAMESPACE = _define_string("namespace", "default", "k8s namespace")
_SIDECAR_CONTAINER = _define_string(
    "sidecar_container",
    "colocated-python-sidecar",
    "Container name of the colocated Python sidecar. Workloads may use a"
    " custom name: it is the container running next to `pathways-worker` in"
    " the TPU worker pods (see the JobSet YAML or the pods' container names).",
)

_START_TIME = _define_string(
    "start_time",
    None,
    "Start timestamp (ISO 8601 / RFC 3339, e.g. 2026-10-22T00:00:00Z)."
    " Timestamps without a timezone are interpreted as UTC.",
)
_END_TIME = _define_string(
    "end_time",
    None,
    "End timestamp (ISO 8601 / RFC 3339, e.g. 2026-10-22T02:00:00Z)."
    " Timestamps without a timezone are interpreted as UTC.",
)
_DURATION = _define_string(
    "duration",
    None,
    "Length of the time window, e.g. 30s, 30m, 2h, 1d, or combinations such"
    " as 1h30m. With --start_time, the window is [start, start + duration];"
    " with --end_time, it is [end - duration, end]; on its own, it is"
    " [now - duration, now]. Cannot be combined with both --start_time and"
    " --end_time.",
)

_ACTION = _define_enum(
    "action",
    "summary",
    [
        "summary",
        "errors",
        "user-workload",
        "proxy",
        "pathways-rm",
        "workers",
        "colocated-python-sidecar",
        "pod-events",
        "node-ooms",
        "interruptions",
        "neighbors",
        "elastic",
        "preflight",
    ],
    "The debugging target or action to perform. Run `preflight` first: it"
    " checks log access and that the workload logged in the time window (it"
    " always runs, with or without --execute).",
)

_EXECUTE = _define_boolean(
    "execute",
    False,
    "If True, will attempt to run the constructed gcloud command locally.",
)

_LIMIT = _define_integer(
    "limit", 100, "Maximum number of log entries to fetch if executing."
)

_ORDER = _define_enum(
    "order",
    "asc",
    ["asc", "desc"],
    "Sort order of returned entries. 'asc' (default) returns the earliest"
    " entries in the time window first, which is what you want when chasing"
    " the first error. Use 'desc' to find the latest progress (e.g. the last"
    " completed step).",
)

_NODE_NAMES = _define_list(
    "node_names",
    [],
    "GKE node names (e.g. gke-tpu-1a2b3c4d-xyz1) the workload ran on, used by"
    " --action=node-ooms and --action=neighbors. If omitted with --execute,"
    " they are discovered from the pods' 'Scheduled' events.",
)

_EXTRA_TERMS = _define_multi_string(
    "extra_terms",
    [],
    "Additional plain-text strings to match, appended to the built-in list of"
    " progress/error strings of the action (OR-ed together). Repeat the flag"
    " for multiple strings, e.g. --extra_terms='train_step'"
    " --extra_terms='loss is nan'. Use it for workload-specific log lines"
    " (e.g. non-MaxText step markers). Only supported by actions with a"
    " built-in list: errors, user-workload, proxy, pathways-rm, workers.",
)

_MIN_SEVERITY = _define_enum(
    "min_severity",
    None,
    ["DEFAULT", "DEBUG", "INFO", "NOTICE", "WARNING", "ERROR", "CRITICAL"],
    "Also match every log line at or above this severity (e.g. WARNING or"
    " ERROR), OR-ed with the built-in list and --extra_terms. Use it to catch"
    " problems the built-in list does not know about, e.g. on the workers or"
    " the RM. DEFAULT matches every line, for errors that are logged at INFO."
    " Note: non-first lines of multiline logs may show up as ERROR."
    " Only supported by the same actions as --extra_terms.",
)

_FIRST_PER_POD = _define_integer(
    "first_per_pod",
    0,
    "If > 0 (with --execute), keep only the first N matching entries of each"
    " pod/container (in --order) plus its last matching entry, so a few chatty"
    " pods or a cascade across hundreds of pods do not fill --limit, while a"
    " fatal error at the end of a pod's log is still shown. Fetches up to"
    " --fetch_limit entries and prints at most --limit of the kept ones.",
)

_FETCH_LIMIT = _define_integer(
    "fetch_limit",
    1000,
    "Maximum entries fetched from Cloud Logging when --first_per_pod is set."
    " Larger values cover more pods but are slower; narrow the time window"
    " first.",
)

_QUERY_TIMEOUT = _define_integer(
    "query_timeout",
    180,
    "Seconds to wait for each gcloud query (with --execute) before giving up"
    " on it. Free-text searches over large or old time windows can take many"
    " minutes; on a timeout, narrow the window or run the printed gcloud"
    " command directly. Also applies to node discovery and --first_per_pod"
    " fetches (up to --fetch_limit entries); raise it (e.g. 600) for very"
    " large workloads. 0 waits forever.",
)

# Node names per query for node-scoped actions (node-ooms, neighbors); larger
# node sets are queried in batches to stay under Cloud Logging's filter length
# limit.
_NODE_BATCH_SIZE = 200

# How far before the query window to look for the pods' "Scheduled" events
# when discovering the workload's nodes (pods are often scheduled well before
# the failure).
_NODE_DISCOVERY_LOOKBACK = datetime.timedelta(hours=24)

_BASE_CONSOLE_URL = "https://console.cloud.google.com/logs/query"

# Workload kinds accepted by --workload, mapped to the Cloud Logging pod label
# that identifies their pods. Cloud Logging stores pod labels with "." replaced
# by "_". `pod` has no label; it matches pod names by prefix.
_KIND_LABELS = {
    "jobset": "k8s-pod/jobset_sigs_k8s_io/jobset-name",
    "lws": "k8s-pod/leaderworkerset_sigs_k8s_io/name",
    "job": "k8s-pod/batch_kubernetes_io/job-name",
    "pod": None,
}


@dataclasses.dataclass(frozen=True)
class Target:
  """One workload object to debug.

  Attributes:
    kind: One of `_KIND_LABELS` (jobset, lws, job or pod).
    name: The object name, or a pod name prefix for kind `pod`.
  """

  kind: str
  name: str


@dataclasses.dataclass(frozen=True)
class Workload:
  """Identifies the GKE workload being debugged.

  Attributes:
    project: GCP project ID that owns the GKE cluster.
    cluster: Name of the GKE cluster running the workload.
    location: Zone or region of the GKE cluster.
    targets: The JobSets, LeaderWorkerSets, Jobs or pod name prefixes that make
      up the workload. Logs of all of them are queried together.
    namespace: k8s namespace the workload runs in.
    node_names: GKE node (VM instance) names the workload's pods ran on. Used to
      scope node-level logs that carry no cluster label (serial console).
    sidecar_container: Container name of the colocated Python sidecar.
  """

  project: str
  cluster: str
  location: str
  targets: tuple[Target, ...]
  namespace: str
  node_names: tuple[str, ...] = ()
  sidecar_container: str = "colocated-python-sidecar"

  @property
  def names(self) -> tuple[str, ...]:
    """Names of the targets; pods of every kind are named with this prefix."""
    return tuple(t.name for t in self.targets)


def parse_targets(
    workloads: Sequence[str],
    jobset: str | None = None,
    lws: str | None = None,
    job: str | None = None,
    pod_prefix: str | None = None,
) -> tuple[Target, ...]:
  """Builds the workload targets from --workload and the shorthand flags.

  Args:
    workloads: Values of --workload, each `<kind>:<name>`.
    jobset: Value of --jobset_name.
    lws: Value of --lws_name.
    job: Value of --job_name.
    pod_prefix: Value of --pod_prefix.

  Returns:
    The de-duplicated targets, in the order given.

  Raises:
    ValueError: If a --workload value is malformed or no target is given.
  """
  targets = []
  for value in workloads:
    kind, sep, name = value.partition(":")
    kind = kind.strip().lower()
    name = name.strip()
    if not sep or kind not in _KIND_LABELS or not name:
      raise ValueError(
          f"Invalid --workload {value!r}; expected <kind>:<name> with kind one"
          f" of {', '.join(_KIND_LABELS)}."
      )
    targets.append(Target(kind, name))
  for kind, name in (
      ("jobset", jobset),
      ("lws", lws),
      ("job", job),
      ("pod", pod_prefix),
  ):
    if name:
      targets.append(Target(kind, name))
  if not targets:
    raise ValueError(
        "Specify the workload with --jobset_name, --lws_name, --job_name,"
        " --pod_prefix or --workload."
    )
  return tuple(dict.fromkeys(targets))


# ---------------------------------------------------------------------------
# Query building helpers.
# ---------------------------------------------------------------------------


_DURATION_UNITS = {
    "s": "seconds",
    "m": "minutes",
    "h": "hours",
    "d": "days",
    "w": "weeks",
}
_DURATION_RE = re.compile(r"(\d+(?:\.\d+)?)([smhdw])")


def parse_duration(value: str) -> datetime.timedelta:
  """Parses a duration such as `30m`, `2h` or `1h30m` into a timedelta.

  Args:
    value: The duration string. A leading `-` or `+` is ignored.

  Returns:
    The parsed (positive) duration.

  Raises:
    ValueError: If `value` is not a valid, non-zero duration.
  """
  text = value.strip().lower().lstrip("+-")
  if not text or _DURATION_RE.sub("", text):
    raise ValueError(
        f"Invalid duration {value!r}; expected e.g. 30s, 30m, 2h, 1d, 1h30m."
    )
  delta = datetime.timedelta()
  for amount, unit in _DURATION_RE.findall(text):
    delta += datetime.timedelta(**{_DURATION_UNITS[unit]: float(amount)})
  if not delta:
    raise ValueError(f"Duration {value!r} must be greater than zero.")
  return delta


def parse_timestamp(value: str) -> datetime.datetime:
  """Parses an ISO 8601 timestamp, assuming UTC if no timezone is given.

  Args:
    value: The timestamp string, e.g. `2026-10-22T00:00:00Z`.

  Returns:
    A timezone-aware datetime.

  Raises:
    ValueError: If `value` is not a valid ISO 8601 timestamp.
  """
  text = value.strip()
  # `fromisoformat` only accepts a trailing "Z" from Python 3.11 onwards.
  if text.endswith(("Z", "z")):
    text = text[:-1] + "+00:00"
  try:
    ts = datetime.datetime.fromisoformat(text)
  except ValueError as e:
    raise ValueError(
        f"Invalid timestamp {value!r}; expected ISO 8601, e.g."
        " 2026-10-22T00:00:00Z."
    ) from e
  if ts.tzinfo is None:
    ts = ts.replace(tzinfo=datetime.timezone.utc)
  return ts


def _to_rfc3339(ts: datetime.datetime) -> str:
  """Formats `ts` as an RFC 3339 UTC timestamp accepted by Cloud Logging."""
  return (
      ts.astimezone(datetime.timezone.utc)
      .isoformat(timespec="seconds")
      .replace("+00:00", "Z")
  )


def compute_time_range(
    start_time: str | None,
    end_time: str | None,
    duration: str | None,
    now: datetime.datetime | None = None,
) -> tuple[datetime.datetime | None, datetime.datetime | None]:
  """Resolves the start/end of the query window from the given parameters.

  Args:
    start_time: Optional ISO 8601 start timestamp.
    end_time: Optional ISO 8601 end timestamp.
    duration: Optional window length, e.g. `2h`.
    now: The current time; defaults to `datetime.now(UTC)`.

  Returns:
    A `(start, end)` tuple; either element may be None (unbounded).

  Raises:
    ValueError: If all three parameters are given, a value fails to parse, or
      the resulting start is after the end.
  """
  if start_time and end_time and duration:
    raise ValueError(
        "At most two of start_time, end_time and duration may be specified."
    )
  start = parse_timestamp(start_time) if start_time else None
  end = parse_timestamp(end_time) if end_time else None
  if duration:
    delta = parse_duration(duration)
    if start:
      end = start + delta
    elif end:
      start = end - delta
    else:
      end = now or datetime.datetime.now(datetime.timezone.utc)
      start = end - delta
  if start and end and start > end:
    raise ValueError(
        f"Start time {_to_rfc3339(start)} is after end time {_to_rfc3339(end)}."
    )
  return start, end


def get_time_filter() -> list[str]:
  """Constructs the time filter part of the query.

  The window is derived from --start_time, --end_time and --duration and is
  always emitted as RFC 3339 timestamps, as required by Cloud Logging.

  Returns:
    A list of timestamp filter clauses (may be empty).
  """
  try:
    start, end = compute_time_range(
        _START_TIME.value, _END_TIME.value, _DURATION.value
    )
  except ValueError as e:
    raise UsageError(str(e)) from e
  filters = []
  if start:
    filters.append(f'timestamp >= "{_to_rfc3339(start)}"')
  if end:
    filters.append(f'timestamp <= "{_to_rfc3339(end)}"')
  return filters


def _quote(term: str) -> str:
  """Quotes a plain-text term as a Cloud Logging string literal."""
  return '"' + term.replace("\\", "\\\\").replace('"', '\\"') + '"'


def _any_of(*terms: str) -> list[str]:
  """Returns query lines matching any of the given (already quoted) terms."""
  first, *rest = terms
  return ["(", f"  {first}"] + [f"  OR {term}" for term in rest] + [")"]


def _cluster_filters(
    w: Workload, resource_type: str | None = None
) -> list[str]:
  """Returns filters scoping logs to the workload's GKE cluster."""
  filters = [f'resource.type="{resource_type}"'] if resource_type else []
  filters += [
      f'resource.labels.project_id="{w.project}"',
      f'resource.labels.cluster_name="{w.cluster}"',
      f'resource.labels.location="{w.location}"',
  ]
  return filters


def _target_filter(t: Target) -> str:
  """Returns the clause matching the container logs of one target's pods."""
  label = _KIND_LABELS[t.kind]
  if label is None:
    return f"resource.labels.pod_name:{_quote(t.name)}"
  return f'labels."{label}"={_quote(t.name)}'


def _pod_name_filter(w: Workload) -> str:
  """Matches pods of any target by name prefix (for logs without pod labels).

  Kubernetes events and other `k8s_pod` logs carry no pod labels, but the pods
  of a JobSet, LeaderWorkerSet or Job are named after it.

  Args:
    w: The workload.

  Returns:
    A single filter clause.
  """
  clauses = [f"resource.labels.pod_name:{_quote(n)}" for n in w.names]
  return clauses[0] if len(clauses) == 1 else f"({' OR '.join(clauses)})"


def _jobset_container_filters(w: Workload) -> list[str]:
  """Returns filters scoping logs to containers belonging to the workload."""
  clauses = [_target_filter(t) for t in w.targets]
  target = clauses[0] if len(clauses) == 1 else f"({' OR '.join(clauses)})"
  return _cluster_filters(w, "k8s_container") + [
      f'resource.labels.namespace_name="{w.namespace}"',
      target,
  ]


def _flatten(query: str) -> str:
  """Flattens a multi-line query onto a single line for shell usage."""
  return query.replace("\n", " ").strip()


# ---------------------------------------------------------------------------
# Per-action query builders.
# ---------------------------------------------------------------------------


def summary_query(w: Workload) -> list[str]:
  """Gathers general events and lifecycle details of the workload.

  Matches Kubernetes events whose object name contains a target name, and the
  JobSet / LeaderWorkerSet controller logs that mention it.

  Args:
    w: The workload.

  Returns:
    The Cloud Logging filter clauses, one per line.
  """
  objects = " OR ".join(_quote(n) for n in w.names)
  return _cluster_filters(w) + [
      "(",
      (
          '  (resource.type="k8s_cluster" AND'
          f" jsonPayload.involvedObject.name:({objects}))"
      ),
      "  OR",
      (
          '  (resource.type="k8s_container" AND'
          ' resource.labels.namespace_name=("jobset-system" OR "lws-system")'
          f" AND textPayload:({objects}))"
      ),
      ")",
  ]


_CRASH_TERMS = (
    '"SIGSEGV"',
    '"SIGABRT"',
    '"SIGBUS"',
    '"SIGILL"',
    '"SIGFPE"',
    '"Check failed"',
    '"RET_CHECK failure"',
    '"Raising signal"',
    '"Fatal Python error"',
    '"Traceback (most recent call last)"',
    '"terminate called"',
    '"OOMKilled"',
    '"Killed process"',
    '"Memory cgroup out of memory"',
    # Fatal errors that are not crashes and may be logged at INFO or WARNING.
    '"Check failure stack trace"',
    '"Unknown command line flag"',
    '"Address already in use"',
    '"incarnation ID mismatch"',
    '"PermissionDenied"',
    '"403 Forbidden"',
)


def errors_query(w: Workload) -> list[str]:
  """Crash-signature sweep across every container of the workload.

  Container-specific actions only match known progress/error strings, so they
  can miss crashes (e.g. a segfault in pathways-rm). Run this first, ordered
  ascending, and chase the earliest hit. Matches `_CRASH_TERMS`.

  Args:
    w: The workload.

  Returns:
    The Cloud Logging filter clauses, one per line.
  """
  return _jobset_container_filters(w)


def user_workload_query(w: Workload) -> list[str]:
  """Filters user workload container logs; matches `_USER_WORKLOAD_TERMS`."""
  # Omit pathways infrastructure containers to find custom named main user
  # containers
  return _jobset_container_filters(w) + [
      'resource.labels.container_name!="pathways-rm"',
      'resource.labels.container_name!="pathways-proxy"',
      'resource.labels.container_name!="pathways-worker"',
      f'resource.labels.container_name!="{w.sidecar_container}"',
  ]


# Progress and error strings of the user workload (JAX) container. Some are
# framework specific (e.g. "completed step" is logged by MaxText); pass
# --extra_terms for other frameworks.
_USER_WORKLOAD_TERMS = (
    '"completed step"',
    '"XPK Start"',
    '"XPK End"',
    '"started goodput"',
    '"Final goodput"',
    '"Restoring checkpoint"',
    '"[process=0] [sync] Finished load"',
    '"Shutting down cumulative goodput process"',
    '"commit_success"',
    '"Fatal Python error:"',
    '"Dict key mismatch"',
    '"Error opening \\"zarr\\" driver"',
    "\"CRITICAL - Timeout from watchdog 'step-timebomb'\"",
    '"RemoteIterator"',
    '"jax.errors.JaxRuntimeError"',
    '"Unable to initialize backend"',
    '"Connecting to IFRT proxy server"',
    '"RESOURCE_EXHAUSTED"',
    *_CRASH_TERMS,
)


def proxy_query(w: Workload) -> list[str]:
  """Queries proxy server logs; matches `_PROXY_TERMS`."""
  return _jobset_container_filters(w) + [
      'resource.labels.container_name="pathways-proxy"'
  ]


# Startup, RM connectivity and error strings of the proxy server.
_PROXY_TERMS = (
    '"IFRT proxy server started"',
    '"IFRT proxy server was terminated"',
    '"Starting new IFRT session"',
    # Repeated "Connection refused" to the RM port (29001) or "not yet
    # heard from" means the resource manager is down or crash-looping.
    '"Connection refused"',
    '"not yet heard from"',
    '"Build label"',
    # Host-to-device transfers from the proxy to the workers are stalled.
    '"Still waiting to acquire semaphore"',
    '"GOAWAY"',
    *_CRASH_TERMS,
)


def pathways_rm_query(w: Workload) -> list[str]:
  """Queries Pathways RM logs; matches `_PATHWAYS_RM_TERMS`."""
  return _jobset_container_filters(w) + [
      'resource.labels.container_name="pathways-rm"'
  ]


# Slice placement, availability, and allocation transitions in Pathways RM.
_PATHWAYS_RM_TERMS = (
    # "Build label" is logged once per process start, so repeated hits
    # mean the RM container is restarting (crash loop).
    '"Build label"',
    '"Pathways Server serving on"',
    '"now ready"',
    '"slice ready"',
    '"New slice available"',
    '"Sufficient slices active"',
    '"Setting new slice event"',
    '"remaining assignable"',
    '"reason: \\"Job cancelled due to"',
    '"expected topology"',
    '"Newly added slice topology"',
    *_CRASH_TERMS,
)


def workers_query(w: Workload) -> list[str]:
  """Queries leader worker logs (`completion-index=0`) to isolate early failures.

  Matches `_WORKERS_TERMS`. The leader filter only applies when every target is
  a JobSet or Job; LeaderWorkerSet and bare-pod workloads get all workers.

  Args:
    w: The workload.

  Returns:
    The Cloud Logging filter clauses, one per line.
  """
  filters = _jobset_container_filters(w) + [
      'resource.labels.container_name="pathways-worker"',
  ]
  if all(t.kind in ("jobset", "job") for t in w.targets):
    # Target the leader pods to reduce logging noise significantly.
    # Cloud Logging stores pod labels with "." replaced by "_".
    filters.append(
        'labels."k8s-pod/batch_kubernetes_io/job-completion-index"="0"'
    )
  return filters


# Hang and error strings of the Pathways workers.
_WORKERS_TERMS = (
    '"The host that have no TPU program running:"',
    '"Megascale hang detected"',
    '"Megascale detects a hang"',
    '"HANG_DETECTED"',
    '"FAILED_PRECONDITION"',
    '"jax.errors.JaxRuntimeError"',
    # Transfers from the proxy did not arrive (see the proxy's
    # "Still waiting to acquire semaphore").
    '"Recv completion error"',
    *_CRASH_TERMS,
)


def colocated_python_sidecar_query(w: Workload) -> list[str]:
  """Queries colocated Python sidecar logs (container `w.sidecar_container`)."""
  return _jobset_container_filters(w) + [
      f'resource.labels.container_name="{w.sidecar_container}"',
  ]


def pod_events_query(w: Workload) -> list[str]:
  """Kubernetes events for the workload's pods (scheduling, kills, OOMs, ...).

  Kubernetes only keeps events for about an hour, so `kubectl get events` is
  empty for past incidents; Cloud Logging keeps them.

  Args:
    w: The workload.

  Returns:
    The Cloud Logging filter clauses, one per line.
  """
  return _cluster_filters(w, "k8s_pod") + [
      'log_id("events")',
      f'resource.labels.namespace_name="{w.namespace}"',
      _pod_name_filter(w),
      # Drop routine lifecycle noise; keep Killing, BackOff, OOMKilling,
      # Evicted, FailedScheduling, Preempted, Unhealthy, FailedMount, ...
      (
          'NOT jsonPayload.reason=("Pulling" OR "Pulled" OR "Created" OR'
          ' "Started" OR "Scheduled")'
      ),
  ]


def node_ooms_query(w: Workload) -> list[str]:
  """Out-of-memory kills and memory-pressure evictions on the cluster's nodes.

  Head-pod OOMs (JAX client, proxy, RM) often never reach container logs. They
  show up as node-problem-detector events (OOMKilling/SystemOOM), kernel
  "Memory cgroup out of memory" lines, and serial-console output.

  The kubelet can also run out of node memory before the kernel does: it then
  evicts pods ("The node was low on resource: memory. Container X was using
  ...") and records EvictionThresholdMet / NodeHasInsufficientMemory node
  events. There is no kernel OOM kill in that case, so these are matched too.
  Evictions for other resources (e.g. ephemeral-storage) also match; the
  message names the resource.

  Serial-console logs live on `gce_instance`, which has no cluster label, and
  TPU node VMs are named gke-tpu-<hash>, so they are scoped to the workload's
  nodes (`w.node_names`, see `discover_workload_nodes`). Without node names they
  fall back to the cluster's zone, which can include unrelated VMs.

  Args:
    w: The workload.

  Returns:
    The Cloud Logging filter clauses, one per line: the OR of
    `node_ooms_parts`, for the printed link and gcloud command.
  """
  lines = ["("]
  for i, (_, clauses) in enumerate(node_ooms_parts(w)):
    if i:
      lines.append("  OR")
    lines += ["  ("] + [f"    {c}" for c in clauses] + ["  )"]
  return lines + [")"]


def node_ooms_parts(w: Workload) -> list[tuple[str, list[str]]]:
  """The parts of `node_ooms_query`, run one by one with --execute.

  The combined query can take many minutes or fail with a backend error on
  large or old time windows, mostly because of the free-text kernel log search.
  Running the parts separately (fast, indexed ones first) means the others
  still answer when one of them times out.

  Args:
    w: The workload.

  Returns:
    (label, filter clauses) pairs.
  """
  if w.node_names:
    names = " OR ".join(f'"{n}"' for n in w.node_names)
    serial_scope = f'labels."compute.googleapis.com/resource_name"=({names})'
    # Other workloads' OOMs on the cluster's other nodes are noise and can
    # fill --limit, so node logs are scoped to the workload's nodes too.
    node_scope = [f"resource.labels.node_name=({names})"]
  else:
    serial_scope = f'resource.labels.zone:"{w.location}"'
    node_scope = []
  return [
      (
          "node OOM and memory-pressure events",
          _cluster_filters(w, "k8s_node")
          + node_scope
          + [
              'log_id("events")',
              (
                  'jsonPayload.reason:("OOMKilling" OR "SystemOOM" OR'
                  ' "EvictionThresholdMet" OR "NodeHasInsufficientMemory")'
              ),
          ],
      ),
      (
          "pod evictions (any resource; the message names it)",
          _cluster_filters(w, "k8s_pod")
          + [
              'log_id("events")',
              f'resource.labels.namespace_name="{w.namespace}"',
              _pod_name_filter(w),
              'jsonPayload.reason="Evicted"',
          ],
      ),
      (
          "kernel OOM lines in node logs",
          _cluster_filters(w, "k8s_node")
          + node_scope
          + [
              'NOT log_id("events")',
              (
                  '("Memory cgroup out of memory" OR "Out of memory" OR'
                  ' "oom_reaper" OR "oom-kill")'
              ),
          ],
      ),
      (
          "serial console of the nodes",
          [
              'resource.type="gce_instance"',
              f'resource.labels.project_id="{w.project}"',
              serial_scope,
              'log_id("serialconsole.googleapis.com/serial_port_1_output")',
              '"Memory cgroup out of memory"',
          ],
      ),
  ]


def interruptions_query(w: Workload) -> list[str]:
  """Node pool / node / VM interruptions: preemption, maintenance, host errors."""
  return [
      "(",
      "  (",
      *(f"    {f}" for f in _cluster_filters(w, "gke_nodepool")),
      "  )",
      "  OR",
      "  (",
      *(f"    {f}" for f in _cluster_filters(w, "k8s_node")),
      '    log_id("events")',
      (
          '    jsonPayload.reason:("NodeNotReady" OR "Rebooted" OR'
          ' "NodeShutdown" OR "TerminationEvent" OR "PreemptionEvent" OR'
          ' "MaintenanceEvent")'
      ),
      "  )",
      "  OR",
      "  (",
      '    resource.type="gce_instance"',
      f'    resource.labels.project_id="{w.project}"',
      f'    resource.labels.zone:"{w.location}"',
      '    log_id("cloudaudit.googleapis.com/system_event")',
      (
          '    protoPayload.methodName:("compute.instances.preempted"'
          ' OR "compute.instances.hostError"'
          ' OR "compute.instances.automaticRestart"'
          ' OR "compute.instances.terminateOnHostMaintenance")'
      ),
      "  )",
      ")",
  ]


def neighbors_query(w: Workload) -> list[str]:
  """Container logs from every pod on the workload's nodes, in any namespace.

  Shows other workloads that shared the nodes (e.g. another job's resource
  manager on the same host and port) and the actual container names of the
  workload's own pods (e.g. a custom-named colocated Python sidecar). GKE
  container logs carry the node name in `compute.googleapis.com/resource_name`.

  Args:
    w: The workload. `w.node_names` must be set (see `discover_workload_nodes`).

  Returns:
    The Cloud Logging filter clauses, one per line.
  """
  names = " OR ".join(_quote(n) for n in w.node_names)
  return _cluster_filters(w, "k8s_container") + [
      f'labels."compute.googleapis.com/resource_name"=({names})',
  ]


def elastic_query(w: Workload) -> list[str]:
  """Elastic recovery timeline from the user workload and the RM.

  Matches `_ELASTIC_TERMS` in every container except the workers and the
  colocated Python sidecar (i.e. the JAX client, pathways-rm and the proxy).

  Args:
    w: The workload.

  Returns:
    The Cloud Logging filter clauses, one per line.
  """
  return _jobset_container_filters(w) + [
      'resource.labels.container_name!="pathways-worker"',
      f'resource.labels.container_name!="{w.sidecar_container}"',
  ]


# Slice loss/return, recovery attempts, and snapshot/checkpoint restore steps
# logged by pathways-rm and the elastic training loop (pathwaysutils, MaxText).
_ELASTIC_TERMS = (
    '"Slices Now Ready"',
    '"placed -> unplaced"',
    '"Unassigning"',
    '"Elastic attempt"',
    '"New slices found"',
    '"in-memory snapshot"',
    '"Falling back to persistent checkpoint"',
    '"Restoring"',
    '"Resuming"',
    '"commit_success"',
    '"completed step"',
    # Include the exception that ended a recovery attempt.
    *_CRASH_TERMS,
)


@dataclasses.dataclass(frozen=True)
class LogAction:
  """A Cloud Logging based debugging action.

  Attributes:
    title: Human-readable description printed as the action header.
    build_query: Returns the Cloud Logging filter clauses (one per line) for the
      given workload, excluding time filters and match terms.
    terms: Built-in (already quoted) strings, at least one of which a log line
      must contain. Empty if the action does not filter on message content; such
      actions do not accept --extra_terms.
    needs_nodes: Whether the query is scoped to the workload's nodes, which are
      discovered from the pods' "Scheduled" events if not given.
  """

  title: str
  build_query: Callable[[Workload], list[str]]
  terms: tuple[str, ...] = ()
  needs_nodes: bool = False


_LOG_ACTIONS: dict[str, LogAction] = {
    "summary": LogAction(
        "summary (Workload events & controller manager logs)", summary_query
    ),
    "errors": LogAction(
        "errors (Crash and fatal-error sweep across all workload containers)",
        errors_query,
        _CRASH_TERMS,
    ),
    "user-workload": LogAction(
        "user-workload (User container steps & error filtering)",
        user_workload_query,
        _USER_WORKLOAD_TERMS,
    ),
    "proxy": LogAction("proxy (Proxy server logs)", proxy_query, _PROXY_TERMS),
    "pathways-rm": LogAction(
        "pathways-rm (Resource Manager slice state transitions)",
        pathways_rm_query,
        _PATHWAYS_RM_TERMS,
    ),
    "workers": LogAction(
        "workers (Leader worker logs filtering)", workers_query, _WORKERS_TERMS
    ),
    "colocated-python-sidecar": LogAction(
        "colocated-python-sidecar (Colocated Python sidecar logs)",
        colocated_python_sidecar_query,
    ),
    "pod-events": LogAction(
        "pod-events (Kubernetes events for the workload's pods)",
        pod_events_query,
    ),
    "node-ooms": LogAction(
        "node-ooms (Node-level OOM kills and memory-pressure evictions)",
        node_ooms_query,
        needs_nodes=True,
    ),
    "interruptions": LogAction(
        "interruptions (Node pool / node / VM preemption, maintenance, host"
        " errors)",
        interruptions_query,
    ),
    "neighbors": LogAction(
        "neighbors (Pods and containers that logged on the workload's nodes)",
        neighbors_query,
        needs_nodes=True,
    ),
    "elastic": LogAction(
        "elastic (Slice loss, recovery and restore timeline)",
        elastic_query,
        _ELASTIC_TERMS,
    ),
}


# ---------------------------------------------------------------------------
# Output and execution.
# ---------------------------------------------------------------------------


def _run_command(cmd: list[str], tool_name: str) -> str | None:
  """Runs `cmd`, returning its stdout, or None (after reporting) on failure."""
  timeout = _QUERY_TIMEOUT.value or None
  try:
    return subprocess.run(
        cmd, capture_output=True, text=True, check=True, timeout=timeout
    ).stdout
  except subprocess.CalledProcessError as e:
    print(f"Error executing {tool_name}: {e.stderr}")
    return None
  except subprocess.TimeoutExpired:
    print(_timeout_message(tool_name, timeout))
    return None


def _timeout_message(tool_name: str, timeout: float | None) -> str:
  """Returns the message printed when a gcloud query times out."""
  return (
      f"[timeout] {tool_name} did not finish within {timeout}s"
      " (--query_timeout). This check is INCOMPLETE, not clean: narrow the"
      " time window (or pass --node_names), raise --query_timeout, or run the"
      " printed gcloud command directly."
  )


def print_console_url(query: str, project: str) -> None:
  """Prints a clickable Cloud Console URL."""
  encoded_query = urllib.parse.quote(query.strip(), safe="")
  url = f"{_BASE_CONSOLE_URL};query={encoded_query};project={project}"
  print("--- Clickable Cloud Logging Link ---")
  print(url)
  print("------------------------------------\n")


_VALUE_FORMAT = (
    "value(timestamp,resource.labels.pod_name,resource.labels.container_name,"
    "severity,jsonPayload.reason,protoPayload.methodName,textPayload,"
    "jsonPayload.message)"
)


def print_gcloud_cmd(query: str, project: str) -> None:
  """Prints the equivalent gcloud logging read command."""
  cmd = (
      f"gcloud logging read {shlex.quote(_flatten(query))} "
      f"--project={shlex.quote(project)} "
      f"--limit={_LIMIT.value} "
      f"--order={_ORDER.value} "
      f"--format={shlex.quote(_VALUE_FORMAT)}"
  )
  print("\n--- Equivalent gcloud command ---")
  print(cmd)
  print("----------------------------------\n")


def _format_entry(log: dict[str, object]) -> str:
  """Formats one log entry compactly: time, pod/container, severity, message."""
  resource = log.get("resource") or {}
  labels = resource.get("labels", {}) if isinstance(resource, dict) else {}
  where = "/".join(
      str(labels[k]) for k in ("pod_name", "container_name") if labels.get(k)
  ) or str(labels.get("node_name") or resource.get("type", ""))
  json_payload = log.get("jsonPayload") or {}
  proto_payload = log.get("protoPayload") or {}
  if log.get("textPayload"):
    message = log["textPayload"]
  elif isinstance(json_payload, dict) and (
      json_payload.get("message") or json_payload.get("reason")
  ):
    reason = json_payload.get("reason")
    message = (f"[{reason}] " if reason else "") + str(
        json_payload.get("message", "")
    )
  elif isinstance(proto_payload, dict) and proto_payload.get("methodName"):
    message = (
        f"{proto_payload['methodName']} {proto_payload.get('resourceName', '')}"
    )
  else:
    message = json.dumps(json_payload or proto_payload, indent=2)
  timestamp = log.get("timestamp", "UNKNOWN_TIME")
  severity = log.get("severity", "DEFAULT")
  return f"[{timestamp}] [{severity}] [{where}] {message}"


def fetch_logs(
    query: str, project: str, limit: int
) -> list[dict[str, Any]] | None:
  """Runs `gcloud logging read` and returns the entries (None on error)."""
  cmd = [
      "gcloud",
      "logging",
      "read",
      _flatten(query),
      f"--project={project}",
      f"--limit={limit}",
      f"--order={_ORDER.value}",
      "--format=json",
  ]
  print(f"Running: {' '.join(cmd)} ...\n")
  stdout = _run_command(cmd, "gcloud command")
  if stdout is None:
    return None
  try:
    return json.loads(stdout)
  except json.JSONDecodeError:
    print("Error parsing JSON output from gcloud command.")
    return None


def first_per_pod(
    logs: Sequence[dict[str, Any]], n: int
) -> list[tuple[dict[str, Any], int]]:
  """Keeps the first `n` entries and the last entry of each pod/container.

  The last entry is always kept because a pod's fatal error is often its final
  matching line, logged after routine or cascade lines.

  Args:
    logs: Log entries, already ordered (by --order).
    n: Leading entries to keep per pod/container.

  Returns:
    (entry, dropped) pairs in input order, where `dropped` is set on the last
    kept entry before a gap to the number of that pod/container's entries that
    were skipped there.
  """
  indices: dict[tuple[str, str], list[int]] = {}
  for i, log in enumerate(logs):
    labels = (log.get("resource") or {}).get("labels", {})
    key = (labels.get("pod_name", ""), labels.get("container_name", ""))
    indices.setdefault(key, []).append(i)
  dropped_after: dict[int, int] = {}
  keep: set[int] = set()
  for idx in indices.values():
    head = idx[:n]
    keep.update(head)
    if len(idx) > n:
      keep.add(idx[-1])
      skipped = len(idx) - n - 1
      if skipped:
        dropped_after[head[-1] if head else idx[-1]] = skipped
  return [(logs[i], dropped_after.get(i, 0)) for i in sorted(keep)]


def run_gcloud(queries: Sequence[str], project: str) -> None:
  """Runs the queries (one per node batch), merges and prints the entries."""
  per_pod = _FIRST_PER_POD.value
  limit = max(_FETCH_LIMIT.value, _LIMIT.value) if per_pod > 0 else _LIMIT.value
  logs = []
  hit_limit = False
  for query in queries:
    batch = fetch_logs(query, project, limit)
    if batch is None:
      return
    hit_limit |= len(batch) >= limit
    logs.extend(batch)
  if not logs:
    print("No logs found matching the query.")
    return
  if len(queries) > 1:
    logs.sort(
        key=lambda e: e.get("timestamp", ""), reverse=_ORDER.value == "desc"
    )
  if per_pod > 0:
    entries = first_per_pod(logs, per_pod)
  else:
    entries = [(log, 0) for log in logs]
  for log, dropped in entries[: _LIMIT.value]:
    more = (
        f"  (... {dropped} more from this pod/container; its last line follows)"
        if dropped
        else ""
    )
    print(_format_entry(log) + more)
  if per_pod > 0 and len(entries) > _LIMIT.value:
    print(
        f"\n[note] {len(entries) - _LIMIT.value} more pod/container entries"
        " not shown; raise --limit."
    )
  if hit_limit:
    print(
        f"\n[note] Hit the fetch limit ({limit}). Narrow the time window or"
        " raise --limit/--fetch_limit; with --order=asc you are seeing the"
        " earliest entries."
    )


def discover_workload_nodes(w: Workload) -> tuple[str, ...]:
  """Finds the nodes the workload's pods were scheduled on.

  Reads the pods' "Scheduled" events ("Successfully assigned <ns>/<pod> to
  <node>") from Cloud Logging, starting `_NODE_DISCOVERY_LOOKBACK` before the
  query window.

  Args:
    w: The workload.

  Returns:
    Sorted, de-duplicated node names (empty if none were found).
  """
  try:
    start, end = compute_time_range(
        _START_TIME.value, _END_TIME.value, _DURATION.value
    )
  except ValueError as e:
    raise UsageError(str(e)) from e
  time_filters = []
  if start:
    time_filters.append(
        f'timestamp >= "{_to_rfc3339(start - _NODE_DISCOVERY_LOOKBACK)}"'
    )
  if end:
    time_filters.append(f'timestamp <= "{_to_rfc3339(end)}"')
  query = "\n".join(
      _cluster_filters(w, "k8s_pod")
      + [
          'log_id("events")',
          f'resource.labels.namespace_name="{w.namespace}"',
          _pod_name_filter(w),
          'jsonPayload.reason="Scheduled"',
      ]
      + time_filters
  )
  cmd = [
      "gcloud",
      "logging",
      "read",
      _flatten(query),
      f"--project={w.project}",
      "--limit=2000",
      "--format=value(jsonPayload.message)",
  ]
  # Large lookback windows occasionally hit transient backend deadlines; retry
  # once before falling back to zone scoping.
  stdout = _run_command(cmd, "node discovery") or _run_command(
      cmd, "node discovery (retry)"
  )
  nodes = set()
  for line in (stdout or "").splitlines():
    m = re.search(r"\bto (\S+)\s*$", line)
    if m:
      nodes.add(m.group(1))
  return tuple(sorted(nodes))


def build_action_query(
    action: LogAction,
    w: Workload,
    extra_terms: Sequence[str] = (),
    min_severity: str | None = None,
) -> list[str]:
  """Returns the action's filter clauses, OR-ing its terms with extra matches.

  Args:
    action: The log action.
    w: The workload.
    extra_terms: Additional plain-text (unquoted) strings to match.
    min_severity: If set, also match every entry at or above this severity.

  Raises:
    UsageError: If `extra_terms` or `min_severity` is given for an action
      without terms.
  """
  if (extra_terms or min_severity) and not action.terms:
    raise UsageError(
        "--extra_terms and --min_severity are only supported by actions with"
        " a built-in list of terms: "
        + ", ".join(name for name, a in _LOG_ACTIONS.items() if a.terms)
    )
  filters = action.build_query(w)
  terms = action.terms + tuple(_quote(t) for t in extra_terms)
  if min_severity:
    terms += (f"severity>={min_severity}",)
  return filters + _any_of(*terms) if terms else filters


def run_neighbors(queries: Sequence[str], w: Workload) -> None:
  """Lists the distinct namespace/pod/container that logged on the nodes.

  Pods that do not belong to the workload are marked, so co-located workloads
  stand out.

  Args:
    queries: The `neighbors` queries (one per node batch), with time filters.
    w: The workload.
  """
  counts: dict[tuple[str, ...], int] = {}
  for query in queries:
    cmd = [
        "gcloud",
        "logging",
        "read",
        _flatten(query),
        f"--project={w.project}",
        f"--limit={max(_LIMIT.value, 10000)}",
        "--format=value("
        + ",".join([
            "resource.labels.namespace_name",
            "resource.labels.pod_name",
            "resource.labels.container_name",
        ])
        + ")",
    ]
    print(f"Running: {' '.join(cmd)} ...\n")
    stdout = _run_command(cmd, "gcloud command")
    if stdout is None:
      return
    for line in stdout.splitlines():
      key = tuple(line.split("\t"))
      if len(key) == 3:
        counts[key] = counts.get(key, 0) + 1
  if not counts:
    print("No container logs found on these nodes.")
    return
  print("lines  namespace/pod/container  (* = not part of this workload)")
  for (ns, pod, container), n in sorted(counts.items()):
    own = ns == w.namespace and any(pod.startswith(x) for x in w.names)
    print(f"{n:6d} {'' if own else '* '}{ns}/{pod}/{container}")


def _node_batches(w: Workload) -> list[Workload]:
  """Splits a workload with many nodes into batches of `_NODE_BATCH_SIZE`."""
  nodes = w.node_names
  if len(nodes) <= _NODE_BATCH_SIZE:
    return [w]
  return [
      dataclasses.replace(w, node_names=nodes[i : i + _NODE_BATCH_SIZE])
      for i in range(0, len(nodes), _NODE_BATCH_SIZE)
  ]


def do_log_action(action: LogAction, w: Workload) -> None:
  """Builds, prints, and optionally executes the query for a log action.

  Node-scoped actions with many nodes run one query per node batch; only the
  first batch's query is printed.

  Args:
    action: The log action.
    w: The workload.
  """
  batches = _node_batches(w) if action.needs_nodes else [w]
  queries = [
      "\n".join(
          build_action_query(
              action, b, _EXTRA_TERMS.value, _MIN_SEVERITY.value
          )
          + get_time_filter()
      )
      for b in batches
  ]
  print(f"=== Action: {action.title} ===")
  if len(queries) > 1:
    print(
        f"[note] {len(w.node_names)} nodes are queried in {len(queries)}"
        f" batches of up to {_NODE_BATCH_SIZE}; showing the first batch's"
        " query.\n"
    )
  print_console_url(queries[0], w.project)
  print_gcloud_cmd(queries[0], w.project)
  if not _EXECUTE.value:
    return
  if action.build_query is neighbors_query:
    run_neighbors(queries, w)
  elif action.build_query is node_ooms_query:
    run_parts(node_ooms_parts, batches, w.project)
  else:
    run_gcloud(queries, w.project)


def run_parts(
    parts: Callable[[Workload], list[tuple[str, list[str]]]],
    batches: Sequence[Workload],
    project: str,
) -> None:
  """Runs each part of a multi-part action as its own query, in order.

  A part that fails or times out is reported, and the next part still runs.

  Args:
    parts: Returns the (label, filter clauses) parts for a node batch.
    batches: The workload, split into node batches.
    project: The GCP project.
  """
  time_filters = get_time_filter()
  per_batch = [parts(b) for b in batches]
  for i, (label, _) in enumerate(per_batch[0]):
    # Parts that are not scoped to nodes are the same in every batch.
    queries = list(
        dict.fromkeys("\n".join(p[i][1] + time_filters) for p in per_batch)
    )
    print(f"--- Part {i + 1}/{len(per_batch[0])}: {label} ---")
    run_gcloud(queries, project)
    print()


def _probe(query: str, project: str) -> tuple[bool | None, str]:
  """Returns (found any entry, error text); found is None on error."""
  cmd = [
      "gcloud",
      "logging",
      "read",
      _flatten(query),
      f"--project={project}",
      "--limit=1",
      "--format=value(timestamp)",
  ]
  try:
    out = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        check=True,
        timeout=_QUERY_TIMEOUT.value or None,
    )
  except subprocess.CalledProcessError as e:
    return None, e.stderr
  except subprocess.TimeoutExpired:
    return None, _timeout_message("preflight query", _QUERY_TIMEOUT.value)
  return bool(out.stdout.strip()), ""


def run_preflight(w: Workload) -> None:
  """Checks log access and that the workload logged in the time window.

  An empty result from another action only means "no error" once these checks
  pass.

  Args:
    w: The workload.
  """
  time_filters = get_time_filter()
  print("=== Preflight ===")
  start, _ = compute_time_range(
      _START_TIME.value, _END_TIME.value, _DURATION.value
  )
  if start and start < datetime.datetime.now(
      datetime.timezone.utc
  ) - datetime.timedelta(days=30):
    print(
        "[warn] The window starts more than 30 days ago; logs may be past the"
        " project's retention period (30 days in the _Default bucket).\n"
    )

  found, err = _probe(
      "\n".join(_cluster_filters(w, "k8s_container") + time_filters),
      w.project,
  )
  if found is None:
    reason = (
        "no permission to read logs (needs roles/logging.viewer)"
        if "PERMISSION_DENIED" in err
        else err.strip().splitlines()[0] if err.strip() else "unknown error"
    )
    print(f"[FAIL] Cannot read logs in project {w.project}: {reason}")
    print("Results from other actions are not meaningful until this passes.")
    return
  if not found:
    print(
        f"[FAIL] No container logs at all for cluster {w.cluster} in"
        f" {w.location} in the time window. Check the project, cluster,"
        " location, time window and log retention."
    )
    return
  print(f"[ok] Cluster {w.cluster} has container logs in the window.")

  for t in w.targets:
    single = dataclasses.replace(w, targets=(t,))
    has_logs, _ = _probe(
        "\n".join(_jobset_container_filters(single) + time_filters), w.project
    )
    has_events, _ = _probe(
        "\n".join(
            pod_events_query(single)[:-1] + time_filters
        ),
        w.project,
    )
    label = f"{t.kind}:{t.name} (namespace {w.namespace})"
    if has_logs:
      print(f"[ok] {label}: container logs found.")
    elif has_events:
      print(
          f"[warn] {label}: pod events but no container logs; the containers"
          " may never have started. Run --action=pod-events and"
          " --action=summary."
      )
    else:
      print(
          f"[FAIL] {label}: no container logs or pod events in the window."
          " Check the name, kind (--jobset_name/--lws_name/--job_name/"
          "--pod_prefix), namespace and time window."
      )


def main(argv: Sequence[str]) -> None:
  _parse_flags(argv[1:])

  try:
    targets = parse_targets(
        _WORKLOADS.value,
        jobset=_JOBSET_NAME.value,
        lws=_LWS_NAME.value,
        job=_JOB_NAME.value,
        pod_prefix=_POD_PREFIX.value,
    )
  except ValueError as e:
    raise UsageError(str(e)) from e
  workload = Workload(
      project=_PROJECT.value,
      cluster=_CLUSTER_NAME.value,
      location=_LOCATION.value,
      targets=targets,
      namespace=_NAMESPACE.value,
      node_names=tuple(_NODE_NAMES.value),
      sidecar_container=_SIDECAR_CONTAINER.value,
  )
  if _ACTION.value == "preflight":
    run_preflight(workload)
    return
  action = _LOG_ACTIONS[_ACTION.value]
  if action.needs_nodes and not workload.node_names:
    nodes = discover_workload_nodes(workload) if _EXECUTE.value else ()
    if nodes:
      print(
          f"Scoping to the workload's {len(nodes)} node(s):"
          f" {', '.join(nodes)}\n"
      )
      workload = dataclasses.replace(workload, node_names=nodes)
    elif _ACTION.value == "node-ooms":
      print(
          "[note] Node names unknown (pass --node_names, or --execute to"
          " discover them); serial-console logs are scoped to zone"
          f" '{workload.location}' and may include unrelated VMs.\n"
      )
    else:
      raise UsageError(
          f"--action={_ACTION.value} needs the workload's nodes: pass"
          " --node_names, or --execute to discover them from the pods'"
          " 'Scheduled' events."
      )
  do_log_action(action, workload)


if __name__ == "__main__":
  try:
    main(sys.argv)
  except UsageError as e:
    _PARSER.error(str(e))

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