Skip to content

fix: preserve external annotations on reconciler Deployment updates#468

Merged
Defilan merged 5 commits into
defilantech:mainfrom
Defilan:fix/router-proxy-preserve-annotations
May 14, 2026
Merged

fix: preserve external annotations on reconciler Deployment updates#468
Defilan merged 5 commits into
defilantech:mainfrom
Defilan:fix/router-proxy-preserve-annotations

Conversation

@Defilan
Copy link
Copy Markdown
Member

@Defilan Defilan commented May 14, 2026

What

Two related fixes that together make 0.7.8 ship-ready for the audience watching Marcel's video.

Fix 1: preserve external pod-template annotations on reconcile (closes #456)

Both the ModelRouter and the InferenceService reconcilers were replacing the pod template wholesale:

existing.Spec.Template = desired.Spec.Template  // router_deployment_builder.go
existingDeployment.Spec = deployment.Spec       // inferenceservice_controller.go

That stripped every annotation an external actor set on the pod template: sidecar injectors (Istio, Linkerd), kubectl rollout restart's kubectl.kubernetes.io/restartedAt, GitOps tool sync labels. The visible symptom was a kubectl rollout restart spinning two ReplicaSets that flap against each other while the controller's reconcile fought kubectl's annotation, and in-flight requests got truncated.

Fixed by adding a mergePreservingExternal(existing, desired) helper. Operator-owned keys win on collision; foreign keys pass through. Spec replacement otherwise stays wholesale so the existing config-hash rollout mechanism keeps working.

Fix 2: drop BlockOwnerDeletion on operator-managed children

While running the MicroShift / MINC lane, PR #466's improved diagnostics surfaced a real flake:

deployments.apps "scc-test-inference" is forbidden:
  cannot set blockOwnerDeletion in this case because cannot find
  RESTMapping for APIVersion inference.llmkube.dev/v1alpha1
  Kind InferenceService: no matches for kind "InferenceService"

controller-runtime's SetControllerReference sets BlockOwnerDeletion=true by default. The kube-apiserver GarbageCollector admission plugin validates that flag by RESTMapping the owner Kind to check the caller's update permission on the owner's finalizers subresource. On kind the API server's discovery cache is warm by the time the controller starts. On MicroShift-in-MINC, the in-container apiserver populates discovery lazily on first request and the controller's first reconcile races it and loses.

LLMKube doesn't need BlockOwnerDeletion. Cascading delete still cleans up operator-managed children when their parent CR is deleted; the "block" semantics only matter for finalizer-based cleanup workflows we don't use. Trade-off: cleaner bootstrap for slightly looser cascade ordering guarantees we weren't relying on.

Fixed by a new setControllerReferenceUnblocked helper that wraps controllerutil.SetControllerReference and clears BlockOwnerDeletion on the owner reference. Applied to all 9 call sites: router Deployment/Service/ConfigMap reconcilers, InferenceService Deployment/Service reconcilers, and the HPA reconciler.

Why

#456 is filed today and is a real ergonomic / correctness problem for any cluster running a service mesh, ArgoCD, or kubectl rollout-restart. The MicroShift flake has been blocking CI signal across multiple recent PRs (#464, #466, this one). Marcel Dempers' YouTube video is driving traffic right now; the operator needs to behave predictably for first-time users on real clusters before we cut 0.7.8.

Fixes #456.

How

Annotation preservation:

  • New helper mergePreservingExternal in internal/controller/merge.go
  • Both reconcilers now call it on the pod-template labels + annotations, plus the router-proxy's top-level Deployment labels
  • Spec replacement is otherwise unchanged so the existing config-hash rollout mechanism keeps working

BlockOwnerDeletion:

  • New helper setControllerReferenceUnblocked in internal/controller/ownerref.go
  • Wraps controllerutil.SetControllerReference, then walks the resulting owner refs and clears BlockOwnerDeletion on the one we just installed
  • All 9 controller call sites switched over

Coverage:

  • TestMergePreservingExternal — helper unit test (4 cases)
  • TestSetControllerReferenceUnblocked — verifies the resulting owner ref has Controller=true and BlockOwnerDeletion=false
  • TestReconcileRouterDeploymentPreservesExternalAnnotations — full fake-client integration test for the annotation fix
  • New e2e step: should preserve external pod-template annotations across reconciles (#456) in the ModelRouter Reconciliation Context patches the proxy Deployment with sidecar/kubectl-rollout-restart annotations, bumps spec.proxy.replicas to force reconcile, then Eventually-asserts the external annotations survive AND the operator-owned config-hash annotation is also still present
  • Local: make lint, make test, go vet -tags=e2e ./test/e2e/... all clean

Checklist

  • Tests added (merge_test.go, ownerref_test.go, router_builders_test.go integration test, new e2e step)
  • go test ./internal/controller/... passes locally
  • make lint passes locally
  • Commit messages follow conventional commits (4 commits: fix:, docs(site):, fix(lint):, test(e2e):, fix: for BlockOwnerDeletion)
  • All commits are signed off (git commit -s) per DCO
  • Documentation updated (Phase 1 limitations callout in concepts/model-router.md)

Defilan added 2 commits May 13, 2026 23:23
Both the ModelRouter and the InferenceService reconcilers updated
their managed Deployment by replacing the pod template wholesale:

  // router_deployment_builder.go
  existing.Spec.Template = desired.Spec.Template
  existing.Labels        = desired.Labels

  // inferenceservice_controller.go
  existingDeployment.Spec = deployment.Spec

That strips every annotation an external actor set on the pod
template: sidecar injectors (Istio, Linkerd), `kubectl rollout
restart`'s `kubectl.kubernetes.io/restartedAt`, GitOps tool sync
labels. The most visible symptom is a `kubectl rollout restart`
spinning two ReplicaSets that flap against each other as the
controller's reconcile fights kubectl's annotation, and in-flight
requests get truncated.

Fix it the same way in both places: a small helper that merges
operator-owned keys over external keys (desired wins on collision,
foreign keys pass through). Spec replacement otherwise stays
wholesale so the existing rollout-on-config-hash mechanism keeps
working.

Coverage:
- mergePreservingExternal unit test (4 cases: empty/desired-only/
  external-only/collision)
- New router-proxy reconcile test exercising the end-to-end fix
  through the fake client: seed a Deployment carrying both
  operator-owned and externally-set annotations, run
  reconcileRouterDeployment with a new config hash, assert the
  operator's hash advances AND every external key on the pod
  template + top-level Deployment metadata survives

Also lands a "Phase 1 limitations" section in the ModelRouter
concept doc covering the three v1alpha1 gaps the release-readiness
audit surfaced: timeouts cap TTFT not stream duration, audit log
lacks token/byte metrics, inbound bodies are buffered. Framed as
v1alpha1 scope rather than apology so users running opencode /
Claude Code / Aider know where to put their safety nets without
filing a bug.

Fixes defilantech#456.

Signed-off-by: Christopher Maher <chris@mahercode.io>
The 0.7.8 release-readiness audit surfaced three honest gaps in
the Phase 1 router-proxy that show up under agentic-coding load:
TTFT-only timeouts (no stream-duration cap), coarse audit log
(no token/byte/stream-duration metrics), and buffered inbound
request bodies. Document them as v1alpha1 scope rather than
discover-during-incident so opencode / Claude Code / Aider users
know where to put their client-side safety nets and what's
planned for Phase 2.

Placement: own section between "What's in scope" and "Comparison
to alternatives". Cross-links defilantech#433 (token/byte metrics) for the
audit-log gap.

Signed-off-by: Christopher Maher <chris@mahercode.io>
@codecov
Copy link
Copy Markdown

codecov Bot commented May 14, 2026

Defilan added 3 commits May 13, 2026 23:38
CI lint surfaced four issues on the prior commit:

* QF1008 ×3 in inferenceservice_controller.go and
  router_deployment_builder.go: PodTemplateSpec embeds ObjectMeta,
  so `.Spec.Template.ObjectMeta.Labels` and friends collapse to
  `.Spec.Template.Labels`. Same semantics, less noise.

* goconst ×1 in router_builders_test.go: the new test used the
  literal `"llmkube"` twice for an `argocd.argoproj.io/instance`
  value, which combined with the existing production usage in
  router_common.go tripped goconst's 3-occurrence threshold. The
  test fixture doesn't need to share that string with production;
  switched to `"coding-router-fleet"` and pulled it into a local
  const so future drift is at least localized.

No behavior change; lint-only.

Signed-off-by: Christopher Maher <chris@mahercode.io>
…unit tests

The unit + fake-client tests in this PR catch any regression of the
mergePreservingExternal path, but the kind-cluster merge gate had no
coverage for the user-visible symptom of defilantech#456 (external pod-template
annotations stomped by a wholesale Spec.Template replace). Add a real
e2e step inside the existing ModelRouter Reconciliation Context that:

1. Reuses the e2e-good-router proxy Deployment the previous test
   already stood up.
2. Patches the Deployment's pod template with the two annotations
   real-world users hit: sidecar.istio.io/inject (Istio sidecar
   injector) and kubectl.kubernetes.io/restartedAt (`kubectl rollout
   restart`).
3. Forces a controller reconcile by bumping spec.proxy.replicas on
   the ModelRouter from 1 to 2 (the controller's watch on ModelRouter
   guarantees a Reconcile() cycle that walks reconcileRouterDeployment).
4. Waits for spec.replicas to be 2 on the Deployment (proves the
   reconcile actually ran).
5. Asserts the two external annotations are still present AND the
   operator-owned config-hash annotation is also still present (so
   we know we're not accidentally preserving external keys at the
   cost of operator keys).

Without the fix this It block fails at step 5; with the fix it
passes. The kind merge gate will now block any regression at PR
time instead of only catching it via the unit / fake-client suite.

The test runs in the same Context as the existing reconcile and
validation tests, so it adds no new namespace / fixture setup
overhead. ~30s additional runtime.

Signed-off-by: Christopher Maher <chris@mahercode.io>
The MicroShift / MINC e2e lane has been flaking on the OpenShift SCC
admission test with a confusing error that PR defilantech#466's improved
diagnostics finally surfaced:

  deployments.apps "scc-test-inference" is forbidden:
    cannot set blockOwnerDeletion in this case because cannot find
    RESTMapping for APIVersion inference.llmkube.dev/v1alpha1
    Kind InferenceService:
    no matches for kind "InferenceService" in version
    "inference.llmkube.dev/v1alpha1"

Trace: controller-runtime's controllerutil.SetControllerReference sets
BlockOwnerDeletion=true by default. The kube-apiserver
GarbageCollector admission plugin validates that flag by RESTMapping
the owner Kind to check the caller's `update` permission on the
owner's `finalizers` subresource. On kind the API server's discovery
cache is warm by the time the controller starts; on MicroShift-in-
MINC, the in-container apiserver populates discovery lazily on first
request, and the controller's first reconcile races it and loses.

We do not need BlockOwnerDeletion. Cascading delete still cleans up
operator-managed Deployments/Services/ConfigMaps/HPAs when their
parent ModelRouter or InferenceService is deleted; the "block"
semantics only matter for finalizer-based cleanup workflows LLMKube
does not use. Trade: cleaner bootstrap for slightly looser cascade
ordering guarantees we weren't relying on.

Fix: new setControllerReferenceUnblocked helper that wraps
controllerutil.SetControllerReference and clears BlockOwnerDeletion
on the owner ref it just installed. Applied to all 9 call sites in
the controller package (router deployment / service / configmap, both
InferenceService and ModelRouter reconcilers, HPA reconciler).

Coverage: TestSetControllerReferenceUnblocked verifies the resulting
owner ref has Controller=true and BlockOwnerDeletion=false. Existing
tests in router_builders_test.go and modelrouter_controller_test.go
continue to pass — the change is in the metadata, not the spec.

Side benefit: removes the controllerutil import from five files that
no longer need it.

Signed-off-by: Christopher Maher <chris@mahercode.io>
@Defilan Defilan merged commit de580c1 into defilantech:main May 14, 2026
21 checks passed
@github-actions github-actions Bot mentioned this pull request May 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] ModelRouter controller overwrites pod template annotations on reconcile

1 participant