Ground Holmes storage investigation in PVC identity
Homelab Main / validate (push) Failing after 2m7s Details
Homelab Main / running-update (push) Has been skipped Details
Homelab Main / debian-ops (push) Has been skipped Details

This commit is contained in:
juvenal.diaz 2026-11-14 23:15:13 -06:00
parent b9347cf5c8
commit 1b0ec22fb8
6 changed files with 155 additions and 3 deletions

View File

@ -47,6 +47,8 @@ read-only checks; any suggested remediation should be reviewed separately.
For a selected Kubernetes application, Doctor also reads up to five pods selected
by each deployment's simple match-label selector and the latest pod events.
For each selected pod it identifies the controller, up to three PVCs, and their
bound PV names and local or host paths without reading application secrets.
For a container in CrashLoopBackOff with a previous restart, it also requests
bounded previous-container logs, and reports when those logs are unavailable.
For a pod on the configured native K3s control-plane node, it also attempts a
@ -120,6 +122,11 @@ additional request with a shorter prompt. It forwards the reply only if it is
one schema-valid Bash call containing a single read-only `kubectl get` command.
It does not invent a call from the prose or force a tool after tool history
exists. Subsequent Holmes actions retain the permissions described above.
If a final response only copies or summarizes a Kubernetes resource after a
tool call, without a full diagnosis, mitigation and validation, the adapter
asks once for the next read-only PVC or PV check using names in the evidence.
Only a schema-valid, single `kubectl get` call is forwarded, and a named PVC or
PV must match the corresponding name in the collected mapping.
If the model immediately repeats an identical Bash command, the adapter asks it
once to continue using the previous result. If it repeats again, Doctor stops
the investigation and reports it as incomplete rather than rerunning it.

View File

@ -269,7 +269,7 @@ doctor_focus_application_lookup() {
}
doctor_focus_application_evidence() {
local name="$1" snapshot deployments namespace deployment state selector pods pod container identity uid node count=0 failed=0
local name="$1" snapshot deployments namespace deployment state selector pods pod container identity uid node claim claim_json volume volume_json count=0 failed=0
snapshot="$(report_ui_cached_probe doctor_focus_application_fetch "${name}")" || return 1
printf '$ kubectl --kubeconfig %q --request-timeout=10s -n argocd get application %q --ignore-not-found -o json | python3 %q\n' "${KUBECONFIG_PATH}" "${name}" "${REPO_ROOT}/scripts/doctor-application.py"
printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" || return 1
@ -287,6 +287,20 @@ doctor_focus_application_evidence() {
printf '%s' "${pods}" | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" pods || failed=1
while read -r pod; do
[[ -n "${pod}" ]] || continue
while read -r claim; do
[[ -n "${claim}" ]] || continue
printf '$ kubectl --kubeconfig %q --request-timeout=10s -n %q get pvc %q -o json | python3 %q pvc-summary\n' "${KUBECONFIG_PATH}" "${namespace}" "${claim}" "${REPO_ROOT}/scripts/doctor-pod-evidence.py"
if claim_json="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" get pvc "${claim}" -o json 2>/dev/null)"; then
printf '%s' "${claim_json}" | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" pvc-summary || failed=1
volume="$(printf '%s' "${claim_json}" | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" pvc-volume 2>/dev/null)" || volume=""
if [[ -n "${volume}" ]]; then
printf '$ kubectl --kubeconfig %q --request-timeout=10s get pv %q -o json | python3 %q pv-summary\n' "${KUBECONFIG_PATH}" "${volume}" "${REPO_ROOT}/scripts/doctor-pod-evidence.py"
if volume_json="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s get pv "${volume}" -o json 2>/dev/null)"; then
printf '%s' "${volume_json}" | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" pv-summary || failed=1
else echo "Persistent volume evidence unavailable."; failed=1; fi
else echo "PVC volume identity unavailable."; fi
else echo "PVC evidence unavailable."; failed=1; fi
done < <(printf '%s' "${pods}" | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" pvc-names "${pod}")
identity="$(printf '%s' "${pods}" | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" identity "${pod}" 2>/dev/null)" || identity=""
read -r uid node <<<"${identity}"
if [[ "${LAB_CLUSTER_PROFILE:-}" == k3s && -n "${uid}" && "${node}" == "${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME:-}" && -n "${LAB_PIMOX_HOST:-}" && -n "${LAB_PIMOX_USER:-}" ]]; then

View File

@ -25,6 +25,22 @@ def main():
print("Previous container logs were empty.")
return
data = json.load(sys.stdin)
if mode in ("pvc-summary", "pvc-volume", "pv-summary"):
meta, spec = data.get("metadata") or {}, data.get("spec") or {}
if mode == "pvc-volume":
volume = spec.get("volumeName", "")
if re.fullmatch(r"[a-z0-9]([-a-z0-9.]*[a-z0-9])?", volume):
print(volume)
elif mode == "pvc-summary":
print("pvc", clean(meta.get("name", "unknown")), "phase=" + clean((data.get("status") or {}).get("phase", "unknown")),
"pv=" + clean(spec.get("volumeName", "unknown")), "storage_class=" + clean(spec.get("storageClassName", "unknown")))
else:
path = (spec.get("local") or {}).get("path") or (spec.get("hostPath") or {}).get("path") or "not local or hostPath"
claim = spec.get("claimRef") or {}
print("pv", clean(meta.get("name", "unknown")), "path=" + clean(path),
"claim=" + clean(claim.get("namespace", "unknown")) + "/" + clean(claim.get("name", "unknown")),
"phase=" + clean((data.get("status") or {}).get("phase", "unknown")))
return
items = data.get("items")
if not isinstance(items, list):
raise ValueError("missing items")
@ -33,6 +49,18 @@ def main():
name = (pod.get("metadata") or {}).get("name", "")
if re.fullmatch(r"[a-z0-9]([-a-z0-9.]*[a-z0-9])?", name):
print(name)
elif mode == "pvc-names":
selected = sys.argv[2]
for pod in items[:5]:
if (pod.get("metadata") or {}).get("name") != selected:
continue
names = []
for volume in (pod.get("spec") or {}).get("volumes") or []:
claim = (volume.get("persistentVolumeClaim") or {}).get("claimName", "")
if re.fullmatch(r"[a-z0-9]([-a-z0-9.]*[a-z0-9])?", claim) and claim not in names:
names.append(claim)
for name in names[:3]:
print(name)
elif mode == "identity":
selected = sys.argv[2]
for pod in items[:5]:
@ -62,6 +90,9 @@ def main():
for pod in items[:5]:
status = pod.get("status") or {}
print("pod", clean((pod.get("metadata") or {}).get("name", "unknown")), "phase=" + clean(status.get("phase", "unknown")))
for owner in ((pod.get("metadata") or {}).get("ownerReferences") or []):
if owner.get("controller") is True:
print("controller", clean(owner.get("kind", "unknown")), clean(owner.get("name", "unknown")))
for container in (status.get("initContainerStatuses") or []) + (status.get("containerStatuses") or []):
state = container.get("state") or {}
current = state.get("waiting") or state.get("terminated") or {}

View File

@ -46,7 +46,7 @@ def translate(result, tools):
return result
def safe_initial_call(message, tools):
def safe_initial_call(message, tools, context=""):
calls = message.get("tool_calls")
if not isinstance(calls, list) or len(calls) != 1:
return False
@ -64,6 +64,14 @@ def safe_initial_call(message, tools):
return False
if any(word.startswith(("--raw", "--watch", "--server", "--token")) for word in words):
return False
pos = words.index("get")
if pos + 2 < len(words) and not words[pos + 2].startswith("-"):
resource, target = words[pos + 1].lower(), words[pos + 2]
pairs = re.findall(r"\bpvc\s+([a-z0-9][a-z0-9.-]*)\s+(?:phase=\S+\s+pv=|is\s+bound\s+to\s+pv\s+)([a-z0-9][a-z0-9.-]*)", context, re.IGNORECASE)
if resource in ("pvc", "pvcs", "persistentvolumeclaim", "persistentvolumeclaims") and target not in {x[0] for x in pairs}:
return False
if resource in ("pv", "pvs", "persistentvolume", "persistentvolumes") and target not in {x[1] for x in pairs}:
return False
return validated is not None
except (ValueError, TypeError, KeyError, AttributeError):
return False
@ -88,6 +96,30 @@ def same_as_last_call(message, history):
return False
def is_resource_extract(message):
content = message.get("content")
if message.get("tool_calls") or not isinstance(content, str):
return False
text = content.strip()
fenced = re.fullmatch(r"```(?:json)?[ \t]*\r?\n(.*?)\r?\n```", text, re.IGNORECASE | re.DOTALL)
try:
data = json.loads(fenced.group(1) if fenced else text, object_pairs_hook=adapter.unique_object)
except (ValueError, TypeError):
return (len(text) >= 100 and bool(re.search(r"\b(pod|container|deployment|persistentvolume|pvc)\b", text, re.IGNORECASE))
and not all(re.search(r"\b" + name + r"\b", text, re.IGNORECASE)
for name in ("diagnosis", "mitigation", "validation")))
if not isinstance(data, dict):
return False
report_keys = {"diagnosis", "root_cause", "mitigation", "validation", "observed_facts"}
resource_keys = {"metadata", "apiVersion", "kind", "containerPort", "volumeMounts", "image", "status"}
if report_keys.intersection(data):
return False
if set(data) == {"response"} and isinstance(data["response"], str):
return not all(re.search(r"\b" + name + r"\b", data["response"], re.IGNORECASE)
for name in ("diagnosis", "mitigation", "validation"))
return bool(resource_keys.intersection(data))
def complete(request, bash_mode):
"""Retry an initial prose-only answer once; never fabricate a tool call."""
result = translate(query_ollama(request), request.get("tools", []))
@ -111,11 +143,26 @@ def complete(request, bash_mode):
"Return only a JSON object with name bash and arguments containing command and suggested_prefixes. "
"Do not modify resources in this first check."}]
retried = translate(query_ollama(retry), request["tools"])
accepted = safe_initial_call(retried["choices"][0]["message"], request["tools"])
accepted = safe_initial_call(retried["choices"][0]["message"], request["tools"], users[-1]["content"])
print("initial_retry", "tool_call=" + str(bool(retried["choices"][0]["message"].get("tool_calls"))), "accepted=" + str(accepted), flush=True)
if accepted:
return retried
message = result["choices"][0]["message"]
if bash_mode and request.get("tools") and any(isinstance(m, dict) and m.get("role") == "tool" for m in messages) and is_resource_extract(message):
users = [m for m in messages if isinstance(m, dict) and m.get("role") == "user" and isinstance(m.get("content"), str)]
if users:
retry = dict(request)
retry["messages"] = [{"role": "system", "content": "Use the bash tool to perform one read-only Kubernetes check using real resource names."}, users[-1],
{"role": "user", "content": "Your last answer only copied a Kubernetes resource; investigation is not finished. "
"Use the actual pod, PVC and PV names in the provided context. Call bash for a single targeted kubectl get "
"check. In an evidence line 'pvc CLAIM phase=... pv=VOLUME', get pvc must use CLAIM; get pv must use VOLUME. "
"Do not use placeholders, pipes, shell operators, or mutate resources. "
"Return only a JSON tool call with command and suggested_prefixes."}]
retried = translate(query_ollama(retry), request["tools"])
accepted = safe_initial_call(retried["choices"][0]["message"], request["tools"], users[-1]["content"])
print("resource_extract_retry", "accepted=" + str(accepted), flush=True)
if accepted and not same_as_last_call(retried["choices"][0]["message"], messages):
return retried
if bash_mode and same_as_last_call(message, messages):
retry = dict(request)
retry["messages"] = messages + [{"role": "user", "content":

View File

@ -405,6 +405,24 @@ doctor_runner_report
pod["metadata"]["uid"] = "bad;touch /tmp/x"
self.assertEqual(run().stdout, "")
def test_pod_volume_evidence_identifies_claim_and_backing_path(self):
script = str(ROOT / "scripts/doctor-pod-evidence.py")
pod = {"metadata": {"name": "n8n-pod", "ownerReferences": [{"controller": True, "kind": "ReplicaSet", "name": "n8n-123"}]},
"spec": {"volumes": [{"persistentVolumeClaim": {"claimName": "n8n-data"}}, {"secret": {"secretName": "hidden"}}]}, "status": {"phase": "Running"}}
result = subprocess.run([sys.executable, script, "pvc-names", "n8n-pod"], input=json.dumps({"items": [pod]}),
capture_output=True, text=True, check=True)
self.assertEqual(result.stdout.strip(), "n8n-data")
result = subprocess.run([sys.executable, script, "pods"], input=json.dumps({"items": [pod]}),
capture_output=True, text=True, check=True)
self.assertIn("controller ReplicaSet n8n-123", result.stdout)
self.assertNotIn("hidden", result.stdout)
pvc = {"metadata": {"name": "n8n-data"}, "spec": {"volumeName": "pvc-123", "storageClassName": "local"}, "status": {"phase": "Bound"}}
result = subprocess.run([sys.executable, script, "pvc-summary"], input=json.dumps(pvc), capture_output=True, text=True, check=True)
self.assertIn("pvc n8n-data phase=Bound pv=pvc-123", result.stdout)
pv = {"metadata": {"name": "pvc-123"}, "spec": {"local": {"path": "/data/pv"}, "claimRef": {"namespace": "n8n", "name": "n8n-data"}}, "status": {"phase": "Bound"}}
result = subprocess.run([sys.executable, script, "pv-summary"], input=json.dumps(pv), capture_output=True, text=True, check=True)
self.assertIn("path=/data/pv claim=n8n/n8n-data", result.stdout)
def test_crash_log_preserves_exception_and_stack_tail(self):
script = str(ROOT / "scripts/doctor-pod-evidence.py")
lines = ["Error: read-only filesystem"] + [f"stack line {i}" for i in range(12)]

View File

@ -63,6 +63,28 @@ class ToolAdapterTests(unittest.TestCase):
PROXY.complete(request, True)
self.assertEqual(query.call_count, 1)
def test_resource_echo_prompts_one_valid_next_read_only_check(self):
tools = [{"type": "function", "function": {"name": "bash", "parameters": {
"type": "object", "properties": {"command": {"type": "string"},
"suggested_prefixes": {"type": "array", "items": {"type": "string"}}},
"required": ["command", "suggested_prefixes"]}}}]
previous = {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": "kubectl -n n8n get pod n8n", "suggested_prefixes": ["kubectl"]})}}]}
request = {"tools": tools, "messages": [{"role": "user", "content": "pvc n8n-data phase=Bound pv=pvc-123"}, previous, {"role": "tool", "content": "pod output"}]}
echo = {"choices": [{"message": {"role": "assistant", "content": '{"name":"n8n","image":"n8n:2"}'}, "finish_reason": "stop"}]}
next_call = {"choices": [{"message": {"role": "assistant", "content": json.dumps({"name": "bash", "arguments": {
"command": "kubectl -n n8n get pvc n8n-data", "suggested_prefixes": ["kubectl"]}})}, "finish_reason": "stop"}]}
with patch.object(PROXY, "query_ollama", side_effect=[echo, next_call]) as query:
result = PROXY.complete(request, True)
self.assertEqual(query.call_count, 2)
self.assertEqual(result["choices"][0]["message"]["tool_calls"][0]["function"]["name"], "bash")
def test_complete_json_diagnosis_is_not_treated_as_resource_echo(self):
self.assertFalse(PROXY.is_resource_extract({"content": '{"status":"bad","diagnosis":"disk"}'}))
self.assertTrue(PROXY.is_resource_extract({"content": '{"response":"Pod is crashing."}'}))
self.assertFalse(PROXY.is_resource_extract({"content": '{"response":"Diagnosis: disk. Mitigation: none. Validation: failed."}'}))
self.assertTrue(PROXY.is_resource_extract({"content": "The pod is running an application and has a container image. " * 3}))
self.assertFalse(PROXY.is_resource_extract({"content": "Diagnosis: bad pod. Mitigation: none. Validation: unavailable."}))
def test_retry_cannot_turn_a_plan_into_a_mutating_command(self):
tools = [{"type": "function", "function": {"name": "bash", "parameters": {
"type": "object", "properties": {"command": {"type": "string"},
@ -73,6 +95,19 @@ class ToolAdapterTests(unittest.TestCase):
"command": command, "suggested_prefixes": ["kubectl"]})}}]}
self.assertFalse(PROXY.safe_initial_call(message, tools))
def test_pvc_and_pv_names_must_match_the_evidence(self):
tools = [{"type": "function", "function": {"name": "bash", "parameters": {
"type": "object", "properties": {"command": {"type": "string"},
"suggested_prefixes": {"type": "array", "items": {"type": "string"}}},
"required": ["command", "suggested_prefixes"]}}}]
context = "pvc n8n-data phase=Bound pv=pvc-123 storage_class=local"
def call(command):
return {"tool_calls": [{"function": {"name": "bash", "arguments": json.dumps({"command": command, "suggested_prefixes": ["kubectl"]})}}]}
self.assertTrue(PROXY.safe_initial_call(call("kubectl -n n8n get pvc n8n-data"), tools, context))
self.assertTrue(PROXY.safe_initial_call(call("kubectl get pv pvc-123"), tools, context))
self.assertFalse(PROXY.safe_initial_call(call("kubectl -n n8n get pvc pvc-123"), tools, context))
self.assertFalse(PROXY.safe_initial_call(call("kubectl get pv n8n-data"), tools, context))
def test_repeated_command_is_not_forwarded_after_one_retry(self):
args = json.dumps({"command": "printf hello", "suggested_prefixes": ["printf"]})
previous = {"role": "assistant", "tool_calls": [{"function": {"name": "bash", "arguments": args}}]}