From d35d645310ee108b0dea5b9b942703f33e73507b Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Wed, 5 Aug 2026 00:15:52 -0600 Subject: [PATCH] fix(k8s): a cross-resource reference resolves to metadata.name, not the declarable id `claimName: pgClaim.name` emitted `claimName: pgClaim`. The manifest named a resource that does not exist, applied cleanly, and failed on the cluster -- which is the failure this system exists to remove. The visitor returned the logical name for every attribute, and both of its branches were identical: attrRef: (name, attr) => { // For K8s, attribute references typically resolve to metadata.name if (attr === "name") return name; return name; }, The lexicon's own plugin comment already said what this should do -- "Cross- resource references are handled by the AttrRef system in the serializer (resolves to metadata.name)" -- so this brings the code to the documentation rather than the other way round. Kubernetes YAML has no deploy-time reference mechanism. There is no !Ref and no Fn::GetAtt, so whatever a reference means has to be resolved before serialization or it means nothing at all. .name the target's metadata.name, falling back to the SAME kebab-case derivation the manifest builder uses when the target declares none. Extracted to derivedName() so a reference and the thing it references cannot drift apart. .namespace the declared namespace, or a refusal naming what to set. Which namespace a manifest lands in is otherwise decided at apply time. .uid refused. A UID is assigned by the API server at admission, so no build-time value exists and any string emitted here would be a fabrication. anything refused, saying k8s can express neither. Every refusal is an error with the fix in it, rather than a plausible string. Verified end to end against INTENTIUS/fountain-ops, which had every cross-resource reference written as a repeated literal precisely because this did not work. Swapping one literal for a reference: YAML byte-identical to the literal version graph {"from":"pgDeployment","to":"pgClaim","kind":"ref","viaAttr":"spec"} That pairing is the whole point: the manifest is unchanged and the graph gains the relationship, so a project can express what references what without touching what it deploys. A k8s estate currently renders as one flat row of unrelated nodes for this reason (fountain-ops#84, behold#131). 10668 tests pass; 6 new cover both resolutions and all three refusals. Closes #1493 Co-Authored-By: Claude Opus 5 (1M context) Claude-Session: https://claude.ai/code/session_012n8PKN49z8c6jZVA9QYwvk --- lexicons/k8s/src/serializer.test.ts | 102 ++++++++++++++++++++++++++++ lexicons/k8s/src/serializer.ts | 79 +++++++++++++++++++-- 2 files changed, 174 insertions(+), 7 deletions(-) diff --git a/lexicons/k8s/src/serializer.test.ts b/lexicons/k8s/src/serializer.test.ts index 82a9eebf6b..03f9f8dc2d 100644 --- a/lexicons/k8s/src/serializer.test.ts +++ b/lexicons/k8s/src/serializer.test.ts @@ -510,3 +510,105 @@ describe("k8sSerializer", () => { expect(result).not.toMatch(/^spec:\s*\n\s+rules:/m); }); }); + +// ── Cross-resource references (#1493) ──────────────────────────────── +// +// Kubernetes YAML has no deploy-time reference mechanism, so a reference has +// to be resolved before serialization or it means nothing. These used to +// serialize to the *logical* name, so a Deployment referencing its PVC emitted +// `claimName: pgClaim` and named a resource that does not exist — it applied +// cleanly and failed on the cluster. + +function mockAttrRef(attribute: string, logicalName: string): any { + // Shape isAttrRefLike() checks for: parent object, string attribute, and + // _setLogicalName. Without the last one the walker treats it as a plain + // object and the test silently asserts nothing. + return { + attribute, + parent: { deref: () => undefined }, + _setLogicalName: () => {}, + getLogicalName: () => logicalName, + }; +} + +describe("cross-resource references resolve at build time (#1493)", () => { + test(".name resolves to the referenced resource's metadata.name", () => { + const claim = mockResource("K8s::Core::PersistentVolumeClaim", { + metadata: { name: "fountain-postgres", namespace: "fountain" }, + spec: { accessModes: ["ReadWriteOnce"] }, + }); + const dep = mockResource("K8s::Apps::Deployment", { + metadata: { name: "fountain-postgres", namespace: "fountain" }, + spec: { + template: { + spec: { + volumes: [ + { name: "data", persistentVolumeClaim: { claimName: mockAttrRef("name", "pgClaim") } }, + ], + }, + }, + }, + }); + const yaml = k8sSerializer.serialize(new Map([["pgClaim", claim], ["pgDeployment", dep]])); + expect(yaml).toContain("claimName: fountain-postgres"); + expect(yaml).not.toContain("claimName: pgClaim"); + }); + + // A resource that declares no name gets one derived from its logical name. + // A reference to it has to derive the SAME one or the two silently disagree. + test(".name matches the derived name when the target declares none", () => { + const claim = mockResource("K8s::Core::PersistentVolumeClaim", { + spec: { accessModes: ["ReadWriteOnce"] }, + }); + const dep = mockResource("K8s::Apps::Deployment", { + spec: { template: { spec: { volumes: [{ claimName: mockAttrRef("name", "pgClaim") }] } } }, + }); + const yaml = k8sSerializer.serialize(new Map([["pgClaim", claim], ["dep", dep]])); + expect(yaml).toContain("name: pg-claim"); + expect(yaml).toContain("claimName: pg-claim"); + }); + + test(".namespace resolves to the declared namespace", () => { + const svc = mockResource("K8s::Core::Service", { + metadata: { name: "fountain", namespace: "fountain" }, + }); + const dep = mockResource("K8s::Apps::Deployment", { + metadata: { name: "app" }, + spec: { host: mockAttrRef("namespace", "service") }, + }); + const yaml = k8sSerializer.serialize(new Map([["service", svc], ["dep", dep]])); + expect(yaml).toContain("host: fountain"); + }); + + // A UID is assigned by the API server at admission, so emitting any + // build-time string for it would be a fabrication. + test(".uid is refused rather than fabricated", () => { + const svc = mockResource("K8s::Core::Service", { metadata: { name: "fountain" } }); + const dep = mockResource("K8s::Apps::Deployment", { + spec: { ownerRef: mockAttrRef("uid", "service") }, + }); + expect(() => k8sSerializer.serialize(new Map([["service", svc], ["dep", dep]]))).toThrow( + /assigned by the API server/, + ); + }); + + test("an unresolvable namespace says what to set rather than emitting a wrong one", () => { + const svc = mockResource("K8s::Core::Service", { metadata: { name: "fountain" } }); + const dep = mockResource("K8s::Apps::Deployment", { + spec: { ns: mockAttrRef("namespace", "service") }, + }); + expect(() => k8sSerializer.serialize(new Map([["service", svc], ["dep", dep]]))).toThrow( + /declares no metadata.namespace/, + ); + }); + + test("an attribute k8s cannot express is refused with the reason", () => { + const svc = mockResource("K8s::Core::Service", { metadata: { name: "fountain" } }); + const dep = mockResource("K8s::Apps::Deployment", { + spec: { x: mockAttrRef("clusterIP", "service") }, + }); + expect(() => k8sSerializer.serialize(new Map([["service", svc], ["dep", dep]]))).toThrow( + /resolves .name and .namespace/, + ); + }); +}); diff --git a/lexicons/k8s/src/serializer.ts b/lexicons/k8s/src/serializer.ts index 8fae3c3df1..b2a13e1806 100644 --- a/lexicons/k8s/src/serializer.ts +++ b/lexicons/k8s/src/serializer.ts @@ -113,16 +113,82 @@ function deriveGVKFromType(entityType: string): { apiVersion: string; kind: stri return { apiVersion, kind }; } +/** + * The name a resource gets when it does not declare one: the logical name, + * kebab-cased. Shared with the manifest builder below so a reference and the + * thing it references cannot derive different names (#1493). + */ +function derivedName(logicalName: string): string { + return logicalName.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(); +} + +/** + * What a cross-resource reference resolves to on this substrate (#1493). + * + * Kubernetes YAML has no deploy-time reference mechanism — no `!Ref`, no + * `Fn::GetAtt`. Whatever a reference is going to mean has to be resolved here, + * before serialization, or it means nothing at all. + * + * This used to return the *logical* name for every attribute, so + * `claimName: pgClaim.name` emitted `claimName: pgClaim` and the manifest + * named a resource that does not exist. It applied cleanly and failed on the + * cluster, which is the failure this whole system exists to remove. The + * lexicon's own plugin comment already described the intended behaviour — + * "resolves to metadata.name" — so this brings the code to the documentation + * rather than the other way round. + * + * `uid` is refused rather than resolved: a UID is assigned by the API server + * at admission, so no build-time value exists and any string emitted here + * would be a fabrication. + */ +function resolveK8sAttr(entity: Declarable | undefined, logicalName: string, attr: string): unknown { + if (attr === "uid") { + throw new Error( + `Cannot reference "${logicalName}.uid": a Kubernetes UID is assigned by the API server at ` + + `admission, so it has no build-time value. Reference .name, or carry the UID at runtime ` + + `with fieldRef: { fieldPath: "metadata.uid" }.`, + ); + } + + const metadata = + entity && isResourceDeclarable(entity) && typeof entity.props === "object" && entity.props !== null + ? ((entity.props as Record).metadata as Record | undefined) + : undefined; + + if (attr === "name") { + // Same fallback the manifest builder applies, so a reference to a resource + // that declares no name still resolves to the name it will actually get. + const declared = metadata?.name; + return typeof declared === "string" && declared.length > 0 ? declared : derivedName(logicalName); + } + + if (attr === "namespace") { + const ns = metadata?.namespace; + if (typeof ns === "string" && ns.length > 0) return ns; + throw new Error( + `Cannot reference "${logicalName}.namespace": it declares no metadata.namespace, and the ` + + `namespace a manifest lands in is decided at apply time (kubectl -n, or the context's ` + + `default). Set metadata.namespace on "${logicalName}" if the reference needs to be stable.`, + ); + } + + throw new Error( + `Cannot reference "${logicalName}.${attr}": the k8s lexicon resolves .name and .namespace at ` + + `build time, and Kubernetes YAML has no way to express any other attribute reference.`, + ); +} + /** * K8s visitor for the generic serializer walker. */ function k8sVisitor(entityNames: Map): SerializerVisitor { + // name → entity, so an AttrRef can reach the resource it points at. The + // walker hands the visitor a logical name, not the Declarable. + const byName = new Map(); + for (const [entity, name] of entityNames) byName.set(name, entity); + return { - attrRef: (name, attr) => { - // For K8s, attribute references typically resolve to metadata.name - if (attr === "name") return name; - return name; - }, + attrRef: (name, attr) => resolveK8sAttr(byName.get(name), name, attr), resourceRef: (name) => name, propertyDeclarable: (entity, walk) => { if (!isResourceDeclarable(entity) || typeof entity.props !== "object" || entity.props === null) { @@ -209,8 +275,7 @@ export const k8sSerializer: Serializer = { // Build metadata const metadata: Record = props.metadata as Record ?? {}; if (!metadata.name) { - // Use the logical name as the resource name (kebab-case) - metadata.name = name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(); + metadata.name = derivedName(name); } // Merge default labels