Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): fail-loud NetPol resync interval and empty-fleet census (#478)
Alfredo Lopez00b0d3e89a01
diff --git a/host-context-controller/README.md b/host-context-controller/README.mdindex 063b6dceb..2e876c2cd 100644--- a/host-context-controller/README.md+++ b/host-context-controller/README.md@@ -439,16 +439,16 @@ Read by `src/gfsConfig.ts`. Invalid values **throw at startup** rather than sile### NetworkPolicy-| Variable | Default | Description |-| ------------------------------------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `CONTEXT_MAPPER_RUNTIME_NAMESPACES` | `mcp-server,mcp-host,sandbox-recipes,rpc-proxy` | Namespaces that get L0 deny-all + L1 infrastructure policies. Manifest overrides to `mcp-server,sandbox-recipes,rpc-proxy,sandbox-ui` — note it **drops `mcp-host`**, whose policies are static (`deploy/base/mcp-host/networkpolicies.yaml`), because an HCC deny-all would block mcp-host from reaching LLM APIs. |-| `CONTEXT_MAPPER_MINIMAL_INFRA_NAMESPACES` | `` (empty) | Subset of runtime namespaces that get **only** deny-all + DNS egress — no HCC-API or K8s-API egress. Manifest sets `sandbox-ui`. |-| `CONTEXT_MAPPER_K8S_API_CIDRS` | _(unset → `[]`)_ | K8s API-server CIDRs for `allow-k8s-api-egress-*`. Empty falls back to `KUBERNETES_SERVICE_HOST`. **Validated fail-closed at module load**: a malformed entry, or one broader than `/24` (IPv4) or `/120` (IPv6), **crashes startup** rather than programming a permissive policy. |-| `CONTEXT_MAPPER_NODELOCAL_DNS_CIDR` | `` (empty) | DNS infrastructure CIDR for NodeLocal DNSCache / kube-dns. Must be exactly one IPv4 `/32`; anything else throws at startup. |-| `CONTEXT_MAPPER_NETPOL_RESYNC_SEC` | `0` | Periodic NetworkPolicy coordinated convergence (seconds). Re-enters the single-flight pass with `ensureDefaults: true` so a tick covers orphan sweep (class A) and L0/L1 defaults (class D). A tick while a pass is in flight is **skipped** (`clerum_hcc_netpol_resync_ticks_skipped_total{reason="pass-in-flight"}`) and does not coalesce; event-driven trailing is unchanged. `0` disables the interval (merge default). Startup still converges once; `start()` already applied defaults as a bootstrap barrier. Default `0` logs a `console.warn` on every boot (same pattern as Host/SFS/GFS/LlmHook) — expected; it names the self-heal gap. **Enable is a separate ops decision** (issue #478, not this merge): with the skip guard the chosen value is **`1500`**; without the guard the floor is **`3600`**. `300` is not a valid enable while passes last minutes. Treadmill ⇔ pass duration ≥ period. Enable preconditions live on #478: image deployed, census read, histogram p99/max ≪ T, then infra **dev first**. |-| `CONTEXT_MAPPER_NETPOL_ORPHAN_DELETE_CAP` | `10` | Absolute orphan-delete cap for a namespace-wide NetworkPolicy sweep. Candidates **strictly above** this count refuse **deletes** and increment `clerum_hcc_netpol_orphan_sweep_capped_total`; the pass **still certifies** (#478: alert and do not delete). Governs every `fullReconcile` (startup, event-driven, timer). Absolute is checked first, so at a fleet ≥ 50 with these defaults the percent rule never binds. One cap over the **sum of all lanes** (not per-lane): a trip leaves those orphans in place until an operator raises the env; the signal is that counter. `0` refuses every orphan delete; a negative or non-canonical value (`2e1`, `10.9`) fails loud at load. Census: `scripts/ops/hcc-netpol-orphan-census.sh` — `live_cap_would_trip` is Deployment env only; `controller_cap_would_trip` applies compiled defaults when unset. Census listed/orphan sets include the controller `repairable` class (managed-by + reserved name, policy-type absent). When the Deployment omits `CONTEXT_MAPPER_RPC_PROXY_NAMESPACE`, the census assumes the compiled `rpc-proxy` default. |-| `CONTEXT_MAPPER_NETPOL_ORPHAN_DELETE_CAP_PERCENT` | `20` | Percent orphan-delete cap against the listed managed fleet. Strict `>`. Inert on a tiny inventory where `percent * listed < 1`. Values above 100 never fire. Same every-`fullReconcile` scope as the absolute cap; only binds when the fleet is small enough that 20% is below the absolute cap of 10. Non-canonical values fail loud at load. |-| `KUBERNETES_SERVICE_HOST` | _(injected by Kubernetes)_ | Not set by the operator — the `/32` fallback source when `CONTEXT_MAPPER_K8S_API_CIDRS` is empty. |+| Variable | Default | Description |+| ------------------------------------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `CONTEXT_MAPPER_RUNTIME_NAMESPACES` | `mcp-server,mcp-host,sandbox-recipes,rpc-proxy` | Namespaces that get L0 deny-all + L1 infrastructure policies. Manifest overrides to `mcp-server,sandbox-recipes,rpc-proxy,sandbox-ui` — note it **drops `mcp-host`**, whose policies are static (`deploy/base/mcp-host/networkpolicies.yaml`), because an HCC deny-all would block mcp-host from reaching LLM APIs. |+| `CONTEXT_MAPPER_MINIMAL_INFRA_NAMESPACES` | `` (empty) | Subset of runtime namespaces that get **only** deny-all + DNS egress — no HCC-API or K8s-API egress. Manifest sets `sandbox-ui`. |+| `CONTEXT_MAPPER_K8S_API_CIDRS` | _(unset → `[]`)_ | K8s API-server CIDRs for `allow-k8s-api-egress-*`. Empty falls back to `KUBERNETES_SERVICE_HOST`. **Validated fail-closed at module load**: a malformed entry, or one broader than `/24` (IPv4) or `/120` (IPv6), **crashes startup** rather than programming a permissive policy. |+| `CONTEXT_MAPPER_NODELOCAL_DNS_CIDR` | `` (empty) | DNS infrastructure CIDR for NodeLocal DNSCache / kube-dns. Must be exactly one IPv4 `/32`; anything else throws at startup. |+| `CONTEXT_MAPPER_NETPOL_RESYNC_SEC` | `0` | Periodic NetworkPolicy coordinated convergence (seconds). Re-enters the single-flight pass with `ensureDefaults: true` so a tick covers orphan sweep (class A) and L0/L1 defaults (class D). A tick while a pass is in flight is **skipped** (`clerum_hcc_netpol_resync_ticks_skipped_total{reason="pass-in-flight"}`) and does not coalesce; event-driven trailing is unchanged. `0` disables the interval (merge default). Startup still converges once; `start()` already applied defaults as a bootstrap barrier. Default `0` logs a `console.warn` on every boot (same pattern as Host/SFS/GFS/LlmHook) — expected; it names the self-heal gap. A non-canonical value (`25m`, `1e3`) **fails loud at load** instead of coercing through `parseInt`. **Enable is a separate ops decision** (issue #478, not this merge): with the skip guard the chosen value is **`1500`**; without the guard the floor is **`3600`**. `300` is not a valid enable while passes last minutes. Treadmill ⇔ pass duration ≥ period. Enable preconditions live on #478: image deployed, census read, histogram p99/max ≪ T, then infra **dev first**. |+| `CONTEXT_MAPPER_NETPOL_ORPHAN_DELETE_CAP` | `10` | Absolute orphan-delete cap for a namespace-wide NetworkPolicy sweep. Candidates **strictly above** this count refuse **deletes** and increment `clerum_hcc_netpol_orphan_sweep_capped_total`; the pass **still certifies** (#478: alert and do not delete). Governs every `fullReconcile` (startup, event-driven, timer). Absolute is checked first, so at a fleet ≥ 50 with these defaults the percent rule never binds. One cap over the **sum of all lanes** (not per-lane): a trip leaves those orphans in place until an operator raises the env; the signal is that counter. `0` refuses every orphan delete; a negative or non-canonical value (`2e1`, `10.9`) fails loud at load. Census: `scripts/ops/hcc-netpol-orphan-census.sh` — `live_cap_would_trip` is Deployment env only (`UNSET` when both keys are omitted, not `none`); `controller_cap_would_trip` applies compiled defaults when unset. Census listed/orphan sets include the controller `repairable` class (managed-by + reserved name, policy-type absent). When the Deployment omits `CONTEXT_MAPPER_RPC_PROXY_NAMESPACE`, the census assumes the compiled `rpc-proxy` default. |+| `CONTEXT_MAPPER_NETPOL_ORPHAN_DELETE_CAP_PERCENT` | `20` | Percent orphan-delete cap against the listed managed fleet. Strict `>`. Inert on a tiny inventory where `listed * percent / 100 < 1`. Values above 100 never fire. Same every-`fullReconcile` scope as the absolute cap; only binds when the fleet is small enough that 20% is below the absolute cap of 10. Non-canonical values fail loud at load. |+| `KUBERNETES_SERVICE_HOST` | _(injected by Kubernetes)_ | Not set by the operator — the `/32` fallback source when `CONTEXT_MAPPER_K8S_API_CIDRS` is empty. |### Plugin image allowlistdiff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 85f6b0842..d25fd9e7f 100644--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-host-context-controller",- "version": "0.1.254",+ "version": "0.1.255","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.254",+ "version": "0.1.255","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex bb14ab1fd..f2fa3361b 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.254",+ "version": "0.1.255","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/config.netPolResync.test.ts b/host-context-controller/src/config.netPolResync.test.tsindex f6586f9d9..4d95ddbdd 100644--- a/host-context-controller/src/config.netPolResync.test.ts+++ b/host-context-controller/src/config.netPolResync.test.ts@@ -79,4 +79,13 @@ describe('NetworkPolicy resync and orphan-sweep config (#478)', () => {).rejects.toThrow(/CONTEXT_MAPPER_NETPOL_ORPHAN_DELETE_CAP_PERCENT/)})++ it.each(['25m', '1e3', '-5', '0.5', '2e1', 'abc'] as const)(+ 'fails loud when the resync interval is non-canonical (%s)',+ async raw => {+ await expect(loadConfig({ CONTEXT_MAPPER_NETPOL_RESYNC_SEC: raw })).rejects.toThrow(+ /CONTEXT_MAPPER_NETPOL_RESYNC_SEC/+ )+ }+ )})diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.tsindex c720a4857..593728418 100644--- a/host-context-controller/src/config.ts+++ b/host-context-controller/src/config.ts@@ -174,7 +174,8 @@ export interface Config {// Periodic NetworkPolicy convergence interval (seconds). Re-enters the// coordinated single-flight pass (not a naked fullReconcile) so a dropped// watch cannot leave stale allows. Default 0 disables the interval; startup- // still runs one convergence pass. Set via CONTEXT_MAPPER_NETPOL_RESYNC_SEC.+ // still runs one convergence pass. Non-canonical values fail loud at load.+ // Set via CONTEXT_MAPPER_NETPOL_RESYNC_SEC.netPolResyncIntervalSec: number// Absolute orphan-delete cap for a NetworkPolicy fullReconcile sweep.@@ -783,7 +784,7 @@ export const config: Config = {// Periodic NetworkPolicy resync. Default 0 (disabled): startup still// converges once; the interval is opt-in so a bad cache cannot periodically// sweep. Unset or 0 → no interval.- netPolResyncIntervalSec: getEnvInt('CONTEXT_MAPPER_NETPOL_RESYNC_SEC', 0),+ netPolResyncIntervalSec: requireCanonicalNonNegativeEnvInt('CONTEXT_MAPPER_NETPOL_RESYNC_SEC', 0),// Mass-delete guard for the namespace-wide orphan sweep. Thresholds are// strict `>`: exactly N candidates still delete; N+1 refuses deletes and// still certifies.diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 8a4681e9d..1cbdf3a2e 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -11352,6 +11352,29 @@ describe('McpServerWatcher NetworkPolicy periodic resync (#478)', () => {)await watcher.stop()})++ it('M1 sibling: event-driven pass after a tick does not inherit ensureDefaults', async () => {+ vi.useFakeTimers()+ mockConfig.netPolResyncIntervalSec = 300+ const watcher = await startWatcherForNetPolResync()+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(1)++ await vi.advanceTimersByTimeAsync(300_000)+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(2)+ expect(mocks.netPolFullReconcile.mock.calls[1]?.[2]).toEqual(+ expect.objectContaining({ ensureDefaults: true })+ )++ await (watcher as any).runInitialNetworkPolicyConvergence()+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(3)+ expect(mocks.netPolFullReconcile).toHaveBeenLastCalledWith(+ expect.any(Array),+ expect.any(Array),+ expect.objectContaining({ ensureDefaults: false })+ )+ await watcher.stop()+ })+it('M2: a tick while a pass is in flight is skipped and does not trail', async () => {vi.useFakeTimers()mockConfig.netPolResyncIntervalSec = 300diff --git a/host-context-controller/src/networkPolicyReconciler.orphanSweep.test.ts b/host-context-controller/src/networkPolicyReconciler.orphanSweep.test.tsindex 61f1a9e43..6497cc2ae 100644--- a/host-context-controller/src/networkPolicyReconciler.orphanSweep.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.orphanSweep.test.ts@@ -288,6 +288,39 @@ describe('NetworkPolicy orphan sweep cap (#478)', () => {warnSpy.mockRestore()})+ it('M4 sibling: cap trip also refuses external-egress deletes and still certifies', async () => {+ const orphans = Array.from({ length: 11 }, (_, i) =>+ orphanContextAllow(`ctx-orphan-${i}-old-server`, `orphan-context-${i}`)+ )+ stubOrphanLists(mockApi, {+ context: orphans,+ external: [+ orphanExternalEgress('ext-egress-orphan-server-old-example-com-443', 'orphan-server'),+ ],+ })+ const complete = vi.fn()+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})++ await reconciler.fullReconcile([], [], {+ ensureDefaults: false,+ contextInventoryAuthoritative: () => true,+ serverInventoryAuthoritative: () => true,+ onAuthoritativeRevocationComplete: complete,+ })++ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(mockApi.deleteNamespacedNetworkPolicy).not.toHaveBeenCalledWith(+ expect.objectContaining({+ name: 'ext-egress-orphan-server-old-example-com-443',+ namespace: 'mcp-server',+ })+ )+ expect(netPolOrphanSweepCappedTotal.inc).toHaveBeenCalledWith({ reason: 'absolute' })+ expect(netPolOrphansDeletedTotal.inc).not.toHaveBeenCalled()+ expect(complete).toHaveBeenCalledOnce()+ warnSpy.mockRestore()+ })+it('M4 sibling: orphans over the percent share refuse deletes with reason=percent and still certify', async () => {const orphans = Array.from({ length: 5 }, (_, i) =>orphanContextAllow(`ctx-orphan-${i}-old-server`, `orphan-context-${i}`)diff --git a/scripts/ops/hcc-netpol-orphan-census.sh b/scripts/ops/hcc-netpol-orphan-census.shindex 572183556..9c99b5b3f 100755--- a/scripts/ops/hcc-netpol-orphan-census.sh+++ b/scripts/ops/hcc-netpol-orphan-census.sh@@ -12,8 +12,8 @@## CONTEXT_MAPPER_* knobs are read from the live host-context-controller# Deployment. Code defaults are never printed as cluster facts: an absent-# env is UNSET. `live_cap_would_trip` therefore stays none when the-# Deployment omitted the cap keys.+# env is UNSET. `live_cap_would_trip` is UNSET when the Deployment omitted+# both cap keys (not `none` — that means "evaluated, would not trip").## The running controller still applies compiled defaults in that case# (absolute 10, percent 20 — host-context-controller/src/config.ts).@@ -33,7 +33,8 @@## Double-samples 90s apart. Adjudicates only when the desired Context +# McpServer identity set is identical across samples; otherwise-# INCONCLUSIVE_RERUN.+# INCONCLUSIVE_RERUN. A sample that listed zero managed policies is+# INCONCLUSIVE_EMPTY, never CLEAN.## Usage:# CONTEXT=<kube-context> ./scripts/ops/hcc-netpol-orphan-census.sh@@ -54,11 +55,17 @@ kc() {}# Live Deployment env only. Missing keys are UNSET — never substitute-# controller source defaults as cluster facts.+# controller source defaults as cluster facts. A kubectl failure is not+# an absent key: fail closed instead of printing UNSET.deployment_env() {local key="$1"local value- value="$(kc -n "${HCC_NS}" get deploy "${HCC_DEPLOYMENT}" -o "jsonpath={.spec.template.spec.containers[0].env[?(@.name==\"${key}\")].value}" 2>/dev/null || true)"+ local rc=0+ value="$(kc -n "${HCC_NS}" get deploy "${HCC_DEPLOYMENT}" -o "jsonpath={.spec.template.spec.containers[0].env[?(@.name==\"${key}\")].value}")" || rc=$?+ if [[ "${rc}" -ne 0 ]]; then+ echo "[census] FATAL: kubectl failed reading ${key} from ${HCC_NS}/${HCC_DEPLOYMENT} (exit ${rc})" >&2+ exit 2+ fiif [[ -z "${value}" ]]; thenprintf "UNSET"else@@ -132,7 +139,7 @@ sample_state() {kc get networkpolicy -n "${MAPPER_NS}" -o jsonkc get networkpolicy -n "${HOST_NS}" -o jsonkc get networkpolicy -n "${RPC_NS}" -o json- } | jq -s "{items: [.[].items[]?]}"+ } | jq -s '{items: [.[].items[]?] | unique_by(.metadata.uid // ((.metadata.namespace // "") + "/" + (.metadata.name // "")))}')"local desired_contexts desired_servers listed untyped orphans orphan_count@@ -162,7 +169,7 @@ sample_state() {if [[ -z "${orphans}" ]]; thenorphan_count=0else- orphan_count="$(printf "%s\n" "${orphans}" | grep -c . || true)"+ orphan_count="$(printf "%s\n" "${orphans}" | awk 'NF { n++ } END { print n+0 }')"fiprintf "DESIRED_CONTEXTS=%s\n" "${desired_contexts}"@@ -238,8 +245,20 @@ cap_would_trip() {fi}+if ! is_uint "${LISTED}" || ! is_uint "${ORPHAN_COUNT}"; then+ echo "[census] live_cap_would_trip=malformed"+ echo "[census] compiled_default_absolute=${COMPILED_ABS_DEFAULT} compiled_default_percent=${COMPILED_PCT_DEFAULT}"+ echo "[census] controller_cap_would_trip=malformed (listed_managed or orphan_count is not an unsigned integer)"+ echo "[census] VERDICT=INCONCLUSIVE_EMPTY"+ echo "[census] listed_managed or orphan_count is not an unsigned integer; do not treat this as CLEAN" >&2+ echo "[census] hint: re-check CONTEXT, mapper/host/rpc-proxy namespaces, and kubectl connectivity" >&2+ exit 4+fi+CAP_REASON="none"-if [[ "${ORPHAN_CAP}" != "UNSET" ]]; then+if [[ "${ORPHAN_CAP}" == "UNSET" && "${ORPHAN_CAP_PCT}" == "UNSET" ]]; then+ CAP_REASON="UNSET"+elif [[ "${ORPHAN_CAP}" != "UNSET" ]]; thenif ! is_uint "${ORPHAN_CAP}"; thenCAP_REASON="malformed"elif [[ "${ORPHAN_COUNT}" -gt "${ORPHAN_CAP}" ]]; then@@ -274,6 +293,12 @@ CONTROLLER_CAP_REASON="$(cap_would_trip "${ORPHAN_COUNT}" "${LISTED}" "${CONTROLecho "[census] live_cap_would_trip=${CAP_REASON}"echo "[census] compiled_default_absolute=${COMPILED_ABS_DEFAULT} compiled_default_percent=${COMPILED_PCT_DEFAULT}"echo "[census] controller_cap_would_trip=${CONTROLLER_CAP_REASON} (live env, else compiled defaults)"+if [[ "${LISTED}" -eq 0 ]]; then+ echo "[census] VERDICT=INCONCLUSIVE_EMPTY"+ echo "[census] listed zero managed NetworkPolicies; \"found nothing\" is not CLEAN"+ echo "[census] hint: re-check CONTEXT, CONTEXT_MAPPER_RPC_PROXY_NAMESPACE, and kubectl connectivity"+ exit 4+fiif [[ "${ORPHAN_COUNT}" -eq 0 ]]; thenecho "[census] VERDICT=CLEAN"else