Compare commits

...

3 Commits

Author SHA1 Message Date
juvenal.diaz 099fa6ac0d Add isolated llama.cpp AI lab
Homelab Main / validate (push) Successful in 1m13s Details
Homelab Main / running-update (push) Successful in 3s Details
Homelab Main / debian-ops (push) Successful in 2m25s Details
2026-11-10 11:23:20 -06:00
juvenal.diaz 688fe9f0f0 Add progressive delivery failure lab 2026-11-10 10:43:35 -06:00
juvenal.diaz dd99af4f58 Add secret and certificate lifecycle lab 2026-11-10 10:37:54 -06:00
19 changed files with 1166 additions and 0 deletions

View File

@ -0,0 +1,4 @@
apiVersion: v2
name: progressive-lab
version: 0.1.0
description: Disposable canary and rollback learning lab

View File

@ -0,0 +1,41 @@
# Progressive delivery and failure lab
This disposable lab demonstrates a manual canary orchestrated by Jeannie and
Argo CD. A small internal router sends traffic to a stable or canary backend and
exposes Prometheus counters. The Argo CD Application's Helm values are the
runtime control for this experiment; Jeannie updates those values and Argo CD
reconciles the workloads. This is a learning implementation, not Argo Rollouts
or a production traffic manager.
Push the commit first. On Debian, select the cluster profile and run:
```sh
cd ~/my-homelab-configs
git pull --ff-only gitea main
./jeannie progressive-lab plan
./jeannie progressive-lab apply
./jeannie progressive-lab run errors
./jeannie progressive-lab run readiness
```
Each run directs approximately 10% of 120 requests to the canary, compares the
router's `progressive_lab_requests_total` counter before and after, and rolls
back when the expected canary error rate exceeds 10%. The `errors` scenario
returns HTTP 500 from the canary; `readiness` uses an intentionally failing
readiness probe, removing the canary endpoint and producing a router error.
The stable service should continue returning success. Jeannie restores the
canary weight to zero in a `finally` block, including on most command failures.
If Jeannie is interrupted or the API is unavailable, explicitly run:
```sh
./jeannie progressive-lab rollback
./jeannie progressive-lab status
```
The ServiceMonitor exposes router counters to the existing Prometheus stack if
its ServiceMonitor selectors include the `monitoring` namespace and the
`release=prometheus-stack` label. The experiment measures the same counters
directly, so a successful run does not by itself prove Prometheus scraped them.
The router is available only through its ClusterIP and temporary local port
forward; existing public routes are unchanged. It is deliberately simple and
does not implement production-grade retries, traffic management, or analysis.

View File

@ -0,0 +1,20 @@
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
code, body = 200, b"ready\n"
elif self.path == "/unready":
code, body = 503, b"deliberately unready\n"
elif os.environ.get("DEMO_FAIL") == "true":
code, body = 500, b"deliberate canary failure\n"
else:
code, body = 200, (os.environ["VERSION"] + "\n").encode()
self.send_response(code)
self.end_headers()
self.wfile.write(body)
ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()

View File

@ -0,0 +1,46 @@
import os
import random
import threading
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
weight = int(os.environ["CANARY_WEIGHT"])
counts = {(version, outcome): 0 for version in ("stable", "canary") for outcome in ("success", "error")}
lock = threading.Lock()
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health":
self.send_response(200)
self.end_headers()
return
if self.path == "/metrics":
with lock:
body = "# TYPE progressive_lab_requests_total counter\n" + "".join(
f'progressive_lab_requests_total{{version="{v}",outcome="{o}"}} {count}\n'
for (v, o), count in counts.items()
)
self.send_response(200)
self.send_header("Content-Type", "text/plain; version=0.0.4")
self.end_headers()
self.wfile.write(body.encode())
return
version = "canary" if random.randrange(100) < weight else "stable"
try:
with urllib.request.urlopen(f"http://progressive-{version}:8080/", timeout=2) as response:
code, body = response.status, response.read()
except urllib.error.HTTPError as exc:
code, body = exc.code, b"upstream error\n"
except (OSError, ValueError):
code, body = 503, b"upstream unavailable\n"
with lock:
counts[version, "success" if code < 500 else "error"] += 1
self.send_response(code)
self.send_header("X-Demo-Version", version)
self.end_headers()
self.wfile.write(body)
ThreadingHTTPServer(("0.0.0.0", 8080), Handler).serve_forever()

View File

@ -0,0 +1,106 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: progressive-lab-code
data:
backend.py: |
{{ .Files.Get "files/backend.py" | indent 4 }}
router.py: |
{{ .Files.Get "files/router.py" | indent 4 }}
---
{{- range $version := list "stable" "canary" }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: progressive-{{ $version }}
spec:
replicas: 1
strategy: {type: Recreate}
selector:
matchLabels: {app: progressive-{{ $version }}}
template:
metadata:
labels: {app: progressive-{{ $version }}}
annotations:
code-hash: {{ $.Files.Get "files/backend.py" | sha256sum | quote }}
spec:
automountServiceAccountToken: false
securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, seccompProfile: {type: RuntimeDefault}}
containers:
- name: app
image: python:3.12-alpine
command: ["python", "-B", "/app/backend.py"]
env:
- {name: VERSION, value: {{ $version | quote }}}
- {name: DEMO_FAIL, value: {{ and (eq $version "canary") $.Values.canaryFailure | quote }}}
ports: [{name: http, containerPort: 8080}]
readinessProbe:
httpGet:
path: {{ if and (eq $version "canary") $.Values.badReadiness }}/unready{{ else }}/health{{ end }}
port: http
periodSeconds: 3
resources:
requests: {cpu: 10m, memory: 32Mi}
limits: {memory: 128Mi}
securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}}
volumeMounts: [{name: code, mountPath: /app, readOnly: true}]
volumes: [{name: code, configMap: {name: progressive-lab-code}}]
---
apiVersion: v1
kind: Service
metadata:
name: progressive-{{ $version }}
spec:
selector: {app: progressive-{{ $version }}}
ports: [{name: http, port: 8080, targetPort: http}]
---
{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
name: progressive-router
spec:
replicas: 1
selector:
matchLabels: {app: progressive-router}
template:
metadata:
labels: {app: progressive-router}
annotations:
code-hash: {{ .Files.Get "files/router.py" | sha256sum | quote }}
spec:
automountServiceAccountToken: false
securityContext: {runAsNonRoot: true, runAsUser: 65532, runAsGroup: 65532, seccompProfile: {type: RuntimeDefault}}
containers:
- name: router
image: python:3.12-alpine
command: ["python", "-B", "/app/router.py"]
env: [{name: CANARY_WEIGHT, value: {{ .Values.canaryWeight | quote }}}]
ports: [{name: http, containerPort: 8080}]
readinessProbe: {httpGet: {path: /health, port: http}}
resources:
requests: {cpu: 10m, memory: 32Mi}
limits: {memory: 128Mi}
securityContext: {allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, capabilities: {drop: [ALL]}}
volumeMounts: [{name: code, mountPath: /app, readOnly: true}]
volumes: [{name: code, configMap: {name: progressive-lab-code}}]
---
apiVersion: v1
kind: Service
metadata:
name: progressive-router
labels: {app: progressive-router}
spec:
selector: {app: progressive-router}
ports: [{name: http, port: 8080, targetPort: http}]
---
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: progressive-lab
namespace: monitoring
labels: {release: prometheus-stack}
spec:
namespaceSelector: {matchNames: [progressive-lab]}
selector: {matchLabels: {app: progressive-router}}
endpoints: [{port: http, path: /metrics, interval: 15s}]

View File

@ -0,0 +1,3 @@
canaryWeight: 0
canaryFailure: false
badReadiness: false

View File

@ -0,0 +1,64 @@
# Secrets and certificate lifecycle lab
This opt-in lab uses External Secrets Operator (ESO) to copy a demo value from
an in-memory Vault development server into a Kubernetes Secret. A separate
cert-manager self-signed Issuer issues a short-lived demo certificate. Jeannie
creates Argo CD applications for the controllers and the lab resources. Both
controllers and their CRDs are cluster-wide, although the demo resources and
Vault service are confined to the `secrets-lab` namespace. Existing controllers
are not adopted automatically.
Vault dev mode uses an automatically generated root token in a Kubernetes
Secret and HTTP inside the cluster. It has no durable storage; a Vault restart
loses its contents. This setup is only for disposable values, not real
passwords, production secrets, or a backup of your existing secrets. The demo
certificate is self-signed and is not trusted by browsers. Neither Dex nor OCI
edge certificates are changed.
Your SOPS workflow stores encrypted values in Git and decrypts them when needed.
This lab instead stores the value in Vault, and ESO periodically synchronizes a
Kubernetes Secret. The generated Kubernetes Secret still exists in the cluster;
ESO does not eliminate the need to protect Kubernetes secrets, access, or
backups. A real secret-manager deployment would need durable storage, access
policies, TLS, token management, and recovery planning.
## Run
Push the commit first; Argo CD reads the configured GitOps repository's `main`
branch. On Debian, with the desired Jeannie profile selected:
```sh
cd ~/my-homelab-configs
git pull --ff-only gitea main
./jeannie secrets-lab plan
./jeannie secrets-lab apply
./jeannie secrets-lab test
```
The first apply downloads two charts and waits for their CRDs and the Vault
deployment. Argo CD may need additional time to synchronize the demo resources.
No secret values are printed. Check progress with `./jeannie secrets-lab status`.
## Exercises
```sh
# Write a new random demo value to Vault and verify ESO copied it.
./jeannie secrets-lab rotate
# If the disposable Vault restarted, create a replacement only if needed.
./jeannie secrets-lab recover
# Delete only the lab TLS Secret and verify cert-manager reissues it.
./jeannie secrets-lab recover-cert
```
Certificate reissuance is a recovery exercise. The Certificate also has a 24-hour
duration and an eight-hour renewal window so you can inspect automatic renewal
using `kubectl describe certificate -n secrets-lab secrets-lab-demo` with the
selected cluster's kubeconfig. Removing the demo TLS Secret changes its private
key; no other TLS Secret is touched. Vault recovery creates a new value if the
in-memory database was lost; it cannot restore the old value.
The chart versions are pinned for the homelab's Kubernetes 1.31 compatibility.
That Kubernetes release and these controller versions require an upgrade plan;
do not treat this lab as a supported production secret-management deployment.

View File

@ -0,0 +1,5 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- vault.yaml
- resources.yaml

View File

@ -0,0 +1,51 @@
apiVersion: external-secrets.io/v1beta1
kind: SecretStore
metadata:
name: secrets-lab-vault
namespace: secrets-lab
spec:
provider:
vault:
server: http://secrets-lab-vault.secrets-lab.svc:8200
path: secret
version: v2
auth:
tokenSecretRef: {name: secrets-lab-vault-token, key: token}
---
apiVersion: external-secrets.io/v1beta1
kind: ExternalSecret
metadata:
name: secrets-lab-demo
namespace: secrets-lab
spec:
refreshInterval: 30s
secretStoreRef: {name: secrets-lab-vault, kind: SecretStore}
target:
name: secrets-lab-demo
creationPolicy: Owner
data:
- secretKey: value
remoteRef: {key: demo, property: value}
---
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
name: secrets-lab-selfsigned
namespace: secrets-lab
spec:
selfSigned: {}
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: secrets-lab-demo
namespace: secrets-lab
spec:
secretName: secrets-lab-demo-tls
duration: 24h
renewBefore: 8h
privateKey:
rotationPolicy: Always
commonName: secrets-lab.local
dnsNames: [secrets-lab.local]
issuerRef: {name: secrets-lab-selfsigned, kind: Issuer}

View File

@ -0,0 +1,47 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: secrets-lab-vault
namespace: secrets-lab
spec:
replicas: 1
selector:
matchLabels: {app: secrets-lab-vault}
template:
metadata:
labels: {app: secrets-lab-vault}
spec:
automountServiceAccountToken: false
containers:
- name: vault
image: hashicorp/vault:1.18.5
args: ["server", "-dev", "-dev-listen-address=0.0.0.0:8200"]
env:
- name: VAULT_DEV_ROOT_TOKEN_ID
valueFrom:
secretKeyRef: {name: secrets-lab-vault-token, key: token}
- {name: VAULT_ADDR, value: "http://127.0.0.1:8200"}
- name: VAULT_TOKEN
valueFrom:
secretKeyRef: {name: secrets-lab-vault-token, key: token}
ports:
- {name: http, containerPort: 8200}
readinessProbe:
httpGet: {path: /v1/sys/health, port: http}
initialDelaySeconds: 3
securityContext:
allowPrivilegeEscalation: false
capabilities: {drop: [ALL]}
resources:
requests: {cpu: 25m, memory: 64Mi}
limits: {memory: 256Mi}
---
apiVersion: v1
kind: Service
metadata:
name: secrets-lab-vault
namespace: secrets-lab
spec:
selector: {app: secrets-lab-vault}
ports:
- {name: http, port: 8200, targetPort: http}

49
docs/ai-lab.md Normal file
View File

@ -0,0 +1,49 @@
# Jeannie AI lab
The AI lab builds a pinned, separate llama.cpp checkout on the Debian server.
It does not change Ollama, OmniRoute, the Jeannie model routes, or cluster
configuration. The build has CPU and Vulkan support; Vulkan detection does not
guarantee that the integrated GPU will be faster than the CPU.
After pushing this change, on Debian:
```sh
cd ~/my-homelab-configs
git pull --ff-only gitea main
./jeannie ai-lab plan
./jeannie ai-lab install
./jeannie ai-lab devices
```
Installation uses `sudo apt-get` for build and Vulkan packages, downloads the
pinned source, and compiles with two parallel jobs. The default lab directory is
`/data/homelab-ai-lab`; set `JEANNIE_AI_LAB_DIR` to use a different directory.
The install refuses to overwrite an existing source checkout whose origin,
commit, or tracked files do not match the expected source.
Once `ollama ps` shows no loaded models, run:
```sh
./jeannie ai-lab bench ollama
./jeannie ai-lab bench cpu
./jeannie ai-lab bench vulkan
```
The Vulkan run defaults to `Vulkan0`. If `devices` shows a different Radeon
device, set `JEANNIE_AI_LAB_VULKAN_DEVICE` to that name for the run. The lab
refuses to start if Ollama currently has a loaded model; it never stops another
model. The Ollama benchmark asks Ollama to unload the model after its own
request. Avoid concurrent AI workloads when comparing results.
Each run reads the existing `llama3.2:3b` GGUF blob; it does not copy, delete,
or modify the model. The Debian user must be able to read the path printed by
`ollama show --modelfile llama3.2:3b`. Inaccessible or non-GGUF files stop the
test. Reports and model output are saved with mode 0600 under the lab's `reports`
directory. Review the llama.cpp log for actual GPU offload and prompt versus
generation timing; the parsed timing values alone do not identify the phase.
Each benchmark is one cold request, using the same prompt, maximum output,
context size and temperature. CLI and Ollama prompt templates, sampling options,
backend allocation and measured time boundaries can differ, so this is an
initial comparison rather than a controlled scientific benchmark. Repeat runs,
inspect answers, and compare end-to-end user experience before changing routes.

41
jeannie
View File

@ -64,6 +64,8 @@ Base, Inventory, And Planning
Review pinned cluster identity and scoped state.
preflight Run non-mutating infrastructure preflight checks.
gateway-lab {plan|apply|status|test} Manage the isolated Gateway API and FastAPI lab.
progressive-lab {plan|apply|status|run|rollback} Practice canary rollout and rollback.
secrets-lab {plan|apply|status|test|rotate|recover|recover-cert} Practice secret and certificate lifecycle.
doctor-preapply Run deeper pre-apply safety checks.
plan [all|provisioning|cluster|platform|apps|edge]
Run OpenTofu plans without applying changes.
@ -81,6 +83,7 @@ Build And Bootstrap
deploy-ai-tools Install/wire local AI CLIs to the AI gateway.
goose-graph <update|context|learn|propose> [question]
Explore the repo with Goose and Graphify.
ai-lab {plan|install|devices|bench BACKEND} Build and benchmark isolated llama.cpp.
lab-window <start|stop|status> Apply the scheduled lab power window.
deploy-omniroute Deploy the OmniRoute LLM routing gateway.
deploy-hermes Deploy the Hermes agent (git-install + venv + gateway service).
@ -255,6 +258,8 @@ case "${1:-}" in
up|cluster|platform|apps|start-cluster) runtime_pipeline=true ;;
start) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;;
gateway-lab) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;;
progressive-lab) case "${2:-plan}" in apply|run|rollback) runtime_pipeline=true ;; esac ;;
secrets-lab) case "${2:-plan}" in apply|test|rotate|recover|recover-cert) runtime_pipeline=true ;; esac ;;
esac
if "${runtime_pipeline}"; then
if [[ "${JEANNIE_RUNTIME_PIPELINE_LOCK:-}" != "${LAB_CLUSTER_PROFILE}" ||
@ -276,6 +281,12 @@ case "${1:-}" in
gateway-lab)
if [[ "${2:-plan}" == apply ]]; then cluster_runtime_require || exit 1; fi
;;
progressive-lab)
case "${2:-plan}" in apply|run|rollback) cluster_runtime_require || exit 1 ;; esac
;;
secrets-lab)
case "${2:-plan}" in apply|test|rotate|recover|recover-cert) cluster_runtime_require || exit 1 ;; esac
;;
__up-task)
cluster_runtime_require || exit 1
;;
@ -306,6 +317,36 @@ case "${1:-}" in
esac
case "${1:-}" in
ai-lab)
require_debian_server "ai-lab"
case "${2:-plan}" in
plan|install|devices) [[ $# -le 2 ]] || { echo "Usage: ./jeannie ai-lab {plan|install|devices|bench {ollama|cpu|vulkan}}" >&2; exit 2; } ;;
bench) [[ $# -eq 3 && "${3}" =~ ^(ollama|cpu|vulkan)$ ]] || { echo "Usage: ./jeannie ai-lab bench {ollama|cpu|vulkan}" >&2; exit 2; } ;;
*) echo "Usage: ./jeannie ai-lab {plan|install|devices|bench {ollama|cpu|vulkan}}" >&2; exit 2 ;;
esac
if [[ "${2:-plan}" == install ]]; then record_change_journal "ai-lab" "$@"; fi
python3 "${REPO_ROOT}/scripts/ai-lab.py" "${@:2}"
;;
progressive-lab)
[[ $# -le 3 && ( $# -le 2 || "${2:-}" == run ) ]] || { echo "Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}" >&2; exit 2; }
case "${2:-plan}" in
plan|apply|status|run|rollback) ;;
*) echo "Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}" >&2; exit 2 ;;
esac
if [[ "${2:-plan}" != plan ]]; then cluster_context_require || exit 1; fi
case "${2:-plan}" in apply|run|rollback) record_change_journal "progressive-lab" "$@" ;; esac
KUBECONFIG="${KUBECONFIG_PATH}" python3 "${REPO_ROOT}/scripts/progressive-lab.py" "${@:2}"
;;
secrets-lab)
[[ $# -le 2 ]] || { echo "Usage: ./jeannie secrets-lab {plan|apply|status|test|rotate|recover|recover-cert}" >&2; exit 2; }
case "${2:-plan}" in
plan|apply|status|test|rotate|recover|recover-cert) ;;
*) echo "Usage: ./jeannie secrets-lab {plan|apply|status|test|rotate|recover|recover-cert}" >&2; exit 2 ;;
esac
if [[ "${2:-plan}" != plan ]]; then cluster_context_require || exit 1; fi
case "${2:-plan}" in apply|rotate|recover|recover-cert) record_change_journal "secrets-lab" "$@" ;; esac
KUBECONFIG="${KUBECONFIG_PATH}" python3 "${REPO_ROOT}/scripts/secrets-lab.py" "${2:-plan}"
;;
gateway-lab)
[[ $# -le 2 ]] || { echo "Usage: ./jeannie gateway-lab {plan|apply|status|test}" >&2; exit 2; }
case "${2:-plan}" in

152
scripts/ai-lab.py Normal file
View File

@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""An isolated llama.cpp build and inference benchmark for the Debian host."""
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time
import urllib.request
from datetime import datetime, timezone
TAG = "b10931"
COMMIT_PREFIX = "3057bb6"
REPOSITORY = "https://github.com/ggml-org/llama.cpp.git"
ROOT = Path(os.environ.get("JEANNIE_AI_LAB_DIR", "/data/homelab-ai-lab"))
SOURCE = ROOT / ("llama.cpp-" + TAG)
CLI = SOURCE / "build/bin/llama-cli"
MODEL = "llama3.2:3b"
PROMPT = "Explain the difference between a Kubernetes Service and an Ingress in three sentences."
ENDPOINT = os.environ.get("LAB_OLLAMA_URL", "http://127.0.0.1:11434").rstrip("/")
def command(args, *, capture=False, timeout=None):
result = subprocess.run(args, text=True, capture_output=capture, timeout=timeout)
if result.returncode:
detail = (result.stderr or "").strip() if capture else ""
raise RuntimeError(f"{args[0]} failed (exit {result.returncode})" + (f": {detail[-1000:]}" if detail else ""))
return result
def read_url(path, payload=None, timeout=15):
data = json.dumps(payload).encode() if payload is not None else None
request = urllib.request.Request(ENDPOINT + path, data=data, headers={"Content-Type": "application/json"})
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.load(response)
def require_idle_ollama():
models = read_url("/api/ps").get("models", [])
if models:
names = ", ".join(model.get("name", "unknown") for model in models)
raise RuntimeError(f"Ollama has loaded models ({names}); wait until they unload before benchmarking. No model was stopped.")
def model_path():
output = command(["ollama", "show", "--modelfile", MODEL], capture=True).stdout
paths = [line.split(maxsplit=1)[1] for line in output.splitlines() if line.startswith("FROM /")]
if len(paths) != 1:
raise RuntimeError("Could not identify one local model file from the Ollama Modelfile")
path = Path(paths[0])
try:
with path.open("rb") as model:
magic = model.read(4)
except OSError as exc:
raise RuntimeError(f"Model file is not readable by this user: {path}") from exc
if magic != b"GGUF":
raise RuntimeError("The Ollama model file is not a GGUF file")
return path
def install():
ROOT.mkdir(parents=True, exist_ok=True)
if shutil.disk_usage(ROOT).free < 5 * 1024 ** 3:
raise RuntimeError(f"Need at least 5 GiB free in {ROOT} to build the lab")
packages = ["git", "build-essential", "cmake", "libvulkan-dev", "glslc", "spirv-headers", "vulkan-tools", "mesa-vulkan-drivers"]
command(["sudo", "apt-get", "update"])
command(["sudo", "apt-get", "install", "-y", *packages])
if not SOURCE.exists():
command(["git", "clone", "--depth", "1", "--branch", TAG, REPOSITORY, str(SOURCE)])
if not (SOURCE / ".git").is_dir():
raise RuntimeError(f"Existing lab source directory is not a Git checkout: {SOURCE}")
origin = command(["git", "-C", str(SOURCE), "remote", "get-url", "origin"], capture=True).stdout.strip()
commit = command(["git", "-C", str(SOURCE), "rev-parse", "HEAD"], capture=True).stdout.strip()
dirty = command(["git", "-C", str(SOURCE), "status", "--porcelain", "--untracked-files=no"], capture=True).stdout.strip()
if origin != REPOSITORY or not commit.startswith(COMMIT_PREFIX) or dirty:
raise RuntimeError("Lab checkout differs from the pinned source or has local edits; refusing to change it")
command(["cmake", "-S", str(SOURCE), "-B", str(SOURCE / "build"), "-DCMAKE_BUILD_TYPE=Release", "-DGGML_VULKAN=ON"])
command(["cmake", "--build", str(SOURCE / "build"), "--config", "Release", "--parallel", "2"])
if not CLI.is_file():
raise RuntimeError("Build completed but llama-cli was not found")
print(f"AI lab installed: {CLI} ({TAG}, {commit})")
print("Next: ./jeannie ai-lab devices")
def devices():
if not CLI.is_file():
raise RuntimeError("AI lab is not installed; run ./jeannie ai-lab install")
command([str(CLI), "--list-devices"])
def make_report(backend, result, log):
reports = ROOT / "reports"
reports.mkdir(parents=True, exist_ok=True, mode=0o700)
name = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + backend + f"-{time.time_ns() % 1000000:06d}"
for suffix, data in ((".json", json.dumps(result, indent=2) + "\n"), (".log", log)):
path = reports / (name + suffix)
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "w") as file:
file.write(data)
print(json.dumps(result, indent=2))
print(f"Private report: {reports / (name + '.json')}")
def benchmark(backend):
if backend not in ("ollama", "cpu", "vulkan"):
raise RuntimeError("Choose ollama, cpu or vulkan")
path = model_path()
require_idle_ollama()
common = {"backend": backend, "model": MODEL, "model_file": str(path), "context": 4096, "max_tokens": 128, "temperature": 0, "prompt": PROMPT, "note": "Single cold request; prompt templates and sampling may differ across backends."}
if backend == "ollama":
payload = {"model": MODEL, "prompt": PROMPT, "stream": False, "keep_alive": 0, "options": {"num_ctx": 4096, "num_predict": 128, "temperature": 0}}
result = read_url("/api/generate", payload, timeout=300)
eval_ns = result.get("eval_duration", 0)
common.update({"total_seconds": result.get("total_duration", 0) / 1e9, "load_seconds": result.get("load_duration", 0) / 1e9, "generated_tokens": result.get("eval_count"), "generation_tokens_per_second": result.get("eval_count", 0) * 1e9 / eval_ns if eval_ns else None})
make_report(backend, common, result.get("response", "") + "\n")
return
if not CLI.is_file():
raise RuntimeError("AI lab is not installed; run ./jeannie ai-lab install")
device = "none" if backend == "cpu" else os.environ.get("JEANNIE_AI_LAB_VULKAN_DEVICE", "Vulkan0")
if backend == "vulkan" and not re.fullmatch(r"Vulkan[0-9]+", device):
raise RuntimeError("Vulkan device must have a name such as Vulkan0")
args = [str(CLI), "-m", str(path), "--device", device, "-ngl", "0" if backend == "cpu" else "999", "-c", "4096", "-n", "128", "--temp", "0", "--single-turn", "--perf", "-p", PROMPT]
started = time.monotonic()
completed = command(args, capture=True, timeout=600)
log = completed.stdout + "\n" + completed.stderr
rates = re.findall(r"([0-9]+(?:\.[0-9]+)?)\s+tokens per second", log)
common.update({"device": device, "elapsed_seconds": round(time.monotonic() - started, 3), "llama_cpp_version": TAG, "tokens_per_second_reported": [float(rate) for rate in rates], "note": common["note"] + " Confirm actual GPU offload and identify prompt/generation rates in the log."})
make_report(backend, common, log)
def main():
action = sys.argv[1] if len(sys.argv) > 1 else "plan"
if action == "plan":
print(json.dumps({"directory": str(ROOT), "source": REPOSITORY, "version": TAG, "expected_commit_prefix": COMMIT_PREFIX, "packages": ["git", "build-essential", "cmake", "libvulkan-dev", "glslc", "spirv-headers", "vulkan-tools", "mesa-vulkan-drivers"], "production_routes": "unchanged"}, indent=2))
elif action == "install":
install()
elif action == "devices":
devices()
elif action == "bench" and len(sys.argv) == 3:
benchmark(sys.argv[2])
else:
raise RuntimeError("Usage: ./jeannie ai-lab {plan|install|devices|bench {ollama|cpu|vulkan}}")
if __name__ == "__main__":
try:
main()
except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
print(f"AI lab: {exc}", file=sys.stderr)
sys.exit(1)

202
scripts/progressive-lab.py Normal file
View File

@ -0,0 +1,202 @@
#!/usr/bin/env python3
"""Run a disposable canary experiment through an Argo CD application."""
import json
import os
import re
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from contextlib import contextmanager
NAMESPACE = "progressive-lab"
OWNER = "homelab.dev/progressive-lab"
METRIC = re.compile(r'^progressive_lab_requests_total\{version="(stable|canary)",outcome="(success|error)"\} (\d+)$')
def kubectl(*args, data=None):
result = subprocess.run(["kubectl", *args], input=data, text=True, capture_output=True)
if result.returncode:
raise RuntimeError(result.stderr.strip() or "kubectl failed")
return result.stdout
def get(kind, name, namespace=None):
args = ["get", kind, name, "--ignore-not-found", "-o", "json"]
if namespace:
args += ["-n", namespace]
value = kubectl(*args).strip()
return json.loads(value) if value else None
def owned(obj):
return obj and obj.get("metadata", {}).get("labels", {}).get(OWNER) == "true"
def check_owned(kind, name, namespace=None):
obj = get(kind, name, namespace)
if obj and not owned(obj):
raise RuntimeError(f"{kind}/{name} already exists and is not owned by this lab")
return obj
def install():
namespace = check_owned("namespace", NAMESPACE)
app = check_owned("application", "progressive-lab", "argocd")
# A pre-existing ServiceMonitor could belong to another deployment.
monitor = get("servicemonitor", "progressive-lab", "monitoring")
if monitor and not app:
raise RuntimeError("monitoring/ServiceMonitor progressive-lab already exists")
if not get("crd", "servicemonitors.monitoring.coreos.com"):
raise RuntimeError("Prometheus Operator ServiceMonitor CRD is missing; deploy monitoring first")
if not namespace:
kubectl("create", "-f", "-", data=json.dumps({"apiVersion": "v1", "kind": "Namespace", "metadata": {"name": NAMESPACE, "labels": {OWNER: "true"}}}))
if not app:
repo = os.environ.get("TF_VAR_gitops_repo_url") or os.environ.get("LAB_GITOPS_REPO_URL") or "ssh://git@192.168.100.73:32222/jv/my-homelab-configs.git"
app = {"apiVersion": "argoproj.io/v1alpha1", "kind": "Application", "metadata": {"name": "progressive-lab", "namespace": "argocd", "labels": {OWNER: "true"}}, "spec": {"project": "default", "source": {"repoURL": repo, "targetRevision": "main", "path": "apps/progressive-lab", "helm": {"valuesObject": {"canaryWeight": 0, "canaryFailure": False, "badReadiness": False}}}, "destination": {"server": "https://kubernetes.default.svc", "namespace": NAMESPACE}, "syncPolicy": {"automated": {"prune": True, "selfHeal": True}}}}
kubectl("create", "-f", "-", data=json.dumps(app))
print("Argo CD application requested. Run ./jeannie progressive-lab run to start the experiment.")
def set_values(weight, failure=False, readiness=False):
if not owned(get("application", "progressive-lab", "argocd")):
raise RuntimeError("Lab application is missing or not owned by Jeannie; run apply first")
patch = {"spec": {"source": {"helm": {"valuesObject": {"canaryWeight": weight, "canaryFailure": failure, "badReadiness": readiness}}}}}
kubectl("-n", "argocd", "patch", "application", "progressive-lab", "--type=merge", "-p", json.dumps(patch))
def wait_values(weight, failure, readiness):
for _ in range(150):
router = get("deployment", "progressive-router", NAMESPACE)
canary = get("deployment", "progressive-canary", NAMESPACE)
if router and canary:
router_env = router["spec"]["template"]["spec"]["containers"][0].get("env", [])
container = canary["spec"]["template"]["spec"]["containers"][0]
env = {entry["name"]: entry["value"] for entry in container.get("env", [])}
path = container["readinessProbe"]["httpGet"]["path"]
if {e["name"]: e["value"] for e in router_env}.get("CANARY_WEIGHT") == str(weight) and env.get("DEMO_FAIL") == str(failure).lower() and path == ("/unready" if readiness else "/health"):
break
time.sleep(2)
else:
raise RuntimeError("Argo CD did not reconcile the requested lab parameters")
for name in ("progressive-stable", "progressive-router"):
kubectl("-n", NAMESPACE, "rollout", "status", f"deployment/{name}", "--timeout=180s")
if not readiness:
kubectl("-n", NAMESPACE, "rollout", "status", "deployment/progressive-canary", "--timeout=180s")
else:
for _ in range(90):
dep = get("deployment", "progressive-canary", NAMESPACE)
endpoints = get("endpoints", "progressive-canary", NAMESPACE)
addresses = [a for subset in (endpoints or {}).get("subsets", []) for a in subset.get("addresses", [])]
if dep and dep.get("status", {}).get("observedGeneration", 0) >= dep["metadata"]["generation"] and not addresses:
break
time.sleep(2)
else:
raise RuntimeError("Canary still has ready endpoints; readiness failure was not observed")
@contextmanager
def forward():
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
proc = subprocess.Popen(["kubectl", "-n", NAMESPACE, "port-forward", "--address", "127.0.0.1", "service/progressive-router", f"{port}:8080"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for _ in range(50):
if proc.poll() is not None:
raise RuntimeError("Router port-forward failed")
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.2):
break
except OSError:
time.sleep(0.2)
else:
raise RuntimeError("Router port-forward timed out")
yield port
finally:
proc.terminate()
proc.wait(timeout=10)
def read_metrics(port):
with urllib.request.urlopen(f"http://127.0.0.1:{port}/metrics", timeout=5) as response:
lines = response.read().decode().splitlines()
values = {}
for line in lines:
match = METRIC.fullmatch(line)
if match:
values[(match.group(1), match.group(2))] = int(match.group(3))
if len(values) != 4:
raise RuntimeError("Router metrics are incomplete")
return values
def exercise(port, requests=120):
before = read_metrics(port)
for _ in range(requests):
try:
with urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=5) as response:
response.read()
except urllib.error.HTTPError as exc:
exc.close()
after = read_metrics(port)
delta = {key: after[key] - before[key] for key in before}
if any(value < 0 for value in delta.values()):
raise RuntimeError("Router restarted during the measurement")
return delta
def run(scenario):
if scenario not in ("errors", "readiness"):
raise RuntimeError("Choose errors or readiness")
failure, readiness = scenario == "errors", scenario == "readiness"
try:
set_values(10, failure, readiness)
wait_values(10, failure, readiness)
with forward() as port:
counts = exercise(port)
total = counts[("canary", "success")] + counts[("canary", "error")]
rate = counts[("canary", "error")] / total if total else 0
print(json.dumps({"scenario": scenario, "canary_requests": total, "canary_errors": counts[("canary", "error")], "canary_error_rate": round(rate, 3), "stable_successes": counts[("stable", "success")], "threshold": 0.1}, indent=2))
if total < 5:
raise RuntimeError("Too few canary samples to evaluate the error rate")
if not counts[("stable", "success")]:
raise RuntimeError("No successful stable requests were observed")
if rate <= 0.1:
raise RuntimeError("Expected failing canary did not exceed the error threshold")
print("Canary error threshold exceeded; rolling back.")
finally:
set_values(0)
wait_values(0, False, False)
print("Rollback reconciled: canary traffic is 0%.")
def main():
action = sys.argv[1] if len(sys.argv) > 1 else "plan"
if action == "plan":
print(json.dumps({"profile": os.environ.get("LAB_CLUSTER_PROFILE"), "route": "internal ClusterIP", "experiment": "10% canary, sampled errors, rollback to 0%", "metrics": "router Prometheus counter and ServiceMonitor"}, indent=2))
elif action == "apply":
install()
elif action == "run":
run(sys.argv[2] if len(sys.argv) > 2 else "errors")
elif action == "rollback":
set_values(0)
wait_values(0, False, False)
print("Rollback reconciled: canary traffic is 0%.")
elif action == "status":
print(kubectl("-n", NAMESPACE, "get", "deployments,services", "--ignore-not-found"))
app = get("application", "progressive-lab", "argocd")
if app:
print(json.dumps(app.get("spec", {}).get("source", {}).get("helm", {}).get("valuesObject", {}), indent=2))
else:
raise RuntimeError("Usage: ./jeannie progressive-lab {plan|apply|status|run [errors|readiness]|rollback}")
if __name__ == "__main__":
try:
main()
except (RuntimeError, ValueError, OSError, KeyError) as exc:
print(f"Progressive lab: {exc}", file=sys.stderr)
sys.exit(1)

191
scripts/secrets-lab.py Normal file
View File

@ -0,0 +1,191 @@
#!/usr/bin/env python3
"""A disposable Vault, External Secrets and cert-manager learning environment."""
import base64
import json
import os
from pathlib import Path
import secrets
import subprocess
import sys
import time
OWNER = "homelab.dev/secrets-lab"
NAMESPACE = "secrets-lab"
ROOT = Path(__file__).resolve().parents[1]
CONTROLLERS = {
"secrets-lab-external-secrets": ("https://charts.external-secrets.io", "external-secrets", "0.12.1", "externalsecrets.external-secrets.io", {"installCRDs": True}),
"secrets-lab-cert-manager": ("https://charts.jetstack.io", "cert-manager", "v1.19.6", "certificates.cert-manager.io", {"crds": {"enabled": True}}),
}
def command(args, data=None, check=True):
result = subprocess.run(args, input=data, text=True, capture_output=True)
if check and result.returncode:
raise RuntimeError(result.stderr.strip() or f"{args[0]} failed")
return result
def kubectl(*args, data=None, check=True):
return command(["kubectl", *args], data, check)
def get(kind, name, namespace=None):
args = ["get", kind, name, "--ignore-not-found", "-o", "json"]
if namespace:
args += ["-n", namespace]
output = kubectl(*args).stdout.strip()
return json.loads(output) if output else None
def owned(obj):
return obj and obj.get("metadata", {}).get("labels", {}).get(OWNER) == "true"
def ensure_available(kind, name, namespace=None):
obj = get(kind, name, namespace)
if obj and not owned(obj):
raise RuntimeError(f"{kind}/{name} exists and is not owned by this lab")
return obj
def apply_json(obj):
kubectl("apply", "-f", "-", data=json.dumps(obj))
def application(name, source, namespace):
return {"apiVersion": "argoproj.io/v1alpha1", "kind": "Application", "metadata": {"name": name, "namespace": "argocd", "labels": {OWNER: "true"}}, "spec": {"project": "default", "source": source, "destination": {"server": "https://kubernetes.default.svc", "namespace": namespace}, "syncPolicy": {"automated": {"prune": True, "selfHeal": True}, "syncOptions": ["CreateNamespace=true", "ServerSideApply=true"]}}}
def ensure_controller(name, config):
repo, chart, version, crd, values = config
app = ensure_available("application", name, "argocd")
if not app and get("crd", crd):
raise RuntimeError(f"{crd} already exists; refusing to install a second controller. Review existing ownership first")
source = {"repoURL": repo, "chart": chart, "targetRevision": version, "helm": {"valuesObject": values}}
apply_json(application(name, source, name))
def wait_crd(name):
for _ in range(150):
if get("crd", name):
kubectl("wait", f"crd/{name}", "--for=condition=Established", "--timeout=120s")
return
time.sleep(2)
raise RuntimeError(f"{name} was not created; inspect the Argo CD controller application")
def vault(*args, data=None, check=True):
return kubectl("-n", NAMESPACE, "exec", "deployment/secrets-lab-vault", "--", "vault", *args, data=data, check=check)
def seed(overwrite=False):
# A successful list distinguishes an absent key from an inaccessible Vault.
result = vault("kv", "list", "-format=json", "secret/", check=False)
if result.returncode and "No value found" not in result.stderr:
raise RuntimeError("Could not inspect the demo Vault; check its health and token")
keys = json.loads(result.stdout) if result.returncode == 0 else []
if "demo" not in keys or overwrite:
value = secrets.token_urlsafe(32)
vault("kv", "put", "secret/demo", "-", data=json.dumps({"value": value}))
return "rotated" if overwrite else "created"
return "preserved"
def install():
namespace = ensure_available("namespace", NAMESPACE)
ensure_available("application", "secrets-lab", "argocd")
for name, config in CONTROLLERS.items():
app = ensure_available("application", name, "argocd")
if not app and get("crd", config[3]):
raise RuntimeError(f"{config[3]} already exists; refusing a second controller")
if not app and get("namespace", name):
raise RuntimeError(f"Namespace {name} already exists; refusing to adopt it")
if not namespace:
apply_json({"apiVersion": "v1", "kind": "Namespace", "metadata": {"name": NAMESPACE, "labels": {OWNER: "true"}}})
token = ensure_available("secret", "secrets-lab-vault-token", NAMESPACE)
if not token:
obj = {"apiVersion": "v1", "kind": "Secret", "metadata": {"name": "secrets-lab-vault-token", "namespace": NAMESPACE, "labels": {OWNER: "true"}}, "type": "Opaque", "stringData": {"token": secrets.token_urlsafe(32)}}
kubectl("create", "-f", "-", data=json.dumps(obj))
for name, config in CONTROLLERS.items():
ensure_controller(name, config)
for config in CONTROLLERS.values():
wait_crd(config[3])
repo = os.environ.get("TF_VAR_gitops_repo_url") or os.environ.get("LAB_GITOPS_REPO_URL") or "ssh://git@192.168.100.73:32222/jv/my-homelab-configs.git"
apply_json(application("secrets-lab", {"repoURL": repo, "targetRevision": "main", "path": "apps/secrets-lab"}, NAMESPACE))
for _ in range(150):
if get("deployment", "secrets-lab-vault", NAMESPACE):
break
time.sleep(2)
else:
raise RuntimeError("Vault deployment was not created; inspect Argo CD application secrets-lab")
kubectl("-n", NAMESPACE, "rollout", "status", "deployment/secrets-lab-vault", "--timeout=300s")
print(f"Demo Vault secret: {seed()}; no values were printed.")
print("Run ./jeannie secrets-lab test to check synchronization and certificate issuance.")
def sync_check():
kubectl("-n", NAMESPACE, "annotate", "externalsecret/secrets-lab-demo", f"force-sync={time.time_ns()}", "--overwrite")
expected = json.loads(vault("kv", "get", "-format=json", "secret/demo").stdout)["data"]["data"]["value"]
for _ in range(90):
obj = get("secret", "secrets-lab-demo", NAMESPACE)
if obj and base64.b64decode(obj.get("data", {}).get("value", "")).decode() == expected:
return
time.sleep(2)
raise RuntimeError("ExternalSecret did not synchronize the Vault value within 180 seconds")
def test():
sync_check()
kubectl("-n", NAMESPACE, "wait", "certificate/secrets-lab-demo", "--for=condition=Ready", "--timeout=180s")
tls = get("secret", "secrets-lab-demo-tls", NAMESPACE)
if not tls or not all(tls.get("data", {}).get(key) for key in ("tls.crt", "tls.key")):
raise RuntimeError("Demo certificate secret is missing certificate or key")
print("Vault and Kubernetes demo secret match; demo certificate is Ready. Secret values were not printed.")
def recover_cert():
old = get("secret", "secrets-lab-demo-tls", NAMESPACE)
if not old:
raise RuntimeError("Demo TLS secret is missing already; run test to observe recovery")
old_uid = old["metadata"]["uid"]
kubectl("-n", NAMESPACE, "delete", "secret", "secrets-lab-demo-tls", "--wait=true")
for _ in range(90):
new = get("secret", "secrets-lab-demo-tls", NAMESPACE)
if new and new["metadata"]["uid"] != old_uid and all(new.get("data", {}).get(k) for k in ("tls.crt", "tls.key")):
kubectl("-n", NAMESPACE, "wait", "certificate/secrets-lab-demo", "--for=condition=Ready", "--timeout=120s")
print("Demo TLS secret recreated and certificate is Ready.")
return
time.sleep(2)
raise RuntimeError("Demo TLS secret was not recreated; inspect the Certificate and Issuer")
def main():
action = sys.argv[1] if len(sys.argv) > 1 else "plan"
if action == "plan":
print(json.dumps({"profile": os.environ.get("LAB_CLUSTER_PROFILE"), "scope": "disposable namespace and cluster-wide controllers", "controllers": {name: config[2] for name, config in CONTROLLERS.items()}, "vault": "in-memory development server; demo data disappears on restart", "certificate": "self-signed demo only"}, indent=2))
elif action == "apply":
install()
elif action == "rotate":
print(f"Demo secret {seed(overwrite=True)} in Vault; waiting for synchronization.")
sync_check()
print("Rotation synchronized successfully; no secret values were printed.")
elif action == "recover":
print(f"Demo Vault secret {seed()}; waiting for synchronization.")
sync_check()
print("Demo secret synchronized; no secret values were printed.")
elif action == "test":
test()
elif action == "recover-cert":
recover_cert()
elif action == "status":
print(kubectl("-n", NAMESPACE, "get", "deployments,secretstores,externalsecrets,issuers,certificates", "--ignore-not-found").stdout)
else:
raise RuntimeError("Usage: ./jeannie secrets-lab {plan|apply|status|test|rotate|recover|recover-cert}")
if __name__ == "__main__":
try:
main()
except (RuntimeError, ValueError, OSError, KeyError) as exc:
print(f"Secrets lab: {exc}", file=sys.stderr)
sys.exit(1)

View File

@ -72,6 +72,16 @@ validate_yaml() {
echo "ruby not installed; skipping generic YAML parse"
}
validate_progressive_chart() {
if ! command -v helm >/dev/null 2>&1; then
echo "helm not installed; skipping progressive lab chart rendering"
return 0
fi
helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" >/dev/null
helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" --set canaryWeight=10 --set canaryFailure=true >/dev/null
helm template progressive-lab "${REPO_ROOT}/apps/progressive-lab" --set canaryWeight=10 --set badReadiness=true >/dev/null
}
validate_tofu_fmt() {
if ! command -v tofu >/dev/null 2>&1; then
echo "tofu not installed; skipping fmt check"
@ -108,6 +118,9 @@ validate_unit_tests() {
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_dex_drift.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_opentelemetry_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_gateway_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_secrets_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_progressive_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_ai_lab.py'
}
main() {
@ -118,6 +131,7 @@ main() {
run_step "Bash syntax" validate_bash_syntax
run_step "Shellcheck" validate_shellcheck
run_step "YAML parse" validate_yaml
run_step "Progressive lab chart" validate_progressive_chart
run_step "Go checks" validate_go
run_step "OpenTofu formatting" validate_tofu_fmt
run_step "Security static checks" validate_security_static

View File

@ -0,0 +1,47 @@
import importlib.util
from pathlib import Path
from types import SimpleNamespace
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("ai_lab", ROOT / "scripts/ai-lab.py")
lab = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lab)
class AiLabTest(unittest.TestCase):
def test_refuses_to_evict_ollama_model(self):
with mock.patch.object(lab, "read_url", return_value={"models": [{"name": "active"}]}):
with self.assertRaisesRegex(RuntimeError, "No model was stopped"):
lab.require_idle_ollama()
def test_allows_empty_ollama(self):
with mock.patch.object(lab, "read_url", return_value={"models": []}):
lab.require_idle_ollama()
def test_invalid_backend_does_not_start_inference(self):
with mock.patch.object(lab, "model_path") as path:
with self.assertRaisesRegex(RuntimeError, "Choose"):
lab.benchmark("unknown")
path.assert_not_called()
def test_ollama_request_has_bounded_context_and_output(self):
output = {"eval_duration": 1000000000, "eval_count": 12, "response": "ok"}
with mock.patch.object(lab, "model_path", return_value=Path("/demo/model")), mock.patch.object(lab, "require_idle_ollama"), mock.patch.object(lab, "read_url", return_value=output) as request, mock.patch.object(lab, "make_report") as report:
lab.benchmark("ollama")
payload = request.call_args.args[1]
self.assertEqual(payload["options"]["num_ctx"], 4096)
self.assertEqual(payload["options"]["num_predict"], 128)
self.assertEqual(payload["keep_alive"], 0)
self.assertEqual(report.call_args.args[1]["generation_tokens_per_second"], 12)
def test_model_must_be_a_unique_absolute_path(self):
result = SimpleNamespace(stdout="FROM llama3.2:3b\n")
with mock.patch.object(lab, "command", return_value=result):
with self.assertRaisesRegex(RuntimeError, "identify"):
lab.model_path()
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,37 @@
import importlib.util
from pathlib import Path
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("progressive_lab", ROOT / "scripts/progressive-lab.py")
lab = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lab)
class ProgressiveLabTest(unittest.TestCase):
def test_refuses_to_adopt_unowned_app(self):
with mock.patch.object(lab, "get", return_value={"metadata": {}}):
with self.assertRaisesRegex(RuntimeError, "not owned"):
lab.check_owned("application", "progressive-lab", "argocd")
def test_metrics_parser_matches_expected_counter(self):
match = lab.METRIC.fullmatch('progressive_lab_requests_total{version="canary",outcome="error"} 42')
self.assertEqual(match.groups(), ("canary", "error", "42"))
self.assertIsNone(lab.METRIC.fullmatch('progressive_lab_requests_total{version="other",outcome="error"} 42'))
def test_run_rolls_back_after_failed_measurement(self):
with mock.patch.object(lab, "set_values") as values, mock.patch.object(lab, "wait_values", side_effect=[RuntimeError("failure"), None]):
with self.assertRaisesRegex(RuntimeError, "failure"):
lab.run("errors")
self.assertEqual(values.call_args_list, [mock.call(10, True, False), mock.call(0)])
def test_invalid_scenario_never_changes_weights(self):
with mock.patch.object(lab, "set_values") as values:
with self.assertRaisesRegex(RuntimeError, "Choose"):
lab.run("unknown")
values.assert_not_called()
if __name__ == "__main__":
unittest.main()

View File

@ -0,0 +1,46 @@
import importlib.util
from pathlib import Path
from types import SimpleNamespace
import unittest
from unittest import mock
ROOT = Path(__file__).resolve().parents[2]
spec = importlib.util.spec_from_file_location("secrets_lab", ROOT / "scripts/secrets-lab.py")
lab = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lab)
class SecretsLabTest(unittest.TestCase):
def test_existing_secret_is_preserved_on_recovery(self):
with mock.patch.object(lab, "vault", return_value=SimpleNamespace(returncode=0, stdout='["demo"]', stderr="")) as vault:
self.assertEqual(lab.seed(), "preserved")
self.assertEqual(vault.call_count, 1)
def test_rotation_writes_new_value_without_returning_it(self):
result = SimpleNamespace(returncode=0, stdout='["demo"]', stderr="")
with mock.patch.object(lab, "vault", return_value=result) as vault:
self.assertEqual(lab.seed(overwrite=True), "rotated")
self.assertEqual(vault.call_count, 2)
self.assertIn("value", vault.call_args.kwargs["data"])
def test_empty_vault_gets_a_demo_value(self):
result = SimpleNamespace(returncode=2, stdout="", stderr="No value found at secret/metadata")
with mock.patch.object(lab, "vault", return_value=result) as vault:
self.assertEqual(lab.seed(), "created")
self.assertEqual(vault.call_count, 2)
def test_vault_error_never_overwrites(self):
result = SimpleNamespace(returncode=2, stdout="", stderr="permission denied")
with mock.patch.object(lab, "vault", return_value=result) as vault:
with self.assertRaisesRegex(RuntimeError, "inspect"):
lab.seed()
self.assertEqual(vault.call_count, 1)
def test_existing_unowned_resource_is_refused(self):
with mock.patch.object(lab, "get", return_value={"metadata": {}}):
with self.assertRaisesRegex(RuntimeError, "not owned"):
lab.ensure_available("namespace", "secrets-lab")
if __name__ == "__main__":
unittest.main()