From ed70e1c56b26e23e5f3104cad2ac42a2d8712f34 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Tue, 28 Jul 2026 01:56:45 -0600 Subject: [PATCH] feat(k8s): owner-referenced children are runtime, not orphans (#1077) A Pod a declared Deployment's controller creates is live and undeclared, the same shape the diff engine has always classified `orphan`. That makes `lifecycle plan` propose deletes for things the controller simply recreates. `ownerReferences` distinguishes an expected runtime child from a genuine orphan; no other chant substrate maintains that chain. Core owns the new classification (`OwnerChainVerdict` in packages/core/src/owner-chain.ts, a pure bounded/cycle-safe chain walker) and threads it through `diffLive` (new `runtimeChildren` bucket), `buildChangeSet` (new `runtime` action, never delete/adopt), and the graph overlays (`_status: "runtime"` instead of `warn`/foreign). An unresolved chain (unreadable hop, cycle, depth bound) stays conservative and routes as `orphan`, composing with #1168's tri-state. The k8s lexicon supplies the chain: describeResources() now scans Pods in the namespaces of entities it just resolved and walks each one's ownerReferences (reading past undeclared intermediates like a ReplicaSet) against the declared/observed set from the same call. Every consumer change is additive; a lexicon that never sets `ownerChain` is unaffected. --- lexicons/k8s/src/api/owner-chain.test.ts | 171 +++++++++++++ lexicons/k8s/src/api/owner-chain.ts | 144 +++++++++++ lexicons/k8s/src/describe-resources.test.ts | 225 +++++++++++++++++- lexicons/k8s/src/describe-resources.ts | 87 ++++++- packages/core/src/cli/handlers/lifecycle.ts | 5 + packages/core/src/graph-ir-live.test.ts | 40 ++++ packages/core/src/graph-ir.ts | 39 ++- packages/core/src/index.ts | 1 + packages/core/src/lexicon.ts | 21 ++ .../core/src/lifecycle/change-set.test.ts | 100 ++++++++ packages/core/src/lifecycle/change-set.ts | 49 +++- packages/core/src/lifecycle/live-diff.test.ts | 88 +++++++ packages/core/src/lifecycle/live-diff.ts | 63 ++++- packages/core/src/owner-chain.test.ts | 97 ++++++++ packages/core/src/owner-chain.ts | 128 ++++++++++ 15 files changed, 1231 insertions(+), 27 deletions(-) create mode 100644 lexicons/k8s/src/api/owner-chain.test.ts create mode 100644 lexicons/k8s/src/api/owner-chain.ts create mode 100644 packages/core/src/owner-chain.test.ts create mode 100644 packages/core/src/owner-chain.ts diff --git a/lexicons/k8s/src/api/owner-chain.test.ts b/lexicons/k8s/src/api/owner-chain.test.ts new file mode 100644 index 0000000000..96ce5d82ce --- /dev/null +++ b/lexicons/k8s/src/api/owner-chain.test.ts @@ -0,0 +1,171 @@ +import { describe, test, expect, vi } from "vitest"; +import { resolveK8sOwnerChain } from "./owner-chain"; +import type { K8sObject } from "@intentius/chant-k8s-client"; + +function pod(uid: string, ownerRefs?: Array>): K8sObject { + return { + apiVersion: "v1", + kind: "Pod", + metadata: { name: "p", namespace: "prod", uid, ...(ownerRefs ? { ownerReferences: ownerRefs } : {}) }, + }; +} + +function ownerRef(kind: string, name: string, uid: string, controller = true): Record { + return { apiVersion: "apps/v1", kind, name, uid, controller }; +} + +describe("resolveK8sOwnerChain (#1077)", () => { + test("no ownerReferences at all → unowned", async () => { + const reader = { readIfPresent: vi.fn() }; + const result = await resolveK8sOwnerChain(pod("pod-uid"), { + declaredByUid: new Map(), + reader, + namespace: "prod", + }); + expect(result).toEqual({ root: "unowned" }); + expect(reader.readIfPresent).not.toHaveBeenCalled(); + }); + + test("owner uid matches a declared entity directly → declared, no extra reads", async () => { + const reader = { readIfPresent: vi.fn() }; + const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("Deployment", "web", "deploy-uid")]), { + declaredByUid: new Map([["deploy-uid", "web"]]), + reader, + namespace: "prod", + }); + expect(result).toEqual({ root: "declared", entity: "web" }); + expect(reader.readIfPresent).not.toHaveBeenCalled(); + }); + + test("Pod → ReplicaSet (undeclared, read live) → Deployment (declared) resolves through the intermediate hop", async () => { + const replicaSet: K8sObject = { + apiVersion: "apps/v1", + kind: "ReplicaSet", + metadata: { + name: "web-7d9f8c9c8", + namespace: "prod", + uid: "rs-uid", + ownerReferences: [ownerRef("Deployment", "web", "deploy-uid")], + }, + }; + const reader = { readIfPresent: vi.fn().mockResolvedValue(replicaSet) }; + const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("ReplicaSet", "web-7d9f8c9c8", "rs-uid")]), { + declaredByUid: new Map([["deploy-uid", "web"]]), + reader, + namespace: "prod", + }); + expect(result).toEqual({ root: "declared", entity: "web" }); + expect(reader.readIfPresent).toHaveBeenCalledTimes(1); + expect(reader.readIfPresent).toHaveBeenCalledWith({ + apiVersion: "apps/v1", + kind: "ReplicaSet", + name: "web-7d9f8c9c8", + namespace: "prod", + }); + }); + + test("chain resolves fully to a live, undeclared root → foreign", async () => { + const replicaSet: K8sObject = { + apiVersion: "apps/v1", + kind: "ReplicaSet", + metadata: { name: "other-rs", namespace: "prod", uid: "rs-uid" }, // no further owner + }; + const reader = { readIfPresent: vi.fn().mockResolvedValue(replicaSet) }; + const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("ReplicaSet", "other-rs", "rs-uid")]), { + declaredByUid: new Map(), // nothing declared at all + reader, + namespace: "prod", + }); + expect(result).toEqual({ root: "foreign" }); + }); + + test("an owner read that 404s (readIfPresent → undefined) is conservative unknown, not foreign", async () => { + const reader = { readIfPresent: vi.fn().mockResolvedValue(undefined) }; + const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("ReplicaSet", "gone-rs", "rs-uid")]), { + declaredByUid: new Map(), + reader, + namespace: "prod", + }); + expect(result).toEqual({ root: "unknown" }); + }); + + test("an owner read that throws (RBAC denial, transport error) is conservative unknown", async () => { + const reader = { readIfPresent: vi.fn().mockRejectedValue(new Error("Forbidden")) }; + const result = await resolveK8sOwnerChain(pod("pod-uid", [ownerRef("ReplicaSet", "denied-rs", "rs-uid")]), { + declaredByUid: new Map(), + reader, + namespace: "prod", + }); + expect(result).toEqual({ root: "unknown" }); + }); + + test("a cycle (A owns B, B owns A) terminates and classifies unknown rather than looping forever", async () => { + const objA: K8sObject = { + apiVersion: "v1", + kind: "Widget", + metadata: { name: "a", namespace: "prod", uid: "a-uid", ownerReferences: [ownerRef("Widget", "b", "b-uid")] }, + }; + const objB: K8sObject = { + apiVersion: "v1", + kind: "Widget", + metadata: { name: "b", namespace: "prod", uid: "b-uid", ownerReferences: [ownerRef("Widget", "a", "a-uid")] }, + }; + const reader = { + readIfPresent: vi.fn(async ({ name }: { name: string }) => (name === "a" ? objA : objB)), + }; + const start: K8sObject = { + apiVersion: "v1", + kind: "Widget", + metadata: { name: "start", namespace: "prod", uid: "start-uid", ownerReferences: [ownerRef("Widget", "a", "a-uid")] }, + }; + const result = await resolveK8sOwnerChain(start, { declaredByUid: new Map(), reader, namespace: "prod" }); + expect(result).toEqual({ root: "unknown" }); + }); + + test("respects a custom maxDepth, fetching no more than maxDepth + 1 objects", async () => { + // A chain 5 hops deep, but bounded to 2 — never reaches the declared root. + const objects: Record = {}; + for (let i = 0; i < 5; i++) { + objects[`n${i}`] = { + apiVersion: "v1", + kind: "Widget", + metadata: { name: `n${i}`, namespace: "prod", uid: `uid-${i}`, ownerReferences: [ownerRef("Widget", `n${i + 1}`, `uid-${i + 1}`)] }, + }; + } + const reader = { + readIfPresent: vi.fn(async ({ name }: { name: string }) => objects[name]), + }; + const start: K8sObject = { + apiVersion: "v1", + kind: "Widget", + metadata: { name: "start", namespace: "prod", uid: "start-uid", ownerReferences: [ownerRef("Widget", "n0", "uid-0")] }, + }; + const result = await resolveK8sOwnerChain(start, { + declaredByUid: new Map([["uid-4", "deep-entity"]]), // reachable, but past the bound + reader, + namespace: "prod", + maxDepth: 2, + }); + expect(result).toEqual({ root: "unknown" }); + expect(reader.readIfPresent.mock.calls.length).toBeLessThanOrEqual(3); // maxDepth + 1 + }); + + test("a starting object without a uid cannot be classified — unknown", async () => { + const reader = { readIfPresent: vi.fn() }; + const noUid: K8sObject = { apiVersion: "v1", kind: "Pod", metadata: { name: "p", namespace: "prod" } }; + const result = await resolveK8sOwnerChain(noUid, { declaredByUid: new Map(), reader, namespace: "prod" }); + expect(result).toEqual({ root: "unknown" }); + expect(reader.readIfPresent).not.toHaveBeenCalled(); + }); + + test("picks the controller:true owner reference when several are present", async () => { + const reader = { readIfPresent: vi.fn() }; + const refs = [ownerRef("OtherOwner", "shared", "shared-uid", false), ownerRef("Deployment", "web", "deploy-uid", true)]; + const result = await resolveK8sOwnerChain(pod("pod-uid", refs), { + declaredByUid: new Map([["deploy-uid", "web"]]), + reader, + namespace: "prod", + }); + expect(result).toEqual({ root: "declared", entity: "web" }); + }); +}); diff --git a/lexicons/k8s/src/api/owner-chain.ts b/lexicons/k8s/src/api/owner-chain.ts new file mode 100644 index 0000000000..4e01ab4644 --- /dev/null +++ b/lexicons/k8s/src/api/owner-chain.ts @@ -0,0 +1,144 @@ +/** + * Resolving a live Kubernetes object's `ownerReferences` chain up to a + * declared, chant-observed entity (chant #1077). + * + * There is no server-side "who ultimately owns this object" query — Kubernetes' + * own garbage collector does not have one either; it walks the same chain one + * hop at a time, reading each intermediate owner. A Pod's `ownerReferences` + * names its ReplicaSet, which chant never declared; the ReplicaSet's own + * `ownerReferences` names the Deployment, which is declared. Reaching that + * declared entity takes reading the ReplicaSet in between. + * + * This module's only job is assembling that chain — fetching each hop through + * the typed client, bounded and cycle-guarded so a corrupt or adversarial + * chain cannot hang an observation. The bounded/cycle-safe *interpretation* of + * the assembled chain (declared / unowned / foreign / unknown) is core's + * `classifyOwnerChain` (`@intentius/chant/owner-chain`) — the issue's own + * division of labor: core owns the category, the lexicon supplies the chain. + */ + +import type { K8sClient, K8sObject } from "@intentius/chant-k8s-client"; +import { + classifyOwnerChain, + DEFAULT_MAX_OWNER_CHAIN_DEPTH, + type OwnerChainNode, + type OwnerChainVerdict, +} from "@intentius/chant/owner-chain"; + +interface RawOwnerRef { + apiVersion?: string; + kind?: string; + name?: string; + uid?: string; + controller?: boolean; +} + +function ownerRefs(obj: K8sObject): RawOwnerRef[] { + const refs = obj.metadata?.ownerReferences; + return Array.isArray(refs) ? (refs as RawOwnerRef[]) : []; +} + +/** + * The reference Kubernetes' own garbage collector treats as the controlling + * parent: the entry with `controller: true`, else the first. An object with + * several owner references (rare — usually a shared, non-controller owner + * alongside the controlling one) is walked through its controller, matching + * what actually recreates the object were it deleted. + */ +function controllingRef(obj: K8sObject): RawOwnerRef | undefined { + const refs = ownerRefs(obj); + return refs.find((r) => r.controller === true) ?? refs[0]; +} + +/** The client surface this module needs — a single object read, addressed by + * an owner reference's own coordinates. */ +export type OwnerChainReader = Pick; + +export interface ResolveOwnerChainOptions { + /** uid → declared chant entity name, from this observation's own resolved entities. */ + declaredByUid: ReadonlyMap; + /** Reads each intermediate owner. */ + reader: OwnerChainReader; + /** + * Namespace the starting object lives in. Owner references are same-namespace + * only — a namespaced object cannot be owned by an object in another + * namespace, the same rule Kubernetes' own garbage collector enforces —so + * every hop is read in this namespace. + */ + namespace: string | undefined; + maxDepth?: number; +} + +/** + * Walk `obj`'s owner-reference chain up to a declared entity, a foreign root, + * or a bound (#1077). Fetches at most `maxDepth + 1` objects (the starting + * object plus up to `maxDepth` ancestors) — the same bound `classifyOwnerChain` + * enforces when interpreting the result, so nothing is fetched that the + * interpretation would not have used anyway. + */ +export async function resolveK8sOwnerChain( + obj: K8sObject, + options: ResolveOwnerChainOptions, +): Promise { + const startUid = obj.metadata?.uid; + if (!startUid) return { root: "unknown" }; + + const maxDepth = options.maxDepth ?? DEFAULT_MAX_OWNER_CHAIN_DEPTH; + const nodes = new Map(); + const visited = new Set(); + + let uid: string | undefined = startUid; + let object: K8sObject | undefined = obj; + + for (let depth = 0; uid !== undefined && depth <= maxDepth; depth++) { + if (visited.has(uid)) break; // cycle — classifyOwnerChain reads it off `nodes` + visited.add(uid); + + const declaredEntity = options.declaredByUid.get(uid); + if (declaredEntity) { + nodes.set(uid, { declaredEntity }); + break; + } + if (!object) { + nodes.set(uid, { ownerUnreadable: true }); + break; + } + + const ref = controllingRef(object); + if (!ref?.uid || !ref.kind || !ref.apiVersion || !ref.name) { + nodes.set(uid, {}); // no further owner — a real, live root + break; + } + nodes.set(uid, { ownerId: ref.uid }); + + if (visited.has(ref.uid)) { + // About to cycle back to an already-visited node — let the loop's own + // check classify it next iteration rather than issuing a wasted read. + uid = ref.uid; + continue; + } + if (options.declaredByUid.has(ref.uid)) { + // Already known to be a declared entity from this observation's own + // resolved set — no need to read it, the next iteration resolves it + // from `declaredByUid` directly. + uid = ref.uid; + object = undefined; + continue; + } + + try { + object = await options.reader.readIfPresent({ + apiVersion: ref.apiVersion, + kind: ref.kind, + name: ref.name, + namespace: options.namespace, + }); + } catch { + object = undefined; + } + if (!object) nodes.set(ref.uid, { ownerUnreadable: true }); + uid = ref.uid; + } + + return classifyOwnerChain(startUid, nodes, maxDepth); +} diff --git a/lexicons/k8s/src/describe-resources.test.ts b/lexicons/k8s/src/describe-resources.test.ts index 9722ab791a..71893a4415 100644 --- a/lexicons/k8s/src/describe-resources.test.ts +++ b/lexicons/k8s/src/describe-resources.test.ts @@ -16,7 +16,7 @@ vi.mock("@intentius/chant/config", () => ({ })); const { describeResources } = await import("./describe-resources"); -const { fakeCluster, objectKey } = await import("./api/fake-cluster"); +const { fakeCluster, objectKey, ownedObject } = await import("./api/fake-cluster"); const { defaultK8sConnector } = await import("./api/connect"); const { fakeKubeconfig, statusBody } = await import("@intentius/chant-k8s-client/testing"); @@ -501,4 +501,227 @@ describe("k8s describeResources", () => { expect(result.unobserved?.web?.detail).toContain("npm i @intentius/chant-k8s-client"); expect(result.unobserved?.web?.type).toBe("K8s::Apps::Deployment"); }); + + // ── Runtime children: owner-reference chain classification (chant #1077) ── + + describe("runtime children (#1077)", () => { + function declaredDeployment() { + return makeEntities([ + { name: "web", entityType: "K8s::Apps::Deployment", props: { metadata: { name: "web", namespace: "prod" } } }, + ]); + } + + test("a Pod owned (via an undeclared ReplicaSet) by a declared Deployment reports ownerChain: declared", async () => { + const replicaSet = { + apiVersion: "apps/v1", + kind: "ReplicaSet", + metadata: { + name: "web-7d9f8c9c8", + namespace: "prod", + uid: "rs-uid", + ownerReferences: [{ apiVersion: "apps/v1", kind: "Deployment", name: "web", uid: "uid-1", controller: true }], + }, + }; + const runtimePod = { + apiVersion: "v1", + kind: "Pod", + metadata: { + name: "web-7d9f8c9c8-abcde", + namespace: "prod", + uid: "pod-uid", + ownerReferences: [{ apiVersion: "apps/v1", kind: "ReplicaSet", name: "web-7d9f8c9c8", uid: "rs-uid", controller: true }], + }, + status: { phase: "Running" }, + }; + const cluster = fakeCluster({ + objects: { + [objectKey("apps/v1", "Deployment", "web", "prod")]: web, + [objectKey("apps/v1", "ReplicaSet", "web-7d9f8c9c8", "prod")]: replicaSet, + [objectKey("v1", "Pod", "web-7d9f8c9c8-abcde", "prod")]: runtimePod, + }, + }); + + const result = await describeResources( + { environment: "prod", buildOutput: "", entityNames: ["web"], entities: declaredDeployment() }, + cluster.connector, + ); + + const child = result.resources["prod/web-7d9f8c9c8-abcde"]; + expect(child).toMatchObject({ + type: "K8s::Core::Pod", + physicalId: "pod-uid", + status: "Running", + ownerChain: { root: "declared", entity: "web" }, + }); + // Reads the ReplicaSet to walk past it — one extra request beyond the + // Deployment read and the Pod list. + expect(cluster.layer.paths()).toContain("/apis/apps/v1/namespaces/prod/replicasets/web-7d9f8c9c8"); + }); + + test("a genuinely unowned Pod in the same namespace reports ownerChain: unowned (still an orphan downstream)", async () => { + const standalonePod = { + apiVersion: "v1", + kind: "Pod", + metadata: { name: "standalone", namespace: "prod", uid: "standalone-uid" }, + status: { phase: "Running" }, + }; + const cluster = fakeCluster({ + objects: { + [objectKey("apps/v1", "Deployment", "web", "prod")]: web, + [objectKey("v1", "Pod", "standalone", "prod")]: standalonePod, + }, + }); + + const result = await describeResources( + { environment: "prod", buildOutput: "", entityNames: ["web"], entities: declaredDeployment() }, + cluster.connector, + ); + + expect(result.resources["prod/standalone"]).toMatchObject({ + type: "K8s::Core::Pod", + ownerChain: { root: "unowned" }, + }); + }); + + test("a Pod owned by something never declared reports ownerChain: foreign", async () => { + const otherRs = { + apiVersion: "apps/v1", + kind: "ReplicaSet", + metadata: { name: "other-rs", namespace: "prod", uid: "other-rs-uid" }, // no further owner + }; + const otherPod = { + apiVersion: "v1", + kind: "Pod", + metadata: { + name: "other-pod", + namespace: "prod", + uid: "other-pod-uid", + ownerReferences: [{ apiVersion: "apps/v1", kind: "ReplicaSet", name: "other-rs", uid: "other-rs-uid", controller: true }], + }, + }; + const cluster = fakeCluster({ + objects: { + [objectKey("apps/v1", "Deployment", "web", "prod")]: web, + [objectKey("apps/v1", "ReplicaSet", "other-rs", "prod")]: otherRs, + [objectKey("v1", "Pod", "other-pod", "prod")]: otherPod, + }, + }); + + const result = await describeResources( + { environment: "prod", buildOutput: "", entityNames: ["web"], entities: declaredDeployment() }, + cluster.connector, + ); + + expect(result.resources["prod/other-pod"]).toMatchObject({ ownerChain: { root: "foreign" } }); + }); + + test("--owned withholds an unrelated Pod, but keeps a runtime child of a declared (owned) entity", async () => { + // The declared Deployment must itself carry chant's marker for `--owned` + // to surface it at all — otherwise it is filtered before a Pod scan ever + // has a declared uid to compare against. + const ownedWeb = ownedObject("apps/v1", "Deployment", "web", "prod", { status: { readyReplicas: 3, replicas: 3 } }); + const standalonePod = { + apiVersion: "v1", + kind: "Pod", + metadata: { name: "standalone", namespace: "prod", uid: "standalone-uid" }, + }; + const runtimePod = { + apiVersion: "v1", + kind: "Pod", + metadata: { + name: "web-abc", + namespace: "prod", + uid: "pod-uid", + ownerReferences: [{ apiVersion: "apps/v1", kind: "Deployment", name: "web", uid: "uid-web", controller: true }], + }, + }; + const cluster = fakeCluster({ + objects: { + [objectKey("apps/v1", "Deployment", "web", "prod")]: ownedWeb, + [objectKey("v1", "Pod", "standalone", "prod")]: standalonePod, + [objectKey("v1", "Pod", "web-abc", "prod")]: runtimePod, + }, + }); + + const result = await describeResources( + { + environment: "prod", + buildOutput: "", + entityNames: ["web"], + entities: declaredDeployment(), + owned: true, + }, + cluster.connector, + ); + + expect(result.resources.web).toBeDefined(); // the marker let it through + expect(result.resources["prod/standalone"]).toBeUndefined(); + expect(result.resources["prod/web-abc"]).toMatchObject({ ownerChain: { root: "declared", entity: "web" } }); + }); + + test("a Pod that is itself declared is never duplicated as a runtime child", async () => { + const declaredPod = { + apiVersion: "v1", + kind: "Pod", + metadata: { name: "standalone-pod", namespace: "prod", uid: "uid-declared-pod" }, + status: { phase: "Running" }, + }; + const cluster = fakeCluster({ + objects: { + [objectKey("apps/v1", "Deployment", "web", "prod")]: web, + [objectKey("v1", "Pod", "standalone-pod", "prod")]: declaredPod, + }, + }); + + const result = await describeResources( + { + environment: "prod", + buildOutput: "", + entityNames: ["web", "standalonePod"], + entities: makeEntities([ + { name: "web", entityType: "K8s::Apps::Deployment", props: { metadata: { name: "web", namespace: "prod" } } }, + { name: "standalonePod", entityType: "K8s::Core::Pod", props: { metadata: { name: "standalone-pod", namespace: "prod" } } }, + ]), + }, + cluster.connector, + ); + + expect(result.resources.standalonePod).toBeDefined(); + expect(result.resources["prod/standalone-pod"]).toBeUndefined(); + 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 () => { + 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), + }); + + const result = await describeResources( + { environment: "prod", buildOutput: "", entityNames: ["web"], entities: declaredDeployment() }, + cluster.connector, + ); + + expect(result.resources.web).toMatchObject({ type: "K8s::Apps::Deployment", physicalId: "uid-1" }); + expect(Object.keys(result.resources)).toEqual(["web"]); + }); + + test("a lexicon-supported entity type with no namespaced entities resolved does no Pod scan at all", async () => { + const ns = { apiVersion: "v1", kind: "Namespace", metadata: { name: "mynamespace", uid: "uid-ns" }, status: { phase: "Active" } }; + const cluster = fakeCluster({ objects: { [objectKey("v1", "Namespace", "mynamespace")]: ns } }); + + const result = await describeResources( + { + environment: "prod", + buildOutput: "", + entityNames: ["ns"], + entities: makeEntities([{ name: "ns", entityType: "K8s::Core::Namespace", props: { metadata: { name: "mynamespace" } } }]), + }, + cluster.connector, + ); + + expect(Object.keys(result.resources)).toEqual(["ns"]); + expect(cluster.layer.paths().some((p) => p.endsWith("/pods"))).toBe(false); + }); + }); }); diff --git a/lexicons/k8s/src/describe-resources.ts b/lexicons/k8s/src/describe-resources.ts index dfcebeadb9..86262d491a 100644 --- a/lexicons/k8s/src/describe-resources.ts +++ b/lexicons/k8s/src/describe-resources.ts @@ -35,12 +35,27 @@ * NOT-OBSERVED with a reason. A declared `k8s.profiles..context` that * disagrees with the ambient one still refuses before a single resource is * touched, via the same `resolveClusterTarget` the GCP lexicon shares. + * + * ## Runtime children (chant #1077) + * + * A Pod a declared Deployment's controller created is live and undeclared — + * 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. */ import type { ObservationResult, ResourceMetadata, UnobservedEntity } from "@intentius/chant/lexicon"; import { observation, unobservedAll } from "@intentius/chant/observation"; import { hasOwnershipMarker, classifyOwnership, LABEL_OWNERSHIP_KEYS } from "@intentius/chant/ownership"; -import type { K8sObject } from "@intentius/chant-k8s-client"; +import type { K8sClient, K8sObject } from "@intentius/chant-k8s-client"; import { defaultK8sConnector, type K8sConnector } from "./api/connect"; import { classifyApiFailure, @@ -49,6 +64,7 @@ import { MISSING_CLIENT_DETAIL, } from "./api/classify"; import { operationFor } from "./api/operation-surface"; +import { resolveK8sOwnerChain } from "./api/owner-chain"; function pruneUndefined>(obj: T): Record { const out: Record = {}; @@ -207,5 +223,74 @@ export async function describeResources( } }); + await addRuntimeChildren(client, resources, options.owned); + return observation(resources, unobserved); } + +/** + * Scan Pods 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 Pod whose chain was worth reporting. + * + * Best-effort and additive: a namespace this scan cannot list (RBAC denial, + * a transient error) is simply skipped rather than failing the observation — + * Pods 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. + */ +async function addRuntimeChildren( + client: K8sClient, + resources: Record, + owned: boolean | undefined, +): Promise { + const declaredByUid = new Map(); + for (const [entityName, meta] of Object.entries(resources)) { + if (meta.physicalId) declaredByUid.set(meta.physicalId, entityName); + } + + const namespaces = new Set(); + for (const meta of Object.values(resources)) { + const namespace = (meta.attributes as { namespace?: string } | undefined)?.namespace; + if (namespace) namespaces.add(namespace); + } + if (namespaces.size === 0) return; + + await client.concurrently([...namespaces], async (namespace) => { + let pods: K8sObject[]; + try { + pods = await client.list({ apiVersion: "v1", kind: "Pod" }, { namespace }); + } catch { + return; // best-effort — see the function doc + } + + await client.concurrently(pods, async (pod) => { + const uid = pod.metadata?.uid; + const name = pod.metadata?.name; + if (!uid || !name || declaredByUid.has(uid)) return; // declared directly, or unaddressable + + const ownerChain = await resolveK8sOwnerChain(pod, { declaredByUid, reader: client, namespace }); + + // `--owned`: withhold a Pod 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(pod.metadata?.labels, LABEL_OWNERSHIP_KEYS); + if (owned && ownerChain.root !== "declared" && !marker) return; + + resources[`${namespace}/${name}`] = { + type: "K8s::Core::Pod", + physicalId: uid, + status: statusFromObject(pod), + lastUpdated: pod.metadata?.creationTimestamp, + ownership: classifyOwnership(pod.metadata?.labels, LABEL_OWNERSHIP_KEYS), + ownerChain, + attributes: pruneUndefined({ + namespace, + labels: pod.metadata?.labels, + resourceVersion: pod.metadata?.resourceVersion, + }), + }; + }); + }); +} diff --git a/packages/core/src/cli/handlers/lifecycle.ts b/packages/core/src/cli/handlers/lifecycle.ts index e97cf8b5e0..89add4a7eb 100644 --- a/packages/core/src/cli/handlers/lifecycle.ts +++ b/packages/core/src/cli/handlers/lifecycle.ts @@ -857,6 +857,7 @@ function renderLiveDiff(lexiconName: string, environment: string, diff: LiveDiff `${diff.missing.length} missing, ${diff.orphan.length} orphan, ` + `${diff.disappeared.length} disappeared, ${diff.newlyObserved.length} newly observed, ` + `${diff.driftedSinceSnapshot.length} drifted, ${diff.unchanged.length} unchanged` + + (diff.runtimeChildren.length > 0 ? `, ${diff.runtimeChildren.length} runtime` : "") + (diff.unobserved.length > 0 ? `, ${diff.unobserved.length} unobserved` : ""); console.log(`\n${formatBold(lexiconName)} — environment: ${environment}`); @@ -877,6 +878,10 @@ function renderLiveDiff(lexiconName: string, environment: string, diff: LiveDiff console.log(formatBold("\nORPHAN (in cloud, not declared):")); for (const name of diff.orphan) console.log(` - ${name}`); } + if (diff.runtimeChildren.length > 0) { + console.log(formatBold("\nRUNTIME (owned by a declared resource; not drift, not an orphan — #1077):")); + for (const r of diff.runtimeChildren) console.log(` - ${r.name} (${r.type}) — owned by ${r.owner}`); + } if (diff.disappeared.length > 0) { console.log(formatBold("\nDISAPPEARED (in last snapshot, gone now):")); for (const name of diff.disappeared) console.log(` - ${name}`); diff --git a/packages/core/src/graph-ir-live.test.ts b/packages/core/src/graph-ir-live.test.ts index ead6ef590b..e1ebf6b359 100644 --- a/packages/core/src/graph-ir-live.test.ts +++ b/packages/core/src/graph-ir-live.test.ts @@ -60,6 +60,23 @@ describe("buildLiveGraphIr", () => { expect(node.attrs).toEqual({}); }); + // #1077 — owner-reference chain classification + it("carries runtimeOwner only when the owner chain resolves to a declared entity", () => { + const ir = buildLiveGraphIr([ + { + lexicon: "k8s", + resources: { + "prod/web-abc": { type: "K8s::Core::Pod", status: "Running", ownerChain: { root: "declared", entity: "web" } }, + "prod/other": { type: "K8s::Core::Pod", status: "Running", ownerChain: { root: "foreign" } }, + "prod/plain": { type: "K8s::Core::Pod", status: "Running" }, + }, + }, + ]); + expect(ir.nodes.find((n) => n.id === "prod/web-abc")!.runtimeOwner).toBe("web"); + expect(ir.nodes.find((n) => n.id === "prod/other")!.runtimeOwner).toBeUndefined(); + expect(ir.nodes.find((n) => n.id === "prod/plain")!.runtimeOwner).toBeUndefined(); + }); + it("is deterministic for a fixed observation set", () => { expect(JSON.stringify(buildLiveGraphIr(observations))).toBe( JSON.stringify(buildLiveGraphIr(observations)), @@ -85,6 +102,18 @@ describe("overlayGraphs (#780 drift overlay)", () => { expect(ir.nodes.map((n) => n.id).sort()).toEqual(["planned-db", "rogue-sg", "web-vpc"]); expect(ir.edges).toHaveLength(1); }); + + // #1077 — a provisioned, undeclared node whose owner chain reaches a + // declared entity paints `runtime`, not `warn` — it is expected runtime, + // not a foreign resource needing attention. + it("classifies a runtime child via _status, distinct from foreign", () => { + const podNode = { id: "prod/web-abc", kind: "K8s::Core::Pod", lexicon: "k8s", attrs: {}, runtimeOwner: "web" }; + const liveWithChild: GraphIR = { nodes: [node("web-vpc"), node("rogue-sg"), podNode], edges: [], groups: {} }; + const ir = overlayGraphs(liveWithChild, declared); + const statusOf = (id: string) => (ir.nodes.find((n) => n.id === id)!.attrs as { _status?: string })._status; + expect(statusOf("prod/web-abc")).toBe("runtime"); + expect(statusOf("rogue-sg")).toBe("warn"); // still foreign — no runtimeOwner + }); }); describe("sourceOverlayGraphs (#821 source-anchored overlay)", () => { @@ -135,6 +164,17 @@ describe("sourceOverlayGraphs (#821 source-anchored overlay)", () => { expect(ir.groups.byLexicon).toEqual({ aws: ["planned-db", "web-vpc"], k8s: ["app-ingress"] }); }); + // #1077 — a live, undeclared node whose owner chain reaches a declared + // entity is appended `runtime`, not `warn`, even though it is just as + // "foreign" (undeclared) from the declared graph's point of view. + it("appends a runtime child as `runtime`, distinct from foreign", () => { + const podNode = { id: "prod/web-abc", kind: "K8s::Core::Pod", lexicon: "k8s", attrs: {}, runtimeOwner: "app-ingress" }; + const liveWithChild: GraphIR = { ...live, nodes: [...live.nodes, podNode] }; + const ir = sourceOverlayGraphs(declared, liveWithChild); + expect(statusOf(ir, "prod/web-abc")).toBe("runtime"); + expect(statusOf(ir, "rogue-sg")).toBe("warn"); // still foreign + }); + it("drops a live edge between two managed nodes — declared edges already cover it", () => { const liveDup: GraphIR = { ...live, edges: [{ from: "app-ingress", to: "web-vpc", kind: "ref", viaAttr: "live-label" }] }; const ir = sourceOverlayGraphs(declared, liveDup); diff --git a/packages/core/src/graph-ir.ts b/packages/core/src/graph-ir.ts index 0a6e3372bf..94fd158ed5 100644 --- a/packages/core/src/graph-ir.ts +++ b/packages/core/src/graph-ir.ts @@ -67,6 +67,15 @@ export interface IRNode { * `owned` = chant-managed. Absent for source-derived IR. */ ownership?: "owned" | "foreign"; + /** + * Live-only, undeclared nodes: the declared entity this node's + * owner-reference chain resolves to (#1077) — a Pod a declared Deployment's + * controller created, for instance. Presence of this field is what an + * overlay reads to paint the node `runtime` instead of `warn`/foreign; a + * node without it (including every declared, source-derived node) is + * unaffected. + */ + runtimeOwner?: string; } /** A directed dependency: `from` references an attribute of `to`. */ @@ -504,6 +513,11 @@ export function buildLiveGraphIr(observations: LiveObservation[]): GraphIR { // information for a painter, and the IR's `ownership` field means "a // verdict was reached" — so only owned/foreign land on the node. if (meta.ownership === "owned" || meta.ownership === "foreign") node.ownership = meta.ownership; + // Owner-reference chain (#1077): only a resolved `declared` root is + // carried onto the node — the same "a verdict was reached" rule as + // ownership above, since `unowned`/`foreign`/`unknown` all mean "no + // declared owner", which is simply the absence of this field. + if (meta.ownerChain?.root === "declared") node.runtimeOwner = meta.ownerChain.entity; nodes.push(node); (byLexicon[lexicon] ??= []).push(name); // A live lexicon maps to one deployable stack, same as the source IR. @@ -540,8 +554,9 @@ export function collectUnobserved(observations: LiveObservation[]): Record n.id)); const unobserved = opts?.unobserved ?? {}; - const nodes: IRNode[] = live.nodes.map((n) => tagStatus(n, declaredIds.has(n.id) ? "good" : "warn")); + const nodes: IRNode[] = live.nodes.map((n) => + tagStatus(n, declaredIds.has(n.id) ? "good" : n.runtimeOwner ? "runtime" : "warn"), + ); for (const n of declared.nodes) { if (liveIds.has(n.id)) continue; const u = unobserved[n.id]; @@ -597,8 +617,10 @@ export function overlayGraphs(live: GraphIR, declared: GraphIR, opts?: OverlayOp * the reason on `_unobserved`. A wrong-cluster or unsupported-kind read used * to paint the whole estate "pending", which is the diagram equivalent of * planning a create for something that already exists. - * **Foreign** resources (provisioned, not declared) are appended and tagged - * `warn`, together with any live-reconstructed edges that touch them — a declared + * **Foreign** resources (provisioned, not declared, no declared owner) are + * appended and tagged `warn`; a provisioned-but-undeclared resource whose + * owner chain reaches a declared entity (#1077) is tagged `runtime` instead — + * both carry any live-reconstructed edges that touch them, since a declared * edge cannot describe an undeclared resource. Declared groups/exports pass * through unchanged; nodes and edges are sorted for deterministic output. */ @@ -620,7 +642,10 @@ export function sourceOverlayGraphs(declared: GraphIR, live: GraphIR, opts?: Ove if (obs.ownership) merged.ownership = obs.ownership; return tagStatus(merged, "good"); }); - for (const n of live.nodes) if (foreignIds.has(n.id)) nodes.push(tagStatus(n, "warn")); // foreign + for (const n of live.nodes) { + if (!foreignIds.has(n.id)) continue; + nodes.push(tagStatus(n, n.runtimeOwner ? "runtime" : "warn")); // runtime child or foreign + } nodes.sort((a, b) => a.id.localeCompare(b.id)); // Declared edges are the canvas (the cross-substrate topology). Add only the diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 1ce36a48c8..83f95171d2 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -50,6 +50,7 @@ export * from "./import/generator"; export * from "./lexicon"; export * from "./observation"; export * from "./deep-observation"; +export * from "./owner-chain"; export * from "./lexicon-integrity"; export * from "./lexicon-manifest"; export * from "./lexicon-schema"; diff --git a/packages/core/src/lexicon.ts b/packages/core/src/lexicon.ts index f60329d9d6..7cd623481e 100644 --- a/packages/core/src/lexicon.ts +++ b/packages/core/src/lexicon.ts @@ -13,6 +13,7 @@ import type { RuleMeta } from "./audit/catalog"; import type { ReferenceCatalog } from "./graph-refs"; import type { DescribeResourcesResult } from "./observation"; import type { DeepNormalizationHooks, DeepObservationResult } from "./deep-observation"; +import type { OwnerChainVerdict } from "./owner-chain"; // Re-exported so lexicons can author a reference catalog (#778) from the same // `@intentius/chant/lexicon` entry they import the plugin contract from. @@ -555,6 +556,13 @@ export interface LexiconPlugin { * `ownership: "unknown"` on what it returns rather than degrading silently — * the change set never escalates `unknown` to a `delete`. * + * An undeclared entry this method returns may carry {@link + * ResourceMetadata.ownerChain} (#1077) — set it when the provider's own + * parent/child graph (Kubernetes `ownerReferences`) shows this object's + * chain reaching a declared entity, so the diff engine classifies it + * `runtime` instead of `orphan`. Optional; a lexicon that never sets it + * keeps every undeclared entry classified `orphan`, unchanged. + * * `entities` carries the chant-side entity declarations for this lexicon, * keyed by chant entity name (e.g. the export name from a `*.ts` file). * Implementations that need to map cloud-side names back to chant entity @@ -783,6 +791,19 @@ export interface ResourceMetadata { * a delete, and never escalates `unknown` to one. */ ownership?: "owned" | "foreign" | "unknown"; + /** + * Where this resource's owner-reference chain leads, for a live resource + * that is not itself declared (#1077). A lexicon that maintains an + * owner-reference graph (Kubernetes) sets this on an undeclared entry it + * returns; the diff engine reads `{ root: "declared" }` as `runtime` + * (a Pod a declared Deployment's controller created) rather than `orphan`. + * Distinct from {@link ownership}: that is chant's own managed-by marker, + * this is the provider's native parent/child graph — a runtime child + * usually carries no chant marker of its own at all. Absent means the + * lexicon supplies no chain, which is exactly today's behavior: every + * undeclared live resource stays `orphan`. + */ + ownerChain?: OwnerChainVerdict; } /** diff --git a/packages/core/src/lifecycle/change-set.test.ts b/packages/core/src/lifecycle/change-set.test.ts index 56d558e93e..d753a8c7d7 100644 --- a/packages/core/src/lifecycle/change-set.test.ts +++ b/packages/core/src/lifecycle/change-set.test.ts @@ -106,6 +106,77 @@ describe("buildChangeSet (#118)", () => { expect(cs.entries.filter((e) => e.action === "adopt").map((e) => e.name)).toEqual(["b", "c"]); }); + // ── Owner-reference chain classification (#1077) ────────────────────────── + + test("undeclared, owner chain reaches a declared entity → runtime, never delete or adopt", () => { + const cs = buildChangeSet("prod", { + declared: new Set(["web"]), + observedNow: { + web: meta({ type: "K8s::Apps::Deployment" }), + "prod/web-abc": meta({ type: "K8s::Core::Pod", ownerChain: { root: "declared", entity: "web" } }), + }, + observedThen: undefined, + }); + const e = cs.entries.find((x) => x.name === "prod/web-abc")!; + expect(e.action).toBe("runtime"); + expect(e.runtimeOwner).toBe("web"); + }); + + test("a runtime child that also carries chant's own ownership marker is still `runtime`, never `delete`", () => { + // Guards the ordering in buildChangeSet: runtimeOwner must be checked + // before the ownership marker, in case a runtime child ever inherits the + // marker (e.g. label propagation from its owner's pod template). + const cs = buildChangeSet("prod", { + declared: new Set(), + observedNow: { + "prod/web-abc": meta({ ownership: "owned", ownerChain: { root: "declared", entity: "web" } }), + }, + observedThen: undefined, + }); + const e = cs.entries.find((x) => x.name === "prod/web-abc")!; + expect(e.action).toBe("runtime"); + }); + + test("undeclared, unowned → orphan/adopt, not runtime", () => { + const cs = buildChangeSet("prod", { + declared: new Set(), + observedNow: { "prod/standalone": meta({ ownerChain: { root: "unowned" } }) }, + observedThen: undefined, + }); + const e = cs.entries.find((x) => x.name === "prod/standalone")!; + expect(e.action).toBe("adopt"); + expect(e.runtimeOwner).toBeUndefined(); + }); + + test("undeclared, foreign root → orphan/adopt, not runtime", () => { + const cs = buildChangeSet("prod", { + declared: new Set(), + observedNow: { "prod/other": meta({ ownerChain: { root: "foreign" } }) }, + observedThen: undefined, + }); + expect(cs.entries.find((x) => x.name === "prod/other")!.action).toBe("adopt"); + }); + + test("undeclared, unresolved chain (unreadable/cycle/depth) → conservative adopt, not runtime", () => { + const cs = buildChangeSet("prod", { + declared: new Set(), + observedNow: { "prod/mystery": meta({ ownerChain: { root: "unknown" } }) }, + observedThen: undefined, + }); + const e = cs.entries.find((x) => x.name === "prod/mystery")!; + expect(e.action).toBe("adopt"); + expect(e.runtimeOwner).toBeUndefined(); + }); + + test("a lexicon with no owner chain at all is unaffected — undeclared stays adopt/delete as before", () => { + const cs = buildChangeSet("prod", { + declared: new Set(), + observedNow: { orphan: meta({ ownership: "owned" }) }, + observedThen: undefined, + }); + expect(cs.entries.find((x) => x.name === "orphan")!.action).toBe("delete"); + }); + test("only in snapshot (gone now, undeclared) → noop", () => { const cs = buildChangeSet("prod", { declared: new Set(), @@ -148,6 +219,23 @@ describe("summarize / renderChangeSet", () => { expect(out).toContain("ADOPT:"); expect(out).toContain("orphan"); }); + + test("summarize and render surface the runtime action (#1077)", () => { + const withRuntime = buildChangeSet("prod", { + declared: new Set(["web"]), + observedNow: { + web: meta({ type: "K8s::Apps::Deployment" }), + "prod/web-abc": meta({ type: "K8s::Core::Pod", ownerChain: { root: "declared", entity: "web" } }), + }, + observedThen: undefined, + }); + expect(summarize(withRuntime).runtime).toBe(1); + expect(summarize(withRuntime).adopt).toBe(0); + const out = renderChangeSet(withRuntime); + expect(out).toContain("RUNTIME"); + expect(out).toContain("prod/web-abc"); + expect(out).toContain("owned by web"); + }); }); describe("gitlabMrReport (#329)", () => { @@ -169,6 +257,18 @@ describe("gitlabMrReport (#329)", () => { expect(gitlabMrReport(cs)).toEqual({ create: 1, update: 1, delete: 1 }); }); + test("a runtime child (#1077) is excluded from the widget — never counted as a change", () => { + const cs = buildChangeSet("prod", { + declared: new Set(["web"]), + observedNow: { + web: meta({ type: "K8s::Apps::Deployment" }), + "prod/web-abc": meta({ type: "K8s::Core::Pod", ownerChain: { root: "declared", entity: "web" } }), + }, + observedThen: undefined, + }); + expect(gitlabMrReport(cs)).toEqual({ create: 0, update: 0, delete: 0 }); + }); + test("empty plan reports all zeros", () => { const cs = buildChangeSet("prod", { declared: new Set(), diff --git a/packages/core/src/lifecycle/change-set.ts b/packages/core/src/lifecycle/change-set.ts index 593900a6bb..f1763f507d 100644 --- a/packages/core/src/lifecycle/change-set.ts +++ b/packages/core/src/lifecycle/change-set.ts @@ -3,8 +3,8 @@ * * `chant lifecycle diff --live` computes a three-way comparison — declared now / * last snapshot / live now — and prints it. `buildChangeSet` promotes that - * same signal into a classified create/update/delete/adopt/noop set that other - * tooling (reconcile, apply) can act on. + * same signal into a classified create/update/delete/adopt/runtime/noop set + * that other tooling (reconcile, apply) can act on. * * Strictly read-only and pure: no I/O, no mutation. The classification reads * ownership from the live marker only (populated downstream); until ownership @@ -25,12 +25,17 @@ import { unobservedReasonText, type UnobservedReason } from "../observation"; * snapshot. * - `adopt` — live but undeclared, ownership not established → a candidate to * pull back into source, never an auto-delete. + * - `runtime` — live but undeclared, and its owner-reference chain reaches a + * declared entity (#1077): a Pod a declared Deployment's controller + * created, for instance. Never a delete, never an adopt candidate — it is + * not drift, just the runtime doing its job. `runtimeOwner` names the + * declared entity it belongs to. * - `noop` — declared and live with no drift, or already reconciled. * - `unobserved` — declared, and the lexicon could not look (#1089). Not a * proposal at all: it is the plan admitting a hole. Never a create, never a * delete. Read `unobservedReason` for which hole. */ -export type ChangeAction = "create" | "update" | "delete" | "adopt" | "noop" | "unobserved"; +export type ChangeAction = "create" | "update" | "delete" | "adopt" | "runtime" | "noop" | "unobserved"; /** * Who answers "is this resource chant's?". `unknown` until a live ownership @@ -69,6 +74,8 @@ export interface ChangeSetEntry { unobservedReason?: UnobservedReason; /** Human-readable backing for `unobservedReason` (the failing command, the missing binding). */ unobservedDetail?: string; + /** The declared entity this resource's owner chain resolves to, for `action: "runtime"` (#1077). */ + runtimeOwner?: string; } export interface ChangeSet { @@ -121,6 +128,15 @@ export function buildChangeSet(env: string, input: DiffLiveInput): ChangeSet { // record chant has to host. const ownership: Ownership = observedNow[name]?.ownership ?? "unknown"; + // Owner-reference chain (#1077), same live-only provenance as ownership + // above. Only a `declared` root changes the classification; `unknown` is + // deliberately not escalated (#1168's tri-state precedent — an + // unconfirmed chain never earns the more confident verdict). + const runtimeOwner = + !isDeclared && observedNow[name]?.ownerChain?.root === "declared" + ? observedNow[name]!.ownerChain!.entity + : undefined; + let action: ChangeAction; let deltas: AttributeChange[] | undefined; @@ -140,6 +156,13 @@ export function buildChangeSet(env: string, input: DiffLiveInput): ChangeSet { } else { action = "noop"; } + } else if (live && runtimeOwner) { + // Live, undeclared, and its owner chain reaches a declared entity + // (#1077) — expected runtime, never a delete/adopt candidate, checked + // ahead of the ownership marker below: even a runtime child that + // happens to carry chant's own marker (label propagation from its + // owner's template) must never be proposed for deletion. + action = "runtime"; } else if (live) { // Live but undeclared. Only a chant-owned orphan is a safe delete; a // foreign or unknown orphan can be adopted but never auto-deleted. @@ -162,6 +185,7 @@ export function buildChangeSet(env: string, input: DiffLiveInput): ChangeSet { ...(unobservedEntry.detail ? { unobservedDetail: unobservedEntry.detail } : {}), } : {}), + ...(runtimeOwner ? { runtimeOwner } : {}), }); } @@ -169,7 +193,7 @@ export function buildChangeSet(env: string, input: DiffLiveInput): ChangeSet { return { env, entries }; } -const ACTION_ORDER: ChangeAction[] = ["create", "update", "delete", "adopt", "noop", "unobserved"]; +const ACTION_ORDER: ChangeAction[] = ["create", "update", "delete", "adopt", "runtime", "noop", "unobserved"]; /** Count entries per action. */ export function summarize(cs: ChangeSet): Record { @@ -178,6 +202,7 @@ export function summarize(cs: ChangeSet): Record { update: 0, delete: 0, adopt: 0, + runtime: 0, noop: 0, unobserved: 0, }; @@ -191,10 +216,11 @@ export function summarize(cs: ChangeSet): Record { * GitLab renders an `artifacts:reports:terraform` artifact in the merge-request * UI as "N to add, M to change, K to delete". The format is generic — any tool * that emits this JSON gets the widget — and the chant plan maps onto it - * directly. Only the mutating actions count: `adopt`, `noop` and `unobserved` - * are excluded, since the widget has no column for "live but undeclared", "no - * change", or "could not look" (#1089). The widget is therefore a floor, not a - * complete plan: read the full change set when entities are unobserved. + * directly. Only the mutating actions count: `adopt`, `runtime`, `noop` and + * `unobserved` are excluded, since the widget has no column for "live but + * undeclared", "expected runtime child" (#1077), "no change", or "could not + * look" (#1089). The widget is therefore a floor, not a complete plan: read + * the full change set when entities are unobserved or classified runtime. * * The widget label reads "Terraform" regardless of producer; that is GitLab's * fixed string, not a claim chant makes. @@ -223,14 +249,17 @@ export function renderChangeSet(cs: ChangeSet): string { lines.push( action === "unobserved" ? "\nUNOBSERVED (declared; chant could not read live state — no action proposed):" - : `\n${action.toUpperCase()}:`, + : action === "runtime" + ? "\nRUNTIME (owned by a declared resource; not drift, never a delete/adopt candidate):" + : `\n${action.toUpperCase()}:`, ); for (const e of group) { const own = e.ownership === "unknown" ? "" : ` [${e.ownership}]`; const why = e.unobservedReason ? ` — ${unobservedReasonText(e.unobservedReason)}${e.unobservedDetail ? `: ${e.unobservedDetail}` : ""}` : ""; - lines.push(` ${e.name}${e.type ? ` (${e.type})` : ""}${own}${why}`); + const owner = e.runtimeOwner ? ` — owned by ${e.runtimeOwner}` : ""; + lines.push(` ${e.name}${e.type ? ` (${e.type})` : ""}${own}${why}${owner}`); for (const d of e.deltas ?? []) { lines.push(` ${d.path}: ${fmt(d.oldValue)} → ${fmt(d.newValue)}`); } diff --git a/packages/core/src/lifecycle/live-diff.test.ts b/packages/core/src/lifecycle/live-diff.test.ts index 618d7c2b1b..cda1a96af6 100644 --- a/packages/core/src/lifecycle/live-diff.test.ts +++ b/packages/core/src/lifecycle/live-diff.test.ts @@ -19,6 +19,7 @@ describe("diffLive", () => { expect(result).toEqual({ missing: [], orphan: [], + runtimeChildren: [], disappeared: [], newlyObserved: [], driftedSinceSnapshot: [], @@ -114,6 +115,93 @@ describe("diffLive", () => { expect(result.unchanged).toEqual(["b"]); }); + // ── Owner-reference chain classification (#1077) ────────────────────────── + + describe("runtime children vs orphans", () => { + test("undeclared, chain reaches a declared entity → runtimeChildren, never orphan", () => { + const result = diffLive({ + declared: new Set(["web"]), + observedNow: { + web: meta({ type: "K8s::Apps::Deployment" }), + "prod/web-abc123": meta({ type: "K8s::Core::Pod", ownerChain: { root: "declared", entity: "web" } }), + }, + observedThen: undefined, + }); + expect(result.orphan).toEqual([]); + expect(result.runtimeChildren).toEqual([ + { name: "prod/web-abc123", type: "K8s::Core::Pod", owner: "web" }, + ]); + }); + + test("undeclared, no owner reference at all → orphan", () => { + const result = diffLive({ + declared: new Set(), + observedNow: { "prod/standalone": meta({ ownerChain: { root: "unowned" } }) }, + observedThen: undefined, + }); + expect(result.orphan).toEqual(["prod/standalone"]); + expect(result.runtimeChildren).toEqual([]); + }); + + test("undeclared, chain resolves to a foreign (non-declared) root → orphan", () => { + const result = diffLive({ + declared: new Set(), + observedNow: { "prod/other-app-pod": meta({ ownerChain: { root: "foreign" } }) }, + observedThen: undefined, + }); + expect(result.orphan).toEqual(["prod/other-app-pod"]); + expect(result.runtimeChildren).toEqual([]); + }); + + test("undeclared, chain could not be resolved (unreadable owner/cycle/depth) → conservative orphan, not runtime", () => { + const result = diffLive({ + declared: new Set(), + observedNow: { "prod/mystery-pod": meta({ ownerChain: { root: "unknown" } }) }, + observedThen: undefined, + }); + expect(result.orphan).toEqual(["prod/mystery-pod"]); + expect(result.runtimeChildren).toEqual([]); + }); + + test("a lexicon that never sets ownerChain is unaffected — undeclared stays orphan", () => { + const result = diffLive({ + declared: new Set(), + observedNow: { legacy: meta() }, // no ownerChain at all + observedThen: undefined, + }); + expect(result.orphan).toEqual(["legacy"]); + expect(result.runtimeChildren).toEqual([]); + }); + + test("a runtime child rolling to a new name between snapshots is not `disappeared`", () => { + const result = diffLive({ + declared: new Set(["web"]), + observedNow: { + web: meta({ type: "K8s::Apps::Deployment" }), + "prod/web-newname": meta({ type: "K8s::Core::Pod", ownerChain: { root: "declared", entity: "web" } }), + }, + observedThen: { "prod/web-oldname": meta({ type: "K8s::Core::Pod", ownerChain: { root: "declared", entity: "web" } }) }, + }); + expect(result.disappeared).toEqual([]); + expect(result.runtimeChildren).toEqual([ + { name: "prod/web-newname", type: "K8s::Core::Pod", owner: "web" }, + ]); + }); + + test("a runtime child's own status change between snapshots is not driftedSinceSnapshot", () => { + const podThen = meta({ type: "K8s::Core::Pod", status: "PROGRESSING", ownerChain: { root: "declared", entity: "web" } }); + const podNow = meta({ type: "K8s::Core::Pod", status: "READY", ownerChain: { root: "declared", entity: "web" } }); + const result = diffLive({ + declared: new Set(["web"]), + observedNow: { web: meta({ type: "K8s::Apps::Deployment" }), "prod/web-stable-0": podNow }, + observedThen: { "prod/web-stable-0": podThen }, + }); + expect(result.driftedSinceSnapshot).toEqual([]); + expect(result.unchanged).not.toContain("prod/web-stable-0"); + expect(result.runtimeChildren.map((r) => r.name)).toEqual(["prod/web-stable-0"]); + }); + }); + // ── The observation tri-state (#1089) ───────────────────────────────────── test("declared and not observed → unobserved, not missing", () => { diff --git a/packages/core/src/lifecycle/live-diff.ts b/packages/core/src/lifecycle/live-diff.ts index ab186a9ee7..cf50f51db7 100644 --- a/packages/core/src/lifecycle/live-diff.ts +++ b/packages/core/src/lifecycle/live-diff.ts @@ -36,6 +36,19 @@ export interface UnobservedResource { detail?: string; } +/** + * A live, undeclared resource whose owner-reference chain reaches a declared + * entity (#1077) — a Pod a declared Deployment's controller created, for + * instance. Reported separately from `orphan`: it is expected runtime, not a + * delete/adopt candidate, and is never counted as drift. + */ +export interface RuntimeChildResource { + name: string; + type: string; + /** The declared chant entity this resource's owner chain resolves to. */ + owner: string; +} + export interface LiveDiffResult { /** * Declared in current build, and the provider reported it absent. Entities @@ -43,8 +56,20 @@ export interface LiveDiffResult { * (#1089), so "missing" keeps meaning "confirmed not there". */ missing: string[]; - /** Observed in cloud right now, but not declared. */ + /** + * Observed in cloud right now, not declared, and either carries no owner + * chain, or the chain does not reach a declared entity (unowned, foreign, + * or unresolvable — #1077 never escalates an incomplete chain read to + * `runtimeChildren`). A resource whose chain *does* reach a declared entity + * is in `runtimeChildren` instead. + */ orphan: string[]; + /** + * Observed in cloud right now, not declared, whose owner-reference chain + * reaches a declared entity (#1077) — expected runtime, not drift. Never a + * delete/adopt candidate; excluded from `orphan` and from drift counts. + */ + runtimeChildren: RuntimeChildResource[]; /** Was in last snapshot but isn't observed now. */ disappeared: string[]; /** Observed now and declared, but not in the previous snapshot. */ @@ -169,6 +194,7 @@ export function diffLive(input: DiffLiveInput): LiveDiffResult { const missing: string[] = []; const orphan: string[] = []; + const runtimeChildren: RuntimeChildResource[] = []; const disappeared: string[] = []; const newlyObserved: string[] = []; const driftedSinceSnapshot: ResourceDrift[] = []; @@ -194,23 +220,43 @@ export function diffLive(input: DiffLiveInput): LiveDiffResult { } } - // In cloud right now but not declared → orphan + // In cloud right now but not declared → orphan, unless its owner-reference + // chain reaches a declared entity (#1077), in which case it is expected + // runtime rather than drift. An `unknown` chain (unreadable hop, cycle, or + // depth bound) is deliberately NOT escalated to runtime — it stays orphan, + // same as `unowned`/`foreign` — composing with #1168's tri-state precedent: + // an incomplete read never earns the more confident classification. + const runtimeChildNames = new Set(); for (const name of observedNowNames) { - if (!declared.has(name)) { + if (declared.has(name)) continue; + const chain = observedNow[name]?.ownerChain; + if (chain?.root === "declared") { + runtimeChildNames.add(name); + runtimeChildren.push({ name, type: observedNow[name].type, owner: chain.entity }); + } else { orphan.push(name); } } // In previous snapshot but not observed now → disappeared. An entity nobody - // could look at has not disappeared; it is unobserved. + // could look at has not disappeared; it is unobserved. A resource the + // *previous* snapshot recorded as a runtime child (#1077) rolling to a new + // name (a Pod replaced by its controller) is not disappearance either — it + // is the same expected churn `runtimeChildren` excludes above, and counting + // it here would recreate the drift noise this module exists to remove. for (const name of observedThenNames) { - if (!observedNowNames.has(name) && !unobservedNames.has(name)) { - disappeared.push(name); - } + if (observedNowNames.has(name) || unobservedNames.has(name)) continue; + if (!declared.has(name) && observedThenMap[name]?.ownerChain?.root === "declared") continue; + disappeared.push(name); } - // Observed now: classify drift relative to previous snapshot + // Observed now: classify drift relative to previous snapshot. Runtime + // children (#1077) are excluded entirely — a controller-owned object's + // transient status is not drift chant should surface, and a snapshot that + // happened to record the same name (e.g. a StatefulSet's stable pod + // identity) must not turn its ordinary churn into `driftedSinceSnapshot`. for (const name of observedNowNames) { + if (runtimeChildNames.has(name)) continue; const now = observedNow[name]; const then = observedThenMap[name]; if (!then) { @@ -235,6 +281,7 @@ export function diffLive(input: DiffLiveInput): LiveDiffResult { return { missing: missing.sort(), orphan: orphan.sort(), + runtimeChildren: runtimeChildren.sort((a, b) => a.name.localeCompare(b.name)), disappeared: disappeared.sort(), newlyObserved: newlyObserved.sort(), driftedSinceSnapshot: driftedSinceSnapshot.sort((a, b) => a.name.localeCompare(b.name)), diff --git a/packages/core/src/owner-chain.test.ts b/packages/core/src/owner-chain.test.ts new file mode 100644 index 0000000000..41aeba7723 --- /dev/null +++ b/packages/core/src/owner-chain.test.ts @@ -0,0 +1,97 @@ +import { describe, test, expect } from "vitest"; +import { classifyOwnerChain, DEFAULT_MAX_OWNER_CHAIN_DEPTH, type OwnerChainNode } from "./owner-chain"; + +describe("classifyOwnerChain (#1077)", () => { + test("owned chain reaching a declared entity → declared", () => { + // pod -> replicaSet -> deployment (declared) + const nodes = new Map([ + ["pod-uid", { ownerId: "rs-uid" }], + ["rs-uid", { ownerId: "deploy-uid" }], + ["deploy-uid", { declaredEntity: "web" }], + ]); + expect(classifyOwnerChain("pod-uid", nodes)).toEqual({ root: "declared", entity: "web" }); + }); + + test("a node that is itself declared resolves immediately", () => { + const nodes = new Map([["deploy-uid", { declaredEntity: "web" }]]); + expect(classifyOwnerChain("deploy-uid", nodes)).toEqual({ root: "declared", entity: "web" }); + }); + + test("no owner reference at all → unowned", () => { + const nodes = new Map([["pod-uid", {}]]); + expect(classifyOwnerChain("pod-uid", nodes)).toEqual({ root: "unowned" }); + }); + + test("chain fully resolves to a live, undeclared root → foreign", () => { + // pod -> replicaSet -> deployment, but the deployment is not declared + const nodes = new Map([ + ["pod-uid", { ownerId: "rs-uid" }], + ["rs-uid", { ownerId: "deploy-uid" }], + ["deploy-uid", {}], + ]); + expect(classifyOwnerChain("pod-uid", nodes)).toEqual({ root: "foreign" }); + }); + + test("the starting node itself could not be read → unknown", () => { + const nodes = new Map([["pod-uid", { ownerUnreadable: true }]]); + expect(classifyOwnerChain("pod-uid", nodes)).toEqual({ root: "unknown" }); + }); + + test("an intermediate owner could not be read → unknown, conservative (never foreign, never declared)", () => { + const nodes = new Map([ + ["pod-uid", { ownerId: "rs-uid" }], + ["rs-uid", { ownerUnreadable: true }], + ]); + expect(classifyOwnerChain("pod-uid", nodes)).toEqual({ root: "unknown" }); + }); + + test("an owner reference naming a node never resolved into the map → unknown", () => { + const nodes = new Map([["pod-uid", { ownerId: "rs-uid" }]]); + expect(classifyOwnerChain("pod-uid", nodes)).toEqual({ root: "unknown" }); + }); + + test("the starting id itself is not in the map → unknown", () => { + expect(classifyOwnerChain("nope", new Map())).toEqual({ root: "unknown" }); + }); + + test("a cycle is detected and classified unknown, not an infinite loop", () => { + const nodes = new Map([ + ["a", { ownerId: "b" }], + ["b", { ownerId: "a" }], + ]); + expect(classifyOwnerChain("a", nodes)).toEqual({ root: "unknown" }); + }); + + test("a self-referencing node is a cycle of one", () => { + const nodes = new Map([["a", { ownerId: "a" }]]); + expect(classifyOwnerChain("a", nodes)).toEqual({ root: "unknown" }); + }); + + test("exceeding the depth bound is conservative unknown, not foreign", () => { + // A straight-line chain one hop longer than the default bound, never + // reaching a declared entity or a definite foreign root within it. + const nodes = new Map(); + const depth = DEFAULT_MAX_OWNER_CHAIN_DEPTH + 5; + for (let i = 0; i < depth; i++) nodes.set(`n${i}`, { ownerId: `n${i + 1}` }); + nodes.set(`n${depth}`, {}); // the true, foreign root — but out of bounds + expect(classifyOwnerChain("n0", nodes)).toEqual({ root: "unknown" }); + }); + + test("a chain exactly at the depth bound still resolves to declared", () => { + const nodes = new Map(); + const depth = DEFAULT_MAX_OWNER_CHAIN_DEPTH; + for (let i = 0; i < depth; i++) nodes.set(`n${i}`, { ownerId: `n${i + 1}` }); + nodes.set(`n${depth}`, { declaredEntity: "root-entity" }); + expect(classifyOwnerChain("n0", nodes)).toEqual({ root: "declared", entity: "root-entity" }); + }); + + test("a custom maxDepth is honored", () => { + const nodes = new Map([ + ["a", { ownerId: "b" }], + ["b", { ownerId: "c" }], + ["c", { declaredEntity: "deep" }], + ]); + expect(classifyOwnerChain("a", nodes, 1)).toEqual({ root: "unknown" }); + expect(classifyOwnerChain("a", nodes, 2)).toEqual({ root: "declared", entity: "deep" }); + }); +}); diff --git a/packages/core/src/owner-chain.ts b/packages/core/src/owner-chain.ts new file mode 100644 index 0000000000..22de7e944b --- /dev/null +++ b/packages/core/src/owner-chain.ts @@ -0,0 +1,128 @@ +/** + * Owner-chain classification (chant #1077). + * + * `describeResources()` already lets a lexicon report a live object it never + * asked about by name — that is how `orphan` has always worked (a resource + * present in `observedNow` that is not in `declared`). Every existing consumer + * treats every such object the same way: undeclared, so a delete/adopt + * candidate. + * + * On Kubernetes that conflates two different things. A console-added SNS + * subscription (the AWS case #1014/#1015 was built for) really is out-of-band + * drift. A Pod a declared Deployment's controller created is not drift at + * all — it is the runtime doing its job, and it will be recreated the moment + * it is deleted. `ownerReferences` is what tells them apart: the Pod's chain + * of owners terminates at the Deployment, which is declared. + * + * This module owns the *category* — the four possible answers to "where does + * this object's owner chain lead" — and the pure algorithm that walks a chain + * to one of them. A lexicon supplies the chain (reading `ownerReferences`, + * possibly across several API reads to walk past an intermediate object chant + * never declared, e.g. a ReplicaSet between a Pod and its Deployment); this + * module supplies the bounded, cycle-safe interpretation, so that logic is + * written and tested once rather than once per lexicon. + */ + +/** + * Where a live, undeclared resource's owner-reference chain leads. + * + * - `declared` — the chain reaches an entity chant's own build declared. This + * is the whole point of #1077: the diff engine reads this as `runtime`, not + * `orphan`, and never proposes deleting it. + * - `unowned` — the resource carries no owner reference at all. A genuinely + * standalone live object; classifies as `orphan`, unchanged from before this + * module existed. + * - `foreign` — the chain fully resolves (every hop was readable, no cycle, no + * depth bound hit) but terminates at a live root that is not declared. + * Still `orphan` — it belongs to something real, just not to this build. + * - `unknown` — some hop could not be resolved: an unreadable owner, a cycle, + * or the depth bound. Composes with #1168's tri-state precedent: an owner + * chain chant could not fully verify is not a confirmed anything, so it is + * never escalated to `declared` and stays routed as `orphan` today, exactly + * as `foreign`/`unowned` are — never treated as a safer-than-warranted + * `runtime` classification just because the read was incomplete. + */ +export type OwnerChainVerdict = + | { readonly root: "declared"; readonly entity: string } + | { readonly root: "unowned" } + | { readonly root: "foreign" } + | { readonly root: "unknown" }; + +/** + * One node in the owner graph a lexicon assembles for {@link classifyOwnerChain}. + * Keyed externally (in the `nodes` map passed to the walk) by whatever stable + * identity the lexicon's provider uses — a Kubernetes UID, for instance. + */ +export interface OwnerChainNode { + /** + * This node's immediate owner, by its key in the same `nodes` map. Omit + * (`undefined`) when the object carries no owner reference at all — that is + * how a chain's *starting* node reports `unowned` rather than `unknown`. + */ + ownerId?: string; + /** + * True when this node's own owner could not be determined — the read + * failed, was denied, or the object simply could not be fetched. Distinct + * from having no owner: this says "unknown", not "none". + */ + ownerUnreadable?: boolean; + /** + * The declared chant entity name, when this node corresponds to one. A node + * with this set ends the walk immediately with `{ root: "declared" }` — + * whatever `ownerId`/`ownerUnreadable` it might also carry is irrelevant, + * since the chain already reached what it was looking for. + */ + declaredEntity?: string; +} + +/** Default bound on how many owner hops {@link classifyOwnerChain} will walk + * before giving up conservatively. Kubernetes' own garbage collector does not + * bound this at all, but a live read has to — a bound this generous is well + * past any real ownership depth (Pod → ReplicaSet → Deployment is 2 hops) and + * exists only to turn a corrupt or adversarial chain into `unknown` rather + * than an infinite walk. */ +export const DEFAULT_MAX_OWNER_CHAIN_DEPTH = 12; + +/** + * Walk the owner chain starting at `startId` through `nodes`, bounded and + * cycle-safe. Pure — the caller has already done whatever I/O was needed to + * populate `nodes`; this function only interprets the graph it was given. + * + * `nodes` need not contain every ancestor: a node the caller never resolved + * (because it gave up, hit the caller's own fetch bound, or the read failed) + * is simply absent from the map, and a reference to an absent node classifies + * as `unknown` — the conservative answer, same as an explicit + * `ownerUnreadable`. + */ +export function classifyOwnerChain( + startId: string, + nodes: ReadonlyMap, + maxDepth: number = DEFAULT_MAX_OWNER_CHAIN_DEPTH, +): OwnerChainVerdict { + const start = nodes.get(startId); + if (!start) return { root: "unknown" }; + if (start.declaredEntity) return { root: "declared", entity: start.declaredEntity }; + if (start.ownerUnreadable) return { root: "unknown" }; + if (start.ownerId === undefined) return { root: "unowned" }; + + const visited = new Set([startId]); + let currentId = start.ownerId; + + for (let depth = 0; depth < maxDepth; depth++) { + if (visited.has(currentId)) return { root: "unknown" }; // cycle + visited.add(currentId); + + const node = nodes.get(currentId); + if (!node) return { root: "unknown" }; // referenced but never resolved + if (node.declaredEntity) return { root: "declared", entity: node.declaredEntity }; + if (node.ownerUnreadable) return { root: "unknown" }; + if (node.ownerId === undefined) return { root: "foreign" }; // a real, live, undeclared root + + currentId = node.ownerId; + } + + // The bound was hit without resolving to a declared entity or a definite + // root. Conservative: not a confirmed `foreign` either, since one more hop + // might have reached a declared entity — see the type doc on `unknown`. + return { root: "unknown" }; +}