Skip to content

refactor(k8s): KubernetesService is the Kubernetes API seam, with a shared fake cluster and its contract suite #1315

Description

@dan-petty

Problem

  • One service and other loaders. KubernetesService [code: src/devops_cli/k8s/service.py:55] is a process singleton (get_instance :76, reset_instance :83) that loads the kubeconfig (load_config :96) and caches API clients. Three functions load configuration and build clients on their own: _kube_configuration [code: k8s/service_proxy.py:159], get_k8s_client [code: k8s/doctor.py:627] and _get_k8s_client [code: ui/data_providers.py:146]. commands/k8s/cluster_context.py reads and loads the kubeconfig itself (:41-43, :126-128) through the SDK modules _k8s_clients hands it [code: commands/k8s/cluster_runtime.py:27]. k8s/informer.py:100 and k8s/service_proxy.py:328 read the service's private _core_v1.
  • Tests patch the SDK. The 6 modules that import kubernetes all import it inside functions [measured: grep at 5c45b1e], so tests swap the package through sys.modules (tests/test_k8s_context_resolution.py, test_k8s_service_proxy.py, test_http_connection_pool.py) or patch its classes. tests/test_k8s_service.py patches the kubernetes.config loaders and the kubernetes.client classes ApiClient, CoreV1Api, AppsV1Api and VersionApi (:39-44), and the service's own load_config (:65, :78). The census counts about 80 patch sites at this edge [measured: census of 2026-10-07].
  • The one shared fake goes in through a private function. FakeCoreV1 [code: tests/k8s_fakes.py:196] is installed by patching ui.data_providers._get_k8s_client in 3 files (tests/test_k8s_models.py:383, test_ui_dashboard.py:51, test_ui_reactive.py:3351). Only tests/test_k8s_doctor.py passes it in as a parameter, through doctor.collect(core) [code: k8s/doctor.py:562]. Other tests build MagicMock API objects (test_k8s_service, test_argo_crd, test_argo) [measured: census].
  • kubectl, helm and minikube are processes, faked by the process fake of refactor(cli): one process runner owns execution, process groups and dry-run #775, not by this item.

Acceptance criteria

Seam

Fake and fixture

  • tests/support/fakes/kubernetes.py promotes FakeCoreV1 and its builders (pod, node, event, healthy_pod, crashlooping_pod, ...) from tests/k8s_fakes.py and covers every call in the Protocol: contexts, namespaces, nodes, pods, pod logs, events, services, deployments, custom objects and watch events. It answers a missing object with the SDK's ApiException and its status, can fail every call as an unreachable API server does, and records each call. tests/k8s_fakes.py is deleted; its five importers change only their import.
  • A fixture installs the fake through the service's hook and returns it, registered once from the root conftest.

Contract suite

  • One suite in tests/k8s/ runs each Protocol call against the fake and against the real kubernetes client, the real side reading recorded API responses from a loopback server the test owns, through a kubeconfig under tmp_path. Cases: list and read results; a 404 and a 403, raising ApiException with the same status on both sides; a watch stream; and an unreachable server (a loopback port nothing listens on), raising the same error on both sides.
  • (person-run) The recorded responses are captured once from a disposable local cluster, scrubbed to example.com hosts and documentation-range addresses, and committed under tests/fixtures/kubernetes/ with the commands that captured them.

Migration

Key questions

  • Fake the SDK's API objects or the service? Decided 2026-10-07: FakeCoreV1, a fake of the SDK's CoreV1Api, is promoted. (proposed) The other API objects are faked at the same level, so the service's caching, context resolution and projections run for real in every test.
  • A live cluster for the real side? Decided 2026-10-07: never; the real side runs against recorded responses or a local tool (Q26).
  • What about kubectl, helm and minikube? Decided 2026-10-07: they are process edges, faked by the process fake (refactor(cli): one process runner owns execution, process groups and dry-run #775) (Q23).
  • Fixture name? (proposed) cluster.

Strategic alignment

Proposed design

Problem statement

KubernetesService is a process singleton that loads Kubernetes configuration and caches API clients. Five other code paths load configuration and build clients independently with conflicting rules. Tests patch the kubernetes SDK at about 80 sites. The shared fake, FakeCoreV1, is installed through a private function. This item makes KubernetesService the single seam for all Kubernetes API access. It promotes the fake into a shared test module and adds a contract suite that validates the fake against the real client.

Acceptance criteria

  • Criterion 1: KubernetesService loads Kubernetes configuration and supplies API objects (core, apps, custom objects, version) and kubeconfig contexts through a Protocol in k8s/.
    Verification: A Protocol type in src/devops_cli/k8s/ names every call devops-cli makes. The service's public methods satisfy the Protocol.
  • Criterion 2: Public accessors replace the private _core_v1 reads at k8s/informer.py:100 and k8s/service_proxy.py:328.
    Verification: No module in src/devops_cli/ reads a private attribute of KubernetesService. A grep for '_core_v1' outside service.py returns no hits in src/devops_cli/.
  • Criterion 3: A hook on the service installs a fake as the source of API objects, and the fixture removes it at teardown through reset_instance.
    Verification: A test installs the fake through the hook, calls a Protocol method, and receives the fake's response. After teardown, the service returns its real client.
  • Criterion 4: tests/support/fakes/kubernetes.py contains FakeCoreV1 and its builders and covers every Protocol call.
    Verification: tests/k8s_fakes.py does not exist. The five importers of tests/k8s_fakes.py import from tests/support/fakes/kubernetes.py.
  • Criterion 5: The fake answers a missing object with ApiException and its status, can fail every call as an unreachable server does, and records each call.
    Verification: A test calls read_namespaced_pod for a missing pod and asserts ApiException with status 404. A test sets unreachable mode and asserts every call raises. A test calls list_node and asserts the call log contains the entry.
  • Criterion 6: A fixture named cluster installs the fake through the service's hook and returns it, registered once from the root conftest.
    Verification: The root conftest.py registers the fixture. A test using the fixture receives a FakeCoreV1 instance.
  • Criterion 7: A contract suite in tests/k8s/ runs each Protocol call against the fake and against the real kubernetes client reading from a loopback server.
    Verification: The suite includes cases for list, read, 404, 403, watch stream, and unreachable server. Both sides raise ApiException with the same status for 404 and 403.
  • Criterion 8: tests/test_k8s_service.py drives the service through the fake or the contract suite and patches no kubernetes name and no method of the service.
    Verification: A grep for 'patch' combined with 'kubernetes' in tests/test_k8s_service.py returns no hits for SDK patches. The file imports from tests/support/fakes/kubernetes.py.
  • Criterion 9: The seam owns one configuration rule: use the kubeconfig when it names the resolved context, else in-cluster. Each ApiClient is built with its own Configuration.
    Verification: KubernetesService.load_config uses new_client_from_config(context=...) or load_incluster_config(client_configuration=...). No client writes to the global default Configuration.
  • Criterion 10: switch_context does not rewrite the kubeconfig file. The in-process client realigns by rebuilding its ApiClient for the new context.
    Verification: A test calls switch_context and asserts the kubeconfig file content is unchanged. The service's ApiClient is rebuilt for the new context.
  • Criterion 11: Tests run offline and each new test runs under 1 second.
    Verification: uv run pytest tests/k8s/ --durations=10 shows no test exceeding 1 second. No test opens a network connection.
  • Criterion 12: uv run devops ci passes.
    Verification: The CI pipeline completes with all checks green.

Key questions

  • Fake the SDK's API objects or the service?: FakeCoreV1, a fake of the SDK's CoreV1Api, is promoted. The other API objects are faked at the same level, so the service's caching, context resolution and projections run for real in every test. (proposed)
  • A live cluster for the real side?: Never. The real side runs against recorded responses or a local tool. (proposed)
  • What about kubectl, helm and minikube?: They are process edges, faked by the process fake in refactor(cli): one process runner owns execution, process groups and dry-run #775. (proposed)
  • Fixture name?: cluster. (proposed)

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

None.

Activity

  1. added
    type/refactor
    scope/k8s
    priority/p2-medium
    on Oct 7, 2026
  2. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Found by the 2026-10-08 client-library audit (05e9388). Two additions for the seam.

    Five client initializers with conflicting rules. Each loads configuration into the client's global default Configuration:

    1. KubernetesService.load_config (k8s/service.py:144-150): in-cluster first. Inside a pod the requested context is ignored, and the failure reason is only logged at debug (:160-163).
    2. _kube_configuration (k8s/service_proxy.py:177-185): in-cluster first as well.
    3. ui/data_providers.py:162-165: kubeconfig first whenever the kubeconfig names a context. Its docstring (:147-157) explains why in-cluster-first is wrong.
    4. k8s/doctor.py:627-635 (get_k8s_client): kubeconfig only, never in-cluster.
    5. commands/k8s/cluster_context.py:126-129: load_kube_config() with no context, so it ignores settings.k8s.context.

    Proposed: the seam owns one rule. Use the kubeconfig when it names the resolved context, else in-cluster. Each ApiClient is built with new_client_from_config(context=...) or load_incluster_config(client_configuration=...) into its own Configuration, not the global default.

    The kubeconfig rewrite.

    • KubernetesService.switch_context (k8s/service.py:212-259) rewrites the kubeconfig with yaml.safe_load/safe_dump.
    • It does so immediately after devops k8s context has already run kubectl config use-context (commands/k8s/cluster_context.py:97-107), so the file is written twice.
    • The second write drops comments.
    • It reads only the first KUBECONFIG entry (_get_kubeconfig_path), so a context in a later file fails (logged as a warning).

    Proposed: delete switch_context's file write. The in-process client realigns by rebuilding its ApiClient for the new context.

    The k8s:// proxy's auth headers and the informer's watch call are filed separately: fix(k8s): k8s:// service requests authenticate with the Kubernetes client's own auth settings, ....

  3. dan-petty-bot commented on Oct 8, 2026

    @dan-petty-bot
    Collaborator

    Intake placed this item to the backlog: at intake only a critical fix goes into a release; a release start pulls Ready items in, P0 features first.

    • Priority: P2-Medium. It improves maintainability and testability of a core module but does not fix a user-facing defect or unblock a release.
    • Value: Medium. It eliminates roughly 80 ad-hoc patch sites and private-attribute reads, making the k8s package far easier to test and extend, but does not add new user-facing capability.
    • Effort: High. It touches at least six modules, requires a new Protocol, a promoted fake covering every Protocol call, a root-conftest fixture, a contract suite with a loopback server, and coordination with three other items (#1322, #1323, #1334).
  4. dan-petty commented on Oct 26, 2026

    @dan-petty
    OwnerAuthor

    Intake placed this item to the backlog: intake puts every new item in the backlog. A person plans the milestones on the board.

    • Priority: P2-Medium. This change improves code organization and testability but is not critical for immediate functionality or security.
    • Value: High. Improves the overall architecture and makes testing more reliable by providing a clear seam for Kubernetes interactions.
    • Effort: High. Involves significant refactoring of multiple modules and creation of new fake implementations and contract tests.
    • Related: test(k8s): devops k8s commands are thin adapters tested over edge fakes, and the _K8sModule patch forwarding is gone #1323, which asks for a different change. Both items relate to Kubernetes testing and command handling, but the candidate focuses on creating a single seam while #1323 addresses command adapters and patch forwarding.
  5. dan-petty commented on Oct 28, 2026

    @dan-petty
    OwnerAuthor

    Status set to Ready at 69636b6 (see proposed design in issue body).

  6. added
    status/ready
    effort/high
    value/high
    on Oct 28, 2026
  7. added a commit that references this issue on Oct 28, 2026
  8. removed
    status/ready
    on Oct 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    effort/highpriority/p2-mediumscope/k8stype/refactorvalue/high

    Type

    No type

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions