Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install gke-kueue-troubleshooting@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin gke-kueue-troubleshooting v1.0.0 follows the Agent Plugins spec.
gh skills-hub install gke-kueue-troubleshooting Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/gke-kueue-troubleshooting/ Extract the ZIP to .github/skills/ in your repo. The folder name must match gke-kueue-troubleshooting for Copilot to auto-discover it.
Skill Files (24)
SKILL.md 27.6 KB
---
name: gke-kueue-troubleshooting
description: Diagnose a GKE batch or AI workload (Job, JobSet, LeaderWorkerSet, RayJob, Kubeflow training jobs, or plain Pods) that is pending, suspended, stuck, evicted or misconfigured when Kueue manages it - from a live GKE cluster, a support bundle or exported controller/audit logs. Load it as soon as the investigation shows a Kueue footprint, even if the user never said "Kueue" - anything under kueue.x-k8s.io (labels, Pod scheduling gates, Workload/LocalQueue/ClusterQueue objects and their conditions), kueue-controller-manager events or logs, or a Job with spec.suspend=true together with a Workload object in its namespace. Scripts compact cluster state and logs into verifiable facts and validate the report, while the agent classifies the cause as Kueue configuration, Kueue defect, or outside Kueue. Don't use for workloads with no Kueue footprint (use gke-node-notready, gke-workload-scaling-troubleshooting, gke-ai-troubleshooting-tpu-reservation-stockout, or gke-ai-troubleshooting-jobset-interruption).
metadata:
version: "1.1.1"
category: Containers
---
# GKE Kueue troubleshooting
> **Read-only rule:** Run read-only diagnostic commands only. Never drain,
> delete, or re-create nodes, or run `kubectl patch/apply/edit/delete` or any
> other command that changes the cluster. When exporting logs for
> `trace_logs.py`, run only read-only log queries scoped to the target cluster,
> `kueue-system`, Kubernetes Event logs, Admin Activity audit logs, and the
> incident time window as described in
> [Log sources](references/log-sources.md) and
> [View GKE logs](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs.md.txt).
> Give the user any fix (remediation YAML, commands, or linked documentation
> steps) to apply themselves in the final `### Diagnostic Summary`.
## 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).
## Prerequisites
- **Tools and cluster access**: Python 3.10+ with `PyYAML` (all diagnostic
scripts live in `scripts/` next to this file and require no cloud SDKs); if
`python3 -c "import yaml"` fails, ask the user for approval before running
`python3 -m pip install "PyYAML>=6,<7"`, and if the user declines or `pip`
fails, stop and tell the user that the scripts require `PyYAML`. In `live`
mode, follow "Before you begin" in
[Deploy a batch system using Kueue](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/kueue-intro.md.txt)
to initialize `gcloud` and select the target project, and follow
[Install kubectl and configure cluster access](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/cluster-access-for-kubectl.md.txt)
to configure cluster credentials (`offline_data` and `logs_archive` read local
files only).
- **Cloud Billing and APIs**: For `live` cluster inspection or Cloud Logging
exports, ensure the project has an active Cloud Billing account and the Google
Kubernetes Engine API (`container.googleapis.com`) and Cloud Logging API
(`logging.googleapis.com`) are enabled.
- **Required IAM roles**: Per
[Google Kubernetes Engine roles and permissions](https://docs.cloud.google.com/iam/docs/roles-permissions/container.md.txt),
`live` cluster resource reads require Kubernetes Engine Viewer
(`roles/container.viewer`), and reading controller pod logs via `kubectl logs`
(`container.pods.getLogs`) or applying Kueue/cluster fixes requires Kubernetes
Engine Developer (`roles/container.developer`) or Kubernetes Engine Admin
(`roles/container.admin`). Exporting Cloud Logging and Admin Activity audit
logs requires Logs Viewer (`roles/logging.viewer`).
- **Scope and related skills**: Upstream Kueue ships experimental interactive
skills (`kueue-lineage` and `kueue-who-preempted`, documented in
[Troubleshooting Agent Skills](https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_agent_skills/))
for quick object-tree and preemption queries on a live cluster. This skill
adds offline support-bundle and Cloud Logging compaction, GKE infrastructure
boundary classification (`Outside Kueue`), and report validation.
## 1. Three-step protocol
The scripts **detect the Kueue release and API version**
(`active_api_schema_reference._detected_kueue_version`, e.g.
`v0.10.x`/`v1beta1` vs `v0.19.x`/`v1beta2`) from controller deployments, CRDs,
object `apiVersion`s or startup/audit logs, and load the **CRD and
`KueueConfiguration` schema for that version**. If `detection_sources` is only
`default:v1beta2`, the version was **assumed** — pass `--kueue-version <tag>`
or confirm the served CRD version before writing remediation YAML.
**Where the schema comes from** (`schema_source` / `config_schema_source`): in
`live` the cluster's served CRDs are used (`live_cluster_crds`); in
`offline_data` bundled CRD manifests are used if present (`bundled_crds`);
otherwise, or if the `live` CRDs cannot be read, release CRDs are read from
`GKE_KUEUE_TROUBLESHOOTING_KUEUE_REPO` or fetched once from GitHub
(`github_release:<tag>`) and cached under
`$XDG_CACHE_HOME/gke-kueue-troubleshooting` (override with
`GKE_KUEUE_TROUBLESHOOTING_CACHE_DIR`). `KueueConfiguration` is not a CRD; in
every mode (`live` included) its field tree is fetched from the
[KueueConfiguration v1beta2 reference](https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/)
or
[KueueConfiguration v1beta1 reference](https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta1/)
matching `config_api_version` (else `builtin_defaults`). `--no-remote-schema`
or `GKE_KUEUE_TROUBLESHOOTING_NO_REMOTE_SCHEMA=1` disables both downloads.
**If `schema_source` is `unavailable`** (`_schema_notice` present): CRD schemas
are never approximated; only `KueueConfiguration` may fall back to
`builtin_defaults`. Note in one sentence at the top of the report that the
release-exact schema was unavailable, name the remedy from `_schema_notice`
(cluster access, bundled CRDs, GitHub access, or `--kueue-version`), and
**continue the diagnosis** using the fields, conditions, and logs in the
snapshot (see [LocalQueue](https://kueue.sigs.k8s.io/docs/concepts/local_queue/)
and
[Topology Aware Scheduling](https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/)).
Remediation YAML still uses the detected `apiVersion`.
**Choose the data mode** (`--mode` or `GKE_KUEUE_TROUBLESHOOTING_MODE`, default
`live`):
- `live`: when `kubectl` reaches the cluster.
- `offline_data`: directory of YAML/JSON manifests (optionally with `logs/`);
pass `--data-path <dir>`.
- `logs_archive`: exported logs only (no cluster or manifests); export to a
local file first and pass `--data-path <file-or-dir>` (scoped per
[Log sources](references/log-sources.md); never `cat` or page raw log exports
into context).
Pass the **same** `--ledger-path <ledger>` inside a per-run temporary directory
to every script call so concurrent runs never collide; Step 3 verifies quotes
and schema against it. Shell state may not persist between commands: run
`mktemp -d /tmp/kueue-triage.XXXXXX` once and pass the printed literal absolute
path (not a shell variable) in every later command. **Do not read or parse the
ledger.**
**Output contract.** `snapshot.py` and `trace_logs.py` print a **digest ordered
most-important-first** (`detected_kueue_version`, derived facts,
`bulk_object_groups` with counts/names/representative, individual objects/log
excerpts, schema reference last) capped at `--max-output-bytes` (48 KB default
for snapshot, 24 KB for logs). The complete output is written to
`full_report_file` (next to the ledger). If command output is truncated to a
saved file, read that saved file once instead of re-running `--action get` or
`grep`. If the digest ends with `truncated:`, all tagged and coverage facts are
already above it; to inspect one dropped object, use
`--action get --kind <kind> --name <name> --namespace <ns>` (`--namespace` is
required for namespaced kinds; at most **4** `get` calls, never the same
`kind/name` twice) or read a ≤ 200-line slice of `full_report_file` / raw bundle
files (at most **twice**). Never read the skill's own Python scripts.
1. **Step 1 — one-shot snapshot or log timeline (schema attached)**
- `live` / `offline_data`: run `scripts/snapshot.py` with
`--mode <mode> --action snapshot --ledger-path <ledger>` (add
`--namespace <ns>` if known; `--kueue-namespace` if not `kueue-system`;
`--ignore-namespaces ns1,ns2` for extra add-on namespaces). If no active
`Workload`/`Job` is present or controller/audit history is needed, also run
`scripts/trace_logs.py --mode <mode> --ledger-path <ledger>` once (at most
2 log commands total).
- `logs_archive`: run
`scripts/trace_logs.py --mode logs_archive --ledger-path <ledger>` with
`--data-path <file-or-dir>` first (add `--workload <name>` to focus).
Never call `kubectl` in this mode.
- **Schema lookup (optional):** `scripts/snapshot.py --action explain` with
`--kind <Kind[.field.path]> --ledger-path <ledger>`.
- **If a script fails or skips files:** read the error once, follow
`next_step`, and continue with available files without retrying in a loop.
If `trace_logs.py` reports `skipped_inputs` (symlinks or non-regular files)
or `unreadable_inputs` (unparseable or concatenated JSON exports), do not
treat those logs as absent from the cluster: tell the user which files were
not read (re-export each filter to its own regular file or verify symlink
targets per [Log sources](references/log-sources.md)) and record any
unresolved gap under `#### Open Questions`.
2. **Step 2 — reason over the facts (the scripts do not reason for you)**
- Script outputs contain **facts, not conclusions**
(`active_api_schema_reference`, `derived_graph_diagnostics`,
`derived_log_diagnostics` with `mechanism_hint`, `key_errors_and_events`,
`discovered_entities`, `audit_resource_actions`). Nothing is pre-ranked as
a root cause.
- **Check the whole admission and execution pipeline (stages 1–6)** — do not
stop at the first symptom if another independent blocker exists. **For
every Workload in the request or `workload_timeline` /
`discovered_entities`, state its terminal state** (`Pending`, `Admitted`,
`Evicted: <reason>`, `Requeued <n>/<limit>`, `Deactivated`, `Finished`,
`Deleted by <owner cascade | TTL | retention policy>`) **and explain each
terminal event.** A Workload deleted via its Job's `ownerReferences` (user
delete, `ttlSecondsAfterFinished`, or parent JobSet) is the Job's own
lifecycle, not a Kueue retention defect — report it as why the object is
gone, not as an `RC<n>`. Consult the
[Documentation catalog](references/doc-links.md) for the full per-stage
upstream Kueue and GKE remediation links and section titles:
1. **Object chain**: Job/JobSet/LWS → Workload → `spec.queueName` →
`LocalQueue` (exists, `Active`) → `ClusterQueue` (exists, `Active`) →
`Cohort` (see
[Troubleshooting Jobs](https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_jobs/)
and
[Troubleshooting Queues](https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_queues/)).
2. **Quota and cohort sharing**: requests per pod set × count vs
`nominalQuota`, borrowing (`lendingLimit`/`borrowingLimit`, cohort quota
layout, `reclaimWithinCohort` / `fairSharing`), `queueingStrategy`
ordering, and GPU/TPU reservation alignment (see
[ClusterQueue](https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/),
[Cohort](https://kueue.sigs.k8s.io/docs/concepts/cohort/), and
[Preemption](https://kueue.sigs.k8s.io/docs/concepts/preemption/)).
3. **Flavor assignment per pod set**: `ResourceFlavor`
`nodeLabels`/`nodeTaints`/tolerations, `topologyName` vs the pod set's
topology request and across `resourceGroups`, and
`resources.transformations`. Per "Implicit TAS and mixed-flavor
ClusterQueues" in
[Topology Aware Scheduling](https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/),
in a `ClusterQueue` combining TAS and non-TAS flavors, implicit TAS is
disabled (unannotated pod sets can use only non-TAS flavors and
TAS-annotated pod sets can use only TAS flavors), and a single pod set
cannot mix TAS and non-TAS flavors across its requested resources.
4. **Admission checks**: `AdmissionCheck` `Active` and attached to the
`ClusterQueue`, DWS `ProvisioningRequest` / retry configuration,
reservation/DWS fallback, and external controllers (see
[ProvisioningRequest AdmissionCheck](https://kueue.sigs.k8s.io/docs/concepts/admission_check/provisioning_request/)
and
[Run a large-scale workload with flex-start with queued provisioning](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/provisioningrequest.md.txt)).
5. **After admission**: scheduling gates (`kueue.x-k8s.io/topology` or
external gates; see
[Troubleshooting Pods](https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_pods/)),
`waitForPodsReady` (`PodsReadyTimeout`, `RequeuingLimitExceeded`),
preemption, container/Job failure policies (`backoffLimit`,
`backoffLimitPerIndex`, `maxFailedIndexes`, `podFailurePolicy`), Cluster
Autoscaler `noScaleUp` / stockouts, TPU slice provisioning, and GKE node
`NotReady` (`NetworkPluginNotReady` / CNI not initialized — follow
"Troubleshoot network connectivity" in
[Troubleshoot nodes with the NotReady status in GKE](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/node-notready.md.txt)
or hand off to `gke-node-notready`).
6. **Controller health and configuration**: `KueueConfiguration`
(`kueue-manager-config` ConfigMap) fields (`integrations.frameworks`,
`manageJobsWithoutQueueName`, `featureGates`,
`resources.transformations`, `objectRetentionPolicies`), client-side
rate limiting vs `kube-apiserver` overload (HTTP 429/503, webhook
timeouts), controller restarts, and audit-logged create/delete/patch of
any object in the chain.
- **Synthesize one unified Root Cause (`RC<n>`) per underlying defect — do
not fragment symptoms:**
- If multiple workloads fail because of the **same underlying configuration
defect** on a `ClusterQueue` or `ResourceFlavor`, report that single
underlying defect as one `RC1` rather than splitting each workload's
symptom into separate root causes with conflicting fixes.
- If an earlier event in the same layer is the **upstream precursor** of
the current blocker, explain the causal chain together rather than
inventing redundant competing root causes for the same failure chain.
- Conversely, when two **genuinely independent** defects both affect the
workload (e.g. a Kueue configuration defect *and* an independent external
control-plane/capacity failure, or two independent Kueue configuration
defects across different stages such as flavor/topology wiring and
`AdmissionCheck` attachment), report each as its own `RC<n>` rather than
dropping one or misclassifying a missing Kueue configuration field as a
`Kueue defect`.
- **Defaults and uninvolved settings are not root causes — configured
mechanisms with terminal events are:** a field left at its Kueue default
(such as `waitForPodsReady` omitted,
`waitForPodsReady.requeuingStrategy.backoffLimitCount` unset/`null`, or
default `leaderElection` timings) is **not** a root cause (`RC<n>`). When a
workload repeatedly triggers a Kueue mechanism (such as `PodsReadyTimeout`
requeuing) because its own pods or Job failure policy never reach
completion or terminal failure, the single root cause (`RC1`) is the
workload's failure/completion configuration (`Outside Kueue: workload
spec`), while Kueue's default retry/requeue setting is background context.
Do **not** propose `waitForPodsReady`, `leaderElection`, or
`integrations.frameworks` ConfigMap changes as "hardening" on quota,
cohort, preemption, TAS, workload-spec, or infrastructure incidents.
**Conversely, a mechanism that is explicitly configured**
(`waitForPodsReady.timeout`, `requeuingStrategy.backoffLimitCount`,
`objectRetentionPolicies`, preemption policies) **and has a terminal event
in the evidence** (`Evicted` with reason `PodsReadyTimeout`, `Deactivated`
/ `RequeuingLimitExceeded`, `Preempted`, or deletion of deactivated
`Workload` objects by `objectRetentionPolicies.workloads`, which per
"Notes" in
[Setup object retention policy](https://kueue.sigs.k8s.io/docs/tasks/manage/setup_object_retention_policy/)
may cascade to objects not created by Kueue such as a `JobSet`) **is part
of the causal chain and must be reported** — as its own `RC<n>` when the
configured value causes the failure, or as an explicit stage of the chain
otherwise. "Working as designed" never justifies leaving such an event
unexplained.
- **Every root cause must be backed by a verbatim quote** (from
`status.conditions`, `spec`, `Events`, or controller/audit logs) reproduced
in `#### Observations`. **A quota or capacity claim additionally needs a
rejection fact for that same resource** — `insufficient quota` /
`insufficient unused quota` in a Workload condition or controller log,
`NotTriggerScaleUp`, or a `Pending` / `FailedScheduling` reason naming the
resource. A `nominalQuota` smaller or larger than node allocatable,
`nominalQuota: 0` on a queue that borrows, `blockAdmission: false`, or a
short `ttlSecondsAfterFinished` is an **observation**, not a root cause,
unless such a rejection fact ties it to the failure.
- **Scope boundary — classify the causal layer (`#### Scope`) before writing
Root Cause or Remediation:** Declare one of `Kueue configuration` |
`Kueue defect` |
`Outside Kueue: <capacity | node | control plane | workload spec>` |
`Mixed: <layers>` | `Undetermined: <what is missing>`. Attribute each
blocking fact by **which component produced the signal and which object
owns the field**, not by how the symptom looks:
1. **Locate the blocking stage(s) in the pipeline** (stages 1–6):
- Stages 1–4 (queue chain, quota/cohort layout, flavor/TAS assignment,
admission check wiring) are decided by Kueue from Kueue objects
(`Kueue configuration`, or `Kueue defect` if Kueue contradicts its
documented behavior for the detected version).
- Stage 5 (after `Admitted=True`) is decided by kube-scheduler, kubelet,
node provisioner / autoscaler, admission-check controllers, and the
workload's own pods. A blocker there is **`Outside Kueue`** unless a
Kueue configuration caused it (e.g. `ResourceFlavor.spec.nodeLabels`
pointing at non-existent labels, a stranded `kueue.x-k8s.io/topology`
scheduling gate, or cohort `nominalQuota` mismatched to cluster
capacity).
- **Cohort `nominalQuota`, borrowing, and Fair Sharing:** Per
[ClusterQueue](https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/)
and [Cohort](https://kueue.sigs.k8s.io/docs/concepts/cohort/), queues
in a cohort can borrow unused `nominalQuota` subject to `lendingLimit`
(which caps how much unused `nominalQuota` a member lends) and
`borrowingLimit`. Compare cohort `nominalQuota` declarations,
`audit_resource_actions`, and Fair Sharing / preemption settings
against observed admission, preemption, or scheduling events. A queue
with `nominalQuota: 0` is a valid borrow-only design, not a defect on
its own, and `#### Remediation` must modify only the resources and
fields implicated by the rejection facts. Per "ClusterQueue share
value" in
[Preemption](https://kueue.sigs.k8s.io/docs/concepts/preemption/),
Kueue summarizes borrowed usage in
`.status.fairSharing.weightedShare` weighted by
`.spec.fairSharing.weight` (higher weight lowers share value for the
same borrowed usage; Kueue admits lowest share first and preempts
highest share first; when cohort members configure different
`.spec.fairSharing.weight` values, report each member's weight and how
Fair Sharing weights their borrowed usage in `#### Observations`).
- Stage 6 (controller health) splits by **signal provenance**: facts
tagged `source side: kueue-client` reflect client-side rate limiting
controlled by `clientConnection.qps` and `clientConnection.burst` in
the "ClientConnection" section of the `KueueConfiguration` reference;
facts tagged `source side: apiserver` (HTTP 429/503, API Priority and
Fairness, webhook/etcd timeouts) belong to
**`Outside Kueue: control plane`** (see
[Collect and view control plane metrics](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/control-plane-metrics.md.txt)).
2. **Independent layers → `Mixed`.** If both a Kueue-side blocker and an
external-layer blocker independently affect the workload(s), set
`#### Scope` to `Mixed: <layers>`, give each layer its own `RC<n>`, and
include the literal phrase `Outside Kueue` in the external `RC<n>`
header line (e.g. `- RC2 (Outside Kueue — control plane): ...`). Never
write `Outside Kueue` in a Kueue-configuration RC header or its
remediation.
3. **Never patch across layers.** An `Outside Kueue` RC is remediated on
the component that owns it (node pool, image, control plane, cloud
capacity, the Job's own spec). A `Kueue configuration` RC is remediated
on the Kueue object that owns the field.
- **When evidence is incomplete, use `#### Open Questions` (`OQ<n>`):**
`BUNDLE_COVERAGE` and `LOG_COVERAGE` state which object kinds and log
sources are present and absent. If the runtime status objects and logs
needed to confirm why a stage failed are absent from both (e.g. a static
manifest-only bundle or a logs-only archive lacking manifests), do **not**
assert an unverified guess as a definite `RC<n>`: record `OQ1` under
`#### Open Questions` as `Basis:` (what is missing), `Candidates:` (each
with its conditional remediation), `Discriminator:` (the deciding
observation), then the read-only `Collect:` command last.
- **Commit when the evidence decides — do not hedge a decided finding.** When
runtime evidence (conditions, events, or logs) settles the cause, write a
definite `RC<n>` under `#### Root Cause` with one concrete fix under
`#### Remediation`, without listing "or possibly ..." alternatives next to
it. Reserve `OQ<n>` for questions the available evidence genuinely cannot
answer **and** that name one read-only command to answer them. If the
first-listed candidate is the only one with a rejection or terminal fact in
the evidence, it is the `RC<n>`, not an `OQ<n>`. Explicitly configured
mechanisms with terminal events belong in the causal chain, not under
`#### Ruled Out`.
3. **Step 3 — evidence and schema validation**
- Number confirmed root causes `RC1`, `RC2`, … and give a matching
remediation entry for each `RC<n>` under `#### Remediation` (conditional
fixes for unresolved candidates go under `Candidates:` of their `OQ<n>`):
- For a **Kueue configuration** RC: link the official Kueue or GKE
documentation section from
[Documentation catalog](references/doc-links.md) alongside the exact
`kubectl` command or YAML manifest in the detected API version,
preserving all `active_api_schema_reference` invariants and covering
every resource requested by the workload's PodSets.
`KueueConfiguration` is not an API resource: tell the user to follow
"Install a custom-configured released version" and "Change the feature
gates configuration" in
[Installation](https://kueue.sigs.k8s.io/docs/getting-started/installation/)
(or the GKE sections in
[Documentation catalog](references/doc-links.md)) to edit
`data.controller_manager_config.yaml` (`kind: Configuration`) in the
`kueue-manager-config` ConfigMap and restart the
`kueue-controller-manager` Deployment, showing the complete
`controller_manager_config.yaml` document rather than a partial patch.
- For a **Kueue defect** RC: do not invent unsupported workarounds that
break workload semantics. Tell the user to collect snapshot and
controller log evidence, check or file an upstream issue at
`https://github.com/kubernetes-sigs/kueue/issues` or contact Cloud
Customer Care per
[Get support](https://docs.cloud.google.com/kubernetes-engine/docs/getting-support.md.txt),
and state the confirmation signal (`Confirm by checking that ...`).
- For an **Outside Kueue** RC: **never** propose a `ClusterQueue`,
`ResourceFlavor`, or `KueueConfiguration` patch to mask an external
infrastructure failure. State the external-layer remediation (linking the
relevant GKE guide from [Documentation catalog](references/doc-links.md)
or handing off to `gke-node-notready`,
`gke-workload-scaling-troubleshooting`,
`gke-ai-troubleshooting-tpu-reservation-stockout`, or
`gke-ai-troubleshooting-jobset-interruption`), state the **confirmation
signal** (`Confirm by checking that <object condition> transitions to
<expected state>`), and for persistent control-plane or hardware issues
advise contacting Cloud Customer Care per
[Get support](https://docs.cloud.google.com/kubernetes-engine/docs/getting-support.md.txt).
- In `#### Observations`, wrap a multi-word phrase in backticks **only** when
it is a verbatim substring of tool output (synthesised summaries go in
plain text).
- Save the draft beside the ledger and run `scripts/validate_report.py` with
`--draft-file <draft.md> --ledger-path <ledger>`. It passes only with
`passed: true` (exit 0); exit 2 means `ledger_missing` (wrong ledger path)
or a non-empty `missing_headers`, `uninspected_graph_objects`,
`fabricated_quotes`, `remediation_gaps`, `open_question_gaps`,
`config_remediation_errors`, `unknown_kubectl_resources`, or
`schema_warnings`; fix those and re-run once. `unsupported_root_causes` is
advisory: tie any listed `RC<n>` to a rejection/terminal signal in
`#### Observations` or move it to `#### Open Questions`; do not re-run the
validator for it.
- Finish with:
```markdown
### Diagnostic Summary
#### Scope
<Kueue configuration | Kueue defect | Outside Kueue: <layer> | Mixed>
#### Observations
- Verbatim evidence from `status.conditions`, `spec`, `Events`, or
controller/audit logs, with timestamps for historical facts.
#### Root Cause
- RC1: <precise root cause and causal mechanism>, tied to the evidence above.
- RC2 (Outside Kueue — <layer>): <if Mixed / external layer, state the external
root cause>.
#### Open Questions
- none (or `OQ1` with `Basis:`, `Candidates:` with conditional remediation,
`Discriminator:`, then a read-only `Collect:` command, when data is absent).
#### Ruled Out
- Brief list of secondary observations, resolved/precursor events, or
non-blocking settings ruled out as root causes.
#### Remediation
- RC1: link the official documentation section describing the fix (plus the
exact `kubectl` command or YAML manifest with that link for Kueue RCs), or
external-layer remediation + confirmation signal (for external RCs).
- RC2: ...
```
attribution.md 1.9 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:gke-kueue-troubleshooting)" \
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:gke-kueue-troubleshooting)` 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:gke-kueue-troubleshooting)
```
- **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.
doc-links.md 10.9 KB
# Per-stage Kueue and GKE documentation catalog
Use these official upstream Kueue and Google Kubernetes Engine (GKE)
documentation pages and sections when diagnosing pipeline stages 1–6 or citing
remediation steps in `#### Remediation`. Run only read-only diagnostic sections
yourself; for any section that creates, edits, or restarts cluster resources,
tell the user to follow the instructions in that section.
## Table of Contents
- [Stage 1: Object chain and queue
wiring](#stage-1-object-chain-and-queue-wiring): Lines 27-48
- [Stage 2: Quota, cohort sharing, and
reservations](#stage-2-quota-cohort-sharing-and-reservations): Lines 49-67
- [Stage 3: Flavor assignment, TAS, and
transformations](#stage-3-flavor-assignment-tas-and-transformations):
Lines 68-85
- [Stage 4: Admission checks and DWS
ProvisioningRequests](#stage-4-admission-checks-and-dws-provisioningrequests):
Lines 86-103
- [Stage 5: Post-admission scheduling, autoscaling, TPUs, and
nodes](#stage-5-post-admission-scheduling-autoscaling-tpus-and-nodes):
Lines 104-141
- [Stage 6: Controller configuration, logs, and
support](#stage-6-controller-configuration-logs-and-support): Lines 142-168
## Stage 1: Object chain and queue wiring
- Missing `Workload` or `Workload` stuck without a valid `LocalQueue` or
`ClusterQueue`:
[Troubleshooting Jobs](https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_jobs/),
[Troubleshooting Queues](https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_queues/),
[Workload](https://kueue.sigs.k8s.io/docs/concepts/workload/),
[LocalQueue](https://kueue.sigs.k8s.io/docs/concepts/local_queue/),
[ClusterQueue](https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/), and
[Cohort](https://kueue.sigs.k8s.io/docs/concepts/cohort/).
- Creating or fixing `ResourceFlavor`, `ClusterQueue`, and `LocalQueue` wiring
on GKE: "Create the ResourceFlavor", "Create the ClusterQueue", "Create the
LocalQueue", and "Create Jobs and observe the admitted workloads" in
[Deploy a batch system using Kueue](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/kueue-intro.md.txt).
- Multislice TPU `JobSet` queue setup on GKE: "Create the Kueue resources",
"Define your Multislice workloads with JobSets", and "Verify Kueue admitted
the workloads" in
[Orchestrate Multislice workloads using JobSet and Kueue](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/tpu-multislice-kueue.md.txt).
- Job TTL cleanup (`ttlSecondsAfterFinished`): "TTL mechanism for finished Jobs"
in
[Kubernetes Jobs](https://kubernetes.io/docs/concepts/workloads/controllers/job/).
## Stage 2: Quota, cohort sharing, and reservations
- `nominalQuota`, `lendingLimit`, `borrowingLimit`, `borrowWithinCohort`,
`reclaimWithinCohort`, and Fair Sharing ("ClusterQueue share value"):
[ClusterQueue](https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/),
[Cohort](https://kueue.sigs.k8s.io/docs/concepts/cohort/), and
[Preemption](https://kueue.sigs.k8s.io/docs/concepts/preemption/).
- Reconfiguring GKE cohort quotas or preemption policies:
- "Create the ClusterQueue and LocalQueue" and "Borrow unused quota with
cohorts" in
[Implement a Job queuing system with quota sharing between namespaces on GKE](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/kueue-cohort.md.txt).
- "Enable Kueue workload priorities and preemption" in
[Orchestrate Multislice workloads using JobSet and Kueue](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/tpu-multislice-kueue.md.txt).
- "Test Kueue preemption and dynamic allocation on your mixed workload" in
[Optimize GKE resource utilization for mixed AI/ML training and inference workloads](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/mixed-workloads.md.txt).
- Consuming reserved GPU or TPU capacity on GKE: "Consuming GPU reservations" or
"Consuming TPU reservations" in
[Consuming reserved zonal resources](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/consuming-reservations.md.txt).
## Stage 3: Flavor assignment, TAS, and transformations
- `ResourceFlavor` `nodeLabels`, `nodeTaints`, tolerations, and `topologyName`
(including "Implicit TAS and mixed-flavor ClusterQueues"):
[ResourceFlavor](https://kueue.sigs.k8s.io/docs/concepts/resource_flavor/) and
[Topology Aware Scheduling](https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/).
- GKE flavor and dynamic slice TAS setup:
- "Create the ResourceFlavors" in
[Implement a Job queuing system with quota sharing between namespaces on GKE](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/kueue-cohort.md.txt).
- "Create a dynamic slice with Kueue and TAS" and "Monitor the status of the
slice" in
[Schedule dynamic slices with Kueue and TAS](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/use-gke-dynamic-slicing.md.txt).
- Extended resource rewrites via `resources.transformations`
(`ResourceTransformation` in `KueueConfiguration`):
[KueueConfiguration v1beta2 reference](https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/)
or
[KueueConfiguration v1beta1 reference](https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta1/).
## Stage 4: Admission checks and DWS ProvisioningRequests
- `AdmissionCheck` and `ProvisioningRequestConfig` wiring and status:
[AdmissionCheck](https://kueue.sigs.k8s.io/docs/concepts/admission_check/),
[ProvisioningRequest AdmissionCheck](https://kueue.sigs.k8s.io/docs/concepts/admission_check/provisioning_request/),
and
[Troubleshooting ProvisioningRequest](https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_provreq/).
- GKE Dynamic Workload Scheduler (DWS) read-only diagnostics ("Troubleshooting",
"Observe the status of a Provisioning Request", "Troubleshoot quota issues",
and "Check if the Provisioning Request request is limited by quota") and Kueue
setup ("Flex-start with queued provisioning for Jobs with Kueue", "Create the
Kueue resources for the Dynamic Workload Scheduler node pool only setup", and
"Create the Kueue resources for Reservation and Dynamic Workload Scheduler
node pool setup"):
[Run a large-scale workload with flex-start with queued provisioning](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/provisioningrequest.md.txt).
- TPU DWS and Kueue configuration rules ("Define the configuration rules"):
[Optimize AI training on TPUs with DWS and Kueue](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/ray-kueue-dws.md.txt).
## Stage 5: Post-admission scheduling, autoscaling, TPUs, and nodes
- External and topology scheduling gates (`kueue.x-k8s.io/topology`): "Why is my
Pod not being scheduled if I am using external scheduling gates" in
[Troubleshooting Pods](https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_pods/)
and
[Topology Aware Scheduling](https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/).
- `waitForPodsReady` (`PodsReadyTimeout`, `RequeuingLimitExceeded`) and
preemption:
[Setup All-or-nothing with ready Pods](https://kueue.sigs.k8s.io/docs/tasks/manage/setup_wait_for_pods_ready/)
and [Preemption](https://kueue.sigs.k8s.io/docs/concepts/preemption/).
- Job and JobSet failure policies (`backoffLimit`, `backoffLimitPerIndex`,
`maxFailedIndexes`, `podFailurePolicy`):
[Kubernetes Jobs](https://kubernetes.io/docs/concepts/workloads/controllers/job/)
and
[JobSet Troubleshooting](https://jobset.sigs.k8s.io/docs/troubleshooting/).
- Cluster Autoscaler `noScaleUp` and stockouts ("View errors in events",
"ScaleUp errors", "Reasons for a noScaleUp event", "Pod doesn't fit on node",
and "Unhealthy clusters prevent scale-up"):
[Troubleshoot cluster autoscaler not scaling up](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/cluster-autoscaler-scale-up.md.txt).
- GKE TPU quota, capacity, and slice scheduling ("Insufficient quota to satisfy
the TPU request", "Insufficient TPU resources to satisfy the TPU request",
"GKE doesn't automatically provision TPU slice nodes", "Scheduling errors when
deploying Pods that consume TPUs in GKE", and "Troubleshooting common issues
with JobSets in GKE"):
[Troubleshoot TPUs in GKE](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/tpus.md.txt).
- GKE `NotReady` nodes (`NetworkPluginNotReady` / CNI not initialized) and node
auto-repair: "Check the node's status and conditions", "Troubleshoot network
connectivity", "Troubleshoot core component failures", and "Verify that the
node has recovered" in
[Troubleshoot nodes with the NotReady status in GKE](https://docs.cloud.google.com/kubernetes-engine/docs/troubleshooting/node-notready.md.txt),
plus "Settings for Autopilot and Standard", "Verify node auto-repair is
enabled for a Standard node pool", and "Enable auto-repair for an existing
Standard node pool" in
[Auto-repair nodes](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/node-auto-repair.md.txt)
(Autopilot clusters always have node auto-repair enabled; the verification and
enablement sections apply only to Standard node pools).
## Stage 6: Controller configuration, logs, and support
- `KueueConfiguration` fields (`waitForPodsReady`, `clientConnection`,
`integrations`, `resources.transformations`, `objectRetentionPolicies`):
[KueueConfiguration v1beta2 reference](https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/),
[KueueConfiguration v1beta1 reference](https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta1/),
and
[Setup object retention policy](https://kueue.sigs.k8s.io/docs/tasks/manage/setup_object_retention_policy/).
- Modifying `data.controller_manager_config.yaml` (`kind: Configuration`) in
`kueue-manager-config` and restarting `kueue-controller-manager`: "Install a
custom-configured released version" and "Change the feature gates
configuration" in
[Installation](https://kueue.sigs.k8s.io/docs/getting-started/installation/),
"Configure Kueue" in
[Optimize GKE resource utilization for mixed AI/ML training and inference workloads](https://docs.cloud.google.com/kubernetes-engine/docs/tutorials/mixed-workloads.md.txt),
and "Enable Slice reuse" in
[Schedule dynamic slices with Kueue and TAS](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/use-gke-dynamic-slicing.md.txt).
- Control plane metrics ("Traffic and error rate", "Saturation") and Cloud
Logging ("Accessing your logs", "Understanding your logs", "Resource types",
"System logs", "Kubernetes Event logs", "Application logs", "Control plane
component logs"):
[Collect and view control plane metrics](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/control-plane-metrics.md.txt)
and
[View GKE logs](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs.md.txt).
- Escalating Kueue defects or persistent GKE infrastructure issues: "Before you
contact support" and "Recommendations for efficient support" in
[Get support](https://docs.cloud.google.com/kubernetes-engine/docs/getting-support.md.txt).
log-sources.md 6.0 KB
# Log sources for `logs_archive` mode
`trace_logs.py --mode logs_archive` reads exported log **files** or directories
(`--data-path <file-or-dir>`). How those exports are produced is up to the
operator or the agent; the scripts never call a cloud SDK, provider CLI, or
subshell themselves.
## Table of Contents
- [Passing exported logs to the script](#passing-exported-logs-to-the-script):
Lines 19-41
- [Accepted file shapes (auto-detected, mixable in one
directory)](#accepted-file-shapes-auto-detected-mixable-in-one-directory):
Lines 43-73
- [Exporting GKE logs from Cloud
Logging](#exporting-gke-logs-from-cloud-logging): Lines 75-111
- [What the agent should not do](#what-the-agent-should-not-do): Lines 113-121
## Passing exported logs to the script
To hand logs over without printing raw records into agent context, export them
to a local file first and point `--data-path` at the file or directory:
```bash
# Write each export to its own file in the per-run directory (never append
# multiple JSON arrays into one file), then pass the directory to --data-path.
# Shell state may not persist between commands: run this block as one command
# and use the printed literal absolute path (not "$WORK_DIR") in later ones.
WORK_DIR=$(mktemp -d /tmp/kueue-triage.XXXXXX)
echo "$WORK_DIR"
<read-only export command> > "$WORK_DIR/controller.json"
python3 scripts/trace_logs.py \
--mode logs_archive \
--data-path "$WORK_DIR" \
--ledger-path "$WORK_DIR/ledger.json"
```
Export commands run by the caller must be strictly read-only and scoped to the
target cluster, the incident time window, `kueue-system`, Kubernetes Event logs,
and Admin Activity audit logs as described below and in
["Accessing your logs"](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs.md.txt).
## Accepted file shapes (auto-detected, mixable in one directory)
- **Kueue controller JSON lines (zap)**: produced by `k8s_container` logs
(`projects/PROJECT_ID/logs/stdout` and `projects/PROJECT_ID/logs/stderr`) or
container runtime files. `Initializing` and `Configuration loaded` lines
carry the release and `apiVersion`.
- **Cloud Logging envelope** (`{timestamp, severity,
jsonPayload|protoPayload|textPayload}`): produced by Cloud Logging JSON or
JSONL exports (see
["Accessing your logs"](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs.md.txt)).
`protoPayload` Admin Activity audit entries
(`projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity`) are
normalised like `audit.k8s.io/v1`.
- **Kubernetes `Event` objects** (`v1` / `events.k8s.io/v1`): produced by
`projects/PROJECT_ID/logs/events` (`k8s_pod`, `k8s_node`, `k8s_cluster`) or
exported Event lists (`List` JSON or one object per line).
- **`audit.k8s.io/v1` `Event` objects (JSONL)**: produced by Kubernetes API
server audit logs; normalised to
`(verb, resource, subresource, namespace, name)`.
- **Collector envelope** (`{log|line|message, time|@timestamp,
kubernetes|labels}`): produced by log collectors; the inner record is
unwrapped recursively.
- **klog text** (`I0924 12:09:02.123 1 <file>:<line>] ...`): produced by older
controllers or webhook sidecars (timestamp has no year).
Files are discovered by extension (`.log`, `.txt`, `.json`, `.jsonl`,
`.ndjson`), by whole-word `log`/`logs` in the file name, or under a `log/` or
`logs/` directory (excluding `.yaml`, `.yml`, dotfiles, and archives).
Directory walks read regular files only and skip symlinks. A pretty-printed
manifest that is not a log record yields nothing, so a support bundle directory
can be passed as-is.
## Exporting GKE logs from Cloud Logging
For how GKE routes container logs (`k8s_container`), Kubernetes Events
(`projects/PROJECT_ID/logs/events` on `k8s_pod`, `k8s_node`, and
`k8s_cluster`), control plane logs (`k8s_control_plane_component`), and Admin
Activity audit logs
(`projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity`), follow
"Accessing your logs", "Understanding your logs", "Resource types", "System
logs", "Kubernetes Event logs", "Application logs", and "Control plane component
logs" in
[View GKE logs](https://docs.cloud.google.com/kubernetes-engine/docs/how-to/view-logs.md.txt).
Verbose per-transition lines from `kueue-controller-manager` may not be present
at default log verbosity; the scripts report the absence of such lines as
`"not determinable"`, not as evidence.
To export a scoped GKE incident window (`<start>` to `<end>` in RFC3339 UTC for
`<cluster>` in `<project>`) into a local JSON file for `trace_logs.py`, query
Cloud Logging with a filter scoped to:
- `resource.labels.cluster_name="<cluster>"` and RFC3339 UTC bounds
`timestamp>="<start>"` and `timestamp<="<end>"`
- `resource.labels.namespace_name="kueue-system"` (Kueue controller container
logs), `logName:"/logs/events"` (Kubernetes Event logs), or
`logName:"cloudaudit.googleapis.com%2Factivity"` (Admin Activity audit logs)
Save each filter export to its own file in the per-run directory (for example
`"$WORK_DIR/controller.json"`, `"$WORK_DIR/events.json"`,
`"$WORK_DIR/audit.json"` — never append multiple JSON array exports into one
file) and pass the directory via `--data-path "$WORK_DIR"`; `trace_logs.py`
reorders JSON array exports chronologically by `timestamp`. If `trace_logs.py`
reports `skipped_inputs` (symlinks or non-regular files) or
`unreadable_inputs` (unparseable or concatenated JSON exports), do not report
those logs as absent from the cluster: tell the user which files were not read,
re-export each filter to its own regular file (or verify symlink targets) and
rerun, or record the gap under `#### Open Questions` if the files cannot be
recovered.
## What the agent should not do
- Do not print or paste a raw export into the conversation; pass the file to
the script.
- Do not widen the export to the whole project or cluster — scope to
`resource.labels.cluster_name`, the incident time window, `kueue-system`,
Kubernetes Event logs, and the Admin Activity audit log.
- Do not install SDKs to fetch logs; pass the exported files to
`trace_logs.py`.
fair_sharing_facts.py 6.7 KB
"""Fair-sharing arithmetic per cohort: weights, weightedShare, and borrowed vs cohort lendable quota.
For every cohort whose members configure ``spec.fairSharing`` or report
``status.fairSharing``, restate per ClusterQueue: weight (default 1 when
omitted),
reported weightedShare, current reservation/usage and borrowed amount per
resource,
nominal quota, lendingLimit, and the cohort's lendable total per resource. Per
https://kueue.sigs.k8s.io/docs/concepts/preemption/ ("ClusterQueue share
value"),
Kueue summarizes a ClusterQueue's usage of borrowed resources in a single
numeric
share value weighted by ``.spec.fairSharing.weight`` (reported in
``.status.fairSharing.weightedShare``); ranking and verdicts are left to the
reader.
"""
from __future__ import annotations
import dataclasses
from typing import Any
import k8s_objects as k8s
import report_output
_PREEMPTION_DOC = "https://kueue.sigs.k8s.io/docs/concepts/preemption/"
_CQ_DOC = "https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/"
@dataclasses.dataclass
class QueueShare:
"""Per-ClusterQueue fair-sharing weights, quotas, and usage totals."""
name: str
weight: Any
weighted_share: Any
has_fair_sharing: bool
reclaim: str
nominal: dict[str, float] = dataclasses.field(default_factory=dict)
lendable: dict[str, float] = dataclasses.field(default_factory=dict)
usage: dict[str, float] = dataclasses.field(default_factory=dict)
borrowed: dict[str, float] = dataclasses.field(default_factory=dict)
unparsed: list[str] = dataclasses.field(default_factory=list)
def _add(
d: dict[str, float], key: str, value: Any, unparsed: list[str], label: str
) -> None:
"""Adds a parsed Kubernetes quantity to `d[key]` or records `unparsed`."""
q = report_output.parse_quantity(value) if value is not None else None
if value is not None and q is None:
unparsed.append(f"{label}={value!r}")
elif q is not None:
d[key] = d.get(key, 0.0) + q
def _queue_share(cq: dict[str, Any]) -> QueueShare:
"""Extracts fair-sharing weights, quotas, usage, and borrowed totals."""
spec, status = k8s.spec(cq), k8s.status(cq)
fs_spec, fs_status = k8s.as_dict(spec.get("fairSharing")), k8s.as_dict(
status.get("fairSharing")
)
reclaim = str(
k8s.as_dict(spec.get("preemption")).get("reclaimWithinCohort") or "Never"
)
qs = QueueShare(
name=k8s.name(cq),
weight=fs_spec.get("weight"),
weighted_share=fs_status.get("weightedShare"),
has_fair_sharing=bool(fs_spec or fs_status),
reclaim=reclaim,
)
for _, fl, res in k8s.flavor_quotas(cq):
r = str(res.get("name", ""))
_add(
qs.nominal,
r,
res.get("nominalQuota"),
qs.unparsed,
f"{fl.get('name')}.{r}.nominalQuota",
)
lend = res.get("lendingLimit")
nominal = report_output.parse_quantity(res.get("nominalQuota"))
lend_q = report_output.parse_quantity(lend) if lend is not None else nominal
if lend is not None and lend_q is None:
qs.unparsed.append(f"{fl.get('name')}.{r}.lendingLimit={lend!r}")
if lend_q is not None and nominal is not None:
qs.lendable[r] = qs.lendable.get(r, 0.0) + min(lend_q, nominal)
# Read flavorsReservation (falling back to flavorsUsage) from status.
for fu in k8s.dict_items(
status.get("flavorsReservation") or status.get("flavorsUsage")
):
for ru in k8s.dict_items(fu.get("resources")):
r = str(ru.get("name", ""))
_add(
qs.usage,
r,
ru.get("total"),
qs.unparsed,
f"{fu.get('name')}.{r}.total",
)
_add(
qs.borrowed,
r,
ru.get("borrowed"),
qs.unparsed,
f"{fu.get('name')}.{r}.borrowed",
)
return qs
def _fmt(d: dict[str, float], resources: list[str]) -> str:
"""Formats resource totals in `d` across `resources` as `r=val` pairs."""
return ", ".join(
f"{r}={report_output.fmt_quantity(d.get(r, 0.0), r)}" for r in resources
)
def _format_share_row(
s: QueueShare, resources: list[str], cohort_lendable: dict[str, float]
) -> str:
"""Formats one ClusterQueue's fair-sharing metrics and borrow ratios."""
ratios: list[str] = []
for r in resources:
b = s.borrowed.get(r, 0.0)
lend = cohort_lendable.get(r, 0.0)
if b > 0 and lend > 0:
b_fmt = report_output.fmt_quantity(b, r)
lend_fmt = report_output.fmt_quantity(lend, r)
ratios.append(f"{r}: {b_fmt}/{lend_fmt}={1000 * b / lend:.0f}‰")
return (
f"{s.name}:"
f" weight={s.weight if s.weight is not None else 'unset(1)'},"
f" status.weightedShare={s.weighted_share},"
f" reclaimWithinCohort={s.reclaim},"
f" nominal[{_fmt(s.nominal, resources)}],"
f" lendable[{_fmt(s.lendable, resources)}],"
f" usage[{_fmt(s.usage, resources)}],"
f" borrowed[{_fmt(s.borrowed, resources)}]"
+ (f", borrowed/cohortLendable {{{'; '.join(ratios)}}}" if ratios else "")
+ (f", unparsed={s.unparsed[:2]}" if s.unparsed else "")
)
def emit_fair_sharing_arithmetic(ctx: Any) -> None:
"""Emits per-cohort fair-sharing weights and quota arithmetic (4e)."""
for cohort, members in sorted(ctx.cohort_map.items()):
shares = sorted((_queue_share(cq) for cq in members), key=lambda q: q.name)
if len(shares) < 2 or not any(s.has_fair_sharing for s in shares):
continue
resource_set: set[str] = set()
for s in shares:
resource_set.update(s.nominal)
resource_set.update(s.borrowed)
resources = sorted(resource_set)
cohort_lendable = {
r: sum(s.lendable.get(r, 0.0) for s in shares) for r in resources
}
rows = [_format_share_row(s, resources, cohort_lendable) for s in shares]
w_str = ", ".join(
f"{s.name}: {s.weight if s.weight is not None else 'unset(1)'}"
for s in shares
)
ctx.add(
f"fair-sharing:{cohort}",
f"FAIR_SHARING_ARITHMETIC (cohort {cohort}):"
f" fairSharing.weight=[{w_str}]; cohort lendable per"
f" resource [{_fmt(cohort_lendable, resources)}] (sum over members of"
f" min(lendingLimit, nominalQuota); {_CQ_DOC}). Members: "
+ " | ".join(rows)
+ ". Kueue summarizes each ClusterQueue's borrowed resource usage in a"
" share value weighted by .spec.fairSharing.weight and reported in"
f" .status.fairSharing.weightedShare ({_PREEMPTION_DOC}); a higher"
" weight lowers the share for the same borrowed amount, and a member"
" that borrows nothing has share 0. During admission Kueue prefers"
" the ClusterQueue with the lowest share, and during preemption it"
" targets workloads in the ClusterQueue with the highest share. Fair"
" Sharing preemption works with withinClusterQueue and"
f" reclaimWithinCohort ({_PREEMPTION_DOC}), not borrowWithinCohort.",
)
k8s_objects.py 6.4 KB
"""Typed, tolerant accessors for Kubernetes objects represented as plain dicts.
Snapshot objects come from `kubectl -o json` or hand-written bundle manifests
and may be partial or malformed. Every accessor returns an empty container
when the field is missing or has the wrong shape, so callers can chain them
without `isinstance` / `(x or {})` guards; `as_text` and `as_int` do the same
for scalar fields. Stdlib only; no project imports.
"""
from __future__ import annotations
from typing import Any
# Key of the KueueConfiguration document inside kueue-manager-config ConfigMap.
KUEUE_CONFIG_KEY = "controller_manager_config.yaml"
# Labels that identify a node group / pool, used only to de-duplicate taint
# facts per pool. Upstream labels first, then common provider labels.
NODE_POOL_LABELS = (
"node.kubernetes.io/instance-type",
"cloud.google.com/gke-nodepool",
"karpenter.sh/nodepool",
"agentpool",
)
def as_dict(value: Any) -> dict[str, Any]:
"""Returns `value` when it is a dict, otherwise an empty dict."""
return value if isinstance(value, dict) else {}
def as_list(value: Any) -> list[Any]:
"""Returns `value` when it is a list, otherwise an empty list."""
return value if isinstance(value, list) else []
def dict_items(value: Any) -> list[dict[str, Any]]:
"""Returns the dict elements of a list-like value (anything else → [])."""
if not isinstance(value, (list, tuple)):
return []
return [x for x in value if isinstance(x, dict)]
def as_text(value: Any) -> str:
"""Returns `str(value)`, or '' when the value is missing (None); `0` stays '0'."""
return "" if value is None else str(value)
def as_int(value: Any, default: int = 0) -> int:
"""Integer value of a count-like field.
Returns `default` only when the field is missing (None) or is not a number
(`"two"`, a list, a boolean), so an explicit `0` stays `0`.
Args:
value: Raw field value as loaded from JSON or YAML.
default: Value returned for a missing or non-numeric field.
Returns:
The field as an int, or `default`.
"""
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
return default
try:
return int(value)
except (ValueError, OverflowError):
return default
def kind(obj: Any) -> str:
return as_text(as_dict(obj).get("kind"))
def metadata(obj: Any) -> dict[str, Any]:
return as_dict(as_dict(obj).get("metadata"))
def name(obj: Any) -> str:
return as_text(metadata(obj).get("name"))
def namespace(obj: Any) -> str:
return as_text(metadata(obj).get("namespace"))
def ref(obj: Any) -> str:
"""Returns `ns/name` for namespaced objects, `name` for cluster-scoped ones."""
ns = namespace(obj)
return f"{ns}/{name(obj)}" if ns else name(obj)
def kind_ref(obj: Any) -> str:
"""Returns `Kind/ns/name` (or `Kind/name` when the object has no namespace)."""
return f"{kind(obj)}/{ref(obj)}"
def labels(obj: Any) -> dict[str, Any]:
return as_dict(metadata(obj).get("labels"))
def annotations(obj: Any) -> dict[str, Any]: # pylint: disable=function-redefined
return as_dict(metadata(obj).get("annotations"))
def owner_refs(obj: Any) -> list[dict[str, Any]]:
return dict_items(metadata(obj).get("ownerReferences"))
def owner_names(obj: Any) -> set[str]:
"""Names of the object's owners (entries without a name are skipped)."""
return {str(o.get("name", "")) for o in owner_refs(obj) if o.get("name")}
def spec(obj: Any) -> dict[str, Any]:
return as_dict(as_dict(obj).get("spec"))
def status(obj: Any) -> dict[str, Any]:
return as_dict(as_dict(obj).get("status"))
def conditions(obj: Any) -> list[dict[str, Any]]:
"""Dict entries of `status.conditions` (non-dict entries are dropped)."""
return dict_items(status(obj).get("conditions"))
def event_timestamp(ev: Any) -> str:
"""Best timestamp of an Event: lastTimestamp, eventTime, firstTimestamp, then creationTimestamp."""
ev = as_dict(ev)
for key in ("lastTimestamp", "eventTime", "firstTimestamp"):
if ev.get(key):
return str(ev[key])
return str(metadata(ev).get("creationTimestamp") or "")
def condition(obj: Any, type_: str) -> dict[str, Any] | None:
"""First `status.conditions[]` entry whose `type` equals `type_`, or None."""
for cond in conditions(obj):
if cond.get("type") == type_:
return cond
return None
def condition_status(obj: Any, type_: str) -> str | None:
"""`status` of the first condition of the given type as a string, or None."""
cond = condition(obj, type_)
return None if cond is None else str(cond.get("status"))
def has_condition(obj: Any, type_: str, status_value: str = "True") -> bool:
"""True when any condition of `type_` carries `status_value` (duplicates included).
The status is compared as text, so an unquoted YAML `status: True` (a
boolean after loading) matches `"True"`, as in `condition_status`.
Args:
obj: Kubernetes object mapping.
type_: Condition type to look for.
status_value: Expected status text.
Returns:
Whether a matching condition exists.
"""
return any(
c.get("type") == type_ and as_text(c.get("status")) == status_value
for c in conditions(obj)
)
def resource_groups(cq: Any) -> list[dict[str, Any]]:
"""Dict entries of `spec.resourceGroups` of a ClusterQueue or Cohort."""
return dict_items(spec(cq).get("resourceGroups"))
def flavor_quotas(cq: Any):
"""Yields `(resource_group, flavor, resource)` dict triples of a ClusterQueue."""
for rg in resource_groups(cq):
for fl in dict_items(rg.get("flavors")):
for res in dict_items(fl.get("resources")):
yield rg, fl, res
def container_statuses(pod: Any) -> list[tuple[str, dict[str, Any]]]:
"""`(field, containerStatus)` pairs for init and regular containers, in that order."""
st = status(pod)
out: list[tuple[str, dict[str, Any]]] = []
for field in ("initContainerStatuses", "containerStatuses"):
for cs in dict_items(st.get(field)):
out.append((field, cs))
return out
def compact_managed_fields(mf_list: Any) -> list[str]:
"""Compacts verbose managedFields into a 1-line attribution summary per manager."""
summary: list[str] = []
for entry in dict_items(mf_list):
manager = entry.get("manager", "unknown")
operation = entry.get("operation", "Update")
subresource = entry.get("subresource", "")
ts = entry.get("time", "")
sub = f"/{subresource}" if subresource else ""
summary.append(f"{manager} ({operation}{sub} @ {ts})")
return summary
kueue_schema.py 31.4 KB
#!/usr/bin/env python3
"""Version-aware Kueue CRD & KueueConfiguration schema registry for the `gke-kueue-troubleshooting` skill.
Automatically detects the exact running Kueue release version (e.g. `v0.10.0`,
`v0.15.0`, `v0.19.4`) and active API version (`kueue.x-k8s.io/v1beta1` vs
`kueue.x-k8s.io/v1beta2`, `config.kueue.x-k8s.io/v1beta1` vs `v1beta2`) from:
1. Live clusters (`Deployment/kueue-controller-manager` image/labels, live
`CustomResourceDefinition` schemas, and active Kueue objects).
2. Offline support bundles (`Deployment`/`Pod` controller image tags, bundled
CRDs, manifest `apiVersion`s, and `logs/`).
3. Controller/Event/Audit logs (`"Initializing"` `gitVersion`, `"Configuration
loaded"`
`apiVersion`, audit-log resource `apiVersion`s, and Event
`involvedObject`).
Loads the schema for the exact detected version from the first available source:
1. `CustomResourceDefinition` objects shipped inside the support bundle
(`offline_data`).
2. The live cluster's CRDs (`kubectl get crd`) — default in `live` mode; the
cluster is the authoritative CRD schema for the release it runs (while
`KueueConfiguration` is fetched from its reference docs unless cached or
`--no-remote-schema` is set).
3. A local Kueue checkout, when present (`git archive <tag>` via
`GKE_KUEUE_TROUBLESHOOTING_KUEUE_REPO`).
4. The upstream GitHub release (`releases/download/<tag>/manifests.yaml`),
used when
no CRDs are at hand (logs-only modes, bundles without CRDs). Enabled by
default;
set `GKE_KUEUE_TROUBLESHOOTING_NO_REMOTE_SCHEMA=1` for air-gapped
environments.
5. Nothing. When none of the above is reachable the schema is reported as
`schema_source=unavailable` together with `schema_notice` explaining how to
supply
it; field-level validation is skipped and only `apiVersion` consistency
with the
detected release is checked. No approximate/stale schema is ever
substituted.
`KueueConfiguration` is not a CRD and has no schema inside a cluster. Its field
tree is
parsed from the published `kueue-config.<version>` reference page
(`https://kueue.sigs.k8s.io/docs/reference/kueue-config.<version>/`, falling
back to
the built-in defaults), see `config_schema_source`.
Downloaded/compiled schemas are cached under
`$XDG_CACHE_HOME/gke-kueue-troubleshooting`
(override with `GKE_KUEUE_TROUBLESHOOTING_CACHE_DIR`); the skill directory is
never written to.
Module map: `kueue_version` (release/API detection), `kueue_schema_registry`
(CRD -> compact registry, cache), `kueue_schema_sources` (source chain),
`kueue_schema_yaml_checks` (remediation YAML checks). This module holds the
I/O adapters (kubectl, git, HTTP), the public entry points and the CLI.
"""
from __future__ import annotations
import argparse
import http.client
import io
import json
import os
import re
import subprocess
import sys
import tarfile
from typing import Any, Callable, Iterable
import urllib.request
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if SCRIPT_DIR not in sys.path:
sys.path.insert(0, SCRIPT_DIR)
# pylint: disable=g-import-not-at-top,wrong-import-position
import kueue_schema_registry as registry
import kueue_schema_sources as sources
import kueue_schema_yaml_checks as yaml_checks
import kueue_version
import report_output
import yaml
# pylint: enable=g-import-not-at-top,wrong-import-position
# Re-exported for tests and sibling modules reaching these via kueue_schema.
detect_target_kueue_version = kueue_version.detect_target_kueue_version
_normalize_release_tag = kueue_version.normalize_release_tag
_normalize_short_api_version = kueue_version.normalize_short_api_version
DEFAULT_KCFG_NESTED = registry.DEFAULT_KCFG_NESTED
_parse_kcfg_struct_tree_from_html = registry.parse_kcfg_struct_tree_from_html
schema_cache_dir = registry.schema_cache_dir
# Public upstream Kueue documentation root used for doc citations.
KUEUE_SOURCE_REF = "v0.20.0"
KUEUE_DOCS_ROOT = "https://kueue.sigs.k8s.io/docs"
KCFG_REF_URL = "https://kueue.sigs.k8s.io/docs/reference/kueue-config.{ver}/"
def cite(url: str) -> str:
"""Format an official public Kueue documentation URL citation."""
if url.startswith("https://"):
return url
return f"{KUEUE_DOCS_ROOT}/{url.lstrip('/')}"
def _resolve_kueue_repo_dir() -> str:
"""Locates a local Kueue checkout, if configured or enclosing."""
candidates = [
os.getenv("GKE_KUEUE_TROUBLESHOOTING_KUEUE_REPO", ""),
os.getenv("KUEUE_DIAGNOSE_KUEUE_REPO", ""),
os.path.abspath(os.path.join(SCRIPT_DIR, "..", "..", "..", "..", "..")),
]
for cand in candidates:
if cand and os.path.isdir(
os.path.join(cand, "config", "components", "crd", "bases")
):
return cand
return ""
KUEUE_REPO_DIR = _resolve_kueue_repo_dir()
GITHUB_RELEASE_URL = (
"https://github.com/kubernetes-sigs/kueue/releases/download/"
"{tag}/manifests.yaml"
)
_SAFE_RELEASE_TAG_RE = re.compile(
r"^v[0-9]+\.[0-9]+\.[0-9]+"
r"(?:-[a-zA-Z0-9_]+(?:[.-][a-zA-Z0-9_]+)*)?"
r"(?:\+[a-zA-Z0-9_]+(?:[.-][a-zA-Z0-9_]+)*)?$"
)
_ALLOWED_KCFG_VERSIONS = frozenset({"v1alpha1", "v1beta1", "v1beta2"})
_HTTP_TIMEOUT_SECONDS = 8
_GIT_TIMEOUT_SECONDS = 5
_KUBECTL_CRD_TIMEOUT_SECONDS = 20
def remote_schema_allowed() -> bool:
"""Returns True unless remote schema downloads are disabled via env."""
val = (
os.getenv("GKE_KUEUE_TROUBLESHOOTING_NO_REMOTE_SCHEMA", "").strip()
or os.getenv("KUEUE_DIAGNOSE_NO_REMOTE_SCHEMA", "").strip()
)
return val.lower() not in ("1", "true", "yes")
# --- Local Kueue checkout (git) ---------------------------------------------
def _git_in_repo(
args: list[str], timeout: int, text: bool = True
) -> subprocess.CompletedProcess[Any] | None:
"""Runs `git -C KUEUE_REPO_DIR <args>`, or returns None if unavailable."""
if not KUEUE_REPO_DIR or not os.path.isdir(
os.path.join(KUEUE_REPO_DIR, ".git")
):
return None
try:
return subprocess.run(
["git", "-C", KUEUE_REPO_DIR, *args],
capture_output=True,
text=text,
check=False,
timeout=timeout,
)
except (OSError, subprocess.SubprocessError):
return None
def _closest_tag(norm: str, tags: set[str]) -> str:
"""Matches exact tag, stripped suffix tag, or latest patch of same minor."""
if norm in tags:
return norm
base_ver = norm.split("-")[0]
if base_ver in tags:
return base_ver
# Try matching v0.minor.0 if patch is newer than local repo
m = re.search(r"^(v[0-9]+\.[0-9]+)\.[0-9]+", base_ver)
if m:
minor_prefix = m.group(1)
minor_candidates = sorted(
t
for t in tags
if re.fullmatch(rf"{re.escape(minor_prefix)}\.[0-9]+", t)
)
if minor_candidates:
return minor_candidates[-1]
return ""
def _resolve_git_tag_in_kueue_repo(release_version: str) -> str:
"""Finds the exact or closest matching git tag in the local Kueue repo."""
if not release_version:
return ""
res = _git_in_repo(["tag", "-l"], timeout=3)
if res is None or res.returncode != 0:
return ""
return _closest_tag(
_normalize_release_tag(release_version), set(res.stdout.splitlines())
)
def _parse_git_archive(
archive: bytes,
) -> tuple[list[dict[str, Any]], dict[str, Any]] | None:
"""CRD documents from a `git archive` tarball."""
crd_docs: list[dict[str, Any]] = []
try:
with tarfile.open(fileobj=io.BytesIO(archive), mode="r:") as tar:
for member in tar.getmembers():
fobj = tar.extractfile(member) if member.isfile() else None
if fobj is None:
continue
raw_text = fobj.read().decode("utf-8", errors="replace")
if member.name.endswith(".yaml"):
doc = yaml.safe_load(raw_text)
if isinstance(doc, dict):
crd_docs.append(doc)
except (tarfile.TarError, yaml.YAMLError, OSError):
return None
return crd_docs, {}
def _storage_version(crd_docs: list[dict[str, Any]], kind: str) -> str:
"""Storage version declared by the CRD of `kind`, or empty if absent."""
for doc in crd_docs:
spec = doc.get("spec") or {}
if (spec.get("names") or {}).get("kind") != kind:
continue
for v in spec.get("versions") or []:
if isinstance(v, dict) and v.get("storage"):
return str(v.get("name") or "")
return ""
def _load_schema_from_git_tag(
git_tag: str, preferred_short_ver: str = "", config_short_ver: str = ""
) -> tuple[dict[str, Any] | None, str]:
"""Extracts CRDs for `git_tag` from a local Kueue checkout (cached)."""
if not git_tag or not _SAFE_RELEASE_TAG_RE.fullmatch(git_tag):
return None, ""
eff_ver = preferred_short_ver or "auto"
cfg_ver = registry.safe_tag(config_short_ver or eff_ver)
cache_file = os.path.join(
schema_cache_dir(),
f"crd_schema_checkout_{registry.safe_tag(git_tag)}_{eff_ver}"
f"_cfg-{cfg_ver}.json",
)
cached = registry.read_cached_registry(cache_file)
if cached is not None:
return cached, f"local_checkout_cache:{git_tag}"
res = _git_in_repo(
["archive", git_tag, "--", "config/components/crd/bases/"],
timeout=_GIT_TIMEOUT_SECONDS,
text=False,
)
if res is None or res.returncode != 0 or not res.stdout:
return None, ""
parsed = _parse_git_archive(res.stdout)
if parsed is None or not parsed[0]:
return None, ""
crd_docs, kcfg_by_ver = parsed
# Use storage version in this tag unless preferred_short_ver was forced.
target_ver = (
preferred_short_ver
or _storage_version(crd_docs, "ClusterQueue")
or "v1beta2"
)
compiled = registry.compile_crd_docs(
crd_docs, target_ver, kcfg_by_ver, config_short_ver
)
compiled["_config_schema_source"] = "builtin_defaults"
registry.write_cached_registry(cache_file, compiled, target_ver)
return compiled, f"local_checkout:{git_tag}"
# --- Live cluster (kubectl) --------------------------------------------------
def _kubectl(args: list[str]) -> subprocess.CompletedProcess[str]:
"""Runs `kubectl` with the CRD request timeout and returns its result."""
return subprocess.run(
["kubectl", *args, f"--request-timeout={_KUBECTL_CRD_TIMEOUT_SECONDS}s"],
capture_output=True,
text=True,
check=False,
timeout=_KUBECTL_CRD_TIMEOUT_SECONDS + 5,
)
def _crd_items(data: Any) -> list[dict[str, Any]]:
"""Extracts Kueue CRDs from decoded `kubectl get crd -o json` output."""
if isinstance(data, dict) and data.get("kind") == "CustomResourceDefinition":
items = [data]
else:
items = data.get("items") if isinstance(data, dict) else []
return [it for it in items or [] if sources.is_kueue_crd(it)]
def _query_live_cluster_crds() -> tuple[list[dict[str, Any]], str]:
"""Lists and fetches `*.kueue.x-k8s.io` CRDs from the live cluster."""
listed = _kubectl(["get", "crd", "-o", "name"])
if listed.returncode != 0:
return (
[],
(
f"`kubectl get crd` failed (rc={listed.returncode}):"
f" {listed.stderr.strip()[:300]}"
),
)
names = [
ln.strip().split("/", 1)[-1]
for ln in listed.stdout.splitlines()
if ln.strip().endswith(".kueue.x-k8s.io")
]
if not names:
return [], "`kubectl get crd` lists no *.kueue.x-k8s.io CRDs"
res = _kubectl(["get", "crd", *names, "-o", "json"])
if res.returncode != 0 or not res.stdout.strip():
return (
[],
(
"`kubectl get crd <kueue crds> -o json` failed"
f" (rc={res.returncode}): {res.stderr.strip()[:300]}"
),
)
crds = _crd_items(json.loads(res.stdout))
if not crds:
return [], "`kubectl get crd` output contained no kueue.x-k8s.io CRDs"
return crds, ""
def _fetch_live_cluster_crds() -> tuple[list[dict[str, Any]], str]:
"""Queries the live cluster for `*.kueue.x-k8s.io` CRDs.
Only the Kueue CRDs are fetched as JSON (names are listed first) so clusters
with hundreds of CRDs do not hit the timeout.
Returns:
A `(crds, error)` tuple where `error` is empty on success, or a short
reason (kubectl missing, timeout, RBAC denial, unparsable output) that the
caller surfaces in the schema notice.
"""
try:
return _query_live_cluster_crds()
except FileNotFoundError:
return [], "kubectl is not installed or not on PATH"
except subprocess.TimeoutExpired:
return (
[],
f"`kubectl get crd` timed out after {_KUBECTL_CRD_TIMEOUT_SECONDS}s",
)
except (OSError, subprocess.SubprocessError) as exc:
return [], f"`kubectl get crd` could not run: {exc}"
except json.JSONDecodeError as exc:
return [], f"`kubectl get crd -o json` output is not valid JSON: {exc}"
# --- GitHub (HTTP) -----------------------------------------------------------
def _http_get_text(url: str) -> str | None:
"""Fetches `url` text, returning None on any network or HTTP failure."""
try:
req = urllib.request.Request(
url,
headers={"User-Agent": "gke-kueue-troubleshooting-schema-loader/1.0"},
)
with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT_SECONDS) as resp:
return resp.read().decode("utf-8", errors="replace")
except (OSError, ValueError, http.client.HTTPException):
return None
def _release_tag_candidates(release_version: str) -> list[str]:
"""Returns exact tag first, then tag without any pre-release/distro suffix."""
tag = _normalize_release_tag(release_version)
if not tag or not _SAFE_RELEASE_TAG_RE.fullmatch(tag):
return []
base = tag.split("-", 1)[0].split("+", 1)[0]
if base == tag or not _SAFE_RELEASE_TAG_RE.fullmatch(base):
return [tag]
return [tag, base]
def _fetch_github_release_crds(
release_version: str,
) -> tuple[list[dict[str, Any]], str]:
"""Fetches GitHub release `manifests.yaml` CRDs and the matched tag."""
for tag in _release_tag_candidates(release_version):
if not _SAFE_RELEASE_TAG_RE.fullmatch(tag):
continue
content = _http_get_text(GITHUB_RELEASE_URL.format(tag=tag))
if content is None:
continue
try:
docs = [
doc
for doc in yaml.safe_load_all(content)
if sources.is_kueue_crd(doc)
]
except yaml.YAMLError:
continue
if docs:
return docs, tag
return [], ""
# --- KueueConfiguration reference page ---------------------------------------
def _read_cached_kcfg(cache_file: str) -> tuple[dict[str, Any] | None, str]:
"""Loads a cached `KueueConfiguration` field tree when fresh and valid."""
if not os.path.isfile(cache_file):
return None, ""
try:
with open(cache_file, "r", encoding="utf-8") as f:
cached = json.load(f)
except (OSError, json.JSONDecodeError):
return None, ""
if (
isinstance(cached, dict)
and cached.get("fields")
and cached.get("source")
and cached.get("format") == registry.SCHEMA_FORMAT
):
return {
"fields": cached["fields"],
"tree": cached.get("tree") or {},
}, f"cache:{cached['source']}"
return None, ""
def _write_cached_kcfg(
cache_file: str, entry: dict[str, Any], source: str
) -> None:
"""Atomically writes a `KueueConfiguration` field tree to `cache_file`."""
try:
tmp_path = f"{cache_file}.tmp.{os.getpid()}"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(
{**entry, "source": source, "format": registry.SCHEMA_FORMAT},
f,
indent=1,
)
os.replace(tmp_path, cache_file)
except OSError:
# The cache only saves a download: an unwritable cache directory must not
# fail the run, and the tree is fetched again next time.
pass
def _fetch_kcfg_ref_html(
cfg_short_ver: str, allow_remote: bool
) -> tuple[str | None, str]:
"""Published `kueue-config.<ver>` reference HTML and its source label."""
if not allow_remote or cfg_short_ver not in _ALLOWED_KCFG_VERSIONS:
return None, ""
url = KCFG_REF_URL.format(ver=cfg_short_ver)
html_text = _http_get_text(url)
if html_text and "<code>Configuration</code>" in html_text:
return html_text, f"reference_docs:kueue-config.{cfg_short_ver}"
return None, ""
def load_kcfg_for_release(
release_version: str, cfg_short_ver: str, allow_remote: bool | None = None
) -> tuple[dict[str, Any] | None, str]:
"""Loads the `KueueConfiguration` field tree from cache or reference docs.
Args:
release_version: Detected Kueue release version string.
cfg_short_ver: Short config API version (`v1beta1` or `v1beta2`).
allow_remote: Whether remote HTTP fetches are permitted (defaults to env).
Returns:
A `(entry, source)` tuple, or `(None, "")` when neither cache nor reference
page is available (callers then use built-in defaults).
"""
tag = _normalize_release_tag(release_version)
if not tag or cfg_short_ver not in ("v1beta1", "v1beta2"):
return None, ""
if allow_remote is None:
allow_remote = remote_schema_allowed()
cache_file = os.path.join(
schema_cache_dir(), f"kcfg_{registry.safe_tag(tag)}_{cfg_short_ver}.json"
)
cached, cached_source = _read_cached_kcfg(cache_file)
if cached is not None:
return cached, cached_source
html_text, source = _fetch_kcfg_ref_html(cfg_short_ver, allow_remote)
if not html_text:
return None, ""
entry = registry.kcfg_fields_and_tree(html_text)
if not entry.get("fields"):
return None, ""
_write_cached_kcfg(cache_file, entry, source)
return entry, source
# --- Public entry points -----------------------------------------------------
def _schema_adapters(
compile_with_kcfg: sources.CompileWithKcfg,
) -> sources.SchemaAdapters:
"""Binds the source chain to this module's patchable I/O functions."""
return sources.SchemaAdapters(
fetch_live_crds=_fetch_live_cluster_crds,
resolve_git_tag=_resolve_git_tag_in_kueue_repo,
load_git_tag_schema=_load_schema_from_git_tag,
fetch_github_crds=_fetch_github_release_crds,
compile_with_kcfg=compile_with_kcfg,
repo_dir=KUEUE_REPO_DIR,
)
def _env_mode() -> str:
"""Data mode set in the environment (`GKE_KUEUE_TROUBLESHOOTING_MODE`), or empty."""
return report_output._env( # pylint: disable=protected-access
"GKE_KUEUE_TROUBLESHOOTING_MODE", "KUEUE_DIAGNOSE_MODE"
)
def _make_kcfg_compiler(
release_ver: str, cfg_short: str, short_api: str, allow_remote_fetch: bool
) -> Callable[[list[dict[str, Any]]], dict[str, Any]]:
"""Builds a callback that compiles CRD docs together with `KueueConfiguration`."""
def _with_kcfg(crds: list[dict[str, Any]]) -> dict[str, Any]:
kcfg, kcfg_src = load_kcfg_for_release(
release_ver, cfg_short, allow_remote_fetch
)
compiled = registry.compile_crd_docs(
crds, short_api, {cfg_short: kcfg} if kcfg else None, cfg_short
)
compiled["_config_schema_source"] = kcfg_src or "builtin_defaults"
return compiled
return _with_kcfg
def load_schema_for_version(
version_info: dict[str, Any] | None = None,
raw_items: list[dict[str, Any]] | None = None,
load_live_crds: bool | None = None,
allow_remote_fetch: bool | None = None,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Loads the CRD and `KueueConfiguration` schema matching `version_info`.
Args:
version_info: Optional pre-detected Kueue version metadata mapping.
raw_items: Optional Kubernetes object list used when detecting the version.
load_live_crds: Whether to query live cluster CRDs; defaults from mode.
allow_remote_fetch: Whether remote release fetching is allowed.
Returns:
`(schema_dict, version_info_dict)` for the resolved Kueue release.
"""
env_mode = _env_mode()
vinfo = dict(
version_info
or detect_target_kueue_version(
mode=env_mode or "live", raw_items=raw_items
)
)
short_api = vinfo.get("short_api_version") or _normalize_short_api_version(
vinfo.get("api_version", "v1beta2")
)
cfg_short = (
_normalize_short_api_version(str(vinfo.get("config_api_version") or ""))
or short_api
)
release_ver = str(vinfo.get("release_version") or "").strip()
mode = str(vinfo.get("mode") or env_mode or "")
if load_live_crds is None:
load_live_crds = mode == "live"
if allow_remote_fetch is None:
allow_remote_fetch = remote_schema_allowed()
with_kcfg = _make_kcfg_compiler(
release_ver, cfg_short, short_api, allow_remote_fetch
)
request = sources.SchemaRequest(
short_api=short_api,
release_ver=release_ver,
raw_items=[it for it in raw_items or [] if isinstance(it, dict)],
load_live_crds=load_live_crds,
allow_remote_fetch=allow_remote_fetch,
adapters=_schema_adapters(with_kcfg),
config_short=cfg_short,
)
result = sources.resolve_schema(request)
vinfo["schema_source"] = result.source
vinfo["config_schema_source"] = str(
result.schema.get("_config_schema_source") or "builtin_defaults"
)
return result.schema, vinfo
def get_active_schema_reference(
kinds: Iterable[str],
version_info: dict[str, Any] | None = None,
raw_items: list[dict[str, Any]] | None = None,
load_live_crds: bool | None = None,
) -> dict[str, Any]:
"""Returns a compact, version-exact schema reference for the given resource kinds."""
schema, resolved_vinfo = load_schema_for_version(
version_info=version_info,
raw_items=raw_items,
load_live_crds=load_live_crds,
)
short_api = resolved_vinfo.get("short_api_version", "v1beta2")
out: dict[str, Any] = {
"_detected_kueue_version": {
"release_version": resolved_vinfo.get("release_version", "unknown"),
"api_version": resolved_vinfo.get(
"api_version", f"kueue.x-k8s.io/{short_api}"
),
"config_api_version": resolved_vinfo.get(
"config_api_version", f"config.kueue.x-k8s.io/{short_api}"
),
"schema_source": resolved_vinfo.get("schema_source", ""),
"config_schema_source": resolved_vinfo.get(
"config_schema_source", ""
),
"detection_sources": resolved_vinfo.get("detection_sources", []),
}
}
if schema.get("_schema_unavailable"):
out["_schema_notice"] = schema.get("_schema_notice", "")
return out
requested = set(kinds)
requested.update({"ClusterQueue", "KueueConfiguration"})
for k in sorted(requested):
if k == "ConfigMap":
k = "KueueConfiguration"
elif k == "_by_api_version":
continue
if k in schema and isinstance(schema[k], dict):
entry = schema[k]
out[k] = {
"apiVersion": entry.get("apiVersion"),
"valid_fields": entry.get("top_level_spec_fields", []),
}
return out
def _explain_kind(
root_key: str, kind_entry: dict[str, Any], resolved_vinfo: dict[str, Any]
) -> dict[str, Any]:
"""Formats the top-level schema explanation dict for `root_key`."""
out = {
"detected_kueue_version": resolved_vinfo,
"kind": root_key,
"apiVersion": kind_entry.get("apiVersion"),
"all_versions_in_release": kind_entry.get("all_versions", []),
"top_level_spec_fields": kind_entry.get("top_level_spec_fields"),
"spec_schema": kind_entry.get("spec_schema", {}),
}
if "nested_fields" in kind_entry:
out["nested_fields"] = kind_entry["nested_fields"]
return out
def _field_tree(kind_entry: dict[str, Any]) -> dict[str, Any]:
"""The entry's fields as a `{name: {"fields": ...}}` tree.
A CRD entry already carries that shape in `spec_schema`. `KueueConfiguration`
has no `spec`: its top-level names and the `nested_fields` tree (plain nested
dicts, `{}` for a leaf or an unexpanded type) are converted here.
Args:
kind_entry: Compiled registry entry of one Kind.
Returns:
The field tree `_walk_spec_schema` descends.
"""
if "nested_fields" not in kind_entry:
return kind_entry.get("spec_schema") or {}
def _convert(plain: Any) -> dict[str, Any]:
if not isinstance(plain, dict):
return {}
return {
name: {"fields": _convert(sub)} if sub else {}
for name, sub in plain.items()
}
tree = _convert(kind_entry.get("nested_fields"))
for name in kind_entry.get("top_level_spec_fields") or []:
tree.setdefault(name, {})
return tree
def _walk_spec_schema(
spec_schema: Any, segments: list[str]
) -> tuple[Any, str, str]:
"""Descends `segments` through the `fields` / `item_fields` of a field tree.
Only those two keys hold child fields; `type`, `summary`, `enum` and
`depth_limited` describe the field itself and are never treated as children.
Args:
spec_schema: Field tree as returned by `_field_tree`.
segments: Field names below the Kind (without `spec`).
Returns:
`(node, missing, reason)`. On success `node` is the entry of the last
segment and `missing` is empty. Otherwise `missing` is the first segment
that could not be resolved and `reason` is `not_found` (`node` is the dict
of its valid siblings), `depth_limited` (the parent has sub-fields the
compiled tree does not keep) or `no_sub_fields` (the parent is a scalar, a
map or an unexpanded type; `node` is the parent's entry in both cases).
"""
node: Any = {"fields": spec_schema if isinstance(spec_schema, dict) else {}}
for seg in segments:
children = node.get("fields") or node.get("item_fields")
if not isinstance(children, dict) or not children:
reason = "depth_limited" if node.get("depth_limited") else "no_sub_fields"
return node, seg, reason
if not isinstance(children.get(seg), dict):
return children, seg, "not_found"
node = children[seg]
return node, "", ""
def _unresolved_field(
node: Any, missing: str, reason: str, where: str
) -> dict[str, Any]:
"""Error keys for a path segment `_walk_spec_schema` could not resolve."""
if reason == "not_found":
return {
"error": f"Field '{missing}' not found under {where}",
"valid_sibling_fields": sorted(node),
}
if reason == "depth_limited":
return {
"error": (
f"Field '{missing}' is below the compiled schema depth"
f" ({registry.SPEC_TREE_DEPTH} levels under spec) for {where};"
" it is neither confirmed nor ruled out"
),
"depth_limited": True,
"next_step": (
"Read the field from the CustomResourceDefinition itself"
" (`kubectl explain <resource>.spec.<path>` on the cluster, or the"
" release's CRD manifest)."
),
}
return {
"error": (
f"Field '{missing}' cannot be resolved under {where}: its parent"
f" (type {node.get('type') or 'not expanded'}) has no named"
" sub-fields in the schema"
),
"valid_sibling_fields": [],
}
def _explain_path(
query: str,
root_key: str,
kind_entry: dict[str, Any],
resolved_vinfo: dict[str, Any],
) -> dict[str, Any]:
"""Resolves a dotted field path under `root_key` in `kind_entry`."""
parts = [p for p in query.strip().split(".") if p]
search_parts = parts[2:] if parts[1] == "spec" else parts[1:]
node, missing, reason = _walk_spec_schema(
_field_tree(kind_entry), search_parts
)
out: dict[str, Any] = {
"detected_kueue_version": resolved_vinfo,
"kind": root_key,
"apiVersion": kind_entry.get("apiVersion"),
"queried_path": query,
}
if not missing:
out["schema"] = node
return out
where = (
f"{root_key} in {kind_entry.get('apiVersion')} (release"
f" {resolved_vinfo.get('release_version')})"
)
out.update(_unresolved_field(node, missing, reason, where))
return out
def explain_schema_path(
query: str,
version_info: dict[str, Any] | None = None,
load_live_crds: bool | None = None,
) -> dict[str, Any]:
"""Explains a Kueue Kind or dotted field path for the exact target Kueue version."""
schema, resolved_vinfo = load_schema_for_version(
version_info=version_info, load_live_crds=load_live_crds
)
if schema.get("_schema_unavailable"):
return {
"detected_kueue_version": resolved_vinfo,
"queried_path": query,
"error": "schema unavailable",
"schema_notice": schema.get("_schema_notice", ""),
}
available_kinds = sorted(k for k in schema.keys() if not k.startswith("_"))
parts = [p for p in query.strip().split(".") if p]
if not parts:
return {
"detected_kueue_version": resolved_vinfo,
"available_kinds": available_kinds,
}
kind_lookup = {k.lower(): k for k in available_kinds}
if "KueueConfiguration" in schema:
# The document's own `kind:` is `Configuration`.
kind_lookup.setdefault("configuration", "KueueConfiguration")
root_key = kind_lookup.get(parts[0].lower())
if not root_key:
return {
"detected_kueue_version": resolved_vinfo,
"error": f"Unknown Kind '{parts[0]}'",
"available_kinds": available_kinds,
}
kind_entry = schema[root_key]
if len(parts) == 1 or (len(parts) == 2 and parts[1] == "spec"):
return _explain_kind(root_key, kind_entry, resolved_vinfo)
return _explain_path(query, root_key, kind_entry, resolved_vinfo)
def validate_yaml_blocks_in_draft(
draft_text: str, version_info: dict[str, Any] | None = None
) -> list[str]:
"""Validates YAML snippets in `#### Remediation` against the exact target Kueue version's schema."""
schema, resolved_vinfo = load_schema_for_version(version_info=version_info)
return yaml_checks.check_remediation_yaml(draft_text, schema, resolved_vinfo)
# --- CLI ---------------------------------------------------------------------
def _build_parser() -> argparse.ArgumentParser:
"""Builds the CLI argument parser for `kueue_schema`."""
parser = argparse.ArgumentParser(
description=(
"Detect running Kueue version and query version-exact Kueue CRD"
" & KueueConfiguration schemas."
)
)
parser.add_argument(
"--detect",
action="store_true",
help="Detect the target Kueue release version and active API version",
)
parser.add_argument(
"--explain",
default="",
help="Explain a Kind or field path (e.g. ClusterQueue.spec.preemption)",
)
parser.add_argument(
"--mode",
default=report_output._env( # pylint: disable=protected-access
"GKE_KUEUE_TROUBLESHOOTING_MODE", "KUEUE_DIAGNOSE_MODE", "live"
),
choices=["live", "offline_data", "logs_archive"],
help="Data mode for version detection",
)
parser.add_argument(
"--data-path",
default=report_output._env( # pylint: disable=protected-access
"GKE_KUEUE_TROUBLESHOOTING_DATA_PATH", "KUEUE_DIAGNOSE_DATA_PATH"
),
help="Path to offline bundle or logs directory for version detection",
)
report_output.add_kueue_version_arguments(parser, live_crds=True)
report_output.add_no_remote_schema_argument(parser)
return parser
def main() -> int:
"""Runs the `kueue_schema` CLI entrypoint."""
args = _build_parser().parse_args()
report_output.apply_no_remote_schema(args)
live_crds_arg: bool | None = True if args.load_live_crds else None
vinfo = detect_target_kueue_version(
mode=args.mode,
data_path=args.data_path,
explicit_release_version=args.kueue_version,
explicit_api_version=args.api_version,
)
if args.detect:
_, resolved = load_schema_for_version(
version_info=vinfo, load_live_crds=live_crds_arg
)
print(json.dumps(resolved, indent=2))
return 0
if args.explain:
explained = explain_schema_path(
args.explain, version_info=vinfo, load_live_crds=live_crds_arg
)
print(json.dumps(explained, indent=2))
return 0
schema, resolved = load_schema_for_version(
version_info=vinfo, load_live_crds=live_crds_arg
)
print(
json.dumps(
{
"detected_kueue_version": resolved,
"kinds": sorted(
k for k in schema.keys() if not k.startswith("_")
),
},
indent=2,
)
)
return 0
if __name__ == "__main__":
sys.exit(main())
kueue_schema_registry.py 15.5 KB
#!/usr/bin/env python3
"""Compiled Kueue schema registry: CRD documents -> compact per-Kind field trees.
Pure functions only (no network, no git, no kubectl):
* `compile_crd_docs(crd_docs, target_short_ver, kcfg_fields_by_ver,
config_short_ver)` turns parsed `CustomResourceDefinition` documents into
`{Kind: {apiVersion, kubectl_names, all_versions, top_level_spec_fields,
spec_schema}}` plus a synthetic `KueueConfiguration` entry for the detected
configuration API version (not a CRD; its fields come from the published
`kueue-config.<version>` reference page or the built-in defaults).
* `read_cached_registry` / `write_cached_registry` persist compiled registries
under `schema_cache_dir()` (`$GKE_KUEUE_TROUBLESHOOTING_CACHE_DIR`, else
`$XDG_CACHE_HOME/gke-kueue-troubleshooting`).
"""
from __future__ import annotations
import json
import os
import re
import tempfile
from typing import Any, Iterable
def schema_cache_dir() -> str:
"""Per-user cache for downloaded/compiled schemas; never inside the skill directory."""
base = (
os.getenv("GKE_KUEUE_TROUBLESHOOTING_CACHE_DIR", "").strip()
or os.getenv("KUEUE_DIAGNOSE_CACHE_DIR", "").strip()
)
if not base:
xdg = os.getenv("XDG_CACHE_HOME", "").strip() or os.path.join(
os.path.expanduser("~"), ".cache"
)
base = os.path.join(xdg, "gke-kueue-troubleshooting")
try:
os.makedirs(base, exist_ok=True)
return base
except OSError:
fallback = os.path.join(
tempfile.gettempdir(), "gke-kueue-troubleshooting-cache"
)
os.makedirs(fallback, exist_ok=True)
return fallback
def safe_tag(tag: str) -> str:
return re.sub(r"[^a-zA-Z0-9._-]", "_", tag)
DEFAULT_KCFG_FIELDS: dict[str, list[str]] = {
"v1beta2": [
"admissionFairSharing",
"apiVersion",
"clientConnection",
"controller",
"fairSharing",
"featureGates",
"health",
"integrations",
"internalCertManagement",
"kind",
"leaderElection",
"manageJobsWithoutQueueName",
"managedJobsNamespaceSelector",
"metrics",
"multiKueue",
"namespace",
"objectRetentionPolicies",
"pprofBindAddress",
"resources",
"tls",
"visibilityServer",
"waitForPodsReady",
"webhook",
],
"v1beta1": [
"admissionFairSharing",
"apiVersion",
"clientConnection",
"controller",
"fairSharing",
"featureGates",
"health",
"integrations",
"internalCertManagement",
"kind",
"leaderElection",
"manageJobsWithoutQueueName",
"managedJobsNamespaceSelector",
"metrics",
"multiKueue",
"namespace",
"objectRetentionPolicies",
"pprofBindAddress",
"queueVisibility",
"resources",
"tls",
"waitForPodsReady",
"webhook",
],
}
def _nested_properties(
field_def: dict[str, Any], ftype: str, max_depth: int, depth: int
) -> tuple[str, dict[str, Any]]:
"""`("fields", tree)` for an object, `("item_fields", tree)` for an array of objects, else `("", {})`."""
if ftype == "object" and "properties" in field_def:
return "fields", _extract_openapi_properties(
field_def, max_depth, depth + 1
)
items_def = field_def.get("items")
if (
ftype == "array"
and isinstance(items_def, dict)
and "properties" in items_def
):
return "item_fields", _extract_openapi_properties(
items_def, max_depth, depth + 1
)
return "", {}
def _field_info(
field_def: dict[str, Any], max_depth: int, depth: int
) -> dict[str, Any]:
"""Builds the compact type, enum, and summary metadata for one field."""
ftype = field_def.get("type", "object")
desc = str(field_def.get("description") or "").strip().splitlines()
info: dict[str, Any] = {"type": ftype}
if field_def.get("enum"):
info["enum"] = field_def["enum"]
if desc and desc[0][:160]:
info["summary"] = desc[0][:160]
nested_key, nested = _nested_properties(field_def, ftype, max_depth, depth)
if nested:
info[nested_key] = nested
elif nested_key and depth + 1 >= max_depth:
# The field has sub-fields that the depth limit cut off; `--action explain`
# reports them as not compiled instead of as unknown.
info["depth_limited"] = True
return info
def _extract_openapi_properties(
prop_schema: dict[str, Any], max_depth: int = 3, depth: int = 0
) -> dict[str, Any]:
"""Recursively compacts OpenAPI v3 properties into a concise field tree."""
if not isinstance(prop_schema, dict) or depth >= max_depth:
return {}
props = prop_schema.get("properties") or {}
return {
field_name: _field_info(field_def, max_depth, depth)
for field_name, field_def in sorted(props.items())
if isinstance(field_def, dict)
}
# Bump when the compiled schema shape or the cache file naming changes so
# cached registries are rebuilt.
SCHEMA_FORMAT = 8
# Levels below `spec` kept in a compiled CRD entry (`spec.a.b.c`).
SPEC_TREE_DEPTH = 3
_HTML_HEADING_RE = re.compile(
r"<h[23]\s+id=[^\s>]*?-([A-Za-z0-9_]+)><code>\1</code>"
)
_HTML_TBODY_RE = re.compile(r"<table[^>]*>.*?<tbody>(.*?)</tbody>", re.DOTALL)
# The scan for `<br>` stops at the end of the cell or at the next row, so a
# page without closing tags cannot make every row scan to the end of the table.
_HTML_ROW_RE = re.compile(
r"<tr>\s*<td><code>([^<]+)</code>(?:(?!</td|<tr>).)*?<br>", re.DOTALL
)
_HTML_TYPE_LINK_RE = re.compile(r'href=["\']?#[^"\'>\s]*-([A-Za-z0-9_]+)["\']?')
# Nested-field tree used when the reference page is unavailable
# (`config_schema_source: builtin_defaults`). Each block is the union of the
# fields that block had in its config API version up to the release pinned as
# `kueue_schema.KUEUE_SOURCE_REF`, so a field of an older release is not
# reported as unknown. Blocks that are not listed are accepted as-is.
_REQUEUING_STRATEGY_FIELDS: dict[str, Any] = {
"timestamp": {},
"backoffLimitCount": {},
"backoffBaseSeconds": {},
"backoffMaxSeconds": {},
}
DEFAULT_KCFG_NESTED: dict[str, dict[str, Any]] = {
"v1beta2": {
"waitForPodsReady": {
"timeout": {},
"blockAdmission": {},
"recoveryTimeout": {},
"unscheduledTimeout": {},
"maxTimeoutOnWorkload": {},
"requeuingStrategy": dict(_REQUEUING_STRATEGY_FIELDS),
},
"integrations": {
"frameworks": {},
"externalFrameworks": {},
"labelKeysToCopy": {},
},
},
"v1beta1": {
"waitForPodsReady": {
"enable": {},
"timeout": {},
"blockAdmission": {},
"recoveryTimeout": {},
"requeuingStrategy": dict(_REQUEUING_STRATEGY_FIELDS),
},
"integrations": {
"frameworks": {},
"externalFrameworks": {},
"podOptions": {},
"labelKeysToCopy": {},
},
},
}
def _html_type_tables(html_text: str) -> dict[str, list[tuple[str, str]]]:
"""Extracts `{TypeName: [(field_name, linked_type_or_empty), ...]}` from a kueue-config reference HTML page."""
matches = list(_HTML_HEADING_RE.finditer(html_text))
tables: dict[str, list[tuple[str, str]]] = {}
for idx, m in enumerate(matches):
tname = m.group(1)
end = matches[idx + 1].start() if idx + 1 < len(matches) else len(html_text)
tb = _HTML_TBODY_RE.search(html_text[m.end() : end])
if not tb:
continue
rows: list[tuple[str, str]] = []
for rm in _HTML_ROW_RE.finditer(tb.group(1)):
fname = rm.group(1).strip()
after = tb.group(1)[rm.end() : rm.end() + 600].split("</tr>", 1)[0]
lm = _HTML_TYPE_LINK_RE.search(after)
rows.append((fname, lm.group(1) if lm else ""))
tables[tname] = rows
return tables
def parse_kcfg_struct_tree_from_html(
html_text: str, root: str = "Configuration", max_depth: int = 4
) -> dict[str, Any]:
"""Builds a nested `{field: {sub_field: {...}}}` tree for `root` from a published `kueue-config` reference HTML page."""
tables = _html_type_tables(html_text)
def _walk(
type_name: str, depth: int, seen: tuple[str, ...]
) -> dict[str, Any]:
rows = tables.get(type_name)
if not rows or depth > max_depth or type_name in seen:
return {}
out: dict[str, Any] = {}
for fname, linked in rows:
if fname == "ControllerManager" or (
fname.startswith("(") and "ControllerManager" in fname
):
out.update(_walk("ControllerManager", depth, seen + (type_name,)))
continue
if fname in ("apiVersion", "kind") or fname.startswith("("):
continue
sub = (
_walk(linked, depth + 1, seen + (type_name,))
if linked in tables
else {}
)
out[fname] = sub
return out
# No field is added here: the page of each config API version lists exactly
# the fields that version decodes (`integrations.podOptions` is v1beta1-only).
return _walk(root, 0, ())
def kcfg_fields_and_tree(html_text: str) -> dict[str, Any]:
"""Returns `{"fields": [...top-level...], "tree": {...nested...}}` for a `kueue-config` reference HTML page."""
tree = parse_kcfg_struct_tree_from_html(html_text)
fields = sorted({"apiVersion", "kind", *tree.keys()}) if tree else []
return {"fields": fields, "tree": tree}
def _choose_crd_version(
versions: list[Any], target_short_ver: str
) -> dict[str, Any] | None:
"""The requested version first; otherwise the storage version; otherwise the last one listed."""
for v in versions:
if isinstance(v, dict) and v.get("name") == target_short_ver:
return v
for v in versions:
if isinstance(v, dict) and v.get("storage"):
return v
chosen = versions[-1]
return chosen if isinstance(chosen, dict) else None
def _kubectl_names(names: dict[str, Any]) -> list[str]:
"""plural / singular / shortNames as `kubectl` accepts them (lower-cased, sorted, de-duplicated)."""
return sorted({
str(n).lower()
for n in [
names.get("plural"),
names.get("singular"),
*(names.get("shortNames") or []),
]
if n
})
def _compile_crd_entry(
doc: dict[str, Any], target_short_ver: str
) -> tuple[str, dict[str, Any]] | None:
"""Compact registry entry `(Kind, entry)` for one Kueue CRD document, or None when it is not one."""
spec = doc.get("spec")
if not isinstance(spec, dict):
return None
group = spec.get("group", "kueue.x-k8s.io")
names = spec.get("names")
versions = spec.get("versions")
if (
not isinstance(group, str)
or not isinstance(names, dict)
or not isinstance(versions, list)
):
return None
kind = names.get("kind", "")
if (
"kueue.x-k8s.io" not in group
or not isinstance(kind, str)
or not kind
or not versions
):
return None
chosen_ver = _choose_crd_version(versions, target_short_ver)
if chosen_ver is None:
return None
raw_ver_name = chosen_ver.get("name")
ver_name = (
raw_ver_name
if isinstance(raw_ver_name, str) and raw_ver_name
else target_short_ver
)
raw_schema = chosen_ver.get("schema")
open_api = (
raw_schema.get("openAPIV3Schema")
if isinstance(raw_schema, dict)
else None
)
if not isinstance(open_api, dict):
open_api = {}
raw_props = open_api.get("properties")
spec_schema = raw_props.get("spec") if isinstance(raw_props, dict) else None
if not isinstance(spec_schema, dict):
spec_schema = {}
spec_tree = _extract_openapi_properties(spec_schema, SPEC_TREE_DEPTH)
return kind, {
"apiVersion": f"{group}/{ver_name}",
"kubectl_names": _kubectl_names(names),
"all_versions": [
f"{group}/{v.get('name')}"
for v in versions
if isinstance(v, dict) and v.get("name")
],
"top_level_spec_fields": sorted(spec_tree.keys()),
"spec_schema": spec_tree,
}
def _kueue_configuration_entry(cfg_ver: str, cfg_entry: Any) -> dict[str, Any]:
"""Synthetic `KueueConfiguration` entry from a parsed reference field tree (`{"fields", "tree"}`), a bare field list or the defaults."""
cfg_tree: dict[str, Any] = {}
if isinstance(cfg_entry, dict):
cfg_fields = cfg_entry.get("fields") or []
cfg_tree = cfg_entry.get("tree") or {}
else:
cfg_fields = cfg_entry or []
if not cfg_fields:
cfg_fields = DEFAULT_KCFG_FIELDS.get(
cfg_ver, DEFAULT_KCFG_FIELDS["v1beta2"]
)
if not cfg_tree:
cfg_tree = DEFAULT_KCFG_NESTED.get(cfg_ver, DEFAULT_KCFG_NESTED["v1beta2"])
return {
"apiVersion": f"config.kueue.x-k8s.io/{cfg_ver}",
"all_versions": [
"config.kueue.x-k8s.io/v1beta2",
"config.kueue.x-k8s.io/v1beta1",
],
"top_level_spec_fields": sorted(cfg_fields),
"nested_fields": cfg_tree,
}
def config_version_for(target_short_ver: str) -> str:
"""`config.kueue.x-k8s.io` version assumed for a release whose storage version is `target_short_ver`, when the configuration version itself was not detected."""
return "v1beta1" if target_short_ver == "v1beta1" else "v1beta2"
def compile_crd_docs(
crd_docs: Iterable[dict[str, Any]],
target_short_ver: str = "v1beta2",
kcfg_fields_by_ver: dict[str, Any] | None = None,
config_short_ver: str = "",
) -> dict[str, Any]:
"""Compiles parsed CRD YAML documents into a compact schema dict.
Args:
crd_docs: Parsed `CustomResourceDefinition` documents.
target_short_ver: CRD API version to compile (`v1beta1`, `v1beta2`).
kcfg_fields_by_ver: `KueueConfiguration` field trees keyed by config API
version; the built-in defaults are used for a missing version.
config_short_ver: Detected `config.kueue.x-k8s.io` version. It is
independent of the CRD version (a release serving `v1beta2` CRDs can run a
`v1beta1` configuration); when empty it follows `target_short_ver`.
Returns:
`{Kind: entry}` for every Kueue CRD plus the `KueueConfiguration` entry.
"""
registry: dict[str, Any] = {}
for doc in crd_docs:
if not isinstance(doc, dict):
continue
compiled = _compile_crd_entry(doc, target_short_ver)
if compiled is not None:
registry[compiled[0]] = compiled[1]
cfg_ver = config_short_ver or config_version_for(target_short_ver)
registry["KueueConfiguration"] = _kueue_configuration_entry(
cfg_ver, (kcfg_fields_by_ver or {}).get(cfg_ver)
)
return registry
def read_cached_registry(cache_file: str) -> dict[str, Any] | None:
"""Reads a compiled schema registry from `cache_file` if its format matches."""
if not os.path.isfile(cache_file):
return None
try:
with open(cache_file, "r", encoding="utf-8") as f:
cached = json.load(f)
except (OSError, json.JSONDecodeError):
return None
if (
isinstance(cached, dict)
and any(not k.startswith("_") for k in cached)
and cached.get("_schema_format") == SCHEMA_FORMAT
and cached.get("_target_short_ver")
):
return cached
return None
def write_cached_registry(
cache_file: str, compiled: dict[str, Any], short_ver: str
) -> None:
"""Atomically writes a compiled schema registry to `cache_file`."""
payload = dict(compiled)
payload["_schema_format"] = SCHEMA_FORMAT
payload["_target_short_ver"] = short_ver
try:
tmp_path = f"{cache_file}.tmp.{os.getpid()}"
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=1)
os.replace(tmp_path, cache_file)
except OSError:
# The cache only saves recompiling: an unwritable cache directory must not
# fail the run, and the registry is rebuilt next time.
pass
kueue_schema_sources.py 8.0 KB
#!/usr/bin/env python3
"""Schema source chain for the `gke-kueue-troubleshooting` skill.
`resolve_schema(request)` tries `SCHEMA_SOURCES` in order and returns the first
`SchemaResult`; when none yields a schema it returns the explicit
"unavailable" schema whose `_schema_notice` names every remedy:
1. `from_bundle_crds` — `CustomResourceDefinition` objects shipped in the
bundle;
2. `from_live_crds` — the live cluster's CRDs (`live` mode, or forced);
3. `from_git_tag` — a local Kueue checkout at the release tag;
4. `from_github_release` — the upstream release manifests (cached per user).
Every source is `(request: SchemaRequest) -> SchemaResult | None`. The request
carries the version to load and a `SchemaAdapters` bundle of callables that do
the actual I/O (kubectl, git, HTTP, compile-with-KueueConfiguration), so this
module stays free of network/subprocess code and the callables remain
patchable on `kueue_schema`.
"""
from __future__ import annotations
import dataclasses
import os
from typing import Any, Callable
import kueue_schema_registry as registry
import kueue_version
CompileWithKcfg = Callable[[list[dict[str, Any]]], dict[str, Any]]
@dataclasses.dataclass(frozen=True)
class SchemaAdapters:
"""I/O entry points used by the sources; see `kueue_schema` for implementations."""
fetch_live_crds: Callable[[], tuple[list[dict[str, Any]], str]]
resolve_git_tag: Callable[[str], str]
load_git_tag_schema: Callable[
[str, str, str], tuple[dict[str, Any] | None, str]
]
fetch_github_crds: Callable[[str], tuple[list[dict[str, Any]], str]]
compile_with_kcfg: CompileWithKcfg
repo_dir: str = ""
@dataclasses.dataclass
class SchemaRequest:
"""Inputs, policy, and live-CRD error state for a schema resolution run."""
short_api: str
release_ver: str
raw_items: list[dict[str, Any]]
load_live_crds: bool
allow_remote_fetch: bool
adapters: SchemaAdapters
# Detected `config.kueue.x-k8s.io` version; empty means "follows short_api".
config_short: str = ""
live_crds_error: str = dataclasses.field(default="", init=False)
@property
def has_release(self) -> bool:
return bool(self.release_ver) and self.release_ver != "unknown"
@property
def version_key(self) -> str:
"""CRD and configuration API versions, as used in cache file names."""
return f"{self.short_api}_cfg-{self.config_short or self.short_api}"
@dataclasses.dataclass(frozen=True)
class SchemaResult:
"""Resolved schema dictionary paired with its provenance label."""
schema: dict[str, Any]
source: str
SchemaSource = Callable[[SchemaRequest], "SchemaResult | None"]
def is_kueue_crd(obj: Any) -> bool:
"""True for a parsed `CustomResourceDefinition` whose group is under `kueue.x-k8s.io`."""
if not isinstance(obj, dict) or obj.get("kind") != "CustomResourceDefinition":
return False
group = str(((obj.get("spec") or {}).get("group")) or "")
return group == "kueue.x-k8s.io" or group.endswith(".kueue.x-k8s.io")
def from_bundle_crds(request: SchemaRequest) -> SchemaResult | None:
"""CRDs shipped inside the bundle (`raw_items`)."""
bundled = [it for it in request.raw_items if is_kueue_crd(it)]
if not bundled:
return None
return SchemaResult(
request.adapters.compile_with_kcfg(bundled),
f"bundled_crds({len(bundled)} CRDs, {request.short_api})",
)
def from_live_crds(request: SchemaRequest) -> SchemaResult | None:
"""CRDs of the live cluster; records the failure reason on the request when none are returned."""
if not request.load_live_crds:
return None
live_crds, err = request.adapters.fetch_live_crds()
if live_crds:
return SchemaResult(
request.adapters.compile_with_kcfg(live_crds),
f"live_cluster_crds({len(live_crds)} CRDs, {request.short_api})",
)
request.live_crds_error = (
err or "`kubectl get crd` returned no kueue.x-k8s.io CRDs"
)
return None
def from_git_tag(request: SchemaRequest) -> SchemaResult | None:
"""A local Kueue checkout at the (closest) release tag."""
if not request.has_release:
return None
matched_tag = request.adapters.resolve_git_tag(request.release_ver)
if not matched_tag:
return None
tag_schema, tag_src = request.adapters.load_git_tag_schema(
matched_tag, request.short_api, request.config_short
)
if not tag_schema:
return None
return SchemaResult(tag_schema, f"{tag_src}({request.short_api})")
def from_github_release(request: SchemaRequest) -> SchemaResult | None:
"""Upstream GitHub release manifests, cached per user under `schema_cache_dir()`.
The cache is keyed by release tag, CRD API version and configuration API
version. It is read before the remote-fetch policy is applied, so a release
that was downloaded once keeps working with `--no-remote-schema`.
Args:
request: The schema resolution request.
Returns:
The cached or freshly compiled schema, or None when neither is available.
"""
if not request.has_release:
return None
tag = kueue_version.normalize_release_tag(request.release_ver)
cache_file = os.path.join(
registry.schema_cache_dir(),
f"crd_schema_github_{registry.safe_tag(tag)}_{request.version_key}.json",
)
cached = registry.read_cached_registry(cache_file)
if cached is not None:
return SchemaResult(
cached, f"github_release_cache:{tag}({request.short_api})"
)
if not request.allow_remote_fetch:
return None
remote_crds, used_tag = request.adapters.fetch_github_crds(
request.release_ver
)
if not remote_crds:
return None
compiled = request.adapters.compile_with_kcfg(remote_crds)
registry.write_cached_registry(cache_file, compiled, request.short_api)
return SchemaResult(
compiled, f"github_release:{used_tag}({request.short_api})"
)
SCHEMA_SOURCES: tuple[SchemaSource, ...] = (
from_bundle_crds,
from_live_crds,
from_git_tag,
from_github_release,
)
def _unavailable_reasons(request: SchemaRequest) -> list[str]:
"""Collects human-readable reasons why no schema source succeeded."""
reasons: list[str] = []
if request.live_crds_error:
reasons.append(request.live_crds_error)
else:
reasons.append("no cluster access (mode is not `live`)")
if not request.has_release:
reasons.append("Kueue release version could not be detected")
return reasons
reasons.append(
"no local Kueue checkout with tag"
f" {kueue_version.normalize_release_tag(request.release_ver)}"
+ (
""
if request.adapters.repo_dir
else " (set GKE_KUEUE_TROUBLESHOOTING_KUEUE_REPO to use one)"
)
)
if not request.allow_remote_fetch:
reasons.append(
"remote schema download disabled (--no-remote-schema) and this"
" release is not in the local schema cache"
)
else:
reasons.append("GitHub release manifests could not be fetched")
return reasons
def unavailable_schema(request: SchemaRequest) -> SchemaResult:
"""Nothing reachable: say so explicitly instead of substituting a stale snapshot."""
schema: dict[str, Any] = {
"_schema_unavailable": True,
"_config_schema_source": "unavailable",
"_schema_notice": (
"The Kueue schema for this incident is unavailable: "
+ "; ".join(_unavailable_reasons(request))
+ ". Diagnosis can continue from the incident data, but field-level"
" schema checks are skipped and the model's built-in knowledge of"
" Kueue may not match this release. To get release-exact checks"
" provide one of: cluster access, `kubectl get crd -o json` output"
" in the bundle, a local Kueue checkout"
" (GKE_KUEUE_TROUBLESHOOTING_KUEUE_REPO), network access to GitHub,"
" or an explicit --kueue-version when the release is unknown."
),
}
return SchemaResult(schema, "unavailable")
def resolve_schema(request: SchemaRequest) -> SchemaResult:
"""First `SchemaResult` from `SCHEMA_SOURCES`, else the unavailable schema."""
for source in SCHEMA_SOURCES:
result = source(request)
if result is not None:
return result
return unavailable_schema(request)
kueue_schema_yaml_checks.py 16.5 KB
#!/usr/bin/env python3
"""Checks of the YAML manifests under `#### Remediation` against a loaded Kueue schema.
`check_remediation_yaml(draft_text, schema, version_info)` is pure: it receives
the
compiled registry (see `kueue_schema_registry`) and the resolved version info
and
returns the warning strings `validate_report.py` reports as `schema_warnings`.
`kueue_schema.validate_yaml_blocks_in_draft` loads the schema and delegates
here.
Pipeline per fenced ```yaml block: dedent and decode (a `ConfigMap` additionally
yields the `controller_manager_config.yaml` document it embeds; an undecodable
block that declares a Kueue apiVersion is reported, not skipped) -> per
document: apiVersion consistency (CRD kinds against the detected API version,
the controller configuration against the detected configuration API version)
-> field names (`KueueConfiguration` top-level + nested reference field tree, or
`spec.*` of a CRD Kind, with the `cohort` / `cohortName` rename called out).
This module is the lowest layer that reads the draft, so it also owns the one
header parser every gate uses: `draft_headers` / `split_sections` /
`section_title` (`report_checks` builds its section lookup on them).
"""
from __future__ import annotations
import dataclasses
import re
import textwrap
from typing import Any
import k8s_objects
import kueue_schema_registry as registry
import kueue_version
import yaml
# The info string ends at the line break (or directly before the content of a
# one-line block), so the indentation of the first content line survives and an
# indented block can be dedented as a whole.
_YAML_FENCE_RE = re.compile(
r"```(?:yaml|yml)\b[ \t]*(?:\r?\n|(?=\S))(.*?)```", re.DOTALL
)
_KUEUE_API_PREFIXES = ("kueue.x-k8s.io/", "config.kueue.x-k8s.io/")
_CONFIG_API_PREFIX = "config.kueue.x-k8s.io/"
# A line that declares a Kueue apiVersion (also inside an embedded controller
# configuration, which is indented).
_KUEUE_API_LINE_RE = re.compile(
r"(?m)^[ \t]*(?:-[ \t]+)?[\"']?apiVersion[\"']?[ \t]*:[ \t]*[\"']?"
r"(?:config\.)?kueue\.x-k8s\.io/"
)
# A `###` / `####` header line. Exactly one blank after the hashes is consumed
# here; the title is trimmed in `section_title`.
_HEADER_RE = re.compile(r"(?m)^[ \t]{0,3}(#{3,4})[ \t]([^\n]*)$")
_TITLE_MARKUP_RE = re.compile(r"[*_`]")
# Canonical titles of the report sections. A header is matched to them after
# normalisation, so `#### Root Causes:` is the `root cause` section.
SECTION_TITLES = (
"diagnostic summary",
"scope",
"observations",
"root cause",
"open questions",
"ruled out",
"remediation",
)
_SECTION_KEYS = {title.rstrip("s"): title for title in SECTION_TITLES}
@dataclasses.dataclass(frozen=True)
class DraftHeader:
"""One `###` / `####` header line of the draft."""
level: int
title: str # normalised, see `section_title`
inline: str # text after `<Section>:` on the header line itself
start: int # offset of the header line
end: int # offset just past the header line
def section_title(raw: str) -> str:
"""Normalises a header title.
Emphasis markers, closing hashes and a trailing `:` are dropped, whitespace is
collapsed and the result is lower-cased. A known section name is returned in
its canonical form whether it was written singular or plural.
Args:
raw: Header text after the leading hashes.
Returns:
The normalised title, e.g. `root cause` for `**Root Causes:**`.
"""
text = " ".join(_TITLE_MARKUP_RE.sub("", raw).split())
text = text.rstrip("#").strip().rstrip(":").strip().lower()
return _SECTION_KEYS.get(text.rstrip("s"), text)
def draft_headers(draft_text: str) -> list[DraftHeader]:
"""Every `###` / `####` header of the draft, in document order.
`#####` and deeper sub-headers are not headers here, so they stay inside the
section that contains them. `#### Scope: Kueue configuration` is the `scope`
header with `Kueue configuration` as its inline text.
Args:
draft_text: The draft report.
Returns:
The parsed headers.
"""
headers: list[DraftHeader] = []
for m in _HEADER_RE.finditer(draft_text):
raw = m.group(2)
head, sep, tail = raw.partition(":")
title, inline = section_title(head), ""
if sep and title in SECTION_TITLES:
inline = tail.strip().lstrip("*_").strip()
else:
title = section_title(raw)
headers.append(
DraftHeader(len(m.group(1)), title, inline, m.start(), m.end())
)
return headers
def split_sections(draft_text: str) -> dict[str, str]:
"""Returns {normalised `####` title: body text}; a repeated title is concatenated."""
heads = [h for h in draft_headers(draft_text) if h.level == 4]
parts: dict[str, list[str]] = {}
for i, head in enumerate(heads):
end = heads[i + 1].start if i + 1 < len(heads) else len(draft_text)
inline = f"{head.inline}\n" if head.inline else ""
parts.setdefault(head.title, []).append(inline + draft_text[head.end : end])
return {title: "".join(bodies) for title, bodies in parts.items()}
@dataclasses.dataclass(frozen=True)
class YamlCheckContext:
"""Loaded schema and detected version against which documents are checked."""
schema: dict[str, Any]
short_api: str
config_short_api: str
release_ver: str
schema_unavailable: bool
version_detected: bool
@classmethod
def from_schema(
cls, schema: dict[str, Any], version_info: dict[str, Any]
) -> "YamlCheckContext":
short_api = version_info.get("short_api_version", "v1beta2")
return cls(
schema=schema,
short_api=short_api,
config_short_api=kueue_version.normalize_short_api_version(
str(version_info.get("config_api_version") or "")
)
or short_api,
release_ver=version_info.get("release_version", "unknown"),
schema_unavailable=bool(schema.get("_schema_unavailable")),
version_detected=any(
not str(src).startswith("default:")
for src in version_info.get("detection_sources") or []
),
)
def remediation_yaml_blocks(draft_text: str) -> list[str]:
"""Dedented bodies of the fenced yaml/yml blocks from the first `#### Remediation` header on."""
start = next(
(
h.end
for h in draft_headers(draft_text)
if h.level == 4 and h.title == "remediation"
),
None,
)
if start is None:
return []
return [
textwrap.dedent(block)
for block in _YAML_FENCE_RE.findall(draft_text[start:])
]
def _yaml_problem(exc: Exception) -> str:
"""One-line description of a YAML decoding failure, with its line when known."""
problem = str(getattr(exc, "problem", "") or "") or str(exc).splitlines()[0]
mark = getattr(exc, "problem_mark", None)
return f"{problem} (line {mark.line + 1})" if mark is not None else problem
def decode_yaml_block(block: str, warnings: list[str]) -> list[Any]:
"""Decodes YAML documents in `block`, expanding embedded ConfigMap configs.
An undecodable block yields no documents. When it declares a Kueue apiVersion
it appends a warning, since its fields were not checked; other manifests are
outside this check. An undecodable embedded configuration appends a warning
as well (the controller would fail to start on it). PyYAML raises `ValueError`
rather than `YAMLError` for a value that looks like a timestamp but is not a
valid date.
Args:
block: Raw YAML text from one fenced remediation code block.
warnings: Mutable list receiving syntax warnings.
Returns:
Decoded YAML documents, including any embedded controller configuration.
"""
try:
docs = list(yaml.safe_load_all(block))
except (yaml.YAMLError, ValueError, RecursionError) as exc:
if _KUEUE_API_LINE_RE.search(block):
warnings.append(
"A YAML block under Remediation declares a Kueue apiVersion but is"
f" not valid YAML: {_yaml_problem(exc)}. Its fields were not"
" checked; correct the syntax."
)
return []
expanded: list[Any] = []
for doc in docs:
expanded.append(doc)
if not (
isinstance(doc, dict) and str(doc.get("kind") or "") == "ConfigMap"
):
continue
data = doc.get("data")
embedded = (
data.get(k8s_objects.KUEUE_CONFIG_KEY)
if isinstance(data, dict)
else None
)
if not isinstance(embedded, str):
continue
try:
expanded.extend(yaml.safe_load_all(embedded))
except (yaml.YAMLError, ValueError, RecursionError):
warnings.append(
"ConfigMap data 'controller_manager_config.yaml' is not valid"
" YAML; the controller will fail to start."
)
return expanded
def _registry_kind(kind: str, api_ver: str) -> str:
"""Maps `Configuration` under `config.kueue.x-k8s.io` to `KueueConfiguration`."""
group, sep, _ = api_ver.partition("/")
if kind == "Configuration" and (
not api_ver or (sep and group == "config.kueue.x-k8s.io")
):
return "KueueConfiguration"
return kind
def _api_version_only_warnings(
kind: str, api_ver: str, ctx: YamlCheckContext
) -> list[str]:
"""Checks `apiVersion` alone when the schema is unavailable."""
expected = (
ctx.config_short_api
if api_ver.startswith(_CONFIG_API_PREFIX)
else ctx.short_api
)
if (
ctx.version_detected
and api_ver.startswith(_KUEUE_API_PREFIXES)
and kueue_version.normalize_short_api_version(api_ver) != expected
):
return [
f"apiVersion '{api_ver}' for {kind} does not match the detected"
f" API version {expected} (release {ctx.release_ver}). Field names"
" were not checked: schema unavailable."
]
return []
def _config_api_version_warnings(
api_ver: str, expected_api: str, release_ver: str
) -> list[str]:
"""A controller configuration is written in the configuration API version the controller loads."""
if kueue_version.normalize_short_api_version(
api_ver
) == kueue_version.normalize_short_api_version(expected_api):
return []
if "v1beta1" in api_ver and "v1beta2" in expected_api:
return [
f"Outdated apiVersion '{api_ver}' for KueueConfiguration: target"
f" cluster (release {release_ver}) uses '{expected_api}'."
]
return [
f"apiVersion '{api_ver}' for KueueConfiguration does not match the"
f" controller configuration API version '{expected_api}' detected for"
f" release {release_ver}; its fields are checked against"
f" '{expected_api}'."
]
def _api_version_warnings(
kind: str, api_ver: str, entry: dict[str, Any], ctx: YamlCheckContext
) -> list[str]:
"""Checks `api_ver` against the target release's expected API versions."""
expected_api = str(entry.get("apiVersion") or "")
all_supported = set(entry.get("all_versions") or [expected_api])
if not api_ver:
return []
if kind == "KueueConfiguration":
# The entry is compiled for the detected `config_api_version`, which is
# independent of the CRD API version.
return _config_api_version_warnings(api_ver, expected_api, ctx.release_ver)
if (
ctx.short_api == "v1beta2"
and "v1beta1" in api_ver
and "v1beta2" in expected_api
):
return [
f"Outdated apiVersion '{api_ver}' for {kind}: target cluster"
f" (release {ctx.release_ver}) uses '{expected_api}'."
]
if ctx.short_api == "v1beta1" and api_ver not in all_supported:
return [
f"Unsupported apiVersion '{api_ver}' for {kind} in target Kueue"
f" release {ctx.release_ver}: supported versions are"
f" {sorted(all_supported)} (expected '{expected_api}')."
]
return []
def _unknown_nested_config_fields(
doc: dict[str, Any],
tree: dict[str, Any],
labels: tuple[str, str],
path: str = "",
) -> list[str]:
"""Reports unknown nested fields in a `KueueConfiguration` document.
Only blocks present in `tree` are descended into; a block whose tree entry is
empty (`{}`) is a leaf or an unparsed type and is accepted as-is.
Args:
doc: Current mapping node within the `KueueConfiguration` document.
tree: Reference nested field tree for the current level.
labels: Tuple of `(expected_api, release_ver)` for warning messages.
path: Dotted field prefix accumulated during recursion.
Returns:
Warning strings for unknown nested configuration fields.
"""
expected_api, release_ver = labels
out: list[str] = []
for key, value in doc.items():
sub_tree = tree.get(key)
if not isinstance(sub_tree, dict) or not sub_tree:
continue
children = value if isinstance(value, list) else [value]
for child in children:
if not isinstance(child, dict):
continue
here = f"{path}{key}"
for child_key in child:
if child_key not in sub_tree:
out.append(
f"Unknown field '{here}.{child_key}' in KueueConfiguration for"
f" {expected_api} (release {release_ver})."
f" Valid fields under '{here}':"
f" {sorted(sub_tree)}."
)
out.extend(
_unknown_nested_config_fields(
child, sub_tree, labels, path=f"{here}."
)
)
return out
def _kueue_configuration_warnings(
doc: dict[str, Any], entry: dict[str, Any], ctx: YamlCheckContext
) -> list[str]:
"""Checks top-level and nested field names of a `KueueConfiguration` doc."""
expected_api = str(entry.get("apiVersion") or "")
valid_top = set(entry["top_level_spec_fields"])
warnings = [
f"Unknown field '{k}' in KueueConfiguration for"
f" {expected_api} (release {ctx.release_ver})."
f" Valid fields: {sorted(valid_top)}."
for k in doc
if k not in valid_top
]
cfg_short = (
kueue_version.normalize_short_api_version(expected_api) or "v1beta2"
)
nested_tree = entry.get("nested_fields") or registry.DEFAULT_KCFG_NESTED.get(
cfg_short, {}
)
warnings.extend(
_unknown_nested_config_fields(
doc, nested_tree, (expected_api, ctx.release_ver)
)
)
return warnings
def _cohort_rename_warning(
spec: dict[str, Any],
valid_spec: set[str],
expected_api: str,
release_ver: str,
) -> list[str]:
"""Flags `spec.cohort` vs `spec.cohortName` mismatches for `ClusterQueue`."""
if (
"cohort" in spec
and "cohortName" in valid_spec
and "cohort" not in valid_spec
):
return [
"Deprecated field 'spec.cohort' in ClusterQueue YAML: use"
f" 'spec.cohortName' in {expected_api} (release {release_ver})."
]
if (
"cohortName" in spec
and "cohort" in valid_spec
and "cohortName" not in valid_spec
):
return [
f"Field 'spec.cohortName' is not supported in {expected_api}"
f" (release {release_ver}): use 'spec.cohort' in v1beta1."
]
return []
def _spec_field_warnings(
kind: str, doc: dict[str, Any], entry: dict[str, Any], ctx: YamlCheckContext
) -> list[str]:
"""Checks top-level `spec` fields of a Kueue CRD manifest against `entry`."""
spec = doc.get("spec")
if not isinstance(spec, dict):
return []
expected_api = str(entry.get("apiVersion") or "")
valid_spec = set(entry.get("top_level_spec_fields") or [])
warnings: list[str] = []
if kind == "ClusterQueue":
warnings.extend(
_cohort_rename_warning(spec, valid_spec, expected_api, ctx.release_ver)
)
for k in spec:
if valid_spec and k not in valid_spec and k not in ("cohort", "cohortName"):
warnings.append(
f"Unknown field 'spec.{k}' in {kind} ({expected_api}, release"
f" {ctx.release_ver}). Valid spec fields: {sorted(valid_spec)}."
)
return warnings
def check_document(doc: Any, ctx: YamlCheckContext) -> list[str]:
"""Warnings for one decoded YAML document (non-mapping documents are ignored)."""
if not isinstance(doc, dict):
return []
kind = str(doc.get("kind") or "")
api_ver = str(doc.get("apiVersion") or "")
if ctx.schema_unavailable:
return _api_version_only_warnings(kind, api_ver, ctx)
kind = _registry_kind(kind, api_ver)
if not kind or kind.startswith("_") or kind not in ctx.schema:
return []
entry = ctx.schema[kind]
warnings = _api_version_warnings(kind, api_ver, entry, ctx)
if kind == "KueueConfiguration":
warnings.extend(_kueue_configuration_warnings(doc, entry, ctx))
else:
warnings.extend(_spec_field_warnings(kind, doc, entry, ctx))
return warnings
def check_remediation_yaml(
draft_text: str, schema: dict[str, Any], version_info: dict[str, Any]
) -> list[str]:
"""All schema warnings for the YAML blocks under `#### Remediation`, in document order."""
ctx = YamlCheckContext.from_schema(schema, version_info)
warnings: list[str] = []
for block in remediation_yaml_blocks(draft_text):
for doc in decode_yaml_block(block, warnings):
warnings.extend(check_document(doc, ctx))
return warnings
kueue_version.py 16.7 KB
#!/usr/bin/env python3
"""Kueue release / API version detection for the `gke-kueue-troubleshooting` skill.
`detect_target_kueue_version()` runs a fixed chain of detectors
(`VERSION_DETECTORS`) over one `VersionDetection` context. Every detector
returns an ordered list of `VersionClue`s; the chain adopts a clue only when the
field it supports (`release_version`, `short_api`, `config_short_api`) is still
unknown, and records the clue's `source` string in `detection_sources` in the
order the clues were produced. The precedence is therefore:
1. explicit overrides (arguments, then
`GKE_KUEUE_TROUBLESHOOTING_KUEUE_VERSION` /
`GKE_KUEUE_TROUBLESHOOTING_API_VERSION`);
2. Kubernetes objects (controller Deployment/Pod labels and image tags, the
`kueue-manager-config` ConfigMap, apiVersions of Kueue objects), scanned
once in list order so the sources interleave exactly as the objects do;
3. controller log lines (passed in, or the first 400 lines of the bundle's
controller log files): `gitVersion`, `config.kueue.x-k8s.io/<ver>` and the
dominant `kueue.x-k8s.io/<ver>`;
4. the live `Deployment/kueue-controller-manager` (`live` mode only, and only
when no release version was found so far);
5. the API version inferred from the release (`<= v0.15` -> `v1beta1`).
Anything still unknown afterwards falls back to the config API version or to
`v1beta2` (`default:v1beta2` is recorded only when no source was found at all).
"""
from __future__ import annotations
import dataclasses
import json
import os
import re
import stat
import subprocess
from typing import Any, Callable
import k8s_objects
_SEMVER_SUFFIX = (
r"(?:-[a-zA-Z0-9_]+(?:[.-][a-zA-Z0-9_]+)*)?"
r"(?:\+[a-zA-Z0-9_]+(?:[.-][a-zA-Z0-9_]+)*)?"
)
_IMAGE_TAG_RE = re.compile(
rf"kueue[^:\s]{{0,128}}:(v[0-9]+\.[0-9]+\.[0-9]+{_SEMVER_SUFFIX})"
)
_LABEL_VERSION_RE = re.compile(
rf"^v?[0-9]+\.[0-9]+(?:\.[0-9]+)?{_SEMVER_SUFFIX}$"
)
_CONFIG_API_RE = re.compile(
r"config\.kueue\.x-k8s\.io/(v1(?:alpha|beta)[0-9]+)"
)
_CONFIGMAP_API_RE = re.compile(
r"apiVersion:\s*config\.kueue\.x-k8s\.io/(v1(?:alpha|beta)[0-9]+)"
)
_GIT_VERSION_RE = re.compile(
rf'"gitVersion"\s*:\s*"(v[0-9]+\.[0-9]+\.[0-9]+{_SEMVER_SUFFIX})"'
)
_LOG_API_RE = re.compile(
r"(?:(?<!config\.)kueue\.x-k8s\.io/|io\.x-k8s\.kueue\.)(v1beta[12])\b"
)
_KUEUE_OBJECT_KINDS = (
"ClusterQueue",
"LocalQueue",
"Workload",
"ResourceFlavor",
"AdmissionCheck",
"ProvisioningRequestConfig",
)
_BUNDLE_LOG_HEAD_LINES = 400
_LIVE_DEPLOYMENT_TIMEOUT_SECONDS = 4
RELEASE_VERSION = "release_version"
SHORT_API = "short_api"
CONFIG_SHORT_API = "config_short_api"
def normalize_short_api_version(api_ver: str) -> str:
"""Extracts short version (`v1beta1`, `v1beta2`, `v1alpha1`) from an apiVersion string."""
if not api_ver:
return ""
s = api_ver.strip()
if "/" in s:
s = s.rsplit("/", 1)[-1]
return s
def normalize_release_tag(release_version: str) -> str:
"""`0.19.4` -> `v0.19.4`; empty, `unknown`, or malformed -> ``."""
norm = (release_version or "").strip()
if not norm or norm == "unknown":
return ""
if not norm.startswith("v") and re.search(r"^[0-9]+\.[0-9]+", norm):
norm = f"v{norm}"
if not _LABEL_VERSION_RE.fullmatch(norm):
return ""
return norm
def _label_release(labels: dict[str, Any], *keys: str) -> str:
"""Release version from the first non-empty label among `keys`, `v`-prefixed; `` if absent."""
lbl_ver = ""
for key in keys:
lbl_ver = str(labels.get(key) or "").strip()
if lbl_ver:
break
if lbl_ver and _LABEL_VERSION_RE.match(lbl_ver):
return lbl_ver if lbl_ver.startswith("v") else f"v{lbl_ver}"
return ""
def _container_images(pod_spec: dict[str, Any]) -> list[str]:
return [
str(c.get("image") or "")
for c in k8s_objects.dict_items(pod_spec.get("containers"))
]
def _pod_spec(item: dict[str, Any], kind: str) -> dict[str, Any]:
"""Pod spec of a Deployment (`spec.template.spec`) or a Pod (`spec`); `{}` for any other shape."""
spec = k8s_objects.spec(item)
if kind != "Deployment":
return spec
template = k8s_objects.as_dict(spec.get("template"))
return k8s_objects.as_dict(template.get("spec"))
@dataclasses.dataclass(frozen=True)
class VersionClue:
"""One piece of version evidence: target field, value, and source entry."""
field: str
value: str
source: str
@dataclasses.dataclass
class VersionDetectionInputs:
"""Arguments of `detect_target_kueue_version()` after env defaults."""
mode: str = "live"
raw_items: list[dict[str, Any]] = dataclasses.field(default_factory=list)
log_lines: list[str] = dataclasses.field(default_factory=list)
data_path: str = ""
explicit_release_version: str = ""
explicit_api_version: str = ""
kueue_namespace: str = "kueue-system"
@dataclasses.dataclass
class VersionDetection:
"""Detection context holding inputs and clues established so far."""
inputs: VersionDetectionInputs
release_version: str = ""
short_api: str = ""
config_short_api: str = ""
sources: list[str] = dataclasses.field(default_factory=list)
def known(self, name: str) -> str:
return str(getattr(self, name))
def adopt(self, clues: list[VersionClue]) -> None:
"""Takes the first clue per field, recording its source; later clues for a known field are dropped."""
for clue in clues:
if clue.value and not self.known(clue.field):
setattr(self, clue.field, clue.value)
self.sources.append(clue.source)
VersionDetector = Callable[[VersionDetection], list[VersionClue]]
def detect_from_explicit(ctx: VersionDetection) -> list[VersionClue]:
"""Explicit overrides: arguments first, then the `GKE_KUEUE_TROUBLESHOOTING_*` / `KUEUE_DIAGNOSE_*` env vars."""
clues: list[VersionClue] = []
release = (
ctx.inputs.explicit_release_version
or os.getenv("GKE_KUEUE_TROUBLESHOOTING_KUEUE_VERSION", "").strip()
or os.getenv("KUEUE_DIAGNOSE_KUEUE_VERSION", "").strip()
)
if release:
clues.append(
VersionClue(
RELEASE_VERSION, release, f"explicit:release_version={release}"
)
)
short_api = normalize_short_api_version(
ctx.inputs.explicit_api_version
or os.getenv("GKE_KUEUE_TROUBLESHOOTING_API_VERSION", "").strip()
or os.getenv("KUEUE_DIAGNOSE_API_VERSION", "").strip()
)
if short_api:
clues.append(
VersionClue(SHORT_API, short_api, f"explicit:api_version={short_api}")
)
return clues
def _controller_workload_clues(
item: dict[str, Any], kind: str
) -> list[VersionClue]:
"""Label then image-tag clues from a `kueue-controller-manager` Deployment or Pod."""
clues: list[VersionClue] = []
lbl_release = _label_release(
k8s_objects.labels(item), "app.kubernetes.io/version", "version"
)
if lbl_release:
clues.append(
VersionClue(
RELEASE_VERSION, lbl_release, f"{kind.lower()}_label:{lbl_release}"
)
)
for img in _container_images(_pod_spec(item, kind)):
m_img = _IMAGE_TAG_RE.search(img)
if m_img:
clues.append(
VersionClue(
RELEASE_VERSION,
m_img.group(1),
f"{kind.lower()}_image:{m_img.group(1)}",
)
)
return clues
def _configmap_clue(item: dict[str, Any]) -> list[VersionClue]:
cfg_text = str(
k8s_objects.as_dict(item.get("data")).get(k8s_objects.KUEUE_CONFIG_KEY)
or ""
)
m_cfg = _CONFIGMAP_API_RE.search(cfg_text)
if not m_cfg:
return []
return [
VersionClue(
CONFIG_SHORT_API,
m_cfg.group(1),
f"configmap:config.kueue.x-k8s.io/{m_cfg.group(1)}",
)
]
@dataclasses.dataclass
class _ObjectApiTally:
"""Tallies observed Kueue object API versions and cohort spec fields."""
counts: dict[str, int] = dataclasses.field(default_factory=dict)
has_v1beta1_cohort_field: bool = False
has_v1beta2_cohort_name_field: bool = False
def observe(self, item: dict[str, Any], kind: str, api_ver: str) -> None:
sv = normalize_short_api_version(api_ver)
if sv in ("v1beta1", "v1beta2"):
self.counts[sv] = self.counts.get(sv, 0) + 1
spec = item.get("spec") or {}
if kind == "ClusterQueue" and isinstance(spec, dict):
if "cohort" in spec and "cohortName" not in spec:
self.has_v1beta1_cohort_field = True
elif "cohortName" in spec:
self.has_v1beta2_cohort_name_field = True
def clues(self) -> list[VersionClue]:
if self.counts:
best = max(sorted(self.counts.keys()), key=lambda k: self.counts[k])
return [
VersionClue(SHORT_API, best, f"k8s_objects:kueue.x-k8s.io/{best}")
]
if self.has_v1beta1_cohort_field and not self.has_v1beta2_cohort_name_field:
return [
VersionClue(SHORT_API, "v1beta1", "clusterqueue_spec:cohort->v1beta1")
]
return []
def detect_from_objects(ctx: VersionDetection) -> list[VersionClue]:
"""One pass over the snapshot / bundle objects, in list order (the source order follows the objects)."""
clues: list[VersionClue] = []
tally = _ObjectApiTally()
for it in ctx.inputs.raw_items:
if not isinstance(it, dict):
continue
kind = str(it.get("kind") or "")
api_ver = str(it.get("apiVersion") or "")
name = str(k8s_objects.metadata(it).get("name") or "")
if kind in ("Deployment", "Pod") and "kueue-controller-manager" in name:
clues.extend(_controller_workload_clues(it, kind))
api_group, api_sep, _ = api_ver.partition("/")
if (
kind in _KUEUE_OBJECT_KINDS
and api_sep
and (
api_group == "kueue.x-k8s.io"
or api_group.endswith(".kueue.x-k8s.io")
)
):
tally.observe(it, kind, api_ver)
if kind == "ConfigMap" and name == "kueue-manager-config":
clues.extend(_configmap_clue(it))
clues.extend(tally.clues())
return clues
def _bundle_log_head(data_path: str) -> list[str]:
"""The first lines of the controller log files a bundle may ship, in the fixed candidate order."""
lines: list[str] = []
root_real = os.path.realpath(data_path)
logs_dir = os.path.join(data_path, "logs")
candidates = [
os.path.join(data_path, "kueue-controller-manager.log"),
os.path.join(data_path, "kueue_logs.jsonl"),
]
if not os.path.islink(logs_dir):
candidates.insert(0, os.path.join(logs_dir, "kueue-controller-manager.log"))
for candidate_log in candidates:
try:
if not stat.S_ISREG(os.lstat(candidate_log).st_mode):
continue
cand_real = os.path.realpath(candidate_log)
if os.path.commonpath([root_real, cand_real]) != root_real:
continue
except (OSError, ValueError):
continue
try:
with open(candidate_log, "r", encoding="utf-8", errors="replace") as f:
for _ in range(_BUNDLE_LOG_HEAD_LINES):
ln = f.readline()
if not ln:
break
lines.append(ln)
except OSError:
# An unreadable candidate is skipped; the next one may still be readable.
pass
return lines
def detect_from_logs(ctx: VersionDetection) -> list[VersionClue]:
"""Controller log lines: `gitVersion`, the config API version and the dominant Kueue API version."""
all_lines = list(ctx.inputs.log_lines)
data_path = ctx.inputs.data_path
if (
data_path
and os.path.isdir(data_path)
and (not ctx.release_version or not ctx.short_api)
):
all_lines.extend(_bundle_log_head(data_path))
clues: list[VersionClue] = []
seen_release = seen_config = False
api_counts: dict[str, int] = {}
for ln in all_lines:
if not seen_release and ("gitVersion" in ln or "v0." in ln):
m_git = _GIT_VERSION_RE.search(ln)
if m_git:
seen_release = True
clues.append(
VersionClue(
RELEASE_VERSION,
m_git.group(1),
f"controller_log:gitVersion={m_git.group(1)}",
)
)
if not seen_config:
m_c = _CONFIG_API_RE.search(ln)
if m_c:
seen_config = True
clues.append(
VersionClue(
CONFIG_SHORT_API,
m_c.group(1),
f"controller_log:config.kueue.x-k8s.io/{m_c.group(1)}",
)
)
for m_k in _LOG_API_RE.finditer(ln):
api_counts[m_k.group(1)] = api_counts.get(m_k.group(1), 0) + 1
if api_counts:
best = max(sorted(api_counts.keys()), key=lambda k: api_counts[k])
clues.append(VersionClue(SHORT_API, best, f"logs:kueue.x-k8s.io/{best}"))
return clues
def _live_controller_deployment(namespace: str) -> dict[str, Any] | None:
"""Fetches the live `kueue-controller-manager` Deployment JSON, or None."""
try:
res = subprocess.run(
[
"kubectl",
"get",
"deployment",
"kueue-controller-manager",
"-n",
namespace,
"-o",
"json",
"--ignore-not-found=true",
],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=_LIVE_DEPLOYMENT_TIMEOUT_SECONDS,
)
if res.returncode == 0 and res.stdout.strip():
dep = json.loads(res.stdout)
return dep if isinstance(dep, dict) else None
except (OSError, subprocess.SubprocessError, ValueError):
# No kubectl, no access or no JSON (`json.JSONDecodeError` is a
# ValueError): the live Deployment is not a source.
pass
return None
def detect_from_live_deployment(ctx: VersionDetection) -> list[VersionClue]:
"""`live` mode only: the controller Deployment's version label and image tag (skipped once a release is known)."""
if ctx.inputs.mode != "live" or ctx.release_version:
return []
dep = _live_controller_deployment(ctx.inputs.kueue_namespace)
if dep is None:
return []
clues: list[VersionClue] = []
lbl_release = _label_release(
k8s_objects.labels(dep), "app.kubernetes.io/version"
)
if lbl_release:
clues.append(
VersionClue(
RELEASE_VERSION, lbl_release, f"live_deployment_label:{lbl_release}"
)
)
for img in _container_images(_pod_spec(dep, "Deployment")):
m_img = _IMAGE_TAG_RE.search(img)
if m_img:
clues.append(
VersionClue(
RELEASE_VERSION,
m_img.group(1),
f"live_deployment_image:{m_img.group(1)}",
)
)
return clues
def detect_from_release(ctx: VersionDetection) -> list[VersionClue]:
"""Kueue v0.1 through v0.15 store `v1beta1`; v0.16+ store `v1beta2`."""
if ctx.short_api or not ctx.release_version:
return []
m_minor = re.search(r"^v?0\.([0-9]+)", ctx.release_version)
if not m_minor:
return []
short_api = "v1beta1" if int(m_minor.group(1)) <= 15 else "v1beta2"
return [
VersionClue(
SHORT_API,
short_api,
f"inferred_from_release:{ctx.release_version}->{short_api}",
)
]
VERSION_DETECTORS: tuple[VersionDetector, ...] = (
detect_from_explicit,
detect_from_objects,
detect_from_logs,
detect_from_live_deployment,
detect_from_release,
)
def _finalize(ctx: VersionDetection) -> dict[str, Any]:
if not ctx.short_api:
ctx.short_api = (
ctx.config_short_api
if ctx.config_short_api in ("v1beta1", "v1beta2")
else "v1beta2"
)
if not ctx.sources:
ctx.sources.append("default:v1beta2")
if not ctx.config_short_api:
ctx.config_short_api = ctx.short_api
return {
"release_version": ctx.release_version or "unknown",
"api_version": f"kueue.x-k8s.io/{ctx.short_api}",
"short_api_version": ctx.short_api,
"config_api_version": f"config.kueue.x-k8s.io/{ctx.config_short_api}",
"detection_sources": ctx.sources,
"mode": ctx.inputs.mode,
}
def run_version_detection(inputs: VersionDetectionInputs) -> dict[str, Any]:
"""Applies `VERSION_DETECTORS` in order and returns the `detected_kueue_version` dict."""
ctx = VersionDetection(inputs=inputs)
for detector in VERSION_DETECTORS:
ctx.adopt(detector(ctx))
return _finalize(ctx)
def detect_target_kueue_version(
mode: str = "live",
raw_items: list[dict[str, Any]] | None = None,
log_lines: list[str] | None = None,
data_path: str = "",
explicit_release_version: str = "",
explicit_api_version: str = "",
kueue_namespace: str = "",
) -> dict[str, Any]:
"""Detects the target Kueue release version and active API versions from cluster, bundle, or logs."""
inputs = VersionDetectionInputs(
mode=mode,
raw_items=list(raw_items or []),
log_lines=list(log_lines or []),
data_path=data_path,
explicit_release_version=explicit_release_version,
explicit_api_version=explicit_api_version,
kueue_namespace=(
kueue_namespace
or os.getenv("GKE_KUEUE_TROUBLESHOOTING_NAMESPACE", "").strip()
or os.getenv("KUEUE_DIAGNOSE_NAMESPACE", "").strip()
or "kueue-system"
),
)
return run_version_detection(inputs)
log_envelopes.py 38.2 KB
#!/usr/bin/env python3
"""Vendor-neutral log record normalisation for `trace_logs.py`.
Log exports arrive in many shapes depending on where they were collected:
* raw Kueue controller output (zap JSON, one object per line) — `kubectl
logs`;
* Kubernetes audit events (`audit.k8s.io/v1` `Event` objects, JSONL);
* Kubernetes Events (`v1` or `events.k8s.io/v1`, from `kubectl get events -o
json`
or an events exporter);
* collector envelopes that wrap one of the above in an outer object:
- Google Cloud Logging export / `gcloud logging read --format=json`
(`jsonPayload` / `protoPayload` / `textPayload`, `severity`,
`timestamp`);
- fluent-bit / Fluentd / Filebeat (`log` or `message`, `kubernetes`,
`time`,
`@timestamp`);
- Grafana Loki `logcli --output=jsonl` (`line`, `labels`, `timestamp`);
- tabular log export rows (`LogMessage`, capitalised `audit.k8s.io`
fields);
* klog text lines (`I0924 12:09:02.123456 1 main.go:748] ...`).
`iter_records()` accepts a file's text in any of these shapes (JSON array, JSONL
or
plain lines) and yields one normalised line per record. Normalised records are
JSON
objects with at least `ts`, `level` and `msg`; audit records additionally carry
the
neutral tuple `verb`, `resource`, `subresource`, `namespace`, `name` under
`logger: "audit"`, regardless of whether they came from a Kubernetes audit
webhook
or from a cloud provider's audit-log format. Unrecognised lines are passed
through
unchanged so text-based matching still works.
Workload secrets can enter a log record via audit request bodies, validation
error dumps (JSON or Go `EnvVar` structs), or accidental Kubernetes `Secret`
manifests mixed into a bundle: every literal container `env[].value` is
replaced with `<REDACTED>` here (`redact_env_values`, `redact_env_text`), and
non-log Kubernetes manifests (`Secret`, `List`, etc.) or truncated JSON
fragments are dropped before a record reaches any fact, report file or ledger.
Kubernetes Event objects are stamped `source_kind: "k8s-event"` so that
downstream counting can tell them from controller log lines that merely
describe an Event.
No third-party dependencies; this module never contacts any service.
"""
from __future__ import annotations
import dataclasses
import json
import re
from typing import Any, Callable, Iterator
_KLOG_RE = re.compile(
r"^([IWEF])(\d{4}) (\d{2}:\d{2}:\d{2}(?:\.\d+)?)\s+\d+\s+\S+:\d+\]\s*(.*)$"
)
_KLOG_LEVELS = {"I": "info", "W": "warning", "E": "error", "F": "fatal"}
# Google Cloud audit `methodName` is the reversed API group followed by
# `<version>.<resource>[.<subresource>].<verb>`, e.g.
# `io.k8s.core.v1.namespaces.delete`, `io.k8s.batch.v1.jobs.create`,
# `io.x-k8s.kueue.v1beta2.workloads.status.patch`. It is read right to left;
# `_API_VERSION_RE` also finds the `<group>/<version>/` head of `resourceName`.
_API_VERSION_RE = re.compile(r"^v\d+(?:(?:alpha|beta)\d+)?$")
_METHOD_SEGMENT_RE = re.compile(r"^[a-z0-9-]+$")
_GCP_METHOD_ROOTS = ("k8s", "x-k8s")
# Marker stamped on normalised Kubernetes Event objects. Kueue's own controller
# log also uses `logger: "events"`, so the logger name alone does not tell an
# exported Event from a controller log line.
K8S_EVENT_SOURCE_KIND = "k8s-event"
REDACTED = "<REDACTED>"
_CRI_PREFIX_RE = re.compile(
r"^\d{4}-\d{2}-\d{2}T\S+\s+(?:stdout|stderr)\s+([FP])\s+(.*)$"
)
_CRI_LINE_RE = re.compile(
r"^(\d{4}-\d{2}-\d{2}T\S+)\s+(stdout|stderr)\s+([FP])\s+(.*)$"
)
_MAX_CRI_PARTIAL_BYTES = 262144
_PRETTY_JSON_MEMBER_RE = re.compile(r'^"[^"\n]+"\s*:')
_TRUNCATED_JSON_ARRAY_RE = re.compile(r'^\[\s*[{"\[]')
_JSON_CLOSING_RE = re.compile(r"^[\]}]+,?$")
# Rendered container `env` entries (JSON in either key order, JSON-patch
# `/env/<idx>/value`, or Go `%#v` `EnvVar{Name:..., Value:...}` dumps), both
# plain and single-level JSON-escaped.
_ENV_TEXT_RE = re.compile(
r'("name"\s*:\s*"(?:[^"\\]|\\.)*"\s*,\s*"value"\s*:\s*)'
r'"(?:[^"\\]|\\.)*(?:"|$)'
)
_ENV_TEXT_VAL_FIRST_RE = re.compile(
r'("value"\s*:\s*)"(?:[^"\\]|\\.)*"'
r'(\s*,\s*"name"\s*:\s*"(?:[^"\\]|\\.)*")'
)
_ENV_PATCH_TEXT_RE = re.compile(
r'("path"\s*:\s*"[^"\n]{0,512}/env/[^/"\n]{1,64}/value"\s*,\s*"value"\s*:\s*)'
r'"(?:[^"\\]|\\.)*(?:"|$)'
)
_ESCAPED_ENV_TEXT_RE = re.compile(
r'(\\"name\\"\s*:\s*\\"(?:[^\\]|\\[^"])*\\"\s*,\s*'
r'\\"value\\"\s*:\s*)\\"(?:[^\\]|\\[^"])*(?:\\"|$)'
)
_ESCAPED_ENV_VAL_FIRST_RE = re.compile(
r'(\\"value\\"\s*:\s*)\\"(?:[^\\]|\\[^"])*\\"'
r'(\s*,\s*\\"name\\"\s*:\s*\\"(?:[^\\]|\\[^"])*\\")'
)
_ESCAPED_ENV_PATCH_TEXT_RE = re.compile(
r'(\\"path\\"\s*:\s*\\"[^\\"\n]{0,512}/env/[^/\\"\n]{1,64}/value\\"\s*,\s*'
r'\\"value\\"\s*:\s*)\\"(?:[^\\]|\\[^"])*(?:\\"|$)'
)
_GO_ENV_VAR_RE = re.compile(
r'(\{\s*Name\s*:\s*"(?:[^"\\]|\\.)*"\s*,\s*Value\s*:\s*)'
r'"(?:[^"\\]|\\.)*(?:"|$)'
)
_ESCAPED_GO_ENV_VAR_RE = re.compile(
r'(\{\s*Name\s*:\s*\\"(?:[^\\]|\\[^"])*\\"\s*,\s*'
r'Value\s*:\s*)\\"(?:[^\\]|\\[^"])*(?:\\"|$)'
)
_NONLOG_AUDIT_KEYS = frozenset({
"objectRef",
"requestObject",
"responseObject",
"auditID",
"protoPayload",
"ObjectRef",
"RequestObject",
"ResponseObject",
"AuditID",
"ProtoPayload",
})
_NONLOG_SECRET_OR_LIST_KINDS = frozenset({"Secret", "SecretList", "List"})
_VERBS = {
"create",
"delete",
"deletecollection",
"get",
"list",
"patch",
"update",
"watch",
}
def _json_or_none(text: str) -> Any:
text = text.strip()
if not text or text[0] not in "{[":
return None
try:
return json.loads(text)
except (json.JSONDecodeError, RecursionError):
return None
def _first(d: dict[str, Any], *keys: str) -> Any:
for k in keys:
v = d.get(k)
if v not in (None, ""):
return v
return None
def _redacted_env_entry(entry: Any) -> Any:
"""One `env[]` entry with its literal `value` hidden; `name`/`valueFrom` stay."""
if isinstance(entry, dict) and "value" in entry:
return {**entry, "value": REDACTED}
return entry
def _redacted_env_patch_op(op: dict[str, Any]) -> dict[str, Any]:
"""A JSON-patch operation with the `env` values it writes hidden."""
path = op.get("path")
if not isinstance(path, str) or "value" not in op:
return op
segs = path.split("/")
if "env" not in segs:
return op
tail = segs[len(segs) - segs[::-1].index("env") :]
value = op["value"]
if not tail and isinstance(value, list):
value = [_redacted_env_entry(e) for e in value]
elif len(tail) == 1:
value = _redacted_env_entry(value)
elif len(tail) == 2 and tail[1] == "value":
value = REDACTED
return {**op, "value": value}
def redact_env_values(node: Any) -> Any:
"""Copy of a JSON value with container `env[].value` and Secret data set to `<REDACTED>`.
Covers pod templates and non-container CRD `env` lists at any depth,
JSON-patch operations whose `path` writes into an `env` list, and `Secret`
`data`/`stringData` maps. `name`, `valueFrom`, `command` and `args` are kept.
Iterative, so that a deeply nested request body costs no interpreter stack.
Args:
node: Decoded JSON value (a `spec`, a request body, or a patch list).
Returns:
The redacted copy; `node` itself is not modified.
"""
holder: list[Any] = [node]
stack: list[tuple[Any, Any]] = [(holder, 0)]
while stack:
parent, key = stack.pop()
cur = parent[key]
if isinstance(cur, dict):
cur = parent[key] = _redacted_env_patch_op(dict(cur))
if isinstance(cur.get("env"), list):
cur["env"] = [_redacted_env_entry(e) for e in cur["env"]]
if cur.get("kind") == "Secret":
for secret_field in ("data", "stringData"):
if isinstance(cur.get(secret_field), dict):
cur[secret_field] = {k: REDACTED for k in cur[secret_field]}
stack.extend((cur, k) for k in cur)
elif isinstance(cur, list):
cur = parent[key] = list(cur)
stack.extend((cur, i) for i in range(len(cur)))
elif isinstance(cur, str):
parent[key] = redact_env_text(cur)
return holder[0]
def redact_env_text(text: str) -> str:
"""`redact_env_values` for an audit summary or error message in rendered text."""
if (
'"value"' not in text
and '\\"value\\"' not in text
and "EnvVar{" not in text
):
return text
out = text
if '"value"' in out:
out = _ENV_TEXT_RE.sub(lambda m: f'{m.group(1)}"{REDACTED}"', out)
out = _ENV_TEXT_VAL_FIRST_RE.sub(
lambda m: f'{m.group(1)}"{REDACTED}"{m.group(2)}', out
)
if "/env/" in out:
out = _ENV_PATCH_TEXT_RE.sub(lambda m: f'{m.group(1)}"{REDACTED}"', out)
if '\\"value\\"' in out:
out = _ESCAPED_ENV_TEXT_RE.sub(
lambda m: f'{m.group(1)}\\"{REDACTED}\\"', out
)
out = _ESCAPED_ENV_VAL_FIRST_RE.sub(
lambda m: f'{m.group(1)}\\"{REDACTED}\\"{m.group(2)}', out
)
if "/env/" in out:
out = _ESCAPED_ENV_PATCH_TEXT_RE.sub(
lambda m: f'{m.group(1)}\\"{REDACTED}\\"', out
)
if "EnvVar{" in out:
out = _GO_ENV_VAR_RE.sub(lambda m: f'{m.group(1)}"{REDACTED}"', out)
if '\\"' in out:
out = _ESCAPED_GO_ENV_VAR_RE.sub(
lambda m: f'{m.group(1)}\\"{REDACTED}\\"', out
)
return out
def _request_object_parts(req: Any) -> dict[str, Any]:
"""Picks the parts of a request/response object worth keeping from audit."""
if isinstance(req, list):
# A JSON-patch body (list of operations) is kept whole under `request`.
return {"request": redact_env_values(req)} if req else {}
if not isinstance(req, dict):
return {}
out: dict[str, Any] = {}
meta = req.get("metadata") if isinstance(req.get("metadata"), dict) else {}
raw_ann = meta.get("annotations")
ann: dict[str, Any] = {}
if isinstance(raw_ann, dict):
ann = {
k: v
for k, v in raw_ann.items()
if k != "kubectl.kubernetes.io/last-applied-configuration"
}
if req.get("spec") is not None:
out["spec"] = redact_env_values(req["spec"])
if ann:
out["annotations"] = ann
if isinstance(meta.get("labels"), dict) and meta["labels"]:
out["labels"] = meta["labels"]
status = req.get("status") if isinstance(req.get("status"), dict) else {}
filtered_status = {
k: status[k]
for k in ("conditions", "admissionChecks", "requeueState")
if k in status
}
if filtered_status:
out["status"] = filtered_status
return out
@dataclasses.dataclass(frozen=True)
class AuditRef:
"""Neutral `(verb, resource, subresource, namespace, name, group)` tuple."""
verb: str = ""
resource: str = ""
subresource: str = ""
namespace: str = ""
name: str = ""
group: str = ""
@property
def resource_path(self) -> str:
return (
f"{self.resource}/{self.subresource}"
if self.subresource
else self.resource
)
@property
def target(self) -> str:
if self.namespace and self.name:
return f"{self.namespace}/{self.name}"
return self.name or self.namespace or ""
def _audit_row(
ref: AuditRef,
*,
ts: str,
level: str,
parts: dict[str, Any],
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Formats a normalized audit log record dictionary from `ref` and `parts`."""
if ref.resource.lower() == "secrets":
parts = {}
summary = [f"[Audit {ref.verb} {ref.resource_path}] {ref.target}"]
for key, limit in (
("spec", 1200),
("request", 400),
("annotations", 450),
("labels", 350),
("status", 600),
):
if key in parts:
summary.append(f"{key}={json.dumps(parts[key], sort_keys=True)[:limit]}")
row: dict[str, Any] = {
"ts": ts,
"level": level or "info",
"logger": "audit",
"msg": " ".join(summary),
"verb": ref.verb,
"resource": ref.resource,
"subresource": ref.subresource,
"group": ref.group,
"namespace": ref.namespace,
"name": ref.name,
"resourceName": ref.target,
}
row.update(parts)
if extra:
row.update(extra)
return row
def _dict_at(d: dict[str, Any], key: str) -> dict[str, Any]:
"""`d[key]` when it is a mapping, else `{}`."""
value = d.get(key)
return value if isinstance(value, dict) else {}
def _k8s_audit_extra(d: dict[str, Any], code: Any) -> dict[str, Any]:
extra: dict[str, Any] = {"stage": str(d.get("stage") or "")}
if code is not None:
extra["responseCode"] = code
user = _dict_at(d, "user")
if user.get("username"):
extra["user"] = str(user["username"])
return extra
def _normalize_k8s_audit_event(d: dict[str, Any]) -> dict[str, Any] | None:
"""`audit.k8s.io/v1` Event (apiserver audit policy / webhook / kind)."""
ref = _dict_at(d, "objectRef")
verb = str(d.get("verb") or "").lower()
if not verb:
return None
code = _dict_at(d, "responseStatus").get("code")
level = "error" if isinstance(code, int) and code >= 400 else "info"
return _audit_row(
AuditRef(
verb=verb,
resource=str(ref.get("resource") or ""),
subresource=str(ref.get("subresource") or ""),
namespace=str(ref.get("namespace") or ""),
name=str(ref.get("name") or ""),
group=str(ref.get("apiGroup") or ""),
),
ts=str(_first(d, "stageTimestamp", "requestReceivedTimestamp") or ""),
level=level,
parts=_request_object_parts(d.get("requestObject")),
extra=_k8s_audit_extra(d, code),
)
def _gcp_method_parts(method: str) -> tuple[str, str, str, str]:
"""`(group, resource, subresource, verb)` of a `methodName`, read right to left.
The group is the one the method spells (`core` -> ``, `io.x-k8s.kueue` ->
`kueue.x-k8s.io`); `gcp_audit_ref` prefers the group of `resourceName`.
Args:
method: Cloud audit `methodName`.
Returns:
Empty strings for every part the method does not name; a method of another
shape yields at most its verb.
"""
segs = method.split(".")
verb = segs[-1] if segs[-1] in _VERBS else ""
if segs[0] != "io" or len(segs) < 2 or segs[1] not in _GCP_METHOD_ROOTS:
return "", "", "", verb
for tail_len in (2, 3): # `<resource>.<verb>`, `<resource>.<sub>.<verb>`
ver_at = len(segs) - tail_len - 1
tail = segs[ver_at + 1 :]
if (
ver_at < 3
or not _API_VERSION_RE.match(segs[ver_at])
or not all(_METHOD_SEGMENT_RE.match(s) for s in tail)
):
continue
group_segs = segs[2:ver_at]
if segs[1] == "x-k8s":
group = ".".join(reversed(group_segs)) + ".x-k8s.io"
else:
group = "" if group_segs == ["core"] else ".".join(group_segs)
return group, tail[0], tail[1] if tail_len == 3 else "", tail[-1]
return "", "", "", verb
def _gcp_resource_target(
res_name: str, resource: str
) -> tuple[str | None, str, str]:
"""`(group, namespace, name)` from a Google Cloud audit `resourceName` path.
The path is `<group>/<version>/[namespaces/<ns>/]<resource>/<name>[/<sub>]`.
The name is taken by position, so a trailing subresource such as `/status`
is never read as the object name.
Args:
res_name: Cloud audit `resourceName`.
resource: Resource plural named by the method (`` when unknown).
Returns:
`group` is None when the path has no `<group>/<version>/` head.
"""
segs = [s for s in res_name.split("/") if s]
group: str | None = None
if len(segs) > 1 and _API_VERSION_RE.match(segs[1]):
group = "" if segs[0] == "core" else segs[0]
segs = segs[2:]
elif resource in segs:
segs = segs[segs.index(resource) :]
if not segs:
return group, "", ""
if segs[0] == "namespaces" and resource != "namespaces" and len(segs) > 2:
return group, segs[1], segs[3] if len(segs) > 3 else ""
if group is not None or segs[0] in ("namespaces", resource):
return group, "", segs[1] if len(segs) > 1 else ""
return group, "", segs[-1]
def gcp_audit_ref(method: str, res_name: str = "") -> AuditRef:
"""Neutral audit tuple from a Cloud audit `methodName` and `resourceName`."""
group, resource, subresource, verb = _gcp_method_parts(method)
path_group, namespace, name = _gcp_resource_target(res_name, resource)
return AuditRef(
verb=verb,
resource=resource,
subresource=subresource,
namespace=namespace,
name=name,
group=group if path_group is None else path_group,
)
def _gcp_audit_extra(
pp: dict[str, Any], method: str, res_name: str
) -> dict[str, Any]:
"""Extracts method, resource, status code, and principal fields from `pp`."""
extra: dict[str, Any] = {
"methodName": method,
"providerResourceName": res_name,
}
st = _dict_at(pp, "status")
if st.get("code") not in (None, 0):
extra["responseCode"] = st.get("code")
auth = _dict_at(pp, "authenticationInfo")
if auth.get("principalEmail"):
extra["user"] = str(auth["principalEmail"])
return extra
def _normalize_gcp_audit(
pp: dict[str, Any], ts: str, severity: str
) -> dict[str, Any] | None:
"""Google Cloud audit log `protoPayload` (AuditLog) for a K8s API call."""
method = str(pp.get("methodName") or "")
res_name = str(pp.get("resourceName") or "")
return _audit_row(
gcp_audit_ref(method, res_name),
ts=ts,
level=severity.lower() if severity else "info",
parts=_request_object_parts(pp.get("request")),
extra=_gcp_audit_extra(pp, method, res_name),
)
def extract_event_emitter(d: dict[str, Any]) -> str:
"""Component that emitted a Kubernetes Event (`''` when unknown)."""
src = d.get("source")
if isinstance(src, dict) and src.get("component"):
return str(src["component"])
if isinstance(src, str) and src and " source: " not in f" {src}":
return src
for key in ("reportingController", "reportingComponent"):
if d.get(key):
return str(d[key])
if d.get("reportingInstance"):
return str(d["reportingInstance"]).split("/", 1)[0]
meta = d.get("metadata")
if isinstance(meta, dict):
managed = meta.get("managedFields")
for mf in managed if isinstance(managed, list) else []:
if (
isinstance(mf, dict)
and mf.get("manager")
and not str(mf["manager"]).startswith("kubectl")
):
return str(mf["manager"])
return ""
def _normalize_k8s_event(d: dict[str, Any]) -> dict[str, Any]:
"""`v1` Event or `events.k8s.io/v1` Event."""
obj = _first(d, "involvedObject", "regarding") or {}
ev_type = str(d.get("type") or "")
row: dict[str, Any] = {
"ts": str(
_first(d, "lastTimestamp", "eventTime", "firstTimestamp") or ""
),
"level": "warning" if ev_type == "Warning" else "info",
"logger": "events",
"source_kind": K8S_EVENT_SOURCE_KIND,
"type": ev_type,
"reason": str(d.get("reason") or ""),
"msg": str(_first(d, "message", "note") or ""),
"object": obj if isinstance(obj, dict) else {},
}
if d.get("count") is not None:
row["count"] = d.get("count")
comp = extract_event_emitter(d)
if comp:
row["source"] = comp
return row
def _looks_like_zap(d: dict[str, Any]) -> bool:
kind = d.get("kind")
if isinstance(kind, str) and kind in _NONLOG_SECRET_OR_LIST_KINDS:
return False
return ("msg" in d or "message" in d) and (
"level" in d or "ts" in d or "logger" in d
)
_MAX_ENVELOPE_DEPTH = 4
def _fill_envelope_defaults(
inner: dict[str, Any], ts: str, severity: str
) -> dict[str, Any]:
"""Adds the envelope's timestamp / severity to an inner record that lacks them."""
if not inner.get("ts"):
inner["ts"] = ts
if not inner.get("level"):
inner["level"] = severity.lower() or "info"
return inner
def _unwrap_text_payload(
text: str, depth: int
) -> tuple[bool, dict[str, Any] | None]:
"""Unwraps a string payload; returns `(dropped, record_or_none)`."""
inner_obj = _json_or_none(text)
if inner_obj is None:
return False, _normalize_text_line(text)
if isinstance(inner_obj, list):
return True, None
if isinstance(inner_obj, dict):
row = normalize_record(inner_obj, depth + 1)
if row is not None:
return False, row
if _is_nonlog_k8s_or_audit_dict(inner_obj):
return True, None
return False, None
# --- Capitalised audit.k8s.io rows -------------------------------------------
def _is_capitalized_audit(obj: dict[str, Any]) -> bool:
return "Verb" in obj and "ObjectRef" in obj and "verb" not in obj
def _unwrap_capitalized_audit(
obj: dict[str, Any], depth: int
) -> dict[str, Any] | None:
"""Normalizes capitalized audit.k8s.io fields and JSON-encoded children."""
del depth
lowered: dict[str, Any] = {}
for k, v in obj.items():
if isinstance(v, str) and v[:1] in "{[":
parsed = _json_or_none(v)
v = parsed if parsed is not None else v
lowered[k[:1].lower() + k[1:]] = v
lowered.setdefault("stageTimestamp", lowered.get("timeGenerated", ""))
return _normalize_k8s_audit_event(lowered)
# --- Kubernetes audit Event / Kubernetes Event -------------------------------
def _is_k8s_audit_event(obj: dict[str, Any]) -> bool:
return (
str(obj.get("kind") or "") == "Event"
and str(obj.get("apiVersion") or "").partition("/")[0] == "audit.k8s.io"
)
def _unwrap_k8s_audit_event(
obj: dict[str, Any], depth: int
) -> dict[str, Any] | None:
"""Normalizes a standard `audit.k8s.io` Event object."""
del depth
return _normalize_k8s_audit_event(obj)
def _is_k8s_event(obj: dict[str, Any]) -> bool:
"""Returns True for a Kubernetes core/events Event object."""
api = str(obj.get("apiVersion") or "")
kind = str(obj.get("kind") or "")
has_object = "involvedObject" in obj or "regarding" in obj
if kind == "Event":
return has_object or api in ("v1", "events.k8s.io/v1")
return not kind and "reason" in obj and has_object
def _unwrap_k8s_event(obj: dict[str, Any], depth: int) -> dict[str, Any]:
"""Normalizes a Kubernetes core/events Event object."""
del depth
return _normalize_k8s_event(obj)
# --- Google Cloud Logging envelope -------------------------------------------
def _is_gcp_logging(obj: dict[str, Any]) -> bool:
"""Returns True for a Cloud Logging entry carrying a supported payload."""
if not any(k in obj for k in ("jsonPayload", "protoPayload", "textPayload")):
return False
if not ("timestamp" in obj or "insertId" in obj or "logName" in obj):
return False
return (
isinstance(obj.get("protoPayload"), dict)
or isinstance(obj.get("jsonPayload"), dict)
or obj.get("textPayload") is not None
)
def _unwrap_gcp_logging(
obj: dict[str, Any], depth: int
) -> dict[str, Any] | None:
"""Unwraps a Google Cloud Logging audit, JSON, or text payload envelope."""
ts = str(obj.get("timestamp") or "")
sev = str(obj.get("severity") or "")
if isinstance(obj.get("protoPayload"), dict):
return _normalize_gcp_audit(obj["protoPayload"], ts, sev)
if isinstance(obj.get("jsonPayload"), dict):
jp = obj["jsonPayload"]
inner = normalize_record(jp, depth + 1)
if inner is None:
if _is_nonlog_k8s_or_audit_dict(jp):
return None
inner = dict(jp)
_fill_envelope_defaults(inner, ts, sev)
if "msg" not in inner and "message" in inner:
inner["msg"] = inner["message"]
if "object" not in inner and "involvedObject" in inner:
inner["object"] = inner["involvedObject"]
return inner
text = str(obj["textPayload"])
dropped, parsed = _unwrap_text_payload(text, depth)
if dropped:
return None
inner = parsed or {"msg": text}
if not inner.get("ts") or ts:
inner["ts"] = ts or inner.get("ts", "")
return _fill_envelope_defaults(inner, "", sev)
# --- Collector envelopes: fluent-bit / Fluentd / Filebeat / Loki -------------
def _collector_payload(obj: dict[str, Any]) -> str | None:
"""The wrapped line of a collector envelope, or None when `obj` is not one."""
payload = _first(obj, "log", "line", "LogMessage")
if (
payload is None
and isinstance(obj.get("message"), str)
and not _looks_like_zap(obj)
):
payload = obj.get("message")
if not isinstance(payload, str):
return None
if any(
k in obj
for k in (
"kubernetes",
"labels",
"time",
"@timestamp",
"timestamp",
"stream",
"TimeGenerated",
)
):
return payload
return None
def _is_collector_envelope(obj: dict[str, Any]) -> bool:
return _collector_payload(obj) is not None
def _unwrap_collector_envelope(
obj: dict[str, Any], depth: int
) -> dict[str, Any] | None:
"""Unwraps a fluent-bit, Fluentd, Filebeat, or Loki log collector envelope."""
payload = _collector_payload(obj) or ""
ts = str(
_first(obj, "time", "@timestamp", "timestamp", "TimeGenerated") or ""
)
dropped, parsed = _unwrap_text_payload(payload, depth)
if dropped:
return None
inner = parsed or {"msg": payload.rstrip("\n")}
inner.setdefault("ts", ts)
inner.setdefault(
"level", str(obj.get("level") or obj.get("severity") or "info").lower()
)
return inner
# --- Plain zap / structured record -------------------------------------------
def _unwrap_zap(obj: dict[str, Any], depth: int) -> dict[str, Any]:
"""Normalizes a zap or structured JSON log record."""
del depth
row = dict(obj)
if "msg" not in row and "message" in row:
row["msg"] = row["message"]
if "ts" not in row:
ts = _first(row, "time", "timestamp", "@timestamp")
if ts is not None:
row["ts"] = str(ts)
if "level" not in row and row.get("severity"):
row["level"] = str(row["severity"]).lower()
if isinstance(row.get("msg"), str) and row["msg"].startswith("[Audit "):
# An audit row normalised by an earlier run or another exporter.
row["msg"] = redact_env_text(row["msg"])
for key in ("spec", "request"):
if isinstance(row.get(key), (dict, list)):
row[key] = redact_env_values(row[key])
return row
EnvelopeMatcher = Callable[[dict[str, Any]], bool]
EnvelopeUnwrapper = Callable[[dict[str, Any], int], "dict[str, Any] | None"]
# Tried in order; the first matching envelope decides the record (its result is
# final even when it is None, e.g. an audit row without a verb).
ENVELOPE_UNWRAPPERS: tuple[tuple[EnvelopeMatcher, EnvelopeUnwrapper], ...] = (
(_is_capitalized_audit, _unwrap_capitalized_audit),
(_is_k8s_audit_event, _unwrap_k8s_audit_event),
(_is_k8s_event, _unwrap_k8s_event),
(_is_gcp_logging, _unwrap_gcp_logging),
(_is_collector_envelope, _unwrap_collector_envelope),
(_looks_like_zap, _unwrap_zap),
)
def normalize_record(obj: Any, depth: int = 0) -> dict[str, Any] | None:
"""Turns one parsed record of any supported shape into a normalized dict.
Args:
obj: Decoded JSON value to inspect and unwrap.
depth: Current envelope nesting depth (bounded by `_MAX_ENVELOPE_DEPTH`).
Returns:
A normalized log record dict, or None when `obj` is not a recognized dict.
"""
if not isinstance(obj, dict) or depth > _MAX_ENVELOPE_DEPTH:
return None
for matches, unwrap in ENVELOPE_UNWRAPPERS:
if matches(obj):
row = unwrap(obj, depth)
if row is not None and depth == 0:
row = redact_env_values(row)
return row
return None
def _normalize_text_line(line: str) -> dict[str, Any] | None:
m = _KLOG_RE.match(line.strip())
if not m:
return None
return {
"level": _KLOG_LEVELS.get(m.group(1), "info"),
"ts": (
f"{m.group(2)[:2]}-{m.group(2)[2:]}T{m.group(3)}"
), # MM-DDTHH:MM:SS; klog omits the year
"msg": m.group(4),
}
def _is_nonlog_k8s_or_audit_dict(obj: dict[str, Any]) -> bool:
"""True when an unrecognized JSON object contains a K8s manifest/Secret/List or audit payload."""
stack: list[Any] = [obj]
while stack:
cur = stack.pop()
if isinstance(cur, dict):
kind = cur.get("kind")
if isinstance(kind, str) and (
kind in _NONLOG_SECRET_OR_LIST_KINDS
or (
isinstance(cur.get("apiVersion"), str)
and (cur is obj or isinstance(cur.get("metadata"), dict))
)
):
return True
if any(k in cur for k in _NONLOG_AUDIT_KEYS):
return True
stack.extend(cur.values())
elif isinstance(cur, list):
stack.extend(cur)
return False
def _decode_json_objects(body: str) -> list[dict[str, Any]] | None:
"""Decodes one or more top-level JSON objects, or None when not a pure JSON object stream."""
decoder = json.JSONDecoder()
idx = 0
n = len(body)
objs: list[dict[str, Any]] = []
while idx < n:
while idx < n and body[idx].isspace():
idx += 1
if idx >= n:
break
try:
obj, end = decoder.raw_decode(body, idx)
except (json.JSONDecodeError, RecursionError, ValueError):
return None
if not isinstance(obj, dict):
return None
objs.append(obj)
idx = end
return objs if objs else None
def _reassemble_cri_lines(lines: list[str]) -> list[str]:
"""Joins CRI partial (`P`) chunks per stream up to their terminating `F` line.
Kubelet splits container log lines over 16 KiB across `stdout P` / `stderr P`
chunks followed by a final `F` line. Reassembling them before classification
restores valid JSON records and ensures an unterminated partial JSON line at
EOF is dropped as one fragment rather than leaking tail chunks.
Args:
lines: Raw lines split from a log file.
Returns:
Lines with CRI `P...F` sequences joined into single lines.
"""
out: list[str] = []
pending: dict[str, tuple[str, list[str], int]] = {}
for line in lines:
m = _CRI_LINE_RE.match(line.lstrip("\ufeff"))
if not m:
out.append(line)
continue
ts, stream, flag, payload = m.groups()
if flag == "P":
if stream in pending:
first_ts, chunks, size = pending[stream]
if size < _MAX_CRI_PARTIAL_BYTES:
room = _MAX_CRI_PARTIAL_BYTES - size
chunks.append(payload[:room])
size += min(len(payload), room)
pending[stream] = (first_ts, chunks, size)
else:
chunk = payload[:_MAX_CRI_PARTIAL_BYTES]
pending[stream] = (ts, [chunk], len(chunk))
continue
if stream in pending:
first_ts, chunks, _ = pending.pop(stream)
out.append(f"{first_ts} {stream} F {''.join(chunks)}{payload}")
else:
out.append(line)
for stream, (first_ts, chunks, _) in pending.items():
out.append(f"{first_ts} {stream} P {''.join(chunks)}")
return out
def _looks_like_json_fragment_payload(text: str) -> bool:
"""True when an unterminated CRI `P` payload carries partial JSON syntax."""
return (
text.startswith(("{", "["))
or bool(_PRETTY_JSON_MEMBER_RE.match(text))
or bool(_JSON_CLOSING_RE.match(text))
or '":' in text
or '" :' in text
)
def _is_bare_json_array_item(stripped: str) -> bool:
"""True for a standalone JSON primitive line inside a pretty-printed array."""
item = stripped[:-1] if stripped.endswith(",") else stripped
if not item:
return False
if item in ("true", "false", "null"):
return True
if (len(item) >= 2 and item[0] == '"' and item[-1] == '"') or (
item[0] in "-0123456789"
):
try:
return isinstance(json.loads(item), (str, int, float))
except (json.JSONDecodeError, RecursionError):
return False
return False
def _classify_non_json_line(stripped: str) -> tuple[str, str]:
"""Classifies a non-JSON line as JSON fragment/close, klog record, or raw."""
if stripped.startswith('{"'):
return "", "json_obj_frag"
if stripped in ("{", "[") or _TRUNCATED_JSON_ARRAY_RE.match(stripped):
return "", "json_opener"
if _PRETTY_JSON_MEMBER_RE.match(stripped):
return "", "json_member"
if stripped.startswith("{"):
return "", "fragment"
if _JSON_CLOSING_RE.match(stripped):
return "", "json_close"
klog = _normalize_text_line(stripped)
if klog:
klog["msg"] = redact_env_text(klog["msg"])
return json.dumps(klog, ensure_ascii=False), "record"
return redact_env_text(stripped), "raw"
def _classify_line(line: str) -> tuple[str, str]:
"""Normalises one log line and classifies it as record, raw, JSON piece, or empty."""
stripped = line.lstrip("\ufeff").strip()
if not stripped:
return "", "empty"
cri = _CRI_PREFIX_RE.match(stripped)
if cri:
flag, candidate = cri.group(1), cri.group(2).strip()
if flag == "P" and _looks_like_json_fragment_payload(candidate):
return "", "fragment"
if (
candidate.startswith(("{", "["))
or _PRETTY_JSON_MEMBER_RE.match(candidate)
or _JSON_CLOSING_RE.match(candidate)
or _KLOG_RE.match(candidate)
):
stripped = candidate
obj = _json_or_none(stripped)
if isinstance(obj, dict):
if not obj:
return "", "json_close"
row = normalize_record(obj)
if row is not None:
return json.dumps(row, ensure_ascii=False), "record"
if any(matches(obj) for matches, _ in ENVELOPE_UNWRAPPERS):
return "", "empty"
if _is_nonlog_k8s_or_audit_dict(obj):
return "", "empty"
return json.dumps(redact_env_values(obj), ensure_ascii=False), "raw_json"
if isinstance(obj, list):
return "", "empty"
return _classify_non_json_line(stripped)
def normalize_line(line: str) -> str:
"""Returns one normalised JSON line (or plain text) for a single raw input line."""
return _classify_line(line)[0]
def _yield_decoded_objects(objs: list[dict[str, Any]]) -> Iterator[str]:
"""Emits normalized lines for top-level JSON objects, dropping non-log manifests."""
for whole in objs:
if isinstance(whole.get("items"), list):
yield from _iter_array(whole["items"])
else:
row = normalize_record(whole)
if row is not None:
yield json.dumps(row, ensure_ascii=False)
def _extract_whole_json(body: str) -> list[str] | None:
"""Decodes a complete JSON array or object document, or None when invalid."""
if body.startswith("["):
arr = _json_or_none(body)
if isinstance(arr, list):
return list(_iter_array(arr))
return None
if body.startswith("{"):
stripped = body.strip()
if "\n" not in stripped:
whole = _json_or_none(stripped)
if isinstance(whole, dict):
return list(_yield_decoded_objects([whole]))
return None
first_line = stripped.split("\n", 1)[0]
if _json_or_none(first_line) is None:
objs = _decode_json_objects(stripped)
if objs is not None:
return list(_yield_decoded_objects(objs))
return None
_JSON_DOC_START_RE = re.compile(r'^(?:\{\s*(?:"|\}|$)|\[\s*(?:\{|\[|"|\]|$))')
_JSON_FRAGMENT_KINDS = frozenset(
{"fragment", "json_opener", "json_member", "json_obj_frag"}
)
def _scan_line_records(
text: str, looks_like_json_doc: bool
) -> tuple[list[str], bool]:
"""Line-by-line fallback extraction with broken pretty-JSON detection."""
records: list[str] = []
recognized = 0
raw_json_count = 0
dropped_fragments = False
has_opener = False
has_member = False
has_bare_opener = False
has_pretty_member = False
json_lines = 0
non_json_raw = 0
for line in _reassemble_cri_lines(text.splitlines()):
stripped = line.lstrip("\ufeff").strip()
if stripped.startswith("["):
arr = _json_or_none(stripped)
if isinstance(arr, list):
emitted = list(_iter_array(arr))
records.extend(emitted)
recognized += len(emitted)
continue
out, kind = _classify_line(line)
if kind in _JSON_FRAGMENT_KINDS:
dropped_fragments = True
json_lines += 1
has_opener = has_opener or kind in ("json_opener", "json_obj_frag")
has_member = has_member or kind in ("json_member", "json_obj_frag")
has_bare_opener = has_bare_opener or kind == "json_opener"
has_pretty_member = has_pretty_member or kind == "json_member"
elif kind == "json_close":
json_lines += 1
elif kind == "record":
recognized += 1
records.append(out)
elif kind == "raw_json":
raw_json_count += 1
records.append(out)
elif out:
records.append(out)
if not _is_bare_json_array_item(stripped):
non_json_raw += 1
if recognized == 0 and dropped_fragments:
if raw_json_count > 0 and not (has_bare_opener or has_pretty_member):
return records, False
if looks_like_json_doc or (
has_opener and has_member and json_lines >= non_json_raw
):
return [], True
return records, False
def extract_file_records(text: str) -> tuple[list[str], bool]:
"""Extracts normalised log lines from one file and flags unreadable JSON exports.
When a JSON export drops fragments (for example a truncated export, two
pretty-printed JSON arrays appended into one file, or a pretty-printed JSON
export prefixed by non-JSON CLI warnings) and yields zero valid log records,
leftover bare strings and preamble lines are discarded and `unreadable` is
returned as True so the caller does not count fragments as log lines.
Plain-text logs without a dominant pretty-printed JSON body keep their
surrounding raw lines even if an isolated line starts with `{`.
Args:
text: Full text content of a log or event file.
Returns:
`(records, unreadable)` where `unreadable` is True when a broken JSON
export dropped fragments and yielded zero recognised records.
"""
body = text.lstrip("\ufeff \t\r\n")
whole = _extract_whole_json(body)
if whole is not None:
return whole, False
return _scan_line_records(text, bool(_JSON_DOC_START_RE.match(body)))
def iter_records(text: str) -> Iterator[str]:
"""Yields normalized lines from a JSON array, JSONL, or plain-text file body.
JSON arrays (e.g. `gcloud logging read --format=json` or `kubectl get events
-o json` `.items`) are ordered by their timestamp field when present so
downstream timeline compression sees records oldest-first. Single or
concatenated JSON documents that are not log records yield nothing; broken
pretty-printed JSON exports yield nothing instead of leftover fragments.
Args:
text: Full text content of a log or event file.
Yields:
One normalized JSON or raw text line per log record.
"""
records, _ = extract_file_records(text)
yield from records
def _iter_array(arr: list[Any]) -> Iterator[str]:
"""Normalizes and timestamp-sorts records from a parsed JSON array."""
rows: list[tuple[str, str]] = []
for item in arr:
if isinstance(item, dict):
row = normalize_record(item)
if row is None:
continue
# Envelope receive timestamp orders the export; inner `ts` is kept for
# display even if formatted differently.
sort_ts = str(
_first(item, "timestamp", "time", "@timestamp", "TimeGenerated")
or row.get("ts")
or ""
)
rows.append((sort_ts, json.dumps(row, ensure_ascii=False)))
elif isinstance(item, str):
out = normalize_line(item)
if out:
rows.append(("", out))
if rows and all(r[0] for r in rows):
rows.sort(key=lambda r: r[0])
for _, line in rows:
yield line
log_facts.py 70.4 KB
"""Derived log facts for the `gke-kueue-troubleshooting` skill.
Turns normalised log lines (Kueue controller JSON, `audit.k8s.io/v1` events,
Kubernetes Events) into the `derived_log_diagnostics` block that
`trace_logs.py` prints: an entity inventory, key errors/events, audit actions
and neutral `derived_log_facts`.
The extraction runs in two layers over a single `LogScanState`:
* record scanners `scan_<topic>(rec, state)` — applied to every parsed record
in `RECORD_SCANNERS` order, each filling the accumulators of one topic;
* fact emitters `emit_<fact>(state)` — applied once after the scan in
`LOG_FACT_EMITTERS` order, each returning `(key, text)` fact tuples.
Plain-text signals that do not need a parsed record (TAS domain errors,
strict-decoding errors, webhook timeouts, API-pressure markers) are collected
by `scan_text_signals` on every line, structured or not.
Every fact string is observational: it states what the log said and, at most,
one sentence of version-independent Kueue semantics with a source citation.
"""
from __future__ import annotations
import dataclasses
import datetime
import json
import re
from typing import Any, Callable
import k8s_objects
import kueue_schema
import log_envelopes
import log_signatures
import report_output
# Exact controller log messages this module matches. Every entry must exist in
# the Kueue source at kueue_schema.KUEUE_SOURCE_REF (tests/test_scripts.py
# checks this when a Kueue checkout is available).
KUEUE_LOG_LITERALS = (
("cmd/kueue/main.go", "Configuration loaded"),
(
"pkg/scheduler/scheduler.go",
"Workload successfully admitted and assigned flavors",
),
(
"pkg/controller/jobframework/reconciler.go",
"Updating the PodsReady condition",
),
(
"pkg/controller/core/workload_controller.go",
"exceeding the PodsReady timeout",
),
(
"pkg/controller/core/workload_controller.go",
(
"Workload is inadmissible because the LocalQueue is terminating or"
" missing"
),
),
(
"pkg/scheduler/preemption/preemption.go",
"Fair Sharing within the cohort",
),
("pkg/cache/scheduler/tas_flavor_snapshot.go", "no topology domains"),
(
"pkg/scheduler/flavorassigner/flavorassigner.go",
"couldn't assign flavors",
),
(
"pkg/scheduler/flavorassigner/flavorassigner.go",
"unavailable in ClusterQueue",
),
(
"pkg/scheduler/flavorassigner/flavorassigner.go",
"insufficient unused quota",
),
("pkg/cache/queue/manager.go", "localQueue doesn't exist"),
# Signature table (log_signatures.py)
(
"pkg/scheduler/flavorassigner/flavorassigner.go",
"couldn't assign flavors to pod set",
),
(
"pkg/scheduler/flavorassigner/flavorassigner.go",
"insufficient quota for",
),
(
"pkg/scheduler/flavorassigner/flavorassigner.go",
"insufficient unused quota for",
),
(
"pkg/cache/scheduler/tas_flavor_snapshot.go",
"doesn't allow to fit any of",
),
("pkg/cache/scheduler/tas_flavor_snapshot.go", "allows to fit only"),
(
"pkg/scheduler/scheduler.go",
(
"Workload requires preemption, but there are no candidate workloads"
" allowed for preemption"
),
),
(
"pkg/scheduler/preemption/preemption.go",
"Preempted to accommodate a workload",
),
(
"pkg/controller/core/workload_controller.go",
"Exceeded the PodsReady timeout",
),
(
"pkg/controller/core/workload_controller.go",
"exceeding the maximum number of re-queuing retries",
),
(
"pkg/controller/core/workload_controller.go",
"the retention period has elapsed",
),
(
"pkg/controller/core/workload_controller.go",
"Deleted finished workload due to elapsed retention",
),
(
"pkg/scheduler/flavorassigner/tas_flavorassigner.go",
"does not contain the requested level",
),
(
"pkg/scheduler/flavorassigner/tas_flavorassigner.go",
"supports only TopologyAwareScheduling",
),
("pkg/scheduler/scheduler.go", "Flavors considered"),
)
# Event emitters that belong to Kueue or to the Kubernetes core controllers.
# Anything else (cluster autoscalers, node provisioners, device operators,
# provider controllers) is an external emitter: its Events are surfaced
# verbatim with the emitter name, whatever their type or reason, so that the
# agent can attribute them without the script knowing any provider's reason
# vocabulary.
_CORE_EMITTER_PREFIXES = (
"kueue",
"job-controller",
"jobset",
"cronjob-controller",
"kubelet",
"default-scheduler",
"replicaset-controller",
"deployment-controller",
"statefulset-controller",
"daemonset-controller",
"endpoint",
"node-controller",
"taint",
"service-controller",
"persistentvolume",
"attachdetach",
"horizontal-pod-autoscaler",
"garbage-collector",
"namespace-controller",
"leaderworkerset",
"ray",
"kubeflow",
)
# Kueue registers its Event recorders as `<gvk>-kueue-controller`,
# `multikueue-*`, `tas-*`, `concurrent-admission-controller`,
# `failure-recovery-*` and `ElasticJobUngater`
# (pkg/controller/jobframework/setup.go, pkg/controller/tas/constants.go,
# pkg/controller/concurrentadmission, pkg/controller/failurerecovery,
# cmd/kueue/main.go).
_KUEUE_EMITTER_MARKERS = (
"kueue",
"tas-",
"concurrent-admission",
"failure-recovery",
"elasticjob",
)
def _is_event_record(d: dict[str, Any]) -> bool:
return (
d.get("kind") == "Event"
or d.get("logger") == "events"
or isinstance(d.get("involvedObject"), dict)
or isinstance(d.get("regarding"), dict)
or isinstance(d.get("source"), dict)
or any(
d.get(k)
for k in (
"reportingController",
"reportingComponent",
"reportingInstance",
)
)
)
def event_emitter(d: dict[str, Any]) -> str:
"""Returns the Event emitter name ('' when unknown) from raw or normalised rows."""
if not _is_event_record(d):
return ""
return log_envelopes.extract_event_emitter(d)
def is_external_emitter(d: dict[str, Any]) -> bool:
"""True when an Event comes from a component outside Kueue and the Kubernetes core."""
emitter = event_emitter(d).lower()
if not emitter or emitter.startswith("kind source:"):
return False
if any(marker in emitter for marker in _KUEUE_EMITTER_MARKERS):
return False
return not any(emitter.startswith(p) for p in _CORE_EMITTER_PREFIXES)
_FRAMEWORKS_YAML_RE = re.compile(
r"integrations:[ \t]*\n(?:[ \t]+(?!frameworks:)\S.*\n)*?[ \t]+frameworks:["
r" \t]*\n((?:[ \t]+-[ \t]*\S+[ \t]*\n?)+)"
)
_FRAMEWORKS_JSON_RE = re.compile(r'"frameworks"\s*:\s*\[([^\]\[]{0,2000})\]')
def frameworks_from_config(config_text: str) -> list[str] | None:
"""integrations.frameworks from the 'Configuration loaded' payload (YAML or JSON); None if absent."""
m = _FRAMEWORKS_YAML_RE.search(config_text)
if m:
return [
ln.strip().lstrip("-").strip().strip("'\"")
for ln in m.group(1).splitlines()
if ln.strip()
]
m = _FRAMEWORKS_JSON_RE.search(config_text)
if m:
return [x.strip().strip("'\"") for x in m.group(1).split(",") if x.strip()]
return None
# Audit verbs on these resources are summarised under `audit_resource_actions`.
_AUDITED_RESOURCES = frozenset({
"workloads",
"localqueues",
"clusterqueues",
"cohorts",
"resourceflavors",
"admissionchecks",
"provisioningrequestconfigs",
"topologies",
"workloadpriorityclasses",
"multikueueconfigs",
"multikueueclusters",
"jobs",
"jobsets",
"namespaces",
"nodes",
"configmaps",
})
# Audited mutations of these resources (any verb) and deletions of any audited
# resource receive a fact id: they change the admission graph or its
# configuration. Job/Workload creations and status patches do not.
_GRAPH_CONFIG_RESOURCES = frozenset({
"localqueues",
"clusterqueues",
"cohorts",
"resourceflavors",
"admissionchecks",
"provisioningrequestconfigs",
"topologies",
"workloadpriorityclasses",
"multikueueconfigs",
"multikueueclusters",
"namespaces",
"configmaps",
})
# Error lines matching these substrings are ordinary controller retry noise
# (optimistic-concurrency conflicts); they stay in key_errors_and_events but
# do not receive a fact id.
_ROUTINE_ERROR_MARKERS = (
"the object has been modified; please apply your changes",
"already exists",
)
# API-pressure signals, classified by the side that produced them.
# kueue-client : emitted by Kueue's own client-go rate limiter
# (clientConnection.qps/burst in KueueConfiguration).
# apiserver : emitted by the Kubernetes API server (HTTP 429/503,
# API Priority and Fairness shedding).
# kueue-leader : controller-runtime leader election outcome.
# The table is observational: it records what the log said and which component
# said it; it does not assert why. A status number counts only next to
# `code` / `status` / `HTTP`: a bare 429 or 503 is as often part of an object
# name or a resourceVersion.
_HTTP_STATUS_CONTEXT = r"(?:code|status|HTTP)[\s:=\"'\\]{0,4}"
_API_PRESSURE_SIGNALS: tuple[tuple[str, str, str], ...] = (
(
"kueue-client",
"client-side rate limiter / throttling",
(
r"client-side throttling|rate:\s*Wait\([^)]*\)\s*would exceed"
r" context deadline"
),
),
(
"apiserver",
"HTTP 503 / the server is currently unable to handle the request",
(
r"unable to handle the request|503 Service Unavailable|"
+ _HTTP_STATUS_CONTEXT
+ r"503\b"
),
),
(
"apiserver",
"HTTP 429 / too many requests",
r"too many requests|" + _HTTP_STATUS_CONTEXT + r"429\b",
),
(
"kueue-leader",
"leader election lost / failed to renew lease",
r"leader election lost|failed to renew lease(?!.*context canceled)",
),
)
_API_PRESSURE_SIDE_NOTE = {
"kueue-client": (
"emitted by Kueue's own client-go rate limiter; its budget is"
" KueueConfiguration.clientConnection.qps/burst"
" (https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/,"
" https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta1/)"
),
"apiserver": (
"emitted by the Kubernetes API server, not by Kueue; HTTP 429/503 are"
" produced by API Priority and Fairness (per priority level / flow"
" schema) or an overloaded/unavailable server; whether other clients of"
" that API server are affected is not visible in this log alone"
),
"kueue-leader": (
"KueueConfiguration.leaderElection configures manager.Manager leader"
" election"
" (https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/,"
" https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta1/)"
),
}
_AUDIT_LOGGERS = ("audit", "cloud-audit")
_ADMISSION_MSG = "Workload successfully admitted and assigned flavors"
_LQ_MISSING_MSG = (
"Workload is inadmissible because the LocalQueue is terminating or missing"
)
# Controller lifecycle chatter that never describes a workload decision.
_BENIGN_SIGNALS = (
"RoleTracker: leader election enabled",
"Stopping and waiting for",
"Shutdown signal received",
"All workers finished",
"Wait completed, proceeding to shutdown",
"client rate limiter Wait returned an error: context canceled",
)
_KEY_EVENT_REASONS = frozenset({
"Pending",
"FailedScheduling",
"EvictedDueToPodsReadyTimeout",
"EvictedDueToAdmissionCheck",
"AdmissionCheckUpdated",
"UpdatedAdmissionCheck",
"Evicted",
"Preempted",
"NotTriggerScaleUp",
"BookingExpired",
"FailedCreate",
"Inadmissible",
})
# Matched case-sensitively against the combined signal text.
_KEY_EVENT_MARKERS = (
"couldn't assign flavors",
"localQueue doesn't exist",
"strict decoding error",
)
# Matched against the lower-cased combined signal text.
_KEY_EVENT_MARKERS_LOWER = (
"inadmissible",
"retrying after failure",
"evicted due to",
"context deadline exceeded",
"would exceed context deadline",
"client-side throttling",
"leader election lost",
"failed to renew lease",
"unable to handle the request",
)
_MAX_KEY_EVENTS = 30
_MAX_AUDIT_ACTIONS = 35
_MAX_AUDIT_DELETIONS = 35
_MAX_AUDIT_ACTIONS_WITH_STATUS = 40
# ---------------------------------------------------------------------------
# Typed access to a parsed record
# ---------------------------------------------------------------------------
def _ref_name(value: Any) -> str:
"""Name from a logged object ref: `{name: ...}` (klog ObjectRef) or a plain string."""
if isinstance(value, dict):
return str(value["name"]) if value.get("name") else ""
if isinstance(value, str):
return value
return ""
def _ref_namespace(value: Any, default: str = "") -> str:
"""Namespace of a klog ObjectRef dict; `default` for strings and other shapes."""
if isinstance(value, dict) and isinstance(value.get("namespace"), str):
return value["namespace"]
return default
def _qualified(namespace: Any, name: str) -> str:
return f"{namespace}/{name}" if namespace else name
def _first_str(d: dict[str, Any], *keys: str) -> str:
"""`str()` of the first truthy value among `keys` ('' when none)."""
for key in keys:
if d.get(key):
return str(d[key])
return ""
@dataclasses.dataclass(frozen=True)
class LogRecord:
"""A parsed log record with its commonly read fields normalised to strings."""
raw: dict[str, Any]
msg: str
note: str
err: str
reason: str
logger: str
ts: str
level: str
ev_type: str
workload: Any
wl_full: str
obj: dict[str, Any] | None
job_ref: str = ""
@classmethod
def from_dict(cls, d: Any) -> "LogRecord":
"""Builds a record from any JSON value; non-dict input yields an empty record."""
if not isinstance(d, dict):
d = {}
wl = d.get("workload")
wl_full = ""
if isinstance(wl, dict) and wl.get("name"):
wl_full = _qualified(_ref_namespace(wl), str(wl["name"]))
elif isinstance(wl, str) and wl:
wl_full = wl
# The job reconciler logs with `job=<ns>/<name>` (ReconcileGenericJob),
# not `workload`.
job = d.get("job")
job_ref = ""
if isinstance(job, str):
job_ref = job
elif isinstance(job, dict) and job.get("name"):
job_ref = _qualified(_ref_namespace(job), str(job.get("name")))
obj = d.get("object") or d.get("involvedObject")
return cls(
raw=d,
msg=_first_str(d, "msg", "message"),
note=_first_str(d, "note"),
err=_first_str(d, "error", "err"),
reason=_first_str(d, "reason"),
logger=_first_str(d, "logger"),
ts=_first_str(d, "ts", "time", "timestamp"),
level=_first_str(d, "level", "severity").lower(),
ev_type=_first_str(d, "type"),
workload=wl,
wl_full=wl_full,
obj=obj if isinstance(obj, dict) else None,
job_ref=job_ref,
)
@property
def ts_field(self) -> str:
"""The literal `ts` field (audit entries are stamped from it alone)."""
return _first_str(self.raw, "ts")
@property
def is_audit(self) -> bool:
"""Audit entries are summarised under `audit_resource_actions`, never as key events."""
return self.logger in _AUDIT_LOGGERS or self.msg.startswith("[Audit ")
@property
def is_audit_source(self) -> bool:
"""Wider test used for source counting (also cloud audit envelopes)."""
return (
self.is_audit
or bool(self.raw.get("auditID"))
or bool(self.raw.get("protoPayload"))
)
@property
def is_kubernetes_event(self) -> bool:
"""An exported Event object (normalised or raw), not a controller log line about one."""
return (
self.raw.get("source_kind") == log_envelopes.K8S_EVENT_SOURCE_KIND
or self.raw.get("kind") == "Event"
or bool(self.raw.get("involvedObject") and self.reason)
)
@property
def combined_signal(self) -> str:
return f"{self.msg} | {self.reason} | {self.note} | {self.err}"
@property
def msg_and_note(self) -> str:
return self.msg + " " + self.note
@property
def named_obj(self) -> dict[str, Any] | None:
"""`object` / `involvedObject` when it carries a name."""
return self.obj if self.obj is not None and self.obj.get("name") else None
# ---------------------------------------------------------------------------
# Scan state
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class LogScanState:
"""Every accumulator filled by the scanners and read by the emitters."""
source_counts: dict[str, int] = dataclasses.field(
default_factory=lambda: {
"total": 0,
"kueue-controller": 0,
"audit": 0,
"kubernetes-event": 0,
"unstructured": 0,
}
)
window_start: str = ""
window_end: str = ""
config_excerpt: str = ""
config_frameworks: list[str] | None = None
# Entity inventory.
workloads: set[str] = dataclasses.field(default_factory=set)
cluster_queues: set[str] = dataclasses.field(default_factory=set)
local_queues: set[str] = dataclasses.field(default_factory=set)
resource_flavors: set[str] = dataclasses.field(default_factory=set)
namespaces: set[str] = dataclasses.field(default_factory=set)
nodes: set[str] = dataclasses.field(default_factory=set)
discovered_kinds: set[str] = dataclasses.field(
default_factory=lambda: {
"ClusterQueue",
"LocalQueue",
"Workload",
"ResourceFlavor",
"KueueConfiguration",
}
)
# Admission volume: (clusterQueue, flavor, resource) -> summed resourceUsage;
# admitted count per CQ.
admitted_usage: dict[tuple[str, str, str], float] = dataclasses.field(
default_factory=dict
)
admitted_count_by_cq: dict[str, int] = dataclasses.field(default_factory=dict)
# PodsReady transitions.
waiting_pods_ready_workloads: set[str] = dataclasses.field(
default_factory=set
)
pods_ready_true_workloads: set[str] = dataclasses.field(default_factory=set)
# Reference -> `reason` of its latest status=False line ('' when not logged).
pods_ready_false_reason: dict[str, str] = dataclasses.field(
default_factory=dict
)
empty_lq_workloads: set[str] = dataclasses.field(default_factory=set)
in_cohort_preemptions: list[str] = dataclasses.field(default_factory=list)
has_insufficient_quota_pending: bool = False
# Audit trail.
audit_actions: list[tuple[str | None, str]] = dataclasses.field(
default_factory=list
)
seen_audit: set[str] = dataclasses.field(default_factory=set)
audit_non_delete_count: int = 0
audit_delete_count: int = 0
omitted_audit: int = 0
omitted_audit_deletions: int = 0
workload_status_by_name: dict[str, str] = dataclasses.field(
default_factory=dict
)
# Namespace -> (timestamp, response code as logged or '').
audit_namespace_deletions: dict[str, tuple[str, str]] = dataclasses.field(
default_factory=dict
)
audit_cq_quota_patches: list[str] = dataclasses.field(default_factory=list)
# (timestamp, ClusterQueue, value, principal, verb, confirmed_change).
audit_cq_quota_patch_detail: list[tuple[str, str, str, str, str, bool]] = (
dataclasses.field(default_factory=list)
)
# Raw CQ quota events buffered during scan, resolved in chronological order
# at the end of `scan_lines`: (ts, seq, cq, kind, value, principal, verb).
audit_cq_quota_events: list[tuple[str, int, str, str, str, str, str]] = (
dataclasses.field(default_factory=list)
)
audit_cq_quota_seq: int = 0
# ClusterQueue -> nominalQuota values of the latest request body seen for it.
audit_cq_quota_bodies: dict[str, str] = dataclasses.field(
default_factory=dict
)
audit_indexed_jobs_no_max_failed: list[str] = dataclasses.field(
default_factory=list
)
# Key errors / events.
key_events: list[tuple[str, str]] = dataclasses.field(default_factory=list)
seen_events: set[str] = dataclasses.field(default_factory=set)
omitted_events: int = 0
# Plain-text signals.
topology_levels_without_domains: set[str] = dataclasses.field(
default_factory=set
)
strict_unknown_fields: set[str] = dataclasses.field(default_factory=set)
unavailable_resources: set[str] = dataclasses.field(default_factory=set)
webhook_timeout_targets: set[str] = dataclasses.field(default_factory=set)
# Webhook name -> connection-level causes logged for it (no timeout among
# them is implied; see `scan_text_signals`).
webhook_connection_errors: dict[str, set[str]] = dataclasses.field(
default_factory=dict
)
# Webhook name -> other logged causes (neither timeout nor connection-level).
webhook_other_errors: dict[str, set[str]] = dataclasses.field(
default_factory=dict
)
api_pressure_signals: set[tuple[str, str]] = dataclasses.field(
default_factory=set
)
client_throttling_count: int = 0
# Controller-message signatures (log_signatures.SIGNATURES), keyed by
# signature key.
signature_hits: dict[str, log_signatures.SignatureHits] = dataclasses.field(
default_factory=dict
)
# ---------------------------------------------------------------------------
# Plain-text scanning (every line, structured or not)
# ---------------------------------------------------------------------------
_TAS_LEVEL_RE = re.compile(
r"no topology domains at level:\s*([A-Za-z0-9./_-]+)"
)
_UNAVAILABLE_RESOURCE_RE = re.compile(
r"resource\s+([a-z0-9._/-]+)\s+unavailable in ClusterQueue"
)
_UNKNOWN_FIELD_RE = re.compile(r'unknown field\s*\\?"([^"\\]+)\\?"')
_WEBHOOK_FAILURE_RE = re.compile(
r'failed calling webhook\s+\\?"([^"\\]+)\\?"', re.IGNORECASE
)
# The webhook URL always carries `?timeout=<n>s`; it is not a cause.
_WEBHOOK_URL_TIMEOUT_RE = re.compile(r"\?timeout=\d+s")
# Go error texts, matched case-sensitively after the webhook name.
_WEBHOOK_TIMEOUT_CAUSE_RE = re.compile(
r"context deadline exceeded|Client\.Timeout|i/o timeout"
)
_WEBHOOK_CONNECTION_CAUSE_RE = re.compile(r"connection refused|\bEOF\b")
_WEBHOOK_CALL_PREFIX_RE = re.compile(
r"^(?:failed to call webhook:\s*)?"
r'(?:(?:Post|Get|Put|Patch|Delete)\s+\\?"[^"\\]+\\?":\s*)?'
)
_UNESCAPED_JSON_END_RE = re.compile(r'(?<!\\)["}]')
def _extract_webhook_other_cause(cause_text: str, *, is_json_line: bool) -> str:
"""Extracts and redacts the trailing error cause after a webhook name."""
text = cause_text.lstrip(" :")
if is_json_line:
end_m = _UNESCAPED_JSON_END_RE.search(text)
if end_m:
text = text[: end_m.start()]
text = _WEBHOOK_CALL_PREFIX_RE.sub("", text).replace('\\"', '"').strip()
text = " ".join(log_envelopes.redact_env_text(text).split())
return text[:160]
def _scan_webhook_failure(text: str, state: LogScanState) -> None:
"""Classifies a 'failed calling webhook' line by its stated cause.
Timeout and connection-level causes are recorded in dedicated sets; any other
logged cause (such as missing endpoints or certificate errors) is recorded
verbatim under `webhook_other_errors` without calling it a timeout.
Args:
text: Log line text.
state: Scan state updated in place.
"""
wh_m = _WEBHOOK_FAILURE_RE.search(text)
if not wh_m:
return
cause_text = _WEBHOOK_URL_TIMEOUT_RE.sub("", text[wh_m.end() :])
if _WEBHOOK_TIMEOUT_CAUSE_RE.search(cause_text):
state.webhook_timeout_targets.add(wh_m.group(1))
return
conn_m = _WEBHOOK_CONNECTION_CAUSE_RE.search(cause_text)
if conn_m:
state.webhook_connection_errors.setdefault(wh_m.group(1), set()).add(
conn_m.group(0)
)
return
other = _extract_webhook_other_cause(
cause_text, is_json_line=text.lstrip().startswith("{")
)
if other:
state.webhook_other_errors.setdefault(wh_m.group(1), set()).add(other)
def scan_text_signals(text: str, state: LogScanState) -> None:
"""Collects signals that are recognisable from the raw line text alone."""
low = text.lower()
lvl_m = _TAS_LEVEL_RE.search(text)
if lvl_m:
state.topology_levels_without_domains.add(lvl_m.group(1))
state.discovered_kinds.add("Topology")
unavail_m = _UNAVAILABLE_RESOURCE_RE.search(text)
if unavail_m:
state.unavailable_resources.add(unavail_m.group(1))
if "ProvisioningRequest" in text or "provisioningrequest" in low:
state.discovered_kinds.update(
{"AdmissionCheck", "ProvisioningRequestConfig"}
)
if "strict decoding error" in text:
state.strict_unknown_fields.update(_UNKNOWN_FIELD_RE.findall(text))
_scan_webhook_failure(text, state)
# API-pressure signals are classified by the side that produced them so the
# reader can tell a Kueue-side client limiter apart from API-server-side
# rejection; the two have different owners and different remediations.
for sig_side, sig_name, pat in _API_PRESSURE_SIGNALS:
if re.search(pat, text, re.IGNORECASE):
state.api_pressure_signals.add((sig_side, sig_name))
if "client-side throttling, not priority and fairness" in low:
state.client_throttling_count += 1
# ---------------------------------------------------------------------------
# Record scanners
# ---------------------------------------------------------------------------
def scan_source_and_window(rec: LogRecord, state: LogScanState) -> None:
"""Counts the record under its source and widens the observed time window."""
if rec.is_audit_source:
state.source_counts["audit"] += 1
elif rec.is_kubernetes_event:
state.source_counts["kubernetes-event"] += 1
else:
state.source_counts["kueue-controller"] += 1
if rec.ts and not rec.ts.replace(".", "", 1).isdigit():
state.window_start = min(state.window_start or rec.ts, rec.ts)
state.window_end = max(state.window_end, rec.ts)
_CONFIG_LOADED_MSGS = (
"Configuration loaded",
"Successfully loaded configuration",
)
def scan_config(rec: LogRecord, state: LogScanState) -> None:
"""Keeps the latest 'Configuration loaded' / 'Successfully loaded configuration' payload and its integrations.frameworks."""
if rec.msg in _CONFIG_LOADED_MSGS and rec.raw.get("config"):
config_text = str(rec.raw.get("config"))
state.config_excerpt = config_text[:1500]
state.config_frameworks = frameworks_from_config(config_text)
def scan_workload_ref(rec: LogRecord, state: LogScanState) -> None:
"""Records the `workload` reference and its namespace."""
if not rec.wl_full:
return
state.workloads.add(rec.wl_full)
ns = _ref_namespace(rec.workload)
if ns:
state.namespaces.add(ns)
def scan_admission(rec: LogRecord, state: LogScanState) -> None:
"""Sums resourceUsage from 'Workload successfully admitted and assigned flavors'."""
d = rec.raw
if rec.msg != _ADMISSION_MSG or not isinstance(d.get("assignments"), list):
return
adm_cq_name = _ref_name(d.get("clusterQueue"))
if not adm_cq_name:
return
state.admitted_count_by_cq[adm_cq_name] = (
state.admitted_count_by_cq.get(adm_cq_name, 0) + 1
)
for ps in d.get("assignments") or []:
if not isinstance(ps, dict):
continue
flavors_map = (
ps.get("flavors") if isinstance(ps.get("flavors"), dict) else {}
)
usage_map = (
ps.get("resourceUsage")
if isinstance(ps.get("resourceUsage"), dict)
else {}
)
for res_n, qty in usage_map.items():
fl_n = str(flavors_map.get(res_n) or "")
qv = report_output.parse_quantity(qty)
if qv is None:
continue
k3 = (adm_cq_name, fl_n, str(res_n))
state.admitted_usage[k3] = state.admitted_usage.get(k3, 0.0) + qv
def scan_pods_ready(rec: LogRecord, state: LogScanState) -> None:
"""Tracks PodsReady condition transitions keyed by the Job/Workload reference."""
if rec.msg != "Updating the PodsReady condition":
return
# JobReconciler.ReconcileGenericJob logs this at V(3) on every PodsReady
# transition with the condition's reason and status; its logger carries
# `job=<ns>/<name>`, not `workload`.
ref = rec.job_ref or rec.wl_full
if not ref:
return
status = str(rec.raw.get("status", "")).lower()
if status == "false":
state.waiting_pods_ready_workloads.add(ref)
state.pods_ready_false_reason[ref] = rec.reason
state.pods_ready_true_workloads.discard(ref)
elif status == "true":
state.pods_ready_true_workloads.add(ref)
state.waiting_pods_ready_workloads.discard(ref)
def scan_local_queue_missing(rec: LogRecord, state: LogScanState) -> None:
"""Workloads reconciled with an empty LocalQueue name."""
if _LQ_MISSING_MSG in rec.msg:
lq_obj = rec.raw.get("localQueue")
lq_name = lq_obj.get("name") if isinstance(lq_obj, dict) else None
if isinstance(lq_name, str) and not lq_name and rec.wl_full:
state.empty_lq_workloads.add(rec.wl_full)
_PREEMPTION_PATH_RE = re.compile(
r"preemptor path:\s*(\S+);\s*preemptee path:\s*(\S+)"
)
def scan_fair_sharing(rec: LogRecord, state: LogScanState) -> None:
"""In-cohort fair-sharing preemptions and 'insufficient unused quota' markers."""
if (
rec.reason == "InCohortFairSharing"
or "due to Fair Sharing within the cohort" in rec.msg_and_note
):
p_cq = _first_str(rec.raw, "preemptingClusterQueue")
t_cq = _first_str(rec.raw, "targetClusterQueue")
if p_cq or t_cq:
state.in_cohort_preemptions.append(f"{p_cq}->{t_cq}")
else:
pm = _PREEMPTION_PATH_RE.search(rec.msg_and_note)
if pm:
state.in_cohort_preemptions.append(f"{pm.group(1)}->{pm.group(2)}")
else:
state.in_cohort_preemptions.append("InCohortFairSharing")
if "insufficient unused quota" in rec.msg_and_note.lower():
state.has_insufficient_quota_pending = True
def scan_queues(rec: LogRecord, state: LogScanState) -> None:
"""Discovers ClusterQueues and LocalQueues named by the record."""
d = rec.raw
cq_name = _ref_name(d.get("clusterQueue") or d.get("clusterqueue"))
if cq_name:
state.cluster_queues.add(cq_name)
lq = d.get("localQueue") or d.get("queue")
if isinstance(lq, dict) and lq.get("name"):
state.local_queues.add(
_qualified(
_ref_namespace(lq, _first_str(d, "namespace")), str(lq["name"])
)
)
elif isinstance(lq, str) and lq:
state.local_queues.add(lq)
def scan_entities(rec: LogRecord, state: LogScanState) -> None:
"""Discovers ResourceFlavors, Nodes and Workload object refs (with PodsReady evictions)."""
d = rec.raw
rf = d.get("resourceFlavor")
if isinstance(rf, dict) and rf.get("name"):
state.resource_flavors.add(str(rf["name"]))
elif "flavor" in rec.logger and d.get("name"):
state.resource_flavors.add(str(d["name"]))
if "node-reconciler" in rec.logger and d.get("name"):
state.nodes.add(str(d["name"]))
obj = rec.named_obj
if (
obj is not None
and obj.get("kind", "") == "Workload"
and isinstance(obj["name"], str)
):
state.workloads.add(_qualified(_ref_namespace(obj), obj["name"]))
@dataclasses.dataclass(frozen=True)
class _AuditRef:
verb: str
resource: str
subresource: str
res_name: str
namespace: str = ""
name: str = ""
@property
def short_name(self) -> str:
"""Object name; the last path segment of `resourceName` when no name field is known."""
return self.name or self.res_name.rsplit("/", 1)[-1]
_AUDIT_MSG_RE = re.compile(
r"\[Audit\s+([a-zA-Z]+)\s+([a-zA-Z0-9._/-]+)\]\s*(\S+)?"
)
def _audit_ref(rec: LogRecord) -> _AuditRef:
"""Verb / resource / subresource / target of an audit entry from its fields, methodName or `[Audit ...]` prefix."""
d = rec.raw
verb = _first_str(d, "verb")
resource = _first_str(d, "resource")
subresource = _first_str(d, "subresource")
res_name = _first_str(d, "resourceName")
namespace = _first_str(d, "namespace")
name = _first_str(d, "name")
if (not verb or not resource) and d.get("methodName"):
parsed = log_envelopes.gcp_audit_ref(
str(d["methodName"]), _first_str(d, "providerResourceName") or res_name
)
verb = verb or parsed.verb
resource = resource or parsed.resource
subresource = subresource or parsed.subresource
namespace = namespace or parsed.namespace
name = name or parsed.name
if (not verb or not resource) and rec.msg.startswith("[Audit "):
am = _AUDIT_MSG_RE.match(rec.msg)
if am:
msg_resource, _, msg_subresource = am.group(2).partition("/")
verb = verb or am.group(1)
resource = resource or msg_resource
subresource = subresource or msg_subresource
res_name = res_name or (am.group(3) or "")
return _AuditRef(verb, resource, subresource, res_name, namespace, name)
def _audit_principal(d: dict[str, Any]) -> str:
user_field = d.get("user")
return str(
d.get("principalEmail")
or (
user_field.get("username", "")
if isinstance(user_field, dict)
else user_field or ""
)
)
def _audit_response_code(d: dict[str, Any]) -> int | None:
code = d.get("responseCode")
if isinstance(code, str) and code.isdigit():
return int(code)
if isinstance(code, int) and not isinstance(code, bool):
return code
return None
def _audit_rejection(d: dict[str, Any]) -> str:
"""Formats the rejection code suffix for an audit row, or returns ''.
`audit.k8s.io` rows carry the HTTP status, which reports a rejection from
400 up. Cloud audit rows carry a `google.rpc.Code` instead, where every
non-zero value (1-16) is an error; those are printed as `rpc_code=<N>`.
Args:
d: Normalised audit row.
Returns:
`' code=<N>'`, `' rpc_code=<N>'`, or `''`.
"""
code = _audit_response_code(d)
if code is None:
return ""
if code >= 400:
return f" code={code}"
if 0 < code < 100:
return f" rpc_code={code}"
return ""
def _nominal_quota_values(spec: Any) -> list[str]:
"""`<flavor>/<resource>=<nominalQuota>` for every quota a ClusterQueue `spec` body sets."""
rows: list[str] = []
groups = k8s_objects.as_dict(spec).get("resourceGroups")
for group in k8s_objects.dict_items(groups):
for flavor in k8s_objects.dict_items(group.get("flavors")):
for res in k8s_objects.dict_items(flavor.get("resources")):
if res.get("nominalQuota") is not None:
rows.append(
f"{flavor.get('name', '')}/{res.get('name', '')}"
f"={res['nominalQuota']}"
)
return rows
_RFC3339_TS_RE = re.compile(
r"^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2})(?:\.(\d+))?"
r"(Z|[+-]\d{2}:?\d{2})?$",
re.IGNORECASE,
)
_NON_QUOTA_PATCH_LEAVES = (
"/borrowingLimit",
"/lendingLimit",
"/coveredResources",
)
def _ts_sort_key(ts: str) -> tuple[int, int, int, str]:
"""Chronological sort key handling variable fractional-second RFC3339 strings."""
m = _RFC3339_TS_RE.match(ts.strip())
if not m:
return (1, 0, 0, ts)
base, frac, tz = m.groups()
tz_iso = "+00:00" if not tz or tz.upper() == "Z" else tz
if len(tz_iso) == 5:
tz_iso = f"{tz_iso[:3]}:{tz_iso[3:]}"
try:
dt = datetime.datetime.fromisoformat(f"{base}{tz_iso}")
except ValueError:
return (1, 0, 0, ts)
nanos = int((frac or "0")[:9].ljust(9, "0"))
return (0, int(dt.timestamp()), nanos, ts)
def _extract_patch_nominal_quotas(val: Any, depth: int = 0) -> list[str]:
"""Extracts `nominalQuota` summaries from a JSON-patch `value` payload."""
if depth > 4:
return []
if isinstance(val, dict):
if "resourceGroups" in val:
return _nominal_quota_values(val)
if "flavors" in val:
return _nominal_quota_values({"resourceGroups": [val]})
if "resources" in val:
return _nominal_quota_values({"resourceGroups": [{"flavors": [val]}]})
if "nominalQuota" in val:
rname = str(val.get("name") or "<resource>")
return [f"{rname}={val['nominalQuota']}"]
elif isinstance(val, list):
out: list[str] = []
for item in val:
out.extend(_extract_patch_nominal_quotas(item, depth + 1))
return out
return []
def _append_quota_event(
state: LogScanState,
rec: LogRecord,
ref: _AuditRef,
kind: str,
val: str,
principal: str,
) -> None:
"""Appends one sequenced ClusterQueue quota event for chronological sorting."""
state.audit_cq_quota_seq += 1
state.audit_cq_quota_events.append((
rec.ts_field,
state.audit_cq_quota_seq,
ref.short_name,
kind,
val,
principal,
ref.verb,
))
def _record_json_patch_op(
op: dict[str, Any],
rec: LogRecord,
state: LogScanState,
ref: _AuditRef,
principal: str,
) -> None:
"""Buffers one RFC 6902 JSON-patch operation affecting ClusterQueue quota."""
op_name = str(op.get("op") or "").lower()
if op_name == "test":
return
path = str(op.get("path") or "")
if "nominalQuota" in path:
if op_name == "remove" and "value" not in op:
val = "<removed>"
elif op_name in ("move", "copy") and "value" not in op:
val = f"<{op_name} from {op.get('from', '')}>"
else:
val = str(op.get("value"))
_append_quota_event(state, rec, ref, "json_patch", val, principal)
return
if path != "/spec" and not path.startswith("/spec/resourceGroups"):
return
op_val = op.get("value")
if path == "/spec" and isinstance(op_val, dict):
body = ", ".join(_nominal_quota_values(op_val))
if body:
_append_quota_event(state, rec, ref, "body", body, principal)
return
if path == "/spec/resourceGroups" and isinstance(op_val, list):
body = ", ".join(_nominal_quota_values({"resourceGroups": op_val}))
if body:
_append_quota_event(state, rec, ref, "body", body, principal)
return
if path.endswith(_NON_QUOTA_PATCH_LEAVES):
return
extracted = ", ".join(_extract_patch_nominal_quotas(op_val))
if (
extracted
or op_name in ("remove", "move", "copy")
or isinstance(op_val, (dict, list))
):
kind = "partial_patch" if extracted else "clear_body"
_append_quota_event(state, rec, ref, kind, extracted, principal)
def _record_quota_patches(
rec: LogRecord, state: LogScanState, ref: _AuditRef
) -> None:
"""Buffers `clusterqueues` nominalQuota events for chronological resolution.
Reads JSON-patch operations (`request` list) and create / merge-patch /
update bodies (`spec`). Actual earlier-body diffing happens in
`_resolve_quota_events` after sorting by parsed timestamp so newest-first log
exports do not reverse the diff or misattribute principals.
Args:
rec: Audit record.
state: Scan state to extend.
ref: Parsed audit reference of `rec`.
"""
d = rec.raw
principal = _audit_principal(d)
for op in k8s_objects.dict_items(d.get("request")):
_record_json_patch_op(op, rec, state, ref, principal)
body = ", ".join(_nominal_quota_values(d.get("spec")))
if body:
_append_quota_event(state, rec, ref, "body", body, principal)
def _resolve_quota_events(state: LogScanState) -> None:
"""Resolves buffered CQ quota events in chronological `(timestamp, seq)` order."""
for ts, _, cq, kind, val, principal, verb in sorted(
state.audit_cq_quota_events, key=lambda e: (_ts_sort_key(e[0]), e[1])
):
if kind == "clear_body":
state.audit_cq_quota_bodies.pop(cq, None)
continue
if kind == "partial_patch":
state.audit_cq_quota_bodies.pop(cq, None)
summary = f"{{{val}}}"
state.audit_cq_quota_patches.append(f"{cq}={summary}")
state.audit_cq_quota_patch_detail.append(
(ts, cq, summary, principal, verb, False)
)
continue
if kind == "json_patch":
state.audit_cq_quota_bodies.pop(cq, None)
state.audit_cq_quota_patches.append(f"{cq}={val}")
state.audit_cq_quota_patch_detail.append(
(ts, cq, val, principal, verb, True)
)
continue
earlier = state.audit_cq_quota_bodies.get(cq)
state.audit_cq_quota_bodies[cq] = val
if verb == "create" or val == earlier:
continue
if earlier is None:
summary, confirmed = f"{{{val}}}", False
else:
summary, confirmed = f"{{{val}}} (earlier body: {{{earlier}}})", True
state.audit_cq_quota_patches.append(f"{cq}={summary}")
state.audit_cq_quota_patch_detail.append(
(ts, cq, summary, principal, verb, confirmed)
)
def _record_indexed_job(
rec: LogRecord, state: LogScanState, res_name: str
) -> None:
"""Job / JobSet creations with backoffLimitPerIndex set and maxFailedIndexes unset."""
spec_d = rec.raw["spec"]
target = str(res_name or rec.raw.get("name") or "")
candidates: list[tuple[str, dict[str, Any]]] = [(target, spec_d)]
for rj in k8s_objects.dict_items(spec_d.get("replicatedJobs")):
rj_spec = k8s_objects.as_dict(rj.get("template")).get("spec")
if isinstance(rj_spec, dict):
candidates.append(
(f"{target}:replicatedJob[{rj.get('name', '')}]", rj_spec)
)
for ref_label, sub_spec in candidates:
if (
sub_spec.get("backoffLimitPerIndex") is not None
and sub_spec.get("maxFailedIndexes") is None
):
state.audit_indexed_jobs_no_max_failed.append(
f"{ref_label} (completionMode={sub_spec.get('completionMode')},"
f" backoffLimitPerIndex={sub_spec.get('backoffLimitPerIndex')},"
" maxFailedIndexes=unset)"
)
def _scan_audit_config_changes(
rec: LogRecord, state: LogScanState, ref: _AuditRef
) -> None:
"""Namespace deletions, nominalQuota writes and Indexed Job creations seen in the audit trail (rejected calls are skipped)."""
d = rec.raw
if _audit_rejection(d):
return
if ref.verb == "delete" and ref.resource == "namespaces" and ref.short_name:
code = _audit_response_code(d)
state.audit_namespace_deletions.setdefault(
ref.short_name, (rec.ts_field, "" if code is None else str(code))
)
if (
ref.verb in ("create", "patch", "update")
and ref.resource == "clusterqueues"
and not ref.subresource
):
_record_quota_patches(rec, state, ref)
if (
ref.verb == "create"
and ref.resource in ("jobs", "jobsets")
and isinstance(d.get("spec"), dict)
):
_record_indexed_job(rec, state, ref.res_name)
_MAX_AUDIT_LINE = 1400
def _replace_audit_spec_segment(msg: str, spec_json: str) -> str:
"""Replaces the first ` spec=...` segment up to the next audit field or end."""
start = msg.find(" spec=")
if start < 0:
return f"{msg} spec={spec_json}"
tail_start = start + len(" spec=")
end = len(msg)
for marker in (" annotations=", " labels=", " status="):
pos = msg.find(marker, tail_start)
if 0 <= pos < end:
end = pos
return f"{msg[:start]} spec={spec_json}{msg[end:]}"
def _audit_action_suffix(d: dict[str, Any], msg: str) -> str:
"""Response code of a rejected call, principal and request body, where `msg` does not already carry them."""
suffix = _audit_rejection(d)
principal = _audit_principal(d)
if principal and "principal=" not in msg:
suffix += f" principal={principal}"
if isinstance(d.get("request"), (dict, list)) and "request=" not in msg:
body = json.dumps(log_envelopes.redact_env_values(d["request"]))
suffix += f" request={body[:400]}"
return suffix
def _audit_action_line(rec: LogRecord) -> str:
"""Builds the audit summary text with spec, status code, principal, and request body.
Container `env` values are redacted. The message is cut, never the
trailing fields.
Args:
rec: Audit record.
Returns:
Redacted, length-bounded audit action summary line.
"""
d = rec.raw
msg = rec.msg
if isinstance(d.get("spec"), dict):
spec_json = json.dumps(
log_envelopes.redact_env_values(d["spec"]), sort_keys=True
)[:1200]
msg = _replace_audit_spec_segment(msg, spec_json)
msg = log_envelopes.redact_env_text(msg)
suffix = _audit_action_suffix(d, msg)
return msg[: max(0, _MAX_AUDIT_LINE - len(suffix))] + suffix
def _is_listed_audit_action(ref: _AuditRef) -> bool:
"""Mutations of audited resources, minus subresources and add-on / CA-bundle ConfigMaps."""
if (
ref.verb not in ("create", "delete", "patch", "update")
or ref.subresource
or ref.resource not in _AUDITED_RESOURCES
):
return False
return ref.resource != "configmaps" or not (
report_output.is_managed_addon_namespace(ref.namespace)
or ref.short_name == "kube-root-ca.crt"
)
def _scan_audit_actions(
rec: LogRecord, state: LogScanState, ref: _AuditRef
) -> None:
"""Workload status patches and deduplicated, capped audit mutations.
A rejected call is listed with its response code and gets no fact id. A
change of the admission graph (a deletion, or any mutation of a
`_GRAPH_CONFIG_RESOURCES` object) is listed once per call, so two updates
of one object at different times are both kept; other audited mutations
(Node, Job, Workload writes) collapse when the same body repeats.
Args:
rec: Audit record.
state: Scan state to extend.
ref: Parsed audit reference of `rec`.
"""
d = rec.raw
rejection = _audit_rejection(d)
if (
ref.resource == "workloads"
and ref.subresource == "status"
and (d.get("status") or " status=" in rec.msg)
):
if not rejection:
state.workload_status_by_name[ref.res_name] = str(rec.msg)[:850]
return
if not _is_listed_audit_action(ref):
return
graph_change = ref.verb == "delete" or ref.resource in _GRAPH_CONFIG_RESOURCES
line = _audit_action_line(rec)
ts = rec.ts_field
dedup_audit_key = f"{ts if graph_change else ''}{rejection} {line[:260]}"
if dedup_audit_key in state.seen_audit:
return
state.seen_audit.add(dedup_audit_key)
if ref.verb == "delete":
if state.audit_delete_count >= _MAX_AUDIT_DELETIONS:
state.omitted_audit_deletions += 1
return
state.audit_delete_count += 1
else:
if state.audit_non_delete_count >= _MAX_AUDIT_ACTIONS:
state.omitted_audit += 1
return
state.audit_non_delete_count += 1
audit_key = (
f"audit:{ref.verb}:{ref.resource}"
if graph_change and not rejection
else None
)
state.audit_actions.append((audit_key, (f"{ts} " if ts else "") + line))
def scan_audit(rec: LogRecord, state: LogScanState) -> None:
"""Audit entries: configuration changes and the capped `audit_resource_actions` list."""
if not rec.is_audit:
return
ref = _audit_ref(rec)
_scan_audit_config_changes(rec, state, ref)
_scan_audit_actions(rec, state, ref)
def _is_housekeeping_event(rec: LogRecord) -> bool:
"""Records about Kueue's optional components, add-on namespaces or controller lifecycle chatter."""
obj_text = json.dumps(rec.obj) if rec.obj is not None else ""
noise_probe = f"{rec.combined_signal} | {rec.logger} | {obj_text}".lower()
if "kueueviz" in noise_probe or "certwatcher" in noise_probe:
return True
if rec.obj is not None and report_output.is_managed_addon_namespace(
_ref_namespace(rec.obj)
):
return True
return any(benign in rec.combined_signal for benign in _BENIGN_SIGNALS)
def _is_key_event(rec: LogRecord) -> bool:
"""Errors, Warnings, external-emitter Events and known decision messages."""
signal = rec.combined_signal
low = signal.lower()
return (
rec.reason in _KEY_EVENT_REASONS
or rec.ev_type == "Warning"
or is_external_emitter(rec.raw)
or rec.level in ("error", "fatal", "panic")
or bool(rec.err)
or any(marker in signal for marker in _KEY_EVENT_MARKERS)
or any(marker in low for marker in _KEY_EVENT_MARKERS_LOWER)
)
def _key_event_summary(rec: LogRecord) -> tuple[str, str]:
"""Returns `(summary_line, detail)` for a key event."""
d = rec.raw
obj_ref = ""
obj = rec.named_obj
if obj is not None:
obj_ref = f"[{obj.get('kind', 'Object')}/{obj.get('name')}] "
elif isinstance(rec.workload, dict) and rec.workload.get("name"):
obj_ref = f"[Workload/{rec.workload.get('name')}] "
lq_detail = ""
if isinstance(d.get("localQueue"), dict) and "localQueue" in rec.msg:
lq_detail = f"localQueue={json.dumps(d.get('localQueue'))}"
detail = (
rec.note
or rec.err
or lq_detail
or (
json.dumps(log_envelopes.redact_env_values(d["spec"]))[:500]
if d.get("spec")
else ""
)
)
emitter_tag = (
f" (emitter: {event_emitter(d)})" if is_external_emitter(d) else ""
)
summary_line = (
f"{obj_ref}{rec.reason or rec.logger}: {rec.msg}"
+ (f" — {detail}" if detail and detail not in rec.msg else "")
+ emitter_tag
)
return summary_line, detail
def scan_key_events(rec: LogRecord, state: LogScanState) -> None:
"""Selects the deduplicated, capped `key_errors_and_events` entries."""
if rec.is_audit or _is_housekeeping_event(rec) or not _is_key_event(rec):
return
summary_line, detail = _key_event_summary(rec)
dedup_key = summary_line[:220]
if dedup_key in state.seen_events:
return
state.seen_events.add(dedup_key)
if len(state.key_events) >= _MAX_KEY_EVENTS:
state.omitted_events += 1
return
# Routine optimistic-concurrency noise is listed but not tracked as a fact.
routine = any(
marker in rec.combined_signal for marker in _ROUTINE_ERROR_MARKERS
)
group_msg = (
detail if (detail and rec.msg in ("", "Event occurred")) else rec.msg
)
if routine:
fact_key = ""
else:
fact_key = report_output.fact_group_key(
"logerr", "", rec.reason or rec.logger, group_msg
)
state.key_events.append((fact_key, summary_line[:450]))
def scan_signatures(rec: LogRecord, state: LogScanState) -> None:
"""Matches the controller-message signature table against the record's message, note and error."""
if rec.is_audit:
return
log_signatures.scan_signature_text(
rec.combined_signal, state.signature_hits, rec.ts
)
RecordScanner = Callable[[LogRecord, LogScanState], None]
# Applied to every parsed record, in this order.
RECORD_SCANNERS: tuple[RecordScanner, ...] = (
scan_source_and_window,
scan_config,
scan_workload_ref,
scan_admission,
scan_pods_ready,
scan_local_queue_missing,
scan_fair_sharing,
scan_queues,
scan_entities,
scan_audit,
scan_key_events,
scan_signatures,
)
# ---------------------------------------------------------------------------
# Fact emitters
# ---------------------------------------------------------------------------
Fact = tuple[str | None, str]
def emit_log_coverage(state: LogScanState) -> list[Fact]:
"""Evidence coverage of the log window, emitted first so the reader knows which questions this source can answer."""
source_questions = (
(
"kueue-controller",
(
"Kueue's own admission, preemption, requeue and config-loading"
" decisions"
),
),
("audit", "who created/patched/deleted which object and when"),
(
"kubernetes-event",
"scheduler/kubelet outcome per pod and Kueue Events per Workload",
),
)
counts = state.source_counts
absent_sources = [
f"{s} (answers: {q})" for s, q in source_questions if not counts.get(s)
]
return [(
"",
(
f"LOG_COVERAGE: lines={counts['total']}"
f" (kueue-controller={counts['kueue-controller']},"
f" audit={counts['audit']},"
f" kubernetes-event={counts['kubernetes-event']},"
f" unstructured={counts['unstructured']});"
f" window={state.window_start or '?'} .. {state.window_end or '?'};"
f" absent sources={absent_sources or 'none'}. Logs show decisions and"
" their stated reasons, not declared configuration: nominalQuota,"
" borrowingLimit, nodeLabels and other spec fields are only"
" observable from the objects themselves (snapshot) or from audit"
" patch bodies. A question that needs an absent source cannot be"
" settled from this log; name the source when reporting it as not"
" determinable."
),
)]
def emit_tas_level(state: LogScanState) -> list[Fact]:
return [
(
f"logfact:tas-level:{level}",
(
"TAS_LOG_FACT: controller logged 'no topology domains at level:"
f" {level}'"
" (https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/)."
" It is emitted when the TAS snapshot for the ResourceFlavor has"
" zero domains at that level: no node both matches the flavor's"
" nodeLabels and carries every label key listed in"
" Topology.spec.levels (and, where the scheduler gate applies,"
" is Ready and schedulable)."
),
)
for level in sorted(state.topology_levels_without_domains)
]
def emit_namespace_delete(state: LogScanState) -> list[Fact]:
"""`delete namespaces` requests that the audit log does not show as rejected."""
facts: list[Fact] = []
for ns_name, (ts, code) in sorted(state.audit_namespace_deletions.items()):
ts_part = f" at {ts}" if ts else ""
if code:
outcome_part = f" (response code {code})"
else:
outcome_part = (
" (whether the request succeeded is not determinable from this entry)"
)
facts.append((
f"logfact:namespace-delete:{ns_name}",
(
"AUDIT_LOG_FACT: the audit log records a `delete namespaces`"
f" request for namespace `{ns_name}`{ts_part}{outcome_part}. A"
" completed namespace deletion removes every namespaced object in"
" it (Jobs, Workloads, LocalQueues, Pods)."
),
))
return facts
def emit_unknown_field(state: LogScanState) -> list[Fact]:
return [
(
f"logfact:unknown-field:{field}",
(
"CONTROLLER_LOG_FACT: controller logged 'strict decoding error:"
f' unknown field "{field}"\' while loading '
"KueueConfiguration"
" (https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/, "
"https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta1/)."
),
)
for field in sorted(state.strict_unknown_fields)
]
def emit_unavailable_resource(state: LogScanState) -> list[Fact]:
return [
(
f"logfact:unavailable-resource:{res_name}",
(
f"CONTROLLER_LOG_FACT: controller reported 'resource {res_name}"
" unavailable in ClusterQueue' (the resource is requested by a"
" podset but is not covered by any resourceGroup of the"
" ClusterQueue)."
),
)
for res_name in sorted(state.unavailable_resources)
]
def emit_webhook_timeout(state: LogScanState) -> list[Fact]:
"""Webhook call failures with a logged timeout, connection-level cause, or other logged error."""
facts: list[Fact] = [
(
f"logfact:webhook-timeout:{wh_target}",
(
"CONTROLLER_LOG_FACT: logs record 'failed calling webhook"
f' "{wh_target}"\' with timeout / context deadline exceeded —'
" API server calls to the admission webhook endpoint did not"
" complete before the webhook timeout."
),
)
for wh_target in sorted(state.webhook_timeout_targets)
]
for wh_target, causes in sorted(state.webhook_connection_errors.items()):
if wh_target in state.webhook_timeout_targets:
continue
facts.append((
f"logfact:webhook-timeout:{wh_target}",
(
"CONTROLLER_LOG_FACT: logs record 'failed calling webhook"
f' "{wh_target}"\' with {" / ".join(sorted(causes))} — API server'
" calls to the admission webhook endpoint ended with a"
" connection-level error; no timeout is logged for them."
),
))
for wh_target, causes in sorted(state.webhook_other_errors.items()):
if (
wh_target in state.webhook_timeout_targets
or wh_target in state.webhook_connection_errors
):
continue
facts.append((
f"logfact:webhook-error:{wh_target}",
(
"CONTROLLER_LOG_FACT: logs record 'failed calling webhook"
f' "{wh_target}"\' with logged error:'
f" {'; '.join(sorted(causes)[:3])}."
),
))
return facts
def emit_api_pressure(state: LogScanState) -> list[Fact]:
return [
(
f"logfact:api-pressure:{sig_side}:{sig_name}",
(
f"CONTROLLER_LOG_FACT: logs record '{sig_name}' (source side:"
f" {sig_side} — {_API_PRESSURE_SIDE_NOTE[sig_side]})."
),
)
for sig_side, sig_name in sorted(state.api_pressure_signals)
]
def emit_in_cohort_preemption(state: LogScanState) -> list[Fact]:
if not state.in_cohort_preemptions:
return []
uniq_paths = sorted(set(state.in_cohort_preemptions))[:4]
return [(
"logfact:in-cohort-preemption-volume",
(
f"CONTROLLER_LOG_FACT: logs record {len(state.in_cohort_preemptions)}"
" InCohortFairSharing preemption entries (preemptor->preemptee"
f" paths={uniq_paths}). Each preemption updates the Workload status"
" and emits an Event"
" (https://kueue.sigs.k8s.io/docs/concepts/preemption/); Fair"
" Sharing preemption works with withinClusterQueue and"
" reclaimWithinCohort"
" (https://kueue.sigs.k8s.io/docs/concepts/preemption/)."
),
)]
def emit_client_throttling(state: LogScanState) -> list[Fact]:
if not state.client_throttling_count:
return []
return [(
"logfact:client-throttling-volume",
(
f"CONTROLLER_LOG_FACT: logs record {state.client_throttling_count}"
" 'Waited for ... due to client-side throttling, not priority and"
" fairness' delays. This message is emitted by client-go when a"
" request waits on Kueue's own rate limiter"
" (KueueConfiguration.clientConnection.qps/burst,"
" https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/,"
" https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta1/)."
),
)]
def emit_jobset_integration(state: LogScanState) -> list[Fact]:
frameworks = state.config_frameworks
if (
frameworks is None
or "jobset.x-k8s.io/jobset" in frameworks
or not state.empty_lq_workloads
):
return []
return [(
"logfact:jobset-integration-disabled",
(
"CONTROLLER_LOG_FACT: the 'Configuration loaded' payload lists"
f" integrations.frameworks={sorted(frameworks)} without"
" 'jobset.x-k8s.io/jobset', while child Jobs"
f" {sorted(state.empty_lq_workloads)} are reconciled by the batch/job"
" integration with an empty queue-name label (localQueue={'name':"
" ''}) and marked Inadmissible. The enabled set is"
" KueueConfiguration.integrations.frameworks"
" (https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/,"
" https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta1/)."
),
)]
_PODS_READY_REASON_NOTES = {
"WaitForStart": (
" For eviction metrics,"
" https://kueue.sigs.k8s.io/docs/reference/metrics/ defines"
' underlying_cause "WaitForStart" as: "the pods have not been ready'
' since admission, or the workload is not admitted".'
),
"WaitForScheduling": (
' Per "Unscheduled timeout" in'
" https://kueue.sigs.k8s.io/docs/tasks/manage/setup_wait_for_pods_ready/,"
' "Workloads waiting for scheduling report PodsReady=False with reason'
' WaitForScheduling."'
),
}
def emit_waiting_pods_ready(state: LogScanState) -> list[Fact]:
"""References whose latest logged PodsReady status is False, with the logged reason."""
stuck_waiting = sorted(
state.waiting_pods_ready_workloads - state.pods_ready_true_workloads
)
facts: list[Fact] = []
for wl_wait in stuck_waiting:
reason = state.pods_ready_false_reason.get(wl_wait, "")
reason_note = _PODS_READY_REASON_NOTES.get(reason, "")
facts.append((
f"logfact:waiting-pods-ready:{wl_wait}",
(
"CONTROLLER_LOG_FACT: the job reconciler logged 'Updating the"
" PodsReady condition' with status=False"
+ (f" (reason={reason})" if reason else "")
+ f" for '{wl_wait}' and no later status=True for the same"
" reference"
" (https://kueue.sigs.k8s.io/docs/tasks/manage/setup_wait_for_pods_ready/)."
+ reason_note
),
))
return facts
def _partition_quota_provenance(
details: list[tuple[str, str, str, str, str, bool]],
) -> tuple[
dict[str, tuple[str, str, str]],
dict[str, set[str]],
dict[str, tuple[str, str, str]],
]:
"""Splits audit quota entries into confirmed changes and unconfirmed bodies."""
confirmed_by_cq: dict[str, tuple[str, str, str]] = {}
principals_by_cq: dict[str, set[str]] = {}
unconfirmed_by_cq: dict[str, tuple[str, str, str]] = {}
for ts_p, cq_p, val_p, who_p, verb_p, confirmed in sorted(
details, key=lambda t: _ts_sort_key(t[0])
):
if confirmed:
confirmed_by_cq[cq_p] = (ts_p, val_p, verb_p)
principals_by_cq[cq_p] = {who_p or "<unknown principal>"}
unconfirmed_by_cq.pop(cq_p, None)
else:
unconfirmed_by_cq[cq_p] = (ts_p, val_p, verb_p)
return confirmed_by_cq, principals_by_cq, unconfirmed_by_cq
def _format_quota_provenance_lead(
confirmed_by_cq: dict[str, tuple[str, str, str]],
principals_by_cq: dict[str, set[str]],
unconfirmed_by_cq: dict[str, tuple[str, str, str]],
) -> str:
"""Formats the lead sentence separating confirmed updates from first-seen bodies."""
unconf_rows = [
f"{cq_p}: {verb} body carried nominalQuota={val}"
+ (f" at {ts_p}" if ts_p else "")
for cq_p, (ts_p, val, verb) in sorted(unconfirmed_by_cq.items())
]
if not confirmed_by_cq:
verbs = "/".join(
sorted({verb for _, _, verb in unconfirmed_by_cq.values()})
)
return (
f"AUDIT_LOG_FACT: audit log records clusterqueues.{verbs} request"
" bodies carrying nominalQuota while workloads emit Pending"
" ('insufficient unused quota'); no earlier body is in this log, so"
" whether nominalQuota changed is not determinable. Per ClusterQueue:"
f" {'; '.join(unconf_rows[:8])}. "
)
verbs = "/".join(sorted({verb for _, _, verb in confirmed_by_cq.values()}))
prov_rows = [
f"{cq_p}: latest"
+ (" confirmed" if cq_p in unconfirmed_by_cq else "")
+ f" nominalQuota {verb}={val}"
+ (f" at {ts_p}" if ts_p else "")
+ f" by {sorted(principals_by_cq[cq_p])}"
for cq_p, (ts_p, val, verb) in sorted(confirmed_by_cq.items())
]
lead = (
f"AUDIT_LOG_FACT: audit log records clusterqueues.{verbs} updates to"
" nominalQuota while workloads emit Pending ('insufficient unused"
f" quota'). Per ClusterQueue: {'; '.join(prov_rows[:8])}. "
)
if unconf_rows:
lead += (
"Other clusterqueues writes whose request body carried nominalQuota"
" without a comparable earlier body in this log (whether nominalQuota"
f" changed is not determinable): {'; '.join(unconf_rows[:8])}. "
)
return lead
def emit_quota_patch_provenance(state: LogScanState) -> list[Fact]:
"""Per-ClusterQueue provenance for confirmed nominalQuota changes and first-seen bodies."""
if not (
state.audit_cq_quota_patches and state.has_insufficient_quota_pending
):
return []
confirmed_by_cq, principals_by_cq, unconfirmed_by_cq = (
_partition_quota_provenance(state.audit_cq_quota_patch_detail)
)
lead = _format_quota_provenance_lead(
confirmed_by_cq, principals_by_cq, unconfirmed_by_cq
)
seen_cqs = set(confirmed_by_cq) | set(unconfirmed_by_cq)
admitted_without_audit = sorted(set(state.admitted_count_by_cq) - seen_cqs)
unpatched_note = ""
if admitted_without_audit:
unpatched_note = (
"ClusterQueues that admitted workloads in this log but have no"
f" nominalQuota write in the audit trail: {admitted_without_audit}. "
)
return [(
"logfact:audit-cq-quota-patch",
lead
+ unpatched_note
+ "Per https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/,"
" nominalQuota is the quantity of this resource that is available for a"
" ClusterQueue at a specific time; compare these values with"
" COHORT_RESOURCE_ARITHMETIC when a snapshot is available.",
)]
def emit_admission_volume(state: LogScanState) -> list[Fact]:
"""Summarises admitted resourceUsage volume per ClusterQueue and flavor."""
if not state.admitted_usage:
return []
by_cq: dict[str, list[str]] = {}
for (cq_a, fl_a, res_a), total_a in sorted(state.admitted_usage.items()):
by_cq.setdefault(cq_a, []).append(
f"{res_a}@{fl_a or '<no flavor>'}={report_output.fmt_quantity(total_a, res_a)}"
)
rows = [
f"{cq_a}(admissions={state.admitted_count_by_cq.get(cq_a, 0)}):"
f" {', '.join(parts)}"
for cq_a, parts in sorted(by_cq.items())
]
return [(
"logfact:admission-volume",
(
"ADMISSION_VOLUME_BY_CLUSTERQUEUE: summed resourceUsage from"
" 'Workload successfully admitted and assigned flavors'"
" (https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/) over this"
f" log window, per ClusterQueue and flavor: {'; '.join(rows[:10])}."
" This is admitted volume over time, not current reservation; it"
" shows which ClusterQueues consumed each flavor's quota."
),
)]
def emit_signatures(state: LogScanState) -> list[Fact]:
"""One fact per matched controller-message signature (mechanism_hint + next_check + citation)."""
return log_signatures.emit_signature_facts(state.signature_hits)
def emit_indexed_jobs(state: LogScanState) -> list[Fact]:
if not state.audit_indexed_jobs_no_max_failed:
return []
return [(
"logfact:audit-indexed-job-backoff",
(
"AUDIT_LOG_FACT: audit log records creation of Indexed Job(s)"
f" {state.audit_indexed_jobs_no_max_failed[:2]} with"
" backoffLimitPerIndex set and no maxFailedIndexes "
"(Kubernetes defaults spec.backoffLimit=2147483647 when"
" backoffLimitPerIndex is set). Under batch/v1 semantics a failed"
" index that has exhausted "
"backoffLimitPerIndex is not retried while remaining indexes keep"
" running, so the Job stays active "
"(https://kubernetes.io/docs/concepts/workloads/controllers/job/,"
" https://kueue.sigs.k8s.io/docs/tasks/manage/setup_wait_for_pods_ready/)."
),
)]
FactEmitter = Callable[[LogScanState], list[Fact]]
# Produces `derived_log_facts`, in this order (LOG_COVERAGE always first).
LOG_FACT_EMITTERS: tuple[FactEmitter, ...] = (
emit_log_coverage,
emit_tas_level,
emit_namespace_delete,
emit_unknown_field,
emit_unavailable_resource,
emit_webhook_timeout,
emit_api_pressure,
emit_in_cohort_preemption,
emit_client_throttling,
emit_jobset_integration,
emit_waiting_pods_ready,
emit_quota_patch_provenance,
emit_admission_volume,
emit_indexed_jobs,
emit_signatures,
)
# ---------------------------------------------------------------------------
# Driver
# ---------------------------------------------------------------------------
def scan_lines(lines: list[str]) -> LogScanState:
"""Runs the text scanner on every line and the record scanners on every parsed JSON object."""
state = LogScanState()
for raw in lines:
raw_str = raw.strip()
if raw_str:
state.source_counts["total"] += 1
if not raw_str.startswith("{"):
state.source_counts["unstructured"] += 1
scan_text_signals(raw_str, state)
if not raw_str.startswith("{"):
if raw_str:
log_signatures.scan_signature_text(raw_str, state.signature_hits)
continue
try:
d = json.loads(raw_str)
except (json.JSONDecodeError, RecursionError):
state.source_counts["unstructured"] += 1
continue
if not isinstance(d, dict):
continue
rec = LogRecord.from_dict(d)
for scanner in RECORD_SCANNERS:
scanner(rec, state)
_resolve_quota_events(state)
return state
def _finalize_sections(state: LogScanState) -> None:
"""Appends workload status patches and truncation trailers to capped sections."""
status_cap = _MAX_AUDIT_ACTIONS_WITH_STATUS + state.audit_delete_count
for wl_stat in state.workload_status_by_name.values():
if (
wl_stat[:220] not in state.seen_audit
and len(state.audit_actions) < status_cap
):
state.audit_actions.append((None, wl_stat[:850]))
# Untagged trailer lines so the reader knows the lists are capped (they
# survive `tag_log_facts`, which rebuilds the sections from these tuples).
if state.omitted_events:
state.key_events.append((
"",
(
f"... {state.omitted_events} more distinct error/Warning entries"
f" omitted (first {_MAX_KEY_EVENTS} kept); the complete timeline is"
" in full_report_file"
),
))
if state.omitted_audit:
state.audit_actions.append((
None,
(
f"... {state.omitted_audit} more distinct non-delete audit entries"
f" omitted (first {_MAX_AUDIT_ACTIONS} kept); the complete timeline"
" is in full_report_file"
),
))
if state.omitted_audit_deletions:
state.audit_actions.append((
None,
(
f"... {state.omitted_audit_deletions} more distinct audit deletion"
f" entries omitted (first {_MAX_AUDIT_DELETIONS} kept); the"
" complete timeline is in full_report_file"
),
))
def extract_derived_log_diagnostics(
lines: list[str], version_info: dict[str, Any] | None = None
) -> dict[str, Any]:
"""Extracts structured entity inventory, key diagnostic signals, and source invariants from log lines."""
state = scan_lines(lines)
_finalize_sections(state)
log_facts: list[Fact] = []
for emitter in LOG_FACT_EMITTERS:
log_facts.extend(emitter(state))
# Most decision-relevant sections first: agent harnesses often show only the
# head (and tail) of a command's stdout.
diag: dict[str, Any] = {
"derived_log_facts": [t for _, t in log_facts],
"key_errors_and_events": [t for _, t in state.key_events],
"discovered_entities": {
"workloads": sorted(state.workloads),
"cluster_queues": sorted(state.cluster_queues),
"local_queues": sorted(state.local_queues),
"resource_flavors": sorted(state.resource_flavors),
"namespaces": sorted(state.namespaces),
"nodes": sorted(state.nodes),
},
}
if state.config_excerpt:
diag["controller_config_excerpt"] = state.config_excerpt
if state.audit_actions:
diag["audit_resource_actions"] = [t for _, t in state.audit_actions]
diag["active_api_schema_reference"] = (
kueue_schema.get_active_schema_reference(
state.discovered_kinds, version_info=version_info
)
)
# Side channel for fact ids (consumed and removed by `tag_log_facts`).
diag["_keyed"] = {
"derived_log_facts": log_facts,
"key_errors_and_events": state.key_events,
"audit_resource_actions": state.audit_actions,
}
return diag
log_signatures.py 15.1 KB
"""Controller-message signatures: which Kueue code path emits a message and what it states.
A signature maps a literal that the Kueue controller (or a Kueue Event) emits to
the source file that emits it, the mechanism it reports, the documentation page
that describes that mechanism, and the next read-only check. Scanning counts
matches per signature and keeps the first few distinct message variants. The
emitter turns each hit into one ``CONTROLLER_LOG_FACT`` whose ``mechanism_hint``
describes the mechanism, not the incident: whether the mechanism explains the
incident is
for the reader to decide from the rest of the evidence.
Every ``source`` literal is verified against the pinned Kueue release by the
unit tests (``KUEUE_LOG_LITERALS``) when
``GKE_KUEUE_TROUBLESHOOTING_TEST_KUEUE_SOURCE`` is set. Every signature links to
an official public upstream documentation page on
``https://kueue.sigs.k8s.io/docs/``.
"""
from __future__ import annotations
import dataclasses
import re
_DOCS = "https://kueue.sigs.k8s.io/docs"
_MAX_VARIANTS = 3
@dataclasses.dataclass(frozen=True)
class LogSignature:
"""Controller log or Event message pattern and its documented mechanism."""
key: str
pattern: re.Pattern[str]
# Kueue source path (verified at kueue_schema.KUEUE_SOURCE_REF by unit tests).
source: str
symbol: str # function / constant emitting the literal
mechanism: str # what the message states, in the documentation's own terms
next_check: str # the one read-only check that discriminates the cause
doc: str = "" # official upstream documentation page
doc_section: str = "" # exact section title on `doc` (no #anchors)
src_only: bool = False
@dataclasses.dataclass
class SignatureHits:
count: int = 0
first_ts: str = ""
last_ts: str = ""
variants: list[str] = dataclasses.field(default_factory=list)
SIGNATURES: tuple[LogSignature, ...] = (
LogSignature(
key="flavor-assignment-per-podset",
pattern=re.compile(
r"couldn't assign flavors to pod set"
r" \"?(?P<podset>[A-Za-z0-9_.-]+)\"?:?"
),
source="pkg/scheduler/flavorassigner/flavorassigner.go",
symbol="Assignment.Message",
mechanism=(
"flavor assignment failed for the named pod set; Kueue assigns"
" flavors per pod set (or podSetGroupName group), and within one"
" pod set all resources covered by the same resourceGroup receive"
" the same flavor; all pod sets must be assigned flavors for the"
" Workload to reserve quota"
),
next_check=(
"compare each pod set's nodeSelector / topology annotations and"
" resource requests with ResourceFlavor.spec.nodeLabels and"
" topologyName of every flavor in the ClusterQueue's resourceGroups"
),
doc=f"{_DOCS}/concepts/cluster_queue/",
doc_section="Resource Groups",
),
LogSignature(
key="quota-exceeds-maximum-capacity",
pattern=re.compile(
r"insufficient quota for (?P<resource>[a-z0-9._/-]+) in flavor"
r" (?P<flavor>[A-Za-z0-9_.-]+),.*?maximum capacity"
),
source="pkg/scheduler/flavorassigner/flavorassigner.go",
symbol="fitsResourceQuota",
mechanism=(
"the request exceeds the flavor's maximum capacity (nominalQuota"
" plus what the cohort can lend within borrowingLimit)"
),
next_check=(
"sum the pod sets' requests × count for that resource and compare"
" with nominalQuota + borrowable cohort quota for the flavor"
),
doc=f"{_DOCS}/concepts/cluster_queue/",
doc_section="Flavors and borrowing semantics",
),
LogSignature(
key="quota-temporarily-unavailable",
pattern=re.compile(
r"insufficient unused quota for (?P<resource>[a-z0-9._/-]+) in"
r" flavor (?P<flavor>[A-Za-z0-9_.-]+), (?P<more>[0-9.A-Za-z]+) more"
r" needed"
),
source="pkg/scheduler/flavorassigner/flavorassigner.go",
symbol="fitsResourceQuota",
mechanism=(
"the request fits the flavor's capacity but currently admitted"
" workloads hold the quota; admission waits for usage to drop or"
" for preemption"
),
next_check=(
"list admitted workloads in the ClusterQueue and its cohort for"
" that flavor and check the preemption policy that would reclaim"
" quota"
),
doc=f"{_DOCS}/concepts/cluster_queue/",
doc_section="Flavors and borrowing semantics",
),
LogSignature(
key="tas-no-fit",
pattern=re.compile(
r"topology \"?(?P<topology>[A-Za-z0-9_.-]+)\"? doesn't allow to fit"
r" any of (?P<total>\d+) (?P<unit>pod|slice)"
),
source="pkg/cache/scheduler/tas_flavor_snapshot.go",
symbol="FindTopologyAssignmentsForFlavor",
mechanism=(
"the topology-aware snapshot for the flavor has no domain able to"
" host even one pod/slice: either no node matches the flavor's"
" nodeLabels together with every Topology level label, or every"
" matching node lacks free capacity for one pod"
),
next_check=(
"count nodes carrying the ResourceFlavor nodeLabels and all"
" Topology.spec.levels keys, then their allocatable minus usage per"
" node"
),
doc=f"{_DOCS}/concepts/topology_aware_scheduling/",
),
LogSignature(
key="tas-partial-fit",
pattern=re.compile(
r"topology \"?(?P<topology>[A-Za-z0-9_.-]+)\"? allows to fit only"
r" (?P<fit>\d+) out of (?P<total>\d+) (?P<unit>pod|slice)"
),
source="pkg/cache/scheduler/tas_flavor_snapshot.go",
symbol="FindTopologyAssignmentsForFlavor",
mechanism=(
"no single domain at the requested topology level has room for the"
" whole pod set; capacity exists but is spread across domains (for"
" example nodes split across zones or hosts)"
),
next_check=(
"group matching nodes by the requested level's label and compute"
" per-domain free capacity against the pod set's count"
),
doc=f"{_DOCS}/concepts/topology_aware_scheduling/",
),
LogSignature(
key="preemption-no-candidates",
pattern=re.compile(
r"Workload requires preemption, but there are no candidate"
r" workloads allowed for preemption"
),
source="pkg/scheduler/scheduler.go",
symbol="schedule",
mechanism=(
"the Workload could fit only by preempting, but the ClusterQueue's"
" preemption policy (withinClusterQueue / reclaimWithinCohort /"
" borrowWithinCohort, fair-sharing strategies) admits no victim"
),
next_check=(
"read spec.preemption of the ClusterQueue and the fairSharing"
" configuration, and compare priorities and borrowing state of the"
" admitted workloads in the cohort"
),
doc=f"{_DOCS}/concepts/preemption/",
),
LogSignature(
key="preempted-with-reason",
pattern=re.compile(
r"Preempted to accommodate a workload \(UID: [^)]*\) due to"
r" (?P<reason>[^;]+)"
),
source="pkg/scheduler/preemption/preemption.go",
symbol="preemptionMessage",
mechanism=(
"the Workload was evicted by Kueue's preemptor with the stated"
" reason (prioritization in the ClusterQueue, reclamation within"
" the cohort, Fair Sharing within the cohort); the preemptor path"
" names the ClusterQueue that triggered it"
),
next_check=(
"map preemptor and preemptee ClusterQueues to their spec.preemption"
" and nominalQuota/borrowing state at that time"
),
doc=f"{_DOCS}/concepts/preemption/",
),
LogSignature(
key="pods-ready-timeout-eviction",
pattern=re.compile(r"Exceeded the PodsReady timeout"),
source="pkg/controller/core/workload_controller.go",
symbol="reconcileNotReadyTimeout",
mechanism=(
"the Workload was evicted when not all of its pods were Ready"
" within waitForPodsReady.timeout after admission; it is requeued"
" according to requeuingStrategy"
),
next_check=(
"compare the pods' scheduling/image-pull/startup duration with"
" waitForPodsReady.timeout in the KueueConfiguration ConfigMap"
),
doc=f"{_DOCS}/tasks/manage/setup_wait_for_pods_ready/",
),
LogSignature(
key="requeuing-limit-exceeded",
pattern=re.compile(
r"exceeding the maximum number of re-queuing retries"
),
source="pkg/controller/core/workload_controller.go",
symbol="reconcileNotReadyTimeout",
mechanism=(
"the Workload was deactivated (spec.active=false) after"
" waitForPodsReady.requeuingStrategy.backoffLimitCount requeues; it"
" stays out of the queue until reactivated"
),
next_check=(
"read status.requeueState.count and"
" requeuingStrategy.backoffLimitCount, then what delayed the pods"
" at each earlier PodsReady timeout"
),
doc=f"{_DOCS}/tasks/manage/setup_wait_for_pods_ready/",
),
LogSignature(
key="retention-delete-finished",
pattern=re.compile(
r"the retention period has elapsed|Deleted finished workload due to"
r" elapsed retention"
),
source="pkg/controller/core/workload_controller.go",
symbol="Reconcile",
mechanism=(
"the finished Workload object was deleted by Kueue's"
" objectRetentionPolicies.workloads.afterFinished"
),
next_check=(
"read objectRetentionPolicies in the KueueConfiguration ConfigMap"
" and the Job's own ttlSecondsAfterFinished"
),
doc=f"{_DOCS}/tasks/manage/setup_object_retention_policy/",
),
LogSignature(
key="tas-level-not-in-topology",
pattern=re.compile(
r"Flavor \\?\"(?P<flavor>[A-Za-z0-9_.-]+)\\?\" does not contain the"
r" requested level"
),
source="pkg/scheduler/flavorassigner/tas_flavorassigner.go",
symbol="checkPodSetAndFlavorMatchForTAS",
mechanism=(
"the pod set requests a topology level"
" (podset-required/preferred-topology annotation) that the Topology"
" referenced by this flavor's topologyName does not define in"
" spec.levels; the flavor is rejected for that pod set before any"
" node is considered"
),
next_check=(
"compare the pod set's topology annotation value with"
" Topology.spec.levels of the flavor's topologyName"
),
doc=f"{_DOCS}/concepts/topology_aware_scheduling/",
),
LogSignature(
key="tas-flavor-requires-tas-podset",
pattern=re.compile(
r"Flavor \\?\"(?P<flavor>[A-Za-z0-9_.-]+)\\?\" supports only"
r" TopologyAwareScheduling"
),
source="pkg/scheduler/flavorassigner/tas_flavorassigner.go",
symbol="checkPodSetAndFlavorMatchForTAS",
mechanism=(
"the flavor has a topologyName and the ClusterQueue mixes TAS and"
" non-TAS flavors (so TAS is not implied), so a pod set without a"
" topology request cannot use this flavor for any resource covered"
" by that resourceGroup"
),
next_check=(
"list which pod sets carry a kueue.x-k8s.io/podset-*-topology"
" annotation and which resourceGroups cover the pod set's requested"
" resources on TAS vs non-TAS flavors"
),
doc=f"{_DOCS}/concepts/topology_aware_scheduling/",
),
LogSignature(
key="flavors-considered-nofit",
pattern=re.compile(
r"Flavors considered: (?P<detail>[^;\"]*NoFit[^\"]{0,200})"
),
source="pkg/scheduler/scheduler.go",
symbol="quotaReservedEventMessage",
mechanism=(
"a ClusterQueue defines the quotas for the flavors of resources"
" that it manages, with rules for how the different flavors can be"
" tried as alternatives"
),
next_check=(
"compare each listed flavor against the flavor's nodeLabels,"
" topologyName and quota in the ClusterQueue"
),
doc=f"{_DOCS}/concepts/cluster_queue/",
),
LogSignature(
key="controller-start",
pattern=re.compile(
r"\"msg\":\s*\"(?:Configuration loaded|Successfully loaded"
r" configuration)\"|\b(?:Configuration loaded|Successfully loaded"
r" configuration)\b"
),
source="cmd/kueue/main.go",
symbol="main",
mechanism=(
"the controller manager started (or restarted) and loaded its"
" configuration at these times; the count and timestamps allow"
" other events to be placed before or after a restart"
),
next_check=(
"place ConfigMap updates, AdmissionCheck / ProvisioningRequest"
" state changes and the first admission decisions on the same"
" timeline as these start times"
),
doc=f"{_DOCS}/getting-started/installation/",
src_only=False,
),
)
def scan_signature_text(
text: str, hits: dict[str, SignatureHits], ts: str = ""
) -> None:
"""Records every signature that matches `text` (one raw line or message)."""
for sig in SIGNATURES:
m = sig.pattern.search(text)
if not m:
continue
h = hits.setdefault(sig.key, SignatureHits())
h.count += 1
if ts:
h.first_ts = min(h.first_ts, ts) if h.first_ts else ts
h.last_ts = max(h.last_ts, ts) if h.last_ts else ts
variant = m.group(0)[:160]
if variant not in h.variants and len(h.variants) < _MAX_VARIANTS:
h.variants.append(variant)
def _citation(sig: LogSignature) -> str:
if not sig.doc:
return f"doc: {_DOCS}/concepts/"
if sig.doc_section:
return f'doc: {sig.doc} (section "{sig.doc_section}")'
return f"doc: {sig.doc}"
def emit_signature_facts(
hits: dict[str, SignatureHits],
) -> list[tuple[str | None, str]]:
"""One fact per matched signature: count, window, message variants, mechanism, next check, citation."""
facts: list[tuple[str | None, str]] = []
for sig in SIGNATURES:
h = hits.get(sig.key)
if not h:
continue
window = (
f" between {h.first_ts} and {h.last_ts}"
if h.first_ts and h.last_ts and h.first_ts != h.last_ts
else (f" at {h.first_ts}" if h.first_ts else "")
)
facts.append((
f"logfact:signature:{sig.key}",
f"CONTROLLER_LOG_FACT: {h.count} line(s){window} match"
f" '{h.variants[0]}'"
+ (f" (also: {h.variants[1:]})" if len(h.variants) > 1 else "")
+ f". mechanism_hint: {sig.mechanism}. next_check: {sig.next_check}."
f" ({_citation(sig)})",
))
return facts
log_timeline.py 6.4 KB
"""Milestone timeline compression for the `gke-kueue-troubleshooting` skill.
Compresses raw log lines into runs of repeated milestone messages (admission,
eviction, preemption, requeue, configuration loading, ...) with repetition
counts, keeps a capped list of verbatim high-priority excerpts and attaches
the derived diagnostics produced by `log_facts`.
"""
from __future__ import annotations
import json
import re
from typing import Any
import log_facts
MILESTONE_RE = re.compile(
r"admit|admission|evict|preempt|quota|requeue|re-queued|finish"
r"|succeed|fail|delete|pending|inadmissible|stopped|strict decoding error"
r"|unknown field|backoffBaseSeconds|ProvisioningRequest"
r"|PodsReadyTimeout|EvictedDueToAdmissionCheck|AdmissionCheckUpdated|UpdatedAdmissionCheck|bad"
r" parameters reference"
r"|Updating the PodsReady condition|exceeding the PodsReady timeout"
r"|localQueue doesn't exist|clusterQueue doesn't exist|no topology domains"
r"|unavailable in ClusterQueue|taint|Insufficient|Configuration loaded"
r"|BookingExpired"
r"|context deadline exceeded|client-side throttling|rate limiter|leader"
r" election|too many requests|unable to handle the request"
r"|Initializing|gitVersion|Audit",
re.IGNORECASE,
)
HIGH_PRIORITY_RE = re.compile(
r"strict decoding error|unknown field|backoffBaseSeconds"
r"|ProvisioningRequest.{0,400}(?:not"
r" found|retry|fail|exhausted|expired|reached|not ready)"
r"|EvictedDueToAdmissionCheck|AdmissionCheckUpdated|UpdatedAdmissionCheck"
r"|inadmissible|StrictFIFO"
r"|insufficient.{0,400}quota|couldn't assign flavors"
r"|localQueue doesn't exist"
r"|PodsReadyTimeout|EvictedDueToPodsReadyTimeout"
r"|FailedScheduling|Insufficient cpu|no topology"
r" domains|TopologyAwareScheduling"
r"|BookingExpired"
r"|context deadline exceeded|client-side throttling|rate limiter|leader"
r" election|too many requests|unable to handle the request"
r"|unavailable in ClusterQueue|taint|\[Audit (?:create|delete|patch|update)"
r" (?:jobs|jobsets|namespaces|resourceflavors|clusterqueues|localqueues|configmaps)\]",
re.IGNORECASE,
)
_TIMESTAMP_RE = re.compile(
r"\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z?\b"
)
_MAX_HIGH_PRIORITY_EXCERPTS = 30
_PATTERN_WIDTH = 180
_LINE_WIDTH = 320
_HEAD_RUNS = 25
def _obj_name(value: Any) -> str:
"""Name from a logged object ref: {name, namespace} (klog ObjectRef) or a plain "ns/name" string."""
if isinstance(value, dict):
return str(value.get("name") or "")
if isinstance(value, str):
return value.rsplit("/", 1)[-1]
return ""
def _first_truthy(
parsed: dict[str, Any], keys: tuple[str, ...], default: Any = ""
) -> Any:
"""The first truthy `parsed[key]` in `keys`, else `default`."""
for key in keys:
if parsed.get(key):
return parsed[key]
return default
def _milestone_message(msg: str) -> str:
"""Formats a JSON log record into a pipe-delimited milestone summary."""
if not msg.startswith("{"):
return msg
try:
parsed = json.loads(msg)
except (json.JSONDecodeError, RecursionError):
return msg
ts = _first_truthy(parsed, ("timestamp", "time", "ts"))
body = _first_truthy(parsed, ("message", "msg", "textPayload"), default=msg)
note = parsed.get("note") or ""
err = parsed.get("error") or ""
reason = parsed.get("reason") or ""
wl = (
parsed.get("workload")
or _obj_name(parsed.get("object"))
or _obj_name(parsed.get("involvedObject"))
or ""
)
if isinstance(wl, dict):
wl = wl.get("name", "")
wl_str = f" | workload={wl}" if wl else ""
reason_str = f" | reason={reason}" if reason else ""
note_str = f" | note={note}" if (note and str(note) not in str(body)) else ""
err_str = f" | error={err}" if err else ""
return f"{ts} | {body}{reason_str}{wl_str}{note_str}{err_str}"
def _collect_milestones(
lines: list[str],
) -> tuple[list[dict[str, Any]], dict[str, int], list[str]]:
"""Returns `(runs, pattern totals, high-priority excerpts)` over the milestone lines."""
milestones: list[dict[str, Any]] = []
totals: dict[str, int] = {}
high_priority_excerpts: list[str] = []
seen_hp: set[str] = set()
for raw in lines:
if not MILESTONE_RE.search(raw):
continue
if HIGH_PRIORITY_RE.search(raw):
short_raw = raw.strip()[:400]
if (
short_raw not in seen_hp
and len(high_priority_excerpts) < _MAX_HIGH_PRIORITY_EXCERPTS
):
seen_hp.add(short_raw)
high_priority_excerpts.append(short_raw)
msg = _milestone_message(raw.strip())
pattern = _TIMESTAMP_RE.sub("<TS>", msg)[:_PATTERN_WIDTH]
totals[pattern] = totals.get(pattern, 0) + 1
if milestones and milestones[-1]["pattern"] == pattern:
milestones[-1]["count"] += 1
milestones[-1]["last_line"] = msg[:_LINE_WIDTH]
else:
milestones.append(
{"pattern": pattern, "count": 1, "first_line": msg[:_LINE_WIDTH]}
)
return milestones, totals, high_priority_excerpts
def _truncate_runs(
milestones: list[dict[str, Any]], max_runs: int
) -> list[dict[str, Any]]:
"""Keeps the first 25 and the last `max_runs - 25` runs with a `truncated_runs` marker between."""
if len(milestones) <= max_runs:
return milestones
head = milestones[:_HEAD_RUNS]
tail = milestones[-(max_runs - _HEAD_RUNS) :]
return head + [{"truncated_runs": len(milestones) - max_runs}] + tail
def compress_timeline(
lines: list[str],
max_runs: int = 120,
version_info: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Compresses raw log lines into milestone runs with repetition counts and key excerpts."""
milestones, totals, high_priority_excerpts = _collect_milestones(lines)
diag = log_facts.extract_derived_log_diagnostics(
lines, version_info=version_info
)
schema_ref = diag.get("active_api_schema_reference") or {}
result: dict[str, Any] = {
"detected_kueue_version": schema_ref.get("_detected_kueue_version")
}
if schema_ref.get("_schema_notice"):
result["schema_notice"] = schema_ref["_schema_notice"]
result |= {
"total_scanned_lines": len(lines),
"distinct_milestone_patterns": len(totals),
"derived_log_diagnostics": diag,
"high_priority_verbatim_log_excerpts": high_priority_excerpts,
"top_milestone_counts": dict(
sorted(totals.items(), key=lambda kv: kv[1], reverse=True)[:20]
),
"compressed_timeline": _truncate_runs(milestones, max_runs),
}
return result
report_checks.py 59.9 KB
#!/usr/bin/env python3
"""Structural gates of the diagnostic-report validator (`validate_report.py`).
Every gate is `(ctx: DraftContext) -> dict[str, list]` and owns exactly one key
of the validator's JSON report; `run_report_gates(ctx)` applies `REPORT_GATES`
in
order and merges the results. Gates never judge whether a conclusion is right,
only whether the report is complete, traceable and executable:
check_headers -> missing_headers
check_graph_coverage -> uninspected_graph_objects
check_evidence_grounding -> fabricated_quotes
check_fact_coverage -> unaddressed_facts
check_remediation_mapping -> remediation_gaps
check_open_questions -> open_question_gaps
check_ruled_out_reasons -> weak_ruled_out
check_config_remediation -> config_remediation_errors
check_kubectl_resources -> unknown_kubectl_resources
check_schema_warnings -> schema_warnings
Sections are found by one parser (`kueue_schema_yaml_checks.split_sections`):
a `####` title is matched after normalisation, so `#### Root Causes:` is the
`root cause` section for every gate, and `#####` sub-headers stay inside their
section. All patterns that scan `kubectl` commands are linear in the input
length: flags are consumed by a bounded, unambiguous loop.
"""
from __future__ import annotations
import bisect
import dataclasses
import os
import re
from typing import Any, Callable
import kueue_schema_yaml_checks as yaml_checks
import report_output
REQUIRED_HEADERS = (
"### Diagnostic Summary",
"#### Scope",
"#### Observations",
"#### Root Cause",
"#### Ruled Out",
"#### Remediation",
)
_RC_RE = re.compile(r"\bRC(\d{1,2})\b")
# An entry header at the start of a line: optional bullet / number / `#####`,
# optional bold or bracket, then the id. The bullet and its trailing blanks
# are one optional group, so no two adjacent quantifiers compete for the same
# blanks.
_ENTRY_PREFIX = r"(?m)^[ \t]*(?:(?:[-*+]|\d{1,3}\.|#{1,6})[ \t]*)?\*{0,2}\[?"
_RC_START_RE = re.compile(_ENTRY_PREFIX + r"RC(\d{1,2})\b")
# Open Questions: explicit "not determinable from this evidence" entries.
_OQ_RE = re.compile(r"\bOQ(\d{1,2})\b")
_OQ_START_RE = re.compile(_ENTRY_PREFIX + r"OQ(\d{1,2})\b")
# A further id listed right after an entry's first id (`RC1 & RC2:`,
# `RC1, RC2:`, `RC1 and RC2`): the entry belongs to each of them. The blanks
# are bounded so the pattern stays linear even when it is not anchored.
_ID_LIST_NEXT_RE = re.compile(
r"\]?\*{0,2}[ \t]{0,4}(?:,|&|/|\+|and\b)[ \t]{0,4}\*{0,2}\[?"
r"(RC|OQ)(\d{1,2})\b"
)
# A part label of an Open Question, at the start of a line (optionally
# bulleted / bold) or inline after a non-word character. A part's body runs
# from its label to the next label or the end of the OQ, so alternatives
# written on their own lines still belong to `Candidates:`, and `Collect:`
# ends where a conditional remediation starts. The two lookaheads name the
# characters a match can start with, so most positions are rejected by one
# test.
_OQ_PART_RE = re.compile(
r"(?im)(?=[ \t*+bcdfr-])"
r"(?:^[ \t]*(?:[-*+][ \t]*)?|(?<![\w*-])(?=[*bcdfr]))\*{0,2}"
r"(basis|candidates|discriminator|collect"
r"|(?:conditional[ \t]+)?(?:remediation|fix))"
r"\*{0,2}[ \t]*:[ \t]*"
)
# A shell line continuation; joined before any command is scanned.
_CONTINUATION_RE = re.compile(r"\\[ \t]*\r?\n[ \t]*")
# --- kubectl command patterns -------------------------------------------------
# Tokens are separated by blanks on one line (continuations are joined first).
# `_FLAGS` consumes the flags between `kubectl`, the verb and the resource:
# a flag from `_VALUE_FLAG` takes the next token as its value, any other
# `-x` / `--x[=v]` token stands alone. The two alternatives exclude each other,
# a value is never the next `kubectl`, and the loop is bounded, so matching is
# linear and `-n workloads` or `-f workload.yaml` is never read as a resource.
_KUBECTL = r"(?<![\w.-])kubectl[ \t]+(?=\S)"
_VALUE_FLAG = (
r"(?:-[cfklnos]|--(?:as|as-group|cluster|container|context|field-manager"
r"|field-selector|filename|kubeconfig|kustomize|namespace|output"
r"|patch-file|replicas|request-timeout|selector|server|subresource"
r"|timeout|token|type|user))"
)
_FLAGS = (
rf"(?:(?:{_VALUE_FLAG}[ \t]+(?!kubectl\b)[^\s`]+"
rf"|(?!{_VALUE_FLAG}[ \t])-[^\s`]+)[ \t]+){{0,8}}"
)
# Verbs that write to the API server or run code in the cluster.
_KUBECTL_WRITE_RE = re.compile(
_KUBECTL
+ _FLAGS
+ r"(?:patch|edit|apply|replace|delete|create|annotate|label|scale"
r"|autoscale|drain|cordon|uncordon|taint|set|exec|cp|run|debug|expose"
r"|rollout[ \t]+(?:restart|undo|pause|resume)"
r"|kueue[ \t]+(?:stop|resume|create|delete)"
r"|certificate[ \t]+(?:approve|deny))(?![\w-])",
re.IGNORECASE,
)
# Non-kubectl CLI mutation rules used by `check_open_questions` (`Collect:`).
# Token-based (single-pass linear lexer) so quoted filter strings never false-
# positive and arbitrary flags/values (including `@`, quotes, combined short
# flags) are handled without regex backtracking.
_GCLOUD_READ_VERBS = frozenset({
"read",
"list",
"describe",
"get",
"show",
"info",
"version",
"help",
"tail",
"ls",
"cat",
"stat",
"du",
"hash",
"search",
"inspect",
"lookup",
"diagnose",
"validate",
"wait",
"wait-until",
"query",
"stream-logs",
"test-iam-permissions",
})
_GCLOUD_READ_PREFIXES = (
"get-",
"print-",
"list-",
"describe-",
"show-",
"read-",
"view-",
"lookup-",
"tail-",
"search-",
"check-",
"wait-",
"query-",
"analyze-",
"troubleshoot-",
)
_GCLOUD_WRITE_VERBS = frozenset({
"acknowledge",
"activate",
"add",
"advance",
"apply",
"approve",
"archive",
"assign",
"attach",
"authorize",
"abandon",
"abort",
"bind",
"bootstrap",
"call",
"cancel",
"cleanup",
"clear",
"clone",
"commit",
"copy",
"cordon",
"create",
"delete",
"deny",
"deploy",
"deprecate",
"destroy",
"detach",
"disable",
"drain",
"edit",
"enable",
"enroll",
"evict",
"execute",
"failover",
"flush",
"grant",
"import",
"init",
"insert",
"install",
"invoke",
"kill",
"lock",
"login",
"migrate",
"modify",
"move",
"mv",
"patch",
"pause",
"perform-maintenance",
"promote",
"provision",
"prune",
"publish",
"purge",
"push",
"rebalance",
"reboot",
"recreate",
"register",
"reimage",
"reinstall",
"reject",
"remove",
"rename",
"repair",
"replace",
"reset",
"resize",
"restart",
"restore",
"resume",
"revoke",
"rm",
"rollback",
"rotate",
"scale",
"scp",
"seal",
"seek",
"send",
"set",
"setup",
"simulate-maintenance-event",
"snapshot",
"ssh",
"start",
"stop",
"submit",
"subscribe",
"suspend",
"switchover",
"sync",
"taint",
"teardown",
"terminate",
"trigger",
"unarchive",
"unassign",
"unbind",
"uncordon",
"undelete",
"undeploy",
"unenroll",
"uninstall",
"unlock",
"unregister",
"unseal",
"unset",
"unsubscribe",
"untag",
"update",
"upgrade",
"upload",
"wipe",
"write",
})
_GCLOUD_WRITE_PREFIXES = tuple(
f"{v}-"
for v in sorted(
_GCLOUD_WRITE_VERBS
| {"complete", "expand", "force", "mark", "perform", "simulate"}
)
)
# Resource command groups whose names start with a write prefix (`resize-`,
# `patch-`, `restore-`, `snapshot-`, etc.) but support read-only subcommands
# like `list` / `describe`. Their subcommand (next positional token) decides
# mutability.
_GCLOUD_GROUP_NAMES = frozenset({
"deploy-policies",
"import-jobs",
"patch-deployments",
"patch-jobs",
"resize-requests",
"restore-channels",
"restore-plan-bindings",
"restore-plans",
"restore-template-executions",
"restore-templates",
"restore-verification-plan-associations",
"restore-verification-plans",
"snapshot-groups",
"snapshot-recycle-bin-policy",
"snapshot-schedule-policies",
"snapshot-settings",
"ssh-keys",
})
_SHELL_BINS = frozenset({"sh", "bash", "zsh", "dash", "ksh"})
_SIMPLE_WRAPPERS = frozenset({
"nohup",
"time",
"exec",
"command",
"if",
"while",
"until",
"do",
"then",
"else",
"elif",
"{",
"!",
})
_SIMPLE_WRAPPER_VALUE_FLAGS = frozenset({"-a"})
_STDBUF_VALUE_FLAGS = frozenset(
{"-i", "-o", "-e", "--input", "--output", "--error"}
)
_SSH_VALUE_FLAGS = frozenset({
"-b",
"-c",
"-D",
"-E",
"-e",
"-F",
"-I",
"-i",
"-J",
"-L",
"-l",
"-m",
"-O",
"-o",
"-p",
"-Q",
"-R",
"-S",
"-W",
"-w",
})
_GCLOUD_STORAGE_VALUE_FLAGS = frozenset({
"--content-type",
"--cache-control",
"--content-disposition",
"--content-encoding",
"--content-language",
"--custom-time",
"--storage-class",
"--predefined-acl",
"--canned-acl",
"--encryption-key",
"--decryption-keys",
"--gzip-in-flight",
"--gzip-local",
"--exclude",
"--include",
"--manifest-path",
"--source-region",
"-a",
"-c",
"-i",
"-j",
"-s",
"-x",
})
_SUDO_VALUE_FLAGS = frozenset({
"-u",
"-g",
"-C",
"-D",
"-h",
"-p",
"-r",
"-t",
"-T",
"-U",
"--user",
"--group",
"--chdir",
})
_ENV_VALUE_FLAGS = frozenset({"-u", "-C", "-S", "--unset", "--chdir"})
_TIMEOUT_VALUE_FLAGS = frozenset({"-s", "-k", "--signal", "--kill-after"})
_XARGS_WATCH_VALUE_FLAGS = frozenset(
{"-n", "-P", "-I", "-L", "-d", "-E", "-s", "-a", "--interval"}
)
_CURL_SHORT_VALUE_FLAGS = frozenset("AbcCDeEHKmortuUwxyYz")
_GCLOUD_VALUE_FLAGS = frozenset({
"--account",
"--access-token-file",
"--billing-project",
"--cluster",
"--configuration",
"--filter",
"--flags-file",
"--flatten",
"--format",
"--impersonate-service-account",
"--limit",
"--location",
"--page-size",
"--project",
"--region",
"--sort-by",
"--universe-domain",
"--verbosity",
"--zone",
})
_HELM_WRITE_VERBS = frozenset({
"install",
"upgrade",
"uninstall",
"delete",
"del",
"un",
"rollback",
"create",
"test",
})
_HELM_VALUE_FLAGS = frozenset({
"-n",
"--namespace",
"--kube-context",
"--kubeconfig",
"--kube-apiserver",
"--kube-token",
"--kube-ca-file",
"--kube-as-user",
"--kube-as-group",
"--registry-config",
"--repository-cache",
"--repository-config",
"--burst-limit",
"--qps",
"-f",
"--values",
"--set",
"--set-string",
"--set-file",
"--version",
"--repo",
"--ca-file",
"--cert-file",
"--key-file",
"-o",
"--output",
})
_CURL_WRITE_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
_CURL_ALWAYS_WRITE_FLAGS = frozenset(
{"--json", "--upload-file", "--form", "--form-string"}
)
_CURL_DATA_FLAGS = frozenset({
"--data",
"--data-raw",
"--data-binary",
"--data-urlencode",
"--data-ascii",
})
# The external-layer marker is read from the RC header line (Root Cause bullet
# or Remediation entry), never from the body, so a negated mention such as
# "this is not Outside Kueue" inside the text does not switch the rule set.
_OUTSIDE_RE = re.compile(r"(?<!\bnot\s)\boutside kueue\b", re.IGNORECASE)
_DEFECT_RE = re.compile(r"(?<!\bnot\s)\bkueue defect\b", re.IGNORECASE)
_DOC_REMEDIATION_LINK_RE = re.compile(
r"https://(?:kueue\.sigs\.k8s\.io/docs/|docs\.cloud\.google\.com/|cloud\.google\.com/|kubernetes\.io/docs/|jobset\.sigs\.k8s\.io/docs/)",
re.IGNORECASE,
)
_DEFECT_ISSUE_LINK_RE = re.compile(
r"https://github\.com/kubernetes-sigs/kueue/issues\b",
re.IGNORECASE,
)
_CONFIRM_SIGNAL_RE = re.compile(
r"\b(?:confirm|verify|verified|until|when|once|expected|check\s+that|transitions?\s+to|becomes?\s+(?:True|Ready|Admitted))\b",
re.IGNORECASE,
)
# A change to a Kueue object: a manifest whose `kind:` line names a Kueue kind,
# or a writing kubectl verb whose resource is a Kueue CRD (any plural, singular
# or short name) or the controller ConfigMap.
_KUEUE_KINDS = (
"ClusterQueue|LocalQueue|ResourceFlavor|AdmissionCheck"
"|ProvisioningRequestConfig|Cohort|Topology|Workload"
"|WorkloadPriorityClass|MultiKueueCluster|MultiKueueConfig"
"|Configuration|KueueConfiguration"
)
_KUEUE_RESOURCES = (
r"(?:clusterqueues?|cq|localqueues?|lq|queues?|resourceflavors?|flavors?"
r"|rf|admissionchecks?|ac|provisioningrequestconfigs?|prc|cohorts?|co"
r"|topolog(?:y|ies)|topo|workloads?|wl|kwl|kueueworkloads?"
r"|workloadpriorityclass(?:es)?|wpc|multikueueclusters?|mkc"
r"|multikueueconfigs?|mkconf)"
)
_KUEUE_MUTATION_RE = re.compile(
rf"(?:^[ \t]*[\"']?kind[\"']?:[ \t]*[\"']?(?:{_KUEUE_KINDS})\b"
rf"|{_KUBECTL}{_FLAGS}"
r"(?:patch|edit|apply|replace|delete|create|annotate|label"
r"|kueue[ \t]+(?:stop|resume|create|delete))[ \t]+"
rf"{_FLAGS}"
rf"(?:{_KUEUE_RESOURCES}(?:\.v1[a-z0-9]*)?(?:\.kueue\.x-k8s\.io)?"
r"(?![\w.-])"
rf"|(?:configmaps?|cm)(?:[ \t]+{_FLAGS}|/)kueue-manager-config(?![\w-])))",
re.IGNORECASE | re.MULTILINE,
)
_KUBECTL_RE = re.compile(
_KUBECTL
+ _FLAGS
+ r"(get|describe|patch|edit|apply|delete|create|annotate|label|scale"
r"|replace|rollout[ \t]+\w+|explain)[ \t]+"
r"(?:(?:-n|--namespace)[ \t]+[^\s`]+[ \t]+)?([^\s`'\",;)]+)",
re.IGNORECASE,
)
# What a kubectl resource argument looks like (`pods`, `deploy/name`,
# `jobsets.jobset.x-k8s.io`). Placeholders, paths, quoted JSON and shell
# syntax do not match and are not checked.
_RESOURCE_TOKEN_RE = re.compile(r"[a-z][a-z0-9.-]*(?:/[a-z0-9.-]+)?")
# Plain words that follow a kubectl verb in prose ("use kubectl describe to
# confirm"); none of them is close to a resource name.
_NOT_A_RESOURCE = frozenset(
"a about after again also an and any are as at be because been before"
" both but by can command commands could does each every fails first for"
" from had has have here how if in instead is it its later manually may"
" must next not now of on once only or output reports returns should"
" shows so still than that the their them then there these this those to"
" until was were what when whether which while why will with would"
" your".split()
)
_FACT_ID_RE = re.compile(r"\b[SL]\d{1,3}\b")
_QUOTE_FACT_PREFIX_RE = re.compile(r"^\[?[SL]\d{1,3}\]?:?\s*")
_FENCED_BLOCK_RE = re.compile(r"```[\s\S]*?```")
_INLINE_CODE_RE = re.compile(r"`([^`\n]+)`")
_MIN_QUOTE_LEN, _MAX_QUOTE_LEN = 18, 160
_INSPECTED_GRAPH_KINDS = (
"cohort",
"clusterqueue",
"resourceflavor",
"admissioncheck",
)
# Resource names (singular, plural, short) that `kubectl` accepts on any
# cluster, independent of Kueue. Anything carrying an explicit API group suffix
# other than kueue.x-k8s.io (e.g. `jobsets.jobset.x-k8s.io`) is also accepted.
_CORE_KUBECTL_RESOURCES = frozenset(
# workloads
"pod pods po deployment deployments deploy replicaset replicasets rs"
" statefulset statefulsets sts daemonset daemonsets ds job jobs cronjob"
" cronjobs cj replicationcontroller replicationcontrollers rc"
" controllerrevision controllerrevisions podtemplate podtemplates"
" horizontalpodautoscaler horizontalpodautoscalers hpa"
" verticalpodautoscaler verticalpodautoscalers vpa"
" poddisruptionbudget poddisruptionbudgets pdb"
# configuration, identity and access
" configmap configmaps cm secret secrets namespace namespaces ns"
" serviceaccount serviceaccounts sa token role roles rolebinding"
" rolebindings clusterrole clusterroles clusterrolebinding"
" clusterrolebindings certificatesigningrequest"
" certificatesigningrequests csr resourcequota resourcequotas quota"
" limitrange limitranges limits priorityclass priorityclasses pc"
" runtimeclass runtimeclasses lease leases"
# nodes, events and metrics
" node nodes no event events ev componentstatus componentstatuses cs"
" podmetrics nodemetrics"
# networking
" service services svc endpoints ep endpointslice endpointslices"
" ingress ingresses ing ingressclass ingressclasses networkpolicy"
" networkpolicies netpol"
# storage
" persistentvolumeclaim persistentvolumeclaims pvc persistentvolume"
" persistentvolumes pv storageclass storageclasses sc csinode csinodes"
" csidriver csidrivers csistoragecapacity csistoragecapacities"
" volumeattachment volumeattachments volumeattributesclass"
" volumeattributesclasses vac"
# dynamic resource allocation
" resourceclaim resourceclaims resourceclaimtemplate"
" resourceclaimtemplates resourceslice resourceslices deviceclass"
" deviceclasses"
# API machinery, admission and flow control
" customresourcedefinition customresourcedefinitions crd crds apiservice"
" apiservices flowschema flowschemas prioritylevelconfiguration"
" prioritylevelconfigurations mutatingwebhookconfiguration"
" mutatingwebhookconfigurations validatingwebhookconfiguration"
" validatingwebhookconfigurations validatingadmissionpolicy"
" validatingadmissionpolicies validatingadmissionpolicybinding"
" validatingadmissionpolicybindings"
# job frameworks and operators commonly installed next to Kueue
" jobset jobsets rayjob rayjobs raycluster rayclusters rayservice"
" rayservices pytorchjob pytorchjobs mpijob mpijobs tfjob tfjobs"
" xgboostjob xgboostjobs paddlejob paddlejobs jaxjob jaxjobs trainjob"
" trainjobs sparkapplication sparkapplications leaderworkerset"
" leaderworkersets lws appwrapper appwrappers podgroup podgroups"
" provisioningrequest provisioningrequests provreq provreqs computeclass"
" computeclasses nodepool nodepools nodeclaim nodeclaims certificate"
" certificates issuer issuers clusterissuer clusterissuers"
" servicemonitor servicemonitors podmonitor podmonitors"
# kubectl category
" all".split()
)
_CONFIG_KIND_RE = re.compile(r"kind:\s*KueueConfiguration\b")
# The rest-of-line scan stops at the next `kubectl`, so a line holding many
# commands is not rescanned to its end from each of them.
_CONFIG_PATCH_RE = re.compile(
_KUBECTL
+ _FLAGS
+ r"patch[ \t]+"
+ _FLAGS
+ r"(?:configmap|cm)\b(?:(?!kubectl)[^\n])*"
r"controller_manager_config\.yaml",
re.IGNORECASE,
)
# --- Context -----------------------------------------------------------------
@dataclasses.dataclass
class LedgerData:
"""What `snapshot.py` / `trace_logs.py` recorded in the coverage ledger (all empty when it is absent)."""
referenced: list[str] = dataclasses.field(default_factory=list)
inspected: list[str] = dataclasses.field(default_factory=list)
tool_outputs: list[str] = dataclasses.field(default_factory=list)
facts: list[dict[str, Any]] = dataclasses.field(default_factory=list)
detected_kueue_version: dict[str, Any] | None = None
@classmethod
def load(cls, ledger_path: str | None) -> "LedgerData":
"""Reads the ledger JSON; a missing or unreadable file yields an empty ledger."""
if not ledger_path or not os.path.exists(ledger_path):
return cls()
data = report_output.load_ledger(ledger_path, strict=True)
vinfo = data.get("detected_kueue_version")
return cls(
referenced=data.get("referenced", []),
inspected=data.get("inspected", []),
tool_outputs=data.get("tool_outputs", []),
facts=[x for x in data.get("facts", []) if isinstance(x, dict)],
detected_kueue_version=vinfo if isinstance(vinfo, dict) else None,
)
@dataclasses.dataclass
class DraftContext:
"""One draft report plus everything the gates compare it against."""
draft_text: str
ledger: LedgerData
version_info: dict[str, Any]
schema: dict[str, Any]
sections: dict[str, str] = dataclasses.field(init=False)
headers: frozenset[tuple[int, str]] = dataclasses.field(init=False)
def __post_init__(self) -> None:
self.sections = split_sections(self.draft_text)
self.headers = frozenset(
(h.level, h.title) for h in yaml_checks.draft_headers(self.draft_text)
)
def section(self, title: str) -> str:
"""Body of the `####` section with this title (any accepted spelling), or empty."""
return self.sections.get(yaml_checks.section_title(title), "")
ReportGate = Callable[[DraftContext], dict[str, list[Any]]]
# The one section parser of the validator (normalised `####` titles).
split_sections = yaml_checks.split_sections
def _normalize_for_match(text: str) -> str:
"""Collapses whitespace and strips quoting/flow-YAML punctuation so YAML/JSON formatting differences do not break substring checks."""
text = text.replace("''", "'").replace('\\"', '"')
text = text.replace('"', "").replace("'", "").replace("`", "")
text = re.sub(r"[\[\]{},]", " ", text)
text = re.sub(r"(?:^|\s)-\s+", " ", text)
return re.sub(r"\s+", " ", text).strip().lower()
def _join_continuations(text: str) -> str:
r"""Joins shell `\`-continued lines, so a command split over lines is scanned as one."""
return _CONTINUATION_RE.sub(" ", text)
def _mentions_id(text: str, fact_id: str) -> bool:
return (
re.search(rf"(?<![A-Za-z0-9-]){re.escape(fact_id)}(?![0-9])", text)
is not None
)
def _first_line(text: str) -> str:
return next((ln for ln in text.splitlines() if ln.strip()), "")
# --- Gates -------------------------------------------------------------------
def check_headers(ctx: DraftContext) -> dict[str, list[str]]:
"""All required section headers exist and no required `####` section is empty.
Headers are matched by normalised title, the same way every other gate finds
its section, so a spelling this gate accepts is never invisible to them. A
required section that is present but has no content fails closed: the gates
that read it would otherwise have nothing to check.
Args:
ctx: Draft report context and parsed sections.
Returns:
A dict mapping `"missing_headers"` to the missing or empty headers.
"""
titles = {title for _, title in ctx.headers}
missing: list[str] = []
for header in REQUIRED_HEADERS:
hashes, _, raw = header.partition(" ")
title = yaml_checks.section_title(raw)
if len(hashes) != 4:
if title not in titles:
missing.append(header)
elif (4, title) not in ctx.headers:
missing.append(header)
elif not ctx.section(title).strip():
missing.append(
f"{header} (the section is empty: write its content, or `- none`"
" when there is nothing to list)"
)
return {"missing_headers": missing}
def check_graph_coverage(ctx: DraftContext) -> dict[str, list[str]]:
"""Referenced Kueue graph objects (Cohort, ClusterQueue, ResourceFlavor, AdmissionCheck) were inspected or at least named."""
inspected_names = {ref.split("/")[-1].lower() for ref in ctx.ledger.inspected}
draft_lower = ctx.draft_text.lower()
uninspected: list[str] = []
for ref in ctx.ledger.referenced:
kind, _, name = ref.partition("/")
short_name = name.split("/")[-1].lower()
if (
kind in _INSPECTED_GRAPH_KINDS
and short_name not in inspected_names
and short_name not in draft_lower
):
uninspected.append(ref)
return {"uninspected_graph_objects": uninspected}
def _is_checkable_quote(match: str) -> bool:
return (
_MIN_QUOTE_LEN <= len(match) <= _MAX_QUOTE_LEN
and " " in match
and not match.startswith(("kubectl", "python"))
)
_DOTTED_YAML_KV_RE = re.compile(
r"^([a-zA-Z0-9_-]+(?:\.[a-zA-Z0-9_-]+)+)\s*([:=])\s*(.+)$"
)
def _quote_in_corpus(needle: str, corpus: str, norm_corpus: str) -> bool:
"""Returns True when an inline-quoted snippet matches the tool output corpus."""
stripped_needle = _QUOTE_FACT_PREFIX_RE.sub("", needle).strip()
if needle in corpus or (stripped_needle and stripped_needle in corpus):
return True
if _normalize_for_match(needle) in norm_corpus:
return True
if stripped_needle and _normalize_for_match(stripped_needle) in norm_corpus:
return True
# Support dotted YAML path notation in prose (e.g.
# `spec.topologyName: example-topology` when the YAML has `spec:` and
# `topologyName: example-topology` on separate lines).
m = _DOTTED_YAML_KV_RE.match(stripped_needle or needle)
if m:
parts = m.group(1).split(".")
leaf_kv = f"{parts[-1]}{m.group(2)} {m.group(3)}"
if _normalize_for_match(leaf_kv) in norm_corpus and all(
p.lower() in norm_corpus for p in parts[:-1]
):
return True
return False
def check_evidence_grounding(ctx: DraftContext) -> dict[str, list[str]]:
"""Inline-quoted evidence under `#### Observations` must occur in the recorded tool outputs."""
tool_outputs = ctx.ledger.tool_outputs
obs_section = ctx.section("observations")
if not tool_outputs or not obs_section:
return {"fabricated_quotes": []}
corpus = "\n".join(tool_outputs)
norm_corpus = _normalize_for_match(corpus)
obs_no_fences = _FENCED_BLOCK_RE.sub("", obs_section)
fabricated = [
match.strip()
for match in _INLINE_CODE_RE.findall(obs_no_fences)
if _is_checkable_quote(match)
and not _quote_in_corpus(match.strip(), corpus, norm_corpus)
]
return {"fabricated_quotes": fabricated}
def check_fact_coverage(ctx: DraftContext) -> dict[str, list[dict[str, str]]]:
"""No-op in the streamlined validator: tagged fact ids are reading aids, not a mandatory checklist."""
del ctx
return {"unaddressed_facts": []}
def _entry_ids(
text: str, first: re.Match[str], prefix: str
) -> tuple[list[str], int]:
"""Ids an entry header lists (`RC1 & RC2:` -> RC1, RC2) and the offset just past the list."""
ids = [f"{prefix}{int(first.group(1))}"]
pos = first.end()
while True:
m = _ID_LIST_NEXT_RE.match(text, pos)
if m is None or m.group(1) != prefix:
return list(dict.fromkeys(ids)), pos
ids.append(f"{prefix}{int(m.group(2))}")
pos = m.end()
def _chunk_by_id(
text: str,
start_re: re.Pattern[str],
any_re: re.Pattern[str],
prefix: str,
stop_re: re.Pattern[str] | None = None,
) -> tuple[list[str], dict[str, str]]:
"""Splits a section into per-id chunks.
Line-start entry headers are preferred over inline cross-references. An
entry whose header lists several ids (`- RC1 & RC2: ...`, `- RC1, RC2: ...`)
is assigned to every one of them. A chunk ends at the next entry, or at a
line-start entry of the other family (`stop_re`), whichever comes first.
Args:
text: Section body.
start_re: Matches an id at the start of a line; group 1 is its number.
any_re: Matches an id anywhere; used when no line starts with one.
prefix: `RC` or `OQ`.
stop_re: Line-start pattern that ends a chunk without starting one.
Returns:
`(ids in order of first appearance, {id: chunk text})`.
"""
matches = list(start_re.finditer(text)) or list(any_re.finditer(text))
entries: list[tuple[int, list[str]]] = []
covered = 0
for m in matches:
if m.start() < covered:
continue # already taken as part of the previous entry's id list
entry_ids, covered = _entry_ids(text, m, prefix)
entries.append((m.start(), entry_ids))
bounds = sorted(
{start for start, _ in entries}
| {m.start() for m in (stop_re.finditer(text) if stop_re else ())}
)
parts: dict[str, list[str]] = {}
for start, entry_ids in entries:
nxt = bisect.bisect_right(bounds, start)
end = bounds[nxt] if nxt < len(bounds) else len(text)
for cid in entry_ids:
parts.setdefault(cid, []).append(text[start:end])
return list(parts), {cid: "".join(texts) for cid, texts in parts.items()}
def _chunk_by_rc(text: str) -> tuple[list[str], dict[str, str]]:
return _chunk_by_id(text, _RC_START_RE, _RC_RE, "RC", _OQ_START_RE)
def _chunk_by_oq(text: str) -> tuple[list[str], dict[str, str]]:
return _chunk_by_id(text, _OQ_START_RE, _OQ_RE, "OQ", _RC_START_RE)
def _has_bullets(text: str) -> bool:
return re.search(r"(?m)^[ \t]*[-*\d]", text) is not None
@dataclasses.dataclass
class _RemediationScan:
"""Per-report inputs of the RC -> remediation mapping, derived once from the sections."""
scope_text: str
oq_ids: list[str]
oq_subjects: dict[
str, str
] # fact id -> OQ that declares it undecided (OQ header line only)
rem_chunks: dict[str, str]
@classmethod
def from_sections(cls, ctx: DraftContext) -> "_RemediationScan":
oq_ids, oq_chunks = _chunk_by_oq(ctx.section("open questions"))
oq_subjects: dict[str, str] = {}
for oq in oq_ids:
for fid in _FACT_ID_RE.findall(_first_line(oq_chunks.get(oq, ""))):
oq_subjects.setdefault(fid, oq)
_, rem_chunks = _chunk_by_rc(ctx.section("remediation"))
return cls(
ctx.section("scope").strip().lower(), oq_ids, oq_subjects, rem_chunks
)
@property
def is_pure_outside_scope(self) -> bool:
return (
"outside kueue" in self.scope_text
and "mixed" not in self.scope_text
and not self.scope_text.startswith("kueue")
)
@property
def is_defect_scope(self) -> bool:
return "kueue defect" in self.scope_text and "mixed" not in self.scope_text
def _no_rc_gaps(root: str, scan: _RemediationScan) -> list[str]:
"""Gaps for a report without any `RC<n>`: either un-numbered entries or neither RC nor OQ."""
if _has_bullets(root) and not re.search(r"\bnone\b", root, re.IGNORECASE):
return [
"Root Cause entries are not numbered: start each one with RC1, RC2, ..."
" so remediation can reference them."
]
if not scan.oq_ids and not scan.scope_text.startswith("undetermined"):
return [
"No RC<n> under Root Cause and no OQ<n> under Open Questions: either"
" establish a root cause from the evidence or open an Open Question"
" that names what is missing (do not leave both empty)."
]
return []
def _remediation_entry_gaps(
rc: str, chunk: str, rc_is_outside: bool, rc_is_defect: bool = False
) -> list[str]:
"""The remediation entry links the documentation (required whenever YAML or a kubectl command is present), or (Outside Kueue / Kueue defect) states an action + confirmation signal."""
if rc_is_outside and _KUEUE_MUTATION_RE.search(_join_continuations(chunk)):
return [
f"{rc}: Root Cause / Scope is 'Outside Kueue', but remediation mutates"
" a Kueue object. Do not blame or patch Kueue to mask an external"
" failure; state the external component/layer action and confirmation"
" signal (or classify the RC as a Kueue configuration issue if a Kueue"
" change is genuinely required)."
]
has_doc_link = _DOC_REMEDIATION_LINK_RE.search(chunk) is not None
has_code_or_cmd = "```" in chunk or "kubectl " in chunk
if rc_is_defect:
if (
has_doc_link or _DEFECT_ISSUE_LINK_RE.search(chunk) is not None
) and _CONFIRM_SIGNAL_RE.search(chunk):
return []
return [
f"{rc}: Kueue defect remediation must link the relevant"
" documentation, https://github.com/kubernetes-sigs/kueue/issues, or"
" support path and state a confirmation signal."
]
if has_code_or_cmd and not has_doc_link:
return [
f"{rc}: remediation includes a YAML manifest or kubectl command without"
" a documentation link (link the official"
" https://kueue.sigs.k8s.io/docs/,"
" https://docs.cloud.google.com/kubernetes-engine/docs/, or"
" https://kubernetes.io/docs/ section that describes the fix)."
]
if has_doc_link:
return []
if rc_is_outside and _CONFIRM_SIGNAL_RE.search(chunk):
return []
if rc_is_outside:
return [
f"{rc}: Outside Kueue remediation without a documentation link must"
" state a verification/confirmation signal (e.g. 'Confirm by checking"
" that ProvisioningRequest Provisioned=True and Workload"
" Admitted=True')."
]
return [
f"{rc}: remediation has no concrete command, manifest, or documentation"
" link (link the official documentation section describing the fix, and"
" include that link with any kubectl command or YAML block)."
]
def _rc_gaps(rc: str, rc_root_text: str, scan: _RemediationScan) -> list[str]:
"""Returns remediation gaps for a single RC<n> root-cause entry."""
chunk = scan.rem_chunks.get(rc)
rc_head = _first_line(rc_root_text)
if chunk is None:
return [f"{rc}: no remediation entry references {rc}."]
rc_is_outside = (
scan.is_pure_outside_scope
or _OUTSIDE_RE.search(rc_head) is not None
or _OUTSIDE_RE.search(_first_line(chunk)) is not None
)
rc_is_defect = (
scan.is_defect_scope
or _DEFECT_RE.search(rc_head) is not None
or _DEFECT_RE.search(_first_line(chunk)) is not None
)
return _remediation_entry_gaps(rc, chunk, rc_is_outside, rc_is_defect)
def check_remediation_mapping(ctx: DraftContext) -> dict[str, list[str]]:
"""Checks that every RC<n> has valid remediation or an OQ<n> is opened."""
scan = _RemediationScan.from_sections(ctx)
root = ctx.section("root cause")
gaps: list[str] = []
rc_ids, root_chunks = _chunk_by_rc(root)
if scan.scope_text.startswith("undetermined") and not scan.oq_ids:
gaps.append(
"Scope is 'Undetermined' but `#### Open Questions` has no OQ<n> entry:"
" state what cannot be decided, the candidate explanations, the"
" discriminating observation and the read-only data to collect."
)
if not rc_ids:
return {"remediation_gaps": gaps + _no_rc_gaps(root, scan)}
for rc in rc_ids:
gaps.extend(_rc_gaps(rc, root_chunks.get(rc, ""), scan))
return {"remediation_gaps": gaps}
def _oq_parts(chunk: str) -> list[tuple[str, str]]:
"""Splits one OQ entry into `(label, body)` parts in order; each body spans up to the next label.
Every occurrence is kept, so a second `Collect:` in the same entry is a part
of its own. Labels are lower-cased with single spaces (`conditional
remediation`).
Args:
chunk: Text of one `OQ<n>` entry.
Returns:
The labelled parts of the entry.
"""
matches = list(_OQ_PART_RE.finditer(chunk))
parts: list[tuple[str, str]] = []
for i, m in enumerate(matches):
end = matches[i + 1].start() if i + 1 < len(matches) else len(chunk)
label = " ".join(m.group(1).lower().split())
parts.append((label, chunk[m.end() : end].strip()))
return parts
def _flush_token(
seg: list[tuple[str, bool]], tok: list[str], tok_quoted: bool
) -> bool:
"""Appends the buffered token to `seg` and clears `tok`; returns reset quoted flag."""
if tok or tok_quoted:
seg.append(("".join(tok), tok_quoted))
tok.clear()
return False
def _last_closing_sq(line: str) -> int:
"""Rightmost single quote in `line` that is not an internal word apostrophe."""
n = len(line)
for j in range(n - 1, -1, -1):
if line[j] != "'":
continue
if j > 0 and j + 1 < n and line[j - 1].isalnum() and line[j + 1].isalnum():
continue
return j
return -1
def _lex_shell_line(line: str, segments: list[list[tuple[str, bool]]]) -> None:
"""Splits one line into `(token, was_quoted)` command segments in O(len(line))."""
last_sq = _last_closing_sq(line)
last_dq = line.rfind('"')
seg: list[tuple[str, bool]] = []
tok: list[str] = []
tok_quoted = False
quote = ""
i, n = 0, len(line)
while i < n:
ch = line[i]
if quote:
if ch == "\\" and quote == '"' and i + 1 < n:
tok.append(line[i + 1])
i += 2
continue
if ch == quote:
quote = ""
else:
tok.append(ch)
i += 1
continue
if (
ch == "'" and i < last_sq and not (i > 0 and line[i - 1].isalnum())
) or (ch == '"' and i < last_dq):
quote = ch
tok_quoted = True
i += 1
continue
if ch == "\\" and i + 1 < n:
tok.append(line[i + 1])
i += 2
continue
if ch in (";", "|", "&", "`", "(", ")"):
tok_quoted = _flush_token(seg, tok, tok_quoted)
if seg:
segments.append(seg)
seg = []
i += 1
continue
if ch in (" ", "\t", "\r"):
tok_quoted = _flush_token(seg, tok, tok_quoted)
i += 1
continue
tok.append(ch)
i += 1
_flush_token(seg, tok, tok_quoted)
if seg:
segments.append(seg)
def _iter_shell_segments(text: str) -> list[list[tuple[str, bool]]]:
"""Splits shell text into command segments of `(token, was_quoted)` pairs."""
segments: list[list[tuple[str, bool]]] = []
for line in text.splitlines():
_lex_shell_line(line, segments)
return segments
def _skip_flags(
seg: list[tuple[str, bool]], idx: int, value_flags: frozenset[str]
) -> int:
"""Advances `idx` past leading flags (and their values for `value_flags`)."""
while idx < len(seg):
tok = seg[idx][0]
if tok == "--":
return idx + 1
if not tok.startswith("-"):
return idx
low = tok.lower()
idx += 2 if ("=" not in low and low in value_flags) else 1
return idx
def _is_env_assignment(tok: str, quoted: bool) -> bool:
"""True for unquoted shell env assignments like `FOO=bar`."""
if quoted or "=" not in tok or tok.startswith("-"):
return False
name = tok.split("=", 1)[0]
return bool(name) and name.replace("_", "").isalnum()
def _find_exec_start(seg: list[tuple[str, bool]], start: int) -> int:
"""Returns the token index after `-exec`/`-execdir` in a `find` segment, or len(seg)."""
for j in range(start, len(seg)):
if seg[j][0] in ("-exec", "-execdir") and j + 1 < len(seg):
return j + 1
return len(seg)
def _build_next_exec(seg: list[tuple[str, bool]]) -> list[int]:
"""For each index `k`, returns the index after the next `-exec`/`-execdir`."""
n = len(seg)
nxt = [n] * (n + 1)
pos = n
for i in range(n - 1, -1, -1):
if seg[i][0] in ("-exec", "-execdir") and i + 1 < n:
pos = i + 1
nxt[i] = pos
return nxt
def _step_shell_wrapper(
seg: list[tuple[str, bool]], i: int, next_exec: list[int] | None
) -> int:
"""Advances `i` past one env assignment or shell wrapper, or returns `i`."""
tok, quoted = seg[i]
if _is_env_assignment(tok, quoted):
return i + 1
if tok.startswith("-"):
return i
base = os.path.basename(tok).lower()
if base in _SIMPLE_WRAPPERS:
return _skip_flags(seg, i + 1, _SIMPLE_WRAPPER_VALUE_FLAGS)
if base == "sudo":
return _skip_flags(seg, i + 1, _SUDO_VALUE_FLAGS)
if base == "env":
return _skip_flags(seg, i + 1, _ENV_VALUE_FLAGS)
if base in ("timeout", "ssh"):
flags = _TIMEOUT_VALUE_FLAGS if base == "timeout" else _SSH_VALUE_FLAGS
j = _skip_flags(seg, i + 1, flags)
return j + 1 if j < len(seg) else j
if base == "stdbuf":
return _skip_flags(seg, i + 1, _STDBUF_VALUE_FLAGS)
if base == "nice":
return _skip_flags(seg, i + 1, frozenset({"-n", "--adjustment"}))
if base in ("xargs", "watch"):
return _skip_flags(seg, i + 1, _XARGS_WATCH_VALUE_FLAGS)
if base == "find":
if next_exec is not None:
return next_exec[i + 1] if i + 1 < len(next_exec) else len(seg)
return _find_exec_start(seg, i + 1)
return i
def _strip_shell_wrappers(
seg: list[tuple[str, bool]],
start: int = 0,
memo: dict[int, int] | None = None,
next_exec: list[int] | None = None,
) -> int:
"""Returns the command-token index after leading env vars and shell wrappers."""
i = start
visited: list[int] = []
while i < len(seg):
if memo is not None and i in memo:
i = memo[i]
break
nxt = _step_shell_wrapper(seg, i, next_exec)
if nxt == i:
break
if memo is not None:
visited.append(i)
i = nxt
if memo is not None:
for v in visited:
memo[v] = i
return i
def _shell_c_script(seg: list[tuple[str, bool]], start: int) -> str:
"""Returns the `-c` script argument for a `sh`/`bash` call, or empty string."""
i = start
while i < len(seg):
tok = seg[i][0]
if tok == "--":
return ""
if tok in ("-o", "+o"):
i += 2
continue
if tok == "-c" or (
tok.startswith("-")
and not tok.startswith("--")
and len(tok) > 1
and tok.endswith("c")
):
return seg[i + 1][0] if i + 1 < len(seg) else ""
if not tok.startswith("-"):
return ""
i += 1
return ""
def _is_gcs_upload_cp(seg: list[tuple[str, bool]], start: int) -> bool:
"""True when `gcloud storage cp`/`rsync` writes to a `gs://` destination."""
val_flags = _GCLOUD_VALUE_FLAGS | _GCLOUD_STORAGE_VALUE_FLAGS
dest = ""
i = start
while i < len(seg):
tok = seg[i][0]
low = tok.lower()
if low.startswith("-"):
i += 2 if ("=" not in low and low in val_flags) else 1
continue
if tok not in (";", "+"):
dest = tok
i += 1
return dest.lower().startswith("gs://")
def _is_mutating_gcloud(seg: list[tuple[str, bool]], start: int) -> bool:
"""True when a `gcloud` command reaches a write verb before any read verb."""
i = start
pos = 0
first_pos = ""
prev_pos = ""
while i < len(seg) and pos < 10:
low = seg[i][0].lower()
if low.startswith("-"):
i += 2 if ("=" not in low and low in _GCLOUD_VALUE_FLAGS) else 1
continue
pos += 1
if pos == 1:
first_pos = low
if low == "deploy" and (
pos == 1
or (pos == 2 and first_pos in ("alpha", "beta"))
or prev_pos == "fleet"
):
prev_pos = low
i += 1
continue
if low == "run" and (
pos == 1 or (pos == 2 and first_pos in ("alpha", "beta"))
):
prev_pos = low
i += 1
continue
if low in _GCLOUD_GROUP_NAMES:
prev_pos = low
i += 1
continue
if low in ("cp", "rsync") and pos <= 3:
return _is_gcs_upload_cp(seg, i + 1)
if low in _GCLOUD_READ_VERBS or low.startswith(_GCLOUD_READ_PREFIXES):
return False
if (
low == "run"
or low in _GCLOUD_WRITE_VERBS
or low.startswith(_GCLOUD_WRITE_PREFIXES)
):
return True
prev_pos = low
i += 1
return False
def _is_mutating_helm(seg: list[tuple[str, bool]], start: int) -> bool:
"""True when a `helm` command's first positional verb mutates or runs pods."""
i = start
while i < len(seg):
low = seg[i][0].lower()
if low.startswith("-"):
i += 2 if ("=" not in low and low in _HELM_VALUE_FLAGS) else 1
continue
return low in _HELM_WRITE_VERBS
return False
def _scan_curl_short_flags(
chars: str, seg: list[tuple[str, bool]], idx: int
) -> tuple[bool, str, bool, bool, int]:
"""Parses a bundled short-flag token like `-sG` or `-sXDELETE`."""
has_get = False
method = ""
always_write = False
has_data = False
step = 1
for pos, ch in enumerate(chars):
rest = chars[pos + 1 :]
if ch == "G":
has_get = True
elif ch == "X":
if rest:
method = rest.upper()
elif idx + 1 < len(seg):
method = seg[idx + 1][0].upper()
step = 2
break
elif ch == "d":
has_data = True
if not rest and idx + 1 < len(seg):
step = 2
break
elif ch in ("F", "T"):
always_write = True
if not rest and idx + 1 < len(seg):
step = 2
break
elif ch in _CURL_SHORT_VALUE_FLAGS:
if not rest and idx + 1 < len(seg):
step = 2
break
return has_get, method, always_write, has_data, step
def _is_mutating_curl(seg: list[tuple[str, bool]], start: int) -> bool:
"""True when a `curl` command sends a write method or body without `-G`/`--get`."""
has_get = False
method = ""
always_write = False
has_data = False
i = start
while i < len(seg):
tok = seg[i][0]
low = tok.lower()
if low == "--get":
has_get = True
i += 1
elif low == "--request" and i + 1 < len(seg):
method = seg[i + 1][0].upper()
i += 2
elif low.startswith("--request="):
method = tok.split("=", 1)[1].upper()
i += 1
elif low.split("=", 1)[0] in _CURL_ALWAYS_WRITE_FLAGS:
always_write = True
i += 2 if ("=" not in low and i + 1 < len(seg)) else 1
elif low.split("=", 1)[0] in _CURL_DATA_FLAGS:
has_data = True
i += 2 if ("=" not in low and i + 1 < len(seg)) else 1
elif tok.startswith("-") and not tok.startswith("--") and len(tok) > 1:
g, m, aw, d, step = _scan_curl_short_flags(tok[1:], seg, i)
has_get = has_get or g
if m:
method = m
always_write = always_write or aw
has_data = has_data or d
i += step
else:
i += 1
if method in _CURL_WRITE_METHODS or always_write:
return True
return has_data and not has_get and method not in ("GET", "HEAD")
_NON_KUBECTL_HINTS = ("gcloud", "helm", "curl", "sh", "eval")
_TRACKED_CMDS = frozenset({"gcloud", "helm", "curl", "eval"}) | _SHELL_BINS
_QUOTED_CMD_HEADS = _TRACKED_CMDS | frozenset({"sudo", "env", "timeout"})
_QUOTED_FILTER_PREVS = frozenset(
{"read", "--filter", "-e", "--regexp", "grep", "rg"}
)
_TEXT_FILTER_CMDS = frozenset({
"grep",
"egrep",
"fgrep",
"rg",
"ag",
"awk",
"gawk",
"sed",
"jq",
"yq",
})
_PROSE_CMD_LEADINS = frozenset({
"run",
"running",
"execute",
"executing",
"invoke",
"invoking",
"use",
"then",
})
_ORDINAL_LEADINS = frozenset({
"first",
"second",
"third",
"next",
"finally",
"lastly",
})
_LEADING_LIST_MARKERS = frozenset({"-", "*", "+", "$", "#", ">", "%", "•"})
_LEADIN_CMD_HEADS = _TRACKED_CMDS | _TEXT_FILTER_CMDS
def _is_prose_leadin(
seg: list[tuple[str, bool]], j: int, start: int, allow_comma: bool = False
) -> bool:
"""True for unquoted command/step introducers (`Run`, `First,`, `Step 1:`)."""
tok, quoted = seg[j]
if quoted or not tok:
return False
if allow_comma and tok.endswith(","):
return True
bare = tok.rstrip(":,").lower()
if bare in _PROSE_CMD_LEADINS:
return True
if bare in _ORDINAL_LEADINS and (j == start or tok[-1] in (":", ",")):
return True
return (
j > 0
and not seg[j - 1][1]
and seg[j - 1][0].lower() == "step"
and tok.rstrip(":.)").isdigit()
)
def _strip_leading_markers(seg: list[tuple[str, bool]]) -> int:
"""Skips leading list bullets (`-`, `*`, `•`, `1.`, `a.`) and shell prompts."""
i = 0
while i < len(seg) and not seg[i][1]:
tok = seg[i][0]
if (
tok in _LEADING_LIST_MARKERS
or (len(tok) >= 2 and tok[-1] in (".", ")") and tok[:-1].isdigit())
or (len(tok) == 2 and tok[0].isalpha() and tok[1] in (".", ")"))
):
i += 1
continue
break
return i
def _prose_leadin_slices(
seg: list[tuple[str, bool]], start: int, allow_comma: bool = False
) -> list[tuple[int, int]]:
"""Returns disjoint `(cmd_idx, end)` slices after prose lead-ins in O(len(seg))."""
has_find = any(
not q and os.path.basename(t).lower() == "find" for t, q in seg[start:]
)
next_exec = _build_next_exec(seg) if has_find else None
memo: dict[int, int] = {}
hits: list[tuple[int, int]] = []
j = start
while j + 1 < len(seg):
if _is_prose_leadin(seg, j, start, allow_comma=allow_comma):
cmd_idx = _strip_shell_wrappers(seg, j + 1, memo, next_exec)
if cmd_idx < len(seg) and not seg[cmd_idx][0].startswith("-"):
if os.path.basename(seg[cmd_idx][0]).lower() in _LEADIN_CMD_HEADS:
hits.append((j, cmd_idx))
j = cmd_idx + 1
continue
j += 1
return [
(cmd_idx, hits[k + 1][0] if k + 1 < len(hits) else len(seg))
for k, (_, cmd_idx) in enumerate(hits)
]
def _scan_chained_cli_cmds(
seg: list[tuple[str, bool]], start: int, depth: int
) -> bool:
"""Checks unquoted chained commands following a read-only CLI in one segment."""
for cmd_idx, end in _prose_leadin_slices(seg, start, allow_comma=True):
mut, _ = _segment_cmd_is_mutating(seg[cmd_idx:end], 0, depth)
if mut:
return True
return False
def _scan_segment_prose_and_quotes(
seg: list[tuple[str, bool]], start: int, depth: int
) -> bool:
"""Scans prose-introduced commands and quoted command tokens in one segment."""
covered: list[tuple[int, int]] = []
for cmd_idx, end in _prose_leadin_slices(seg, start):
mut, skip_quoted = _segment_cmd_is_mutating(seg[cmd_idx:end], 0, depth)
if mut:
return True
if skip_quoted:
covered.append((cmd_idx, end))
if depth >= 2:
return False
cov_i = 0
for qidx, (tok, quoted) in enumerate(seg):
while cov_i < len(covered) and qidx >= covered[cov_i][1]:
cov_i += 1
if cov_i < len(covered) and covered[cov_i][0] <= qidx < covered[cov_i][1]:
continue
if quoted and any(c.isspace() for c in tok):
prev_low = seg[qidx - 1][0].lower() if qidx > 0 else ""
if _quoted_cmd_is_mutating(tok, prev_low, depth):
return True
return False
def _quoted_cmd_is_mutating(tok: str, prev_low: str, depth: int) -> bool:
"""True when a quoted multi-word token holds a mutating command."""
if depth >= 2 or prev_low in _QUOTED_FILTER_PREVS:
return False
parts = tok.lstrip().split(None, 1)
if len(parts) < 2:
return False
if prev_low != "eval":
if parts[0].startswith("-"):
return False
if os.path.basename(parts[0]).lower() not in _QUOTED_CMD_HEADS:
return False
return _has_mutating_non_kubectl_cmd(tok, depth + 1)
def _segment_cmd_is_mutating(
seg: list[tuple[str, bool]], idx: int, depth: int
) -> tuple[bool, bool]:
"""Returns `(is_mutating, skip_quoted_scan)` for the command starting at `seg[idx]`."""
if idx >= len(seg):
return False, False
tok = seg[idx][0]
if tok.startswith("-"):
return False, False
cmd = os.path.basename(tok).lower()
if cmd in _TEXT_FILTER_CMDS:
return False, True
if cmd == "gcloud":
return _is_mutating_gcloud(seg, idx + 1), True
if cmd == "helm":
return _is_mutating_helm(seg, idx + 1), True
if cmd == "curl":
return _is_mutating_curl(seg, idx + 1), True
if depth < 2 and cmd in _SHELL_BINS:
script = _shell_c_script(seg, idx + 1)
return (
bool(script and _has_mutating_non_kubectl_cmd(script, depth + 1)),
True,
)
if depth < 2 and cmd == "eval":
joined = " ".join(t for t, _ in seg[idx + 1 :])
return (
bool(joined and _has_mutating_non_kubectl_cmd(joined, depth + 1)),
True,
)
return False, False
def _has_mutating_non_kubectl_cmd(text: str, depth: int = 0) -> bool:
"""Checks command-position segments, prose lead-ins, and quoted commands."""
low_text = text.lower()
if not any(h in low_text for h in _NON_KUBECTL_HINTS):
return False
for seg in _iter_shell_segments(text):
start = _strip_leading_markers(seg)
idx = _strip_shell_wrappers(seg, start)
mut, is_known_cli = _segment_cmd_is_mutating(seg, idx, depth)
if mut:
return True
if is_known_cli:
cmd = os.path.basename(seg[idx][0]).lower() if idx < len(seg) else ""
if cmd not in _TEXT_FILTER_CMDS and _scan_chained_cli_cmds(
seg, idx + 1, depth
):
return True
continue
if _scan_segment_prose_and_quotes(seg, idx, depth):
return True
return False
def _is_mutating(text: str) -> bool:
"""True when `text` holds a writing CLI command (`kubectl`/`gcloud`/`helm`/`curl`) or Kueue manifest."""
joined = _join_continuations(text)
return bool(
_KUBECTL_WRITE_RE.search(joined)
or _KUEUE_MUTATION_RE.search(joined)
or _has_mutating_non_kubectl_cmd(joined)
)
def check_open_questions(ctx: DraftContext) -> dict[str, list[str]]:
"""Streamlined Open Questions check: rejects mutating commands inside any `Collect:` part.
Every `Collect:` part of an entry is checked, whether its label starts a line
or sits inline. A conditional remediation written after `Collect:` under its
own label (`Conditional remediation:`, `Remediation:`, `Fix:`) is a separate
part and may carry a writing command.
Args:
ctx: Draft report context and parsed sections.
Returns:
A dict mapping `"open_question_gaps"` to one message per offending OQ.
"""
text = ctx.section("open questions")
oq_ids, chunks = _chunk_by_oq(text)
gaps: list[str] = []
for oq in oq_ids:
if any(
label == "collect" and _is_mutating(body)
for label, body in _oq_parts(chunks.get(oq, ""))
):
gaps.append(
f"{oq}: `Collect:` must be read-only; it contains a mutating command"
" or manifest."
)
return {"open_question_gaps": gaps}
def check_ruled_out_reasons(ctx: DraftContext) -> dict[str, list[str]]:
"""No-op in the streamlined validator: Ruled Out bullets do not require a minimum word count."""
del ctx
return {"weak_ruled_out": []}
def check_config_remediation(ctx: DraftContext) -> dict[str, list[str]]:
"""Controller-configuration remediations that cannot work as written."""
rem = _join_continuations(ctx.section("remediation"))
problems: list[str] = []
if _CONFIG_KIND_RE.search(rem):
problems.append(
"The controller configuration document is `kind: Configuration`"
" (apiVersion config.kueue.x-k8s.io/...), not `kind:"
" KueueConfiguration` (see"
" https://kueue.sigs.k8s.io/docs/getting-started/installation/ and"
" https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/)."
)
if _CONFIG_PATCH_RE.search(rem):
problems.append(
"`kubectl patch configmap ... controller_manager_config.yaml` replaces"
" the whole `controller_manager_config.yaml` string; unless the patch"
" carries the complete document every other setting is lost. Show the"
" complete edited document (`kubectl edit configmap` or `kubectl apply`"
" of the full ConfigMap) instead."
)
return {"config_remediation_errors": problems}
def _known_kubectl_resources(schema: dict[str, Any]) -> set[str]:
"""Returns lowercase kubectl resource names and shortNames known to the cluster."""
known = set(_CORE_KUBECTL_RESOURCES)
for kind, entry in schema.items():
if kind.startswith("_") or kind == "KueueConfiguration":
continue
low = kind.lower()
known.update({low, low + "s"})
if low.endswith("y"):
known.add(low[:-1] + "ies")
# plural / singular / shortNames as declared by the release's CRDs
# (e.g. `cq`, `lq`, `rf`, `ac`, `queue`, `flavor`).
if isinstance(entry, dict):
known.update(str(n).lower() for n in entry.get("kubectl_names") or [])
return known
def _kubectl_resource(target: str) -> str:
r"""The resource part of a kubectl argument, lower-cased, or "" when not a resource.
`deployment/name` -> `deployment`, `pods|grep` -> `pods`. Flags, `<name>`
placeholders, file paths, a bare `\` and plain English words that follow a
verb in prose yield "", and are not checked against the known kinds.
Args:
target: The token after the kubectl verb.
Returns:
The resource name (possibly group-qualified), or "".
"""
token = re.split(r"[|>&]", target.strip("`'\""), maxsplit=1)[0].lower()
if not _RESOURCE_TOKEN_RE.fullmatch(token) or token in _NOT_A_RESOURCE:
return ""
return token.split("/", 1)[0]
def check_kubectl_resources(ctx: DraftContext) -> dict[str, list[str]]:
"""kubectl commands whose resource argument is not a known kind."""
schema = ctx.schema
known = _known_kubectl_resources(schema)
problems: list[str] = []
seen: set[str] = set()
remediation = _join_continuations(ctx.section("remediation"))
for m in _KUBECTL_RE.finditer(remediation):
verb, target = m.group(1), m.group(2).strip("`'\"")
resource = _kubectl_resource(target)
if not resource:
continue
base, _, group = resource.partition(".")
if (
group
and group != "kueue.x-k8s.io"
and not group.endswith(".kueue.x-k8s.io")
):
continue
if base in known or base in seen:
continue
seen.add(base)
hint = ""
if base in (
"configuration",
"kueueconfiguration",
"config",
"configurations",
):
hint = (
" KueueConfiguration is not an API resource: edit the controller"
" ConfigMap (data.controller_manager_config.yaml) and restart the"
" controller deployment."
)
elif schema.get("_schema_unavailable"):
# Without a release schema the set of Kueue kinds is unknown; only the
# structural KueueConfiguration mistake above can be asserted.
continue
problems.append(
f"`kubectl {verb} {target}`: unknown resource {base!r}.{hint}"
)
return {"unknown_kubectl_resources": problems}
# Terms that, in a root-cause chunk, indicate a rejection or terminal signal
# rather than a configuration observation. Taken from Kueue's own condition
# reasons and controller messages (Workload conditions, flavorassigner / TAS /
# preemption / PodsReady messages) and from kube-scheduler / autoscaler event
# reasons.
_REJECTION_SIGNAL_RE = re.compile(
# First letters of the alternatives below: one cheap test per position
# before the alternation is tried (keep in sync when adding a term).
r"(?=[acdefilnpqrsuw])(?:"
r"insufficient (?:unused )?quota|couldn't assign flavors|doesn't allow to"
r" fit|allows to fit only|"
r"does not contain the requested level|supports only"
r" TopologyAwareScheduling|unavailable in ClusterQueue|"
r"Inadmissible|QuotaReserved=False|Admitted=False|Evicted|PodsReadyTimeout|RequeuingLimitExceeded|Deactivated|"
r"Preempted|NotTriggerScaleUp|FailedScheduling|Unschedulable|ImagePullBackOff|CrashLoopBackOff|"
r"strict decoding error|unknown field|failed calling"
r" webhook|ProvisioningRequest.{0,40}(?:Failed|Expired|not"
r" ready|Provisioned=False)|"
r"NotReady|LocalQueue .{0,40}(?:doesn't exist|not"
r" found|Inactive)|ClusterQueue .{0,40}Inactive|"
r"reason=Pending|WARNING_EVENT|WORKLOAD_TERMINAL_EVENT|\bWarning\b)",
re.IGNORECASE,
)
# Observations that are not rejections by themselves.
_OBSERVATION_ONLY_RE = re.compile(
r"nominalQuota|allocatable|ttlSecondsAfterFinished|blockAdmission|borrowingLimit|lendingLimit|weight",
re.IGNORECASE,
)
def check_root_cause_evidence(ctx: DraftContext) -> dict[str, list[str]]:
"""Warns when an `RC<n>` chunk cites no rejection or terminal signal.
A root cause written only from configuration observations (quota sizes, TTLs,
limits) with no rejection fact in its chunk or in the Observations it points
to is reported under `unsupported_root_causes`. This never fails the draft; it
tells the author which RC still lacks a fact that ties the setting to the
failure.
Args:
ctx: Draft report context and parsed sections.
Returns:
A dict mapping `"unsupported_root_causes"` to advisory warning strings.
"""
rc_section = ctx.section("root cause")
if not rc_section:
return {"unsupported_root_causes": []}
observations = ctx.section("observations")
ids, chunks = _chunk_by_rc(rc_section)
unsupported: list[str] = []
for rc_id in ids:
chunk = chunks.get(rc_id, "")
if _REJECTION_SIGNAL_RE.search(chunk):
continue
# Follow fact ids ([S12], [L3]) cited in the chunk into Observations.
cited = re.findall(r"(?<![A-Za-z0-9-])([SL]\d{1,3})(?![0-9])", chunk)
cited_text = " ".join(
line
for line in observations.splitlines()
if any(_mentions_id(line, c) for c in cited)
)
if cited and _REJECTION_SIGNAL_RE.search(cited_text):
continue
if _OBSERVATION_ONLY_RE.search(chunk) or not cited:
unsupported.append(
f"{rc_id}: no rejection or terminal signal (condition reason,"
" controller message, Warning event) is cited in this root cause"
+ (" or in the Observations it references" if cited else "")
+ "; a configuration value alone is an observation."
)
return {"unsupported_root_causes": unsupported}
def check_schema_warnings(ctx: DraftContext) -> dict[str, list[str]]:
"""YAML manifests under `#### Remediation` conform to the detected release's field names."""
return {
"schema_warnings": yaml_checks.check_remediation_yaml(
ctx.draft_text, ctx.schema, ctx.version_info
)
}
REPORT_GATES: tuple[ReportGate, ...] = (
check_headers,
check_graph_coverage,
check_evidence_grounding,
check_fact_coverage,
check_remediation_mapping,
check_open_questions,
check_ruled_out_reasons,
check_config_remediation,
check_kubectl_resources,
check_root_cause_evidence,
check_schema_warnings,
)
def run_report_gates(ctx: DraftContext) -> dict[str, list[Any]]:
"""Applies `REPORT_GATES` in order; each gate contributes its own report key(s)."""
merged: dict[str, list[Any]] = {}
for gate in REPORT_GATES:
merged.update(gate(ctx))
return merged
report_output.py 20.9 KB
"""Shared output helpers for the gke-kueue-troubleshooting scripts.
Agent harnesses show only a limited window of a command's stdout (commonly
8–30 KB, often head + tail with the middle cut out). The scripts therefore:
* always write the complete report to a file next to the ledger
(``<ledger_dir>/gke-kueue-troubleshooting-reports/<stem>-<utc
timestamp>.<ext>``), and
* print a digest ordered most-important-first whose size is bounded by
``--max-output-bytes``; the first key of the digest is ``full_report_file``
so the reader can open the dropped parts with a file viewer.
Nothing here depends on third-party packages.
"""
from __future__ import annotations
import datetime as _dt
import json
import os
import re
import stat
import sys
import tempfile
from typing import Any, Callable
try:
import fcntl # pylint: disable=g-import-not-at-top
except ImportError: # pragma: no cover - non-POSIX fallback
fcntl = None # type: ignore[assignment]
REPORT_DIR_NAME = "gke-kueue-troubleshooting-reports"
_SCHEMA_META_KEYS = ("_detected_kueue_version",)
# Namespaces whose objects are platform housekeeping and never part of a Kueue
# admission path. Only the upstream Kubernetes namespaces are built in; add
# provider or in-house add-on namespaces with --ignore-namespaces or the
# GKE_KUEUE_TROUBLESHOOTING_IGNORE_NAMESPACES environment variable
# (comma-separated).
_UPSTREAM_ADDON_NAMESPACES = frozenset(
{"kube-system", "kube-node-lease", "kube-public"}
)
def is_regular_file(path: str) -> bool:
"""True only for regular files (rejects symlinks, FIFOs, devices, sockets)."""
try:
return stat.S_ISREG(os.lstat(path).st_mode)
except OSError:
return False
def _env(primary: str, legacy: str = "", default: str = "") -> str:
"""Reads `primary` env var first, falling back to `legacy`, then `default`."""
val = os.getenv(primary, "").strip()
if val:
return val
if legacy:
val = os.getenv(legacy, "").strip()
if val:
return val
return default
def ignored_namespaces() -> frozenset[str]:
"""Operator-supplied namespaces to treat as platform add-ons (env var, comma-separated)."""
raw = _env(
"GKE_KUEUE_TROUBLESHOOTING_IGNORE_NAMESPACES",
"KUEUE_DIAGNOSE_IGNORE_NAMESPACES",
)
return frozenset(x.strip() for x in raw.split(",") if x.strip())
def is_managed_addon_namespace(namespace: str | None) -> bool:
"""Returns True for upstream `kube-*` or operator-ignored add-on namespaces.
The namespace Kueue runs in (`--kueue-namespace` /
GKE_KUEUE_TROUBLESHOOTING_NAMESPACE, default kueue-system) is never treated as
an add-on namespace.
Args:
namespace: Kubernetes namespace name to check.
Returns:
True if `namespace` is a managed add-on namespace, False otherwise.
"""
kueue_ns = _env(
"GKE_KUEUE_TROUBLESHOOTING_NAMESPACE",
"KUEUE_DIAGNOSE_NAMESPACE",
"kueue-system",
)
if not namespace or namespace == kueue_ns:
return False
return (
namespace in _UPSTREAM_ADDON_NAMESPACES
or namespace in ignored_namespaces()
)
def add_kueue_version_arguments(parser, *, live_crds: bool = False) -> None:
"""--kueue-version / --api-version (+ --load-live-crds) with the shared env defaults."""
parser.add_argument(
"--kueue-version",
default=_env(
"GKE_KUEUE_TROUBLESHOOTING_KUEUE_VERSION",
"KUEUE_DIAGNOSE_KUEUE_VERSION",
),
help="Explicit Kueue release version override (e.g. v0.10.0, v0.19.4)",
)
parser.add_argument(
"--api-version",
default=_env(
"GKE_KUEUE_TROUBLESHOOTING_API_VERSION", "KUEUE_DIAGNOSE_API_VERSION"
),
help="Explicit Kueue API version override (e.g. v1beta1, v1beta2)",
)
if live_crds:
parser.add_argument(
"--load-live-crds",
action="store_true",
help=(
"Force loading OpenAPI v3 schemas from the live cluster's CRDs"
" (default in --mode live)"
),
)
def add_no_remote_schema_argument(parser) -> None:
parser.add_argument(
"--no-remote-schema",
action="store_true",
help=(
"Never download release schemas (same as"
" GKE_KUEUE_TROUBLESHOOTING_NO_REMOTE_SCHEMA=1)"
),
)
def apply_no_remote_schema(args) -> None:
"""Exports --no-remote-schema so every module (and child process) honours it."""
if getattr(args, "no_remote_schema", False):
os.environ["GKE_KUEUE_TROUBLESHOOTING_NO_REMOTE_SCHEMA"] = "1"
os.environ["KUEUE_DIAGNOSE_NO_REMOTE_SCHEMA"] = "1"
def add_kueue_namespace_argument(parser, help_text: str) -> None:
parser.add_argument(
"--kueue-namespace",
default=_env(
"GKE_KUEUE_TROUBLESHOOTING_NAMESPACE",
"KUEUE_DIAGNOSE_NAMESPACE",
"kueue-system",
),
help=help_text,
)
def apply_kueue_namespace(args) -> None:
"""Exports --kueue-namespace so the noise rules never drop Kueue's own namespace."""
if getattr(args, "kueue_namespace", ""):
os.environ["GKE_KUEUE_TROUBLESHOOTING_NAMESPACE"] = args.kueue_namespace
os.environ["KUEUE_DIAGNOSE_NAMESPACE"] = args.kueue_namespace
def add_ledger_path_argument(parser, help_text: str, *aliases: str) -> None:
parser.add_argument(
"--ledger-path",
*aliases,
dest="ledger_path",
default=_env(
"GKE_KUEUE_TROUBLESHOOTING_LEDGER_PATH", "KUEUE_DIAGNOSE_LEDGER_PATH"
),
help=help_text,
)
def add_max_output_bytes_argument(
parser, default_bytes: int, help_text: str
) -> None:
parser.add_argument(
"--max-output-bytes",
type=int,
default=int(
_env(
"GKE_KUEUE_TROUBLESHOOTING_MAX_OUTPUT_BYTES",
"KUEUE_DIAGNOSE_MAX_OUTPUT_BYTES",
str(default_bytes),
)
),
help=help_text,
)
def load_ledger(ledger_path: str, *, strict: bool = True) -> Any:
"""Loads the ledger JSON file, or returns a fresh empty ledger if unreadable.
With `strict` (default) a stored value that is not a mapping is also replaced
by the empty ledger; the lenient form returns whatever was stored.
Args:
ledger_path: Path to the ledger JSON file.
strict: Whether non-dict JSON values are replaced with an empty ledger.
Returns:
The parsed ledger mapping (or stored JSON value when `strict=False`).
"""
empty: dict[str, Any] = {
"referenced": [],
"inspected": [],
"tool_outputs": [],
}
if not os.path.exists(ledger_path):
return empty
try:
with open(ledger_path, "r", encoding="utf-8") as f:
data = json.load(f)
except (OSError, json.JSONDecodeError):
return empty
if strict and not isinstance(data, dict):
return empty
return data
def emit_error(
message: str, next_step: str, *, render, stderr_prefix: str = ""
) -> int:
"""Prints `{error, next_step}` with the caller's renderer and the message on stderr; returns 1."""
sys.stdout.write(render({"error": message, "next_step": next_step}))
sys.stderr.write(f"{stderr_prefix}{message}\n")
return 1
def add_ignore_namespaces_argument(parser) -> None:
"""Registers --ignore-namespaces; the value is exported so every module sees it."""
parser.add_argument(
"--ignore-namespaces",
default=_env(
"GKE_KUEUE_TROUBLESHOOTING_IGNORE_NAMESPACES",
"KUEUE_DIAGNOSE_IGNORE_NAMESPACES",
),
help=(
"Comma-separated namespaces of platform add-ons to treat as noise in"
" addition to kube-system, kube-public and kube-node-lease (same as"
" GKE_KUEUE_TROUBLESHOOTING_IGNORE_NAMESPACES)"
),
)
def apply_ignore_namespaces(args) -> None:
if getattr(args, "ignore_namespaces", ""):
os.environ["GKE_KUEUE_TROUBLESHOOTING_IGNORE_NAMESPACES"] = (
args.ignore_namespaces
)
os.environ["KUEUE_DIAGNOSE_IGNORE_NAMESPACES"] = args.ignore_namespaces
_QUANTITY_SUFFIX = {
"m": 1e-3,
"k": 1e3,
"M": 1e6,
"G": 1e9,
"T": 1e12,
"P": 1e15,
"Ki": 2**10,
"Mi": 2**20,
"Gi": 2**30,
"Ti": 2**40,
"Pi": 2**50,
}
def parse_quantity(value: Any) -> float | None:
"""Parses a Kubernetes quantity (`8`, `500m`, `2Gi`, `1k`) into a float; None if unparsable."""
if value is None or isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return float(value)
s = str(value).strip()
if len(s) > 64:
return None
m = re.fullmatch(r"([0-9]+(?:\.[0-9]+)?|\.[0-9]+)([a-zA-Z]*)", s)
if not m:
return None
num, suffix = m.group(1), m.group(2)
if not suffix:
return float(num)
if suffix in _QUANTITY_SUFFIX:
return float(num) * _QUANTITY_SUFFIX[suffix]
return None
def fmt_num(x: float) -> str:
return str(int(x)) if float(x).is_integer() else f"{x:g}"
def fmt_quantity(x: float | None, resource: str) -> str:
"""Formats a parsed quantity for humans: memory/storage-like resources in Gi, everything else as a number."""
if x is None:
return "n/a"
if resource in ("memory", "ephemeral-storage") or resource.endswith(
"storage"
):
if x == 0:
return "0Gi"
for unit, power in (("Pi", 50), ("Ti", 40), ("Gi", 30)):
v = x / 2**power
if v >= 1:
return f"{v:.6g}{unit}"
return f"{x / 2**20:.6g}Mi"
return fmt_num(x)
def report_dir_for(ledger_path: str | None) -> str:
"""Returns the directory where full reports are written for this ledger."""
if ledger_path:
base = os.path.dirname(os.path.abspath(ledger_path))
else:
base = tempfile.gettempdir()
return os.path.join(base, REPORT_DIR_NAME)
def write_full_report(
ledger_path: str | None, stem: str, text: str, ext: str
) -> str:
"""Atomically writes `text` to a new, uniquely named report file and returns its path."""
out_dir = report_dir_for(ledger_path)
os.makedirs(out_dir, exist_ok=True)
stamp = _dt.datetime.now(_dt.timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
path = os.path.join(out_dir, f"{stem}-{stamp}.{ext}")
tmp = f"{path}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
f.write(text)
os.replace(tmp, path)
return path
def compact_schema_reference(
schema_ref: dict[str, Any],
) -> tuple[dict[str, Any], int]:
"""Drops per-kind `valid_fields` lists, keeping version info and invariants.
The full field lists stay in the full report and are available via
`snapshot.py --action explain --kind <Kind>`.
Args:
schema_ref: Active API schema reference mapping keyed by Kind.
Returns:
A `(compacted_copy, dropped_kind_count)` tuple.
"""
if not isinstance(schema_ref, dict):
return schema_ref, 0
out: dict[str, Any] = {}
dropped = 0
for kind, body in schema_ref.items():
if kind in _SCHEMA_META_KEYS or not isinstance(body, dict):
out[kind] = body
continue
slim = {k: v for k, v in body.items() if k != "valid_fields"}
if "valid_fields" in body:
slim["valid_fields"] = (
f"<{len(body['valid_fields'])} fields omitted; see full_report_file"
f" or `snapshot.py --action explain --kind {kind}`>"
)
dropped += 1
out[kind] = slim
return out, dropped
def truncation_note(
full_report_file: str,
max_output_bytes: int,
dropped: dict[str, Any],
hint: str,
) -> dict[str, Any]:
"""Builds the standard `truncated` block appended to a budgeted digest."""
return {
"dropped_items": dropped,
"max_output_bytes": max_output_bytes,
"full_report_file": full_report_file,
"hint": hint,
}
# A trim step shrinks the digest by one notch (drop a few list entries, halve a
# dict, compact a sub-document) and returns True; it returns False when it has
# nothing left to remove. Steps record what they dropped themselves (closures
# over a shared bookkeeping object) so the caller can build the `truncated`
# note from it.
TrimStep = Callable[[dict[str, Any]], bool]
# Room reserved for the `truncated` note appended once shrinking is done, and
# the smallest budget a digest is ever shrunk to.
_TRUNCATION_NOTE_RESERVE = 1500
_MIN_DIGEST_BUDGET = 1000
def serialized_size(payload: Any) -> int:
"""Size in bytes of `payload` as the scripts print it (`json.dumps(indent=2)`)."""
return len(json.dumps(payload, indent=2).encode("utf-8"))
def apply_output_cap(
payload: dict[str, Any],
max_bytes: int,
trim_steps: list[TrimStep],
note: Callable[[], dict[str, Any] | None] | None = None,
*,
size: Callable[[Any], int] = serialized_size,
skip_if_fits: bool = True,
) -> dict[str, Any]:
"""Shrinks `payload` in place until its serialised size fits `max_bytes`.
Applies each step in `trim_steps` repeatedly until the budget (`max_bytes`
minus room for `truncated`) is met or all steps are exhausted, then stores
`note()` under `payload["truncated"]` if non-empty.
Args:
payload: Digest dictionary to shrink in place.
max_bytes: Maximum allowed serialised byte size.
trim_steps: Ordered callables that each remove one notch and return True.
note: Optional zero-arg builder for the `truncated` metadata block.
size: Byte-size measurer matching the caller's output format.
skip_if_fits: Return `payload` untouched if it already fits `max_bytes`.
Returns:
The mutated `payload` dictionary.
"""
if skip_if_fits and size(payload) <= max_bytes:
return payload
budget = max(_MIN_DIGEST_BUDGET, max_bytes - _TRUNCATION_NOTE_RESERVE)
for step in trim_steps:
while size(payload) > budget and step(payload):
pass
if size(payload) <= budget:
break
block = note() if note is not None else None
if block:
payload["truncated"] = block
return payload
_TAGGED_RE = re.compile(r"^\[[SL]\d+\]")
_PINNED_NOTE_PREFIXES = (
"BUNDLE_COVERAGE:",
"LOG_COVERAGE:",
"SNAPSHOT_INVENTORY:",
"KUEUECONFIGURATION_FACTS:",
"PROVISIONINGREQUESTCONFIG_FACTS",
"ADMISSIONCHECK_FACTS",
"FAIR_SHARING_ARITHMETIC",
"WORKLOAD_LIFECYCLE:",
"WORKLOAD_TIMELINE:",
"WORKLOAD_TERMINAL_EVENT:",
"CLUSTERQUEUE_FACTS",
"NODE_TAINT_FACTS",
"NODE_CONDITION_FACTS",
)
def shrink_untagged_notes(
notes: list[str], step: int = 1
) -> tuple[list[str], int]:
"""Removes up to `step` untagged, non-pinned notes from the tail of `notes`.
Tagged facts (`[S<n>]`/`[L<n>]`) and pinned coverage/config headers are never
removed.
Args:
notes: Fact strings in display order.
step: Maximum number of removable untagged notes to drop.
Returns:
A `(shrunk_notes, removed_count)` tuple.
"""
out = list(notes)
removed = 0
idx = len(out) - 1
while idx >= 0 and removed < step:
note = out[idx]
if (
isinstance(note, str)
and not _TAGGED_RE.match(note)
and not note.startswith("...")
and not note.startswith(_PINNED_NOTE_PREFIXES)
):
del out[idx]
removed += 1
idx -= 1
return out, removed
def untagged_trailer(removed: int, what: str) -> str:
"""Trailer line appended to a shrunk fact list."""
return (
f"... {removed} untagged {what} omitted from this digest (all tagged"
" facts kept); see full_report_file"
)
# ---------------------------------------------------------------------------
# Fact ids
#
# Each script tags the facts a report must explicitly classify (status
# conditions, Warning events, deletions, audit mutations, log-derived facts)
# with a short id such as ``[S3]`` (snapshot) or ``[L7]`` (trace_logs). The id
# -> fact mapping is stored in the ledger under ``facts`` as a stable reading
# aid across re-runs of a script within one investigation: the same ``key``
# always maps to the same id.
# ---------------------------------------------------------------------------
MAX_TRACKED_FACTS_PER_SOURCE = 18
MAX_TRACKED_FACTS_TOTAL = 28
def _atomic_write_json(path: str, payload: Any) -> None:
"""Writes `payload` as indented JSON via a sibling temp file and atomic replace."""
parent = os.path.dirname(os.path.abspath(path))
os.makedirs(parent, exist_ok=True)
fd, tmp_path = tempfile.mkstemp(prefix=".ledger-", suffix=".tmp", dir=parent)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2)
os.replace(tmp_path, path)
except BaseException:
try:
os.unlink(tmp_path)
except OSError:
pass
raise
def mutate_ledger(
ledger_path: str,
mutate: Callable[[dict[str, Any]], Any],
*,
strict: bool = True,
) -> dict[str, Any]:
"""Atomically loads, mutates, and persists `ledger_path` under an exclusive lock.
If `mutate` returns `False` explicitly, the disk write is skipped while still
holding the lock across the read.
Args:
ledger_path: Path to the ledger JSON file.
mutate: Callback mutating the loaded ledger dict in place.
strict: Passed through to `load_ledger` when reading existing state.
Returns:
The resulting ledger dictionary after `mutate` runs.
"""
abs_path = os.path.abspath(ledger_path)
os.makedirs(os.path.dirname(abs_path), exist_ok=True)
lock_path = f"{abs_path}.lock"
with open(lock_path, "a+", encoding="utf-8") as lock_f:
if fcntl is not None:
fcntl.flock(lock_f.fileno(), fcntl.LOCK_EX)
try:
ledger = load_ledger(ledger_path, strict=strict)
if not isinstance(ledger, dict):
ledger = {"referenced": [], "inspected": [], "tool_outputs": []}
mutated = mutate(ledger)
if not (isinstance(mutated, bool) and not mutated):
_atomic_write_json(ledger_path, ledger)
return ledger
finally:
if fcntl is not None:
fcntl.flock(lock_f.fileno(), fcntl.LOCK_UN)
def _fact_core(key: str) -> str:
"""The part of a key that is comparable across sources (drops the category prefix)."""
return key.split(":", 1)[1] if ":" in key else key
def _apply_register_facts(
ledger: dict[str, Any],
prefix: str,
facts: list[tuple[str, str]],
max_tracked: int,
max_total: int,
) -> tuple[dict[str, str], bool]:
"""Applies capped fact ID registration to `ledger` in place."""
all_existing = [
f for f in ledger.get("facts", []) if isinstance(f, dict) and "key" in f
]
existing = [
f for f in all_existing if str(f.get("id", "")).startswith(prefix)
]
by_key = {str(f["key"]): str(f["id"]) for f in existing}
by_core = {_fact_core(str(f["key"])): str(f["id"]) for f in all_existing}
next_num = len(existing) + 1
mapping: dict[str, str] = {}
new_entries: list[dict[str, Any]] = []
for key, text in facts:
if key in mapping:
continue
if key in by_key:
mapping[key] = by_key[key]
continue
core = _fact_core(key)
if core in by_core:
mapping[key] = by_core[core]
continue
if (
len(by_key) + len(new_entries) >= max_tracked
or len(all_existing) + len(new_entries) >= max_total
):
continue
fid = f"{prefix}{next_num}"
next_num += 1
mapping[key] = fid
by_core[core] = fid
new_entries.append({"id": fid, "key": key, "text": text[:600]})
if new_entries:
ledger.setdefault("facts", []).extend(new_entries)
return mapping, bool(new_entries)
def register_facts(
ledger_path: str | None,
prefix: str,
facts: list[tuple[str, str]],
max_tracked: int = MAX_TRACKED_FACTS_PER_SOURCE,
max_total: int = MAX_TRACKED_FACTS_TOTAL,
) -> dict[str, str]:
"""Assigns capped, stable ids to `(key, text)` facts in `ledger_path` and returns `{key: id}`."""
if not ledger_path:
mapping, _ = _apply_register_facts(
{}, prefix, facts, max_tracked, max_total
)
return mapping
result_holder: dict[str, dict[str, str]] = {}
def _mutate(ledger: dict[str, Any]) -> bool:
mapping, changed = _apply_register_facts(
ledger, prefix, facts, max_tracked, max_total
)
result_holder["mapping"] = mapping
return changed
mutate_ledger(ledger_path, _mutate, strict=True)
return result_holder.get("mapping", {})
def tag(mapping: dict[str, str], key: str | None, text: str) -> str:
"""Prefixes `text` with its fact id when the key is tracked."""
if key and key in mapping:
return f"[{mapping[key]}] {text}"
return text
_QUOTED_RE = re.compile(r"\"[^\"]*\"|'[^']*'|`[^`]*`")
_ALNUM_TOKEN_RE = re.compile(r"\b[a-z0-9]{5,}\b")
_NUMBER_RE = re.compile(r"\d+(?:\.\d+)?")
def _mask_hexish(match: re.Match[str]) -> str:
tok = match.group(0)
return "<id>" if any(ch.isdigit() for ch in tok[:-4]) else tok
def fact_group_key(
category: str, kind: str, reason: str, message: str, width: int = 72
) -> str:
"""Builds a shape-normalised grouping key for a message-bearing fact.
Quoted strings, hex-like suffixes, and numbers are masked before taking the
first `width` characters so equivalent messages share one fact id.
Args:
category: Fact category prefix (e.g. `event`, `logerr`).
kind: Involved Kubernetes object kind, or empty string.
reason: Event or condition reason string.
message: Raw message text to normalise.
width: Maximum normalised message prefix length.
Returns:
The composite `<category>:<kind>:<reason>:<normalised_prefix>` key.
"""
norm = _QUOTED_RE.sub("<q>", message)
norm = _ALNUM_TOKEN_RE.sub(_mask_hexish, norm)
norm = _NUMBER_RE.sub("#", norm)
norm = re.sub(r"\s+", " ", norm).strip().lower()
return f"{category}:{kind}:{reason}:{norm[:width]}"
snapshot.py 37.5 KB
#!/usr/bin/env python3
"""Kueue cluster-state snapshot compaction for the `gke-kueue-troubleshooting` skill.
Collects the Kueue admission graph (Workloads, LocalQueues, ClusterQueues,
Cohorts,
ResourceFlavors, AdmissionChecks, ProvisioningRequestConfigs, Topologies, the
controller ConfigMap) plus the Jobs, Pods, Events and Nodes around it, and
emits:
* `active_api_schema_reference` — CRD / KueueConfiguration schema for the
detected
Kueue release (see `kueue_schema.py`), so the agent writes remediation YAML
in
the right API version;
* `derived_graph_diagnostics` — neutral, mechanically derived facts
(inventory,
Warning events, quota arithmetic, label matching, configuration values). The
script never ranks causes or prescribes report content;
* `kueue_graph_objects` — sanitised, compacted objects, priority-ordered and
capped
by `--max-output-bytes`.
`--action explain --kind <Kind[.field.path]>` answers schema questions for the
detected version using the loaded schema (live CRDs in `live` mode, or
offline/cached schemas in `offline_data` / `logs_archive`).
Sources (`--mode`): `live` via `kubectl`, `offline_data` from a directory of
manifests, `logs_archive` (no manifests) delegates to `trace_logs.py`. No cloud
SDKs or provider CLIs are used.
Module map: `snapshot_loaders.py` reads, sanitises, filters and groups objects
and maintains the ledger; `snapshot_facts.py` holds the fact emitters;
`k8s_objects.py` provides tolerant accessors for Kubernetes dicts. This module
keeps the CLI, the fact orchestrator and the stdout digest budget.
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
from typing import Any
import yaml
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if SCRIPT_DIR not in sys.path:
sys.path.insert(0, SCRIPT_DIR)
# pylint: disable=g-import-not-at-top,wrong-import-position,g-bad-import-order
import k8s_objects
import kueue_schema
import report_output
import snapshot_facts
import snapshot_loaders
# pylint: enable=g-import-not-at-top,wrong-import-position,g-bad-import-order
FactContext = snapshot_facts.FactContext
LedgerInputs = snapshot_loaders.LedgerInputs
LoadError = snapshot_loaders.LoadError
compact_managed_fields = k8s_objects.compact_managed_fields
filter_and_sort_snapshot_items = snapshot_loaders.filter_and_sort_snapshot_items
group_bulk_objects = snapshot_loaders.group_bulk_objects
load_items = snapshot_loaders.load_items
load_static_items = snapshot_loaders.load_static_items
sample_bulk_groups = snapshot_loaders.sample_bulk_groups
sanitize_and_compact_object = snapshot_loaders.sanitize_and_compact_object
update_ledger = snapshot_loaders.update_ledger
_event_timestamp = k8s_objects.event_timestamp
__all__ = [
"FactContext",
"LedgerInputs",
"LoadError",
"compact_managed_fields",
"compute_derived_diagnostics",
"compute_derived_facts",
"filter_and_sort_snapshot_items",
"group_bulk_objects",
"load_items",
"load_static_items",
"main",
"sample_bulk_groups",
"sanitize_and_compact_object",
"update_ledger",
]
_parse_quantity = report_output.parse_quantity
# Order in which keyed facts receive ids when the per-source cap applies
# (lower = earlier). Grouped Warning events come last because they are the
# most numerous and usually restate a condition already listed.
_FACT_PRIORITY = {
"condition": 0,
"config": 0,
"provreq": 1,
"workload-pods": 1,
"pod-status": 1,
"job-spec": 1,
"unreferenced-ac": 1,
"nodeselector": 1,
"tas-domains": 1,
"node-cond": 1,
"queue-chain": 1,
"podset-flavor": 2,
"cohort-overcommit": 2,
"fair-sharing": 2,
"cohort-layout": 3,
"deletion": 3,
"workload-lifecycle": 4,
"inventory": 4,
"event": 6,
}
_YAML_WIDTH = 100000
class _PyFullDumper(yaml.SafeDumper):
"""Safe YAML dumper that writes every object out in full.
The stock dumper turns an object that is referenced twice into `&id001` /
`*id001`. That is fine in the digest, which is read as a whole, but not in
the full report, which is read by line range: the anchor is usually outside
the range.
"""
def ignore_aliases(self, data: Any) -> bool:
return True
class _CFullDumper(getattr(yaml, "CSafeDumper", yaml.SafeDumper)):
"""`_PyFullDumper` on the libyaml emitter."""
def ignore_aliases(self, data: Any) -> bool:
return True
# libyaml is used when PyYAML was built with it. Both emitters write the same
# text for ordinary manifests and equivalent YAML otherwise (they differ on
# mapping keys that are empty, 128 or more characters long or not printable
# ASCII, and on where a string longer than the line width is folded).
_use_libyaml = hasattr(yaml, "CSafeDumper")
def _dumper(aliases: bool) -> Any:
if aliases:
return yaml.CSafeDumper if _use_libyaml else yaml.SafeDumper
return _CFullDumper if _use_libyaml else _PyFullDumper
def _dump(payload: Any, aliases: bool = False) -> str:
"""YAML text of `payload`; `aliases` keeps `&id001` anchors for shared objects (digest only)."""
global _use_libyaml # pylint: disable=global-statement
try:
return yaml.dump(
payload, Dumper=_dumper(aliases), sort_keys=False, width=_YAML_WIDTH
)
except (UnicodeError, yaml.YAMLError):
if not _use_libyaml:
raise
# libyaml refuses what the Python emitter escapes (a lone surrogate from a
# JSON `\ud800` escape). The switch is kept for the rest of the run, so the
# sizes measured while trimming and the printed text come from one emitter.
_use_libyaml = False
return yaml.dump(
payload, Dumper=_dumper(aliases), sort_keys=False, width=_YAML_WIDTH
)
# ---------------------------------------------------------------------------
# Derived facts
# ---------------------------------------------------------------------------
def compute_derived_diagnostics(items: list[dict[str, Any]]) -> list[str]:
"""Returns the derived facts as plain strings (see `compute_derived_facts`)."""
return [text for _, text in compute_derived_facts(items)]
def compute_derived_facts(
items: list[dict[str, Any]],
) -> list[tuple[str | None, str]]:
"""Computes neutral, verifiable facts about the Kueue admission graph.
Every entry is `(key, statement)`. The statement is derived mechanically from
the snapshot (counts, status conditions, quota arithmetic, label matching,
configuration values) plus, where useful, one sentence of version-independent
Kueue API semantics. `key` is non-None for facts the report is expected to
classify explicitly (conditions, Warning events, deletions, request/flavor
mismatches); it groups equivalent facts so they share one id. The function
does NOT rank causes, recommend fixes, or tell the reader what to include in
or exclude from a report — interpretation is left to the diagnosing agent.
The sections live in `snapshot_facts.FACT_EMITTERS`; their order is the
order of the facts in the digest.
Args:
items: Raw Kubernetes object mappings in the snapshot.
Returns:
Ordered `(group_key_or_none, fact_statement)` tuples.
"""
ctx = FactContext.from_items(items)
for emit in snapshot_facts.FACT_EMITTERS:
try:
emit(ctx)
except Exception as exc: # pylint: disable=broad-exception-caught
# One malformed object stops its own section only; the facts of every
# other section (and those this one had already added) are kept.
ctx.add(None, _unavailable_note(getattr(emit, "__name__", ""), exc))
return ctx.notes
def _unavailable_note(section: str, exc: Exception) -> str:
detail = " ".join(f"{type(exc).__name__}: {exc}".split())[:300]
scope = f" ({section})" if section else ""
return (
f"DERIVED_DIAGNOSTICS_UNAVAILABLE{scope}: {detail}; the facts of this"
" section are incomplete"
)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"Compacts Kueue cluster state (live or from a bundle) into a"
" schema-annotated snapshot with derived facts."
)
)
_add_selection_arguments(parser)
_add_schema_and_output_arguments(parser)
report_output.add_ignore_namespaces_argument(parser)
return parser
def _add_selection_arguments(parser: argparse.ArgumentParser) -> None:
"""Source mode, action and object selection flags."""
parser.add_argument(
"--mode",
choices=["live", "offline_data", "logs_archive"],
default=report_output._env( # pylint: disable=protected-access
"GKE_KUEUE_TROUBLESHOOTING_MODE", "KUEUE_DIAGNOSE_MODE", "live"
),
help=(
"live: kubectl; offline_data: directory of YAML/JSON manifests (+"
" optional logs/); logs_archive: no manifests available, delegates to"
" trace_logs.py"
),
)
parser.add_argument(
"--action",
choices=["snapshot", "list", "get", "events", "explain"],
default="",
help=(
"Action: 'snapshot', 'list', 'get', 'events', or 'explain' (queries"
" version-aware Kueue CRD schema)."
),
)
parser.add_argument(
"--kind",
default="all",
help=(
"Kubernetes resource kind (or dotted field path for --action explain,"
" e.g. ClusterQueue.spec.preemption)"
),
)
parser.add_argument("--name", default="", help="Resource name (for get)")
parser.add_argument(
"-n",
"--namespace",
dest="namespace",
default="",
help="Optional namespace",
)
parser.add_argument(
"--data-path",
"--source",
dest="data_path",
default=report_output._env( # pylint: disable=protected-access
"GKE_KUEUE_TROUBLESHOOTING_DATA_PATH", "KUEUE_DIAGNOSE_DATA_PATH"
),
help=(
"Path to a directory (or single file) of YAML/JSON manifests for"
" offline_data"
),
)
report_output.add_ledger_path_argument(
parser, "Optional path to coverage_ledger.json", "--ledger"
)
def _add_schema_and_output_arguments(parser: argparse.ArgumentParser) -> None:
"""Kueue version / schema source flags and the stdout budget."""
report_output.add_kueue_version_arguments(parser, live_crds=True)
report_output.add_no_remote_schema_argument(parser)
report_output.add_kueue_namespace_argument(
parser,
"Namespace where the Kueue controller and kueue-manager-config live"
" (default kueue-system)",
)
report_output.add_max_output_bytes_argument(
parser,
48000,
"Cap on the stdout digest (schema field lists, then lowest-priority"
" objects are dropped); the complete snapshot is always written to"
" full_report_file next to the ledger",
)
def _print_error(message: str, next_step: str) -> int:
return report_output.emit_error(message, next_step, render=_dump)
def _live_crds_arg(args: argparse.Namespace) -> bool | None:
return True if args.load_live_crds else None
def _is_snapshot_request(args: argparse.Namespace, action: str) -> bool:
return action == "snapshot" or args.kind.lower() == "all"
def _resolve_action(args: argparse.Namespace) -> str:
if args.action:
return args.action
if args.kind.lower() in ("all", "snapshot", ""):
return "snapshot"
if args.kind.lower() in ("event", "events"):
return "events"
if args.name:
return "get"
return "get" if args.kind else "snapshot"
def run_explain(args: argparse.Namespace) -> int:
"""`--action explain`: prints the schema of a Kind / field path for the detected Kueue version."""
ledger_vinfo = None
if (
args.ledger_path
and os.path.exists(args.ledger_path)
and not args.kueue_version
and not args.api_version
):
ledger_vinfo = report_output.load_ledger(args.ledger_path, strict=True).get(
"detected_kueue_version"
)
vinfo = ledger_vinfo or kueue_schema.detect_target_kueue_version(
mode=args.mode,
data_path=args.data_path,
explicit_release_version=args.kueue_version,
explicit_api_version=args.api_version,
kueue_namespace=args.kueue_namespace,
)
out_str = yaml.safe_dump(
kueue_schema.explain_schema_path(
args.kind,
version_info=vinfo,
load_live_crds=_live_crds_arg(args),
),
sort_keys=False,
)
sys.stdout.write(out_str)
return 0
def _run_logs_archive(args: argparse.Namespace) -> int:
"""Delegates `logs_archive` mode to `trace_logs.py` when no manifests exist."""
trace_script = os.path.join(SCRIPT_DIR, "trace_logs.py")
cmd = [
sys.executable,
trace_script,
"--mode",
args.mode,
"--kueue-namespace",
args.kueue_namespace,
]
if args.data_path:
cmd.extend(["--data-path", args.data_path])
if args.ledger_path:
cmd.extend(["--ledger-path", args.ledger_path])
if args.kueue_version:
cmd.extend(["--kueue-version", args.kueue_version])
if args.api_version:
cmd.extend(["--api-version", args.api_version])
res = subprocess.run(cmd, capture_output=True, text=True, check=False)
sys.stdout.write(res.stdout)
if res.returncode != 0:
sys.stderr.write(res.stderr)
return res.returncode
# ---------------------------------------------------------------------------
# list / get / events
# ---------------------------------------------------------------------------
def _condition_summary(cond: dict[str, Any]) -> str:
message = str(cond.get("message") or "")[:120]
return (
f"{cond.get('type')}={cond.get('status')}({cond.get('reason')}:"
f" {message})"
)
def _list_summary_rows(raw_items: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Builds compact kind/namespace/name/conditions rows for the list action."""
summary_rows = []
for x in (sanitize_and_compact_object(x) for x in raw_items):
if not isinstance(x, dict):
continue
m = k8s_objects.metadata(x)
summary_rows.append({
"kind": x.get("kind"),
"namespace": m.get("namespace", ""),
"name": m.get("name", ""),
"conditions": [
_condition_summary(c) for c in k8s_objects.conditions(x)
],
})
return summary_rows
def _compact_keep_dups(obj: dict[str, Any]) -> dict[str, Any]:
compacted = sanitize_and_compact_object(obj)
if isinstance(obj, dict) and obj.get("_yaml_duplicate_keys"):
return {"_yaml_duplicate_keys": obj["_yaml_duplicate_keys"], **compacted}
return compacted
def _print_and_record(out_str: str, inputs: LedgerInputs) -> int:
"""Prints the output and records it in the ledger; a failure of one does not skip the other."""
ledger_error = ""
try:
sys.stdout.write(out_str)
finally:
try:
update_ledger(inputs)
except OSError as exc:
ledger_error = f"{type(exc).__name__}: {exc}"
if ledger_error:
sys.stderr.write(
f"coverage ledger {inputs.ledger_path!r} was not updated:"
f" {ledger_error}\n"
)
return 1
return 0
def run_list_get_events(
args: argparse.Namespace, action: str, raw_obj: dict[str, Any]
) -> int:
"""Prints compacted objects for `list`, `get` and `events` and records them in the ledger."""
if isinstance(raw_obj, dict) and raw_obj.get("kind") == "List":
raw_items = k8s_objects.dict_items(raw_obj.get("items"))
for warning in k8s_objects.as_list(raw_obj.get("_warnings")):
sys.stderr.write(f"warning: {warning}\n")
if action == "list":
out_str = _dump(_list_summary_rows(raw_items))
else:
out_str = _dump([_compact_keep_dups(x) for x in raw_items])
else:
out_str = _dump(_compact_keep_dups(raw_obj))
return _print_and_record(
out_str,
LedgerInputs(
args.ledger_path,
action if action != "snapshot" else "get",
raw_obj,
out_str,
),
)
# ---------------------------------------------------------------------------
# snapshot
# ---------------------------------------------------------------------------
class _DigestBuilder:
"""Assembles the snapshot payload (full report and stdout digest share the layout)."""
def __init__(
self, schema_ref: dict[str, Any], derived_notes: list[str], warnings: Any
) -> None:
self.schema_ref = schema_ref
self.derived_notes = derived_notes
self.warnings = warnings
def payload(
self, groups: dict[str, Any], objects: list[dict[str, Any]]
) -> dict[str, Any]:
"""Returns the ordered snapshot dictionary for the full report or digest."""
# Most decision-relevant sections first: agent harnesses often show only
# the head (and tail) of a command's stdout.
out: dict[str, Any] = {
"detected_kueue_version": self.schema_ref.get("_detected_kueue_version")
}
if self.schema_ref.get("_schema_notice"):
out["schema_notice"] = self.schema_ref["_schema_notice"]
out["derived_graph_diagnostics"] = self.derived_notes
if groups:
out["bulk_object_groups"] = groups
out |= {
"kueue_graph_objects": objects,
"active_api_schema_reference": self.schema_ref,
}
if self.warnings:
out["warnings"] = self.warnings
return out
def _namespace_of(obj: Any) -> str:
ns = k8s_objects.metadata(obj).get("namespace")
return ns if isinstance(ns, str) else ""
def _scoped_snapshot_items(
args: argparse.Namespace, raw_items: list[dict[str, Any]]
) -> list[dict[str, Any]]:
"""Keeps cluster-scoped objects, relevant cluster-level Events, and objects in `--namespace` / `--kueue-namespace`."""
if not args.namespace:
return raw_items
scoped = [
x
for x in raw_items
if not _namespace_of(x)
or _namespace_of(x) in (args.namespace, args.kueue_namespace)
or (
str(x.get("kind") or "") == "Event"
and snapshot_loaders._event_is_relevant(x) # pylint: disable=protected-access
)
]
has_ns_match = any(_namespace_of(x) == args.namespace for x in raw_items)
return scoped if has_ns_match else raw_items
def _fact_input_items(
args: argparse.Namespace,
unfiltered_items: list[dict[str, Any]],
shown_items: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Items the derived facts are computed from: the displayed ones plus healthy workload Pods.
The display filter drops Running/Succeeded Pods without failures to keep
the digest small. Facts that relate a Workload to its Pods need them, so
they are added back for fact computation only. Pods of platform add-on
namespaces stay out, as does everything else the filter removed (add-on
Events, other ConfigMaps), and a `--namespace` scope that applied to the
display applies here too.
Args:
args: Parsed CLI arguments (`namespace`, `kueue_namespace`).
unfiltered_items: Every loaded object.
shown_items: The filtered, scoped objects of the digest.
Returns:
`shown_items` followed by the hidden healthy Pods in scope.
"""
shown = {id(x) for x in shown_items}
scoped = bool(args.namespace) and any(
_namespace_of(x) == args.namespace for x in shown_items
)
hidden_pods = [
x
for x in unfiltered_items
if k8s_objects.kind(x) == "Pod"
and id(x) not in shown
and not report_output.is_managed_addon_namespace(_namespace_of(x))
and (
not scoped
or _namespace_of(x) in (args.namespace, args.kueue_namespace)
)
]
return shown_items + hidden_pods
_MAX_SKIPPED_SHOWN = 8
def _coverage_gap_notes(raw_obj: dict[str, Any]) -> list[str]:
"""The pinned line naming sources the loader could not read (empty when it read everything).
It carries the `BUNDLE_COVERAGE:` prefix, which the digest trimmer never
drops: without it a kind that could not be listed reads as a kind with no
objects.
Args:
raw_obj: The loaded `kind: List` with optional `_skipped_sources`.
Returns:
Zero or one derived-fact line.
"""
skipped = [
str(s)[:120] for s in k8s_objects.as_list(raw_obj.get("_skipped_sources"))
]
if not skipped:
return []
shown = "; ".join(skipped[:_MAX_SKIPPED_SHOWN])
if len(skipped) > _MAX_SKIPPED_SHOWN:
shown += f"; ... {len(skipped) - _MAX_SKIPPED_SHOWN} more"
return [
f"BUNDLE_COVERAGE: partial snapshot, {len(skipped)} source(s) not"
f" loaded: {shown}. Objects from these sources are missing from every"
" fact and object list in this output, and their absence here says"
" nothing about the cluster; the load errors are listed under warnings."
]
def _detect_schema(
args: argparse.Namespace,
present_kinds: set[str],
unfiltered_items: list[dict[str, Any]],
) -> tuple[dict[str, Any], dict[str, Any]]:
"""(detected Kueue version info, active schema reference) for the snapshot."""
detected_vinfo = kueue_schema.detect_target_kueue_version(
mode=args.mode,
raw_items=unfiltered_items,
data_path=args.data_path,
explicit_release_version=args.kueue_version,
explicit_api_version=args.api_version,
)
schema_ref = kueue_schema.get_active_schema_reference(
present_kinds,
version_info=detected_vinfo,
raw_items=unfiltered_items,
load_live_crds=_live_crds_arg(args),
)
if isinstance(schema_ref.get("_detected_kueue_version"), dict):
detected_vinfo.update(schema_ref["_detected_kueue_version"])
return detected_vinfo, schema_ref
def _tagged_derived_notes(
ledger_path: str, raw_items: list[dict[str, Any]]
) -> list[str]:
"""Derived facts with `[S<n>]` ids assigned to keyed facts in `_FACT_PRIORITY` order."""
try:
keyed_facts = compute_derived_facts(raw_items)
except Exception as exc: # pylint: disable=broad-exception-caught
# A malformed Kubernetes object must not abort snapshot generation.
keyed_facts = [(None, _unavailable_note("", exc))]
tracked = sorted(
((k, t) for k, t in keyed_facts if k),
key=lambda kt: _FACT_PRIORITY.get(kt[0].split(":", 1)[0], 9),
)
fact_ids = report_output.register_facts(ledger_path, "S", tracked)
return [report_output.tag(fact_ids, k, t) for k, t in keyed_facts]
class _DigestTrimmer:
"""Trim steps for the stdout digest, applied by `report_output.apply_output_cap`.
Each step removes one notch from the lowest-value part of the digest and
returns True when it removed something; `dropped` records what went, in the
order the steps ran, for the `truncated` note.
"""
def __init__(self, digest: dict[str, Any]):
self.digest = digest
self.dropped: dict[str, Any] = {}
self._groups: dict[str, list[Any]] = {}
def steps(self) -> list[report_output.TrimStep]:
# Least valuable first: per-kind schema field lists, grouped bulk objects
# (rarest signatures at the tail), priority-sorted graph objects, and as a
# last resort untagged derived facts (tagged [S<n>] facts always stay).
return [
self.compact_schema_fields,
*(self._bulk_group_step(key) for key in ("events", "pods", "nodes")),
self.drop_graph_objects,
self.drop_untagged_notes,
]
def compact_schema_fields(self, digest: dict[str, Any]) -> bool:
if "active_api_schema_reference.valid_fields" in self.dropped:
return False
slim, n_slim = report_output.compact_schema_reference(
digest["active_api_schema_reference"]
)
if not n_slim:
return False
digest["active_api_schema_reference"] = slim
self.dropped["active_api_schema_reference.valid_fields"] = n_slim
return True
def _bulk_group_step(self, group_key: str) -> report_output.TrimStep:
"""Returns a trim step that drops a quarter of one bulk object group list."""
def step(digest: dict[str, Any]) -> bool:
groups = self._groups.get(group_key)
if groups is None:
groups = list(
(digest.get("bulk_object_groups") or {}).get(group_key) or []
)
if not groups:
return False
notch = max(1, len(groups) // 4)
groups = groups[:-notch]
self._groups[group_key] = groups
dropped_key = f"bulk_object_groups.{group_key}"
self.dropped[dropped_key] = self.dropped.get(dropped_key, 0) + notch
digest["bulk_object_groups"][group_key] = groups + [
{"omitted_groups": self.dropped[dropped_key]}
]
return True
return step
def drop_graph_objects(self, digest: dict[str, Any]) -> bool:
objects = digest["kueue_graph_objects"]
if len(objects) <= 1:
return False
notch = max(1, len(objects) // 10)
digest["kueue_graph_objects"] = objects[:-notch]
self.dropped["kueue_graph_objects"] = (
self.dropped.get("kueue_graph_objects", 0) + notch
)
return True
def drop_untagged_notes(self, digest: dict[str, Any]) -> bool:
"""Drops a batch of untagged derived facts while keeping all [S<n>] facts."""
notes = digest["derived_graph_diagnostics"]
already = self.dropped.get("derived_graph_diagnostics", 0)
if (
notes
and isinstance(notes[-1], str)
and notes[-1].startswith("... ")
and already
):
notes = notes[:-1]
notes, removed = report_output.shrink_untagged_notes(
notes, step=max(1, len(notes) // 10)
)
if not removed:
return False
self.dropped["derived_graph_diagnostics"] = already + removed
digest["derived_graph_diagnostics"] = notes + [
report_output.untagged_trailer(
self.dropped["derived_graph_diagnostics"], "derived facts"
)
]
return True
def truncation_note(
self, report_file: str, max_output_bytes: int
) -> dict[str, Any] | None:
"""Builds the truncation metadata block if any digest items were dropped."""
if not self.dropped:
return None
dropped_notes = self.dropped.get("derived_graph_diagnostics", 0)
if not dropped_notes:
facts_state = "derived_graph_diagnostics is complete"
else:
facts_state = (
f"derived_graph_diagnostics lost {dropped_notes} untagged facts"
" (every [S<n>] fact is kept)"
)
return report_output.truncation_note(
report_file,
max_output_bytes,
self.dropped,
f"This is a digest; {facts_state}. Dropped items are the"
" lowest-priority objects and the rarest Node/Pod/Event groups. Fetch"
" a specific object with --action get --kind <kind> --name <name>"
" --namespace <ns> (--namespace is not needed for cluster-scoped"
" kinds), re-run with --namespace <ns>, or open full_report_file by"
" line range for one object — do not read the whole file. Do not"
" parse the ledger.",
)
def _yaml_size(payload: Any) -> int:
"""Byte size of `payload` as the digest prints it (anchors for shared objects)."""
return len(_dump(payload, aliases=True).encode("utf-8"))
def _aliasable(value: Any) -> bool:
"""True for values the YAML dumper anchors when it meets the same object twice."""
return not (
value is None
or isinstance(value, (str, bytes, bool, int, float))
or (isinstance(value, tuple) and not value)
)
# One measured piece of the digest: (key path, is a list entry, value).
_Unit = tuple[tuple[str, ...], bool, Any]
# Above this many shared objects anchor names may grow past `id999`, and a
# piece dumped on its own would no longer have the width it has in the digest.
_MAX_FAST_ANCHORS = 900
class _DigestSizer:
"""Exact byte size of the digest YAML without re-serialising it for every trim step.
The digest is cut into units: each top-level section, and each entry of a
list a trim step shortens. In block style the dump of a mapping or sequence
is the concatenation of the dumps of its entries, so a unit that shares no
object with another unit has the same text wherever it is dumped; it is
dumped once, under the keys it has in the digest, and its size is cached.
Units that do share an object (the dumper writes `&id001` once and `*id001`
afterwards) are dumped together, in digest order, and that dump is cached
per set of units. The sizes add up to the size of the real dump as long as
trim steps replace lists by shorter ones and never edit a unit in place.
"""
GROUPS_KEY = "bulk_object_groups"
def __init__(self) -> None:
self._sizes: dict[tuple[Any, ...], int] = {}
self._parts: dict[tuple[Any, ...], tuple[int, list[_Unit]]] = {}
# Everything whose id() is part of a cache key stays referenced, so an id
# is never reused by a newer object.
self._pinned: list[Any] = []
self._owners: dict[int, list[tuple[Any, ...]]] = {}
self._shared: set[tuple[Any, ...]] = set()
self._registered: set[tuple[Any, ...]] = set()
self._anchors = 0
def __call__(self, digest: dict[str, Any]) -> int:
sections = list(self._sections(digest))
for section in sections:
self._register_section(*section)
if self._anchors > _MAX_FAST_ANCHORS or not sections:
return _yaml_size(digest)
total = self._frame_size(
tuple(p for p, v in sections if isinstance(v, list) and v)
)
together: list[_Unit] = []
for section in sections:
size, shared = self._section_part(*section)
total += size
together.extend(shared)
if together:
total += self._memo(
("together", *map(self._key, together)),
lambda: self._joint_size(together),
)
return total
def _sections(self, digest: dict[str, Any]) -> Any:
"""Yields `(key path, value)` for every section; bulk groups count one per group."""
for key, value in digest.items():
if key != self.GROUPS_KEY or not isinstance(value, dict):
yield (key,), value
elif value and all(isinstance(g, list) and g for g in value.values()):
for group_key, group in value.items():
yield (key, group_key), group
else:
# Not the shape the trim steps maintain: measured as one unit, and
# as a fresh copy, since the steps edit this mapping in place.
yield (key,), dict(value)
def _section_units(self, path: tuple[str, ...], value: Any) -> list[_Unit]:
if isinstance(value, list) and value:
return [(path, True, entry) for entry in value]
return [(path, False, value)]
def _key(self, unit: _Unit) -> tuple[Any, ...]:
path, in_list, value = unit
return path, in_list, value if isinstance(value, str) else id(value)
def _memo(self, key: tuple[Any, ...], compute: Any) -> int:
if key not in self._sizes:
self._sizes[key] = compute()
return self._sizes[key]
def _register_section(self, path: tuple[str, ...], value: Any) -> None:
"""Registers every aliasable unit inside one digest section."""
seen_key = ("section", path, id(value))
if seen_key in self._registered:
return
self._registered.add(seen_key)
self._pinned.append(value)
in_section: set[tuple[Any, ...]] = set()
for unit in self._section_units(path, value):
key = self._key(unit)
if key in in_section and _aliasable(unit[2]):
# The same object twice in one list: the second entry is an alias.
self._anchors += key not in self._shared
self._shared.add(key)
in_section.add(key)
self._register(unit)
def _register(self, unit: _Unit) -> None:
"""Records which aliasable objects the unit holds and which units share one."""
key = self._key(unit)
if key in self._registered:
return
self._registered.add(key)
seen: set[int] = set()
stack = [unit[2]]
while stack:
node = stack.pop()
if not _aliasable(node):
continue
if id(node) in seen:
self._anchors += 1
continue
seen.add(id(node))
owners = self._owners.setdefault(id(node), [])
owners.append(key)
if len(owners) > 1:
self._anchors += len(owners) == 2
self._shared.update(owners)
if isinstance(node, dict):
stack.extend(k for k in node if not isinstance(k, str))
stack.extend(node.values())
elif isinstance(node, (list, tuple, set, frozenset)):
stack.extend(node)
def _section_part(
self, path: tuple[str, ...], value: Any
) -> tuple[int, list[_Unit]]:
"""(bytes of the section's unshared units, its units that share objects)."""
part_key = (path, id(value), len(self._shared))
if part_key not in self._parts:
units = self._section_units(path, value)
shared = [u for u in units if self._key(u) in self._shared]
size = sum(
self._memo(("unit", *self._key(u)), lambda u=u: self._joint_size([u]))
for u in units
if self._key(u) not in self._shared
)
self._parts[part_key] = (size, shared)
return self._parts[part_key]
def _skeleton(
self, units: list[_Unit], sentinel_only: bool
) -> dict[str, Any]:
"""A digest-shaped mapping holding `units`; each of their lists ends with a `0` sentinel."""
out: dict[str, Any] = {}
lists: list[list[Any]] = []
for path, in_list, value in units:
parent = out
for key in path[:-1]:
parent = parent.setdefault(key, {})
if not in_list:
if not sentinel_only:
parent[path[-1]] = value
elif path[-1] not in parent:
parent[path[-1]] = [] if sentinel_only else [value]
lists.append(parent[path[-1]])
elif not sentinel_only:
parent[path[-1]].append(value)
for entries in lists:
entries.append(0)
return out
def _joint_size(self, units: list[_Unit]) -> int:
"""Bytes `units` take in the digest: their joint dump minus the key lines and sentinels around them."""
base = self._skeleton(units, sentinel_only=True)
return _yaml_size(self._skeleton(units, sentinel_only=False)) - (
_yaml_size(base) if base else 0
)
def _frame_size(self, list_paths: tuple[tuple[str, ...], ...]) -> int:
"""Bytes of the key lines above the digest's non-empty lists."""
if not list_paths:
return 0
def measure() -> int:
units: list[_Unit] = [(p, True, 0) for p in list_paths]
one = self._skeleton(units, sentinel_only=True)
two = self._skeleton(units + units, sentinel_only=False)
# `one` holds one sentinel per list, `two` three.
return (3 * _yaml_size(one) - _yaml_size(two)) // 2
return self._memo(("frame", list_paths), measure)
def _trim_to_budget(
digest: dict[str, Any], max_output_bytes: int, report_file: str, size: Any
) -> str:
"""Applies digest trim steps under `size` and returns the dumped digest YAML."""
trimmer = _DigestTrimmer(digest)
report_output.apply_output_cap(
digest,
max_output_bytes,
trimmer.steps(),
note=lambda: trimmer.truncation_note(report_file, max_output_bytes),
size=size,
skip_if_fits=False,
)
return _dump(digest, aliases=True)
def _fit_digest_to_budget(
digest: dict[str, Any], max_output_bytes: int, report_file: str
) -> str:
"""Shrinks the digest until it fits `max_output_bytes` and returns the YAML to print."""
# Trim steps replace top-level values and bulk group lists, so this shallow
# copy is enough to start over.
pristine = {
k: dict(v) if k == _DigestSizer.GROUPS_KEY and isinstance(v, dict) else v
for k, v in digest.items()
}
sizer = _DigestSizer()
text = _trim_to_budget(digest, max_output_bytes, report_file, sizer)
if sizer(digest) == len(text.encode("utf-8")):
return text
# The piecewise sizes did not add up to the real dump (a shape the sizer
# does not model). Trim again, measuring the whole digest at every step.
digest.clear()
digest.update(pristine)
return _trim_to_budget(digest, max_output_bytes, report_file, _yaml_size)
def run_snapshot(args: argparse.Namespace, raw_obj: dict[str, Any]) -> int:
"""Builds the full report and the budgeted stdout digest from a `kind: List` of raw objects."""
unfiltered_items = k8s_objects.dict_items(raw_obj.get("items"))
raw_items = filter_and_sort_snapshot_items(unfiltered_items)
present_kinds = {str(x.get("kind", "")) for x in raw_items if x.get("kind")}
raw_items = _scoped_snapshot_items(args, raw_items)
detected_vinfo, schema_ref = _detect_schema(
args, present_kinds, unfiltered_items
)
# Facts see the healthy Pods the display filter hides; the object lists
# below do not.
derived_notes = _coverage_gap_notes(raw_obj) + _tagged_derived_notes(
args.ledger_path, _fact_input_items(args, unfiltered_items, raw_items)
)
compacted_items = [sanitize_and_compact_object(x) for x in raw_items]
ungrouped_items, bulk_groups = group_bulk_objects(compacted_items)
builder = _DigestBuilder(schema_ref, derived_notes, raw_obj.get("_warnings"))
# The full report (and therefore the quote ledger) keeps every object and
# every member name; only the stdout digest is grouped and sampled.
full_out_str = _dump(builder.payload(bulk_groups, compacted_items))
report_file = report_output.write_full_report(
args.ledger_path, "snapshot", full_out_str, "yaml"
)
digest = {
"full_report_file": report_file,
**builder.payload(sample_bulk_groups(bulk_groups), ungrouped_items),
}
out_str = _fit_digest_to_budget(digest, args.max_output_bytes, report_file)
return _print_and_record(
out_str,
LedgerInputs(
args.ledger_path,
"get",
raw_obj,
full_out_str,
detected_version=detected_vinfo,
),
)
def main() -> int:
args = build_parser().parse_args()
report_output.apply_ignore_namespaces(args)
report_output.apply_no_remote_schema(args)
report_output.apply_kueue_namespace(args)
if args.action == "explain":
return run_explain(args)
if args.mode == "logs_archive":
return _run_logs_archive(args)
action = _resolve_action(args)
try:
raw_obj = load_items(args.mode, args, action)
except LoadError as exc:
return _print_error(exc.message, exc.next_step)
if (
isinstance(raw_obj, dict)
and raw_obj.get("kind") == "List"
and _is_snapshot_request(args, action)
):
return run_snapshot(args, raw_obj)
return run_list_get_events(args, action, raw_obj)
if __name__ == "__main__":
sys.exit(main())
snapshot_facts.py 80.8 KB
"""Derived-fact emitters for `snapshot.py` (`derived_graph_diagnostics`).
Each `emit_<section>(ctx)` function appends neutral, mechanically derived
facts about one aspect of the Kueue admission graph to `ctx.notes`. The
orchestrator (`snapshot.compute_derived_facts`) builds a `FactContext` from the
snapshot items and calls the emitters in `FACT_EMITTERS` order; the order
determines the order of the facts in the digest and must not change.
The emitters describe observations and documented Kueue mechanisms only; they
never rank causes or prescribe report content.
"""
from __future__ import annotations
import dataclasses
import functools
import re
from typing import Any, Callable
import fair_sharing_facts
import k8s_objects as k8s
import report_output
import topology_facts
import workload_timeline
import yaml
_parse_quantity = report_output.parse_quantity
_fmt_num = report_output.fmt_num
_fmt_qty = report_output.fmt_quantity
_TAS_ANNOTATIONS = (
"kueue.x-k8s.io/podset-required-topology",
"kueue.x-k8s.io/podset-preferred-topology",
"kueue.x-k8s.io/podset-unconstrained-topology",
)
# `topologyRequest` fields that opt a pod set into topology-aware scheduling
# (Kueue `tas.HasTopologyConstraint`). The index labels Kueue derives for every
# batch Job / JobSet pod set are not a constraint by themselves.
_TAS_CONSTRAINT_FIELDS = (
"required",
"preferred",
"unconstrained",
"podSetSliceRequiredTopology",
"podSetSliceSize",
"podsetSliceRequiredTopologyConstraints",
)
_TAS_INDEX_FIELDS = ("podIndexLabel", "subGroupIndexLabel")
_WORKLOAD_NAME_KEY = "kueue.x-k8s.io/workload"
_PREBUILT_WORKLOAD_LABEL = "kueue.x-k8s.io/prebuilt-workload-name"
_JOB_NAME_LABELS = ("batch.kubernetes.io/job-name", "job-name")
# Workload owner kind -> kinds of the intermediate objects through which that
# owner creates its Pods; the intermediate's name starts with `<owner name>-`.
_INTERMEDIATE_OWNER_KINDS = {
"JobSet": ("Job",),
"LeaderWorkerSet": ("StatefulSet",),
"MPIJob": ("Job",),
"RayJob": ("RayCluster",),
"RayService": ("RayCluster",),
"TrainJob": ("Job",),
}
_MAX_OWNER_HOPS = 16
# Resources a pod-level `spec.resources.requests` entry replaces the container
# aggregate for (plus every `hugepages-*` resource).
_POD_LEVEL_RESOURCES = ("cpu", "memory")
# Deletion events on these kinds describe routine rollout/pod churn, not Kueue
# graph objects, and are not listed as deletion facts.
_HOUSEKEEPING_EVENT_KINDS = frozenset({
"ReplicaSet",
"Deployment",
"StatefulSet",
"DaemonSet",
"Pod",
"Node",
"Endpoints",
"EndpointSlice",
"Lease",
"Ingress",
"Service",
})
# Status conditions reported as facts: (kind, condition type, status) tuples.
_NEGATIVE_CONDITIONS = {
("Workload", "QuotaReserved", "False"),
("Workload", "Admitted", "False"),
("Workload", "Evicted", "True"),
("Workload", "Preempted", "True"),
("Workload", "Requeued", "False"),
("Workload", "PodsReady", "False"),
("Workload", "Finished", "True"),
("ClusterQueue", "Active", "False"),
("LocalQueue", "Active", "False"),
("AdmissionCheck", "Active", "False"),
("Cohort", "Active", "False"),
("JobSet", "Completed", "False"),
("JobSet", "Failed", "True"),
("Job", "Failed", "True"),
("Job", "Suspended", "True"),
}
_INVENTORY_KINDS = (
"Workload",
"Job",
"JobSet",
"Pod",
"LocalQueue",
"ClusterQueue",
"Cohort",
"ResourceFlavor",
"AdmissionCheck",
"ProvisioningRequestConfig",
"ProvisioningRequest",
"Topology",
"Node",
"Event",
)
# Each absent kind is paired with the question only that kind answers, so a
# report can open an Open Question of type "missing data" against a named
# object instead of guessing.
_COVERAGE_QUESTIONS = (
(
"ClusterQueue",
(
"declared nominalQuota / borrowingLimit / lendingLimit per flavor"
" and the cohort membership"
),
),
("Cohort", "quota declared on the Cohort object itself and its parent"),
(
"ResourceFlavor",
"nodeLabels / taints / tolerations a flavor injects into pods",
),
(
"Workload",
"current admission status, flavor assignment and requeueState",
),
("Pod", "scheduler and kubelet outcome after admission"),
("Node", "physical capacity and labels behind each flavor"),
("Event", "Kubernetes Event history (admission, eviction, scheduling)"),
(
"AdmissionCheck",
"which admission checks gate the queues and their Active state",
),
(
"ProvisioningRequest",
"the runtime outcome of a provisioning admission check",
),
(
"ConfigMap",
"KueueConfiguration (waitForPodsReady, clientConnection, integrations)",
),
)
_TAS_CITE = "https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/"
# ---------------------------------------------------------------------------
# Context
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class FactContext:
"""Snapshot objects bucketed by kind plus the lookup tables the sections share."""
by_kind: dict[str, list[dict[str, Any]]]
notes: list[tuple[str | None, str]] = dataclasses.field(default_factory=list)
def __post_init__(self) -> None:
self.workloads = self.by_kind.get("Workload", [])
self.jobs = self.by_kind.get("Job", [])
self.jobsets = self.by_kind.get("JobSet", [])
self.pods = self.by_kind.get("Pod", [])
self.lqs = self.by_kind.get("LocalQueue", [])
self.cqs = self.by_kind.get("ClusterQueue", [])
self.cohort_objects = self.by_kind.get("Cohort", [])
self.acs = self.by_kind.get("AdmissionCheck", [])
self.prcs = self.by_kind.get("ProvisioningRequestConfig", [])
self.provreqs = self.by_kind.get("ProvisioningRequest", [])
self.rfs = self.by_kind.get("ResourceFlavor", [])
self.nodes = self.by_kind.get("Node", [])
self.events = self.by_kind.get("Event", [])
self.configmaps = self.by_kind.get("ConfigMap", [])
self.lq_by_ref = {
f"{k8s.namespace(lq)}/{k8s.name(lq)}": lq for lq in self.lqs
}
self.cq_by_name = {k8s.name(cq): cq for cq in self.cqs}
self.rf_by_name = {k8s.name(rf): rf for rf in self.rfs}
self.ac_by_name = {k8s.name(ac): ac for ac in self.acs}
self.prc_by_name = {k8s.name(prc): prc for prc in self.prcs}
# AdmissionCheck names referenced by any ClusterQueue, and ClusterQueues
# without any.
self.cq_referenced_acs: set[str] = set()
self.unconfigured_cqs: list[str] = []
for cq in self.cqs:
this_cq_acs = _cq_admission_checks(cq)
self.cq_referenced_acs.update(this_cq_acs)
if k8s.name(cq) and not this_cq_acs:
self.unconfigured_cqs.append(k8s.name(cq))
self.cohort_map: dict[str, list[dict[str, Any]]] = {}
for cq in self.cqs:
cohort = _cq_cohort(cq)
if isinstance(cohort, str) and cohort:
self.cohort_map.setdefault(cohort, []).append(cq)
@functools.cached_property
def pod_index(self) -> "_PodIndex":
"""Pod lookup tables for the Workload -> Pod correlation (built on first use)."""
return _PodIndex.build(self.by_kind)
@classmethod
def from_items(cls, items: list[dict[str, Any]]) -> "FactContext":
by_kind: dict[str, list[dict[str, Any]]] = {}
for it in items:
if isinstance(it, dict):
by_kind.setdefault(k8s.kind(it), []).append(it)
return cls(by_kind=by_kind)
def add(self, key: str | None, text: str) -> None:
self.notes.append((key, text))
def _cq_cohort(cq: dict[str, Any]) -> Any:
sp = k8s.spec(cq)
return sp.get("cohortName") or sp.get("cohort") or ""
def _strategy_admission_checks(cq_spec: dict[str, Any]) -> list[str]:
"""AdmissionCheck names listed under `spec.admissionChecksStrategy.admissionChecks`."""
entries = k8s.dict_items(
k8s.as_dict(cq_spec.get("admissionChecksStrategy")).get("admissionChecks")
)
return [str(e["name"]) for e in entries if e.get("name")]
def _cq_admission_checks(cq: dict[str, Any]) -> list[str]:
"""String AdmissionCheck names from `spec.admissionChecks` and `spec.admissionChecksStrategy`."""
cq_spec = k8s.spec(cq)
names = k8s.as_list(cq_spec.get("admissionChecks"))
out = [n for n in names if isinstance(n, str)]
return out + _strategy_admission_checks(cq_spec)
# ---------------------------------------------------------------------------
# Shared helpers (quota arithmetic, events, pod sets)
# ---------------------------------------------------------------------------
def _cpu_quota(cq: dict[str, Any]) -> dict[str, Any]:
"""Aggregates per-flavor CPU quota figures for one ClusterQueue.
`lendable` sums, per flavor, `min(lendingLimit, nominalQuota)` (or the full
nominal when no lendingLimit is set). `borrowing_limit` is the per-flavor sum
when every cpu flavor sets one, otherwise None (unbounded).
Args:
cq: Raw ClusterQueue object mapping.
Returns:
Dict with `nominal`, `lendable`, `borrowing_limit`, `flavors`, `unparsed`.
"""
nominal = 0.0
lendable = 0.0
borrowing_sum = 0.0
borrowing_all_set = True
flavors: list[str] = []
unparsed: list[str] = []
for _, fl, res in k8s.flavor_quotas(cq):
if res.get("name") != "cpu":
continue
parsed = _parse_cpu_limits(fl, res, unparsed)
if parsed is None:
continue
nom, lend, borrow = parsed
nominal += nom
lendable += nom if lend is None else min(lend, nom)
if borrow is None:
borrowing_all_set = False
else:
borrowing_sum += borrow
flavors.append(
f"{fl.get('name')}: nominal={_fmt_num(nom)}"
+ (f" lendingLimit={_fmt_num(lend)}" if lend is not None else "")
+ (f" borrowingLimit={_fmt_num(borrow)}" if borrow is not None else "")
)
return {
"nominal": nominal,
"lendable": lendable,
"borrowing_limit": (
borrowing_sum if (flavors and borrowing_all_set) else None
),
"flavors": flavors,
"unparsed": unparsed,
}
def _parse_cpu_limits(
fl: dict[str, Any], res: dict[str, Any], unparsed: list[str]
) -> tuple[float, float | None, float | None] | None:
"""Parses (nominalQuota, lendingLimit, borrowingLimit); records unparsable values and returns None."""
nom = _parse_quantity(res.get("nominalQuota"))
if nom is None:
unparsed.append(
f"{fl.get('name')}: nominalQuota={res.get('nominalQuota')!r}"
)
return None
lend_raw = res.get("lendingLimit")
lend = _parse_quantity(lend_raw) if lend_raw is not None else None
if lend_raw is not None and lend is None:
unparsed.append(f"{fl.get('name')}: lendingLimit={lend_raw!r}")
return None
borrow_raw = res.get("borrowingLimit")
borrow = _parse_quantity(borrow_raw) if borrow_raw is not None else None
if borrow_raw is not None and borrow is None:
unparsed.append(f"{fl.get('name')}: borrowingLimit={borrow_raw!r}")
return None
return nom, lend, borrow
def _resource_quota_summary(cq: dict[str, Any]) -> dict[str, list[str]]:
"""Returns per-resource flavor quota summary strings for one ClusterQueue."""
out: dict[str, list[str]] = {}
for _, fl, res in k8s.flavor_quotas(cq):
name = k8s.as_text(res.get("name"))
if not name:
continue
parts = [f"nominalQuota={res.get('nominalQuota')}"]
for key in ("lendingLimit", "borrowingLimit"):
if res.get(key) is not None:
parts.append(f"{key}={res.get(key)}")
out.setdefault(name, []).append(f"{fl.get('name')}: " + " ".join(parts))
return out
def _event_summary(ev: dict[str, Any]) -> str:
obj = ev.get("involvedObject") or {}
ref = ""
if isinstance(obj, dict) and obj.get("name"):
ref = f"[{obj.get('kind', 'Object')}/{obj.get('name')}] "
count = ev.get("count")
count_str = f" (x{count})" if isinstance(count, int) and count > 1 else ""
return (
f"{ref}{ev.get('reason', '')}:"
f" {str(ev.get('message', ''))[:300]}{count_str}"
)
def _event_identity(ev: dict[str, Any]) -> tuple[str, str, str]:
obj = ev.get("involvedObject") or {}
obj_ref = ""
if isinstance(obj, dict):
obj_ref = str(
obj.get("uid")
or f"{obj.get('kind', '')}/{obj.get('namespace', '')}/{obj.get('name', '')}"
)
return (
obj_ref,
k8s.as_text(ev.get("reason")),
k8s.as_text(ev.get("message")),
)
def _podset_topology_request(ps: dict[str, Any]) -> tuple[str, bool]:
"""Describes a pod set's topology request and tells whether it is a TAS constraint.
Mirrors Kueue `tas.HasTopologyConstraint`: only the fields in
`_TAS_CONSTRAINT_FIELDS` (or, without them, a TAS pod template annotation)
make the pod set a topology-aware one. Index labels are shown as text only.
Args:
ps: One `spec.podSets[]` entry of a Workload.
Returns:
`(description, has_constraint)`; the description is `none` when the pod set
carries neither a constraint nor index labels.
"""
tr = k8s.as_dict(ps.get("topologyRequest"))
set_fields = {
k: v
for k, v in tr.items()
if v is not None and not (isinstance(v, list) and not v)
}
parts = [
f"{k}={v}"
for k, v in set_fields.items()
if k in _TAS_CONSTRAINT_FIELDS or k in _TAS_INDEX_FIELDS
]
if any(k in set_fields for k in _TAS_CONSTRAINT_FIELDS):
return "topologyRequest{" + ", ".join(parts) + "}", True
ann = k8s.annotations(k8s.as_dict(ps.get("template")))
hits = [
f"{k.rsplit('/', 1)[-1]}={v}"
for k, v in ann.items()
if k in _TAS_ANNOTATIONS
]
if hits:
return "annotations{" + ", ".join(hits) + "}", True
if parts:
index_only = ", ".join(parts)
return f"none (topologyRequest sets index labels only: {index_only})", False
return "none", False
def _parse_requests(reqs: Any, raw: dict[str, str]) -> dict[str, float]:
"""Parses a `resource -> quantity` mapping; unparsable values are recorded in `raw`."""
out: dict[str, float] = {}
for name, val in k8s.as_dict(reqs).items():
q = _parse_quantity(val)
if q is None:
raw[str(name)] = str(val)
else:
out[str(name)] = q
return out
def _add_requests(total: dict[str, float], extra: dict[str, float]) -> None:
for name, q in extra.items():
total[name] = total.get(name, 0.0) + q
def _pod_requests(
pod_spec: dict[str, Any], raw: dict[str, str]
) -> dict[str, float]:
"""Effective requests of one pod, following the Kubernetes `PodRequests` rule Kueue uses.
Per resource: max(sum of containers + restartable init containers, each
regular init container + the restartable init containers declared before
it); pod-level `resources.requests` replace that aggregate for cpu, memory
and hugepages; `overhead` is added last.
Args:
pod_spec: A pod `spec` mapping (of a Pod or a pod template).
raw: Collects `resource -> value` for quantities that do not parse.
Returns:
Parsed per-pod request per resource name.
"""
def requests_of(holder: dict[str, Any]) -> dict[str, float]:
resources = k8s.as_dict(holder.get("resources"))
return _parse_requests(resources.get("requests"), raw)
total: dict[str, float] = {}
for c in k8s.dict_items(pod_spec.get("containers")):
_add_requests(total, requests_of(c))
sidecars: dict[str, float] = {}
init_peak: dict[str, float] = {}
for c in k8s.dict_items(pod_spec.get("initContainers")):
use = requests_of(c)
if c.get("restartPolicy") == "Always":
_add_requests(total, use)
_add_requests(sidecars, use)
use = sidecars
else:
_add_requests(use, sidecars)
for name, q in use.items():
init_peak[name] = max(init_peak.get(name, 0.0), q)
for name, q in init_peak.items():
total[name] = max(total.get(name, 0.0), q)
for name, q in requests_of(pod_spec).items():
if name in _POD_LEVEL_RESOURCES or name.startswith("hugepages-"):
total[name] = q
_add_requests(total, _parse_requests(pod_spec.get("overhead"), raw))
return total
def _podset_requests(ps: dict[str, Any]) -> dict[str, str]:
"""Formatted requests of one pod of a pod template (per pod, not multiplied by count)."""
raw: dict[str, str] = {}
totals = _pod_requests(k8s.spec(k8s.as_dict(ps.get("template"))), raw)
out = {k: _fmt_num(v) for k, v in sorted(totals.items())}
out.update(raw)
return out
def _nodes_matching_labels(
nodes: list[dict[str, Any]], rf_labels: dict[str, Any]
) -> list[dict[str, Any]]:
"""Nodes whose labels carry every `rf_labels` key with the same value (label equality)."""
return [
n
for n in nodes
if all(k8s.labels(n).get(k) == v for k, v in rf_labels.items())
]
def _rf_node_labels(rf: Any) -> Any:
"""`spec.nodeLabels` of a ResourceFlavor as stored (callers check that it is a mapping)."""
return (k8s.spec(rf).get("nodeLabels") or {}) if isinstance(rf, dict) else {}
# ---------------------------------------------------------------------------
# 1. Inventory and coverage
# ---------------------------------------------------------------------------
def emit_inventory(ctx: FactContext) -> None:
"""1. Inventory: object counts per kind and the no-workload case."""
inventory = ", ".join(
f"{kind}={len(ctx.by_kind.get(kind, []))}"
for kind in _INVENTORY_KINDS
if kind in ctx.by_kind
)
ctx.add(None, f"SNAPSHOT_INVENTORY: {inventory}")
if not ctx.workloads and not ctx.jobs and not ctx.jobsets:
ctx.add(
"inventory:no-workloads",
"SNAPSHOT_INVENTORY: no Workload, Job, or JobSet objects are present"
f" in the snapshot; {len(ctx.lqs)} LocalQueue object(s) present. Any"
" workload history must come from Events, controller logs, or audit"
" logs rather than from live objects.",
)
def emit_coverage(ctx: FactContext) -> None:
"""Emits section 1a evidence-coverage facts for present and absent kinds."""
absent = [
f"{kind} (answers: {q})"
for kind, q in _COVERAGE_QUESTIONS
if not ctx.by_kind.get(kind)
]
present = [kind for kind, _ in _COVERAGE_QUESTIONS if ctx.by_kind.get(kind)]
ctx.add(
None,
f"BUNDLE_COVERAGE: present={present}; absent={absent or 'none'}. A"
" question whose answer lives only in an absent kind cannot be settled"
" from this snapshot; name that kind when reporting it as not"
" determinable.",
)
def emit_status_conditions(ctx: FactContext) -> None:
"""1b. Status conditions of Kueue objects (verbatim reason/message)."""
for kind in (
"ClusterQueue",
"LocalQueue",
"AdmissionCheck",
"Cohort",
"Workload",
"JobSet",
"Job",
):
for obj in ctx.by_kind.get(kind, []):
ref = f"{kind}/{k8s.ref(obj)}"
for cond in k8s.conditions(obj):
ctype = k8s.as_text(cond.get("type"))
cstatus = k8s.as_text(cond.get("status"))
if (kind, ctype, cstatus) not in _NEGATIVE_CONDITIONS:
continue
reason = k8s.as_text(cond.get("reason"))
ctx.add(
f"condition:{kind}:{ctype}:{reason}",
f"STATUS_CONDITION: [{ref}] {ctype}={cstatus} reason={reason}:"
f" {k8s.as_text(cond.get('message'))[:300]}",
)
# ---------------------------------------------------------------------------
# 1c. Workload -> LocalQueue -> ClusterQueue resolution and per-pod-set facts
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class _FlavorCoverage:
"""Which ClusterQueue flavors are topology-aware and which resources each group covers."""
tas_flavors: list[str]
plain_flavors: list[str]
tas_res: set[str]
plain_res: set[str]
# Flavors whose ResourceFlavor object is not in the snapshot: whether they
# set topologyName is not known, so they belong to neither group.
unknown_flavors: list[str] = dataclasses.field(default_factory=list)
@property
def any(self) -> bool:
return bool(self.tas_flavors or self.plain_flavors or self.unknown_flavors)
def summary(self) -> str:
"""Text listing the ClusterQueue's flavors per group."""
text = "; ClusterQueue flavors"
known = bool(self.tas_flavors or self.plain_flavors)
if known or not self.unknown_flavors:
text += (
f" with topologyName={self.tas_flavors or []},"
f" without={self.plain_flavors or []}"
)
if self.unknown_flavors:
text += (
f"{',' if known else ''} with no ResourceFlavor object in the"
f" snapshot (topologyName not determinable)={self.unknown_flavors}"
)
return text
def _flavor_coverage(
ctx: FactContext, cq: dict[str, Any] | None
) -> _FlavorCoverage:
"""Classifies a ClusterQueue's flavors into TAS and non-TAS coverage sets."""
cov = _FlavorCoverage([], [], set(), set())
if cq is None:
return cov
for rg in k8s.resource_groups(cq):
rg_res = {str(r) for r in k8s.as_list(rg.get("coveredResources")) if r}
for fl in k8s.dict_items(rg.get("flavors")):
if not fl.get("name"):
continue
fl_name = str(fl["name"])
rf = ctx.rf_by_name.get(fl_name)
if rf is None:
cov.unknown_flavors.append(fl_name)
elif k8s.spec(rf).get("topologyName"):
cov.tas_flavors.append(fl_name)
cov.tas_res.update(rg_res)
else:
cov.plain_flavors.append(fl_name)
cov.plain_res.update(rg_res)
return cov
def _resolve_workload_cq(
ctx: FactContext, wl: dict[str, Any], wl_ref: str
) -> dict[str, Any] | None:
"""Emits the WORKLOAD_QUEUE_CHAIN fact and returns the resolved ClusterQueue, if any."""
ns = k8s.namespace(wl)
queue_name = str(k8s.spec(wl).get("queueName") or "")
lq = ctx.lq_by_ref.get(f"{ns}/{queue_name}") if queue_name else None
if not queue_name:
ctx.add(
f"queue-chain:{wl_ref}",
f"WORKLOAD_QUEUE_CHAIN: [{wl_ref}] spec.queueName is empty; the"
" workload is not assigned to any LocalQueue.",
)
return None
if lq is None:
ctx.add(
f"queue-chain:{wl_ref}",
f"WORKLOAD_QUEUE_CHAIN: [{wl_ref}] spec.queueName={queue_name}; no"
f" LocalQueue named {queue_name!r} exists in namespace {ns!r} in the"
" snapshot.",
)
return None
cq_name = str(k8s.spec(lq).get("clusterQueue") or "")
cq = ctx.cq_by_name.get(cq_name)
ctx.add(
None,
f"WORKLOAD_QUEUE_CHAIN: [{wl_ref}] queueName={queue_name} -> ClusterQueue"
f" {cq_name or '<unset>'}"
+ (
""
if cq is not None
else f" (no ClusterQueue named {cq_name!r} in the snapshot)"
),
)
return cq
def _podset_flavor_note(
cov: _FlavorCoverage, treq: bool, req_keys: set[str], wl_finished: bool
) -> tuple[str | None, str]:
"""Returns (key, suffix) describing the TAS / non-TAS flavor fit of one pod set."""
if cov.unknown_flavors:
# A flavor of unknown kind could belong to either group: no fit statement.
return None, ""
needs_tas_res = bool(req_keys & (cov.tas_res - cov.plain_res))
needs_plain_res = bool(req_keys & (cov.plain_res - cov.tas_res))
if treq and not cov.tas_flavors:
return "podset-flavor", (
". A pod set with a topology request is only assigned flavors whose"
" ResourceFlavor sets topologyName ("
+ _TAS_CITE
+ ")."
)
if treq and cov.tas_flavors and cov.plain_flavors and needs_plain_res:
only_plain = sorted(req_keys & (cov.plain_res - cov.tas_res))
on_tas = sorted(req_keys & cov.tas_res)
return "podset-flavor", (
". Requested resources covered only by flavors without topologyName:"
f" {only_plain}; covered by flavors with topologyName: {on_tas}. With"
" an explicit topology request, a flavor without topologyName is"
" accepted only when its resourceGroup covers none of the pod's"
" requested resources; otherwise it is rejected with 'does not support"
" TopologyAwareScheduling' ("
+ _TAS_CITE
+ ")."
)
if (
not treq
and cov.tas_flavors
and cov.plain_flavors
and not wl_finished
and (needs_tas_res or not (cov.tas_res - cov.plain_res))
):
on_tas_only = sorted(req_keys & (cov.tas_res - cov.plain_res))
on_plain = sorted(req_keys & cov.plain_res)
return "podset-flavor", (
". Requested resources covered only by flavors with topologyName:"
f" {on_tas_only}; covered by flavors without topologyName: {on_plain}."
" Without a topology request, a flavor whose ResourceFlavor sets"
" topologyName is rejected with 'supports only"
" TopologyAwareScheduling' unless every flavor of the ClusterQueue is"
" topology-aware ("
+ _TAS_CITE
+ ")."
)
return None, ""
def _emit_podset_facts(
ctx: FactContext, wl: dict[str, Any], wl_ref: str, cov: _FlavorCoverage
) -> None:
"""Emits per-podSet resource, topology, and flavor-compatibility facts."""
wl_finished = k8s.has_condition(wl, "Finished")
for ps in k8s.dict_items(k8s.spec(wl).get("podSets")):
ps_name = k8s.as_text(ps.get("name"))
treq, has_tas = _podset_topology_request(ps)
ps_reqs = _podset_requests(ps)
tmpl_spec = k8s.spec(k8s.as_dict(ps.get("template")))
line = (
f"WORKLOAD_PODSET_FACTS: [{wl_ref}] podSet {ps_name!r}:"
f" count={ps.get('count')}, requests/pod={ps_reqs}, topology"
f" request={treq},"
f" tolerations={len(k8s.as_list(tmpl_spec.get('tolerations')))},"
f" nodeSelector={tmpl_spec.get('nodeSelector') or {}}"
)
key = None
if cov.any:
line += cov.summary()
marker, suffix = _podset_flavor_note(
cov, has_tas, set(ps_reqs.keys()), wl_finished
)
if marker:
key = None if wl_finished else f"podset-flavor:{wl_ref}:{ps_name}"
line += suffix
ctx.add(key, line)
def emit_queue_chain(ctx: FactContext) -> None:
"""Emits section 1c Workload -> LocalQueue -> ClusterQueue chain facts."""
for wl in ctx.workloads:
wl_ref = f"Workload/{k8s.namespace(wl)}/{k8s.name(wl)}"
cq = _resolve_workload_cq(ctx, wl, wl_ref)
_emit_podset_facts(ctx, wl, wl_ref, _flavor_coverage(ctx, cq))
# ---------------------------------------------------------------------------
# 1c-bis. Job and JobSet static spec inspection
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class _JobTotals:
pods: int = 0
requests: dict[str, float] = dataclasses.field(default_factory=dict)
def _job_specs_to_check(
kind_name: str, j_ref: str, j_spec: dict[str, Any]
) -> list[tuple[str, dict[str, Any], int]]:
"""(ref, batch Job spec, replicas) for a Job or every replicatedJob of a JobSet."""
if kind_name == "Job":
return [(j_ref, j_spec, 1)]
out: list[tuple[str, dict[str, Any], int]] = []
for rj in k8s.dict_items(j_spec.get("replicatedJobs")):
rj_name = k8s.as_text(rj.get("name"))
rj_replicas = k8s.as_int(rj.get("replicas"), 1)
rj_job_spec = k8s.spec(k8s.as_dict(rj.get("template")))
out.append((f"{j_ref}:replicatedJob[{rj_name}]", rj_job_spec, rj_replicas))
return out
def _emit_job_sub_specs(
ctx: FactContext, specs: list[tuple[str, dict[str, Any], int]]
) -> _JobTotals:
"""Emits Indexed/backoffLimitPerIndex facts and sums pods and requests over the sub specs."""
totals = _JobTotals()
for sub_ref, sub_spec, replicas in specs:
comp_mode = str(sub_spec.get("completionMode") or "")
blpi = sub_spec.get("backoffLimitPerIndex")
mfi = sub_spec.get("maxFailedIndexes")
parallelism = k8s.as_int(sub_spec.get("parallelism"), 1) * replicas
totals.pods += parallelism
pod_reqs = _podset_requests({"template": sub_spec.get("template") or {}})
for r_k, r_v in pod_reqs.items():
q_val = _parse_quantity(r_v)
if q_val is not None:
totals.requests[r_k] = (
totals.requests.get(r_k, 0.0) + q_val * parallelism
)
if comp_mode == "Indexed" and blpi is not None and mfi is None:
ctx.add(
f"job-spec:{sub_ref}:indexed-backoff",
f"JOB_SPEC_FACT: [{sub_ref}] has completionMode=Indexed and"
f" backoffLimitPerIndex={blpi} while "
"maxFailedIndexes is unset (null). batch/v1 semantics: when a pod for"
" an index exhausts backoffLimitPerIndex, that index is recorded in"
" status.failedIndexes and stops retrying while the other indexes"
" keep running; with maxFailedIndexes unset the Job is marked Failed"
" once all indexes have finished if at least one index failed"
" (whereas with maxFailedIndexes set, once the number of failed"
" indexes exceeds it the remaining running pods are terminated and"
' the Job is then marked Failed; "Backoff limit per index" in'
" https://kubernetes.io/docs/concepts/workloads/controllers/job/). "
"Kueue's PodsReady condition for a Job tracks whether the Job's pods"
" have reached Ready/Succeeded "
"(https://kueue.sigs.k8s.io/docs/tasks/manage/setup_wait_for_pods_ready/).",
)
return totals
def _cq_quota_and_flavors(
ctx: FactContext, cq: dict[str, Any]
) -> tuple[dict[str, float], list[str], bool]:
"""Summed nominalQuota per resource, per-flavor nodeLabels summary and whether every ResourceFlavor is present."""
cq_quotas: dict[str, float] = {}
rf_summary: list[str] = []
all_rfs_present = True
for rg in k8s.resource_groups(cq):
for fl in k8s.dict_items(rg.get("flavors")):
if not fl.get("name"):
continue
rf_o = ctx.rf_by_name.get(str(fl["name"]))
if rf_o is None:
all_rfs_present = False
rf_summary.append(
f"{fl['name']}(nodeLabels={(k8s.spec(rf_o).get('nodeLabels') or {})})"
)
for r_entry in k8s.dict_items(fl.get("resources")):
if r_entry.get("name"):
r_nom = _parse_quantity(r_entry.get("nominalQuota"))
if r_nom is not None:
r_n = str(r_entry["name"])
cq_quotas[r_n] = cq_quotas.get(r_n, 0.0) + r_nom
return cq_quotas, rf_summary, all_rfs_present
def _admission_check_details(
ctx: FactContext, cq_acs: list[str]
) -> tuple[list[str], bool]:
"""Describes each AdmissionCheck with its ProvisioningRequestConfig; False when one is missing."""
ac_details: list[str] = []
all_acs_present = True
for ac_n in cq_acs:
ac_obj = ctx.ac_by_name.get(str(ac_n))
if ac_obj is None:
all_acs_present = False
continue
ac_sp = k8s.spec(ac_obj)
p_ref = ac_sp.get("parametersRef") or ac_sp.get("parameters") or {}
prc_n = k8s.as_text(p_ref.get("name")) if isinstance(p_ref, dict) else ""
prc_obj = ctx.prc_by_name.get(prc_n)
if prc_n and prc_obj is None:
all_acs_present = False
prc_sp = k8s.spec(prc_obj)
ac_details.append(
f"{ac_n}(controller={ac_sp.get('controllerName')}, prc={prc_n}, "
f"provisioningClassName={prc_sp.get('provisioningClassName')})"
)
return ac_details, all_acs_present
def _emit_static_queue_chain(
ctx: FactContext, job_obj: dict[str, Any], j_ref: str, totals: _JobTotals
) -> None:
"""JOB_QUEUE_CHAIN_FACTS for one Job/JobSet when the snapshot has no Workload objects."""
j_ns = k8s.namespace(job_obj)
q_name = str(
k8s.labels(job_obj).get("kueue.x-k8s.io/queue-name")
or k8s.annotations(job_obj).get("kueue.x-k8s.io/queue-name")
or ""
)
lq = ctx.lq_by_ref.get(f"{j_ns}/{q_name}") if q_name else None
cq_name = str(k8s.spec(lq).get("clusterQueue") or "") if lq else ""
cq = ctx.cq_by_name.get(cq_name) if cq_name else None
req_summary = {k: _fmt_num(v) for k, v in sorted(totals.requests.items())}
chain_msg = (
f"JOB_QUEUE_CHAIN_FACTS: [{j_ref}] queue-name={q_name or '<unset>'} ->"
f" ClusterQueue={cq_name or '<unresolved>'}; totalPods={totals.pods},"
f" totalRequests={req_summary}"
)
chain_key: str | None = None
if cq is not None:
# Unlike 1d, every `spec.admissionChecks` entry counts here (a non-string
# entry cannot be resolved and therefore suppresses the static-chain key).
cq_acs = k8s.as_list(
k8s.spec(cq).get("admissionChecks")
) + _strategy_admission_checks(k8s.spec(cq))
cq_quotas, rf_summary, all_rfs_present = _cq_quota_and_flavors(ctx, cq)
fits_quota = bool(totals.requests) and all(
r_k in cq_quotas and totals.requests[r_k] <= cq_quotas[r_k]
for r_k in totals.requests
)
if (
cq_acs
and not ctx.provreqs
and not ctx.nodes
and all_rfs_present
and fits_quota
):
ac_details, all_acs_present = _admission_check_details(ctx, cq_acs)
if all_acs_present:
chain_key = f"provreq:static-chain:{j_ref}"
chain_msg += (
f"; ClusterQueue nominalQuota covers totalRequests ({req_summary})"
f" and admission is gated on AdmissionCheck {ac_details} targeting"
f" ResourceFlavor {rf_summary}. The bundle contains no"
" ProvisioningRequest, Node, or Workload status objects, so the"
" runtime outcome of the admission check (ProvisioningRequest"
" conditions, node provisioning) is not observable from this"
" bundle; it must come from controller/autoscaler logs or events"
" if present."
)
ctx.add(chain_key, chain_msg)
def emit_job_specs(ctx: FactContext) -> None:
"""Emits section 1c-bis Job/JobSet static spec and queue-chain facts."""
for kind_name, job_objs in (("Job", ctx.jobs), ("JobSet", ctx.jobsets)):
for job_obj in job_objs:
j_ref = f"{kind_name}/{k8s.namespace(job_obj)}/{k8s.name(job_obj)}"
totals = _emit_job_sub_specs(
ctx, _job_specs_to_check(kind_name, j_ref, k8s.spec(job_obj))
)
if not ctx.workloads:
_emit_static_queue_chain(ctx, job_obj, j_ref, totals)
# ---------------------------------------------------------------------------
# 1d / 1e. Admission checks and ProvisioningRequests
# ---------------------------------------------------------------------------
def _ac_referencing_cqs(ctx: FactContext, ac_name: str) -> list[str]:
return sorted(
k8s.name(cq) for cq in ctx.cqs if ac_name in _cq_admission_checks(cq)
)
def emit_admission_checks(ctx: FactContext) -> None:
"""1d. Workload admissionChecks, requeueState, and AdmissionCheck wiring."""
for ac in ctx.acs:
ac_name, ac_spec = k8s.name(ac), k8s.spec(ac)
p_ref = ac_spec.get("parametersRef") or ac_spec.get("parameters")
if ac_name and ac_name not in ctx.cq_referenced_acs:
ctx.add(
f"unreferenced-ac:{ac_name}",
f"ADMISSIONCHECK_FACTS ({ac_name}):"
f" controllerName={ac_spec.get('controllerName')},"
f" parametersRef={p_ref}; NOT referenced by any"
" ClusterQueue.spec.admissionChecks / admissionChecksStrategy in the"
" snapshot (ClusterQueues without"
f" admissionChecks={ctx.unconfigured_cqs}). An AdmissionCheck applies"
" only to workloads of ClusterQueues that list it in"
" spec.admissionChecks or spec.admissionChecksStrategy"
" (https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/,"
" https://kueue.sigs.k8s.io/docs/concepts/admission_check/);"
" workloads of other ClusterQueues are admitted on quota alone, and"
" no ProvisioningRequest is created for them.",
)
elif ac_name:
ctx.add(
None,
f"ADMISSIONCHECK_FACTS ({ac_name}):"
f" controllerName={ac_spec.get('controllerName')},"
f" parametersRef={p_ref}, referenced by"
f" ClusterQueue(s)={_ac_referencing_cqs(ctx, ac_name)}",
)
for wl in ctx.workloads:
wl_ref = f"Workload/{k8s.namespace(wl)}/{k8s.name(wl)}"
status = k8s.status(wl)
requeue = k8s.as_dict(status.get("requeueState"))
for ac_st in k8s.dict_items(status.get("admissionChecks")):
ac_name = k8s.as_text(ac_st.get("name"))
state = k8s.as_text(ac_st.get("state"))
msg = k8s.as_text(ac_st.get("message"))[:300]
retry_count = ac_st.get("retryCount")
requeue_str = f", requeueState={requeue}" if requeue else ""
retry_str = (
f", retryCount={retry_count}" if retry_count is not None else ""
)
key = (
f"provreq:wl-ac:{ac_name}:{state}"
if state in ("Retry", "Rejected") or (state == "Pending" and msg)
else None
)
ctx.add(
key,
f"WORKLOAD_ADMISSIONCHECK_FACTS: [{wl_ref}] admissionCheck={ac_name}"
f" state={state}{retry_str}{requeue_str}"
+ (f": {msg}" if msg else ""),
)
def emit_provisioning_requests(ctx: FactContext) -> None:
"""1e. ProvisioningRequest objects and conditions."""
for pr in ctx.provreqs:
pr_name = k8s.name(pr)
pr_ref = f"ProvisioningRequest/{k8s.ref(pr)}"
owners = [
f"{o.get('kind')}/{o.get('name')}"
for o in k8s.owner_refs(pr)
if o.get("name")
]
status = k8s.status(pr)
cond_parts: list[str] = []
bad_reasons: list[str] = []
for c in k8s.conditions(pr):
ct = k8s.as_text(c.get("type"))
cs = k8s.as_text(c.get("status"))
cr = k8s.as_text(c.get("reason"))
cm = k8s.as_text(c.get("message"))[:240]
cond_parts.append(
f"{ct}={cs} (reason={cr}: {cm})" if cm else f"{ct}={cs} (reason={cr})"
)
if (ct in ("Provisioned", "Accepted") and cs == "False") or (
ct in ("Failed", "BookingExpired", "CapacityRevoked") and cs == "True"
):
bad_reasons.append(f"{ct}={cs}:{cr}")
details = status.get("provisioningClassDetails") or {}
key = f"provreq:{pr_name}:{','.join(bad_reasons)}" if bad_reasons else None
ctx.add(
key,
f"PROVISIONINGREQUEST_FACTS: [{pr_ref}] owner={owners or 'none'} "
f"provisioningClassName={k8s.spec(pr).get('provisioningClassName')} "
f"conditions=[{'; '.join(cond_parts) or 'none'}]"
+ (f" provisioningClassDetails={details}" if details else ""),
)
# ---------------------------------------------------------------------------
# 1f. Workload -> Pod correlation & Pod failure/gate facts
# ---------------------------------------------------------------------------
_OwnerRef = tuple[str, str] # (kind, name)
def _owner_ref_pairs(obj: Any) -> list[_OwnerRef]:
return [
(k8s.as_text(o.get("kind")), str(o["name"]))
for o in k8s.owner_refs(obj)
if o.get("name")
]
def _pod_ancestry(
p: dict[str, Any], objs: dict[tuple[str, str, str], dict[str, Any]]
) -> tuple[set[str], list[_OwnerRef]]:
"""Names a pod is owned under, and its owners that are not snapshot objects.
Walks ownerReferences upward through the objects present in the snapshot
(Pod -> Job -> JobSet). A pod without ownerReferences is filed under its
job-name label; a pod with neither is its own unresolved owner (kind '').
Args:
p: Pod object.
objs: Snapshot objects keyed by `(namespace, kind, name)`.
Returns:
`(names, unresolved)`: the pod's own name plus the name of every owner on
the chain, and the `(kind, name)` owners whose object is not in the
snapshot (the only ones the name-prefix fallback applies to).
"""
ns, p_labels = k8s.namespace(p), k8s.labels(p)
names = {k8s.name(p)}
unresolved: list[_OwnerRef] = []
frontier = _owner_ref_pairs(p)
if not frontier:
job = [str(p_labels[k]) for k in _JOB_NAME_LABELS if p_labels.get(k)]
if job:
frontier = [("Job", job[0])]
else:
unresolved.append(("", k8s.name(p)))
seen: set[_OwnerRef] = set()
while frontier and len(seen) < _MAX_OWNER_HOPS:
ref = frontier.pop()
if ref in seen:
continue
seen.add(ref)
names.add(ref[1])
owner = objs.get((ns, *ref))
if owner is None:
unresolved.append(ref)
else:
frontier.extend(_owner_ref_pairs(owner))
return names, unresolved
@dataclasses.dataclass
class _PodIndex:
"""Pods keyed by every name a Workload can reference them by (one pass over the Pods)."""
pods: list[dict[str, Any]]
# (tag, namespace, name) -> [(pod position, kind of the unresolved owner)].
# Tags: `workload` (label / annotation), `prebuilt` (label), `owner` (own
# name or the name of an owner on the chain), `prefix` (dash-prefixes of the
# name of an owner whose object is not in the snapshot).
table: dict[tuple[str, str, str], list[tuple[int, str]]] = dataclasses.field(
default_factory=dict
)
@classmethod
def build(cls, by_kind: dict[str, list[dict[str, Any]]]) -> "_PodIndex":
index = cls(pods=by_kind.get("Pod", []))
objs: dict[tuple[str, str, str], dict[str, Any]] = {}
for kind, group in by_kind.items():
if kind in ("Event", "Node"):
continue
for o in group:
objs[(k8s.namespace(o), kind, k8s.name(o))] = o
for pos, p in enumerate(index.pods):
index._add_pod(pos, p, objs)
return index
def _add(
self, tag: str, ns: str, name: Any, pos: int, kind: str = ""
) -> None:
if name:
self.table.setdefault((tag, ns, str(name)), []).append((pos, kind))
def _add_pod(
self,
pos: int,
p: dict[str, Any],
objs: dict[tuple[str, str, str], dict[str, Any]],
) -> None:
"""Indexes one Pod under its workload labels and owner ancestry keys."""
ns, p_labels = k8s.namespace(p), k8s.labels(p)
self._add("workload", ns, p_labels.get(_WORKLOAD_NAME_KEY), pos)
self._add("workload", ns, k8s.annotations(p).get(_WORKLOAD_NAME_KEY), pos)
self._add("prebuilt", ns, p_labels.get(_PREBUILT_WORKLOAD_LABEL), pos)
names, unresolved = _pod_ancestry(p, objs)
for name in names:
self._add("owner", ns, name, pos)
for kind, name in unresolved:
# `a-b-c` is filed under `a` and `a-b`: the owner names it may extend.
for i, ch in enumerate(name):
if ch == "-":
self._add("prefix", ns, name[:i], pos, kind)
def get(self, tag: str, ns: str, name: str) -> list[tuple[int, str]]:
return self.table.get((tag, ns, name), [])
def _pods_of_workload(
ctx: FactContext, wl: dict[str, Any]
) -> list[dict[str, Any]]:
"""Pods in the workload's namespace that reference it by label, annotation, owner chain or owner-name prefix.
The `<owner name>-` prefix fallback applies only to a pod that has neither
ownerReferences nor a job-name label, or to an owner on the pod's chain that
is absent from the snapshot and of a kind through which the Workload's owner
creates Pods (`_INTERMEDIATE_OWNER_KINDS`). Pods of Job `a-b` are therefore
not attributed to the Workload of Job `a`.
Args:
ctx: Fact context (its pod index is built on first use).
wl: Workload object.
Returns:
Matching Pod objects in snapshot order.
"""
index, ns, wl_name = ctx.pod_index, k8s.namespace(wl), k8s.name(wl)
hits = {pos for pos, _ in index.get("workload", ns, wl_name)}
if k8s.metadata(wl).get("uid"):
hits.update(pos for pos, _ in index.get("prebuilt", ns, wl_name))
for o_kind, o_name in _owner_ref_pairs(wl):
via = _INTERMEDIATE_OWNER_KINDS.get(o_kind, ())
hits.update(pos for pos, _ in index.get("owner", ns, o_name))
hits.update(
pos
for pos, kind in index.get("prefix", ns, o_name)
if not kind or kind in via
)
return [index.pods[pos] for pos in sorted(hits)]
def _pod_gates(p: dict[str, Any]) -> list[str]:
return [
k8s.as_text(g.get("name"))
for g in k8s.dict_items(k8s.spec(p).get("schedulingGates"))
if g.get("name")
]
def _topology_gate_note(
ctx: FactContext, status: dict[str, Any], sample_gates: list[str]
) -> tuple[bool, str]:
"""(topologyAssignment present, explanatory note when the TAS gate is held without an assignment)."""
psa = k8s.dict_items(
k8s.as_dict(status.get("admission")).get("podSetAssignments")
)
has_topo_assign = any(bool(a.get("topologyAssignment")) for a in psa)
assigned_no_topo_rfs: list[str] = []
for a in psa:
for fl_v in k8s.as_dict(a.get("flavors")).values():
rf_o = ctx.rf_by_name.get(str(fl_v))
if (
rf_o is not None
and not (k8s.spec(rf_o).get("topologyName"))
and str(fl_v) not in assigned_no_topo_rfs
):
assigned_no_topo_rfs.append(str(fl_v))
if "kueue.x-k8s.io/topology" not in sample_gates or has_topo_assign:
return has_topo_assign, ""
rf_clause = ""
if assigned_no_topo_rfs:
rf_clause = (
f"; assigned ResourceFlavor(s) {assigned_no_topo_rfs} have"
" spec.topologyName unset"
)
return has_topo_assign, (
" Workload status.admission.podSetAssignments[].topologyAssignment is"
f" absent/empty{rf_clause}. "
"Kueue removes only the scheduling gates that it manages when it admits"
" the workload"
" (https://kueue.sigs.k8s.io/docs/tasks/troubleshooting/troubleshooting_pods/)."
)
def _emit_workload_pod_correlation(
ctx: FactContext, wl: dict[str, Any]
) -> None:
"""Emits missing-pod and scheduling-gate facts for an admitted Workload.
Admitted means the `Admitted` condition is True. `status.admission` alone is
not used: Kueue fills it at quota reservation, while admission checks may
still be pending and the job suspended (the admission-check facts cover
that state).
Args:
ctx: Fact context.
wl: Workload object.
"""
wl_ref = f"Workload/{k8s.namespace(wl)}/{k8s.name(wl)}"
status = k8s.status(wl)
if (
not k8s.has_condition(wl, "Admitted")
or k8s.has_condition(wl, "PodsReady")
or k8s.has_condition(wl, "Finished")
):
return
expected_pods = sum(
k8s.as_int(ps.get("count"))
for ps in k8s.dict_items(k8s.spec(wl).get("podSets"))
)
matching_pods = _pods_of_workload(ctx, wl)
if expected_pods > 0 and not matching_pods:
ctx.add(
f"workload-pods:{wl_ref}:zero-pods",
f"WORKLOAD_POD_FACTS: [{wl_ref}] Admitted=True (expected"
f" {expected_pods} pod(s) across spec.podSets), but 0 matching Pod"
f" objects exist in namespace {k8s.namespace(wl)!r} in the snapshot.",
)
return
gated_count = 0
gate_names: set[str] = set()
for p in matching_pods:
gates = _pod_gates(p)
if gates:
gated_count += 1
gate_names.update(gates)
if not gated_count:
return
sample_gates = sorted(gate_names)
has_topo_assign, topo_note = _topology_gate_note(ctx, status, sample_gates)
ctx.add(
f"workload-pods:{wl_ref}:gated",
f"WORKLOAD_POD_FACTS: [{wl_ref}] Admitted=True;"
f" {gated_count}/{len(matching_pods)} pod(s) remain Pending with"
f" spec.schedulingGates={sample_gates} (topologyAssignment"
f" present={has_topo_assign}).{topo_note}",
)
def _emit_pod_status_facts(ctx: FactContext, p: dict[str, Any]) -> None:
"""Emits container waiting and non-zero termination facts for one Pod."""
p_ns = k8s.namespace(p)
p_ref = f"Pod/{p_ns}/{k8s.name(p)}"
node_name = k8s.spec(p).get("nodeName")
for field, cs in k8s.container_statuses(p):
cname = k8s.as_text(cs.get("name"))
st = k8s.as_dict(cs.get("state"))
waiting = k8s.as_dict(st.get("waiting"))
w_reason = k8s.as_text(waiting.get("reason"))
if w_reason and w_reason not in ("ContainerCreating", "PodInitializing"):
w_msg = k8s.as_text(waiting.get("message"))[:240]
ctx.add(
f"pod-status:{p_ns}:{cname}:{w_reason}",
f"POD_STATUS_FACT: [{p_ref}] (node={node_name}) {field}.{cname}"
f" waiting reason={w_reason}: {w_msg}",
)
for t_source, t_dict in (
("state.terminated", st.get("terminated")),
(
"lastState.terminated",
k8s.as_dict(cs.get("lastState")).get("terminated"),
),
):
if isinstance(t_dict, dict) and t_dict.get("exitCode") not in (None, 0):
t_reason = k8s.as_text(t_dict.get("reason"))
t_msg = k8s.as_text(t_dict.get("message"))[:200]
ctx.add(
f"pod-status:{p_ns}:{cname}:exit-{t_dict.get('exitCode')}",
f"POD_STATUS_FACT: [{p_ref}] (node={node_name}) {field}.{cname}"
f" {t_source} exit_code={t_dict.get('exitCode')} reason={t_reason}"
f" restartCount={cs.get('restartCount')}"
+ (f": {t_msg}" if t_msg else ""),
)
def emit_workload_pods(ctx: FactContext) -> None:
"""1f. Workload -> Pod correlation & Pod failure/gate facts."""
for wl in ctx.workloads:
_emit_workload_pod_correlation(ctx, wl)
for p in ctx.pods:
_emit_pod_status_facts(ctx, p)
# ---------------------------------------------------------------------------
# 2 / 3. Events
# ---------------------------------------------------------------------------
def emit_warning_events(ctx: FactContext) -> None:
"""Emits section 2 deduplicated Warning events ordered newest first."""
seen_ids: set[tuple[str, str, str]] = set()
warnings: list[tuple[str, str, str]] = []
for ev in ctx.events:
if k8s.as_text(ev.get("type")) != "Warning":
continue
ident = _event_identity(ev)
if ident in seen_ids:
continue
seen_ids.add(ident)
# Kind is deliberately left out of the key so the same event seen in the
# controller log (trace_logs.py) shares the id.
group = report_output.fact_group_key(
"event",
"",
k8s.as_text(ev.get("reason")),
k8s.as_text(ev.get("message")),
)
warnings.append((k8s.event_timestamp(ev), _event_summary(ev), group))
warnings.sort(key=lambda t: t[0], reverse=True)
for ts, line, group in warnings[:25]:
ctx.add(group, f"WARNING_EVENT: {ts + ' ' if ts else ''}{line}")
if len(warnings) > 25:
ctx.add(
None,
f"WARNING_EVENT: ... {len(warnings) - 25} more Warning events omitted"
" (oldest)",
)
def emit_deletion_events(ctx: FactContext) -> None:
"""Emits section 3 non-housekeeping object deletion Events newest first."""
deletions: list[tuple[str, str, str]] = []
for ev in ctx.events:
msg = k8s.as_text(ev.get("message"))
reason = k8s.as_text(ev.get("reason"))
obj = k8s.as_dict(ev.get("involvedObject"))
if k8s.as_text(obj.get("kind")) in _HOUSEKEEPING_EVENT_KINDS:
continue
if re.search(r"\bdelet(?:ed|ing|ion)\b", msg, re.IGNORECASE) or re.search(
r"(?<![a-z])delet", reason, re.IGNORECASE
):
deletions.append((
k8s.event_timestamp(ev),
_event_summary(ev),
f"deletion:{obj.get('kind', '')}:{reason}",
))
deletions.sort(key=lambda t: t[0], reverse=True)
for ts, line, group in deletions[:10]:
ctx.add(group, f"DELETION_EVENT: {ts + ' ' if ts else ''}{line}")
if len(deletions) > 10:
ctx.add(
None,
f"DELETION_EVENT: ... {len(deletions) - 10} more deletion-related"
" events omitted (oldest)",
)
# ---------------------------------------------------------------------------
# 4. ClusterQueue facts
# ---------------------------------------------------------------------------
def _cq_status_parts(status: dict[str, Any]) -> list[str]:
"""Formats workload counts, fair-sharing share, and borrowed quota."""
status_parts: list[str] = []
if "admittedWorkloads" in status or "pendingWorkloads" in status:
status_parts.append(
f"admittedWorkloads={status.get('admittedWorkloads', 0)},"
f" pendingWorkloads={status.get('pendingWorkloads', 0)}"
)
fs_ws = (
(status.get("fairSharing") or {}).get("weightedShare")
if isinstance(status.get("fairSharing"), dict)
else None
)
if fs_ws is not None:
status_parts.append(f"fairSharing.weightedShare={fs_ws}")
borrowed_parts: list[str] = []
for fu in k8s.dict_items(
status.get("flavorsUsage") or status.get("flavorsReservation") or []
):
fl_n = fu.get("name", "")
for r_u in k8s.dict_items(fu.get("resources")):
if r_u.get("borrowed") and str(r_u.get("borrowed")) != "0":
borrowed_parts.append(
f"{fl_n}.{r_u.get('name')}:"
f" total={r_u.get('total')}/borrowed={r_u.get('borrowed')}"
)
if borrowed_parts:
status_parts.append(f"borrowed=[{', '.join(borrowed_parts)}]")
return status_parts
def emit_clusterqueues(ctx: FactContext) -> None:
"""Emits section 4 ClusterQueue strategy, cohort, quota, and preemption."""
for cq in ctx.cqs:
cq_name = k8s.name(cq)
spec = k8s.spec(cq)
q_strat = spec.get("queueingStrategy", "BestEffortFIFO")
cohort = _cq_cohort(cq)
quotas = _resource_quota_summary(cq)
quota_str = "; ".join(
f"{res}: [{', '.join(v)}]" for res, v in sorted(quotas.items())
)
status_parts = _cq_status_parts(k8s.status(cq))
status_suffix = (
f"; status: {', '.join(status_parts)}" if status_parts else ""
)
fs_w = k8s.as_dict(spec.get("fairSharing")).get("weight")
fs_str = f"; fairSharing.weight={fs_w}" if fs_w is not None else ""
ctx.add(
None,
f"CLUSTERQUEUE_FACTS ({cq_name}): queueingStrategy={q_strat};"
f" cohort={cohort or 'none'}{fs_str};"
f" {quota_str or 'no resourceGroups'}{status_suffix}",
)
if q_strat == "StrictFIFO":
ctx.add(
None,
f"CLUSTERQUEUE_FACTS ({cq_name}): StrictFIFO semantics — the head"
" workload is admitted before any workload behind it is considered;"
" while the head cannot fit, the workloads queued behind it (ordered"
" by priority, then creation time) in the same ClusterQueue remain"
" pending even if they would fit.",
)
preemption = (
spec.get("preemption")
if isinstance(spec.get("preemption"), dict)
else None
)
if preemption:
bwc_obj = preemption.get("borrowWithinCohort")
bwc = bwc_obj.get("policy") if isinstance(bwc_obj, dict) else None
reclaim = preemption.get("reclaimWithinCohort")
within = preemption.get("withinClusterQueue")
ctx.add(
None,
f"CLUSTERQUEUE_FACTS ({cq_name}):"
f" preemption.withinClusterQueue={within or 'Never (default)'},"
f" preemption.reclaimWithinCohort={reclaim or 'Never (default)'},"
f" preemption.borrowWithinCohort.policy={bwc or 'Never (default)'}."
" Preemption settings govern evicting running workloads; they do not"
" enable or disable borrowing of idle cohort quota.",
)
def emit_cohort_cpu_arithmetic(ctx: FactContext) -> None:
"""Emits section 4b sibling ClusterQueue CPU quota arithmetic per cohort."""
for cohort, members in sorted(ctx.cohort_map.items()):
if len(members) < 2:
continue
quotas_by_name = {k8s.name(m): _cpu_quota(m) for m in members}
unparsed = [
f"{name} ({'; '.join(q['unparsed'])})"
for name, q in quotas_by_name.items()
if q["unparsed"]
]
if unparsed:
ctx.add(
None,
f"COHORT_CPU_ARITHMETIC (cohort={cohort}): not computed — unparsable"
f" cpu quantity on {', '.join(unparsed)}",
)
continue
total_lendable = sum(q["lendable"] for q in quotas_by_name.values())
rows: list[str] = []
for name, q in sorted(quotas_by_name.items()):
from_siblings = total_lendable - q["lendable"]
bl = q["borrowing_limit"]
borrowable = from_siblings if bl is None else min(from_siblings, bl)
bound = q["nominal"] + borrowable
rows.append(
f"{name}: nominal={_fmt_num(q['nominal'])}"
f" lendable={_fmt_num(q['lendable'])} "
f"borrowingLimit={'unset' if bl is None else _fmt_num(bl)} "
f"-> nominal+borrowable-from-siblings={_fmt_num(q['nominal'])}+{_fmt_num(borrowable)}={_fmt_num(bound)}"
)
shown = rows[:20]
more = f"; ... {len(rows) - 20} more members" if len(rows) > 20 else ""
if ctx.cohort_objects:
cohort_obj_note = (
f" {len(ctx.cohort_objects)} Cohort object(s) present in snapshot —"
" quota defined on a Cohort or inherited from a parent cohort is NOT"
" included below."
)
else:
cohort_obj_note = (
" No Cohort objects in snapshot; quota defined on a Cohort or"
" parent cohort (if any) is not included."
)
ctx.add(
None,
f"COHORT_CPU_ARITHMETIC (cohort={cohort}, members={len(members)}):"
" per-flavor cpu totals; lendable = sum over flavors of"
" min(lendingLimit, nominalQuota); borrowable-from-siblings = min(sum"
" of siblings' lendable, own borrowingLimit), assuming siblings are"
f" idle.{cohort_obj_note} "
+ "; ".join(shown)
+ more,
)
def _node_capacity_summary(
matching_nodes: list[dict[str, Any]],
) -> tuple[int, int, list[str]]:
"""(ready count, unschedulable count, per-resource max/sum of allocatable) over the given nodes."""
ready = 0
unschedulable = 0
per_res: dict[str, list[float]] = {}
for n in matching_nodes:
if k8s.spec(n).get("unschedulable"):
unschedulable += 1
if k8s.has_condition(n, "Ready"):
ready += 1
for r_name, r_val in k8s.as_dict(k8s.status(n).get("allocatable")).items():
if (
r_name in ("cpu", "memory", "ephemeral-storage")
or "/" in str(r_name)
or str(r_name).startswith("hugepages-")
):
q = _parse_quantity(r_val)
if q is not None:
per_res.setdefault(str(r_name), []).append(q)
res_parts = [
f"{r}: max/node={_fmt_qty(max(vals), r)}, sum={_fmt_qty(sum(vals), r)}"
for r, vals in sorted(per_res.items())
]
return ready, unschedulable, res_parts
def emit_flavor_node_capacity(ctx: FactContext) -> None:
"""Emits section 4c observational Node capacity per ResourceFlavor."""
if not ctx.nodes:
return
for fl_name, rf in sorted(ctx.rf_by_name.items()):
rf_labels = _rf_node_labels(rf)
if not isinstance(rf_labels, dict):
ctx.add(
None,
f"FLAVOR_NODE_CAPACITY (flavor={fl_name}): spec.nodeLabels is not a"
f" mapping ({type(rf_labels).__name__}); node matching skipped.",
)
continue
matching_nodes = _nodes_matching_labels(ctx.nodes, rf_labels)
if not matching_nodes:
ctx.add(
None,
f"FLAVOR_NODE_CAPACITY (flavor={fl_name}):"
f" nodeLabels={rf_labels or {}}; 0 matching Node(s) in the snapshot.",
)
continue
ready, unschedulable, res_parts = _node_capacity_summary(matching_nodes)
ctx.add(
None,
f"FLAVOR_NODE_CAPACITY (flavor={fl_name}):"
f" nodeLabels={rf_labels or {}}; {len(matching_nodes)} matching Node(s)"
" (label equality,"
" https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/;"
" a TAS flavor additionally requires its Topology level labels),"
f" Ready={ready}, unschedulable={unschedulable}; allocatable"
f" {'; '.join(res_parts) or 'n/a'}. Snapshot observation: nodeLabels"
" select the Node set the flavor's pods may land on"
" (https://kueue.sigs.k8s.io/docs/concepts/resource_flavor/); these"
" figures carry no verdict without a scheduler or controller message"
" on this workload's pods or Workload.",
)
# ---------------------------------------------------------------------------
# 4d. Cohort quota layout and cohort nominalQuota vs Node allocatable
# ---------------------------------------------------------------------------
_FlavorRes = tuple[str, str]
_MemberEntry = tuple[str, float, dict[str, Any]]
@dataclasses.dataclass
class _CohortLayout:
"""Aggregated nominal quota and member entries for one cohort."""
cohort: str
members: list[dict[str, Any]]
nominal: dict[_FlavorRes, float] = dataclasses.field(default_factory=dict)
pairs: dict[_FlavorRes, list[_MemberEntry]] = dataclasses.field(
default_factory=dict
)
def __post_init__(self) -> None:
for m in self.members:
m_name = k8s.name(m)
for _, fl, res in k8s.flavor_quotas(m):
if not fl.get("name") or not res.get("name"):
continue
key = (str(fl["name"]), str(res["name"]))
nom = _parse_quantity(res.get("nominalQuota"))
if nom is not None:
self.nominal[key] = self.nominal.get(key, 0.0) + nom
self.pairs.setdefault(key, []).append((m_name, nom, m))
@property
def has_reclaim_or_fs(self) -> bool:
return any(
(
k8s.as_dict(k8s.spec(m).get("preemption")).get(
"reclaimWithinCohort"
)
in ("Any", "LowerPriority")
)
or bool(k8s.spec(m).get("fairSharing"))
for m in self.members
)
def member_layout(self, fl_name: str, r_name: str) -> list[str]:
"""Per-member nominal/borrowingLimit/lendingLimit and status reservation for one flavor+resource."""
out_rows: list[str] = []
for m_name, m_nom, m_cq in self.pairs.get((fl_name, r_name), []):
bl_v = ld_v = None
for _, fl, res in k8s.flavor_quotas(m_cq):
if str(fl.get("name")) == fl_name and str(res.get("name")) == r_name:
bl_v = _parse_quantity(res.get("borrowingLimit"))
ld_v = _parse_quantity(res.get("lendingLimit"))
m_status = k8s.status(m_cq)
reserved, borrowed = _flavor_reservation(m_status, fl_name, r_name)
out_rows.append(
f"{m_name}(nominal={_fmt_qty(m_nom, r_name)},"
f" borrowingLimit={'unset' if bl_v is None else _fmt_qty(bl_v, r_name)},"
f" lendingLimit={'unset' if ld_v is None else _fmt_qty(ld_v, r_name)},"
f" reserved={_fmt_qty(reserved, r_name)},"
f" borrowed={_fmt_qty(borrowed, r_name)},"
f" admitted={k8s.as_int(m_status.get('admittedWorkloads'))},"
f" pending={k8s.as_int(m_status.get('pendingWorkloads'))})"
)
return out_rows
def _flavor_reservation(
cq_status: dict[str, Any], fl_name: str, r_name: str
) -> tuple[float | None, float | None]:
"""(total, borrowed) of `status.flavorsReservation` for one flavor+resource (last match wins)."""
reserved = borrowed = None
for fr in k8s.dict_items(cq_status.get("flavorsReservation")):
if str(fr.get("name")) == fl_name:
for rr in k8s.dict_items(fr.get("resources")):
if str(rr.get("name")) == r_name:
reserved = _parse_quantity(rr.get("total"))
borrowed = _parse_quantity(rr.get("borrowed"))
return reserved, borrowed
def _borrowing_active(
entries: list[_MemberEntry], fl_name: str, r_name: str
) -> bool:
"""True when a zero-nominal member has workloads or any member reports borrowed > 0."""
for _, s_nom, s_cq in entries:
s_st = k8s.status(s_cq)
if s_nom == 0 and (
k8s.as_int(s_st.get("admittedWorkloads")) > 0
or k8s.as_int(s_st.get("pendingWorkloads")) > 0
):
return True
for fr in k8s.dict_items(s_st.get("flavorsReservation")):
if str(fr.get("name")) == fl_name:
for rr in k8s.dict_items(fr.get("resources")):
if (
str(rr.get("name")) == r_name
and (_parse_quantity(rr.get("borrowed")) or 0) > 0
):
return True
return False
def _emit_cohort_layout_facts(ctx: FactContext, layout: _CohortLayout) -> None:
for (fl_name, r_name), total_nom in sorted(layout.nominal.items()):
if total_nom <= 0 or not layout.has_reclaim_or_fs:
continue
entries = layout.pairs.get((fl_name, r_name), [])
if len(entries) < 2:
continue
borrowing_active = _borrowing_active(entries, fl_name, r_name)
ctx.add(
f"cohort-layout:{layout.cohort}:layout:{fl_name}:{r_name}"
if borrowing_active
else None,
f"COHORT_QUOTA_LAYOUT (cohort={layout.cohort}, flavor={fl_name},"
f" resource={r_name}): cohort nominalQuota total"
f" {_fmt_qty(total_nom, r_name)}; reclaimWithinCohort or fairSharing is"
" set on at least one member. Members:"
f" {'; '.join(layout.member_layout(fl_name, r_name))}. A ClusterQueue"
" admits beyond its nominalQuota by borrowing nominalQuota that is"
" unused by cohort members or defined on the Cohort / parent Cohorts"
" (Cohort.spec.resourceGroups, not included in the totals above), and"
" workloads admitted on borrowed quota are preemption candidates when"
" a sibling reclaims (spec.preemption.reclaimWithinCohort) or fair"
" sharing rebalances"
" (https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/,"
" https://kueue.sigs.k8s.io/docs/concepts/preemption/).",
)
def _emit_cohort_node_arithmetic(
ctx: FactContext, layout: _CohortLayout
) -> None:
"""Emits cohort nominalQuota vs matching Node allocatable facts."""
cohort = layout.cohort
for (fl_name, r_name), total_nom in sorted(layout.nominal.items()):
rf = ctx.rf_by_name.get(fl_name)
if rf is None:
ctx.add(
None,
f"COHORT_RESOURCE_ARITHMETIC (cohort={cohort}, flavor={fl_name},"
f" resource={r_name}): ResourceFlavor object not in snapshot; node"
" arithmetic skipped.",
)
continue
rf_labels = k8s.spec(rf).get("nodeLabels") or {}
if not isinstance(rf_labels, dict):
continue
matching_nodes = _nodes_matching_labels(ctx.nodes, rf_labels)
if not matching_nodes:
continue
match_note = (
" (nodeLabels unset: every Node counts)" if not rf_labels else ""
)
allocatable = [
k8s.as_dict(k8s.status(n).get("allocatable")) for n in matching_nodes
]
node_alloc = sum(
_parse_quantity(alloc.get(r_name)) or 0.0 for alloc in allocatable
)
if node_alloc > 0 and total_nom > node_alloc:
ctx.add(
f"cohort-overcommit:{cohort}:overcommit:{fl_name}:{r_name}",
f"COHORT_RESOURCE_ARITHMETIC (cohort={cohort}, flavor={fl_name},"
f" resource={r_name}): sum of member ClusterQueue nominalQuota is"
f" {_fmt_qty(total_nom, r_name)}; allocatable {r_name} on the"
f" {len(matching_nodes)} matching Node(s){match_note} in the snapshot"
f" is {_fmt_qty(node_alloc, r_name)}. Members:"
f" {'; '.join(layout.member_layout(fl_name, r_name))}. Quota defined"
" on the Cohort or parent Cohorts (Cohort.spec.resourceGroups), if"
" any, is not included in the sum. For non-TAS flavors admission is"
" decided against declared quota, not node allocatable. nominalQuota"
" is the quantity of this resource that is available for a"
" ClusterQueue at a specific time"
" (https://kueue.sigs.k8s.io/docs/concepts/cluster_queue/); whether"
" capacity beyond the snapshot's nodes is reachable is not visible"
" from the snapshot.",
)
def emit_cohort_layout(ctx: FactContext) -> None:
"""Emits section 4d cohort quota layout and Node allocatable comparisons."""
for cohort, members in sorted(ctx.cohort_map.items()):
if len(members) < 2:
continue
layout = _CohortLayout(cohort, members)
_emit_cohort_layout_facts(ctx, layout)
if ctx.nodes:
_emit_cohort_node_arithmetic(ctx, layout)
# ---------------------------------------------------------------------------
# 5 / 6. ProvisioningRequestConfig and KueueConfiguration
# ---------------------------------------------------------------------------
def emit_provisioning_request_configs(ctx: FactContext) -> None:
"""5. ProvisioningRequestConfig facts."""
for prc in ctx.prcs:
prc_name = k8s.name(prc)
spec = k8s.spec(prc)
retry = k8s.as_dict(spec.get("retryStrategy"))
is_default_retry = (
retry.get("backoffLimitCount") == 3
and retry.get("backoffBaseSeconds") == 60
and retry.get("backoffMaxSeconds") == 1800
)
if is_default_retry:
retry_desc: Any = (
f"{retry} (standard Kueue default values — normal retry behavior, not"
" a misconfiguration)"
)
else:
retry_desc = (
retry
or "unset (defaults: backoffLimitCount=3, backoffBaseSeconds=60, backoffMaxSeconds=1800)"
)
ctx.add(
None,
f"PROVISIONINGREQUESTCONFIG_FACTS ({prc_name}):"
f" provisioningClassName={spec.get('provisioningClassName')};"
f" managedResources={spec.get('managedResources')};"
f" retryStrategy={retry_desc}",
)
if retry.get("backoffBaseSeconds") == 0:
ctx.add(
None,
f"PROVISIONINGREQUESTCONFIG_FACTS ({prc_name}):"
" retryStrategy.backoffBaseSeconds=0, so the exponential retry delay"
" (min(backoffBaseSeconds^n, backoffMaxSeconds),"
" https://kueue.sigs.k8s.io/docs/concepts/admission_check/provisioning_request/)"
" evaluates to 0 seconds for every attempt.",
)
def _load_manager_config(
ctx: FactContext, cm: dict[str, Any]
) -> dict[str, Any] | None:
"""Parses `controller_manager_config.yaml`; emits parse facts and returns None when there is nothing to inspect."""
dup_info = cm.get("_yaml_duplicate_keys")
if isinstance(dup_info, list) and dup_info:
ctx.add(
"config:duplicate-yaml-key",
"KUEUECONFIGURATION_FACTS: ConfigMap kueue-manager-config YAML source"
" contains duplicate mapping key(s): "
+ "; ".join(str(x) for x in dup_info)
+ ".",
)
cfg_raw = k8s.as_dict(cm.get("data")).get(k8s.KUEUE_CONFIG_KEY) or ""
if not cfg_raw:
return None
try:
cfg = yaml.safe_load(cfg_raw)
except yaml.YAMLError as exc:
ctx.add(
"config:parse-error",
"KUEUECONFIGURATION_FACTS: controller_manager_config.yaml failed to"
f" parse as YAML: {exc}",
)
return None
if not isinstance(cfg, dict):
ctx.add(
None,
"KUEUECONFIGURATION_FACTS: controller_manager_config.yaml top level is"
f" {type(cfg).__name__}, not a mapping",
)
return None
return cfg
def _emit_config_general_facts(ctx: FactContext, cfg: dict[str, Any]) -> None:
"""Emits general integrations, client, leader-election, and retention facts."""
if "manageJobsWithoutQueueName" in cfg:
ctx.add(
None,
"KUEUECONFIGURATION_FACTS:"
f" manageJobsWithoutQueueName={cfg.get('manageJobsWithoutQueueName')}, "
f"integrations.frameworks={(cfg.get('integrations') or {}).get('frameworks') if isinstance(cfg.get('integrations'), dict) else None}",
)
if any(
k in cfg for k in ("clientConnection", "leaderElection", "fairSharing")
):
cc = k8s.as_dict(cfg.get("clientConnection"))
le = k8s.as_dict(cfg.get("leaderElection"))
fs = k8s.as_dict(cfg.get("fairSharing"))
parts_cfg: list[str] = []
if cc:
parts_cfg.append(
f"clientConnection={{qps: {cc.get('qps')}, burst: {cc.get('burst')}}}"
)
if le:
parts_cfg.append(
f"leaderElection={{leaderElect: {le.get('leaderElect')},"
f" leaseDuration: {le.get('leaseDuration')}, renewDeadline:"
f" {le.get('renewDeadline')}, retryPeriod: {le.get('retryPeriod')}}}"
)
if fs:
parts_cfg.append(f"fairSharing={fs}")
if parts_cfg:
ctx.add(None, "KUEUECONFIGURATION_FACTS: " + ", ".join(parts_cfg))
if "objectRetentionPolicies" in cfg:
orp = k8s.as_dict(cfg.get("objectRetentionPolicies"))
w_orp = k8s.as_dict(orp.get("workloads"))
ctx.add(
None,
"KUEUECONFIGURATION_FACTS:"
f" objectRetentionPolicies.workloads={w_orp or orp} "
"(Kueue deletes finished Workloads after afterFinished and"
" Kueue-deactivated Workloads after "
"afterDeactivatedByKueue —"
" https://kueue.sigs.k8s.io/docs/tasks/manage/setup_object_retention_policy/)",
)
def _emit_config_wait_for_pods_ready(
ctx: FactContext, cfg: dict[str, Any]
) -> None:
"""Emits waitForPodsReady configuration and requeuingStrategy facts."""
if "waitForPodsReady" not in cfg:
return
wfpr = cfg.get("waitForPodsReady")
if not isinstance(wfpr, dict):
ctx.add(
None,
f"KUEUECONFIGURATION_FACTS: waitForPodsReady is {type(wfpr).__name__}"
f" ({wfpr!r}); the API expects a mapping"
" (https://kueue.sigs.k8s.io/docs/reference/kueue-config.v1beta2/).",
)
return
req_strat = k8s.as_dict(wfpr.get("requeuingStrategy"))
blc = req_strat.get("backoffLimitCount")
# config v1beta1 has 'enable'; v1beta2 removed it (presence of the block
# enables the feature).
if str(cfg.get("apiVersion") or "").endswith("v1beta1"):
enabled = bool(wfpr.get("enable", False))
enable_str = f"enable={wfpr.get('enable')}"
else:
enabled = True
enable_str = (
"present (config v1beta2 has no `enable` field; the block being present"
" turns the feature on)"
)
blc_note = ""
if enabled and blc is None:
blc_note = (
" (unset is the Kueue default — null means requeues after a"
" PodsReadyTimeout eviction are unbounded; "
"this field only matters if workloads actually show Evicted"
" reason=PodsReadyTimeout with a growing "
"status.requeueState.count —"
" https://kueue.sigs.k8s.io/docs/tasks/manage/setup_wait_for_pods_ready/)"
)
ctx.add(
None,
f"KUEUECONFIGURATION_FACTS: waitForPodsReady {enable_str},"
f" timeout={wfpr.get('timeout')},"
f" blockAdmission={wfpr.get('blockAdmission')},"
f" recoveryTimeout={wfpr.get('recoveryTimeout')},"
f" requeuingStrategy.backoffLimitCount={'unset' if blc is None else blc}"
+ blc_note,
)
def _transform_candidate_cqs(
ctx: FactContext, inp: str, outputs: list[str]
) -> set[str]:
"""ClusterQueue names targeted by Workloads/Events using `inp`/`outputs` via LocalQueues."""
targets = {t for t in (inp, *outputs) if t}
cqs: set[str] = set()
for wl in ctx.workloads:
q_name = str(k8s.spec(wl).get("queueName") or "")
lq = ctx.lq_by_ref.get(f"{k8s.namespace(wl)}/{q_name}") if q_name else None
cq_n = str(k8s.spec(lq).get("clusterQueue") or "") if lq else ""
if cq_n and any(
t in str(k8s.spec(wl)) or t in str(k8s.status(wl)) for t in targets
):
cqs.add(cq_n)
for ev in ctx.events:
msg = str(ev.get("message") or "")
if any(t in msg for t in targets):
ev_ns = str(
k8s.as_dict(ev.get("involvedObject")).get("namespace")
or k8s.namespace(ev)
)
for lq in ctx.lqs:
if not ev_ns or k8s.namespace(lq) == ev_ns:
cq_n = str(k8s.spec(lq).get("clusterQueue") or "")
if cq_n:
cqs.add(cq_n)
if not cqs:
cqs = {
str(k8s.spec(lq).get("clusterQueue") or "")
for lq in ctx.lqs
if k8s.spec(lq).get("clusterQueue")
}
return cqs
def _emit_config_transformations(ctx: FactContext, cfg: dict[str, Any]) -> None:
"""Emits resources.transformations facts and missing ClusterQueue outputs."""
transforms = k8s.as_dict(cfg.get("resources")).get("transformations") or []
for tr in k8s.dict_items(transforms):
inp = k8s.as_text(tr.get("input"))
strategy = tr.get("strategy", "Retain")
outputs = [str(o) for o in k8s.as_dict(tr.get("outputs"))]
replace_note = ""
if strategy == "Replace":
replace_note = (
" (with strategy Replace the input resource is removed from the"
" effective request and only the outputs are counted against quota)"
)
ctx.add(
None,
f"KUEUECONFIGURATION_FACTS: resources.transformations entry input={inp}"
f" strategy={strategy} outputs={outputs}"
+ replace_note,
)
if strategy != "Replace":
continue
candidate_cqs = _transform_candidate_cqs(ctx, inp, outputs)
for cq in ctx.cqs:
covered: list[str] = []
for rg in k8s.resource_groups(cq):
covered.extend(str(r) for r in k8s.as_list(rg.get("coveredResources")))
participates = (
inp in covered
or any(o in covered for o in outputs)
or k8s.name(cq) in candidate_cqs
)
missing = [o for o in outputs if o not in covered]
if participates and missing:
ctx.add(
None,
f"KUEUECONFIGURATION_FACTS: ClusterQueue {k8s.name(cq)} covers"
f" input {inp!r}: {inp in covered}; coveredResources={covered} does"
f" not include transformation output(s) {missing}",
)
def emit_kueue_configuration(ctx: FactContext) -> None:
"""6. KueueConfiguration (kueue-manager-config) facts."""
for cm in ctx.configmaps:
if k8s.metadata(cm).get("name") != "kueue-manager-config":
continue
cfg = _load_manager_config(ctx, cm)
if cfg is None:
continue
_emit_config_general_facts(ctx, cfg)
_emit_config_wait_for_pods_ready(ctx, cfg)
_emit_config_transformations(ctx, cfg)
# ---------------------------------------------------------------------------
# 7 / 8. ResourceFlavor <-> Node label matching, Node taints and conditions
# ---------------------------------------------------------------------------
def _rf_label_breakdown(
nodes: list[dict[str, Any]], labels: dict[str, Any]
) -> tuple[list[str], bool, bool]:
"""Per-key match counts; (rows, some key matches a node, some key matches none)."""
per_key: list[str] = []
some_match = False
zero_match = False
for k, v in labels.items():
exact = sum(1 for n in nodes if k8s.labels(n).get(k) == v)
other_vals = sorted({
str(k8s.labels(n).get(k))
for n in nodes
if k in k8s.labels(n) and k8s.labels(n).get(k) != v
})
if exact > 0:
some_match = True
else:
zero_match = True
if other_vals:
per_key.append(
f"{k}={v!r} on {exact}/{len(nodes)} nodes (other values on nodes:"
f" {other_vals[:4]})"
)
else:
per_key.append(f"{k}={v!r} on {exact}/{len(nodes)} nodes")
return per_key, some_match, zero_match
def _emit_rf_node_match(
ctx: FactContext, rf: dict[str, Any], base: str, labels: dict[str, Any]
) -> None:
"""Emits Node label-matching count and per-key breakdown for one flavor."""
rf_name = k8s.name(rf)
matching = _nodes_matching_labels(ctx.nodes, labels)
rf_key = None
detail = (
f"; {len(matching)} of {len(ctx.nodes)} nodes in the snapshot carry all"
" of these labels."
)
if not matching and len(labels) >= 1:
per_key, _, zero_match = _rf_label_breakdown(ctx.nodes, labels)
detail += " Per-key breakdown: " + ", ".join(per_key) + "."
mf = k8s.compact_managed_fields(k8s.metadata(rf).get("managedFields") or [])
if mf:
detail += f" managedFieldsSummary={mf}."
if zero_match:
rf_key = f"nodeselector:rf:{rf_name}"
ctx.add(rf_key, base + detail)
def emit_flavor_node_labels(ctx: FactContext) -> None:
"""Emits section 7 ResourceFlavor <-> Node label matching facts."""
if ctx.rfs:
ctx.add(
None,
f"RESOURCEFLAVOR_FACTS: {len(ctx.rfs)} ResourceFlavor(s); label"
f" matching below uses the {len(ctx.nodes)} Node object(s) in the"
" snapshot only — nodes created later by an autoscaler or a"
" ProvisioningRequest are not represented.",
)
for rf in ctx.rfs:
spec = k8s.spec(rf)
labels = k8s.as_dict(spec.get("nodeLabels"))
taints = k8s.as_list(spec.get("nodeTaints"))
tolerations = k8s.as_list(spec.get("tolerations"))
base = (
f"RESOURCEFLAVOR_FACTS ({k8s.name(rf)}): nodeLabels={labels or '{}'};"
f" topologyName={spec.get('topologyName')}; nodeTaints={len(taints)};"
f" tolerations={len(tolerations)}"
)
if not labels:
ctx.add(
None,
base
+ "; empty nodeLabels places no node-label constraint (matches any"
" node).",
)
elif ctx.nodes:
_emit_rf_node_match(ctx, rf, base, labels)
else:
ctx.add(
None,
base
+ "; no Node objects in the snapshot, label matching not evaluated.",
)
def _node_pool(n: dict[str, Any]) -> Any:
n_labels = k8s.labels(n)
return next(
(n_labels[k] for k in k8s.NODE_POOL_LABELS if n_labels.get(k)),
k8s.metadata(n).get("name", ""),
)
def emit_node_taints_and_conditions(ctx: FactContext) -> None:
"""8. Node taints and non-Ready / pressure conditions (one fact per pool)."""
seen_taints: set[str] = set()
seen_node_conds: set[str] = set()
for n in ctx.nodes:
pool = _node_pool(n)
for t in k8s.dict_items(k8s.spec(n).get("taints")):
if t.get("effect") in ("NoSchedule", "NoExecute"):
t_str = f"{t.get('key')}={t.get('value')}:{t.get('effect')}"
key = f"{pool}|{t_str}"
if key in seen_taints:
continue
seen_taints.add(key)
ctx.add(
None,
f"NODE_TAINT_FACTS ({pool}): taint {t_str}; pods and"
" ResourceFlavors without a matching toleration cannot land on"
" these nodes.",
)
for c in k8s.conditions(n):
ct = k8s.as_text(c.get("type"))
cs = k8s.as_text(c.get("status"))
if (ct == "Ready" and cs != "True") or (ct != "Ready" and cs == "True"):
cr = k8s.as_text(c.get("reason"))
cm = k8s.as_text(c.get("message"))[:200]
cond_id = f"{pool}|{ct}={cs}|{cr}"
if cond_id in seen_node_conds:
continue
seen_node_conds.add(cond_id)
ctx.add(
f"node-cond:{pool}:{ct}:{cs}",
f"NODE_CONDITION_FACTS ({pool}, sample"
f" node={k8s.metadata(n).get('name', '')}): {ct}={cs} reason={cr}"
+ (f": {cm}" if cm else ""),
)
# Registry: the orchestrator iterates this tuple; order == order of facts in
# the digest.
FACT_EMITTERS: tuple[Callable[[FactContext], None], ...] = (
emit_inventory, # 1
emit_coverage, # 1a
emit_status_conditions, # 1b
emit_queue_chain, # 1c
emit_job_specs, # 1c-bis
emit_admission_checks, # 1d
emit_provisioning_requests, # 1e
emit_workload_pods, # 1f
workload_timeline.emit_workload_timeline, # 1g
emit_warning_events, # 2
emit_deletion_events, # 3
emit_clusterqueues, # 4
emit_cohort_cpu_arithmetic, # 4b
emit_flavor_node_capacity, # 4c
emit_cohort_layout, # 4d
fair_sharing_facts.emit_fair_sharing_arithmetic, # 4e
emit_provisioning_request_configs, # 5
emit_kueue_configuration, # 6
emit_flavor_node_labels, # 7
topology_facts.emit_topology_domains, # 7b
emit_node_taints_and_conditions, # 8
)
snapshot_loaders.py 56.3 KB
"""Object loading, sanitising and grouping for `snapshot.py`.
Responsibilities:
* reading objects from a live cluster (`kubectl`) or from an offline bundle of
YAML/JSON manifests (`load_items`, `load_static_items`), recording every
source that could not be read (`LoadNotes`) instead of dropping it;
* masking Secret payloads and literal container `env[].value` entries
(`_mask_in_place` at load, `_masked_copy` when compacting);
* stripping Kubernetes boilerplate per kind (`sanitize_and_compact_object`);
* filtering noise and ordering Kueue graph objects first
(`filter_and_sort_snapshot_items`);
* collapsing identical Nodes/Pods/Events into groups for the stdout digest
(`group_bulk_objects`, `sample_bulk_groups`);
* maintaining the coverage ledger (`update_ledger`).
`snapshot.py` re-exports the public names so tests keep importing them from
there.
"""
from __future__ import annotations
import argparse
import collections.abc
import dataclasses
import json
import os
import subprocess
from typing import Any, Callable
import k8s_objects as k8s
import report_output
import yaml
_GRAPH_KINDS = {
"cohort",
"cohorts",
"clusterqueue",
"clusterqueues",
"localqueue",
"localqueues",
"resourceflavor",
"resourceflavors",
"admissioncheck",
"admissionchecks",
"provisioningrequestconfig",
"provisioningrequestconfigs",
"topology",
"topologies",
"workload",
"workloads",
"configmap",
"configmaps",
}
# Namespaces of platform add-ons whose Pods are never part of a Kueue admission
# path: the upstream `kube-*` namespaces plus whatever the operator passes via
# --ignore-namespaces / GKE_KUEUE_TROUBLESHOOTING_IGNORE_NAMESPACES
# (see report_output).
_is_managed_addon_namespace = report_output.is_managed_addon_namespace
# Node labels shown in snapshots: anything a ResourceFlavor `nodeLabels`, a
# Topology level or a pod nodeSelector is likely to reference. Everything else
# (OS, arch, image, boot-disk, runtime, ...) is counted but not listed.
_SCHEDULING_LABEL_MARKERS = (
"pool",
"accelerator",
"gpu",
"tpu",
"spot",
"preemptible",
"capacity",
"instance",
"topology",
"zone",
"region",
"machine",
"nodegroup",
"placement",
"reservation",
)
_PRIORITY_KIND_ORDER = {
"Workload": 1,
"LocalQueue": 2,
"ClusterQueue": 3,
"Cohort": 4,
"ResourceFlavor": 5,
"AdmissionCheck": 6,
"ProvisioningRequestConfig": 7,
"ProvisioningRequest": 8,
"Topology": 9,
"WorkloadPriorityClass": 10,
"ConfigMap": 11,
"Job": 12,
"JobSet": 12,
"LeaderWorkerSet": 12,
"TFJob": 12,
"PyTorchJob": 12,
"RayJob": 12,
"MPIJob": 12,
"Event": 13,
"Node": 14,
"Pod": 15,
}
# Event involvedObject kinds that are always kept by
# `filter_and_sort_snapshot_items`.
_RELEVANT_EVENT_KINDS = (
"workload",
"job",
"jobset",
"clusterqueue",
"localqueue",
"admissioncheck",
"provisioningrequest",
"provisioningrequestconfig",
"configmap",
)
CLUSTER_SCOPED_KINDS = (
"clusterqueues.kueue.x-k8s.io,resourceflavors.kueue.x-k8s.io,cohorts.kueue.x-k8s.io,"
"admissionchecks.kueue.x-k8s.io,provisioningrequestconfigs.kueue.x-k8s.io,"
"topologies.kueue.x-k8s.io,workloadpriorityclasses.kueue.x-k8s.io,nodes"
)
NAMESPACED_KINDS = (
"workloads.kueue.x-k8s.io,localqueues.kueue.x-k8s.io,jobs.batch,jobsets.jobset.x-k8s.io,"
"provisioningrequests.autoscaling.x-k8s.io,pods,events"
)
def _is_scheduling_label(key: str) -> bool:
"""True for node labels that commonly drive Kueue flavor/topology matching."""
if key in k8s.NODE_POOL_LABELS:
return True
prefix, sep, _ = key.partition("/")
if (sep and prefix == "beta.kubernetes.io") or key in (
"kubernetes.io/hostname",
"kubernetes.io/os",
"kubernetes.io/arch",
):
return False
low = key.lower()
return any(marker in low for marker in _SCHEDULING_LABEL_MARKERS)
def _pod_has_failure(pod: dict[str, Any]) -> bool:
"""True when a Pod is non-Running/Succeeded or has a container waiting/terminated with an error."""
phase = str(k8s.status(pod).get("phase") or "")
if phase and phase not in ("Running", "Succeeded"):
return True
for _, cs in k8s.container_statuses(pod):
state = k8s.as_dict(cs.get("state"))
waiting = k8s.as_dict(state.get("waiting"))
if waiting.get("reason") and waiting.get("reason") not in (
"ContainerCreating",
"PodInitializing",
):
return True
if k8s.as_dict(state.get("terminated")).get("exitCode") not in (None, 0):
return True
last_term = k8s.as_dict(k8s.as_dict(cs.get("lastState")).get("terminated"))
if last_term.get("exitCode") not in (None, 0):
return True
return False
# ---------------------------------------------------------------------------
# Sanitising / compaction
# ---------------------------------------------------------------------------
def _compact_metadata(meta: dict[str, Any], kind: str) -> dict[str, Any]:
"""Drops noisy metadata fields; summarises managedFields for non-bulk kinds."""
if "managedFields" in meta:
compacted_mf = k8s.compact_managed_fields(meta.pop("managedFields"))
if compacted_mf and kind not in ("Node", "Pod", "Event"):
meta["managedFieldsSummary"] = compacted_mf
for noisy_key in ("uid", "selfLink", "generation", "resourceVersion"):
meta.pop(noisy_key, None)
annotations = dict(k8s.as_dict(meta.get("annotations")))
annotations.pop("kubectl.kubernetes.io/last-applied-configuration", None)
if annotations:
meta["annotations"] = annotations
else:
meta.pop("annotations", None)
return meta
def _compact_node(out: dict[str, Any]) -> dict[str, Any]:
"""Strips non-scheduling labels, annotations, and healthy conditions on a Node."""
meta = out["metadata"]
status = k8s.status(out)
all_labels = k8s.as_dict(meta.get("labels"))
labels = {k: v for k, v in all_labels.items() if _is_scheduling_label(k)}
hidden = len(all_labels) - len(labels)
if hidden > 0:
labels["<other labels omitted>"] = str(hidden)
meta["labels"] = labels
meta.pop("annotations", None)
out["metadata"] = meta
out["spec"] = {"taints": k8s.spec(out).get("taints") or []}
allocatable = k8s.as_dict(status.get("allocatable"))
node_conds = []
for c in k8s.dict_items(status.get("conditions")):
ctype = c.get("type")
cstatus = c.get("status")
if ctype == "Ready" or cstatus == "True":
entry: dict[str, Any] = {"type": ctype, "status": cstatus}
if (ctype == "Ready" and cstatus != "True") or (
ctype != "Ready" and cstatus == "True"
):
if c.get("reason"):
entry["reason"] = c.get("reason")
if c.get("message"):
entry["message"] = str(c.get("message"))[:200]
node_conds.append(entry)
out["status"] = {
"allocatable": {
k: v
for k, v in allocatable.items()
if k in ("cpu", "memory", "pods") or "/" in k
},
"conditions": node_conds,
}
return out
def _compact_container_statuses(statuses: Any) -> list[dict[str, Any]]:
return [
{
"name": cs.get("name"),
"ready": cs.get("ready"),
"restartCount": cs.get("restartCount"),
"state": cs.get("state"),
"lastState": cs.get("lastState"),
}
for cs in k8s.dict_items(statuses)
]
def _compact_pod_spec(spec: dict[str, Any]) -> dict[str, Any]:
"""Retains scheduling fields and container image/resource specs from a Pod spec."""
containers = [
{
"name": c.get("name"),
"image": c.get("image"),
"resources": c.get("resources"),
}
for c in k8s.dict_items(spec.get("containers"))
]
init_containers = [
{
"name": c.get("name"),
"image": c.get("image"),
"imagePullPolicy": c.get("imagePullPolicy"),
"resources": c.get("resources"),
}
for c in k8s.dict_items(spec.get("initContainers"))
]
pod_spec: dict[str, Any] = {
"nodeName": spec.get("nodeName"),
"nodeSelector": spec.get("nodeSelector"),
"tolerations": spec.get("tolerations"),
"containers": containers,
}
if spec.get("schedulingGates"):
pod_spec["schedulingGates"] = spec.get("schedulingGates")
if init_containers:
pod_spec["initContainers"] = init_containers
return pod_spec
def _compact_pod(out: dict[str, Any]) -> dict[str, Any]:
"""Compacts a Pod's metadata, spec, and container statuses for the snapshot."""
meta = out["metadata"]
meta.pop("annotations", None)
out["metadata"] = meta
out["spec"] = _compact_pod_spec(k8s.spec(out))
status = k8s.status(out)
pod_status: dict[str, Any] = {"phase": status.get("phase")}
# Pod-level reason/message carry the kubelet verdict (Evicted, NodeShutdown,
# ...) that no condition or container status repeats.
for field in ("reason", "message"):
if status.get(field):
pod_status[field] = status.get(field)
pod_status["conditions"] = status.get("conditions")
pod_status["containerStatuses"] = _compact_container_statuses(
status.get("containerStatuses")
)
if status.get("initContainerStatuses"):
pod_status["initContainerStatuses"] = _compact_container_statuses(
status.get("initContainerStatuses")
)
out["status"] = pod_status
return out
def _compact_event(out: dict[str, Any]) -> dict[str, Any]:
meta = out["metadata"]
involved = k8s.as_dict(out.get("involvedObject"))
return {
"kind": "Event",
"metadata": {
"name": meta.get("name"),
"namespace": meta.get("namespace", "default"),
},
"type": out.get("type"),
"reason": out.get("reason"),
"involvedObject": (
f"{involved.get('kind', '')}/{involved.get('namespace', '')}/{involved.get('name', '')}"
.strip("/")
),
"message": out.get("message"),
"lastTimestamp": (
out.get("lastTimestamp")
or out.get("eventTime")
or meta.get("creationTimestamp")
),
}
_KIND_COMPACTORS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {
"Node": _compact_node,
"Pod": _compact_pod,
"Event": _compact_event,
}
# ---------------------------------------------------------------------------
# Redaction
# ---------------------------------------------------------------------------
REDACTED = "<REDACTED>"
_MAX_TREE_DEPTH = 100
_DEPTH_PLACEHOLDER = f"<nesting below {_MAX_TREE_DEPTH} levels omitted>"
class TreeBudgetError(Exception):
"""A manifest tree is cyclic, too deep, or larger than its budget allows."""
def _env_needs_mask(entry: Any) -> bool:
return (
isinstance(entry, dict)
and "value" in entry
and entry["value"] != REDACTED
)
def _mask_secret_payload(secret: dict[str, Any]) -> None:
"""Masks `data` / `stringData` values of a Secret in place (keys stay)."""
for field in ("data", "stringData"):
payload = secret.get(field)
if isinstance(payload, dict):
secret[field] = {k: REDACTED for k in payload}
elif payload is not None:
secret[field] = REDACTED
def _mask_in_place(obj: dict[str, Any]) -> None:
"""Masks a freshly loaded manifest in place.
Secret payloads and every literal `env[].value` (whether under `containers`,
`initContainers`, `ephemeralContainers`, or CRD fields such as
`spec.trainer.env` / `spec.driver.env`) become `<REDACTED>`; `name`,
`valueFrom`, `command` and `args` stay. A node shared through YAML aliases
is visited once and stays shared.
Args:
obj: A manifest the loader owns (nothing else references it yet).
"""
if obj.get("kind") == "Secret":
_mask_secret_payload(obj)
seen: set[int] = set()
stack: list[Any] = [obj]
while stack:
node = stack.pop()
if not isinstance(node, (dict, list)) or id(node) in seen:
continue
seen.add(id(node))
if isinstance(node, list):
stack.extend(node)
continue
for key, child in node.items():
if key == "env":
for entry in k8s.dict_items(child):
if "value" in entry:
entry["value"] = REDACTED
stack.append(child)
def _masked_env_list(env: Any) -> Any:
"""An `env` list with literal `value` masked, or the same list when clean."""
if not isinstance(env, list) or not any(map(_env_needs_mask, env)):
return env
return [{**e, "value": REDACTED} if _env_needs_mask(e) else e for e in env]
def _masked_copy(value: Any, depth: int = 0) -> Any:
"""`value` with literal `env[].value` entries masked, copying only what changes.
A subtree with nothing to mask is returned as the same object, so the
caller's input is never modified and objects that share a subtree (YAML
aliases in a bundle) keep sharing it.
Args:
value: Any part of a manifest.
depth: Nesting level; kubectl JSON deeper than `_MAX_TREE_DEPTH` is cut.
Returns:
`value` itself or a partial copy with the masked entries.
"""
if not isinstance(value, (dict, list)):
return value
if depth > _MAX_TREE_DEPTH:
return _DEPTH_PLACEHOLDER
out = value
pairs = value.items() if isinstance(value, dict) else enumerate(value)
for key, child in pairs:
if isinstance(value, dict) and key == "env":
new = _masked_env_list(child)
else:
new = _masked_copy(child, depth + 1)
if new is not child:
if out is value:
out = dict(value) if isinstance(value, dict) else list(value)
out[key] = new
return out
class _TreeMeter:
"""Measures manifests the way the full report writes them: every YAML alias expanded.
Through aliases a small file can describe an arbitrarily large or a cyclic
tree. The meter counts the nodes of the expanded tree in time proportional
to the nodes actually stored, and raises `TreeBudgetError` for a cycle, for
nesting deeper than `_MAX_TREE_DEPTH`, and once the manifests charged so far
exceed `budget` nodes (no limit when `budget` is None).
"""
def __init__(self, budget: int | None = None) -> None:
self._left = budget
self._known: dict[int, tuple[int, int]] = {} # id -> (nodes, height)
self._open: set[int] = set()
@property
def exhausted(self) -> bool:
return self._left is not None and self._left < 0
def charge(self, obj: Any) -> None:
"""Counts one manifest against the budget."""
self._open = set()
nodes, _ = self._measure(obj, 0)
if self._left is not None:
self._left -= nodes
if self._left < 0:
raise TreeBudgetError("YAML aliases expand past the size of the file")
def _measure(self, node: Any, depth: int) -> tuple[int, int]:
"""Counts nodes and subtree height under `node`, rejecting deep or cyclic trees."""
if not isinstance(node, (dict, list)):
return 1, 0
if depth > _MAX_TREE_DEPTH:
raise TreeBudgetError(f"nesting deeper than {_MAX_TREE_DEPTH} levels")
known = self._known.get(id(node))
if known is None:
if id(node) in self._open:
raise TreeBudgetError("a YAML alias refers to its own ancestor")
self._open.add(id(node))
nodes, height = 1, 0
for child in node.values() if isinstance(node, dict) else node:
child_nodes, child_height = self._measure(child, depth + 1)
nodes += child_nodes
height = max(height, child_height + 1)
self._open.discard(id(node))
known = self._known[id(node)] = (nodes, height)
if depth + known[1] > _MAX_TREE_DEPTH:
raise TreeBudgetError(f"nesting deeper than {_MAX_TREE_DEPTH} levels")
return known
def sanitize_and_compact_object(obj: dict[str, Any]) -> dict[str, Any]:
"""Strips Kubernetes boilerplate while preserving diagnostic signal and field attribution.
Secret payloads and literal container `env[].value` entries are masked in
the result; the input object is not modified.
Args:
obj: A raw Kubernetes object mapping.
Returns:
The compacted, masked object (non-mapping input is returned unchanged).
"""
if not isinstance(obj, dict):
return obj
out = dict(obj)
out.pop("_yaml_duplicate_keys", None)
kind = str(out.get("kind", ""))
out["metadata"] = _compact_metadata(dict(k8s.metadata(out)), kind)
compactor = _KIND_COMPACTORS.get(kind)
if compactor:
out = compactor(out)
if kind == "Secret":
_mask_secret_payload(out)
return _masked_copy(out)
# ---------------------------------------------------------------------------
# Bulk grouping
# ---------------------------------------------------------------------------
_BULK_NAME_SAMPLE = 5
def _signature(value: Any) -> str:
return json.dumps(value, sort_keys=True, default=str)
def _sample_names(names: list[str]) -> list[str]:
if len(names) <= _BULK_NAME_SAMPLE:
return names
return names[:_BULK_NAME_SAMPLE] + [
f"... {len(names) - _BULK_NAME_SAMPLE} more"
]
_POD_STATUS_VOLATILE_KEYS = frozenset({
"lastTransitionTime",
"lastProbeTime",
"startedAt",
"finishedAt",
"containerID",
"imageID",
})
def _strip_volatile(value: Any) -> Any:
"""Removes timestamps and ids from a status tree so identical failures compare equal."""
if isinstance(value, dict):
return {
k: _strip_volatile(v)
for k, v in value.items()
if k not in _POD_STATUS_VOLATILE_KEYS
}
if isinstance(value, list):
return [_strip_volatile(v) for v in value]
return value
def _pod_failure_signature(status: dict[str, Any]) -> dict[str, Any]:
return _strip_volatile({
"reason": status.get("reason"),
"conditions": status.get("conditions") or [],
"containerStatuses": status.get("containerStatuses") or [],
"initContainerStatuses": status.get("initContainerStatuses") or [],
})
def _group_node(groups: dict[str, dict[str, Any]], it: dict[str, Any]) -> None:
sig = {
"labels": k8s.metadata(it).get("labels") or {},
"taints": k8s.spec(it).get("taints") or [],
"allocatable": k8s.status(it).get("allocatable") or {},
"conditions": k8s.status(it).get("conditions") or [],
}
g = groups.setdefault(
_signature(sig), {"kind": "NodeGroup", "count": 0, "names": [], **sig}
)
g["count"] += 1
g["names"].append(k8s.name(it))
def _group_pod(groups: dict[str, dict[str, Any]], it: dict[str, Any]) -> None:
"""Adds a compacted Pod to its matching PodGroup bucket by failure signature."""
spec = k8s.spec(it)
status = k8s.status(it)
owners = [
f"{o.get('kind', '')}/{o.get('name', '')}" for o in k8s.owner_refs(it)
]
sig = {
"namespace": k8s.namespace(it),
"owners": owners,
"phase": status.get("phase"),
"scheduled": bool(spec.get("nodeName")),
"nodeSelector": spec.get("nodeSelector"),
"tolerations": spec.get("tolerations"),
"schedulingGates": spec.get("schedulingGates"),
"containers": spec.get("containers"),
"initContainers": spec.get("initContainers"),
"failureSignature": _pod_failure_signature(status),
}
g = groups.setdefault(
_signature(sig),
{
"kind": "PodGroup",
"count": 0,
"names": [],
"nodeNames": [],
**{k: v for k, v in sig.items() if k != "failureSignature"},
"representativeStatus": status,
},
)
g["count"] += 1
g["names"].append(k8s.name(it))
node_name = spec.get("nodeName")
if node_name and node_name not in g["nodeNames"]:
g["nodeNames"].append(str(node_name))
def _group_event(groups: dict[str, dict[str, Any]], it: dict[str, Any]) -> None:
"""Adds a compacted Event to its matching EventGroup bucket and updates timestamps."""
sig = {
"type": it.get("type"),
"reason": it.get("reason"),
"message": it.get("message"),
}
ts = str(it.get("lastTimestamp") or "")
g = groups.setdefault(
_signature(sig),
{
"kind": "EventGroup",
"count": 0,
"involvedObjects": [],
"firstTimestamp": ts,
"lastTimestamp": ts,
**sig,
},
)
g["count"] += 1
inv = str(it.get("involvedObject", ""))
if inv not in g["involvedObjects"]:
g["involvedObjects"].append(inv)
if ts:
g["firstTimestamp"] = min(g["firstTimestamp"] or ts, ts)
g["lastTimestamp"] = max(g["lastTimestamp"], ts)
_GROUPERS = {
"Node": ("nodes", _group_node),
"Pod": ("pods", _group_pod),
"Event": ("events", _group_event),
}
def group_bulk_objects(
items: list[dict[str, Any]],
) -> tuple[list[dict[str, Any]], dict[str, list[dict[str, Any]]]]:
"""Collapses diagnostically identical Nodes, Pods, and Events into groups.
Every field shown on a group is copied verbatim from its members, so quotes
taken from a group remain checkable against the ledger.
Args:
items: Sanitised and compacted Kubernetes object mappings.
Returns:
A `(remaining_items, groups)` tuple with complete member lists.
"""
remaining: list[dict[str, Any]] = []
by_group: dict[str, dict[str, dict[str, Any]]] = {
"nodes": {},
"pods": {},
"events": {},
}
for it in items:
if not isinstance(it, dict):
continue
grouper = _GROUPERS.get(k8s.kind(it))
if grouper is None:
remaining.append(it)
continue
group_key, fn = grouper
fn(by_group[group_key], it)
groups = {
k: sorted(v.values(), key=lambda g: -g["count"])
for k, v in by_group.items()
}
return remaining, {k: v for k, v in groups.items() if v}
_GROUP_LIST_KEYS = ("names", "nodeNames", "involvedObjects")
def sample_bulk_groups(
groups: dict[str, list[dict[str, Any]]],
) -> dict[str, list[dict[str, Any]]]:
"""Returns a copy of `groups` with member lists shortened to a sample.
The full report and the ledger keep the complete lists so that every object
name remains quotable; only the digest is sampled.
Args:
groups: Bulk object groups keyed by `"nodes"`, `"pods"`, `"events"`.
Returns:
A shallow copy of `groups` with sampled member name lists.
"""
out: dict[str, list[dict[str, Any]]] = {}
for group_key, group_list in groups.items():
sampled: list[dict[str, Any]] = []
for g in group_list:
g2 = dict(g)
for lk in _GROUP_LIST_KEYS:
if isinstance(g2.get(lk), list):
g2[lk] = _sample_names(list(g2[lk]))
sampled.append(g2)
out[group_key] = sampled
return out
# ---------------------------------------------------------------------------
# Filtering
# ---------------------------------------------------------------------------
def _event_is_relevant(it: dict[str, Any]) -> bool:
involved = k8s.as_dict(it.get("involvedObject"))
inv_kind = str(involved.get("kind", "")).lower()
inv_name = str(involved.get("name", "")).lower()
msg = str(it.get("message", "")).lower()
return (
str(it.get("type", "")) == "Warning"
or inv_kind in _RELEVANT_EVENT_KINDS
or "kueue" in inv_name
or "kueue" in msg
or "provision" in msg
or "fairsh" in msg
or "quota" in msg
or "admit" in msg
)
def _keep_snapshot_item(it: dict[str, Any]) -> bool:
"""Returns True when an object should be kept in the compacted snapshot."""
kind = k8s.kind(it)
ns = k8s.namespace(it)
name = k8s.name(it)
if kind == "Pod":
has_fail = _pod_has_failure(it)
if _is_managed_addon_namespace(ns) and not has_fail:
return False
phase = str(k8s.status(it).get("phase") or "")
if (
phase in ("Running", "Succeeded")
and "kueue" not in name
and not has_fail
):
return False
elif kind == "ConfigMap":
if name != "kueue-manager-config":
return False
elif kind == "Event":
if not _event_is_relevant(it) and _is_managed_addon_namespace(ns):
return False
return True
def filter_and_sort_snapshot_items(
items: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Filters noisy kube-system Pods/Events and orders Kueue graph objects first."""
filtered = [
it for it in items if isinstance(it, dict) and _keep_snapshot_item(it)
]
filtered.sort(
key=lambda x: _PRIORITY_KIND_ORDER.get(str(x.get("kind", "")), 50)
)
return filtered
# ---------------------------------------------------------------------------
# Coverage ledger
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class LedgerInputs:
"""One ledger update: which action ran, what it returned and what was printed."""
ledger_path: str | None
action: str
obj_or_list: Any
raw_output_str: str
detected_version: dict[str, Any] | None = None
def _ledger_items(obj_or_list: Any) -> list[dict[str, Any]]:
if isinstance(obj_or_list, dict):
if obj_or_list.get("kind") == "List":
return k8s.dict_items(obj_or_list.get("items"))
return [obj_or_list]
return k8s.dict_items(obj_or_list)
def _record_item_refs(
item: dict[str, Any], action: str, referenced: set[str], inspected: set[str]
) -> None:
"""Adds the item and the graph objects it points at to the referenced/inspected sets."""
kind = k8s.kind(item).lower()
meta = k8s.metadata(item)
name = meta.get("name") or ""
ns = meta.get("namespace") or ""
ref_id = f"{kind}/{ns}/{name}" if ns else f"{kind}/{name}"
if kind in _GRAPH_KINDS and name:
referenced.add(ref_id)
if action == "get":
inspected.add(ref_id)
if kind != "clusterqueue":
return
spec = k8s.spec(item)
cohort = spec.get("cohort") or spec.get("cohortName")
if isinstance(cohort, str) and cohort:
referenced.add(f"cohort/{cohort}")
if action == "get":
inspected.add(f"cohort/{cohort}")
for rg in k8s.resource_groups(item):
for fl in k8s.dict_items(rg.get("flavors")):
if fl.get("name"):
referenced.add(f"resourceflavor/{fl.get('name')}")
strategy = k8s.as_dict(spec.get("admissionChecksStrategy"))
for ac in k8s.dict_items(strategy.get("admissionChecks")):
if ac.get("name"):
referenced.add(f"admissioncheck/{ac.get('name')}")
for ac_name in k8s.as_list(spec.get("admissionChecks")):
if isinstance(ac_name, str):
referenced.add(f"admissioncheck/{ac_name}")
_LEDGER_CHUNK_CHARS = 120000
_LEDGER_MAX_CHUNKS = 50
def _ledger_strings(value: Any) -> list[str]:
return [x for x in k8s.as_list(value) if isinstance(x, str)]
def _apply_ledger_update(ledger: dict[str, Any], inputs: LedgerInputs) -> None:
"""Merges one script run into the loaded ledger mapping in place."""
if inputs.detected_version:
ledger["detected_kueue_version"] = inputs.detected_version
referenced = set(_ledger_strings(ledger.get("referenced")))
inspected = set(_ledger_strings(ledger.get("inspected")))
for item in _ledger_items(inputs.obj_or_list):
_record_item_refs(item, inputs.action, referenced, inspected)
outputs = _ledger_strings(ledger.get("tool_outputs"))
if inputs.raw_output_str:
# Chunked so that every object name in the full report stays quotable; the
# validator joins all entries into one corpus.
for i in range(0, len(inputs.raw_output_str), _LEDGER_CHUNK_CHARS):
outputs.append(inputs.raw_output_str[i : i + _LEDGER_CHUNK_CHARS])
ledger["referenced"] = sorted(referenced)
ledger["inspected"] = sorted(inspected)
ledger["tool_outputs"] = outputs[-_LEDGER_MAX_CHUNKS:]
def update_ledger(inputs: LedgerInputs) -> None:
"""Updates the coverage ledger with discovered and inspected Kueue graph objects and detected Kueue version.
The read-modify-write runs under the lock every ledger writer takes
(`report_output.mutate_ledger`), so a `trace_logs.py` run in parallel keeps
its entries and this one keeps its own.
Args:
inputs: What the current run loaded and printed.
"""
if not inputs.ledger_path:
return
report_output.mutate_ledger(
inputs.ledger_path,
lambda ledger: _apply_ledger_update(ledger, inputs),
strict=False,
)
# ---------------------------------------------------------------------------
# Offline bundle loading
# ---------------------------------------------------------------------------
class LoadError(Exception):
"""Raised when objects cannot be loaded; carries the user-facing message and next step."""
def __init__(self, message: str, next_step: str) -> None:
super().__init__(message)
self.message = message
self.next_step = next_step
_MAX_LOAD_WARNINGS = 30
@dataclasses.dataclass
class LoadNotes:
"""What a load could not read: full texts for `warnings`, short labels for the coverage line."""
warnings: list[str] = dataclasses.field(default_factory=list)
skipped: list[str] = dataclasses.field(default_factory=list)
def warn(self, text: str) -> None:
self.warnings.append(text)
def skip(self, source: str, detail: str) -> None:
"""Records a source (file, document, kind) whose objects are missing from the result."""
self.skipped.append(source)
self.warnings.append(f"{source} not loaded: {detail}")
def summary(self) -> str:
"""Suffix for error messages: how many sources were skipped and the first reason."""
if not self.skipped:
return ""
first = next((w for w in self.warnings if " not loaded: " in w), "")
return f" ({len(self.skipped)} source(s) skipped; first: {first[:300]})"
def attach(self, raw_obj: dict[str, Any]) -> dict[str, Any]:
"""Stores the notes on a `kind: List` result as `_warnings` / `_skipped_sources`."""
if self.warnings:
shown = self.warnings[:_MAX_LOAD_WARNINGS]
hidden = len(self.warnings) - len(shown)
if hidden:
shown.append(f"... {hidden} more load warnings")
raw_obj.setdefault("_warnings", []).extend(shown)
if self.skipped:
raw_obj["_skipped_sources"] = list(self.skipped)
return raw_obj
class _DuplicateKeyTrackingLoader(yaml.SafeLoader):
"""YAML SafeLoader that records overwritten duplicate keys on the document root.
Mappings are built depth-first, so an overwritten value is complete when it
is summarised. Only keys written in the mapping itself are compared: a key
merged in through `<<` may be overridden without being a duplicate. The
findings of a document are stored on its root mapping as
`_yaml_duplicate_keys` (dotted key paths), never inside nested mappings.
"""
def __init__(self, stream: Any) -> None:
super().__init__(stream)
self._key_path: list[str] = []
self._duplicates: list[str] = []
def construct_document(self, node: yaml.Node) -> Any:
self._key_path, self._duplicates = [], []
data = super().construct_document(node)
if self._duplicates and isinstance(data, dict):
data["_yaml_duplicate_keys"] = self._duplicates
return data
def construct_mapping(
self, node: yaml.MappingNode, deep: bool = False
) -> dict[Any, Any]:
own_keys = {id(key_node) for key_node, _ in node.value}
self.flatten_mapping(node)
mapping: dict[Any, Any] = {}
seen: set[Any] = set()
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=True)
if not isinstance(key, collections.abc.Hashable):
raise yaml.constructor.ConstructorError(
"while constructing a mapping",
node.start_mark,
"found unhashable key",
key_node.start_mark,
)
self._key_path.append(str(key))
try:
val = self.construct_object(value_node, deep=True)
finally:
self._key_path.pop()
if id(key_node) in own_keys:
if key in seen:
self._duplicates.append(
f"key {'.'.join(self._key_path + [str(key)])!r} defined"
f" multiple times{_previous_config_summary(mapping.get(key))}"
)
seen.add(key)
mapping[key] = val
return mapping
def _previous_config_summary(prev: Any) -> str:
"""Summarises an overwritten `controller_manager_config.yaml` block, or '' for other values."""
if not (isinstance(prev, dict) and k8s.KUEUE_CONFIG_KEY in prev):
return ""
try:
prev_cfg = yaml.safe_load(str(prev.get(k8s.KUEUE_CONFIG_KEY) or ""))
if isinstance(prev_cfg, dict):
return (
" (earlier block had"
f" manageJobsWithoutQueueName={prev_cfg.get('manageJobsWithoutQueueName')}, "
f"waitForPodsReady={'present' if 'waitForPodsReady' in prev_cfg else 'absent'}, "
f"integrations.frameworks={(prev_cfg.get('integrations') or {}).get('frameworks') if isinstance(prev_cfg.get('integrations'), dict) else None})"
)
except Exception: # pylint: disable=broad-exception-caught
# Malformed YAML in an overwritten block must not abort manifest loading.
pass
return ""
def _manifest_paths(data_path: str) -> list[str]:
"""Returns sorted manifest paths and symlinked subdirs; `_read_manifest` skips and records non-regular entries."""
paths: list[str] = []
if os.path.isfile(data_path):
# Operator named this path explicitly: follow a symlink to a regular file.
paths.append(os.path.realpath(data_path))
elif os.path.isdir(data_path):
for root, dirs, files in os.walk(data_path):
kept_dirs: list[str] = []
for dname in sorted(dirs):
if dname == report_output.REPORT_DIR_NAME:
continue
full_dir = os.path.join(root, dname)
if os.path.islink(full_dir):
paths.append(full_dir)
else:
kept_dirs.append(dname)
dirs[:] = kept_dirs
for fname in sorted(files):
if fname.endswith((".yaml", ".yml", ".json")):
paths.append(os.path.join(root, fname))
return paths
def _load_error_text(exc: Exception, line_offset: int = 0) -> str:
"""One-line description of a parse error with file-absolute line numbers."""
mark = getattr(exc, "problem_mark", None)
if mark is None:
text = " ".join(str(exc).split())
return f"{type(exc).__name__}: {text[:300]}"
parts = [getattr(exc, "context", None), getattr(exc, "problem", None)]
text = " ".join(str(p) for p in parts if p) or type(exc).__name__
line = line_offset + mark.line + 1
return f"{text} (line {line}, column {mark.column + 1})"
def _split_yaml_documents(text: str) -> list[tuple[int, str]]:
"""Splits YAML text at `---` markers into `(first line index, document text)` pairs."""
lines = text.split("\n")
chunks: list[tuple[int, str]] = []
start = 0
for idx, line in enumerate(lines):
if idx and (line.rstrip() == "---" or line.startswith(("--- ", "---\t"))):
chunks.append((start, "\n".join(lines[start:idx])))
start = idx
chunks.append((start, "\n".join(lines[start:])))
return [(first, chunk) for first, chunk in chunks if chunk.strip()]
def _yaml_documents(text: str, source: str, notes: LoadNotes) -> list[Any]:
"""Parses every YAML document of a file; a document that fails is recorded and skipped.
The file is parsed in one pass first. Only when that fails is it split at
the `---` markers and parsed document by document, so the documents before
and after a broken one are still loaded.
Args:
text: The file content.
source: Label of the file for `notes`.
notes: Collector for skipped documents.
Returns:
The parsed documents, in file order.
"""
try:
return list(yaml.load_all(text, Loader=_DuplicateKeyTrackingLoader))
except Exception: # pylint: disable=broad-exception-caught
# Any loader failure (syntax, unacceptable character, nesting depth) is
# attributed to its document in the second pass below.
pass
docs: list[Any] = []
for number, (first, chunk) in enumerate(_split_yaml_documents(text), 1):
try:
docs.extend(yaml.load_all(chunk, Loader=_DuplicateKeyTrackingLoader))
except Exception as exc: # pylint: disable=broad-exception-caught
notes.skip(
f"{source} (document {number}, from line {first + 1})",
_load_error_text(exc, first),
)
return docs
def _is_json_lines(text: str) -> bool:
"""True for JSON Lines content (log exports), which is not a manifest file."""
head, _, rest = text.lstrip().partition("\n")
if not rest.strip():
return False
try:
json.loads(head)
except (ValueError, RecursionError):
return False
return True
def _json_documents(text: str, source: str, notes: LoadNotes) -> list[Any]:
"""Parses a `.json` file; invalid JSON is recorded, JSON Lines logs are left to `trace_logs.py`."""
try:
return [json.loads(text)]
except (ValueError, RecursionError) as exc:
if not _is_json_lines(text):
notes.skip(source, _load_error_text(exc))
return []
def _stamped_list_item(
member: dict[str, Any], item_kind: str, api_version: Any
) -> dict[str, Any]:
"""A typed-list item with the `kind` / `apiVersion` the API server leaves out."""
stamp: dict[str, Any] = {}
if item_kind and api_version and not member.get("apiVersion"):
stamp["apiVersion"] = api_version
if item_kind and not member.get("kind"):
stamp["kind"] = item_kind
if not stamp:
return member
return {**stamp, **{k: v for k, v in member.items() if k not in stamp}}
def _document_objects(doc: Any, depth: int = 0) -> list[dict[str, Any]]:
"""Kubernetes objects of one parsed document, with `List` and `<Kind>List` documents expanded.
Items of a typed list (`PodList`, `SecretList`, ...) get the list kind
without its `List` suffix and the list `apiVersion` when they carry none.
A list whose `items` is null or not a list yields nothing.
Args:
doc: One parsed YAML/JSON document.
depth: Nesting level of lists inside lists.
Returns:
The mappings that have a `kind`.
"""
if not isinstance(doc, dict):
return []
kind = doc.get("kind")
if not isinstance(kind, str) or not kind:
return []
if not (kind.endswith("List") and ("items" in doc or kind == "List")):
return [doc]
out: list[dict[str, Any]] = []
if depth > 2:
return out
for member in k8s.dict_items(doc.get("items")):
member = _stamped_list_item(member, kind[:-4], doc.get("apiVersion"))
out.extend(_document_objects(member, depth + 1))
return out
def _is_kubeconfig(obj: dict[str, Any]) -> bool:
return obj.get("kind") == "Config" and any(
key in obj for key in ("users", "clusters", "contexts")
)
def _collect_docs(
docs: Any,
items: list[dict[str, Any]],
source: str = "",
notes: LoadNotes | None = None,
budget: int | None = None,
) -> None:
"""Appends the objects of parsed documents to `items`: lists expanded, secrets masked, kubeconfigs dropped."""
notes = notes if notes is not None else LoadNotes()
meter = _TreeMeter(budget)
for doc in docs:
for obj in _document_objects(doc):
if _is_kubeconfig(obj):
notes.warn(
f"{source}: kubeconfig document (kind: Config) holds credentials"
" and was left out"
)
continue
try:
meter.charge(obj)
except TreeBudgetError as exc:
notes.skip(f"{source} ({k8s.kind(obj)} {_obj_name(obj)!r})", str(exc))
if meter.exhausted:
notes.warn(f"{source}: the documents after that object were not read")
return
continue
_mask_in_place(obj)
items.append(obj)
def _obj_name(obj: Any) -> str:
"""`metadata.name` as a string; '' when missing or null."""
return str(k8s.metadata(obj).get("name") or "")
def _obj_namespace(obj: Any) -> str:
return str(k8s.metadata(obj).get("namespace") or "")
# Node budget of one manifest file relative to its size: a parsed tree has
# fewer nodes than the file has characters unless YAML aliases multiply it.
# The full report writes aliases out, so this bounds its size as well.
_NODES_PER_CHAR = 4
_MIN_NODE_BUDGET = 100000
def _read_manifest(path: str, source: str, notes: LoadNotes) -> str | None:
if not report_output.is_regular_file(path):
notes.skip(source, "non-regular file or symlink")
return None
try:
with open(path, "r", encoding="utf-8-sig") as f:
return f.read()
except (OSError, UnicodeError) as exc:
notes.skip(source, _load_error_text(exc))
return None
def load_static_items(
data_path: str, notes: LoadNotes | None = None
) -> list[dict[str, Any]]:
"""Loads Kubernetes objects from a file or directory for offline_data.
Unreadable files and unparsable documents are skipped and recorded in
`notes`; everything else in the bundle is still loaded.
Args:
data_path: A manifest file or a directory that is walked recursively.
notes: Optional collector for skipped sources and warnings.
Returns:
The loaded objects with secrets masked. Subtrees a file shares through
YAML aliases stay shared.
"""
notes = notes if notes is not None else LoadNotes()
items: list[dict[str, Any]] = []
prefix = data_path.rstrip(os.sep) + os.sep
for p in _manifest_paths(data_path):
source = p[len(prefix) :] if p.startswith(prefix) else os.path.basename(p)
text = _read_manifest(p, source, notes)
if text is None:
continue
parse = _json_documents if p.endswith(".json") else _yaml_documents
budget = max(_MIN_NODE_BUDGET, _NODES_PER_CHAR * len(text))
_collect_docs(parse(text, source, notes), items, source, notes, budget)
return items
# ---------------------------------------------------------------------------
# Live cluster loading
# ---------------------------------------------------------------------------
def _served_resource_names() -> tuple[set[str] | None, str]:
"""Returns the resource names the API server serves as `{plural, plural.group}` or `(None, err)`."""
try:
res = subprocess.run(
["kubectl", "api-resources", "-o", "name"],
capture_output=True,
text=True,
check=False,
timeout=20,
)
except (OSError, subprocess.SubprocessError) as exc:
return None, str(exc)
names: set[str] = set()
for line in res.stdout.splitlines():
name = line.strip()
if not name:
continue
names.add(name)
names.add(name.split(".", 1)[0])
if not names:
return None, res.stderr.strip() or "kubectl api-resources returned nothing"
# Partial discovery failures (one broken aggregated API) still list the rest.
return names, res.stderr.strip() if res.returncode != 0 else ""
def _filter_served(kinds_csv: str, served: set[str]) -> tuple[str, list[str]]:
"""Splits a `kubectl get` kind list into (served csv, missing kinds)."""
kept: list[str] = []
missing: list[str] = []
for kind in kinds_csv.split(","):
kind = kind.strip()
if not kind:
continue
if kind in served or kind.split(".", 1)[0] in served:
kept.append(kind)
else:
missing.append(kind)
return ",".join(kept), missing
# Upper bound for one kubectl call. Listing every Pod of a large cluster takes
# minutes; a call that exceeds this is reported like any other kubectl error
# (optional kinds are skipped, required ones end the run).
_KUBECTL_TIMEOUT_SECONDS = 300
_KUBECTL_NOT_RUN = "kubectl could not be run"
def _kubectl_json(
cmd: list[str], timeout: float = _KUBECTL_TIMEOUT_SECONDS
) -> tuple[dict[str, Any] | None, str]:
"""Runs a `kubectl ... -o json` command.
Args:
cmd: Full kubectl command argv.
timeout: Maximum seconds to wait for kubectl to exit.
Returns:
`(object, "")` on success, or `(None, error text)` on failure.
"""
try:
res = subprocess.run(
cmd,
capture_output=True,
text=True,
errors="replace",
check=False,
timeout=timeout,
)
except subprocess.TimeoutExpired:
return None, f"`{' '.join(cmd[:3])}` did not finish within {timeout:g}s"
except (OSError, subprocess.SubprocessError) as exc:
return None, f"{_KUBECTL_NOT_RUN}: {type(exc).__name__}: {exc}"
if res.returncode != 0:
return None, res.stderr.strip() or f"kubectl exit code {res.returncode}"
if not res.stdout.strip():
return {"kind": "List", "items": []}, ""
try:
parsed = json.loads(res.stdout)
except ValueError as exc:
return None, f"kubectl returned non-JSON output: {exc}"
if not isinstance(parsed, dict):
return None, "kubectl returned JSON that is not an object"
return parsed, ""
def _kubectl_load_error(what: str, err: str, next_step: str) -> LoadError:
"""`LoadError` for a failed kubectl call; a missing binary gets its own next step."""
if err.startswith(_KUBECTL_NOT_RUN):
next_step = (
"Verify that kubectl is installed and on PATH; for a saved bundle pass"
" --mode offline_data --data-path <directory>."
)
return LoadError(f"{what}: {err}", next_step)
def _served_kind_lists() -> tuple[str, str, list[str], str]:
"""(cluster-scoped csv, namespaced csv, missing kinds, discovery error) after API discovery."""
# Not every cluster serves every optional group (JobSet, ProvisioningRequest,
# Topology on older Kueue). A single `kubectl get a,b,c` aborts on the first
# unknown type, so query the API server once and keep only the served kinds.
served, served_err = _served_resource_names()
if served is None:
return CLUSTER_SCOPED_KINDS, NAMESPACED_KINDS, [], served_err
cluster_list, miss_c = _filter_served(CLUSTER_SCOPED_KINDS, served)
ns_list, miss_n = _filter_served(NAMESPACED_KINDS, served)
return cluster_list, ns_list, miss_c + miss_n, served_err
def _missing_kinds_warning(missing_kinds: list[str], served_err: str) -> str:
if served_err:
# Discovery was incomplete (e.g. one broken aggregated API); the
# kinds may well exist, so do not assert that they are not served.
return (
"Resource types not listed by API discovery (skipped): "
+ ", ".join(missing_kinds)
+ f". Discovery was incomplete: {served_err[:300]}. Verify with"
" `kubectl get <kind>` before concluding anything about these kinds."
)
return (
"Resource types not served by this cluster (skipped): "
+ ", ".join(missing_kinds)
+ ". A workload of such a kind cannot be managed here until its"
" CRDs/operator are installed."
)
def _append_manager_config(
raw_obj: dict[str, Any], kueue_namespace: str, notes: LoadNotes
) -> None:
"""Fetches `kueue-manager-config` via kubectl and appends it, or records why it is missing."""
cm_obj, err = _kubectl_json([
"kubectl",
"get",
"configmap",
"kueue-manager-config",
"-n",
kueue_namespace,
"-o",
"json",
"--ignore-not-found=true",
])
if isinstance(cm_obj, dict) and cm_obj.get("kind") == "ConfigMap":
raw_obj["items"].append(cm_obj)
return
# `--ignore-not-found` exits 0 with empty output when the ConfigMap does not
# exist, which is what a wrong --kueue-namespace looks like.
notes.skip(
f"configmap kueue-manager-config (namespace {kueue_namespace!r})",
(err or "no ConfigMap of that name exists in that namespace")
+ ". Pass --kueue-namespace if Kueue is installed elsewhere.",
)
_CLUSTER_NEXT_STEP = (
"Check `kubectl config current-context` and that Kueue CRDs are installed"
" (`kubectl api-resources --api-group=kueue.x-k8s.io`)."
)
def _fetch_cluster_scoped_items(
cluster_list: str, notes: LoadNotes
) -> list[dict[str, Any]]:
"""Fetches cluster-scoped Kueue CRDs and nodes in separate kubectl calls.
The Kueue kinds are required. Nodes are optional: a role without node list
permission still gets a snapshot, with the gap recorded in `notes`.
Args:
cluster_list: Comma-separated served cluster-scoped kinds.
notes: Collector for kinds that could not be listed.
Returns:
The fetched objects.
Raises:
LoadError: When the Kueue cluster-scoped kinds cannot be listed.
"""
cluster_kinds = [k for k in cluster_list.split(",") if k]
kueue_cluster_kinds = [k for k in cluster_kinds if k != "nodes"]
cluster_items: list[dict[str, Any]] = []
if kueue_cluster_kinds:
cluster_obj, err = _kubectl_json([
"kubectl",
"get",
",".join(kueue_cluster_kinds),
"-o",
"json",
"--ignore-not-found=true",
])
if cluster_obj is None:
raise _kubectl_load_error(
"kubectl error while listing cluster-scoped Kueue objects",
err,
_CLUSTER_NEXT_STEP,
)
cluster_items.extend(k8s.dict_items(cluster_obj.get("items")))
if "nodes" in cluster_kinds:
nodes_obj, err = _kubectl_json(
["kubectl", "get", "nodes", "-o", "json", "--ignore-not-found=true"]
)
if nodes_obj is None:
notes.skip("nodes", f"kubectl: {err[:300]}")
else:
cluster_items.extend(k8s.dict_items(nodes_obj.get("items")))
return cluster_items
def _fetch_namespaced_items(
ns_list: str, args: argparse.Namespace, notes: LoadNotes
) -> list[dict[str, Any]]:
"""Lists the namespaced kinds in one kubectl call, or kind by kind when that call fails.
One kind the caller may not list (pods, events, ...) fails the combined
call as a whole. On the retry only `workloads` is required; every other
kind that cannot be listed is recorded in `notes` and left out.
Args:
ns_list: Comma-separated served namespaced kinds.
args: Parsed CLI arguments (`namespace` selects one namespace).
notes: Collector for kinds that could not be listed.
Returns:
The fetched objects.
Raises:
LoadError: When Workloads cannot be listed.
"""
scope = ["-n", args.namespace] if args.namespace else ["-A"]
base = ["kubectl", "get", "-o", "json", "--ignore-not-found=true", *scope]
ns_obj, err = _kubectl_json(base[:2] + [ns_list] + base[2:])
if ns_obj is not None:
return k8s.dict_items(ns_obj.get("items"))
kinds = [k for k in ns_list.split(",") if k]
items: list[dict[str, Any]] = []
for kind in kinds:
if len(kinds) > 1:
ns_obj, err = _kubectl_json(base[:2] + [kind] + base[2:])
if ns_obj is not None:
items.extend(k8s.dict_items(ns_obj.get("items")))
elif kind.startswith("workloads"):
raise _kubectl_load_error(
f"kubectl error while listing {kind}",
err,
"Retry with `--namespace <workload namespace>` to narrow the query,"
" or inspect objects with plain kubectl.",
)
else:
notes.skip(kind, f"kubectl: {err[:300]}")
return items
def _live_snapshot(args: argparse.Namespace) -> dict[str, Any]:
"""Collects cluster-scoped, namespaced, and ConfigMap objects via kubectl."""
cluster_list, ns_list, missing_kinds, served_err = _served_kind_lists()
if not any(
k.startswith(("clusterqueues", "workloads"))
for k in (cluster_list + "," + ns_list).split(",")
):
raise LoadError(
"Kueue CRDs (clusterqueues/workloads.kueue.x-k8s.io) are not served by"
" this cluster"
+ (f" ({served_err})" if served_err else ""),
"Check `kubectl config current-context` and that Kueue is installed"
" (`kubectl api-resources --api-group=kueue.x-k8s.io`).",
)
notes = LoadNotes()
cluster_items = _fetch_cluster_scoped_items(cluster_list, notes)
raw_obj = {
"kind": "List",
"items": cluster_items + _fetch_namespaced_items(ns_list, args, notes),
}
if missing_kinds:
notes.warn(_missing_kinds_warning(missing_kinds, served_err))
_append_manager_config(raw_obj, args.kueue_namespace, notes)
return notes.attach(raw_obj)
def _live_list(args: argparse.Namespace, action: str) -> dict[str, Any]:
"""Lists resources or events from the live cluster via kubectl."""
cmd = [
"kubectl",
"get",
"events" if action == "events" else args.kind,
"-o",
"json",
]
if args.namespace:
cmd.extend(["-n", args.namespace])
else:
cmd.append("-A")
raw_obj, err = _kubectl_json(cmd)
if raw_obj is None:
raise _kubectl_load_error(
"kubectl error",
err,
"Verify the kind/namespace, RBAC and the current kube-context.",
)
return raw_obj
def _live_get(args: argparse.Namespace) -> dict[str, Any]:
"""Fetches a specific resource or kind list from the live cluster via kubectl."""
cmd = ["kubectl", "get", args.kind]
if args.name:
cmd.append(args.name)
cmd.extend(["-o", "json"])
if args.namespace:
cmd.extend(["-n", args.namespace])
elif not args.name:
cmd.append("-A")
raw_obj, err = _kubectl_json(cmd)
if raw_obj is None:
raise _kubectl_load_error(
"kubectl error",
err,
"Verify the kind/name/namespace and the current kube-context.",
)
return raw_obj
# kubectl short names of the kinds a Kueue investigation looks up, mapped to
# the lower-case singular kind. Plurals and `<resource>.<group>` forms are
# resolved by `_kind_candidates`.
_KIND_SHORT_NAMES = {
"ac": "admissioncheck",
"co": "cohort",
"cq": "clusterqueue",
"flavor": "resourceflavor",
"rf": "resourceflavor",
"kwl": "workload",
"kueueworkload": "workload",
"wl": "workload",
"lq": "localqueue",
"queue": "localqueue",
"mkc": "multikueuecluster",
"mkconf": "multikueueconfig",
"prc": "provisioningrequestconfig",
"provreq": "provisioningrequest",
"wpc": "workloadpriorityclass",
"cm": "configmap",
"ev": "event",
"no": "node",
"ns": "namespace",
"pc": "priorityclass",
"po": "pod",
"quota": "resourcequota",
"limits": "limitrange",
}
def _kind_candidates(requested: str) -> set[str]:
"""Lower-case singular kinds a `--kind` value can name.
Accepts what kubectl accepts: the kind in any case, its plural, a short
name, and the `<resource>.<group>` / `<resource>.<version>.<group>` forms.
Args:
requested: The `--kind` value.
Returns:
Candidate kinds, compared against the lower-cased `kind` of each object.
"""
base = requested.strip().lower().split(".", 1)[0]
forms = {base}
if base.endswith("ies"):
forms.add(base[:-3] + "y")
if base.endswith("es"):
forms.add(base[:-2])
if base.endswith("s"):
forms.add(base[:-1])
return {_KIND_SHORT_NAMES.get(form, form) for form in forms}
def _single_offline_match(
matched: list[dict[str, Any]], args: argparse.Namespace, context: str
) -> dict[str, Any]:
"""The object a named offline `get` selects; a missing or ambiguous name is an error."""
where = f" in namespace {args.namespace!r}" if args.namespace else ""
if not matched:
raise LoadError(
f"no object of kind {args.kind!r} named {args.name!r}{where} in"
f" {args.data_path!r}{context}",
f"Check the name with `--action list --kind {args.kind}`; the kind"
" accepts singular, plural and kubectl short forms.",
)
namespaces = sorted({_obj_namespace(it) for it in matched})
if len(namespaces) > 1:
raise LoadError(
f"{len(matched)} objects of kind {args.kind!r} are named"
f" {args.name!r}, in namespaces {namespaces}",
"Pass --namespace <namespace> to select one of them.",
)
return matched[0]
def _offline_match(
all_items: list[dict[str, Any]],
args: argparse.Namespace,
action: str,
notes: LoadNotes,
) -> dict[str, Any]:
"""Filters offline bundle items for `get`, `list`, or `events` queries."""
wanted = {"event"} if action == "events" else _kind_candidates(args.kind)
named = action == "get" and bool(args.name)
matched = [
it
for it in all_items
if k8s.kind(it).lower() in wanted
and (not args.namespace or _obj_namespace(it) in ("", args.namespace))
and (not named or _obj_name(it) == args.name)
]
if not named:
return notes.attach({"kind": "List", "items": matched})
context = ""
if not matched:
present = sorted({k8s.kind(it) for it in all_items})
context = f"; kinds in the bundle: {', '.join(present)}{notes.summary()}"
return _single_offline_match(matched, args, context)
def _offline_items(args: argparse.Namespace, action: str) -> dict[str, Any]:
"""Loads static bundle items and filters them for `action`."""
if not args.data_path or not os.path.exists(args.data_path):
raise LoadError(
f"data path not found: {args.data_path!r}",
"Pass --data-path <directory with YAML/JSON manifests and optional"
" logs/>, or use --mode live.",
)
notes = LoadNotes()
all_items = load_static_items(args.data_path, notes)
if not all_items:
raise LoadError(
f"no Kubernetes objects were loaded from {args.data_path!r}"
f"{notes.summary()}",
"Verify that --data-path holds YAML/JSON manifests (documents with a"
" `kind`); for a bundle that has only logs pass --mode logs_archive.",
)
if action == "snapshot" or args.kind.lower() == "all":
return notes.attach({"kind": "List", "items": all_items})
return _offline_match(all_items, args, action, notes)
def load_items(
mode: str, args: argparse.Namespace, action: str
) -> dict[str, Any]:
"""Loads raw Kubernetes object(s) for `action` from live kubectl or offline files.
Args:
mode: Either `"live"` or `"offline_data"`.
args: Parsed CLI arguments specifying kind, name, namespace, and data path.
action: Resolved action (`"snapshot"`, `"list"`, `"get"`, or `"events"`).
Returns:
A `kind: List` mapping (possibly with `_warnings` and `_skipped_sources`)
or a single object dict.
Raises:
LoadError: When objects cannot be loaded from the selected source.
"""
if mode == "live":
if action == "snapshot" or args.kind.lower() == "all":
return _live_snapshot(args)
if action in ("events", "list"):
return _live_list(args, action)
return _live_get(args)
return _offline_items(args, action)
topology_facts.py 3.9 KB
"""Topology-aware scheduling facts: how the nodes in the snapshot populate each flavor's topology domains.
For every ResourceFlavor with ``spec.topologyName`` and a matching Topology
object,
count — among the nodes that carry the flavor's ``nodeLabels`` — the distinct
domains per Topology level and the largest domain at each level. These are the
numbers Kueue's TAS snapshot works from when it reports ``doesn't allow to fit``
or ``allows to fit only N out of M``; the facts only restate them, they do not
say
whether a given pod set fits.
"""
from __future__ import annotations
from typing import Any
import k8s_objects as k8s
_TAS_DOC = "https://kueue.sigs.k8s.io/docs/concepts/topology_aware_scheduling/"
def _topology_levels(topology: dict[str, Any]) -> list[str]:
return [
str(lvl.get("nodeLabel"))
for lvl in k8s.dict_items(k8s.spec(topology).get("levels"))
if lvl.get("nodeLabel")
]
def _domains_per_level(
matching: list[dict[str, Any]], levels: list[str]
) -> list[str]:
"""Summarizes distinct and largest TAS domains per level across `matching`.
A node enters the TAS domain count only if it carries all
`ResourceFlavor.spec.nodeLabels` and every label key in
`Topology.spec.levels`, while `nodes without the label` counts how many
`nodeLabels`-matching nodes lack that specific level key.
Args:
matching: Snapshot Node objects matching `ResourceFlavor.spec.nodeLabels`.
levels: Ordered `nodeLabel` keys from `Topology.spec.levels`.
Returns:
Formatted per-level domain summary strings.
"""
tas_eligible = [
n
for n in matching
if all(k8s.labels(n).get(lbl) is not None for lbl in levels)
]
rows: list[str] = []
for label in levels:
counts: dict[str, int] = {}
for n in tas_eligible:
value = str(k8s.labels(n).get(label))
counts[value] = counts.get(value, 0) + 1
missing = sum(1 for n in matching if k8s.labels(n).get(label) is None)
largest = max(counts.values()) if counts else 0
rows.append(
f"{label}: {len(counts)} domain(s), largest={largest} node(s)"
+ (f", nodes without the label={missing}" if missing else "")
)
return rows
def emit_topology_domains(ctx: Any) -> None:
"""Emits matching node counts and per-level TAS domain layouts (7b)."""
topologies = {k8s.name(t): t for t in ctx.by_kind.get("Topology", [])}
for rf in ctx.rfs:
spec = k8s.spec(rf)
topo_name = spec.get("topologyName")
if not topo_name:
continue
labels = k8s.as_dict(spec.get("nodeLabels"))
matching = [
n
for n in ctx.nodes
if all(k8s.labels(n).get(k) == v for k, v in labels.items())
]
topology = topologies.get(str(topo_name))
head = (
f"TAS_DOMAIN_FACTS ({k8s.name(rf)} -> Topology/{topo_name}):"
f" {len(matching)} of {len(ctx.nodes)} snapshot nodes match"
f" nodeLabels={labels or '{}'}"
)
if topology is None:
ctx.add(
f"tas-domains:{k8s.name(rf)}",
head
+ f"; Topology object '{topo_name}' is absent from the snapshot, so"
" the levels cannot be evaluated.",
)
continue
levels = _topology_levels(topology)
if not matching:
ctx.add(
f"tas-domains:{k8s.name(rf)}",
head
+ f"; levels={levels}; with no matching node the TAS snapshot for"
" this flavor has no domains at any level (nodes that an"
" autoscaler or ProvisioningRequest would add later are not in the"
f" snapshot) ({_TAS_DOC}).",
)
continue
ctx.add(
f"tas-domains:{k8s.name(rf)}",
head
+ f"; domains per level among matching nodes ({_TAS_DOC}):"
f" {'; '.join(_domains_per_level(matching, levels))}. A pod set with"
" a required level fits only inside one domain of that level;"
" 'largest' bounds how many single-node pods it can hold there"
f" ({_TAS_DOC}).",
)
trace_logs.py 36.6 KB
#!/usr/bin/env python3
"""Kueue controller log timeline compaction for the `gke-kueue-troubleshooting` skill.
Reads Kueue controller logs (and, when present, Kubernetes audit events and
Events),
compresses them into a milestone timeline and emits mechanically derived facts:
* `active_api_schema_reference` — the CRD / KueueConfiguration schema for the
Kueue
release detected from the log stream (startup banner, `Configuration
loaded`,
audit `apiVersion`s), so clusterless diagnosis still uses version-exact
fields;
* `derived_log_diagnostics.derived_log_facts` — neutral facts (audit-logged
deletions, configuration unknown-field errors, TAS domain errors, resources
missing from a ClusterQueue) with at most one sentence of
version-independent Kueue semantics each. The script never ranks causes or
prescribes report content.
Input sources (`--mode`):
live `kubectl logs` of the Kueue controller deployment.
offline_data a support-bundle directory (manifests + `logs/`).
logs_archive a file or directory of exported logs in any supported shape
(see `log_envelopes.py`): raw controller output,
`audit.k8s.io/v1` events, Kubernetes Events, or collector /
cloud-logging envelopes.
No cloud SDKs or shell command wrappers are used; the only external tool is
`kubectl`, and only in `live` mode.
Module map: `log_facts.py` holds the record scanners and fact emitters behind
`_extract_derived_log_diagnostics`; `log_timeline.py` holds the milestone
timeline compression; this module keeps the CLI, the input sources, the ledger
append and the stdout digest cap.
"""
from __future__ import annotations
import argparse
from collections.abc import Sequence
import dataclasses
import json
import os
import re
import subprocess
import sys
from typing import Any
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if SCRIPT_DIR not in sys.path:
sys.path.insert(0, SCRIPT_DIR)
# pylint: disable=g-import-not-at-top,wrong-import-position
import kueue_schema
import log_envelopes
import log_facts
import log_timeline
import report_output
# pylint: enable=g-import-not-at-top,wrong-import-position
# Names kept on this module for tests and sibling scripts; the implementations
# live in log_facts.py / log_timeline.py.
_MILESTONE_RE = log_timeline.MILESTONE_RE
HIGH_PRIORITY_RE = log_timeline.HIGH_PRIORITY_RE
compress_timeline = log_timeline.compress_timeline
KUEUE_LOG_LITERALS = log_facts.KUEUE_LOG_LITERALS
event_emitter = log_facts.event_emitter
is_external_emitter = log_facts.is_external_emitter
frameworks_from_config = log_facts.frameworks_from_config
_extract_derived_log_diagnostics = log_facts.extract_derived_log_diagnostics
# Objects whose log/audit records are housekeeping noise (Kueue's own optional
# components, the autoscaler status ConfigMap). Matched as substrings of the
# record text; nothing here changes the facts. Platform add-ons are not listed
# by name: records about objects in managed add-on namespaces are dropped by
# report_output.is_managed_addon_namespace (extend with --ignore-namespaces).
_NOISE_SUBSTRINGS = (
"kueueviz",
"certwatcher",
"cluster-autoscaler-status",
)
_AUDIT_PATH_NAMESPACE_RE = re.compile(
r"^\[Audit [^\]]*\]\s*\S*?/namespaces/([a-z0-9.-]+)/"
)
def _record_namespaces(d: dict[str, Any]) -> set[str]:
"""Namespaces the record is *about*: its object refs and, for audit rows, the request path."""
found: set[str] = set()
for key in (
"objectRef",
"involvedObject",
"object",
"workload",
"localQueue",
"job",
):
ref = d.get(key)
if isinstance(ref, dict) and ref.get("namespace"):
found.add(str(ref["namespace"]))
elif isinstance(ref, str) and "/" in ref:
found.add(ref.split("/", 1)[0].strip())
if d.get("namespace"):
found.add(str(d["namespace"]))
m = _AUDIT_PATH_NAMESPACE_RE.match(
str(d.get("msg") or d.get("message") or "")
)
if m:
found.add(m.group(1))
return found
def _is_noise(line: str) -> bool:
"""Returns True for optional-component or platform add-on housekeeping lines.
The namespace test looks only at the record's own object references and audit
request path, never at free text such as error messages, and never drops the
namespace Kueue itself runs in (`--kueue-namespace`).
Args:
line: Normalised log line text.
Returns:
True if the line should be filtered out as housekeeping noise.
"""
low = line.lower()
if any(tok in low for tok in _NOISE_SUBSTRINGS):
return True
stripped = line.lstrip()
if not stripped.startswith("{"):
return False
try:
d = json.loads(stripped)
except (ValueError, TypeError, RecursionError):
return False
if not isinstance(d, dict):
return False
return any(
report_output.is_managed_addon_namespace(ns)
for ns in _record_namespaces(d)
)
def _filter_lines(lines: list[str], workload_filter: str) -> list[str]:
needle = workload_filter.lower()
out: list[str] = []
for ln in lines:
if not ln or _is_noise(ln):
continue
if not needle or needle in ln.lower() or _MILESTONE_RE.search(ln):
out.append(ln)
return out
_KUBECTL_LOGS_TIMEOUT_SECONDS = 120
_MAX_KUBECTL_ERROR_CHARS = 600
def _kubectl_logs(
kueue_namespace: str, tail_lines: int, previous: bool
) -> tuple[str, str]:
"""`(stdout, error)` of one `kubectl logs` call on the controller deployment; `error` is '' on success."""
cmd = [
"kubectl",
"logs",
"-n",
kueue_namespace,
"deployment/kueue-controller-manager",
f"--tail={tail_lines}",
]
if previous:
cmd.append("--previous")
try:
res = subprocess.run(
cmd,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=_KUBECTL_LOGS_TIMEOUT_SECONDS,
)
except (OSError, subprocess.SubprocessError) as exc:
return "", f"{type(exc).__name__}: {exc}"[:_MAX_KUBECTL_ERROR_CHARS]
if res.returncode != 0:
detail = (res.stderr or "").strip() or f"exit status {res.returncode}"
return "", detail[:_MAX_KUBECTL_ERROR_CHARS]
return res.stdout or "", ""
def _live_log_lines(
tail_lines: int, kueue_namespace: str
) -> tuple[list[str], str]:
"""Normalised controller log lines, oldest first, and kubectl's error for the running container.
The terminated container (`--previous`) is read before the running one, so
that scanners which keep the latest value see the lines in the order they
were written. A failing `--previous` call is expected when the container
never restarted and is not reported.
Args:
tail_lines: Max lines to read per container.
kueue_namespace: Namespace of the Kueue controller deployment.
Returns:
`(lines, error)`; `error` is '' when the running container was read.
"""
lines: list[str] = []
error = ""
for previous in (True, False):
out, err = _kubectl_logs(kueue_namespace, tail_lines, previous)
lines.extend(log_envelopes.normalize_line(ln) for ln in out.splitlines())
if not previous:
error = err
return lines, error
def extract_lines_from_live(
workload_filter: str, tail_lines: int, kueue_namespace: str = "kueue-system"
) -> list[str]:
"""Reads controller logs (previous container, then the running one) from the live cluster via kubectl."""
lines, _ = _live_log_lines(tail_lines, kueue_namespace)
return _filter_lines(lines, workload_filter)
_LOG_EXTENSIONS = (".log", ".txt", ".jsonl", ".ndjson", ".json")
# Manifests, ledger side files and compressed archives are never log text.
_NON_LOG_EXTENSIONS = (
".yaml",
".yml",
".lock",
".tmp",
".gz",
".tgz",
".zip",
".tar",
".bz2",
".xz",
".zst",
)
_LOG_DIR_NAMES = ("log", "logs")
# `log` / `logs` as a whole token of the file name (`controller-log`,
# `kueue_logs.1`), not as a substring (`catalog`, `topologies`).
_LOG_TOKEN_RE = re.compile(r"(?:^|[^a-z0-9])logs?(?:[^a-z0-9]|$)")
def _is_log_file(fname: str, in_logs_dir: bool = False) -> bool:
"""Checks whether a bundle file should be read as logs.
Args:
fname: File name without its directory.
in_logs_dir: Whether the file sits under a `logs/` directory, where files
without an extension (one per pod) are log files as well.
Returns:
True when `fname` should be parsed as a log file.
"""
low = fname.lower()
if low.startswith(".") or low.endswith(_NON_LOG_EXTENSIONS):
return False
return (
in_logs_dir
or low.endswith(_LOG_EXTENSIONS)
or bool(_LOG_TOKEN_RE.search(low))
)
def _bundle_log_candidates(
data_path: str, exclude_paths: frozenset[str] = frozenset()
) -> list[str]:
"""Log-named entries and symlinked subdirs under `data_path`, in stable order."""
top = os.path.abspath(data_path)
found: list[str] = []
for root, dirs, files in os.walk(top):
kept_dirs: list[str] = []
for dname in sorted(dirs):
if dname == report_output.REPORT_DIR_NAME:
continue
full_dir = os.path.join(root, dname)
if os.path.islink(full_dir):
found.append(full_dir)
else:
kept_dirs.append(dname)
dirs[:] = kept_dirs
rel_dirs = os.path.relpath(root, os.path.dirname(top)).lower().split(os.sep)
in_logs_dir = any(part in _LOG_DIR_NAMES for part in rel_dirs)
for fname in sorted(files):
if not _is_log_file(fname, in_logs_dir):
continue
full_path = os.path.join(root, fname)
if os.path.abspath(full_path) in exclude_paths:
continue
found.append(full_path)
return found
def _bundle_log_files(
data_path: str, exclude_paths: frozenset[str] = frozenset()
) -> list[str]:
"""Regular log files under `data_path` (or explicit file path), in stable order."""
if os.path.isfile(data_path):
# Operator named this path explicitly: follow a symlink to a regular file.
return [os.path.realpath(data_path)]
if not os.path.isdir(data_path):
return []
return [
p
for p in _bundle_log_candidates(data_path, exclude_paths)
if report_output.is_regular_file(p)
]
def skipped_log_inputs(
data_path: str, exclude_paths: frozenset[str] = frozenset()
) -> list[str]:
"""Log-named entries or symlinked subdirs skipped because they are non-regular."""
if not data_path or data_path == "-" or not os.path.isdir(data_path):
return []
top = os.path.abspath(data_path)
return [
os.path.relpath(p, top)
for p in _bundle_log_candidates(data_path, exclude_paths)
if not report_output.is_regular_file(p)
]
def extract_bundle_records(
data_path: str,
workload_filter: str,
exclude_paths: frozenset[str] = frozenset(),
) -> tuple[list[str], list[str]]:
"""Reads and normalises log records and reports unreadable JSON inputs.
Every file is passed through `log_envelopes.extract_file_records`, so raw
controller output, `audit.k8s.io/v1` events, Kubernetes Events and collector /
cloud-logging envelopes (JSON array, JSONL or plain lines) all yield the same
record model. Files that only yield dropped JSON fragments (such as truncated
or concatenated pretty-printed JSON arrays) are returned in `unreadable` with
zero lines counted.
Args:
data_path: File or directory path containing exported log files (`-` is
accepted as a legacy stdin fallback).
workload_filter: Optional substring filter for non-milestone lines.
exclude_paths: Absolute file paths (such as the active ledger) to skip.
Returns:
`(filtered_lines, unreadable_inputs)`.
"""
lines: list[str] = []
unreadable: list[str] = []
if data_path == "-":
raw_in = getattr(sys.stdin, "buffer", None)
body = (
raw_in.read().decode("utf-8", errors="replace")
if raw_in is not None
else sys.stdin.read()
)
recs, is_unreadable = log_envelopes.extract_file_records(body)
lines.extend(recs)
if is_unreadable:
unreadable.append("<stdin>")
return _filter_lines(lines, workload_filter), unreadable
if not os.path.exists(data_path):
return lines, unreadable
is_dir = os.path.isdir(data_path)
top = os.path.abspath(data_path) if is_dir else ""
for fpath in _bundle_log_files(data_path, exclude_paths):
if not report_output.is_regular_file(fpath):
continue
try:
with open(fpath, "r", encoding="utf-8", errors="replace") as f:
body = f.read()
except OSError:
continue
recs, is_unreadable = log_envelopes.extract_file_records(body)
if is_unreadable:
label = (
os.path.relpath(fpath, top) if is_dir else os.path.basename(data_path)
)
unreadable.append(label)
continue
lines.extend(recs)
return _filter_lines(lines, workload_filter), unreadable
def extract_lines_from_bundle(
data_path: str,
workload_filter: str,
exclude_paths: frozenset[str] = frozenset(),
) -> list[str]:
"""Reads and normalises log records from a file or directory of exported logs."""
lines, _ = extract_bundle_records(data_path, workload_filter, exclude_paths)
return lines
_LOG_FACT_PRIORITY = {"logfact": 0, "logerr": 1, "audit": 2}
_TAGGED_SECTIONS = (
"derived_log_facts",
"key_errors_and_events",
"audit_resource_actions",
)
def _log_fact_rank(key: str) -> int:
if key == "logfact:signature:controller-start":
return 2
return _LOG_FACT_PRIORITY.get(key.split(":", 1)[0], 9)
def tag_log_facts(
result: dict[str, Any], ledger_path: str | None
) -> dict[str, str]:
"""Registers keyed log facts in the ledger and prefixes them with `[L<n>]` ids.
Mutates `result["derived_log_diagnostics"]` in place, removes the `_keyed`
side channel and returns the key -> id mapping.
Args:
result: Compressed timeline result dict containing `_keyed` entries.
ledger_path: Optional path to the coverage ledger JSON file.
Returns:
Mapping of tracked fact keys to their assigned `L<n>` identifiers.
"""
diag = result.get("derived_log_diagnostics") or {}
keyed = diag.pop("_keyed", None) or {}
tracked: list[tuple[str, str]] = []
for section in _TAGGED_SECTIONS:
tracked.extend((k, t) for k, t in keyed.get(section, []) if k)
tracked.sort(key=lambda kt: _log_fact_rank(kt[0]))
mapping = report_output.register_facts(ledger_path, "L", tracked)
for section in _TAGGED_SECTIONS:
if section in diag and section in keyed:
diag[section] = [
report_output.tag(mapping, k, t) for k, t in keyed[section]
]
return mapping
# ---------------------------------------------------------------------------
# Coverage ledger
# ---------------------------------------------------------------------------
@dataclasses.dataclass(frozen=True)
class LedgerEntry:
"""What one trace_logs run contributes to the coverage ledger."""
out_json: str
raw_excerpts: list[str]
raw_lines: list[str] | None = None
def tool_output(self) -> str:
"""Full output, high-priority excerpts and the raw tail, capped for the ledger."""
tail_raw = "\n".join((self.raw_lines or [])[-600:])
combined = (
self.out_json
+ "\n"
+ "\n".join(self.raw_excerpts)
+ ("\n" + tail_raw if tail_raw else "")
)
return combined[:250000]
def _merge_discovered_entities(ledger: dict[str, Any], out_json: str) -> None:
"""Marks ClusterQueues / ResourceFlavors named in the logs as referenced and inspected."""
try:
parsed_out = json.loads(out_json)
diag_block = parsed_out.get("derived_log_diagnostics") or {}
det_ver = (diag_block.get("active_api_schema_reference") or {}).get(
"_detected_kueue_version"
)
if isinstance(det_ver, dict):
ledger["detected_kueue_version"] = det_ver
entities = diag_block.get("discovered_entities") or {}
ref_set = set(ledger.get("referenced", []))
insp_set = set(ledger.get("inspected", []))
for cq in entities.get("cluster_queues", []):
ref_set.add(f"clusterqueue/{cq}")
insp_set.add(f"clusterqueue/{cq}")
for rf in entities.get("resource_flavors", []):
ref_set.add(f"resourceflavor/{rf}")
insp_set.add(f"resourceflavor/{rf}")
ledger["referenced"] = sorted(ref_set)
ledger["inspected"] = sorted(insp_set)
except Exception: # pylint: disable=broad-except
pass
def append_to_ledger(ledger_path: str | None, entry: LedgerEntry) -> None:
"""Appends trace_logs output and raw log excerpts to the coverage ledger.
The read-modify-write runs under the ledger lock
(`report_output.mutate_ledger`), so a snapshot run that writes the same
ledger at the same time loses no entry.
Args:
ledger_path: Path to the coverage ledger JSON file; falsy skips the write.
entry: Output of this run.
"""
if not ledger_path:
return
def mutate(ledger: dict[str, Any]) -> None:
_merge_discovered_entities(ledger, entry.out_json)
outputs = ledger.get("tool_outputs")
outputs = list(outputs) if isinstance(outputs, list) else []
outputs.append(entry.tool_output())
ledger["tool_outputs"] = outputs[-50:]
ingested = ledger.get("raw_bytes_ingested")
ledger["raw_bytes_ingested"] = (
ingested if isinstance(ingested, int) else 0
) + len(entry.out_json.encode("utf-8"))
report_output.mutate_ledger(ledger_path, mutate, strict=False)
# ---------------------------------------------------------------------------
# Stdout digest cap
# ---------------------------------------------------------------------------
@dataclasses.dataclass
class _DigestTrim:
"""Bookkeeping shared by the trim steps of one digest."""
diag: dict[str, Any]
dropped: dict[str, int] = dataclasses.field(default_factory=dict)
lost: dict[str, int] = dataclasses.field(default_factory=dict)
def _shrunk_list(key: str, seq: list[Any]) -> tuple[list[Any], int] | None:
"""One notch off a list section; None when nothing removable is left."""
step = max(1, len(seq) // 4)
if key == "compressed_timeline":
mid = len(seq) // 2
return seq[: mid - step // 2] + seq[mid + (step - step // 2) :], step
if key == "audit_resource_actions":
# Lines carrying a fact id ([L<n>]) must stay visible; drop untagged ones
# from the tail.
untagged = [
i for i, line in enumerate(seq) if not str(line).startswith("[L")
]
if not untagged:
return None
drop_idx = set(untagged[-step:])
return [line for i, line in enumerate(seq) if i not in drop_idx], len(
drop_idx
)
return seq[:-step], step
def _section_step(
trim: _DigestTrim, key: str, holder: dict[str, Any]
) -> report_output.TrimStep:
"""Halves a dict section or removes a quarter of a list section per call."""
def step(unused_payload: dict[str, Any]) -> bool:
seq = holder.get(key)
if isinstance(seq, dict):
if len(seq) <= 2:
return False
holder[key] = dict(list(seq.items())[: max(2, len(seq) // 2)])
trim.dropped[key] = trim.dropped.get(key, 0) + len(seq) - len(holder[key])
return True
if not isinstance(seq, list) or len(seq) <= 2:
return False
shrunk = _shrunk_list(key, seq)
if shrunk is None:
return False
holder[key], removed = shrunk
trim.dropped[key] = trim.dropped.get(key, 0) + removed
return True
return step
def _schema_step(trim: _DigestTrim) -> report_output.TrimStep:
"""Drops the per-kind `valid_fields` lists once."""
applied = False
def step(unused_payload: dict[str, Any]) -> bool:
nonlocal applied
if applied:
return False
applied = True
slim, n_dropped = report_output.compact_schema_reference(
trim.diag.get("active_api_schema_reference") or {}
)
if not n_dropped:
return False
trim.diag["active_api_schema_reference"] = slim
trim.dropped["active_api_schema_reference.valid_fields"] = n_dropped
return True
return step
def _entity_step(
trim: _DigestTrim, entities: dict[str, Any], key: str
) -> report_output.TrimStep:
"""Halves one discovered_entities list (never below 20) and appends a `+N more` marker."""
state = {"seq": entities.get(key)}
dkey = f"discovered_entities.{key}"
def step(unused_payload: dict[str, Any]) -> bool:
seq = state["seq"]
if not isinstance(seq, list) or len(seq) <= 20:
return False
keep = max(20, len(seq) // 2)
hidden = len(seq) - keep
state["seq"] = seq[:keep]
trim.dropped[dkey] = trim.dropped.get(dkey, 0) + hidden
entities[key] = state["seq"] + [f"... (+{trim.dropped[dkey]} more)"]
return True
return step
def _untagged_step(
trim: _DigestTrim, key: str, what: str
) -> report_output.TrimStep:
"""Removes untagged notes from the tail of a fact list; tagged [L<n>] lines always stay."""
def step(unused_payload: dict[str, Any]) -> bool:
seq = trim.diag.get(key)
if not isinstance(seq, list):
return False
if trim.lost.get(key) and seq and str(seq[-1]).startswith("... "):
seq = seq[:-1]
seq, removed = report_output.shrink_untagged_notes(
[str(x) for x in seq], step=max(1, len(seq) // 10)
)
if not removed:
return False
trim.lost[key] = trim.lost.get(key, 0) + removed
trim.diag[key] = seq + [
report_output.untagged_trailer(trim.lost[key], what)
]
trim.dropped[key] = trim.lost[key]
return True
return step
_MAX_REPORTED_INPUT_WARNINGS = 20
def _cap_input_list(
items: Sequence[str], limit: int = _MAX_REPORTED_INPUT_WARNINGS
) -> list[str]:
"""Bounds `skipped_inputs` / `unreadable_inputs` with an accurate omitted marker."""
if len(items) <= limit:
return list(items)
return list(items[:limit]) + [f"... {len(items) - limit} more omitted"]
def _input_warning_step(
trim: _DigestTrim,
holder: dict[str, Any],
key: str,
full_items: Sequence[str],
) -> report_output.TrimStep:
"""Halves a capped warning list (never below 2) while preserving the omitted count."""
state = {"keep": min(len(full_items), _MAX_REPORTED_INPUT_WARNINGS)}
total = len(full_items)
def step(unused_payload: dict[str, Any]) -> bool:
if key not in holder or state["keep"] <= 2:
return False
next_keep = max(2, state["keep"] // 2)
if next_keep == state["keep"]:
return False
state["keep"] = next_keep
holder[key] = _cap_input_list(full_items, next_keep)
trim.dropped[key] = total - next_keep
return True
return step
def _digest_trim_steps(
result: dict[str, Any],
trim: _DigestTrim,
raw_inputs: dict[str, list[str]],
) -> list[report_output.TrimStep]:
"""Trim steps in shrink order (see `_apply_output_cap`)."""
diag = trim.diag
steps: list[report_output.TrimStep] = [
_section_step(trim, "compressed_timeline", result),
_section_step(trim, "top_milestone_counts", result),
_schema_step(trim),
_section_step(trim, "high_priority_verbatim_log_excerpts", result),
_section_step(trim, "audit_resource_actions", diag),
_input_warning_step(
trim, result, "skipped_inputs", raw_inputs.get("skipped_inputs", [])
),
_input_warning_step(
trim,
result,
"unreadable_inputs",
raw_inputs.get("unreadable_inputs", []),
),
]
entities = diag.get("discovered_entities") or {}
for key in sorted(
entities,
key=lambda k: -len(entities[k]) if isinstance(entities[k], list) else 0,
):
steps.append(_entity_step(trim, entities, key))
steps.append(
_untagged_step(trim, "key_errors_and_events", "key errors/events")
)
steps.append(_untagged_step(trim, "derived_log_facts", "log facts"))
return steps
def _digest_truncation_note(
trim: _DigestTrim, full_report_file: str, max_bytes: int
) -> dict[str, Any]:
if trim.lost:
facts_state = "; ".join(
f"{k} lost {n} untagged entries (every [L<n>] fact is kept)"
for k, n in trim.lost.items()
)
else:
facts_state = "derived_log_facts and key errors are complete"
return report_output.truncation_note(
full_report_file,
max_bytes,
trim.dropped,
f"This is a digest; {facts_state}. Open full_report_file with your file"
" viewer (by line range) for the dropped timeline/sections, or re-run"
" with --workload <name> to narrow the logs. Do not parse the ledger.",
)
def _apply_output_cap(
result: dict[str, Any], max_bytes: int, full_report_file: str = ""
) -> dict[str, Any]:
"""Returns the stdout digest: `result` shrunk until the JSON fits `max_bytes`.
`full_report_file` (if given) is placed first so a reader can open the
complete report. Tagged `[L<n>]` facts, the coverage fact and
`detected_kueue_version` are never cut.
Args:
result: Full timeline result dictionary.
max_bytes: Maximum serialised JSON byte budget.
full_report_file: Optional path to the full report file on disk.
Returns:
The budgeted digest dictionary.
"""
if full_report_file:
result = {"full_report_file": full_report_file, **result}
raw_inputs: dict[str, list[str]] = {}
for key in ("skipped_inputs", "unreadable_inputs"):
if isinstance(result.get(key), list):
raw_inputs[key] = list(result[key])
result[key] = _cap_input_list(raw_inputs[key])
trim = _DigestTrim(diag=result.get("derived_log_diagnostics") or {})
return report_output.apply_output_cap(
result,
max_bytes,
_digest_trim_steps(result, trim, raw_inputs),
note=lambda: _digest_truncation_note(trim, full_report_file, max_bytes),
)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def _emit_error(message: str, next_step: str) -> int:
return report_output.emit_error(
message,
next_step,
render=lambda p: json.dumps(p, indent=2) + "\n",
stderr_prefix="error: ",
)
def _add_source_arguments(parser: argparse.ArgumentParser) -> None:
"""Where the logs come from (`--mode` and its per-mode inputs)."""
parser.add_argument(
"--mode",
choices=["live", "offline_data", "logs_archive"],
default=report_output._env( # pylint: disable=protected-access
"GKE_KUEUE_TROUBLESHOOTING_MODE", "KUEUE_DIAGNOSE_MODE", "live"
),
help=(
"live: kubectl logs; offline_data: support bundle dir; logs_archive:"
" exported log file(s)"
),
)
parser.add_argument(
"--workload",
default="",
help="Optional workload or queue name substring to focus on",
)
parser.add_argument(
"--tail",
type=int,
default=20000,
help="Max lines to read per container in live mode",
)
parser.add_argument(
"--data-path",
default=report_output._env( # pylint: disable=protected-access
"GKE_KUEUE_TROUBLESHOOTING_DATA_PATH", "KUEUE_DIAGNOSE_DATA_PATH"
),
help="File or directory with manifests/logs (offline_data, logs_archive)",
)
def _add_output_arguments(parser: argparse.ArgumentParser) -> None:
"""Ledger, schema-version overrides, controller namespace and the stdout digest cap."""
report_output.add_ledger_path_argument(
parser,
"Path to the coverage ledger JSON shared by all scripts in one"
" investigation",
)
report_output.add_kueue_version_arguments(parser)
report_output.add_kueue_namespace_argument(
parser,
"Namespace of the Kueue controller deployment (default kueue-system)",
)
report_output.add_max_output_bytes_argument(
parser,
24000,
"Cap on the stdout digest; the complete report is always written to"
" full_report_file next to the ledger",
)
report_output.add_no_remote_schema_argument(parser)
report_output.add_ignore_namespaces_argument(parser)
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description=(
"Compacts Kueue controller logs (live, bundle or exported) into a"
" milestone timeline and derived facts."
)
)
_add_source_arguments(parser)
_add_output_arguments(parser)
return parser
# `(message, next_step)` as printed by `_emit_error`.
ReadError = tuple[str, str]
_EMPTY_BUNDLE_RESULT = {
"total_scanned_lines": 0,
"note": (
"No controller log files or Kubernetes Event records are present in"
" this static offline bundle; rely on snapshot.py output and"
" derived_graph_diagnostics."
),
"derived_log_diagnostics": {
"derived_log_facts": [],
"key_errors_and_events": [],
},
}
def _read_live_lines(
args: argparse.Namespace,
) -> tuple[list[str], ReadError | None]:
"""Reads live controller logs via kubectl or returns a ReadError."""
raw_lines, kubectl_error = _live_log_lines(args.tail, args.kueue_namespace)
lines = _filter_lines(raw_lines, args.workload)
if lines:
return lines, None
namespace_hint = (
"Check `kubectl get deploy -A | grep kueue` and pass"
" --kueue-namespace; or export logs to a file and use --mode"
" logs_archive."
)
if not kubectl_error:
return [], (
(
"no controller log lines read from"
" deployment/kueue-controller-manager in namespace"
f" {args.kueue_namespace!r}"
),
namespace_hint,
)
access_hint = (
"Check that kubectl is installed, that `kubectl config current-context`"
" is reachable and that the account may read pods/log in that"
" namespace; or export logs to a file and pass --mode logs_archive."
)
return [], (
(
"kubectl logs deployment/kueue-controller-manager in namespace"
f" {args.kueue_namespace!r} failed: {kubectl_error}"
),
namespace_hint if "(NotFound)" in kubectl_error else access_hint,
)
def _is_static_bundle(mode: str, data_path: str) -> bool:
"""An offline bundle made of manifests only (no logs to read is not an error)."""
if mode != "offline_data" or not os.path.isdir(data_path):
return False
for _, _, files in os.walk(data_path):
if any(fn.lower().endswith((".yaml", ".yml", ".json")) for fn in files):
return True
return False
def _exclude_paths_for(args: argparse.Namespace) -> frozenset[str]:
"""Paths owned by the script itself (such as the active ledger) to skip."""
ledger_path = getattr(args, "ledger_path", "")
if not ledger_path:
return frozenset()
return frozenset({os.path.abspath(ledger_path)})
@dataclasses.dataclass(frozen=True)
class _ArchiveReadResult:
lines: list[str]
error: ReadError | None = None
skipped: tuple[str, ...] = ()
unreadable: tuple[str, ...] = ()
def _warn_unread_inputs(
data_path: str, skipped: list[str], unreadable: list[str]
) -> None:
"""Logs actionable warnings to stderr for skipped symlinks or unreadable JSON files."""
if skipped:
sys.stderr.write(
f"warning: {len(skipped)} log input(s) under {data_path!r} are"
" symlinks or not regular files and were not read:"
f" {', '.join(skipped[:5])}. Verify their targets before passing a"
" trusted regular log file via --data-path or re-exporting them as"
" regular files.\n"
)
if unreadable:
sys.stderr.write(
f"warning: {len(unreadable)} log input(s) under {data_path!r} could"
" not be parsed as valid JSON/log records (for example truncated or"
f" concatenated JSON arrays): {', '.join(unreadable[:5])}. Write each"
" export to its own file in the directory and pass the directory via"
" --data-path.\n"
)
def _read_archive_result(args: argparse.Namespace) -> _ArchiveReadResult:
"""Reads exported or bundled log records plus skipped/unreadable diagnostics."""
data_path = args.data_path
is_stdin = args.mode == "logs_archive" and data_path == "-"
if not data_path or (not is_stdin and not os.path.exists(data_path)):
return _ArchiveReadResult(
[],
(
f"data path not found: {data_path!r}",
(
"Pass --data-path <file or directory with exported logs> (see"
" references/log-sources.md)."
),
),
)
exclude = _exclude_paths_for(args)
lines, unreadable = extract_bundle_records(data_path, args.workload, exclude)
skipped = [] if is_stdin else skipped_log_inputs(data_path, exclude)
_warn_unread_inputs(data_path, skipped, unreadable)
if not lines and (is_stdin or not _is_static_bundle(args.mode, data_path)):
notes: list[str] = []
if skipped:
notes.append(f"{len(skipped)} symlinked or non-regular input(s) skipped")
if unreadable:
notes.append(
f"{len(unreadable)} unreadable JSON input(s): "
+ ", ".join(unreadable[:5])
)
suffix = f" ({'; '.join(notes)})" if notes else ""
next_step = (
"Supported shapes: Kueue controller JSON lines, audit.k8s.io/v1"
" events, Kubernetes Events, cloud-logging / collector envelopes"
" (JSON array or JSONL). Check the export is not empty."
)
if unreadable:
next_step = (
"One or more files contained broken or concatenated JSON exports."
" Write each export to its own file in a directory (never append"
" JSON arrays into one file) and pass the directory via --data-path"
" (see references/log-sources.md)."
)
return _ArchiveReadResult(
[],
(f"no log records recognised under {data_path!r}{suffix}", next_step),
tuple(skipped),
tuple(unreadable),
)
return _ArchiveReadResult(lines, None, tuple(skipped), tuple(unreadable))
def _read_archive_lines(
args: argparse.Namespace,
) -> tuple[list[str], ReadError | None]:
"""Reads exported or bundled log records from `--data-path`."""
res = _read_archive_result(args)
return res.lines, res.error
def read_lines(args: argparse.Namespace) -> tuple[list[str], ReadError | None]:
"""Reads the log lines for `args.mode`.
Args:
args: Parsed CLI arguments specifying mode, data path, and filters.
Returns:
`(lines, None)` on success, `([], (message, next_step))` on error, or
`([], None)` for a static offline bundle that has no logs.
"""
if args.mode == "live":
return _read_live_lines(args)
return _read_archive_lines(args)
def _empty_bundle_payload(
skipped: Sequence[str], unreadable: Sequence[str], max_bytes: int = 0
) -> dict[str, Any]:
"""Builds the empty-bundle JSON payload, keeping warning lists within `max_bytes`."""
empty = dict(_EMPTY_BUNDLE_RESULT)
reasons: list[str] = []
if skipped:
reasons.append(
f"{len(skipped)} log input(s) are symlinks or not regular files"
)
if unreadable:
reasons.append(
f"{len(unreadable)} log input(s) could not be parsed as valid"
" JSON/log records"
)
if reasons:
empty["note"] = (
"; ".join(reasons)
+ " and were not read, so log evidence is not determinable from this"
" run; verify symlink targets or re-export each filter to its own"
" regular file before rerunning."
)
limit = _MAX_REPORTED_INPUT_WARNINGS
while True:
if skipped:
empty["skipped_inputs"] = _cap_input_list(skipped, limit)
if unreadable:
empty["unreadable_inputs"] = _cap_input_list(unreadable, limit)
if (
max_bytes <= 0
or limit <= 2
or len(json.dumps(empty, indent=2).encode("utf-8")) <= max_bytes
):
return empty
limit = max(2, limit // 2)
def run(args: argparse.Namespace) -> int:
"""Executes `trace_logs` end-to-end for parsed CLI arguments."""
report_output.apply_ignore_namespaces(args)
report_output.apply_no_remote_schema(args)
report_output.apply_kueue_namespace(args)
if args.mode == "live":
lines, error = _read_live_lines(args)
skipped: Sequence[str] = ()
unreadable: Sequence[str] = ()
else:
archive = _read_archive_result(args)
lines, error = archive.lines, archive.error
skipped, unreadable = archive.skipped, archive.unreadable
if error:
return _emit_error(*error)
if not lines:
empty = _empty_bundle_payload(skipped, unreadable, args.max_output_bytes)
print(json.dumps(empty, indent=2))
return 0
vinfo = kueue_schema.detect_target_kueue_version(
mode=args.mode,
log_lines=lines,
data_path=args.data_path,
explicit_release_version=args.kueue_version,
explicit_api_version=args.api_version,
kueue_namespace=args.kueue_namespace,
)
full_result = compress_timeline(lines, version_info=vinfo)
if skipped:
full_result["skipped_inputs"] = list(skipped)
if unreadable:
full_result["unreadable_inputs"] = list(unreadable)
tag_log_facts(full_result, args.ledger_path)
full_json = json.dumps(full_result, indent=2)
report_file = report_output.write_full_report(
args.ledger_path, "trace-logs", full_json, "json"
)
append_to_ledger(
args.ledger_path,
LedgerEntry(
full_json,
full_result.get("high_priority_verbatim_log_excerpts", []),
raw_lines=lines,
),
)
digest = _apply_output_cap(
json.loads(full_json), args.max_output_bytes, full_report_file=report_file
)
print(json.dumps(digest, indent=2))
return 0
def main() -> int:
return run(build_parser().parse_args())
if __name__ == "__main__":
sys.exit(main())
validate_report.py 8.9 KB
#!/usr/bin/env python3
"""Diagnostic report verifier for the `gke-kueue-troubleshooting` skill.
Audits a draft '### Diagnostic Summary' against the coverage ledger written by
`snapshot.py` / `trace_logs.py` and the schema of the detected Kueue release
(`kueue_schema.py`):
1. All required sections exist and are not empty (`### Diagnostic Summary`,
`#### Scope`, `#### Observations`, `#### Root Cause`, `#### Ruled Out`,
`#### Remediation`). Titles are matched after normalisation (case, a
trailing `:`, singular/plural), by the same parser every gate uses.
2. All referenced Kueue graph objects (`Cohort`, `ClusterQueue`,
`ResourceFlavor`, `AdmissionCheck`) were inspected or named.
3. Quoted evidence in `#### Observations` matches actual tool outputs (zero
fabricated quotes).
4. Root causes are numbered `RC1`, `RC2`, ... and every one has a matching
remediation entry that links the official documentation describing the fix
(and includes that link whenever a `kubectl` command or YAML manifest is
given), or states an external action and confirmation signal
(`remediation_gaps`).
A report with no RC must open at least one `OQ<n>` under `#### Open
Questions`.
5. Open Questions (`OQ<n>`) keep read-only commands in every `Collect:` part
(`open_question_gaps`); a conditional fix under its own
`Conditional remediation:` / `Fix:` label is not part of `Collect:`.
6. Controller configuration remediations use `kind: Configuration` and avoid
partial `kubectl patch` of `controller_manager_config.yaml`
(`config_remediation_errors`).
7. `kubectl` commands in `#### Remediation` target resource kinds that exist
(`unknown_kubectl_resources`).
8. YAML manifests in `#### Remediation` conform to the detected API version's
field names (`schema_warnings`).
9. Advisory only (does not fail `passed`): root causes without a rejection or
terminal signal in `#### Observations` (`unsupported_root_causes`).
All checks are structural: the validator never judges whether a conclusion is
right, only whether the report is complete, traceable and executable.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Any
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
if SCRIPT_DIR not in sys.path:
sys.path.insert(0, SCRIPT_DIR)
# pylint: disable=g-import-not-at-top,wrong-import-position
import kueue_schema
import report_checks
import report_output
# pylint: enable=g-import-not-at-top,wrong-import-position
_LEDGER_MISSING_NOTE = (
"No tool outputs found in the coverage ledger; quote verification was"
" skipped. Pass the same --ledger-path to snapshot.py / trace_logs.py and"
" to this validator."
)
_UNADDRESSED_FACTS_HINT = (
"Each listed id must appear under `#### Root Cause` (as evidence of an RC),"
" under `#### Open Questions` (as a fact the question is about) or under"
" `#### Ruled Out` with a one-line reason why it does not block the"
" workload. Ids may be grouped (e.g. `- S4: concerns ClusterQueue team-b,"
" which is not in this workload's chain`)."
)
_OPEN_QUESTION_HINT = (
"An OQ<n> is a claim that the evidence cannot decide something — it must be"
" as rigorous as an RC: `- OQ1 (S7, L2): <what cannot be decided>` followed"
" by indented `Basis: missing data | indistinguishable hypotheses | owner"
" intent — <specifics>`, `Candidates: (a) ... (b) ...`, `Discriminator:"
" <observation that decides>`, `Collect: <read-only commands / data /"
" question to the owner>`. `Collect:` holds read-only commands only: put"
" a fix that depends on the answer with its candidate, or on its own"
" `Conditional remediation:` line."
)
_WEAK_RULED_OUT_HINT = (
"A Ruled Out bullet must state why the fact cannot be blocking this"
" workload: name the object it concerns and why that object is outside the"
" workload's chain, or quote the later fact (with timestamp) showing the"
" condition cleared. Labels such as 'transient' or 'noise' are not reasons."
" If the fact describes a stage of this workload's own admission pipeline,"
" it is evidence for a root cause, not something to rule out."
)
# Report keys in output order; every one is produced by exactly one gate in
# `REPORT_GATES`.
_GATE_KEYS = (
"missing_headers",
"uninspected_graph_objects",
"fabricated_quotes",
"unaddressed_facts",
"remediation_gaps",
"open_question_gaps",
"weak_ruled_out",
"config_remediation_errors",
"unknown_kubectl_resources",
"schema_warnings",
)
def _resolve_version_info(
ledger_vinfo: dict[str, Any] | None,
explicit_release_version: str,
explicit_api_version: str,
) -> dict[str, Any]:
"""The ledger's detected version unless an override is given or the ledger has none."""
if ledger_vinfo and not explicit_release_version and not explicit_api_version:
return ledger_vinfo
return kueue_schema.detect_target_kueue_version(
mode=report_output._env( # pylint: disable=protected-access
"GKE_KUEUE_TROUBLESHOOTING_MODE",
"KUEUE_DIAGNOSE_MODE",
"offline_data",
),
explicit_release_version=explicit_release_version
or (ledger_vinfo or {}).get("release_version", ""),
explicit_api_version=explicit_api_version
or (ledger_vinfo or {}).get("api_version", ""),
)
def _build_report(
ctx: report_checks.DraftContext, findings: dict[str, list[Any]]
) -> dict[str, Any]:
"""Assembles the validator's JSON report from the merged gate findings."""
referenced = ctx.ledger.referenced
uninspected = findings["uninspected_graph_objects"]
ledger_missing = not ctx.ledger.tool_outputs
coverage_pct = (
round(100.0 * (len(referenced) - len(uninspected)) / len(referenced), 1)
if referenced
else 100.0
)
passed = not ledger_missing and not any(findings[key] for key in _GATE_KEYS)
report: dict[str, Any] = {
"passed": passed,
"ledger_missing": ledger_missing,
"ledger_note": _LEDGER_MISSING_NOTE if ledger_missing else "",
"detected_kueue_version": ctx.version_info,
}
report.update({key: findings[key] for key in _GATE_KEYS})
# Advisory only (never affects `passed`): root causes that cite no
# rejection/terminal signal.
report["unsupported_root_causes"] = findings.get(
"unsupported_root_causes", []
)
if report["unsupported_root_causes"]:
report["unsupported_root_causes_hint"] = (
"Advisory: tie each listed RC to a rejection or terminal fact (Workload"
" condition reason, controller message, Warning event) in ####"
" Observations, or move it to Open Questions; a quota, TTL or limit"
" value by itself is an observation."
)
report["graph_coverage_pct"] = coverage_pct
if ctx.schema.get("_schema_unavailable"):
report["schema_notice"] = ctx.schema.get("_schema_notice", "")
if findings["unaddressed_facts"]:
report["unaddressed_facts_hint"] = _UNADDRESSED_FACTS_HINT
if findings["open_question_gaps"]:
report["open_question_hint"] = _OPEN_QUESTION_HINT
if findings["weak_ruled_out"]:
report["weak_ruled_out_hint"] = _WEAK_RULED_OUT_HINT
return report
def audit_draft(
draft_text: str,
ledger_path: str | None,
explicit_release_version: str = "",
explicit_api_version: str = "",
) -> dict[str, Any]:
"""Runs deterministic verification and version-exact Kueue schema checks on a diagnostic report."""
ledger = report_checks.LedgerData.load(ledger_path)
vinfo = _resolve_version_info(
ledger.detected_kueue_version,
explicit_release_version,
explicit_api_version,
)
schema, _ = kueue_schema.load_schema_for_version(version_info=vinfo)
ctx = report_checks.DraftContext(
draft_text=draft_text, ledger=ledger, version_info=vinfo, schema=schema
)
return _build_report(ctx, report_checks.run_report_gates(ctx))
def main() -> int:
parser = argparse.ArgumentParser(
description=(
"Validate a draft Kueue diagnostic summary against the coverage"
" ledger and target Kueue version schema."
)
)
parser.add_argument(
"--draft-file", required=True, help="Path to draft markdown file"
)
report_output.add_ledger_path_argument(parser, "Path to coverage_ledger.json")
report_output.add_kueue_version_arguments(parser)
report_output.add_no_remote_schema_argument(parser)
args = parser.parse_args()
report_output.apply_no_remote_schema(args)
if not os.path.exists(args.draft_file):
sys.stderr.write(f"Draft file not found: {args.draft_file}\n")
return 1
with open(args.draft_file, "r", encoding="utf-8") as f:
draft_text = f.read()
report = audit_draft(
draft_text,
args.ledger_path,
explicit_release_version=args.kueue_version,
explicit_api_version=args.api_version,
)
print(json.dumps(report, indent=2))
return 0 if report["passed"] else 2
if __name__ == "__main__":
sys.exit(main())
workload_timeline.py 7.5 KB
"""Per-workload lifecycle timeline derived from Kubernetes Events and Workload status.
Facts only: the ordered milestone list of each Workload (quota reservation,
admission, evictions with their reason, preemption, requeue count, deactivation,
finish, deletion) and whether the Workload object itself is still present in the
snapshot. Nothing here ranks explanations; the reader decides which terminal
event
matters. Reason names come from Kueue's documented event and metric vocabulary
(https://kueue.sigs.k8s.io/docs/concepts/workload/,
https://kueue.sigs.k8s.io/docs/reference/metrics/).
"""
from __future__ import annotations
import dataclasses
import re
from typing import Any
import k8s_objects as k8s
# Event reasons recorded as lifecycle milestones. Everything else stays in the
# generic WARNING_EVENT list. ``Evicted`` is a prefix match (EvictedDueTo<X>).
_MILESTONE_REASONS = (
"Pending",
"QuotaReserved",
"Admitted",
"Preempted",
"PreemptedWorkload",
"Finished",
"Deactivated",
"Requeued",
)
_EVICTED_RE = re.compile(r"^Evicted(?:DueTo)?(?P<reason>[A-Za-z]*)$")
# EvictedDueToDeactivatedDueToRequeuingLimitExceeded ->
# ("Deactivated", "RequeuingLimitExceeded").
_CAUSE_RE = re.compile(r"^(?P<reason>[A-Za-z]+?)DueTo(?P<detail>[A-Za-z]+)$")
_EVICT_CITE = "https://kueue.sigs.k8s.io/docs/concepts/workload/"
_MAX_WORKLOADS = 8
_MAX_MILESTONES = 14
@dataclasses.dataclass(frozen=True)
class Milestone:
"""Single timestamped lifecycle Event milestone for a Workload."""
ts: str
reason: str
count: int
message: str
@dataclasses.dataclass
class WorkloadLifecycle:
"""Aggregated lifecycle milestones and current state for a single Workload."""
ref: str
milestones: list[Milestone] = dataclasses.field(default_factory=list)
present: bool = False
requeue_count: Any = None
active: Any = None
def _evictions_and_deactivated(self) -> tuple[dict[str, int], str]:
"""Counts evictions by reason and captures the last deactivation cause."""
evictions: dict[str, int] = {}
deactivated = ""
for m in self.milestones:
ev = _EVICTED_RE.match(m.reason)
if not ev:
continue
reason = ev.group("reason") or "Unspecified"
cause = _CAUSE_RE.match(reason)
if cause:
reason = cause.group("reason")
if reason == "Deactivated":
deactivated = cause.group("detail")
evictions[reason] = evictions.get(reason, 0) + m.count
return evictions, deactivated
def outcome_key(self) -> str:
"""Groups workloads sharing the same terminal outcome shape into one key."""
evictions, deactivated = self._evictions_and_deactivated()
last = self.milestones[-1].reason if self.milestones else "none"
ev_sig = ",".join(f"{k}:{v}" for k, v in sorted(evictions.items()))
return (
f"workload-lifecycle:present={self.present}:ev={ev_sig}"
f":deact={deactivated}:active={self.active}:last={last}"
)
def summary(self) -> str:
"""Formats a one-line summary of admissions, evictions, and state."""
admitted = sum(m.count for m in self.milestones if m.reason == "Admitted")
evictions, deactivated = self._evictions_and_deactivated()
last = self.milestones[-1] if self.milestones else None
parts = [
f"admitted={admitted}",
"evicted=" + (str(evictions) if evictions else "{}"),
]
if deactivated:
parts.append(f"deactivated={deactivated}")
if self.requeue_count is not None:
parts.append(f"requeueState.count={self.requeue_count}")
if self.active is not None:
parts.append(f"spec.active={self.active}")
parts.append(f"last={last.reason}@{last.ts}" if last else "last=none")
parts.append(
"object_present="
+ ("yes" if self.present else "no (deleted or outside snapshot)")
)
return " ".join(parts)
def _is_milestone(reason: str) -> bool:
return reason in _MILESTONE_REASONS or bool(_EVICTED_RE.match(reason))
def collect_lifecycles(ctx) -> list[WorkloadLifecycle]:
"""Builds one lifecycle per Workload seen in Events or present in the snapshot."""
by_ref: dict[str, WorkloadLifecycle] = {}
for wl in ctx.workloads:
lc = by_ref.setdefault(
f"{k8s.namespace(wl)}/{k8s.name(wl)}",
WorkloadLifecycle(ref=f"{k8s.namespace(wl)}/{k8s.name(wl)}"),
)
lc.present = True
rq = k8s.status(wl).get("requeueState")
lc.requeue_count = (
k8s.as_dict(rq).get("count") if isinstance(rq, dict) else None
)
lc.active = k8s.spec(wl).get("active")
for ev in ctx.events:
obj = k8s.as_dict(ev.get("involvedObject"))
if str(obj.get("kind", "")) != "Workload" or not obj.get("name"):
continue
reason = str(ev.get("reason", ""))
if not _is_milestone(reason):
continue
ref = f"{obj.get('namespace', '')}/{obj.get('name')}"
lc = by_ref.setdefault(ref, WorkloadLifecycle(ref=ref))
count = (
ev.get("count")
if isinstance(ev.get("count"), int) and ev.get("count") > 0
else 1
)
lc.milestones.append(
Milestone(
k8s.event_timestamp(ev),
reason,
count,
str(ev.get("message", ""))[:160],
)
)
for lc in by_ref.values():
lc.milestones.sort(key=lambda m: m.ts)
# Workloads with evictions / deactivation first, then by milestone count.
return sorted(
by_ref.values(),
key=lambda lc: (
-sum(1 for m in lc.milestones if _EVICTED_RE.match(m.reason)),
-len(lc.milestones),
lc.ref,
),
)
def _has_lifecycle(lc: WorkloadLifecycle) -> bool:
"""A Workload earns a timeline once it moved past a single Pending/QuotaReserved event or had a terminal event."""
reasons = {m.reason for m in lc.milestones}
terminal = any(
_EVICTED_RE.match(r) or r in ("Finished", "Deactivated", "Preempted")
for r in reasons
)
return (
terminal
or len(reasons - {"Pending", "QuotaReserved"}) >= 1
and len(lc.milestones) >= 2
)
def emit_workload_timeline(ctx: Any) -> None:
"""Emits ordered lifecycle milestones and summaries per Workload (1g)."""
lifecycles = [lc for lc in collect_lifecycles(ctx) if _has_lifecycle(lc)]
if not lifecycles:
return
for lc in lifecycles[:_MAX_WORKLOADS]:
shown = lc.milestones[-_MAX_MILESTONES:]
omitted = len(lc.milestones) - len(shown)
chain = " -> ".join(
f"{m.ts} {m.reason}" + (f"(x{m.count})" if m.count > 1 else "")
for m in shown
)
# Untagged: chain is context; LIFECYCLE / TERMINAL_EVENT carry tagged facts.
ctx.add(
None,
f"WORKLOAD_TIMELINE: [Workload/{lc.ref}] "
+ (f"({omitted} earlier milestones omitted) " if omitted > 0 else "")
+ chain,
)
has_terminal = any(
_EVICTED_RE.match(m.reason) or m.reason in ("Finished", "Deactivated")
for m in shown
)
ctx.add(
lc.outcome_key() if (has_terminal or not lc.present) else None,
f"WORKLOAD_LIFECYCLE: [Workload/{lc.ref}] {lc.summary()}",
)
for m in shown:
if _EVICTED_RE.match(m.reason) or m.reason in ("Finished", "Deactivated"):
# WORKLOAD_LIFECYCLE already tags the terminal outcome; keep verbatim
# event lines untagged.
ctx.add(
None,
f"WORKLOAD_TERMINAL_EVENT: [Workload/{lc.ref}] {m.ts} {m.reason}:"
f" {m.message} (event reason vocabulary: {_EVICT_CITE})",
)
if len(lifecycles) > _MAX_WORKLOADS:
ctx.add(
None,
f"WORKLOAD_TIMELINE: ... {len(lifecycles) - _MAX_WORKLOADS} more"
" Workloads omitted (fewest evictions first)",
)
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