# Composition helpers

Writing raw Kubernetes manifests often means repeating the same boilerplate in multiple places, such as declaring a volume and its mount path separately or copying container ports into a matching Service. The `kix.*` composition helpers let you write each concern once: some transform container and workload specs directly, while others drop into a package's `build` list to wire ingress routes, Prometheus scraping, and post-deploy health checks.

:::note[Helpful background]
- [07. Package anatomy and safe resource composition](/docs/tutorials/07-package-anatomy-and-safe-resource-composition/): see how `kix.withMounts`, `kix.mkEnvVars`, and `kix.service.fromWorkload` work together in a package.
- [Package anatomy](/docs/reference/package-anatomy/): review how entries in a package's `build` list are evaluated and merged.
- [Resources and `out`](/docs/reference/resources-and-out/): see how the resources returned by these helpers expose `.out` attributes.
- [Service (Kubernetes docs)](https://kubernetes.io/docs/concepts/services-networking/service/): review how Kubernetes Services select pods and route traffic to container ports.
:::

## Env helpers

Kubernetes expects a container's `env` field to be a list of `{ name, value }` or `{ name, valueFrom }` objects. `kix.mkEnvVars` and `kix.mkEnv` let you write concise attribute sets while supporting secret and downward-API `valueFrom` references and conditional `null` entries.

### `kix.mkEnvVars` and `kix.mkEnv`

| Function | Signature | Description |
| --- | --- | --- |
| `kix.mkEnvVars` | `attrs -> list` | Converts an attribute set `{ KEY = value; ... }` into a sorted list of Kubernetes `env` entries, dropping any key whose value is `null`. |
| `kix.mkEnv` | `attrs -> list -> list` | Equivalent to `(kix.mkEnvVars attrs) ++ rawList`. Combines an attribute set of env vars with an explicit list of `{ name; ... }` objects. |

Each value in `attrs` passed to `kix.mkEnvVars` or `kix.mkEnv` can be:
- **A string**: becomes `{ name = KEY; value = "..."; }`.
- **An attribute set containing `valueFrom`** (such as `self.secret.out.keyRef "password"`): becomes `{ name = KEY; valueFrom = value.valueFrom; }`. Any attribute set without `valueFrom` throws an evaluation error.
- **`null`**: omitted from the returned list.

```nix
env = kix.mkEnv {
  PORT = "8080";
  LOG_LEVEL = config.logLevel;
  DB_PASSWORD = self.dbSecret.out.keyRef "password";
  OPTIONAL_FEATURE = if config.enableFeature then "true" else null;
} [
  {
    name = "POD_IP";
    valueFrom.fieldRef.fieldPath = "status.podIP";
  }
];
```

When merging user-supplied environment variables from `kix.options.env` (`config.env`), use [`kix.mergeEnv`](/docs/reference/package-anatomy/#escape-hatches-and-guard-helpers) so operators cannot overwrite environment variables owned by typed package options.

---

## Mount helpers

In raw Kubernetes specs, mounting a volume requires updating two separate places: `spec.template.spec.volumes` and `spec.template.spec.containers[*].volumeMounts`. Kix's `kix.mount.*` constructors and `kix.withMounts` / `kix.withMountsOn` keep each volume and its mount path together in one declaration.

```nix
deployment = scope.mkDeployment (
  kix.withMounts [
    (kix.mount.configMap self.configMap {
      mountPath = "/etc/myapp";
      readOnly = true;
    })
    (kix.mount.secret self.tlsSecret {
      mountPath = "/etc/tls";
    })
    (kix.mount.emptyDir {
      name = "cache";
      mountPath = "/var/cache/myapp";
      sizeLimit = "512Mi";
    })
  ] {
    name = "myapp";
    spec = {
      replicas = 2;
      selector.matchLabels = scope.selectorLabels;
      template.spec.containers = [
        {
          name = "myapp";
          image = kix.image.ref config.image;
          resources = config.resources;
        }
      ];
    };
  }
);
```

### `kix.mount.*` constructors

All resource-backed mount constructors (`kix.mount.pvc`, `kix.mount.configMap`, and `kix.mount.secret`) return `null` when their first argument (`resource`) is `null`, so optional mounts work without extra `lib.optional` wrappers. They also derive the volume name from `resource.out.name` by default (propagating the resource's Nix string context so the workload automatically depends on the mounted `ConfigMap`, `Secret`, or `PersistentVolumeClaim`) and record the resource's namespace for `checkNamespacedRefs`.

| Constructor | Signature | Options in final attrset |
| --- | --- | --- |
| `kix.mount.pvc` | `pvc -> { mountPath, name ? pvc.out.name, readOnly ? false, subPath ? null }` | Mounts a `PersistentVolumeClaim` (`persistentVolumeClaim.claimName = pvc.out.name`). |
| `kix.mount.configMap` | `cm -> { mountPath, name ? cm.out.name, readOnly ? false, subPath ? null, defaultMode ? null, items ? null }` | Mounts a `ConfigMap` (`configMap.name = cm.out.name`). |
| `kix.mount.secret` | `sec -> { mountPath, name ? sec.out.name, readOnly ? false, subPath ? null, defaultMode ? null, items ? null }` | Mounts a `Secret` (`secret.secretName = sec.out.name`). |
| `kix.mount.emptyDir` | `{ name, mountPath, medium ? null, sizeLimit ? null, readOnly ? false, subPath ? null }` | Mounts a scratch `emptyDir` volume named `name`. |
| `kix.mount.hostPath` | `{ name, mountPath, hostPath, type ? "DirectoryOrCreate", readOnly ? false, subPath ? null }` | Mounts the node path `hostPath` as a volume named `name`. |

`readOnly = true` sets `readOnly` on the container's `volumeMounts` entry. Set it on each mount record separately: a mount record carries one `readOnly` value, so a container that writes a volume and one that only reads it take two records of the same volume, which `kix.withMountsOn` declares once.

### `kix.withMounts` and `kix.withMountsOn`

| Function | Signature | Behavior |
| --- | --- | --- |
| `kix.withMounts` | `mounts -> workloadAttrs -> workloadAttrs` | Attaches all non-null `mounts` to the one container in the pod template's `containers`. Init containers do not count. Fails the build when the pod template has more than one container. |
| `kix.withMountsOn` | `containerName -> mounts -> workloadAttrs -> workloadAttrs`, or `[ containerName ... ] -> mounts -> workloadAttrs -> workloadAttrs` | Attaches all non-null `mounts` to each named container, searching `containers` and `initContainers`. Fails the build when a name matches no container. |

The pod template is `spec.jobTemplate.spec.template.spec` when the workload has a `jobTemplate` (a `CronJob`), and `spec.template.spec` otherwise.

Both functions add each volume to the pod template's `volumes` once. A volume that is already there with the same name and the same source (the same claim, ConfigMap, Secret, or emptyDir settings) is not added again, so the same volume can be mounted into several containers, or at several paths, with separate calls or separate mount records. Two volumes with the same name and different sources fail the build. The error names both sources; give one of them another name with `name = "..."`.

```nix
# The init container writes the token; the main containers read it.
{ name = "worker"; spec = { ... }; }
|> kix.withMountsOn "write-token" [ (tokenMount false) ]
|> kix.withMountsOn [ "app" "sidecar" ] [ (tokenMount true) ]
|> scope.mkDeployment
```

Each call appends to the named containers' `volumeMounts`, so the order of the calls is the order of the mounts in each container.

---

## service.fromWorkload

`kix.service.fromWorkload` derives a `v1/Service` definition from a workload resource, wiring the workload's label selector and resolving container ports automatically. Pass its result to `scope.mkResource`.

```nix
service = scope.mkResource (
  kix.service.fromWorkload {
    name = "echo";
  } self.deployment
);
```

### `kix.service.fromWorkload` arguments

| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | Required | `metadata.name` of the `Service`. |
| `type` | string | `"ClusterIP"` | Kubernetes Service type (`"ClusterIP"`, `"NodePort"`, `"LoadBalancer"`). |
| `ports` | list of `{ name?; port; targetPort?; protocol?; }` or `null` | `null` | Explicit Service ports. When `null`, Kix extracts all ports declared across the workload's containers (`port = containerPort`, `protocol = protocol or "TCP"`, and `name` when present; no `targetPort` is set). When explicit `ports` are passed, any string `targetPort` is verified against the workload's named container ports and resolved to its numeric port number. |
| `outputs` | attrset | `{ }` | Extra fields merged onto the Service's `.out` surface (`outputs.port` defaults to the first Service port number). |
| `...` | any | None | Any additional `scope.mkResource` arguments (`labels`, `annotations`, `requires`, `extra`, or extra `spec` fields) are forwarded to `scope.mkResource`. |

### Related port helpers

- **`kix.port name containerPort`**: Shorthand returning `{ name = name; containerPort = containerPort; protocol = "TCP"; }` for container `ports` lists.
- **`kix.service.extractPorts workload`**: Returns the list of `{ port, protocol, name? }` objects extracted from `workload`'s container specs (no `targetPort` field is included).

---

## expose

`kix.expose` is a composable `build` list entry that exposes a package `Service` outside the cluster using whichever ingress provider the cluster has deployed (`gateway` for Gateway API `HTTPRoute`, or `ingressNginx` for `networking.k8s.io/v1` `Ingress`). It pairs with `ingress = kix.options.ingress;` in `options`.

```nix
options = {
  ingress = kix.options.ingress;
};

build = [
  (
    { self, config }:
    {
      deployment = ...;
      service = ...;
      root = self.service;
    }
  )
  (kix.expose { service = "service"; })
];
```

### `kix.expose` arguments

| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `service` | string or `null` | `null` | Part name in `self` (looked up as `self.${service}`) identifying a single target `Service`. Exactly one of `service` or `paths` must be set; setting both or neither throws an evaluation error. |
| `paths` | list of `{ path; pathType ? "Prefix"; service; port?; }` or `null` | `null` | Path routing table for multi-service packages, where each entry's `service` is a part name in `self`. Cannot be combined with `service`. |
| `port` | int, string, or `null` | `null` | Explicit Service port name or number used when `service` is set (defaults to `service.out.port`). |
| `partName` | string | `"route"` | Part name for the generated `HTTPRoute` or `Ingress` resource. In Gateway mode, `"${partName}Crd"` holds the `HTTPRoute` CRD reference (`scope.mkCRDRef` for `gateway.networking.k8s.io/v1` `HTTPRoute`). |
| `exposurePart` | string | `"exposure"` | Attribute name in `self` where resolved exposure metadata (`self.exposure`) is published. |
| `defaultAnnotations` | attrset | `{ }` | Default annotations for the generated `Ingress` or `HTTPRoute`. Keys in `config.ingress.annotations` override them. |
| `timeouts` | `{ request?; backendRequest?; }` or `null` | `null` | Optional Gateway API `HTTPRoute` rule timeouts (for example, `{ request = "60s"; }`). Overridden when the instance sets `config.ingress.timeouts`. Ignored in Ingress mode. |
| `filters` | list of Gateway API `HTTPRouteFilter` | `[ ]` | Gateway API `HTTPRouteFilter` entries (such as `ResponseHeaderModifier`) added to every generated backend rule. Supported only in Gateway mode; fails evaluation in Ingress mode. |
| `extraRules` | list of Gateway API `HTTPRouteRule` | `[ ]` | Complete `HTTPRouteRule` entries prepended before the generated backend rules (for example, a `RequestRedirect` on an exact path). Supported only in Gateway mode; fails evaluation in Ingress mode. |
| `deriveHost` | bool | `true` | When `true`, falls back to `"${scope.instanceName}.${clusterConfig.cluster.domain}"` if `config.ingress.host` is `null`. When `false`, a route is emitted only when `config.ingress.host` is explicitly set. |

`kix.expose` reads `config.ingress` (defined by `kix.options.ingress`): `host`, `extraHosts`, and `annotations` apply in both Gateway and Ingress modes, while `timeouts` applies only in Gateway mode.

In Gateway mode, `kix.expose` checks during evaluation that at least one Gateway listener accepts each hostname (`host` and every entry in `extraHosts`) from the instance's namespace, and fails evaluation if none does. When a listener sets `allowedRoutes.namespaces.from = "Selector"`, Kix checks selectors that match only the `kubernetes.io/metadata.name` label; selectors on other labels cannot be checked during evaluation and emit a warning.

### `self.exposure` metadata

Even before the route resource is built, `kix.expose` populates `self.${exposurePart}` (default `self.exposure`) so sibling resources in `build` can read the external URL without creating a circular dependency:

| `self.exposure` field | Type | Description |
| --- | --- | --- |
| `via` | `"gateway"` \| `"ingress"` \| `null` | Active exposure mechanism when either `gateway` (claiming the gateway contract) or `ingressNginx` is wired and a hostname is resolved, or `null` otherwise. Having both `gateway` and `ingressNginx` present throws an evaluation error. |
| `host` | string or `null` | Resolved external hostname (for example, `"grafana.example.com"`), or `null` when no hostname is configured or derived. |
| `scheme` | `"https"` \| `"http"` \| `null` | In `"ingress"` mode, `"https"` when `clusterIssuer` is present and `"http"` otherwise. In `"gateway"` mode, derived from the matched listener on `gateway.out.listeners` (`"https"` for `HTTPS`, `"http"` for `HTTP`), or `null` when the gateway publishes no `out.listeners`. `null` when `via == null`. |
| `url` | string | Full external URL (`"${scheme}://${host}"`, with `:<port>` appended when a Gateway listener uses a non-default port). Throws an evaluation error when `urlOrNull == null`. |
| `urlOrNull` | string or `null` | Full external URL when `scheme != null` and `host != null`, or `null` when unexposed or when the gateway publishes no `out.listeners`. |

In `"ingress"` mode, when a `clusterIssuer` dependency is bound, `kix.expose` applies `clusterIssuer.out.withCert` to annotate the `Ingress` and populate `spec.tls` (`secretName = "${scope.instanceName}-tls"`). In `"gateway"` mode, TLS termination is owned by the Gateway listener and no `Certificate` resource is created by `kix.expose`.

### Lower-level route helpers

When a package needs custom routing outside `kix.expose`, use the lower-level builders directly with `scope.mkResource` or `scope.mkCR`:
- `kix.ingress.fromService { name, host, path ? "/", pathType ? "Prefix", port ? null, className ? null, tls ? [ ], ... } svc` (returns an `Ingress` attribute set for `scope.mkResource`; extra attributes such as `annotations` and `labels` are forwarded)
- `kix.httpRoute.fromService { name, host, parentRef, path ? "/", pathType ? "PathPrefix", port ? null, timeouts ? null, ... } svc` (returns an `HTTPRoute` attribute set for `scope.mkCR` or `scope.mkResource`)
- `kix.httpRoute.fromPaths { name, host, parentRef, timeouts ? null, paths }` where `paths` is a list of `{ path; pathType ? "Prefix"; svc; port ? null; }` (returns an `HTTPRoute` attribute set for `scope.mkCR` or `scope.mkResource`)

---

## monitor

`kix.monitor` is a composable `build` list entry that creates a `monitoring.coreos.com/v1` `ServiceMonitor` (and an optional `PrometheusRule` for alerts) whenever a `prometheus` provider is bound in the cluster and `config.metrics.enabled` is `true`. It pairs with `metrics = kix.options.monitor;` in `options`.

```nix
options = {
  metrics = kix.options.monitor;
};

build = [
  (
    { self, config }:
    {
      deployment = ...;
      service = ...;
      root = self.service;
    }
  )
  (kix.monitor {
    service = "service";
    port = "metrics";
    alerts = {
      EchoHighErrorRate = {
        expr = ''rate(http_requests_total{status=~"5.."}[5m]) > 0.05'';
        "for" = "5m";
        severity = "warning";
        summary = "High HTTP 5xx error rate on echo";
        description = "More than 5% of requests have failed over the last 5 minutes.";
      };
    };
  })
];
```

### `kix.monitor` arguments

| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `service` | string | Required | Target `Service` part name in `self` (looked up as `self.${service}`). |
| `port` | string or int | `"metrics"` | Port name (sets `port` on the endpoint) or port number (sets `targetPort` on the endpoint) to scrape. Checked against the selected `Service`'s ports by the [`architecture.monitorSelectorMatchesService`](/docs/reference/scorecard-and-rules/) scorecard rule. |
| `path` | string | `"/metrics"` | HTTP scrape path. |
| `scheme` | string | `"http"` | Scrape scheme (`"http"` or `"https"`). |
| `tlsConfig` | attrset or `null` | `null` | Prometheus endpoint `tlsConfig` block. |
| `params` | attrset of `listOf str` or `null` | `null` | URL query parameters added to scrape requests. |
| `honorLabels` | bool or `null` | `null` | Whether Prometheus preserves labels exported by the scraped target. |
| `extraEndpoints` | list of attrsets | `[ ]` | Additional endpoint definitions appended to `spec.endpoints` on the `ServiceMonitor`. |
| `alerts` | attrset | `{ }` | Map of `<AlertName> = { expr; "for"?; keep_firing_for?; severity?; summary?; description; runbook_url?; labels?; annotations?; }`. |
| `extraLabels` | attrset | `{ }` | Extra `metadata.labels` merged onto generated monitoring resources. |
| `name` | string or `null` | `null` (uses `scope.instanceName`) | Override base name of the generated `ServiceMonitor` (`name`) and `PrometheusRule` (`"${name}-alerts"`). |
| `monitorPart` | string | `"serviceMonitor"` | Part name for the `ServiceMonitor` in the returned parts attrset. |
| `rulesPart` | string | `"prometheusRules"` | Part name for the `PrometheusRule` in the returned parts attrset. |

### Standalone alert rules (`kix.alerts`)

For packages that define `PrometheusRule` alerts without a `ServiceMonitor` (for example, rules evaluated over kube-state-metrics or node-exporter series), pair `metrics = kix.options.alerts;` in `options` with `kix.alerts`:

```nix
(kix.alerts {
  alerts = {
    NamespacePodRestartLoop = {
      expr = ''increase(kube_pod_container_status_restarts_total{namespace="default"}[15m]) > 5'';
      "for" = "5m";
      severity = "warning";
      description = "Pod in namespace default is restarting repeatedly.";
    };
  };
})
```

`kix.alerts` accepts `alerts`, `name` (defaults to `scope.instanceName`), `extraLabels`, and `rulesPart` (defaults to `"prometheusRules"`), and is gated by `config.metrics.enabled` (default `true`).

### Operator reconcile errors (`kix.reconcileErrorsAlert`)

Operators built on controller-runtime increment `controller_runtime_reconcile_errors_total` on every failed reconcile, including optimistic-lock conflicts that a busy, healthy operator immediately retries. For operators that expose `controller_runtime_reconcile_total` and `controller_runtime_reconcile_errors_total`, `kix.reconcileErrorsAlert` builds a `"warning"` alert entry for `alerts`. It fires when a controller's 30-minute failure rate exceeds 10% (with at least three errors, `> 2.5` after `increase()` extrapolation) for 15 minutes.

```nix
alerts = {
  FooOperatorReconcileErrors = kix.reconcileErrorsAlert {
    selector = ''namespace="${ns}",service="${metricsServiceName}"'';
    operator = "Foo operator ${ns}/${name}";
    summary = "The Foo operator is failing to reconcile resources.";
    impact = "Foo resources may not match their specs";
    nextStep = "Check the operator logs for the failing resource and error.";
  };
};
```

| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `selector` | string | Required | PromQL label matchers that scope both reconcile counters to this operator instance. |
| `by` | list of strings | `[ "namespace" "service" ]` | Labels used to group the alert by operator instance (`controller` is always appended). When scraping through a `PodMonitor` or a `VMServiceScrape` that identifies the target by `job`, pass `[ "namespace" "job" ]`. |
| `operator` | string | Required | Operator name and `<namespace>/<instance>`, placed after `of the ` in the description (omit a leading `the`). |
| `summary` | string | Required | Static `summary` annotation for the alert. |
| `impact` | string | Required | Clause placed after `so ` in the description to explain what may be out of date while reconciles fail. |
| `nextStep` | string | Required | Final sentence of the description telling the reader what to check first. |

The generated `description` reads "The `<controller>` controller of the `<operator>` has failed `<percentage>` of its reconciles over the last 30 minutes, so `<impact>`. `<nextStep>`". Merge an attribute set with `//` to override fields such as `severity` or `"for"`.

---

## healthCheck

`kix.healthCheck` is a composable `build` list entry that returns two parts: `${partName}` (default `"healthCheck"`, a `batch/v1` `Job` named `"${scope.instanceName}-health"`) and `${partName}Script` (default `"healthCheckScript"`, a `v1/ConfigMap` mounted into the Job at `/probe`). Because the Job depends on `self.root` and nothing in the package's forward closure depends on the Job, Kix classifies it in `inverseDeps` (`kix.run/inverse-deps`) and deploys it after `self.root` is ready. The Job sets `kix.run/rerun: on-change` and runs again when the `script`, the `env` values, any Kix-built Secret or ConfigMap referenced in `env`, `self.root`, or any resource returned by `requires` changes. `kix.run/rerun-hash` covers the script ConfigMap and any Kix-built Secrets or ConfigMaps referenced in `env`, and `kix.healthCheck` adds `checksum/*` annotations on the pod template for `self.root` and each resource in `requires`. It pairs with `healthCheck = kix.options.healthCheck;` in `options`.

```nix
options = {
  healthCheck = kix.options.healthCheck;
};

build = [
  (
    { self, config }:
    {
      deployment = ...;
      service = ...;
      root = self.service;
    }
  )
  (kix.healthCheck {
    script = ''
      import os, urllib.request
      url = f"http://{os.environ['SERVICE_HOST']}:{os.environ['SERVICE_PORT']}/healthz"
      with urllib.request.urlopen(url, timeout=5) as resp:
          assert resp.status == 200
    '';
    env = { self, ... }: {
      SERVICE_HOST = self.service.out.fqdn;
      SERVICE_PORT = toString self.service.out.port;
    };
  })
];
```

### `kix.healthCheck` arguments

| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `script` | string | Required | Verification script written to the `${partName}Script` `ConfigMap` and executed inside the probe container. |
| `env` | `({ self, config, deps }: attrset)` | `_: { }` | Function returning environment variables passed to `kix.mkEnvVars` (supports strings and Secret `keyRef` values) and merged with runtime defaults and `RETRY_FOR = toString retryFor`. |
| `when` | `({ self, config, deps }: bool)` | `{ config, ... }: config.healthCheck.enabled or true` | Predicate function that gates the health check. Providing a custom `when` function replaces the default `config.healthCheck.enabled` check unless your function also reads `config.healthCheck.enabled`. |
| `retryFor` | `({ self, config, deps }: positive int)` | `{ config, ... }: config.healthCheck.retryFor or 90` | Function returning the retry budget in seconds exposed to the script as `$RETRY_FOR`. |
| `requires` | `({ self, config, deps }: list)` | `_: [ ]` | Function returning extra resources the health-check Job must wait for (when empty and `env` carries no resource context, `self.root` is wired automatically). |
| `partName` | string | `"healthCheck"` | Part name for the `Job` in `self` (the script `ConfigMap` is placed at `"${partName}Script"`). |
| `runtime` | `{ image, file, interpreter, env? }` | `kix.healthCheck.runtimes.python` | Probe execution runtime. Built-in runtimes: `kix.healthCheck.runtimes.python` (`docker.io/library/python:3.13-slim`, `file = "health-check.py"`, `interpreter = [ "python3" ]`) and `kix.healthCheck.runtimes.shell` (`docker.io/curlimages/curl:8.14.1`, `file = "health-check.sh"`, `interpreter = [ "/bin/sh" "-eu" ]`). |
| `activeDeadlineSeconds` | positive int or `null` | `null` (uses `retry + 90`) | Kubernetes `Job` `spec.activeDeadlineSeconds`. Defaults to `retry + kix.healthCheck.roundBudget` (`retry + 90`), and throws an evaluation error if set lower than `retry + 90`. |

Like every Job Kix builds, the finished Job stays on the cluster until a later build no longer contains it, and Kix deletes it then.

---

## availability

Kix models cluster availability across four ordered levels: `"none"` < `"pod"` < `"node"` < `"zone"`. Inside a package, the `availability` argument is a plain string (`"none"`, `"pod"`, `"node"`, or `"zone"`) holding the effective availability level for the current instance (clamped to `meta.availability.max`). Pass that `availability` string to the helpers on `kix.availability`:

| Value or helper | Signature | Description |
| --- | --- | --- |
| `availability` | string | Effective availability level passed to the package (`"none"`, `"pod"`, `"node"`, or `"zone"`). |
| `kix.availability.levels` | list of strings | `[ "none" "pod" "node" "zone" ]`. |
| `kix.availability.rank` | `level -> int` | Maps `"none" -> 0`, `"pod" -> 1`, `"node" -> 2`, `"zone" -> 3`. |
| `kix.availability.pick` | `level -> { none, pod, node, zone } -> value` | Selects `table.${level}`. All four keys (`none`, `pod`, `node`, and `zone`) are required; omitting any key throws an evaluation error. |
| `kix.availability.atLeast` | `min -> level -> bool` | Returns `true` when `rank level >= rank min` (for example, `kix.availability.atLeast "node" availability`). Throws an evaluation error inside a package if `min` exceeds the package's `meta.availability.max`. |
| `kix.availability.spreadConstraints` | `{ level, selector, topology } -> list` | Synthesizes `topologySpreadConstraints` for operator custom resources (such as CloudNativePG `Cluster` or Valkey) from `topology` (`clusterConfig.cluster.topology`, which is required). Emits one constraint per key in `topology.failureDomainKeys`, setting `whenUnsatisfiable = "DoNotSchedule"` on `topology.zoneKey` when `level == "zone"` and on `topology.hostKey` when `level == "node"`, and `"ScheduleAnyway"` otherwise. |

---

## operandPolicy

`kix.operandPolicy` builds a network policy for pods that an operator creates at runtime from a custom resource, such as database replicas or proxy pods (or for workload rules whose ports come from instance `config`). Because Kix does not build operator-created pods directly, the package that renders the custom resource declares their allowed traffic:

```nix
build = { self, scope, kix, ... }: {
  replicasEgress = kix.operandPolicy {
    inherit scope;
    name = "pg-replicas-egress";
    selector = { "cnpg.io/cluster" = "pg"; };
    egress = [
      scope.networkPolicyEnforcer.netpol.dnsEgressRule
      scope.networkPolicyEnforcer.netpol.apiServerEgressRule
    ];
  };
  root = {
    resource = self.cluster;
    requires = builtins.filter (p: p != null) [ self.replicasEgress ];
  };
};
```

| Argument | Type | Default | Description |
|---|---|---|---|
| `scope` | scope | required | The package's `scope`. Kix places the policy in `scope`'s namespace. |
| `name` | string | required | Name of the generated policy resource. |
| `selector` | attrset | required | Pod label selector (`matchLabels`) matching the target pods. |
| `ingress` | list | `[ ]` | Ingress rules from `scope.networkPolicyEnforcer.netpol` builders (such as `mkCallerIngressRule` or `mkSelfRules`). |
| `egress` | list | `[ ]` | Egress rules from `scope.networkPolicyEnforcer.netpol` builders (such as `dnsEgressRule`, `mkServiceEgressRule`, or `translateIntentRules`). |

`kix.operandPolicy` returns `null` when the cluster has no network policy enforcer or when all rules are filtered out by `networkPolicy.directions`, so filter out `null` values before adding policies to `root.requires`. Because Kix evaluates `ingress` and `egress` lazily only when an enforcer is present, those lists can reference `scope.networkPolicyEnforcer.netpol` directly without a null check.

Legacy calls may pass `spec` (a complete `CiliumNetworkPolicy` `spec` with `endpointSelector`) instead of `selector`, `ingress`, and `egress`. Passing both `spec` and `selector`, or omitting both, fails evaluation.

## cloudIdentity

Packages that call AWS, Google Cloud, or Azure APIs can accept either a [cloud identity](/docs/reference/instances-and-composition/#cloud-identities) or a Secret instance on the same dependency and unpack it with `kix.cloudIdentity.use`:

```nix
build =
  { self, config, providerCredentials ? null, ... }:
  let
    credentials = kix.cloudIdentity.use {
      inherit scope;
      dep = providerCredentials;
      arg = "providerCredentials";
      cloud = "aws";
    };
  in
  {
    serviceAccount =
      { apiVersion = "v1"; kind = "ServiceAccount"; inherit name; }
      |> credentials.bind
      |> scope.mkResource;
    # Reference this ServiceAccount in the pod spec: serviceAccount = self.serviceAccount;
    # credentials.secret holds the Secret instance when one was passed, or null.
  };
```

| Argument | Description |
| --- | --- |
| `scope` | The package's `scope`, used to name the instance and package in evaluation errors. |
| `dep` | The dependency value: a cloud identity, a Secret instance, or `null`. |
| `cloud` | Which cloud API the software calls: `"aws"`, `"gcp"`, `"azure"`, or `null` when cloud identities are not accepted. Passing an identity for any other cloud fails evaluation. |
| `arg` | Optional string (defaults to `null`). Name of the dependency argument in `build`, such as `"providerCredentials"`. When set, evaluation errors name `deps.<arg>` and set the error's `dependency` field. Always pass `arg` when a package has more than one credentials dependency, so users know which one to fix. |
| `identityGoesTo` | Optional string (defaults to `null`). Where the cluster author should move the cloud identity, such as ``"`deps.controllerIdentity` of the cert-manager instance"``. Appended to the error's fix when `cloud` is `null` and `dep` is a cloud identity. |
| `supportedClouds` | Optional list of strings (defaults to `null`), such as `[ "aws" ]` for a package that supports only S3 settings. Lists every cloud the package supports across all configurations. Passing an identity for an unlisted cloud fails evaluation, reports that the package does not support that cloud yet, and omits the suggestion to change `config`. When `null`, a cloud mismatch suggests changing `config` to match the identity's cloud. |

`kix.cloudIdentity.use` returns an attribute set with three fields:

| Returned field | Description |
| --- | --- |
| `secret` | `dep` when `dep` is not a cloud identity (such as a Secret instance or `null`); `null` when `dep` is a cloud identity. |
| `identity` | `dep` when `dep` is a cloud identity; `null` otherwise. |
| `bind` | Function that transforms ServiceAccount arguments before `scope.mkResource`. When `identity` is non-null, `scope.mkResource` writes the cloud's ServiceAccount annotations and `kix.run/cloud-identity`, and orders the ServiceAccount after the cluster's `cloudIdentity` provider. Workload builders (`scope.mkDeployment`, `mkStatefulSet`, `mkDaemonSet`, `mkJob`, and `mkCronJob`) then add `checksum/cloud-identity` and any required pod labels to every pod template with `serviceAccount = self.<part>`. When `networkPolicy.enable = true`, Kix also adds the credential egress rules for that cloud identity mechanism (see below) to each bound workload's egress policy. When `identity` is `null`, `bind` returns its arguments unchanged. |

If a package builds two ServiceAccounts with separate identities, declare two dependencies and call `kix.cloudIdentity.use` once for each.

Each cluster's cloud identity mechanism declares the outbound traffic a pod needs to fetch its credentials:

| Mechanism | Credential egress |
| --- | --- |
| IRSA (`eks`, `irsa-webhook`) | TCP 443 to any address outside the cluster (AWS STS) |
| EKS Pod Identity (`eks` with `cluster.flavor.eks.cloudIdentity = "pod-identity"`) | TCP 80 to `169.254.170.23/32` and `fd00:ec2::23/128` on the pod's own node |
| GKE Workload Identity Federation (`gke`, `gke-autopilot`) | TCP 80 and 8080 to `169.254.169.254/32` on the pod's own node |
| Microsoft Entra Workload ID (`aks`, `azure-workload-identity-webhook`) | TCP 443 to any address outside the cluster |

Kix adds these rules only to workloads whose ServiceAccount has a bound cloud identity. On GKE, IAM roles can be granted directly to a Kubernetes ServiceAccount without an `iam.gke.io/gcp-service-account` annotation, but default-deny egress blocks the GKE metadata server unless an identity is bound; pass `kix.cloudIdentity.gcp { }` on the instance's credentials dependency to open that egress rule. For node-local addresses, the `cilium` enforcer emits both a `toCIDR` rule (used through Cilium 1.16) and a `host` entity rule (used from Cilium 1.17 onward) on those ports; the `host` rule also allows traffic to any other host-network listener on the same port on the pod's node.

When an operator creates the ServiceAccount from a custom resource, `credentials.bind` cannot modify it. Instead, take `cloudIdentity ? null` as a build argument and call `kix.cloudIdentity.annotationsFor { inherit scope; identity = credentials.identity; provider = cloudIdentity; }`. Pass the returned `{ serviceAccountAnnotations, podLabels }` into the custom resource (both sets are empty when `identity` is `null`). `annotationsFor` also returns `networkIntents` (`{ egress = [ ... ]; }`, or `{ egress = [ ]; }` when `identity` is `null`): pass `{ intents.identity = rendered.networkIntents; }` to `scope.networkPolicyEnforcer.netpol.translateIntentRules` inside the operand pods' `kix.operandPolicy` (as `cnpg-cluster`, `stackgres-cluster`, and `velero` do) so default-deny egress does not block credential requests from operator-created pods. Because the operator creates those pods, Kix does not add `checksum/cloud-identity` to restart them automatically when the identity changes. Also call `kix.cloudIdentity.annotationsFor` when a workload launches its own pods at runtime under a bound ServiceAccount: merge the returned `podLabels` into the ConfigMap or setting that controls those pods' labels (as `velero` does for its node-agent and repository-maintenance ConfigMaps). For example, `cnpg-cluster` writes `serviceAccountAnnotations` to `spec.serviceAccountTemplate.metadata.annotations` and any `podLabels` to `spec.inheritedMetadata.labels` on the `Cluster`, and locks those keys in `kix.mergeGuarded`.

### When one package owns the ServiceAccount and another chooses the cloud

Sometimes one package owns the ServiceAccount while another chooses the cloud provider. For example, `cert-manager` runs the controller pod and owns its ServiceAccount, while each `cluster-issuer` instance configures Route 53, Cloud DNS, or Azure DNS. Because a Kubernetes ServiceAccount carries a single cloud identity, always declare the cloud identity dependency on the package that owns the ServiceAccount. Keep any static credential Secret and any option for using ambient pod credentials on the package that chooses the cloud; that package never accepts a cloud identity.

Because `out` values flow from a dependency to its dependents, how the two packages validate the cloud depends on the dependency direction:

| Direction | `out` field | Published by | Value | Checked by |
| --- | --- | --- | --- | --- |
| Cloud package depends on ServiceAccount package (for example, `cluster-issuer` -> `cert-manager`) | `out.identityCloud` | The ServiceAccount package | `credentials.cloud` from `useIdentity` (`"aws"`, `"gcp"`, `"azure"`, or `null`) | The cloud package, via `kix.cloudIdentity.ambientProblem` in `assertions` |
| ServiceAccount package depends on cloud package (for example, `stackgres-cluster` -> `stackgres-object-storage`) | `out.ambientCloud` | The cloud package | `"aws"`, `"gcp"`, `"azure"`, or `null` when using a Secret | The ServiceAccount package, passed as `cloud` to `kix.cloudIdentity.useIdentity` |

#### `kix.cloudIdentity.useIdentity`

The package that owns the ServiceAccount unpacks its cloud identity dependency with `kix.cloudIdentity.useIdentity`:

```nix
credentials = kix.cloudIdentity.useIdentity {
  inherit scope;
  dep = controllerIdentity;
  arg = "controllerIdentity";
  secretGoesTo = "`deps.issuerCredentials` of a cluster-issuer instance";
};
controllerServiceAccount =
  { apiVersion = "v1"; kind = "ServiceAccount"; inherit name labels; }
  |> credentials.bind
  |> scope.mkResource;
root.out.identityCloud = credentials.cloud;
```

| Argument | Description |
| --- | --- |
| `scope` | The package's `scope`, used to name the instance and package in evaluation errors. |
| `dep` | The dependency value: a cloud identity or `null`. Passing a Secret instance or any other value fails evaluation. |
| `arg` | Optional string (defaults to `null`). Name of the dependency argument in `build`, such as `"controllerIdentity"`. When set, evaluation errors name `deps.<arg>` and set the error's `dependency` field. |
| `secretGoesTo` | Required string naming where to pass a Secret instead (for example, ``"`deps.issuerCredentials` of a cluster-issuer instance"``). Included in the error's fix when `dep` is not a cloud identity or when `cloud` is `null`. |
| `cloud` | Optional (`"aws"`, `"gcp"`, `"azure"`, or `null`). Pass a dependency's `out.ambientCloud` when a dependency chooses the cloud: an identity for another cloud fails evaluation, and an explicit `null` (meaning the pods use a Secret) rejects any cloud identity. Omit `cloud` altogether when dependents choose the cloud; `useIdentity` then validates only the identity's own fields. |

`kix.cloudIdentity.useIdentity` returns an attribute set with three fields:

| Returned field | Description |
| --- | --- |
| `identity` | `dep` when `dep` is a cloud identity, or `null` when `dep` is `null`. |
| `cloud` | The identity's cloud (`"aws"`, `"gcp"`, or `"azure"`), or `null` when `dep` is `null`. Publish this as `out.identityCloud` when dependents choose the cloud. |
| `bind` | Same ServiceAccount transformer as `bind` on `kix.cloudIdentity.use` (or pass `identity` to `kix.cloudIdentity.annotationsFor` when an operator creates the ServiceAccount). |

#### `kix.cloudIdentity.ambientProblem`

When the package that chooses the cloud depends on the ServiceAccount owner, call `kix.cloudIdentity.ambientProblem { cloud; holder; }` in `assertions` for each configuration that uses `holder`'s pod credentials:

- `cloud`: `"aws"`, `"gcp"`, `"azure"`, or `null` (when using a static Secret instead of pod credentials).
- `holder`: the dependency instance whose pods make the cloud API calls (which publishes `out.identityCloud`).

`ambientProblem` returns `{ message, fix }` when `cloud` and `holder.out.identityCloud` are both non-null and differ, or `null` otherwise (including when `holder` has no cloud identity, since its pods may still receive default credentials from the cluster or node). Wrap a non-null result with `// { assertion = false; }` in the package's `assertions` list.

When the ServiceAccount owner exposes a builder function in `out` that chooses the cloud (such as `out.mkSecretStore` in `external-secrets`), the package cannot pass itself as `holder`. Pass `holderName` and `identityCloud` instead:

```nix
kix.cloudIdentity.ambientProblem {
  inherit cloud;
  holderName = "${scope.namespaceName}/${scope.instanceName}";
  identityCloud = credentials.cloud;
}
```

- `holderName`: `"<namespace>/<instance>"` of the ServiceAccount owner, shown in mismatch errors.
- `identityCloud`: `"aws"`, `"gcp"`, `"azure"`, or `null` (from `credentials.cloud` on `useIdentity`).

Both forms return the same `{ message, fix }` attribute set or `null`. Pass `cloud` with either `holder` or both `holderName` and `identityCloud`; any other combination fails evaluation. Inside an `out` builder, pass a non-null result to the consumer's `scope.fail` so the error points to the consumer instance.

#### Choosing a helper

| Situation | Helper |
| --- | --- |
| Same package owns the ServiceAccount and accepts either a Secret or a cloud identity | `kix.cloudIdentity.use` |
| Package owns the ServiceAccount while another package chooses the cloud and accepts any Secret | `kix.cloudIdentity.useIdentity` |
| An operator creates the ServiceAccount from a custom resource | `kix.cloudIdentity.annotationsFor` (pass `credentials.identity` from `use` or `useIdentity`) |
| Package chooses the cloud and uses the pod credentials of a dependency that owns the ServiceAccount | `kix.cloudIdentity.ambientProblem` (in `assertions`) |

The cluster's flavor or cloud identity module (such as `kix.modules.experimental.irsa-webhook`) selects the delivery mechanism, keeping packages portable across clusters ([Flavors and capabilities](/docs/reference/flavors-and-capabilities/#cloud-identity)).

---

## Version helpers

Packages can read `clusterConfig.k8sVersion` in `build` and compare it against a version bound to omit flags, collectors, or RBAC rules that older Kubernetes releases do not support.

### `kix.version.atLeast`, `kix.version.atMost`, and `kix.version.ofTag`

| Function | Signature | Behavior |
| --- | --- | --- |
| `kix.version.atLeast` | `version -> bound -> bool or null` | Returns `true` when `version` is `bound` or newer, `false` when older, or `null` when `version` is too imprecise to tell. |
| `kix.version.atMost` | `version -> bound -> bool or null` | Returns `true` when `version` is `bound` or older, `false` when newer, or `null` when `version` is too imprecise to tell. |
| `kix.version.ofTag` | `string -> string or null` | Extracts the version from a tag string, stripping any leading `v`, vendor suffix, or `@digest` while keeping pre-release suffixes (the same rules as [`kix.image.version`](#image-and-pin-helpers)). For example, `"v1.156.0-cluster"` returns `"1.156.0"`, `"2.0.0-rc1"` returns `"2.0.0-rc1"`, and `"latest"` returns `null`. Use it for standalone tag strings outside an image option, such as a custom resource's version field. |

Both functions compare up to the segment precision of `bound` (using the [version rules](/docs/reference/package-anatomy/#metaversion)), so `kix.version.atLeast "1.36.2" "1.36"` and `kix.version.atMost "1.36.2" "1.36"` both return `true`. When `version` has fewer numeric segments than `bound` and matches its prefix (such as `"1.36"` against `"1.36.2"`), both return `null`; if an earlier segment already differs (such as `"1.35"` against `"1.36.2"`), they still return `true` or `false`.

Passing `null` or a non-version string throws an evaluation error. Because `clusterConfig.k8sVersion` is `null` when the cluster leaves it unset, check for `null` first. Comparing with `!= false` keeps the feature enabled when `k8sVersion` is unset or less precise than `bound`:

```nix
k8sVersion = clusterConfig.k8sVersion or null;
served = k8sVersion == null || kix.version.atLeast k8sVersion "1.36" != false;
```

---

## Image and pin helpers

### `kix.image.ref`, `kix.image.version`, `kix.image.isPinned`, and `kix.image.checkRelease`

Pair `kix.options.image` in `options` with `kix.image.ref` in container specs:

```nix
image = kix.image.ref config.image;
imagePullPolicy = config.image.pullPolicy;
```

| Function | Signature | Behavior |
| --- | --- | --- |
| `kix.image.ref` | `{ repository, tag, digest ? null, ... } -> string` | Formats a container image reference from an image attribute set. Both `repository` and `tag` are required and must be non-empty strings (throws an evaluation error if either is missing or `""`). Renders `"${repository}:${tag}@${digest}"` when `digest` is non-null, or `"${repository}:${tag}"` when `digest` is `null`. |
| `kix.image.version` | `{ tag ? null, ... } -> string or null` | Returns the version the image's tag names, without a leading `v`, a digest, or a vendor suffix: `"v1.37.1-alpine"` gives `"1.37.1"`. A pre-release suffix stays: `"2.0.0-rc1"` gives `"2.0.0-rc1"`. Returns `null` when the tag names no version, such as `"latest"`. A package publishes the result as `out.version` so that an instance reports the version it runs. |
| `kix.image.isPinned` | `{ digest ? null, ... } -> bool` | Takes an image attribute set and returns `true` when `image.digest` is non-null (`(image.digest or null) != null`). |
| `kix.image.checkRelease` | `{ image, release, reason, option ? "image", also ? [ ], fix ? null } -> assertion` | Builds an entry for the package's `assertions` list that checks `image.tag` against `release`. The check passes when `image.tag` starts with the same major.minor version as `release`, or with any major.minor listed in `also`, such as `"1.9"`. It ignores any leading `v` and anything after the minor version, so a custom rebuild tagged `"1.21.3"` or `"v1.21.3-internal"` still passes when `release` is `"v1.21.3"`. `option` sets the option path reported on failure (`"${option}.tag"`). `reason` explains why the package requires that release (rendered after `"because"`, for example `"the CRDs in kix/packages/experimental/velero/crds come from ${release}"`). On failure, Kix suggests setting a tag from the accepted release series or removing the override to use the default, and appends `fix` when set (for example, instructions for updating the package to another version). |

Use `kix.image.checkRelease` when a package ships CRDs or RBAC rules from a specific upstream release:

```nix
assertions =
  { config, ... }:
  [
    (kix.image.checkRelease {
      inherit (config) image;
      inherit release;
      reason = "the CRDs in kix/packages/experimental/velero/crds come from ${release}";
      fix = "To update this package to another version, change release in kix/packages/experimental/velero/common.nix and run uv run scripts/vendor-crds.py velero.";
    })
  ];
```

### `kix.pins`

`kix.pins` (`source -> { get, ref, keys, all, instances, file }`) loads a JSON pin file (such as `./pins.json`) or an attribute set of image pins. When a flake passes `pins = ./pins.json;` to `kix.lib.mkFlake`, cluster definitions that declare a `pins` argument receive `kix.pins ./pins.json`:

| Helper | Signature | Description |
| --- | --- | --- |
| `(kix.pins source).get` | `key -> { repository, tag, digest, ... }` | Looks up a top-level image pin entry by `key`, throwing a descriptive error if the key does not exist. |
| `(kix.pins source).ref` | `key -> string` | Equivalent to `kix.image.ref ((kix.pins source).get key)`. |
| `(kix.pins source).keys` | list of strings | Attribute names of all top-level image pins. |
| `(kix.pins source).all` | attrset | Full validated attribute set of top-level image pins. |
| `(kix.pins source).instances` | attrset | Validated per-instance option pins from a `version = 2` pin file, keyed `"<namespace>/<instance>" = { <optionPath> = pin; }`. |
| `(kix.pins source).file` | string or `null` | Store path string when `source` is a file path, or `null` when `source` is an attribute set. |

### Image provenance (`kix-image-sources.json`)

Every built cluster output includes `kix-image-sources.json`, which maps each container image string in the cluster to its `origin`:
- `"pin"`: Supplied by the cluster pin file's `instances."<namespace>/<instance>"` map or via `kix.pins`.
- `"package_default"`: Declared in `kix.options.image` default values inside the package.
- `"injected"`: Injected into the instance's configuration by a consumer dependency (`deps.<arg>.config`).
- `"nix_built"`: Carries Nix derivation string context on `repository`, `tag`, or `digest`.
- `"code"`: Set in cluster or instance configuration (`instances.<namespace>.<name>.config`) or inline in Nix expressions without a pin or derivation context.

---

## Facts and untrackedRef

### `kix.facts`

When Kix inspects a resource manifest, it classifies every `.out` reference to determine how the reference affects deployment ordering and network policy derivation:

- **Default (ambient reference)**: Counts as both a deployment dependency (`kix.run/depends-on`) and a network traffic path when pointing to a `Service` endpoint (`out.fqdn` or `out.url`).
- **`kix.facts.refOnly s`**: Replaces `endpoint` fact tokens on string `s` with `refonly` fact tokens. The deployment dependency (`kix.run/depends-on`) is preserved, but no derived network policy ingress or egress rule is generated for this reference.
- **`kix.facts.connect factCtx s`**: (`factCtx -> s -> string`) Attaches the endpoint fact context from `factCtx` (such as `svc.factTokens.endpoint`) onto string `s` so workloads embedding `s` receive a network policy edge to that Service.
- **`kix.facts.structural value`**: Wraps a custom resource `outputs` value (`outputs = { replicas = kix.facts.structural "3"; };`) as structural metadata so `scope.mkResource` strips endpoint facts with `refOnly` while keeping resource ordering context.

```nix
# Referencing a Service FQDN in an operator CLI flag without opening pod-to-service data traffic
args = [
  "--webhook-service-host=${kix.facts.refOnly self.webhookService.out.fqdn}"
];
```

### `kix.untrackedRef`

Kix validates that every cross-resource reference in a manifest (`serviceAccountName`, volume `claimName`, `secretName`, `configMap.name`, ingress backend, etc.) points to a Kix-managed resource via `.out`. When a field intentionally references a resource created outside Kix or dynamically at runtime by a controller, wrap the reference in `kix.untrackedRef`:

```nix
# Referencing a Secret created dynamically at runtime by this workload itself
volumes = [
  {
    name = "webhook-cert";
    secret = {
      secretName = kix.untrackedRef {
        name = "my-operator-webhook-cert";
        by = "self";
      };
      optional = true;
    };
  }
];

# Referencing a ConfigMap created at runtime by an operator workload
env = kix.mkEnvVars {
  DYNAMIC_CONFIG = kix.untrackedRef {
    name = "operator-generated-cm";
    kind = "ConfigMap";
    by = deps.myOperator.root;
  };
};
```

`kix.untrackedRef` accepts either a plain string (`kix.untrackedRef "external-name"`) or an attribute set:

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | Required | Name of the untracked Kubernetes resource. |
| `kind` | string or `null` | `null` | Kubernetes kind (such as `"Secret"` or `"ConfigMap"`). Forbidden when `by = "self"`. When `kind` is set, Kix records `apiVersion\|kind\|name` in `metadata.annotations."kix.run/expects"` for pre-deploy cluster checks. |
| `apiVersion` | string or `null` | `"v1"` when `kind` is set | API version paired with `kind` in `kix.run/expects`. Forbidden when `by = "self"`. |
| `by` | resource, `"self"`, or `null` | `null` | Who creates the resource at runtime. Must be `"self"`, `null`, or a Kix resource with `outPath` (a workload, Job, or operator custom resource, such as `self.setupJob` or `deps.myOperator.root`; a dependency package view like `deps.myOperator` has no `outPath`). Passing a resource attaches its store context so it deploys first. Passing `by = "self"` declares that the current workload creates the resource itself (requires `optional = true` on the pod's volume or env reference, and forbids `kind` and `apiVersion`). Leaving `by = null` emits a scorecard finding under `architecture.untrackedReferences`. |