Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(hcc): observe create attempts and existence reads
Alfredo Lopez28d6e488ab6c
diff --git a/host-context-controller/CREATE_OBSERVABILITY.md b/host-context-controller/CREATE_OBSERVABILITY.mdnew file mode 100644index 000000000..f1456e1bb--- /dev/null+++ b/host-context-controller/CREATE_OBSERVABILITY.md@@ -0,0 +1,115 @@+# HCC create and existence-read metrics++This instrumentation supports issue #598. It observes the existing reconciliation+paths; it does not introduce read-before-create, extra Kubernetes requests,+ownership rules, retries, or updates to resources currently left unchanged.++## Counters++Both counters use the existing HCC Prometheus registry and the bounded labels+`kind` and `outcome`. The kind inventory is NetworkPolicy, Service, Deployment,+ConfigMap, PersistentVolumeClaim, ServiceAccount, Role, RoleBinding,+PodDisruptionBudget, and Secret. No resource names, namespaces, user identifiers,+request bodies, or exception messages become metric labels.++| Counter | Outcome | Meaning |+| ---------------------------------- | ---------- | -------------------------------------------------------------------------------------------------------- |+| `clerum_hcc_creates_total` | `issued` | One invocation of a Kubernetes create operation, including failed attempts. |+| | `conflict` | An issued create rejected with HTTP 409. This is a subset of `issued`, not an exclusive outcome. |+| | `skipped` | Reserved for a future presence-based create suppression; remains zero in this instrumentation change. |+| `clerum_hcc_existence_reads_total` | `found` | An instrumented existence read resolved successfully. The wrapper does not validate or alter its result. |+| | `absent` | An instrumented read rejected with HTTP 404; the original error still reaches the caller. |+| | `error` | An instrumented read rejected for any other reason, including HTTP 409. |++The bounded series are initialized at zero. Re-importing metrics must preserve+the registry and existing values. A zero series alone is not proof that a path+executed. Do not sum create outcomes to calculate request count.++`observeCreate` and `observeExistenceRead` invoke their callbacks once and preserve+the returned value or rejected value. They do not swallow a 404, turn it into+`null`, retry a failed request, or convert an error into a create. Existing caller+catch behavior remains responsible for those decisions. Synchronous client+failures count as attempts/outcomes too, so these counters are client-operation+observations rather than proof that every attempt reached the API server.++## Coverage++All 24 production `createNamespaced*` expressions are observed, including the+already-read-first Secret and the safety-inventory NetworkPolicy writer. Their+exemption from future conversion does not exempt them from measurement.++The 21 instrumented existence-read expressions are:++| File | Read paths | Expressions |+| ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ----------: |+| `src/utils.ts` | Shared NetworkPolicy conflict convergence | 1 |+| `src/hostReconciler.ts` | Role; runtime Secret; channel-reader Service; channel-reader Deployment outer read and retry; PVC; Host Service and Deployment | 8 |+| `src/reconciler.ts` | ConfigMap, Deployment, Service conflict convergence | 3 |+| `src/llmHookReconciler.ts` | Deployment, Service, NetworkPolicy conflict convergence | 3 |+| `src/sharedFileSystemReconciler.ts` | Deployment conflict convergence | 1 |+| `src/k8s/gfsK8sApi.ts` | Deployment update check and conflict convergence; PDB conflict convergence | 3 |+| `src/networkPolicyReconciler.ts` | Fresh external-egress observation; safety-create conflict convergence | 2 |++Counts refer to source expressions, not requests per reconciliation. Retry paths+can execute more than once. The fresh external-egress helper has several callers;+all invocations are counted, including checks where no later write is necessary.++This is not a counter of all HCC reads. LISTs, reads of input objects used to build+a desired spec, readiness checks, scale-only operations, and safety replace/delete+paths unrelated to a create decision are excluded. An already-available snapshot+does not represent another API read. The inventory must be updated when a writer+or its read path changes; do not instrument both the API call and its retry wrapper.++## Historical evidence and attribution limits++The original five five-minute windows contained 1,684 / 1,833 / 1,669 / 1,171 /+2,107 HCC create conflicts. These are historical observations, not acceptance+thresholds, a performance benchmark, or validation of this candidate.++A metadata-only re-query of the historical `reg3` window (2026-09-09+08:30:00–08:35:00 UTC) returned 1,846 conflicts for the four selected kinds,+below its 20,000-result cap: NetworkPolicy 1,020; Service 389; Deployment 381;+PVC 56. These exactly match the archived aggregate for those kinds.++| Kind | Observed name-family counts |+| ------------- | --------------------------------------------------------------------------------------------------------------------- |+| NetworkPolicy | `ctx-` 509; `rpc-egress-` 254; `wfc-` 56; `channel-reader-` 22; `gfsc-` 12; `llmhook-` 4; `ext-egress-` 12; other 151 |+| Deployment | `channel-reader-` 20; `gfsc-` 6; `llmhook-` 4; `wfc-` 28; other 323 |+| Service | `channel-reader-` 20; `gfsc-` 6; `llmhook-` 4; `wfc-` 28; other 331 |+| PVC | other 56 |++These are prefix observations, not executed call-site traces. The classifier used+the literal `gfsc-` prefix, so the exact Service name `gfsc` belongs to `other`.+The PVC factories also fall outside the selected prefixes. Do not assign their+counts to a caller by subtraction.++Code maps the first five NetworkPolicy families to the shared apply helper (853+conflicts in total), but this is source-derived attribution. `ext-egress-` can+reach both that helper and the safety writer. Other names include additional+LlmHook policies. General Host/McpServer Service and Deployment names have no+mandatory prefix, so prefix matches alone do not exclude collisions. Namespace,+the relevant inventory, and writer provenance are needed before asserting a+unique site. Complete per-expression attribution remains unproven.++## Validating a deployment++Compare counter increments and audit events from the same exact half-open UTC+window, cluster, HCC identity, image/revision, and replica set. Account for process+restarts, scrape gaps, ingestion delay, and query truncation. Record successful+command exits and retained-row counts; missing data is unknown, not zero. Local+tests and a historical re-query do not replace simultaneous deployed validation.++For create conflicts, compare the `conflict` subset with the audit's conflict+result, not with all issued operations. The audit uses `google.rpc.Code=10`,+which represents conflict, while client errors use HTTP 409. Historical audit+data did not contain GET records; no API-server read rate is inferred from that+absence. The read counter only covers the explicit inventory above.++No fixed GET-to-POST ratio is required: an existing POST409→GET path already+reads, whereas a create-and-ignore-conflict path does not. Future read-first+work must preserve that distinction. This change does not demonstrate savings+in CPU, latency, admission cost, APF, or request volume.++The next read-first PR remains dependent on deployment and validated measurement+of this instrumentation. T0, T1, T2, CI, and browser E2E are separate evidence+lanes; see [the local runtime runbook](../docs/testing/minikube-t2-runbook.md).diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex a62bb6812..b27f5eef3 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.297",+ "version": "0.1.298","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.297",+ "version": "0.1.298","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 55d3bb0c6..625714367 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.297",+ "version": "0.1.298","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/createMetrics.test.ts b/host-context-controller/src/createMetrics.test.tsnew file mode 100644index 000000000..9b65b5185--- /dev/null+++ b/host-context-controller/src/createMetrics.test.ts@@ -0,0 +1,182 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type * as k8s from '@kubernetes/client-node'+import { readFileSync, readdirSync } from 'node:fs'+import { join } from 'node:path'+import ts from 'typescript'+import { CREATE_KINDS, createsTotal, registry } from './metrics'+import { applyNetworkPolicy, observeCreate } from './utils'++async function count(kind: string, outcome: string): Promise<number> {+ const snapshot = await createsTotal.get()+ const sample = snapshot.values.find(v => v.labels.kind === kind && v.labels.outcome === outcome)+ expect(sample, `Missing ${kind}/${outcome} sample`).toBeDefined()+ return sample!.value+}++it('initializes create samples in the real registry before any test seeding', async () => {+ expect(registry.getSingleMetric('clerum_hcc_creates_total')).toBe(createsTotal)+ for (const kind of CREATE_KINDS) {+ for (const outcome of ['issued', 'conflict', 'skipped']) {+ expect(await count(kind, outcome)).toBe(0)+ }+ }+})++describe('Kubernetes create instrumentation', () => {+ beforeEach(() => {+ createsTotal.reset()+ for (const kind of CREATE_KINDS) {+ for (const outcome of ['issued', 'conflict', 'skipped']) {+ createsTotal.inc({ kind, outcome }, 0)+ }+ }+ })++ it('instruments the complete production create inventory with the matching kind', () => {+ const kinds: string[] = []+ const root = new URL('.', import.meta.url).pathname+ for (const relative of readdirSync(root, { recursive: true }) as string[]) {+ if (+ !relative.endsWith('.ts') ||+ relative.endsWith('.test.ts') ||+ relative.includes('__tests__')+ )+ continue+ const file = ts.createSourceFile(+ relative,+ readFileSync(join(root, relative), 'utf8'),+ ts.ScriptTarget.Latest,+ true+ )+ const visit = (node: ts.Node): void => {+ if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression)) {+ const match = /^create(?:Namespaced|Cluster)(.+)$/.exec(node.expression.name.text)+ if (match) {+ kinds.push(match[1])+ const arrow = node.parent+ expect(ts.isArrowFunction(arrow), `${relative}: ${node.expression.name.text}`).toBe(+ true+ )+ const wrapper = arrow.parent+ expect(ts.isCallExpression(wrapper)).toBe(true)+ if (ts.isCallExpression(wrapper)) {+ expect(wrapper.expression.getText(file)).toBe('observeCreate')+ expect(wrapper.arguments[0].getText(file)).toBe(`'${match[1]}'`)+ }+ }+ }+ ts.forEachChild(node, visit)+ }+ visit(file)+ }+ expect(kinds).toHaveLength(24)+ expect([...new Set(kinds)].sort()).toEqual([...CREATE_KINDS].sort())+ })++ it('preserves a synchronous client failure and counts the attempt', async () => {+ const error = new Error('client request construction failed')+ const create = vi.fn(() => {+ throw error+ })+ await expect(observeCreate('Service', create)).rejects.toBe(error)+ expect(create).toHaveBeenCalledTimes(1)+ expect(await count('Service', 'issued')).toBe(1)+ expect(await count('Service', 'conflict')).toBe(0)+ })++ it('preserves real registry samples and nonzero counts across re-import', async () => {+ // Existing observations must survive module initialization without being reset.+ const create = vi.fn().mockResolvedValue({})+ await observeCreate('Service', create)+ expect(create).toHaveBeenCalledTimes(1)+ vi.resetModules()+ const reloaded = await import('./metrics')+ expect(reloaded.registry).toBe(registry)+ expect(reloaded.createsTotal).toBe(createsTotal)+ const exposition = await registry.metrics()+ for (const kind of CREATE_KINDS) {+ for (const outcome of ['issued', 'conflict', 'skipped']) {+ expect(exposition).toContain(`clerum_hcc_creates_total{kind="${kind}",outcome="${outcome}"`)+ expect(await count(kind, outcome)).toBe(kind === 'Service' && outcome === 'issued' ? 1 : 0)+ }+ }+ })++ it('issues exactly once and returns the original server response', async () => {+ const response = { metadata: { uid: 'created-policy', resourceVersion: '17' } }+ const create = vi.fn(async () => {+ expect(await count('NetworkPolicy', 'issued')).toBe(1)+ return response+ })+ expect(await observeCreate('NetworkPolicy', create)).toBe(response)+ expect(create).toHaveBeenCalledTimes(1)+ expect(await count('NetworkPolicy', 'issued')).toBe(1)+ expect(await count('NetworkPolicy', 'conflict')).toBe(0)+ expect(await count('NetworkPolicy', 'skipped')).toBe(0)+ })++ it.each([{ code: 409 }, { response: { statusCode: 409 } }])(+ 'counts a conflict as a subset of attempts and preserves the error: %j',+ async error => {+ const create = vi.fn().mockRejectedValue(error)+ await expect(observeCreate('Service', create)).rejects.toBe(error)+ expect(create).toHaveBeenCalledTimes(1)+ expect(await count('Service', 'issued')).toBe(1)+ expect(await count('Service', 'conflict')).toBe(1)+ expect(await count('Service', 'skipped')).toBe(0)+ }+ )++ it.each([{ code: 403 }, { code: 500 }, { code: 'ECONNRESET' }, null, undefined])(+ 'propagates non-conflict errors without retrying or counting a conflict: %j',+ async error => {+ const create = vi.fn().mockRejectedValue(error)+ await expect(observeCreate('Deployment', create)).rejects.toBe(error)+ expect(create).toHaveBeenCalledTimes(1)+ expect(await count('Deployment', 'issued')).toBe(1)+ expect(await count('Deployment', 'conflict')).toBe(0)+ }+ )++ it('observes the existing POST-first conflict path without counting replace conflicts', async () => {+ const policy: k8s.V1NetworkPolicy = {+ kind: 'NetworkPolicy',+ metadata: { name: 'metrics-policy' },+ spec: { podSelector: {}, policyTypes: ['Ingress'], ingress: [] },+ }+ const api = {+ createNamespacedNetworkPolicy: vi.fn().mockRejectedValue({ code: 409 }),+ readNamespacedNetworkPolicy: vi.fn().mockResolvedValue(policy),+ replaceNamespacedNetworkPolicy: vi.fn(),+ }+ await applyNetworkPolicy(+ api as unknown as k8s.NetworkingV1Api,+ 'metrics-policy',+ 'test',+ policy+ )+ expect(api.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)+ expect(api.readNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)+ expect(api.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(await count('NetworkPolicy', 'issued')).toBe(1)+ expect(await count('NetworkPolicy', 'conflict')).toBe(1)+ expect(await count('NetworkPolicy', 'skipped')).toBe(0)+ })++ it('does not count a create when its mutation fence has already expired', async () => {+ const allowed = vi.fn(() => false)+ const create = vi.fn()+ await applyNetworkPolicy(+ { createNamespacedNetworkPolicy: create } as unknown as k8s.NetworkingV1Api,+ 'metrics-policy',+ 'test',+ {},+ '[test]',+ allowed+ )+ expect(allowed).toHaveBeenCalledTimes(1)+ expect(create).not.toHaveBeenCalled()+ expect(await count('NetworkPolicy', 'issued')).toBe(0)+ expect(await count('NetworkPolicy', 'skipped')).toBe(0)+ })+})diff --git a/host-context-controller/src/existenceReadMetrics.test.ts b/host-context-controller/src/existenceReadMetrics.test.tsnew file mode 100644index 000000000..d5923a833--- /dev/null+++ b/host-context-controller/src/existenceReadMetrics.test.ts@@ -0,0 +1,268 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type * as k8s from '@kubernetes/client-node'+import { readFileSync } from 'node:fs'+import ts from 'typescript'+import { CREATE_KINDS, createsTotal, existenceReadsTotal, registry } from './metrics'+import { applyNetworkPolicy, observeExistenceRead } from './utils'++async function count(kind: string, outcome: string): Promise<number> {+ const sample = (await existenceReadsTotal.get()).values.find(+ value => value.labels.kind === kind && value.labels.outcome === outcome+ )+ expect(sample).toBeDefined()+ return sample!.value+}++it('initializes the real read registry before any test seeding', async () => {+ expect(registry.getSingleMetric('clerum_hcc_existence_reads_total')).toBe(existenceReadsTotal)+ const snapshot = await existenceReadsTotal.get()+ expect(snapshot.values).toHaveLength(CREATE_KINDS.length * 3)+ for (const kind of CREATE_KINDS) {+ for (const outcome of ['found', 'absent', 'error']) expect(await count(kind, outcome)).toBe(0)+ }+ for (const sample of snapshot.values)+ expect(Object.keys(sample.labels).sort()).toEqual(['kind', 'outcome'])+})++it('observes the documented physical GET expressions without wrapping snapshots or lists', () => {+ const inventory: Record<string, number> = {+ 'utils.ts': 1,+ 'hostReconciler.ts': 8,+ 'reconciler.ts': 3,+ 'llmHookReconciler.ts': 3,+ 'sharedFileSystemReconciler.ts': 1,+ 'k8s/gfsK8sApi.ts': 3,+ 'networkPolicyReconciler.ts': 2,+ }+ let total = 0+ for (const [path, expected] of Object.entries(inventory)) {+ const source = ts.createSourceFile(+ path,+ readFileSync(new URL(path, import.meta.url), 'utf8'),+ ts.ScriptTarget.Latest,+ true+ )+ let calls = 0+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === 'observeExistenceRead'+ ) {+ calls+++ const [kind, read] = node.arguments+ expect(ts.isStringLiteral(kind), path).toBe(true)+ expect(ts.isArrowFunction(read), path).toBe(true)+ if (ts.isStringLiteral(kind) && ts.isArrowFunction(read)) {+ expect(ts.isCallExpression(read.body), path).toBe(true)+ if (+ ts.isCallExpression(read.body) &&+ ts.isPropertyAccessExpression(read.body.expression)+ ) {+ expect(read.body.expression.name.text, path).toBe(`readNamespaced${kind.text}`)+ } else throw new Error(`${path}: the wrapper must observe a direct API read`)+ }+ }+ ts.forEachChild(node, visit)+ }+ visit(source)+ expect(calls, path).toBe(expected)+ total += calls+ }+ expect(total).toBe(21)+})++describe('Kubernetes existence-read instrumentation', () => {+ beforeEach(() => {+ existenceReadsTotal.reset()+ createsTotal.reset()+ for (const kind of CREATE_KINDS) {+ for (const outcome of ['found', 'absent', 'error'])+ existenceReadsTotal.inc({ kind, outcome }, 0)+ for (const outcome of ['issued', 'conflict', 'skipped'])+ createsTotal.inc({ kind, outcome }, 0)+ }+ })++ it.each([{ metadata: { uid: 'existing', resourceVersion: '17' } }, null, undefined])(+ 'returns the exact resolved value with one read: %j',+ async response => {+ const read = vi.fn().mockResolvedValue(response)+ expect(await observeExistenceRead('Service', read)).toBe(response)+ expect(read).toHaveBeenCalledTimes(1)+ expect(await count('Service', 'found')).toBe(1)+ expect(await count('Service', 'absent')).toBe(0)+ expect(await count('Service', 'error')).toBe(0)+ expect((await createsTotal.get()).values.every(sample => sample.value === 0)).toBe(true)+ }+ )++ it.each([+ [{ code: 404 }, 'absent'],+ [{ response: { statusCode: 404 } }, 'absent'],+ [{ code: 403 }, 'error'],+ [{ response: { statusCode: 500 } }, 'error'],+ [{ code: 409 }, 'error'],+ [{ code: 'ECONNRESET' }, 'error'],+ [null, 'error'],+ [undefined, 'error'],+ ] as const)(+ 'preserves rejection identity and classifies only 404 as absent: %j',+ async (error, outcome) => {+ const read = vi.fn().mockRejectedValue(error)+ await expect(observeExistenceRead('Service', read)).rejects.toBe(error)+ expect(read).toHaveBeenCalledTimes(1)+ for (const candidate of ['found', 'absent', 'error'])+ expect(await count('Service', candidate)).toBe(candidate === outcome ? 1 : 0)+ }+ )++ it.each([{ code: 404 }, new Error('request construction failed'), null, undefined])(+ 'preserves synchronous throws with one attempt: %j',+ async error => {+ const read = vi.fn(() => {+ throw error+ })+ await expect(observeExistenceRead('Deployment', read)).rejects.toBe(error)+ expect(read).toHaveBeenCalledTimes(1)+ expect(await count('Deployment', error && 'code' in error ? 'absent' : 'error')).toBe(1)+ }+ )++ it('preserves existing observations across module re-import', async () => {+ const response = { metadata: { uid: 'observed' } }+ const read = vi.fn().mockResolvedValue(response)+ expect(await observeExistenceRead('Service', read)).toBe(response)+ vi.resetModules()+ const reloaded = await import('./metrics')+ expect(reloaded.registry).toBe(registry)+ expect(reloaded.existenceReadsTotal).toBe(existenceReadsTotal)+ expect(read).toHaveBeenCalledTimes(1)+ expect(await count('Service', 'found')).toBe(1)+ expect(await registry.metrics()).toMatch(+ /clerum_hcc_existence_reads_total\{kind="Service",outcome="found"[^}]*\} 1/+ )+ })++ const policy: k8s.V1NetworkPolicy = {+ kind: 'NetworkPolicy',+ metadata: { name: 'read-metrics-policy' },+ spec: { podSelector: {}, policyTypes: ['Ingress'], ingress: [] },+ }++ it('preserves POST-first success without adding an existence request', async () => {+ const api = {+ createNamespacedNetworkPolicy: vi.fn().mockResolvedValue(policy),+ readNamespacedNetworkPolicy: vi.fn(),+ }+ await applyNetworkPolicy(+ api as unknown as k8s.NetworkingV1Api,+ 'read-metrics-policy',+ 'test',+ policy+ )+ expect(api.createNamespacedNetworkPolicy).toHaveBeenCalledExactlyOnceWith({+ namespace: 'test',+ body: policy,+ })+ expect(api.readNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(await count('NetworkPolicy', 'found')).toBe(0)+ })++ it('attributes GET conflicts to reads without adding POST conflicts or retrying', async () => {+ const error = { response: { statusCode: 409 } }+ const api = {+ createNamespacedNetworkPolicy: vi.fn().mockRejectedValue({ code: 409 }),+ readNamespacedNetworkPolicy: vi.fn().mockRejectedValue(error),+ replaceNamespacedNetworkPolicy: vi.fn(),+ }+ await expect(+ applyNetworkPolicy(+ api as unknown as k8s.NetworkingV1Api,+ 'read-metrics-policy',+ 'test',+ policy+ )+ ).rejects.toBe(error)+ expect(api.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)+ expect(api.readNamespacedNetworkPolicy).toHaveBeenCalledExactlyOnceWith({+ name: 'read-metrics-policy',+ namespace: 'test',+ })+ expect(api.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ expect(await count('NetworkPolicy', 'error')).toBe(1)+ const samples = (await createsTotal.get()).values.filter(+ sample => sample.labels.kind === 'NetworkPolicy'+ )+ expect(samples.map(sample => [sample.labels.outcome, sample.value])).toEqual([+ ['issued', 1],+ ['conflict', 1],+ ['skipped', 0],+ ])+ })++ it('counts physical retry reads once and preserves fresh resource versions', async () => {+ const events: string[] = []+ let reads = 0+ const api = {+ createNamespacedNetworkPolicy: vi.fn(async () => {+ events.push('POST')+ throw { code: 409 }+ }),+ readNamespacedNetworkPolicy: vi.fn(async () => {+ events.push('GET')+ return {+ ...policy,+ metadata: { ...policy.metadata, resourceVersion: String(++reads) },+ spec: { ...policy.spec, ingress: [{}] },+ }+ }),+ replaceNamespacedNetworkPolicy: vi.fn(async ({ body }: { body: k8s.V1NetworkPolicy }) => {+ events.push('PUT:' + body.metadata?.resourceVersion)+ if (body.metadata?.resourceVersion === '1') throw { code: 409 }+ return body+ }),+ }+ await applyNetworkPolicy(+ api as unknown as k8s.NetworkingV1Api,+ 'read-metrics-policy',+ 'test',+ policy+ )+ expect(events).toEqual(['POST', 'GET', 'PUT:1', 'GET', 'PUT:2'])+ expect(api.readNamespacedNetworkPolicy).toHaveBeenCalledTimes(2)+ expect(api.replaceNamespacedNetworkPolicy).toHaveBeenCalledTimes(2)+ expect(await count('NetworkPolicy', 'found')).toBe(2)+ expect(await count('NetworkPolicy', 'error')).toBe(0)+ const conflicts = (await createsTotal.get()).values.find(+ sample => sample.labels.kind === 'NetworkPolicy' && sample.labels.outcome === 'conflict'+ )+ expect(conflicts?.value).toBe(1)+ })++ it('observes a read that expires the existing fence and prevents replace', async () => {+ let active = true+ const allowed = vi.fn(() => active)+ const api = {+ createNamespacedNetworkPolicy: vi.fn().mockRejectedValue({ code: 409 }),+ readNamespacedNetworkPolicy: vi.fn(async () => {+ active = false+ return { ...policy, spec: { ...policy.spec, ingress: [{}] } }+ }),+ replaceNamespacedNetworkPolicy: vi.fn(),+ }+ await applyNetworkPolicy(+ api as unknown as k8s.NetworkingV1Api,+ 'read-metrics-policy',+ 'test',+ policy,+ '[test]',+ allowed+ )+ expect(allowed.mock.results.map(result => result.value)).toEqual([true, false])+ expect(api.createNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)+ expect(api.readNamespacedNetworkPolicy).toHaveBeenCalledTimes(1)+ expect(await count('NetworkPolicy', 'found')).toBe(1)+ expect(api.replaceNamespacedNetworkPolicy).not.toHaveBeenCalled()+ })+})diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 730a2c5e6..6fd28f36e 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -78,6 +78,8 @@ import {canonicalizeValue,deploymentMatchesDesired,getErrorCode,+ observeCreate,+ observeExistenceRead,preserveDeploymentAnnotations,preserveServiceAssignedFields,replaceWithConflictRetry,@@ -1027,7 +1029,9 @@ export class HostReconciler {metadata: { name, namespace: host.namespace, labels: this.rbacLabels(host) },}try {- await this.coreApi.createNamespacedServiceAccount({ namespace: host.namespace, body })+ await observeCreate('ServiceAccount', () =>+ this.coreApi.createNamespacedServiceAccount({ namespace: host.namespace, body })+ )console.log(`[HostReconciler] Created ServiceAccount "${name}"`)} catch (err) {if (getErrorCode(err) === 409) return // already exists; SA itself has no spec to update@@ -1080,7 +1084,9 @@ export class HostReconciler {],}try {- await this.rbacApi.createNamespacedRole({ namespace: host.namespace, body })+ await observeCreate('Role', () =>+ this.rbacApi.createNamespacedRole({ namespace: host.namespace, body })+ )console.log(`[HostReconciler] Created Role "${name}"`)return} catch (err) {@@ -1091,7 +1097,9 @@ export class HostReconciler {}// Already exists — replace to pick up rotated secretRef / new resourceNames.try {- const existing = await this.rbacApi.readNamespacedRole({ name, namespace: host.namespace })+ const existing = await observeExistenceRead('Role', () =>+ this.rbacApi.readNamespacedRole({ name, namespace: host.namespace })+ )if (roleMatchesDesired(body, existing)) returnbody.metadata!.resourceVersion = existing.metadata?.resourceVersionawait this.rbacApi.replaceNamespacedRole({ name, namespace: host.namespace, body })@@ -1124,7 +1132,9 @@ export class HostReconciler {},}try {- await this.rbacApi.createNamespacedRoleBinding({ namespace: host.namespace, body })+ await observeCreate('RoleBinding', () =>+ this.rbacApi.createNamespacedRoleBinding({ namespace: host.namespace, body })+ )console.log(`[HostReconciler] Created RoleBinding "${name}"`)} catch (err) {if (getErrorCode(err) === 409) return@@ -1616,7 +1626,9 @@ export class HostReconciler {const name = mcpHostRuntimeTokenSecretName(host)let existing: k8s.V1Secret | null = nulltry {- existing = await this.coreApi.readNamespacedSecret({ name, namespace: host.namespace })+ existing = await observeExistenceRead('Secret', () =>+ this.coreApi.readNamespacedSecret({ name, namespace: host.namespace })+ )} catch (err) {if (getErrorCode(err) !== 404) throw err}@@ -1833,7 +1845,9 @@ export class HostReconciler {}if (!existing) {- await this.coreApi.createNamespacedSecret({ namespace: host.namespace, body })+ await observeCreate('Secret', () =>+ this.coreApi.createNamespacedSecret({ namespace: host.namespace, body })+ )this.gfsTokenLifecycleEvidence.set(HostReconciler.gfsLifecycleEvidenceKey(host), {gfs_subject: expectedGfsSubject,gfs_outcome: 'minted',@@ -2488,10 +2502,12 @@ export class HostReconciler {const service = this.buildChannelReaderService(host)try {- await this.coreApi.createNamespacedService({- namespace: ns,- body: service,- })+ await observeCreate('Service', () =>+ this.coreApi.createNamespacedService({+ namespace: ns,+ body: service,+ })+ )console.log(`[HostReconciler] Created channel-reader Service "${name}"`)} catch (err) {if (getErrorCode(err) !== 409) {@@ -2505,7 +2521,10 @@ export class HostReconciler {body: service,mergeExisting: preserveServiceAssignedFields,isUpToDate: serviceMatchesDesired,- read: () => this.coreApi.readNamespacedService({ name, namespace: ns }),+ read: () =>+ observeExistenceRead('Service', () =>+ this.coreApi.readNamespacedService({ name, namespace: ns })+ ),replace: body =>this.coreApi.replaceNamespacedService({name,@@ -2546,7 +2565,9 @@ export class HostReconciler {const desired = this.buildChannelReaderDeployment(host, revision)try {- await this.appsApi.createNamespacedDeployment({ namespace: ns, body: desired })+ await observeCreate('Deployment', () =>+ this.appsApi.createNamespacedDeployment({ namespace: ns, body: desired })+ )console.log(`[HostReconciler] Created channel-reader Deployment "${name}"`)} catch (err) {if (getErrorCode(err) !== 409) {@@ -2555,7 +2576,9 @@ export class HostReconciler {}let existing: k8s.V1Deploymenttry {- existing = await this.appsApi.readNamespacedDeployment({ name, namespace: ns })+ existing = await observeExistenceRead('Deployment', () =>+ this.appsApi.readNamespacedDeployment({ name, namespace: ns })+ )} catch (readErr) {if (getErrorCode(readErr) === 404) {console.warn(@@ -2584,7 +2607,10 @@ export class HostReconciler {// B2: rebuild against each fresh read so an unsynced CC cache// preserves the live replica count even after a 409 retry.body: this.buildChannelReaderDeployment(host, revision, existing.spec?.replicas),- read: () => this.appsApi.readNamespacedDeployment({ name, namespace: ns }),+ read: () =>+ observeExistenceRead('Deployment', () =>+ this.appsApi.readNamespacedDeployment({ name, namespace: ns })+ ),replace: body =>this.appsApi.replaceNamespacedDeployment({name,@@ -3314,18 +3340,22 @@ export class HostReconciler {const pvc = this.buildPvc(host)const name = this.pvcName(host)try {- await this.coreApi.createNamespacedPersistentVolumeClaim({- namespace: host.namespace,- body: pvc,- })+ await observeCreate('PersistentVolumeClaim', () =>+ this.coreApi.createNamespacedPersistentVolumeClaim({+ namespace: host.namespace,+ body: pvc,+ })+ )console.log(`[HostReconciler] Created PVC "${name}"`)} catch (error) {if (getErrorCode(error) === 409) {try {- const existing = await this.coreApi.readNamespacedPersistentVolumeClaim({- namespace: host.namespace,- name,- })+ const existing = await observeExistenceRead('PersistentVolumeClaim', () =>+ this.coreApi.readNamespacedPersistentVolumeClaim({+ namespace: host.namespace,+ name,+ })+ )if (existing.spec?.volumeName) {return}@@ -3348,10 +3378,12 @@ export class HostReconciler {private async ensureService(host: HostCRD): Promise<void> {const service = this.buildService(host)try {- await this.coreApi.createNamespacedService({- namespace: host.namespace,- body: service,- })+ await observeCreate('Service', () =>+ this.coreApi.createNamespacedService({+ namespace: host.namespace,+ body: service,+ })+ )console.log(`[HostReconciler] Created Service "${host.name}"`)} catch (error) {if (getErrorCode(error) === 409) {@@ -3363,10 +3395,12 @@ export class HostReconciler {mergeExisting: preserveServiceAssignedFields,isUpToDate: serviceMatchesDesired,read: () =>- this.coreApi.readNamespacedService({- namespace: host.namespace,- name: host.name,- }),+ observeExistenceRead('Service', () =>+ this.coreApi.readNamespacedService({+ namespace: host.namespace,+ name: host.name,+ })+ ),replace: body =>this.coreApi.replaceNamespacedService({namespace: host.namespace,@@ -3401,10 +3435,12 @@ export class HostReconciler {}const deployment = await buildDesiredDeployment()try {- await this.appsApi.createNamespacedDeployment({- namespace: host.namespace,- body: deployment,- })+ await observeCreate('Deployment', () =>+ this.appsApi.createNamespacedDeployment({+ namespace: host.namespace,+ body: deployment,+ })+ )console.log(`[HostReconciler] Created Deployment "${host.name}"`)} catch (error) {if (getErrorCode(error) !== 409) {@@ -3420,10 +3456,12 @@ export class HostReconciler {mergeExisting: preserveHostDeploymentAnnotations,isUpToDate: deploymentMatchesDesired,read: () =>- this.appsApi.readNamespacedDeployment({- namespace: host.namespace,- name: host.name,- }),+ observeExistenceRead('Deployment', () =>+ this.appsApi.readNamespacedDeployment({+ namespace: host.namespace,+ name: host.name,+ })+ ),replace: body =>this.appsApi.replaceNamespacedDeployment({namespace: host.namespace,diff --git a/host-context-controller/src/k8s/gfsK8sApi.ts b/host-context-controller/src/k8s/gfsK8sApi.tsindex 769a368b6..8b7d6b926 100644--- a/host-context-controller/src/k8s/gfsK8sApi.ts+++ b/host-context-controller/src/k8s/gfsK8sApi.ts@@ -1,7 +1,13 @@import * as k8s from '@kubernetes/client-node'import type { GfsK8sApi } from '../gfsReconciler'import type { GlobalFileSystemStatus } from '../types'-import { applyNetworkPolicy, getErrorCode, replaceWithConflictRetry } from '../utils'+import {+ applyNetworkPolicy,+ getErrorCode,+ observeCreate,+ observeExistenceRead,+ replaceWithConflictRetry,+} from '../utils'import { GFS_TEMPLATE_HASH_ANNOTATION } from './gfsFactory'const GROUP = 'clerum.io'@@ -37,7 +43,9 @@ export class K8sGfsApi implements GfsK8sApi {async applyPvc(pvc: k8s.V1PersistentVolumeClaim, namespace: string): Promise<void> {try {- await this.coreApi.createNamespacedPersistentVolumeClaim({ namespace, body: pvc })+ await observeCreate('PersistentVolumeClaim', () =>+ this.coreApi.createNamespacedPersistentVolumeClaim({ namespace, body: pvc })+ )} catch (err) {// A PVC spec is immutable once bound; an existing one is left as-is.if (getErrorCode(err) !== 409) throw err@@ -48,7 +56,9 @@ export class K8sGfsApi implements GfsK8sApi {const name = dep.metadata?.name ?? ''const desired = dep.metadata?.annotations?.[GFS_TEMPLATE_HASH_ANNOTATION]try {- const existing = await this.appsApi.readNamespacedDeployment({ name, namespace })+ const existing = await observeExistenceRead('Deployment', () =>+ this.appsApi.readNamespacedDeployment({ name, namespace })+ )const current = existing.metadata?.annotations?.[GFS_TEMPLATE_HASH_ANNOTATION]return !desired || current !== desired} catch (err) {@@ -88,7 +98,9 @@ export class K8sGfsApi implements GfsK8sApi {async applyDeployment(dep: k8s.V1Deployment, namespace: string): Promise<void> {const name = dep.metadata?.name ?? ''try {- await this.appsApi.createNamespacedDeployment({ namespace, body: dep })+ await observeCreate('Deployment', () =>+ this.appsApi.createNamespacedDeployment({ namespace, body: dep })+ )return} catch (err) {if (getErrorCode(err) !== 409) throw err@@ -97,7 +109,10 @@ export class K8sGfsApi implements GfsK8sApi {description: `deployment "${name}" in ${namespace}`,logPrefix: LOG,body: dep,- read: () => this.appsApi.readNamespacedDeployment({ name, namespace }),+ read: () =>+ observeExistenceRead('Deployment', () =>+ this.appsApi.readNamespacedDeployment({ name, namespace })+ ),replace: body => this.appsApi.replaceNamespacedDeployment({ name, namespace, body }),})}@@ -105,7 +120,9 @@ export class K8sGfsApi implements GfsK8sApi {async applyPodDisruptionBudget(pdb: k8s.V1PodDisruptionBudget, namespace: string): Promise<void> {const name = pdb.metadata?.name ?? ''try {- await this.policyApi.createNamespacedPodDisruptionBudget({ namespace, body: pdb })+ await observeCreate('PodDisruptionBudget', () =>+ this.policyApi.createNamespacedPodDisruptionBudget({ namespace, body: pdb })+ )return} catch (err) {if (getErrorCode(err) !== 409) throw err@@ -114,7 +131,10 @@ export class K8sGfsApi implements GfsK8sApi {description: `pod disruption budget "${name}" in ${namespace}`,logPrefix: LOG,body: pdb,- read: () => this.policyApi.readNamespacedPodDisruptionBudget({ name, namespace }),+ read: () =>+ observeExistenceRead('PodDisruptionBudget', () =>+ this.policyApi.readNamespacedPodDisruptionBudget({ name, namespace })+ ),replace: body =>this.policyApi.replaceNamespacedPodDisruptionBudget({ name, namespace, body }),})@@ -122,7 +142,9 @@ export class K8sGfsApi implements GfsK8sApi {async applyService(svc: k8s.V1Service, namespace: string): Promise<void> {try {- await this.coreApi.createNamespacedService({ namespace, body: svc })+ await observeCreate('Service', () =>+ this.coreApi.createNamespacedService({ namespace, body: svc })+ )} catch (err) {// clusterIP is immutable; the gfsc Service spec is stable, so an existing// Service is left in place rather than risking an invalid replace.diff --git a/host-context-controller/src/llmHookReconciler.ts b/host-context-controller/src/llmHookReconciler.tsindex d6c4848df..e70e28e07 100644--- a/host-context-controller/src/llmHookReconciler.ts+++ b/host-context-controller/src/llmHookReconciler.ts@@ -41,6 +41,8 @@ import {deploymentMatchesDesired,getErrorCode,networkPolicyMatchesDesired,+ observeCreate,+ observeExistenceRead,preserveDeploymentAnnotations,preserveObjectAnnotations,preserveServiceAssignedFields,@@ -755,10 +757,12 @@ export class LlmHookReconciler {const deployment = this.buildDeployment(podKey, members, credentialsRevision)const name = deployment.metadata!.name!try {- await this.appsApi.createNamespacedDeployment({- namespace: config.llmHooksNamespace,- body: deployment,- })+ await observeCreate('Deployment', () =>+ this.appsApi.createNamespacedDeployment({+ namespace: config.llmHooksNamespace,+ body: deployment,+ })+ )console.log(`${LOG} Created Deployment "${name}"`)return} catch (error) {@@ -771,7 +775,9 @@ export class LlmHookReconciler {mergeExisting: preserveDeploymentAnnotations,isUpToDate: deploymentMatchesDesired,read: () =>- this.appsApi.readNamespacedDeployment({ name, namespace: config.llmHooksNamespace }),+ observeExistenceRead('Deployment', () =>+ this.appsApi.readNamespacedDeployment({ name, namespace: config.llmHooksNamespace })+ ),replace: body =>this.appsApi.replaceNamespacedDeployment({name,@@ -785,10 +791,12 @@ export class LlmHookReconciler {const service = this.buildService(podKey, port)const name = service.metadata!.name!try {- await this.coreApi.createNamespacedService({- namespace: config.llmHooksNamespace,- body: service,- })+ await observeCreate('Service', () =>+ this.coreApi.createNamespacedService({+ namespace: config.llmHooksNamespace,+ body: service,+ })+ )console.log(`${LOG} Created Service "${name}"`)return} catch (error) {@@ -800,7 +808,10 @@ export class LlmHookReconciler {body: service,mergeExisting: preserveServiceAssignedFields,isUpToDate: serviceMatchesDesired,- read: () => this.coreApi.readNamespacedService({ name, namespace: config.llmHooksNamespace }),+ read: () =>+ observeExistenceRead('Service', () =>+ this.coreApi.readNamespacedService({ name, namespace: config.llmHooksNamespace })+ ),replace: body =>this.coreApi.replaceNamespacedService({ name, namespace: config.llmHooksNamespace, body }),})@@ -819,7 +830,9 @@ export class LlmHookReconciler {const name = policy.metadata!.name!const namespace = policy.metadata!.namespace ?? config.llmHooksNamespacetry {- await this.networkingApi.createNamespacedNetworkPolicy({ namespace, body: policy })+ await observeCreate('NetworkPolicy', () =>+ this.networkingApi.createNamespacedNetworkPolicy({ namespace, body: policy })+ )console.log(`${LOG} Created NetworkPolicy "${name}" (${namespace})`)return} catch (error) {@@ -831,7 +844,10 @@ export class LlmHookReconciler {body: policy,mergeExisting: preserveObjectAnnotations,isUpToDate: networkPolicyMatchesDesired,- read: () => this.networkingApi.readNamespacedNetworkPolicy({ name, namespace }),+ read: () =>+ observeExistenceRead('NetworkPolicy', () =>+ this.networkingApi.readNamespacedNetworkPolicy({ name, namespace })+ ),replace: body => this.networkingApi.replaceNamespacedNetworkPolicy({ name, namespace, body }),})}diff --git a/host-context-controller/src/metrics.ts b/host-context-controller/src/metrics.tsindex c7af445f3..151c8f226 100644--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@ -298,6 +298,45 @@ export const hostFleetLifecycleCatchTotal = counter({labelNames: ['decision'] as const,})+// Events overlap: every conflict is also an issued request. Never sum outcomes+// for request totals. The bounded kind inventory includes the read-first Secret.+export const CREATE_KINDS = [+ 'NetworkPolicy',+ 'Service',+ 'Deployment',+ 'ConfigMap',+ 'PersistentVolumeClaim',+ 'ServiceAccount',+ 'Role',+ 'RoleBinding',+ 'PodDisruptionBudget',+ 'Secret',+] as const+export type CreateKind = (typeof CREATE_KINDS)[number]+export const createsTotal = counter({+ name: 'clerum_hcc_creates_total',+ help: 'Kubernetes create events: issued attempts, conflict responses (a subset of issued), and creates skipped after reading an existing object, by kind.',+ labelNames: ['kind', 'outcome'] as const,+})+for (const kind of CREATE_KINDS) {+ for (const outcome of ['issued', 'conflict', 'skipped']) {+ createsTotal.inc({ kind, outcome }, 0)+ }+}++// Actual GETs in the documented create/converge paths, including retry reads.+// LIST results and reused caller snapshots do not represent new requests.+export const existenceReadsTotal = counter({+ name: 'clerum_hcc_existence_reads_total',+ help: 'Kubernetes existence GET outcomes in instrumented create/converge paths: found, absent (404), or error, by kind.',+ labelNames: ['kind', 'outcome'] as const,+})+for (const kind of CREATE_KINDS) {+ for (const outcome of ['found', 'absent', 'error']) {+ existenceReadsTotal.inc({ kind, outcome }, 0)+ }+}+// #493: successful replace() only, inside replaceWithConflictRetry. Kind is// next.kind ?? 'unknown'. Direct Role PUTs stay invisible until G5.export const writesTotal = counter({diff --git a/host-context-controller/src/networkPolicyReconciler.egressClassification.test.ts b/host-context-controller/src/networkPolicyReconciler.egressClassification.test.tsindex aacb2e14f..577863147 100644--- a/host-context-controller/src/networkPolicyReconciler.egressClassification.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.egressClassification.test.ts@@ -46,6 +46,8 @@ vi.mock('node:dns/promises', () => ({}))vi.mock('./metrics', () => ({+ createsTotal: { inc: vi.fn() },+ existenceReadsTotal: { inc: vi.fn() },networkPolicySafetyPassDurationSeconds: { observe: vi.fn() },networkPolicySafetyPassPoliciesTotal: { inc: vi.fn() },writesTotal: { inc: vi.fn() },diff --git a/host-context-controller/src/networkPolicyReconciler.egressFailStatic.test.ts b/host-context-controller/src/networkPolicyReconciler.egressFailStatic.test.tsindex 79457d9a1..77a1aad6a 100644--- a/host-context-controller/src/networkPolicyReconciler.egressFailStatic.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.egressFailStatic.test.ts@@ -46,6 +46,8 @@ vi.mock('node:dns/promises', () => ({}))vi.mock('./metrics', () => ({+ createsTotal: { inc: vi.fn() },+ existenceReadsTotal: { inc: vi.fn() },networkPolicySafetyPassDurationSeconds: { observe: vi.fn() },networkPolicySafetyPassPoliciesTotal: { inc: vi.fn() },writesTotal: { inc: vi.fn() },diff --git a/host-context-controller/src/networkPolicyReconciler.egressObservation.test.ts b/host-context-controller/src/networkPolicyReconciler.egressObservation.test.tsindex 4d833a8e3..dc1305840 100644--- a/host-context-controller/src/networkPolicyReconciler.egressObservation.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.egressObservation.test.ts@@ -19,6 +19,8 @@ vi.mock('./config', () => ({}))vi.mock('node:dns/promises', () => ({ resolve4: vi.fn() }))vi.mock('./metrics', () => ({+ createsTotal: { inc: vi.fn() },+ existenceReadsTotal: { inc: vi.fn() },writesTotal: { inc: vi.fn() },writeSkipsTotal: { inc: vi.fn() },externalEgressRetriesAtCap: { set: vi.fn() },diff --git a/host-context-controller/src/networkPolicyReconciler.orphanSweep.test.ts b/host-context-controller/src/networkPolicyReconciler.orphanSweep.test.tsindex ecdccb240..fd1c2ba15 100644--- a/host-context-controller/src/networkPolicyReconciler.orphanSweep.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.orphanSweep.test.ts@@ -32,6 +32,8 @@ vi.mock('node:dns/promises', () => ({}))vi.mock('./metrics', () => ({+ createsTotal: { inc: vi.fn() },+ existenceReadsTotal: { inc: vi.fn() },networkPolicySafetyPassDurationSeconds: { observe: vi.fn() },networkPolicySafetyPassPoliciesTotal: { inc: vi.fn() },netPolOrphansDeletedTotal: { inc: vi.fn() },diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.tsindex 94c849a20..50c58d777 100644--- a/host-context-controller/src/networkPolicyReconciler.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.test.ts@@ -76,6 +76,8 @@ vi.mock('node:dns/promises', () => ({}))vi.mock('./metrics', () => ({+ createsTotal: { inc: vi.fn() },+ existenceReadsTotal: { inc: vi.fn() },networkPolicySafetyPassDurationSeconds: { observe: vi.fn() },networkPolicySafetyPassPoliciesTotal: { inc: vi.fn() },netPolOrphansDeletedTotal: { inc: vi.fn() },diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.tsindex 6788c3710..d11a272be 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -58,6 +58,8 @@ import {canonicalizeValue,getErrorCode,networkPolicyMatchesDesired,+ observeCreate,+ observeExistenceRead,replaceWithConflictRetry,} from './utils'@@ -2105,10 +2107,12 @@ export class NetworkPolicyReconciler {): Promise<FreshExternalEgressPolicy> {let policy: k8s.V1NetworkPolicytry {- policy = await this.networkingApi.readNamespacedNetworkPolicy({- name,- namespace: server.namespace,- })+ policy = await observeExistenceRead('NetworkPolicy', () =>+ this.networkingApi.readNamespacedNetworkPolicy({+ name,+ namespace: server.namespace,+ })+ )} catch (error: unknown) {if (getErrorCode(error) === 404) return { policy: null, repairRequired: false }throw error@@ -3504,10 +3508,12 @@ export class NetworkPolicyReconciler {if (!isCurrent()) return falselet created: k8s.V1NetworkPolicytry {- created = await this.networkingApi.createNamespacedNetworkPolicy({- namespace,- body: desired,- })+ created = await observeCreate('NetworkPolicy', () =>+ this.networkingApi.createNamespacedNetworkPolicy({+ namespace,+ body: desired,+ })+ )} catch (error: unknown) {if (getErrorCode(error) !== 409) throw error// This is the only creation route that does not go through@@ -3534,7 +3540,10 @@ export class NetworkPolicyReconciler {description: `policy "${name}" in ${namespace}`,logPrefix: '[NetPol]',body: desired,- read: () => this.networkingApi.readNamespacedNetworkPolicy({ name, namespace }),+ read: () =>+ observeExistenceRead('NetworkPolicy', () =>+ this.networkingApi.readNamespacedNetworkPolicy({ name, namespace })+ ),replace: body =>this.networkingApi.replaceNamespacedNetworkPolicy({ name, namespace, body }),mutationAllowed: isCurrent,diff --git a/host-context-controller/src/reconciler.ts b/host-context-controller/src/reconciler.tsindex 3756104b3..ea722336c 100644--- a/host-context-controller/src/reconciler.ts+++ b/host-context-controller/src/reconciler.ts@@ -32,6 +32,8 @@ import {configMapMatchesDesired,deploymentMatchesDesired,getErrorCode,+ observeCreate,+ observeExistenceRead,preserveDeploymentAnnotations,preserveObjectAnnotations,preserveServiceAssignedFields,@@ -951,10 +953,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvconst name = `${server.name}-nginx-conf`const namespace = server.namespacetry {- await this.coreApi.createNamespacedConfigMap({- namespace,- body: cm,- })+ await observeCreate('ConfigMap', () =>+ this.coreApi.createNamespacedConfigMap({+ namespace,+ body: cm,+ })+ )console.log(`[Reconciler] Created nginx ConfigMap "${name}"`)} catch (error: unknown) {if (getErrorCode(error) !== 409) {@@ -967,7 +971,10 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvmergeExisting: preserveObjectAnnotations,isUpToDate: configMapMatchesDesired,mutationAllowed: isCurrent,- read: () => this.coreApi.readNamespacedConfigMap({ name, namespace }),+ read: () =>+ observeExistenceRead('ConfigMap', () =>+ this.coreApi.readNamespacedConfigMap({ name, namespace })+ ),replace: body => this.coreApi.replaceNamespacedConfigMap({ name, namespace, body }),})}@@ -1478,10 +1485,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvif (!isCurrent()) returntry {- await this.appsApi.createNamespacedDeployment({- namespace: server.namespace,- body: deployment,- })+ await observeCreate('Deployment', () =>+ this.appsApi.createNamespacedDeployment({+ namespace: server.namespace,+ body: deployment,+ })+ )console.log(`[Reconciler] Created Deployment "${server.name}"`)return} catch (error: unknown) {@@ -1502,10 +1511,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvmergeExisting: preserveDeploymentAnnotations,isUpToDate: deploymentMatchesDesired,read: () =>- this.appsApi.readNamespacedDeployment({- name: server.name,- namespace: server.namespace,- }),+ observeExistenceRead('Deployment', () =>+ this.appsApi.readNamespacedDeployment({+ name: server.name,+ namespace: server.namespace,+ })+ ),replace: body =>this.appsApi.replaceNamespacedDeployment({name: server.name,@@ -1528,10 +1539,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvif (!isCurrent()) returntry {- await this.coreApi.createNamespacedService({- namespace: server.namespace,- body: service,- })+ await observeCreate('Service', () =>+ this.coreApi.createNamespacedService({+ namespace: server.namespace,+ body: service,+ })+ )} catch (error: unknown) {if (getErrorCode(error) === 409) {await replaceWithConflictRetry({@@ -1541,10 +1554,12 @@ ${authHeaderLines ? '\n # ── Credential auth headers (envsubst-resolvmergeExisting: preserveServiceAssignedFields,isUpToDate: serviceMatchesDesired,read: () =>- this.coreApi.readNamespacedService({- name: server.name,- namespace: server.namespace,- }),+ observeExistenceRead('Service', () =>+ this.coreApi.readNamespacedService({+ name: server.name,+ namespace: server.namespace,+ })+ ),replace: body =>this.coreApi.replaceNamespacedService({name: server.name,diff --git a/host-context-controller/src/sharedFileSystemReconciler.ts b/host-context-controller/src/sharedFileSystemReconciler.tsindex 32054805f..cea3655bb 100644--- a/host-context-controller/src/sharedFileSystemReconciler.ts+++ b/host-context-controller/src/sharedFileSystemReconciler.ts@@ -48,6 +48,8 @@ import {applyNetworkPolicy,deploymentMatchesDesired,getErrorCode,+ observeCreate,+ observeExistenceRead,preserveDeploymentAnnotations,replaceWithConflictRetry,} from './utils'@@ -271,10 +273,12 @@ export class SharedFileSystemReconciler {const pvc = buildPvc(sfs, this.factoryConfig)const name = pvcName(sfs)try {- await this.coreApi.createNamespacedPersistentVolumeClaim({- namespace: this.factoryConfig.hostNamespace,- body: pvc,- })+ await observeCreate('PersistentVolumeClaim', () =>+ this.coreApi.createNamespacedPersistentVolumeClaim({+ namespace: this.factoryConfig.hostNamespace,+ body: pvc,+ })+ )console.log(`${LOG} Created PVC "${name}"`)} catch (err) {if (getErrorCode(err) !== 409) {@@ -343,10 +347,12 @@ export class SharedFileSystemReconciler {const dep = buildDeployment(sfs, this.factoryConfig)const name = wfcDeploymentName(sfs)try {- await this.appsApi.createNamespacedDeployment({- namespace: this.factoryConfig.hostNamespace,- body: dep,- })+ await observeCreate('Deployment', () =>+ this.appsApi.createNamespacedDeployment({+ namespace: this.factoryConfig.hostNamespace,+ body: dep,+ })+ )console.log(`${LOG} Created Deployment "${name}"`)} catch (err) {if (getErrorCode(err) !== 409) {@@ -357,10 +363,12 @@ export class SharedFileSystemReconciler {logPrefix: LOG,body: dep,read: () =>- this.appsApi.readNamespacedDeployment({- namespace: this.factoryConfig.hostNamespace,- name,- }),+ observeExistenceRead('Deployment', () =>+ this.appsApi.readNamespacedDeployment({+ namespace: this.factoryConfig.hostNamespace,+ name,+ })+ ),// The public auth-key reconciler may use `kubectl rollout restart` on// this HCC-owned Deployment. Preserve the pod-template restart marker// when the periodic SFS reconcile replaces the raw desired manifest;@@ -385,10 +393,12 @@ export class SharedFileSystemReconciler {const svc = buildService(sfs, this.factoryConfig)const name = wfcServiceName(sfs)try {- await this.coreApi.createNamespacedService({- namespace: this.factoryConfig.hostNamespace,- body: svc,- })+ await observeCreate('Service', () =>+ this.coreApi.createNamespacedService({+ namespace: this.factoryConfig.hostNamespace,+ body: svc,+ })+ )console.log(`${LOG} Created Service "${name}"`)} catch (err) {if (getErrorCode(err) !== 409) {diff --git a/host-context-controller/src/utils.ts b/host-context-controller/src/utils.tsindex e1bb34ef6..fbf8c7dd3 100644--- a/host-context-controller/src/utils.ts+++ b/host-context-controller/src/utils.ts@@ -1,6 +1,12 @@import * as k8s from '@kubernetes/client-node'import { hccLogger } from './logger'-import { writeSkipsTotal, writesTotal } from './metrics'+import {+ type CreateKind,+ createsTotal,+ existenceReadsTotal,+ writeSkipsTotal,+ writesTotal,+} from './metrics'/** Extract HTTP status code from a K8s client error (handles both error formats). */export function getErrorCode(error: unknown): number | undefined {@@ -8,6 +14,35 @@ export function getErrorCode(error: unknown): number | undefined {return e.code ?? e.response?.statusCode}+/** Observe only the create request, preserving its response and error identity. */+export async function observeCreate<T>(kind: CreateKind, create: () => Promise<T>): Promise<T> {+ createsTotal.inc({ kind, outcome: 'issued' })+ try {+ return await create()+ } catch (error) {+ if (error != null && getErrorCode(error) === 409) {+ createsTotal.inc({ kind, outcome: 'conflict' })+ }+ throw error+ }+}++/** Observe one existence GET without changing its value or error handling. */+export async function observeExistenceRead<T>(+ kind: CreateKind,+ read: () => Promise<T>+): Promise<T> {+ try {+ const result = await read()+ existenceReadsTotal.inc({ kind, outcome: 'found' })+ return result+ } catch (error) {+ const outcome = error != null && getErrorCode(error) === 404 ? 'absent' : 'error'+ existenceReadsTotal.inc({ kind, outcome })+ throw error+ }+}+/*** Re-read + replace with optimistic-lock retry. K8s rejects a replace whose* `metadata.resourceVersion` does not match the current value; the only@@ -460,7 +495,9 @@ export async function applyNetworkPolicy(): Promise<void> {if (mutationAllowed && !mutationAllowed()) returntry {- await api.createNamespacedNetworkPolicy({ namespace, body: policy })+ await observeCreate('NetworkPolicy', () =>+ api.createNamespacedNetworkPolicy({ namespace, body: policy })+ )hccLogger.info('NetworkPolicy created', { scope: logPrefix, policy: name, namespace })return} catch (error: unknown) {@@ -472,7 +509,10 @@ export async function applyNetworkPolicy(description: `policy "${name}" in ${namespace}`,logPrefix,body: policy,- read: () => api.readNamespacedNetworkPolicy({ name, namespace }),+ read: () =>+ observeExistenceRead('NetworkPolicy', () =>+ api.readNamespacedNetworkPolicy({ name, namespace })+ ),replace: body => api.replaceNamespacedNetworkPolicy({ name, namespace, body }),mutationAllowed,validateExisting,