prefect-kubernetes observer: _get_k8s_jobs raises UnboundLocalError when the Kubernetes client can't be created
Author: kratos0718Created Sep 27, 2026Updated Sep 27, 2026
Labelsbug
Bug summary
In the prefect-kubernetes observer, _get_k8s_jobs() has an except Exception that logs and returns [], but its finally always runs await client.close(). When _get_kubernetes_client() is the call that fails (no in-cluster config and no usable kubeconfig, for example), client was never assigned. The finally then raises UnboundLocalError and the [] fallback never reaches the caller in _mark_flow_run_as_crashed.
Reproduction on main (4f52bc6), run with uv run --project ./src/integrations/prefect-kubernetes:
import asyncio, logging
from unittest.mock import patch
from prefect_kubernetes import observer
async def main():
with patch.object(observer, "_get_kubernetes_client",
side_effect=RuntimeError("could not load kubeconfig")):
print(await observer._get_k8s_jobs("abc", "default", logging.getLogger("x")))
asyncio.run(main())Output:
ERROR | x - Failed to get jobs for flow run abc: could not load kubeconfig
Traceback (most recent call last):
...
File ".../prefect_kubernetes/observer.py", line 928, in _get_k8s_jobs
await client.close() # type: ignore
^^^^^^
UnboundLocalError: cannot access local variable 'client' where it is not associated with a valueSetting client = None before the try and only closing it when it is not None makes the function return [] as intended. I'm happy to open a PR with that change and a test if it sounds right.
Version info
Version: 3.8.7
API version: 0.8.4
Python version: 3.13.9
Git commit: 4f52bc6d
OS/Arch: darwin/arm64
Pydantic version: 2.13.5
Integrations:
prefect-kubernetes: 0.0.1.dev1+g4f52bc6d0Source: PrefectHQ/prefect