From 62ae97ccb46b72ab65b9b8f63364b1b82c5f9548 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Sat, 8 Aug 2026 22:51:28 -0600 Subject: [PATCH] feat(k8s): the runtime sweep is discovery-driven, bounded by namespaces instead of kinds (#1517) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The runtime-children sweep bounded itself by kind: first Pods (#1077), then the estate's own declared API groups (#1518). Both miss where the runtime tier says the most — an operator's children are whatever kinds its controllers make, including kinds in groups the estate never declares (a CR's Deployments, a chain through a foreign CRD group), and no kind list can anticipate them. The sweep now asks the cluster itself. K8sClient gains preferredGroupVersions() — one groupVersion per served group, from the same cached root discovery servedGroupVersions reads — and the sweep lists every listable kind those serve. What bounds it is reach, not a table: - namespaced kinds are listed only in the namespaces the declared estate touches (owner references cannot cross a namespace); - cluster-scoped kinds are listed only when a declared cluster-scoped entity resolved (a cluster-scoped object's owners are cluster-scoped, Kubernetes' own GC rule); - Events are skipped: they name their subject via involvedObject, never ownerReferences, so listing them can only cost; - outside Pods, a swept object is still only reported when its owner chain (or the #1549 label channel) resolves to a declared entity — the sweep is not an inventory. Tri-state honesty extends to the sweep: a kind discovery names but the sweep cannot list (RBAC denial, a flaking apiserver) becomes a runtime-sweep:* entry in unobserved — recorded once per kind, naming the scopes that failed — never a silent gap that would read as "no runtime children there". A list 404 stays an absence, and declared resolution is never failed by the sweep. The k8s lexicon's optional client dependency moves to ^0.42.1 so the workspace client (which carries the new method) links instead of the published 0.41.20 nesting under lexicons/k8s. --- lexicons/k8s/package.json | 2 +- lexicons/k8s/src/describe-resources.test.ts | 183 +++++++++++- lexicons/k8s/src/describe-resources.ts | 315 ++++++++++++-------- package-lock.json | 12 +- packages/k8s-client/src/client.test.ts | 33 ++ packages/k8s-client/src/client.ts | 72 ++++- 6 files changed, 465 insertions(+), 152 deletions(-) diff --git a/lexicons/k8s/package.json b/lexicons/k8s/package.json index b3233dd5ce..ad3eabfa15 100644 --- a/lexicons/k8s/package.json +++ b/lexicons/k8s/package.json @@ -76,7 +76,7 @@ "@types/js-yaml": "^4.0.9" }, "optionalDependencies": { - "@intentius/chant-k8s-client": "^0.41.5" + "@intentius/chant-k8s-client": "^0.42.1" }, "devDependencies": { "@intentius/chant": "*", diff --git a/lexicons/k8s/src/describe-resources.test.ts b/lexicons/k8s/src/describe-resources.test.ts index 7d97f68ee4..120a1d7d3f 100644 --- a/lexicons/k8s/src/describe-resources.test.ts +++ b/lexicons/k8s/src/describe-resources.test.ts @@ -573,6 +573,161 @@ describe("k8s describeResources", () => { expect(result.resources["prod/hand-made"]).toBeUndefined(); }); + // The issue's own estate: a declared MicroVMReplicaSet whose operator + // made MicroVMs — a CRD kind no table anticipated. Discovery names it. + test("a controller-made child of a CRD kind surfaces as a runtime child of the declared CR", async () => { + const replicaSet = { + apiVersion: "lambda.aws.amazon.com/v1alpha1", + kind: "MicroVMReplicaSet", + metadata: { name: "kmv-dev-a-vm", namespace: "microvm-demo", uid: "mvrs-uid" }, + }; + const vm = { + apiVersion: "lambda.aws.amazon.com/v1alpha1", + kind: "MicroVM", + metadata: { + name: "kmv-dev-a-vm-42sgf", + namespace: "microvm-demo", + uid: "vm-uid", + ownerReferences: [ + { apiVersion: "lambda.aws.amazon.com/v1alpha1", kind: "MicroVMReplicaSet", name: "kmv-dev-a-vm", uid: "mvrs-uid", controller: true }, + ], + }, + status: { phase: "Running" }, + }; + const cluster = fakeCluster({ + objects: { + [objectKey("lambda.aws.amazon.com/v1alpha1", "MicroVMReplicaSet", "kmv-dev-a-vm", "microvm-demo")]: replicaSet, + [objectKey("lambda.aws.amazon.com/v1alpha1", "MicroVM", "kmv-dev-a-vm-42sgf", "microvm-demo")]: vm, + }, + }); + + const result = await describeResources( + { + environment: "dev", + buildOutput: "", + entityNames: ["workloadReplicaSet"], + entities: makeEntities([ + { + name: "workloadReplicaSet", + entityType: "K8s::KubeMicroVM::MicroVMReplicaSet", + props: { metadata: { name: "kmv-dev-a-vm", namespace: "microvm-demo" } }, + }, + ]), + }, + cluster.connector, + ); + + expect(result.resources["microvm-demo/kmv-dev-a-vm-42sgf"]).toMatchObject({ + type: "K8s::Lambda::MicroVM", + physicalId: "vm-uid", + ownerChain: { root: "declared", entity: "workloadReplicaSet" }, + }); + }); + + test("a child in a group the estate never declares surfaces too — discovery names the kinds, not the declaration", async () => { + // A declared CR whose operator makes ordinary Deployments: ray.io is + // declared, apps/v1 is not, and the estate-groups sweep never listed it. + const rayCluster = { apiVersion: "ray.io/v1", kind: "RayCluster", metadata: { name: "ml", namespace: "ray", uid: "ray-uid" } }; + const head = { + apiVersion: "apps/v1", + kind: "Deployment", + metadata: { + name: "ml-head", + namespace: "ray", + uid: "head-uid", + ownerReferences: [{ apiVersion: "ray.io/v1", kind: "RayCluster", name: "ml", uid: "ray-uid", controller: true }], + }, + status: { readyReplicas: 1, replicas: 1 }, + }; + const cluster = fakeCluster({ + objects: { + [objectKey("ray.io/v1", "RayCluster", "ml", "ray")]: rayCluster, + [objectKey("apps/v1", "Deployment", "ml-head", "ray")]: head, + }, + }); + + const result = await describeResources( + { + environment: "prod", + buildOutput: "", + entityNames: ["ml"], + entities: makeEntities([ + { name: "ml", entityType: "K8s::Ray::RayCluster", props: { metadata: { name: "ml", namespace: "ray" } } }, + ]), + }, + cluster.connector, + ); + + expect(result.resources["ray/ml-head"]).toMatchObject({ + type: "K8s::Apps::Deployment", + physicalId: "head-uid", + ownerChain: { root: "declared", entity: "ml" }, + }); + }); + + test("a discovered kind the sweep cannot list is an unobserved hole, never silently absent", async () => { + const cluster = fakeCluster({ + objects: { [objectKey("batch/v1", "CronJob", "backup", "prod")]: cronJob }, + respond: (req) => + req.path === "/apis/batch/v1/namespaces/prod/jobs" + ? { status: 403, body: statusBody(403, "Forbidden", "jobs is forbidden") } + : undefined, + }); + + const result = await describeResources( + { environment: "prod", buildOutput: "", entityNames: ["backup"], entities: declaredCronJob() }, + cluster.connector, + ); + + // Declared resolution is never failed by the sweep. + expect(result.resources.backup).toMatchObject({ type: "K8s::Batch::CronJob", physicalId: "cj-uid" }); + // The failed list is a hole the observation admits, with the failure's + // own classification — a 403 is a credentials problem, and silence here + // would have read as "no runtime children in prod". + expect(result.unobserved?.["runtime-sweep:batch/v1/Job"]).toMatchObject({ + type: "K8s::Batch::Job", + reason: "no-credentials", + }); + expect(result.unobserved?.["runtime-sweep:batch/v1/Job"]?.detail).toContain("namespace prod"); + }); + + test("a cluster-scoped child chains to a declared cluster-scoped entity — the one case cluster-scoped kinds are swept", async () => { + const ns = { apiVersion: "v1", kind: "Namespace", metadata: { name: "team-a", uid: "ns-uid" }, status: { phase: "Active" } }; + const role = { + apiVersion: "rbac.authorization.k8s.io/v1", + kind: "ClusterRole", + metadata: { + name: "team-a-admin", + uid: "role-uid", + ownerReferences: [{ apiVersion: "v1", kind: "Namespace", name: "team-a", uid: "ns-uid", controller: true }], + }, + }; + const cluster = fakeCluster({ + objects: { + [objectKey("v1", "Namespace", "team-a")]: ns, + [objectKey("rbac.authorization.k8s.io/v1", "ClusterRole", "team-a-admin")]: role, + }, + }); + + const result = await describeResources( + { + environment: "prod", + buildOutput: "", + entityNames: ["team"], + entities: makeEntities([ + { name: "team", entityType: "K8s::Core::Namespace", props: { metadata: { name: "team-a" } } }, + ]), + }, + cluster.connector, + ); + + expect(result.resources["cluster:team-a-admin"]).toMatchObject({ + type: "K8s::Rbac::ClusterRole", + physicalId: "role-uid", + ownerChain: { root: "declared", entity: "team" }, + }); + }); + test("a Flux-managed Deployment is attributed to its declared Kustomization by the controller's labels (#1549)", async () => { // Flux stamps managed objects with name+namespace labels instead of // ownerReferences, so the chain walk reaches nothing — the label @@ -702,7 +857,7 @@ describe("k8s describeResources", () => { expect(result.resources["flux-system/cert-manager"]).toBeUndefined(); }); - test("a core-only estate sweeps no extra groups — Pods stay the core representative", async () => { + test("the sweep's bound is the estate's namespaces, not a kind list — and no cluster-scoped list without a cluster-scoped entity", async () => { const svc = { apiVersion: "v1", kind: "Service", metadata: { name: "web", namespace: "prod", uid: "svc-uid" } }; const cluster = fakeCluster({ objects: { [objectKey("v1", "Service", "web", "prod")]: svc }, @@ -720,10 +875,20 @@ describe("k8s describeResources", () => { cluster.connector, ); - // Discovery was consulted for no non-core groupVersion: the only list - // sweeps are the namespace's pods. - const groupDiscovery = cluster.layer.paths().filter((p) => /^\/apis\/[^/]+\/[^/]+$/.test(p) && !p.includes("namespaces")); - expect(groupDiscovery.filter((p) => !p.startsWith("/apis/apps"))).toEqual([]); + const paths = cluster.layer.paths(); + const isDiscovery = (p: string) => + p === "/api" || p === "/apis" || /^\/api\/[^/]+$/.test(p) || /^\/apis\/[^/]+\/[^/]+$/.test(p); + const reads = paths.filter((p) => !isDiscovery(p)); + // Discovery names the kinds; every actual read or list stays inside the + // one namespace the estate touches. Nothing is listed cluster-wide. + expect(reads.length).toBeGreaterThan(0); + expect(reads.every((p) => p.includes("/namespaces/prod/"))).toBe(true); + // Nothing declared is cluster-scoped, so no owner chain could reach a + // cluster-scoped object — their kinds are not listed at all. + expect(paths.some((p) => p.endsWith("/clusterroles"))).toBe(false); + // Events churn by the thousands and can never chain (`involvedObject`, + // not `ownerReferences`) — discovery serves them, the sweep skips them. + expect(paths.some((p) => p.endsWith("/events"))).toBe(false); }); }); @@ -914,7 +1079,7 @@ describe("k8s describeResources", () => { expect(Object.keys(result.resources)).toHaveLength(2); // web + standalonePod, no synthetic duplicate }); - test("a Pod-list failure for a namespace is best-effort — declared entities still resolve", async () => { + test("a Pod-list failure never fails declared resolution — and surfaces as an unobserved hole (#1517)", async () => { const cluster = fakeCluster({ objects: { [objectKey("apps/v1", "Deployment", "web", "prod")]: web }, respond: (req) => (req.path.endsWith("/pods") ? { status: 403, body: statusBody(403, "Forbidden", "no pods list") } : undefined), @@ -927,6 +1092,12 @@ describe("k8s describeResources", () => { expect(result.resources.web).toMatchObject({ type: "K8s::Apps::Deployment", physicalId: "uid-1" }); expect(Object.keys(result.resources)).toEqual(["web"]); + // Silence would read as "no runtime Pods in prod", which the failed + // list never proved — the sweep admits the hole instead. + expect(result.unobserved?.["runtime-sweep:v1/Pod"]).toMatchObject({ + type: "K8s::Core::Pod", + reason: "no-credentials", + }); }); test("a lexicon-supported entity type with no namespaced entities resolved does no Pod scan at all", async () => { diff --git a/lexicons/k8s/src/describe-resources.ts b/lexicons/k8s/src/describe-resources.ts index 96ff529668..39d2aeb280 100644 --- a/lexicons/k8s/src/describe-resources.ts +++ b/lexicons/k8s/src/describe-resources.ts @@ -42,17 +42,19 @@ * exactly the shape `lifecycle diff --live` has always classified `orphan`. * On Kubernetes that is wrong: it is expected runtime, not drift, and will be * recreated the moment it is deleted. After the declared-entity reads above - * resolve, this scans Pods in the namespaces they actually live in and walks - * each one's `ownerReferences` chain (`./api/owner-chain.ts`) against the - * entities this very call resolved. A chain reaching one of them is reported - * with `ownerChain: { root: "declared", ... }`; core's diff/change-set engine - * reads that as `runtime` instead of `orphan`. Deliberately scoped to Pods — - * the concrete case the issue and its acceptance criteria name — and to the - * namespaces this observation already touched, not a cluster-wide sweep; - * widening to other controller-spawned kinds is the same walk repeated. + * resolve, this sweeps candidate kinds in the namespaces they actually live in + * and walks each object's `ownerReferences` chain (`./api/owner-chain.ts`) + * against the entities this very call resolved. A chain reaching one of them + * is reported with `ownerChain: { root: "declared", ... }`; core's + * diff/change-set engine reads that as `runtime` instead of `orphan`. + * + * Which kinds are candidates is the cluster's own API discovery's answer + * (#1517): every listable kind it serves, one version per group. The sweep's + * bound is the namespaces the declared estate touches, never a kind table — + * see `addRuntimeChildren`. */ -import type { ObservationResult, ResourceMetadata, UnobservedEntity } from "@intentius/chant/lexicon"; +import type { ObservationResult, ResourceMetadata, UnobservedEntity, UnobservedReason } from "@intentius/chant/lexicon"; import { observation, unobservedAll } from "@intentius/chant/observation"; import { hasOwnershipMarker, classifyOwnership, LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership"; import type { K8sClient, K8sObject } from "@intentius/chant-k8s-client"; @@ -366,44 +368,47 @@ export async function describeResources( } }); - // chant #1517 — the API groups this estate's own declarations use. A - // controller's children usually live in its controller's group (a - // MicroVMReplicaSet makes MicroVMs), so the runtime scan sweeps those - // groupVersions' kinds besides Pods. Core (`v1`) is excluded from the group - // sweep — Pods represent it; sweeping every core kind would walk endpoints - // and events for nothing. - const runtimeGroupVersions = new Set(); - for (const { entityType } of declared) { - const op = operationFor(entityType); - if (op && op.apiVersion.includes("/")) runtimeGroupVersions.add(op.apiVersion); - } - - await addRuntimeChildren(client, resources, options.owned, runtimeGroupVersions, declared); + await addRuntimeChildren(client, resources, unobserved, options.owned, declared); return observation(resources, unobserved); } /** - * Scan runtime-child candidates in the namespaces of entities this call just + * Sweep runtime-child candidates in the namespaces of entities this call just * resolved, and classify each one's owner-reference chain (#1077). Mutates * `resources` in place, adding an entry per object whose chain was worth - * reporting. + * reporting, and `unobserved` for the parts of the sweep that could not look. + * + * The candidate kinds are the cluster's own API discovery's answer (#1517): + * every listable kind it serves, one version per group (the group's + * preferredVersion, so nothing is listed twice at a second served version). + * The first cut scoped this to Pods, the second to the estate's own declared + * API groups — and both missed exactly where the runtime tier says the most: + * an operator's children are whatever kinds its controllers make (a + * MicroVMReplicaSet's MicroVMs, a CR's Deployments in a group the estate + * never declares), which no kind table can anticipate. The same open-world + * inversion behold#74 made for declared CRDs, applied to the runtime axis. * - * Two candidate pools: - * - **Pods** — the built-in workload leaf, always scanned. - * - **The estate's own API groups** (#1517) — every namespaced, listable - * kind in each `groupVersions` entry, from the cluster's own discovery. - * An operator estate's interesting children are custom resources its - * controllers made (a MicroVMReplicaSet's MicroVMs), which no kind table - * could anticipate — the same open-world inversion behold#74 made for - * declared CRDs, applied to the runtime axis. Bounded by what the estate - * declares, never a cluster-wide sweep. + * What bounds the sweep is not a kind list but reach: + * - **Namespaced kinds** are listed only in the namespaces the declared + * estate touches (where its entities resolved, plus the namespaces its + * GitOps CRs target) — owner references cannot cross a namespace, so a + * child elsewhere could never chain to this estate anyway. + * - **Cluster-scoped kinds** are listed only when the estate resolved a + * cluster-scoped entity — a cluster-scoped object's owners are themselves + * cluster-scoped (Kubernetes' own GC rule), so without one declared there + * is nothing such a chain could reach. + * - **It is not an inventory**: outside Pods (whose chain verdicts, foreign + * included, are #1077's original contract), a swept object is only + * reported when its chain resolves to a declared entity. * - * Best-effort and additive: a namespace or kind this scan cannot list (RBAC - * denial, a transient error) is simply skipped rather than failing the - * observation — these are not declared entities, so there is no NOT-OBSERVED - * axis for them to report against, the same way an out-of-band AWS child - * resource has none either. + * Tri-state honesty (#1089, extended to the sweep): a kind discovery names + * but the sweep cannot list — RBAC denial, a flaking apiserver — becomes a + * `runtime-sweep:*` entry in `unobserved`, never a silent gap. Silence would + * read as "no runtime children there", which the failed list never proved. + * A list 404 (the kind vanished between discovery and the list) stays an + * absence, per `classifyApiFailure`'s standing rule. Declared-entity + * resolution is never failed by the sweep. */ /** The declared GitOps CRs, indexed the way their controllers' labels can be * resolved (#1549). `byRef` keys are `type\0namespace\0name` (Flux — exact); @@ -466,11 +471,29 @@ function gitopsOwner(labels: Record | undefined, gitops: GitopsI return undefined; } +/** One candidate kind of the discovery-driven sweep. */ +interface SweptKind { + apiVersion: string; + kind: string; + typeName: string; +} + +/** + * Kinds the sweep skips even though discovery serves them. Not a kind table + * creeping back in: each entry is a kind that CANNOT attribute to a declared + * owner — an Event names its subject via `involvedObject`, never + * `ownerReferences` — and churns by the thousands in any active namespace, + * so listing it can only cost and never attach. + */ +function isSweepNoise(info: { kind: string; group: string }): boolean { + return info.kind === "Event" && (info.group === "" || info.group === "events.k8s.io"); +} + async function addRuntimeChildren( client: K8sClient, resources: Record, + unobserved: Record, owned: boolean | undefined, - groupVersions: ReadonlySet = new Set(), declared: readonly Declared[] = [], ): Promise { const declaredByUid = new Map(); @@ -488,9 +511,11 @@ async function addRuntimeChildren( const gitops = gitopsIndex(declared); const namespaces = new Set(); + let clusterScopedDeclared = false; for (const meta of Object.values(resources)) { const namespace = (meta.attributes as { namespace?: string } | undefined)?.namespace; if (namespace) namespaces.add(namespace); + else clusterScopedDeclared = true; } // The namespaces a declared GitOps CR TARGETS are declared literals too // (Argo `spec.destination.namespace`, Flux `spec.targetNamespace`) — the @@ -498,93 +523,147 @@ async function addRuntimeChildren( // reading it off the declaration keeps this bounded by the estate, never a // cluster-wide sweep. for (const ns of gitops.targetNamespaces) namespaces.add(ns); - if (namespaces.size === 0) return; - - // The kinds to scan: Pods, plus each declared groupVersion's namespaced, - // listable kinds from discovery (#1517). A groupVersion the cluster does - // not serve contributes nothing — an answer, not a failure. - const kinds: Array<{ apiVersion: string; kind: string; typeName: string }> = [ - { apiVersion: "v1", kind: "Pod", typeName: "K8s::Core::Pod" }, - ]; - // A GitOps estate's managed WORKLOADS live in groups the estate itself never - // declares (a pure Argo/Flux estate declares only the CRs), so without this - // the label channel could only ever fire on Pods (#1549). - if (gitops.present) { - kinds.push( - { apiVersion: "apps/v1", kind: "Deployment", typeName: "K8s::Apps::Deployment" }, - { apiVersion: "apps/v1", kind: "StatefulSet", typeName: "K8s::Apps::StatefulSet" }, - { apiVersion: "apps/v1", kind: "DaemonSet", typeName: "K8s::Apps::DaemonSet" }, - { apiVersion: "v1", kind: "Service", typeName: "K8s::Core::Service" }, - { apiVersion: "v1", kind: "ConfigMap", typeName: "K8s::Core::ConfigMap" }, - ); + if (namespaces.size === 0 && !clusterScopedDeclared) return; + + // Every kind the cluster serves, from its own discovery (#1517): one + // groupVersion per group, every listable kind, split by scope. Failing to + // enumerate is a hole the observation must admit — silently sweeping + // nothing would read as "no runtime children", which was never established. + let groupVersions: string[]; + try { + groupVersions = await client.preferredGroupVersions(); + } catch (err) { + const outcome = classifyApiFailure(err); + unobserved["runtime-sweep"] = { + reason: outcome.kind === "unobserved" ? outcome.reason : "read-failed", + detail: + "cluster API discovery failed, so runtime children were not swept" + + (outcome.kind === "unobserved" ? `: ${outcome.detail}` : ""), + }; + return; } - for (const gv of [...groupVersions].sort()) { - let infos; + + const perGroup = await client.concurrently(groupVersions, async (gv) => { try { - infos = await client.resources(gv); - } catch { - continue; // best-effort — see the function doc + return await client.resources(gv); + } catch (err) { + const outcome = classifyApiFailure(err); + if (outcome.kind === "unobserved") { + unobserved[`runtime-sweep:${gv}`] = { + reason: outcome.reason, + detail: `discovery for ${gv} failed, so its kinds were not swept: ${outcome.detail}`, + }; + } + return []; } - const [group, version] = [gv.slice(0, gv.indexOf("/")), gv.slice(gv.indexOf("/") + 1)]; + }); + + const namespacedKinds: SweptKind[] = []; + const clusterKinds: SweptKind[] = []; + for (const infos of perGroup) { for (const info of infos) { - if (!info.namespaced || !info.verbs.includes("list")) continue; - kinds.push({ apiVersion: gv, kind: info.kind, typeName: gvkToTypeName({ group, version, kind: info.kind }) }); + if (!info.verbs.includes("list") || isSweepNoise(info)) continue; + const swept: SweptKind = { + apiVersion: info.apiVersion, + kind: info.kind, + typeName: gvkToTypeName({ group: info.group, version: info.version, kind: info.kind }), + }; + (info.namespaced ? namespacedKinds : clusterKinds).push(swept); } } - await client.concurrently([...namespaces], async (namespace) => { - for (const { apiVersion, kind, typeName } of kinds) { - let objects: K8sObject[]; - try { - objects = await client.list({ apiVersion, kind }, { namespace }); - } catch { - continue; // best-effort — see the function doc - } + // A failed list is recorded once per kind, naming every scope it failed in, + // rather than once per (kind, namespace) — one RBAC rule denying a kind + // across N namespaces is one hole, not N. + const listFailures = new Map< + string, + { typeName: string; reason: UnobservedReason; scopes: string[]; detail: string } + >(); - await client.concurrently(objects, async (obj) => { - const uid = obj.metadata?.uid; - const name = obj.metadata?.name; - if (!uid || !name || declaredByUid.has(uid)) return; // declared directly, or unaddressable - if (resources[`${namespace}/${name}`]) return; // already reported by an earlier kind - - let ownerChain = await resolveK8sOwnerChain(obj, { declaredByUid, reader: client, namespace }); - // The label channel (#1549) — only when the chain itself said nothing: - // a verdict the walk DID reach is never overridden. - if (ownerChain.root !== "declared") { - const entity = gitopsOwner(obj.metadata?.labels, gitops); - if (entity) ownerChain = { root: "declared", entity }; - } - - // `--owned`: withhold an object that is neither a runtime child of a - // declared entity nor carrying chant's own marker — the same rule the - // declared-entity read above applies, extended to the undeclared axis - // this scan introduces. - const marker = hasOwnershipMarker(obj.metadata?.labels, LABEL_OWNERSHIP_KEYS); - if (owned && ownerChain.root !== "declared" && !marker) return; - - // An undeclared object with NO owner chain at all is not a runtime - // child — reporting every loose object a group serves would turn the - // scan into an inventory. Pods keep their pre-#1517 reporting (their - // chain verdicts, including foreign, were already part of #1077's - // contract); swept group kinds only report when the chain reaches a - // declared entity. - if (kind !== "Pod" && ownerChain.root !== "declared") return; - - resources[`${namespace}/${name}`] = { - type: typeName, - physicalId: uid, - status: statusFromObject(obj), - lastUpdated: obj.metadata?.creationTimestamp, - ownership: classifyOwnership(obj.metadata?.labels, LABEL_OWNERSHIP_KEYS), - ownerChain, - attributes: pruneUndefined({ - namespace, - labels: obj.metadata?.labels, - resourceVersion: obj.metadata?.resourceVersion, - conditions: unhappyConditions(obj), - }), - }; - }); + const sweep = async (swept: SweptKind, namespace: string | undefined): Promise => { + let objects: K8sObject[]; + try { + objects = await client.list( + { apiVersion: swept.apiVersion, kind: swept.kind }, + namespace ? { namespace } : {}, + ); + } catch (err) { + const outcome = classifyApiFailure(err); + // `absent` (a list 404: the kind vanished between discovery and now) + // proves no instance exists — nothing to record. + if (outcome.kind === "unobserved") { + const key = `runtime-sweep:${swept.apiVersion}/${swept.kind}`; + const scope = namespace ? `namespace ${namespace}` : "cluster scope"; + const failure = listFailures.get(key); + if (failure) failure.scopes.push(scope); + else listFailures.set(key, { typeName: swept.typeName, reason: outcome.reason, scopes: [scope], detail: outcome.detail }); + } + return; } + + await client.concurrently(objects, async (obj) => { + const uid = obj.metadata?.uid; + const name = obj.metadata?.name; + if (!uid || !name || declaredByUid.has(uid)) return; // declared directly, or unaddressable + const key = namespace ? `${namespace}/${name}` : `cluster:${name}`; + if (resources[key]) return; // already reported by an earlier kind + + let ownerChain = await resolveK8sOwnerChain(obj, { declaredByUid, reader: client, namespace }); + // The label channel (#1549) — only when the chain itself said nothing: + // a verdict the walk DID reach is never overridden. + if (ownerChain.root !== "declared") { + const entity = gitopsOwner(obj.metadata?.labels, gitops); + if (entity) ownerChain = { root: "declared", entity }; + } + + // `--owned`: withhold an object that is neither a runtime child of a + // declared entity nor carrying chant's own marker — the same rule the + // declared-entity read above applies, extended to the undeclared axis + // this scan introduces. + const marker = hasOwnershipMarker(obj.metadata?.labels, LABEL_OWNERSHIP_KEYS); + if (owned && ownerChain.root !== "declared" && !marker) return; + + // An undeclared object with NO owner chain at all is not a runtime + // child — reporting every loose object the cluster serves would turn + // the sweep into an inventory. Pods keep their pre-#1517 reporting + // (their chain verdicts, including foreign, were already part of + // #1077's contract); every other swept kind only reports when the + // chain reaches a declared entity. + if (swept.kind !== "Pod" && ownerChain.root !== "declared") return; + + resources[key] = { + type: swept.typeName, + physicalId: uid, + status: statusFromObject(obj), + lastUpdated: obj.metadata?.creationTimestamp, + ownership: classifyOwnership(obj.metadata?.labels, LABEL_OWNERSHIP_KEYS), + ownerChain, + attributes: pruneUndefined({ + namespace, + labels: obj.metadata?.labels, + resourceVersion: obj.metadata?.resourceVersion, + conditions: unhappyConditions(obj), + }), + }; + }); + }; + + await client.concurrently([...namespaces], async (namespace) => { + for (const swept of namespacedKinds) await sweep(swept, namespace); }); + + // Cluster-scoped kinds are swept once (their lists are cluster-wide by + // nature), and only when a declared cluster-scoped entity exists for a + // chain to reach — a cluster-scoped object's owners are cluster-scoped. + if (clusterScopedDeclared) { + await client.concurrently(clusterKinds, async (swept) => sweep(swept, undefined)); + } + + for (const [key, failure] of listFailures) { + unobserved[key] = { + type: failure.typeName, + reason: failure.reason, + detail: `the runtime-children sweep could not list this kind in ${failure.scopes.join(", ")}: ${failure.detail}`, + }; + } } diff --git a/package-lock.json b/package-lock.json index 65a0cee837..4c9c3466e8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -231,7 +231,7 @@ "typescript": "^5.9.3" }, "optionalDependencies": { - "@intentius/chant-k8s-client": "^0.41.5" + "@intentius/chant-k8s-client": "^0.42.1" }, "peerDependencies": { "@intentius/chant": "^0.42.1", @@ -239,16 +239,6 @@ "zod": "^4.3.6" } }, - "lexicons/k8s/node_modules/@intentius/chant-k8s-client": { - "version": "0.41.20", - "resolved": "https://registry.npmjs.org/@intentius/chant-k8s-client/-/chant-k8s-client-0.41.20.tgz", - "integrity": "sha512-i1AhwIjnk2QwbgN0FoJceS2HPU36InLKWNRD44vmSXHq57Ke9YGf+hqtbwCVvYhCL3OVdaJMxHqsdiW88sTfeA==", - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@kubernetes/client-node": "^1.4.0" - } - }, "lexicons/temporal": { "name": "@intentius/chant-lexicon-temporal", "version": "0.42.1", diff --git a/packages/k8s-client/src/client.test.ts b/packages/k8s-client/src/client.test.ts index 3b3e1cc819..4a0f341d1b 100644 --- a/packages/k8s-client/src/client.test.ts +++ b/packages/k8s-client/src/client.test.ts @@ -201,6 +201,39 @@ describe("resource resolution through the cluster's own discovery", () => { expect(c.discoveryCacheKeys()).toEqual(["apps/v1"]); }); + // chant #1517 — the runtime-children sweep's enumeration unit: one version + // per group, so every kind is named exactly once. + test("preferredGroupVersions returns core v1 plus each group's own preferredVersion, once", async () => { + const layer = fakeRequestLayer((req) => { + if (req.path === "/api") return { body: { kind: "APIVersions", versions: ["v1"] } }; + if (req.path === "/apis") { + return { + body: { + kind: "APIGroupList", + groups: [ + { + name: "apps", + preferredVersion: { groupVersion: "apps/v1", version: "v1" }, + versions: [{ groupVersion: "apps/v1" }, { groupVersion: "apps/v1beta1" }], + }, + // A group reporting no preferredVersion falls back to its first + // listed version rather than being dropped. + { name: "widgets.example.com", versions: [{ groupVersion: "widgets.example.com/v1alpha1" }] }, + ], + }, + }; + } + return { status: 404, body: statusBody(404, "NotFound", `${req.path} not found`) }; + }); + const c = await client(layer); + + expect(await c.preferredGroupVersions()).toEqual(["v1", "apps/v1", "widgets.example.com/v1alpha1"]); + + // Cached: a second call issues no further discovery requests. + await c.preferredGroupVersions(); + expect(layer.paths().filter((p) => p === "/apis")).toHaveLength(1); + }); + test("kubectl-style resource strings resolve the way kubectl resolves them", async () => { const c = await client(cluster()); // plural.group — how waitForReady's callers have always spelled CRDs diff --git a/packages/k8s-client/src/client.ts b/packages/k8s-client/src/client.ts index b06c94b2df..374dc13a00 100644 --- a/packages/k8s-client/src/client.ts +++ b/packages/k8s-client/src/client.ts @@ -215,6 +215,15 @@ export interface K8sClient { * such groupVersion — an answer, not a failure. Cached like `resolve`. */ resources(apiVersion: string, signal?: AbortSignal): Promise; + /** + * One groupVersion per API group the cluster serves — each group's own + * `preferredVersion` (falling back to its first listed version), with the + * core group's `v1` first (chant #1517). This is the discovery-driven + * sweep's enumeration unit: one version per group names every kind exactly + * once, without re-listing the same resources at a second served version. + * Cached for the client's lifetime, like the rest of discovery. + */ + preferredGroupVersions(signal?: AbortSignal): Promise; /** The API resource lists discovery has been asked for so far, for tests and diagnostics. */ discoveryCacheKeys(): string[]; } @@ -231,6 +240,14 @@ interface ApiResourceListResponse { }>; } +/** The `/api` + `/apis` root discovery documents, kept structured so both the + * flat enumeration (`servedGroupVersions`) and the one-per-group enumeration + * (`preferredGroupVersions`, chant #1517) derive from a single cached fetch. */ +interface RootDiscovery { + coreVersions: string[]; + groups: Array<{ preferred?: string; versions: string[] }>; +} + /** * Build a client. Nothing is read from the network here — the kubeconfig is * parsed, the context resolved, and the credential policy enforced, all before @@ -306,7 +323,7 @@ export async function createK8sClient(options: K8sClientOptions = {}): Promise>(); - let groupVersionsCache: Promise | undefined; + let rootDiscoveryCache: Promise | undefined; async function send( path: string, @@ -399,15 +416,13 @@ export async function createK8sClient(options: K8sClientOptions = {}): Promise { - if (groupVersionsCache) return groupVersionsCache; - groupVersionsCache = (async () => { - const out: string[] = []; + async function rootDiscovery(signal?: AbortSignal): Promise { + if (rootDiscoveryCache) return rootDiscoveryCache; + rootDiscoveryCache = (async (): Promise => { const core = await sendJson<{ versions?: string[] }>("/api", "GET", { signal, target: "discovery /api", }); - out.push(...(core.versions ?? ["v1"])); const groups = await sendJson<{ groups?: Array<{ name?: string; @@ -415,19 +430,43 @@ export async function createK8sClient(options: K8sClientOptions = {}): Promise; }>; }>("/apis", "GET", { signal, target: "discovery /apis" }); - for (const group of groups.groups ?? []) { - const preferred = group.preferredVersion?.groupVersion; - if (preferred) out.push(preferred); - for (const v of group.versions ?? []) { - if (v.groupVersion && v.groupVersion !== preferred) out.push(v.groupVersion); - } - } - return [...new Set(out)]; + return { + coreVersions: core.versions ?? ["v1"], + groups: (groups.groups ?? []).map((group) => ({ + preferred: group.preferredVersion?.groupVersion, + versions: (group.versions ?? []) + .map((v) => v.groupVersion) + .filter((gv): gv is string => typeof gv === "string" && gv.length > 0), + })), + }; })().catch((err: unknown) => { - groupVersionsCache = undefined; + rootDiscoveryCache = undefined; throw err; }); - return groupVersionsCache; + return rootDiscoveryCache; + } + + async function servedGroupVersions(signal?: AbortSignal): Promise { + const root = await rootDiscovery(signal); + const out: string[] = [...root.coreVersions]; + for (const group of root.groups) { + if (group.preferred) out.push(group.preferred); + for (const gv of group.versions) { + if (gv !== group.preferred) out.push(gv); + } + } + return [...new Set(out)]; + } + + async function preferredGroupVersions(signal?: AbortSignal): Promise { + const root = await rootDiscovery(signal); + const core = root.coreVersions.includes("v1") ? "v1" : root.coreVersions[0]; + const out: string[] = core ? [core] : []; + for (const group of root.groups) { + const gv = group.preferred ?? group.versions[0]; + if (gv) out.push(gv); + } + return [...new Set(out)]; } function toInfo(apiVersion: string, entry: NonNullable[number]): ApiResourceInfo { @@ -655,6 +694,7 @@ export async function createK8sClient(options: K8sClientOptions = {}): Promise mapConcurrent(items, fn, concurrency), resources: resourcesOf, + preferredGroupVersions, discoveryCacheKeys: () => [...discoveryCache.keys()].sort(), }; }