Order-independent quality modules for a GitOps Kubernetes platform
How I made mesh, zero trust, elasticity and resilience modules adoptable on a running K3s platform in any valid order, as gated Argo CD migrations that never edit the base, and how a field-ownership diff checks that across all 25 orders.
The platform is a GitOps-managed K3s cluster with a base that is production-ready on day one: Argo CD, Kyverno, External Secrets, Prometheus, Loki, Alloy and Grafana, Traefik on Gateway API, and Tekton CI with rootless BuildKit. On top of it sit five optional quality modules: O distributed observability (OpenTelemetry Collector, Tempo, SLO alerting), M service mesh (Istio in ambient mode), S zero trust (identity authorization, strict mTLS, signed images), R elasticity (KEDA scaling on Kafka lag) and Rs active resilience (waypoints, timeouts, retries, outlier detection, a fault-injection gate). A team adopts them one at a time, on a running system, when it needs them.
The constraint that shapes everything else: adopting a module, in any valid order, must not edit the application, the base or any module that is already active. That means zero changed files outside the module's directory and zero changed fields owned by anything else, both checked by a machine. The workload is the OpenTelemetry Demo (Astronomy Shop: about 18 services in several languages, gRPC and HTTP, and Kafka between checkout and two consumers). The lab is four VMs on one 8-core, 32 GB desktop: a 2 vCPU / 6 GiB control plane and three 3 vCPU / 4.5 GiB workers.
The model
The nodes are V = {B, O, M, S, R, Rs}. An edge (u, v) means u must come before v. Hard edges are requirements; soft edges are only preferences and never block an adoption:
E_hard = {(B,O), (B,M), (B,R), (M,S), (M,Rs), (O,Rs)}
E_soft = {(O,M), (O,S), (O,R), (S,Rs), (R,Rs)}
An active set X is valid if it contains B and is closed under hard edges. A module m is adoptable in X if all of its hard predecessors are in X. Of the 32 subsets of modules, 16 are valid. Of the 120 permutations of the five modules, 25 are valid adoption orders. Across all valid sets there are 28 distinct (set, module) transitions, and those 28 transitions are everything that has to be tested.
The model is code, loaded from the module specs, so the CLI, the in-cluster prechecks and the test harness cannot disagree about it:
def is_valid(self, active):
return all(self.modules[m].hard <= active for m in active)
def adoptable(self, m, active):
return m not in active and self.modules[m].hard <= active
def completed_by(self, m, active):
"""Derivatives that adopting m activates (installed by m's migration)."""
return self.active_derivatives(active | {m}) - self.active_derivatives(active)
def valid_orders(self):
out = []
for perm in itertools.permutations(sorted(self.modules)):
active = frozenset()
for m in perm:
if not self.adoptable(m, active):
break
active |= {m}
else:
out.append(perm)
return out
The "no edits" property needs a precise notion of ownership. Let C_v be the part of the cluster configuration owned by node v. Field managers cannot draw that line: every Argo CD Application applies as argocd-controller, and every Kyverno policy writes as the background controller. So the owner of an object is the Application in its Argo CD tracking-id annotation (for Kyverno-generated objects, the Application that owns the generating policy), and C_v is the set of fields in that applier's managedFields entry, with their values. The label that M's mutate policy adds to a base Namespace therefore belongs to M, not to the base. The property is: for every valid X and every m adoptable in X, adopting m leaves C_v unchanged for all v in X and leaves the application's configuration unchanged. It follows that two orders reaching the same set must end in the same configuration.
Seams: wiring the base in advance
If a module may not edit the base, the base has to already contain every hook a module will need. I call these hooks seams. They live in a catalog, and each seam has a machine-checkable predicate. A module's precheck refuses to start if any seam the module requires is missing. The catalog has 23 entries. The ones that matter most:
- Pre-wired endpoints. Alloy already exports traces to
otel-traces.module-o.svc:4317, a Service that does not exist yet. Before O arrives, spans are dropped (retries off, queue of 500), at a cost of about three error log lines per minute. O creates the Service, and nothing restarts. The base Prometheus is pointed the same way at an Alertmanager inmodule-o. - Mesh-ready NetworkPolicies. The base policies already allow TCP 15008 (HBONE) and
169.254.7.127/32, the address ambient mode uses as the source of kubelet probes. Without this, M would have to edit every policy. - Labels owned by the module. Candidate namespaces carry
platform.io/mesh-enroll=true, and M's own Kyverno policy addsistio.io/dataplane-mode=ambient. With server-side apply and self-heal, Argo CD leaves that label alone because the label is not part of the base's desired state. I verified this on the cluster before building any module. - Replica ownership. Argo CD ignores
/spec/replicas. HPAs exist only for synchronous services, and the queue consumers have none, so KEDA can own them without two controllers fighting over one object. - Per-workload identity. The demo runs all 18 services under one ServiceAccount, which would collapse S's policies to namespace granularity. A base guardrail generates a
wl-<component>ServiceAccount for each workload and mutates Pods, not templates, to use it, so Argo CD sees no drift. - Ingress shape. Traefik runs in its own namespace, because istio-cni excludes
kube-system. It runs two replicas under a PDB, and it balances to the Service ClusterIP instead of Pod endpoints, so a waypoint attached to the Service also covers ingress traffic.
- id: traces-endpoint-prewired
enables: [o]
check: {kind: ConfigMap, namespace: observability, name: alloy,
contains: otel-traces.module-o.svc}
- id: replicas-ignored
enables: [r]
check: {kind: Application, name: astronomy-shop,
ignoreDifferences: /spec/replicas}
- id: ingress-redundant
enables: [rs]
check: {kind: Deployment, namespace: ingress, name: traefik,
minReplicas: 2, pdb: true}
Most seams were not designed up front. Each one is the record of a module that, without it, would have had to edit something it does not own. Every seam is a small scar.
A migration is one commit and one sync
To adopt m, you commit a three-line enablement manifest with kind, name and dir. An ApplicationSet with a Git files generator turns each one into an Application named module-m. Derivatives are enabled the same way. plat, the CLI, never applies a manifest to the cluster. It commits, pushes, waits until Argo CD serves that exact revision, and then triggers the sync.
kind: ApplicationSet
metadata: {name: quality-modules}
spec:
syncPolicy:
applicationsSync: create-update # never deletes
generators:
- git:
files:
- path: clusters/lab/modules/*.yaml
- path: clusters/lab/derivatives/*.yaml
template:
spec:
source: {path: '{{ .dir }}'}
syncPolicy: # no automated: plat triggers one sync
syncOptions: [ServerSideApply=true, SkipDryRunOnMissingResource=true,
RespectIgnoreDifferences=true, PrunePropagationPolicy=foreground]
Both policies there are scar tissue. With auto-sync, Argo CD re-ran a migration that had failed a gate, at the same revision, three times; a gate only means something if failure stops the migration, so plat triggers exactly one sync at the revision it pushed. With polling, the generator once evaluated a stale revision and deleted module-o four times mid-adoption, running its undo hooks each time; deletion is now only an explicit plat rollback.
Stages map to sync waves, and verification maps to hooks. Each module has a spec, and its hook Jobs are generated from it:
kind: QualityModule
metadata: {name: s}
spec:
hardDeps: [m]
softDeps: [o]
seamsRequired: [ingress-own-namespace, per-workload-identity,
netpol-platform-access, image-signatures-verifiable]
stages:
- {id: 10-scanner, wave: 10} # Trivy Operator
- {id: 20-authz, wave: 20} # derived ALLOW policies
- {id: 21-deny, wave: 21} # deny by default, after every ALLOW exists
- {id: 30-strict, wave: 30} # PeerAuthentication STRICT
- {id: 40-verify-images, wave: 40} # Kyverno verifyImages, Enforce
gates:
- id: g20-authz
wave: 22
timeout: 300
checks:
- {name: checkout-journey, type: flow, steps: [...], maxSeconds: 3}
- {name: authz-probe, type: job, namespace: module-s}
- id: g40-image-policy
wave: 41
checks:
- {name: unsigned-golden-image-denied, type: admission, namespace: golden,
image: registry.lab:5000/golden/unsigned-probe:1,
expect: denied, deniedBy: verify-golden-images}
- {name: signed-golden-image-admitted, type: admission, namespace: golden,
imageFrom: {namespace: golden, name: catalog-api}, expect: admitted}
plat then deletes the Application, which runs the PreDelete guard and the PostDelete undo. The evidence stays in module-<m>-status with phase RolledBack.Every hook is the same gate-runner image, invoked as precheck, gate, report, fail, guard or undo. All state lives in a ConfigMap per module. The PreDelete guard refuses a rollback while a Ready module hard-depends on this one, so even a module file deleted from Git without the CLI cannot leave an invalid set. Around Argo CD, plat separates three outcomes:
- A gate failure ("one or more synchronization tasks completed unsuccessfully") triggers an immediate rollback.
- A transient Argo CD error (
ComparisonError,DeadlineExceeded, repo serverUnavailable) means the manifests were never compared, so it is not a migration outcome.platre-triggers the sync, at most three times. - A wave that waits on a resource's health for more than 10 minutes fails the migration. It surfaced when waypoint Pods could not be created under Pod Security
restricted: Argo CD waited forever on the Gateway's health and the next gate never ran. "Progressing" is a state of mind.
$ plat adopt r
adopting r; X = ['m', 'o', 'r', 's']; derivatives completed: ['s-r']
derivative s-r (before r): Synced/Healthy
sync triggered at 5e0b7c21
argo=Running migration=Migrating gates=[]
argo=Running migration=Migrating gates=['g10-keda-ready✓']
argo=Running migration=Migrating gates=['g10-keda-ready✓', 'g20-scalers-active✓']
argo=Succeeded migration=Ready gates=['g10-keda-ready✓', 'g20-scalers-active✓', 'g30-dashboard✓']
migration Ready in 139s (wall clock, including Git and Argo CD)
Gates
The check types are ready, condition, promql, flow (a multi-step HTTP journey with a latency bound), job (a probe workload), routes, admission and steady. admission creates a Pod as a server-side dry run, so webhooks run but nothing is persisted. S uses it in both directions: a never-signed image must be denied by verify-golden-images specifically, and the deployed signed image must be admitted. Three rules came out of the gates failing for the wrong reasons:
- A gate must match the intermediate state. M's stage-20 gate first required mTLS from the ingress. But at stage 20 only platform namespaces are enrolled, and ingress-to-app traffic is plaintext by design. Stage 20 now checks that ztunnel carries the inbound traffic of each enrolled platform namespace. The application check (at least 0.99 of connections reported as
mutual_tls) waits until stage 30. - A gate must hold in every order. S's unauthorized-client probe expected a connection reset from ztunnel. When Rs had already been adopted, the same denial comes back as an HTTP 403
RBAC: access deniedfrom the waypoint. The probe read that as "allowed", and S rolled back even though its policy was correct. The probe now accepts either form of denial and fails on anything else. - Configuration diffs cannot see broken behaviour. After each adoption, every active module re-runs its quick checks read-only. Without that, adopting S after R without the S∧R glue would leave every config diff empty while R silently stopped scaling.
The steady-state gate is a hypothesis test
Rs's last gate runs checkout journeys for 180 s while Chaos Mesh injects four faults: pod kills of product-catalog and cart at 15 s and 50 s (grace 0), a hung product-catalog replica at 90 s and a cart replica with 100 % packet loss at 130 s, each for 25 s. A fixed 99 % cutoff failed healthy adoptions on sampling noise: at a pooled 0.5 % failure rate and 230 to 320 journeys, it rejects a healthy system 8 to 11 % of the time. The gate now rejects the claim "P(success) ≥ p0 = 0.99" only when an exact one-sided binomial test makes it implausible:
p0, alpha = c["test"]["p0"], c["test"]["alpha"] # 0.99, 0.01
f, q = total - ok_n, 1 - p0
pval = 1.0 - sum(math.comb(total, i) * q**i * p0**(total - i) for i in range(f))
passed = total >= c["test"]["minJourneys"] and pval >= alpha and faults_injected
At about 640 journeys per run the gate rejects at 14 failures (2.2 %), so a healthy adoption fails with probability at most 1 %. A fault that could not be created fails the gate outright. The caveat: once the base had readiness probes, the base without Rs passed this test too. The gate is a necessary condition, not evidence that Rs helps; that is measured separately.
Derivatives: where two modules meet
S's deny-by-default stops KEDA, which belongs to R, from reading Kafka lag. The allowance that fixes it belongs to neither module. In S, it would make S's content depend on whether R exists. In R, the reverse. Either way, the configuration would depend on the adoption order. So the graph gets a third kind of node: a derivative d(S,R) that is active exactly when both of its operands are. The migration that completes the pair installs it, and rolling back either operand removes it. It is new configuration, not an edit, so the property still holds once C(X) includes the active derivatives.
kind: Derivative
metadata: {name: s-r}
spec:
operands: [s, r]
timing:
r: before # completed by R while S is active
s: {afterGate: g20-authz} # completed by S while R is active
---
kind: AuthorizationPolicy
metadata: {name: allow-keda-to-kafka, namespace: astronomy-shop}
spec:
selector: {matchLabels: {app.kubernetes.io/component: kafka}}
action: ALLOW
rules: [{from: [{source: {principals: [cluster.local/ns/keda/sa/keda-operator]}}]}]
The content is the same in both orders, but when it may land is not, and that turned out to be a scheduling problem.
plat handles all three timings. For before, it syncs the derivative's Application first and waits until it is Synced and Healthy. For afterGate, a callback watches the module's status ConfigMap and triggers the derivative's sync as soon as the named gate passes, while the module's own sync carries on with wave 30. The default, after, waits until the module is Ready. The cost is measurable: in the S-after-R order there is a short window between wave 21 and the derivative in which KEDA cannot read the lag. The consumers hold their replica counts, with no outage and no scaling. When the derivative landed only after S was Ready, that window lasted about five minutes.
S and Rs interact too, but they have no derivative. Their glue would have to land between Rs's waypoint creation and its Service enrollment, inside another Application's sync, and Argo CD cannot express that. Instead, S renders every allowance at both of ambient mode's enforcement points. The ztunnel policy (a selector on the workload) admits the callers plus the namespace's waypoint principal. The waypoint policy (targetRefs on the workload's Services) admits the callers. Without Rs, the second policy is inert. S also reserves the waypoint ServiceAccount to Istio's controller chain with Kyverno (istiod creates the Deployment, the Deployment controller the ReplicaSet, the ReplicaSet controller the Pod). The first version of that rule matched every UPDATE. It blocked the garbage collector's foreground deletion when Rs rolled back, the stale waypoint Deployments survived, and istiod re-adopted them on the next attempt. A rule written for "who may create X" must not constrain the lifecycle writes controllers make on X.
Derived content
S's allowlists and Rs's routes are not written by hand. They are derived from live telemetry at adoption time and committed together with the enablement file, so the adoption is a reviewable diff and stays pure GitOps.
S: allowed = observed ∪ declared. Observed edges are bytes received per (source principal, destination workload) over a 20-minute window. Bytes, not connections: gRPC keeps long-lived connections, and counting opened connections found 8 edges and missed most calls. gRPC simply does not hang up. With a waypoint in the path ztunnel sees the waypoint's identity, so callers are also read from the waypoint's own reports; otherwise the derivation would depend on whether Rs came first. Declared edges come from a hand-written dependency list, because telemetry only sees exercised paths. The call nobody made during the window is exactly the one that pages you at 3 a.m. Excluded edges (other modules' identities, stale principals) are listed in the generated file's header, never silently allowed. ztunnel has no dry-run mode for L4 authorization, so S cannot rehearse: ALLOW policies go out at wave 20 and deny-by-default at wave 21, and allowed traffic never sees a denial window.
Rs: timeouts from O's span metrics. This is why O is a hard dependency of Rs:
K, T_MIN, T_MAX = 2, 1.0, 10.0
RETRY = {"attempts": 2, "backoff": "25ms", "codes": [503]}
def own_timeout(p999_ms): # round up to 100 ms, clamp to [1 s, 10 s]
return min(max(math.ceil(K * p999_ms / 100) / 10, T_MIN), T_MAX)
def t(s): # deadline nesting over the declared call graph
callee = [t(c) * (1 + RETRY["attempts"] * (c in retried)) for c in calls[s]]
return min(max([own[s], *callee]), T_MAX)
A caller's timeout covers its slowest callee's timeout multiplied by that callee's attempts. That way a caller never gives up while a callee is still legitimately retrying, which is the same idea as gRPC deadline propagation. At the calibrated load, frontend's p99.9 of 738 ms gives a 1.5 s own timeout and a 9 s nested one, and most other services sit at the 1 s floor. On retries:
- Only the operations the app declares idempotent (catalog reads,
GetCart, currency conversion, quotes) retry on 503. - Everything else keeps the waypoint's default policy:
connect-failure, refused-stream, unavailable, cancelled. Those are failures where the request never reached the handler. - Nothing retries on
reset, so a charge or an order is never repeated. Retrying a payment is how you end up explaining idempotency to finance.
The DestinationRules carry a retry budget (at most 20 % of active requests may be retries) and outlier detection on gateway errors only. That means consecutiveGatewayErrors: 3 with consecutive5xxErrors: 0, because Envoy maps gRPC statuses into 5xx, and injected application faults would otherwise eject healthy hosts. Every workload whose HPA keeps at least two replicas gets a PDB with minAvailable: 1. For repeatable runs, plat adopt --frozen keeps the committed derivation, so every order applies byte-identical content.
Checking the property
Two diffs are taken at every transition. Δ_git lists the files changed outside the module's directory, its derivatives and its enablement file. Δ_live snapshots every listable resource with its managedFields before and after the adoption, assigns each object to a node, hashes the owner's fields and classifies every foreign field:
- Declared extension: a field that a seam declares extensible. The namespace dataplane label, the Service
use-waypointlabel, the PodserviceAccountName, and ClusterRoleruleswritten by the aggregation controller. - Runtime:
status,generation, finalizers, owner references, replica counts, or anything written by the Kubernetes controllers and a node's own operators. - Undeclared: anything else.
Δ_live is empty if and only if no owner field of another node changed, no object belonging to another node disappeared and no undeclared foreign field appeared. Comparing final configurations across orders uses the effective configuration (owned plus non-runtime foreign fields, since which manager holds a field varies between installs), canonical values (empty defaulted stanzas dropped), and excludes per-install identity: generated TLS material, caBundle, ServiceAccount tokens, Kyverno provenance labels, a chart's random rollme annotation.
The checker has earned its keep twice. The first passing Rs adoption reported one undeclared field: the base's kyverno:background-controller ClusterRole rules, which the aggregation controller had rewritten from Rs's aggregated role. That is Kyverno's intended extension point, but it was not in the catalog, so it became a seam. To test sensitivity, I made a deliberate base edit through the normal GitOps path, raising the frontend HPA's maxReplicas from 3 to 4. Δ_live reported exactly [hpa astronomy-shop/frontend, owner base, spec.maxReplicas] and came back empty after the revert.
Then the full sweep: all 25 valid orders, each on a cluster rebuilt from empty VMs, all at one revision.
| Measure | Value |
|---|---|
| Orders run | 25 of 25 |
| Distinct transitions observed | 28 of 28 (124 observations) |
| Completed adoptions | 120 |
| Completed adoptions with non-empty Δ_git or Δ_live | 0 |
| Adoptions stopped at a gate | 4, all at Rs's steady-state gate |
| Complete orders with the same final configuration | 21 of 21 |
| Median adoption time | O 258 s, M 163 s, S 144 s, R 121 s, Rs 315 s |
| Base convergence from empty VMs | median 761 s (650–1015 s) |
None of the four stopped adoptions was a module defect.
- Two came from the demo having no readiness probes. A replacement cart Pod was listed as Ready about a second after its container started, before .NET was listening, and ztunnel logged
connection refusedfrom the waypoint. The two-replica availability floor was not real. The base now adds TCP readiness probes. - The other two came from Chaos Mesh's webhook certificate and its
caBundlebeing generated in different chart renders, so the webhook rejected every fault. The bootstrap now dry-runs a PodChaos and repairs the pair if needed.
The first comparison of final configurations flagged 6 of 20 orders on a single field: kubectl's last-applied-configuration annotation on one Application, which had or had not captured Argo CD's pre-delete finalizers depending on timing. The fields it copies are compared directly anyway, so it joined the identity list.
For contrast, the same tools installed as flat auto-sync Argo CD Applications (no stages, gates or derivatives) needed the same two hand corrections in every paired run. istiod rewrites its webhooks' caBundle and failurePolicy at runtime and self-heal fights it; and under S, Kafka's ztunnel rejects KEDA's identity (HBONE 401), so R never converges. Even after the allowance was applied by hand, KEDA took about 24 minutes to recover from its exponential backoff. Each correction matches a mechanism the migration path already has: ignoreDifferences on webhook fields, and the derivative.
Where it actually broke
None of the defects I found were in a tool taken alone. All of them were at a boundary: between the base and a module, between two modules, or between the system and the instrument measuring it. For once, it wasn't DNS.
- Ambient captures connections when they open. A new waypoint only sees new connections. Under steady load, Traefik's keep-alive connections to frontend-proxy never go idle, so the ones opened before the waypoint existed bypass it indefinitely, along with Rs's timeouts and retries. Traefik has no maximum connection lifetime, and frontend-proxy's Envoy config is baked into the image. The fix was the
ingress-redundantseam plus a gate action that recycles Traefik one Pod at a time through the Eviction API. It waits on HTTP 429 while the PDB has no budget, and it waits until the Deployment is ready again before evicting the next Pod. No spec changes, so Δ is unaffected. - Mesh rollback order. The first rollback removed the enrollment labels while M's mutate-existing policy still existed. Kyverno re-added them, Istio was removed from under enrolled Pods, and the storefront went dark until the Pods in three namespaces were restarted. The undo now deletes the policies, removes the labels, and waits until istio-cni has cleared
ambient.istio.io/redirectionfrom every Pod. Only then does it let Argo CD delete Istio. - A hairpin through the mesh. The demo's single-node KRaft broker reached its own controller as
kafka:9093, through its own Service and so through ztunnel. After S, controller heartbeats timed out every few seconds and checkout's publish span sat at the 15 s ceiling, yet S's gates passed because they checked status codes only. The quorum now points at1@localhost:9093, and every journey check has a latency bound. - Metadata propagation colliding with admission. Rs's Gateways were first generated by a Kyverno policy, so they carried
generate.kyverno.io/*labels. istiod copies a Gateway's metadata onto the Deployment and ServiceAccount it creates, and Kyverno rejects any writer other than itself that sets those labels. No waypoint was ever created. Rs now owns static Gateways and usesspec.infrastructurefor what it wants propagated.
One question is still open. During the black-holed cart replica (100 % packet loss for 25 s), one run showed a 30 s failure burst before Rs and 3.6 s after it, and the next run showed none before and 27.5 s after. My working hypothesis is that connections to the dead replica wait out the connect timeout before the waypoint can retry or eject it, because ejection needs three consecutive gateway errors on the same host. That is the next thing to read in the Envoy response flags.
The source isn't public yet, so the snippets here are trimmed excerpts rather than links. It goes public once the thesis ships. Until then it works on my machine, and my machine is the whole cluster.