Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(hcc): give class D a defaults-only tick independent of the fleet pass
Alfredo Lopezccaf6657f203
diff --git a/host-context-controller/README.md b/host-context-controller/README.mdindex 2e876c2cd..85ee15fa6 100644--- a/host-context-controller/README.md+++ b/host-context-controller/README.md@@ -439,16 +439,17 @@ 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. 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. |+| 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, when that flag is set, L0/L1 defaults (class D). Class D also has a separate cheap path via `CONTEXT_MAPPER_NETPOL_DEFAULTS_RESYNC_SEC` (#488). 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_DEFAULTS_RESYNC_SEC` | `0` | Periodic L0/L1 defaults-only tick (seconds). Calls `ensureDefaultPolicies()` only — never `fullReconcile` / `runInitialNetworkPolicyConvergence`. Write sets are disjoint from the typed sweep (`policy-type ∈ {context-allow, rpc-proxy-egress, external-egress}`), so a concurrent full pass is safe and this timer does **not** share `initialConvergenceRuns` or increment `{reason="pass-in-flight"}`. Overlapping defaults-only ticks serialize (`clerum_hcc_netpol_resync_ticks_skipped_total{reason="defaults-only-in-flight"}`). `0` disables the interval (merge default) and does not warn. Not shipped in `deploy/base` or public overlays. A non-canonical value fails loud at load. Enable is a separate ops decision (issue #488). |+| `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 b655ed648..816b17d89 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.263",+ "version": "0.1.264","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.263",+ "version": "0.1.264","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 cf3a69df9..287c519e3 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.263",+ "version": "0.1.264","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 4d95ddbdd..06d5aa0a4 100644--- a/host-context-controller/src/config.netPolResync.test.ts+++ b/host-context-controller/src/config.netPolResync.test.ts@@ -4,6 +4,7 @@ const originalEnv = process.envconst KNOBS = ['CONTEXT_MAPPER_NETPOL_RESYNC_SEC',+ 'CONTEXT_MAPPER_NETPOL_DEFAULTS_RESYNC_SEC','CONTEXT_MAPPER_NETPOL_ORPHAN_DELETE_CAP','CONTEXT_MAPPER_NETPOL_ORPHAN_DELETE_CAP_PERCENT',] as const@@ -25,6 +26,7 @@ describe('NetworkPolicy resync and orphan-sweep config (#478)', () => {it('defaults resync to 0 and caps to 10/20 when unset', async () => {const { config } = await loadConfig({})expect(config.netPolResyncIntervalSec).toBe(0)+ expect(config.netPolDefaultsResyncIntervalSec).toBe(0)expect(config.netPolOrphanDeleteCap).toBe(10)expect(config.netPolOrphanDeleteCapPercent).toBe(20)})@@ -89,3 +91,26 @@ describe('NetworkPolicy resync and orphan-sweep config (#478)', () => {})})++describe('NetworkPolicy defaults-only resync config (#488)', () => {+ it('keeps the defaults-only interval disabled when unset or 0', async () => {+ const unset = await loadConfig({})+ expect(unset.config.netPolDefaultsResyncIntervalSec).toBe(0)+ const zero = await loadConfig({ CONTEXT_MAPPER_NETPOL_DEFAULTS_RESYNC_SEC: '0' })+ expect(zero.config.netPolDefaultsResyncIntervalSec).toBe(0)+ })++ it('accepts an explicit defaults-only interval', async () => {+ const { config } = await loadConfig({ CONTEXT_MAPPER_NETPOL_DEFAULTS_RESYNC_SEC: '120' })+ expect(config.netPolDefaultsResyncIntervalSec).toBe(120)+ })++ it.each(['25m', '1e3', '-5', '0.5', '2e1', 'abc'] as const)(+ 'fails loud when the defaults-only interval is non-canonical (%s)',+ async raw => {+ await expect(loadConfig({ CONTEXT_MAPPER_NETPOL_DEFAULTS_RESYNC_SEC: raw })).rejects.toThrow(+ /CONTEXT_MAPPER_NETPOL_DEFAULTS_RESYNC_SEC/+ )+ }+ )+})diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.tsindex 593728418..9006c5088 100644--- a/host-context-controller/src/config.ts+++ b/host-context-controller/src/config.ts@@ -178,6 +178,12 @@ export interface Config {// Set via CONTEXT_MAPPER_NETPOL_RESYNC_SEC.netPolResyncIntervalSec: number+ // Periodic L0/L1 defaults-only interval (seconds). Re-applies+ // ensureDefaultPolicies without entering a fleet fullReconcile. Default 0+ // disables the interval. Non-canonical values fail loud at load. Set via+ // CONTEXT_MAPPER_NETPOL_DEFAULTS_RESYNC_SEC.+ netPolDefaultsResyncIntervalSec: number+// Absolute orphan-delete cap for a NetworkPolicy fullReconcile sweep.// Candidates strictly above this count refuse deletes and increment the// cap metric; the pass still certifies. 0 refuses every orphan delete.@@ -785,6 +791,13 @@ export const config: Config = {// converges once; the interval is opt-in so a bad cache cannot periodically// sweep. Unset or 0 → no interval.netPolResyncIntervalSec: requireCanonicalNonNegativeEnvInt('CONTEXT_MAPPER_NETPOL_RESYNC_SEC', 0),+ // Periodic L0/L1 defaults-only tick (#488). Default 0 (disabled): start()+ // still applies defaults once as a bootstrap barrier. The interval is+ // opt-in and is not shipped in deploy/base. Unset or 0 → no interval.+ netPolDefaultsResyncIntervalSec: requireCanonicalNonNegativeEnvInt(+ 'CONTEXT_MAPPER_NETPOL_DEFAULTS_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 1cbdf3a2e..6c26b416d 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -271,6 +271,7 @@ const mockConfig = vi.hoisted(() => ({hostK8sRequestTimeoutMs: 30_000,hostResyncIntervalSec: 0,netPolResyncIntervalSec: 0,+ netPolDefaultsResyncIntervalSec: 0,externalEgressResyncIntervalSec: 0,externalEgressRefreshFloorSec: 5,controlApiBaseUrl: 'http://control-api.test:8090',@@ -631,6 +632,7 @@ describe('McpServerWatcher startup', () => {mocks.hasCertifiedSafetyInventory.mockReset().mockReturnValue(true)mockConfig.externalEgressResyncIntervalSec = 0 // keep periodic resync off by defaultmockConfig.netPolResyncIntervalSec = 0+ mockConfig.netPolDefaultsResyncIntervalSec = 0mocks.ensureDefaultPolicies.mockReset().mockResolvedValue(undefined)mocks.netPolFullReconcile.mockReset().mockImplementation(async (...args: unknown[]) => {const options = args[2] as { onAuthoritativeRevocationComplete?: () => void } | undefined@@ -11322,6 +11324,7 @@ describe('McpServerWatcher NetworkPolicy periodic resync (#478)', () => {afterEach(() => {vi.useRealTimers()mockConfig.netPolResyncIntervalSec = 0+ mockConfig.netPolDefaultsResyncIntervalSec = 0mocks.netPolFullReconcile.mockReset().mockImplementation(async (...args: unknown[]) => {const options = args[2] as { onAuthoritativeRevocationComplete?: () => void } | undefinedoptions?.onAuthoritativeRevocationComplete?.()@@ -11467,3 +11470,177 @@ describe('McpServerWatcher NetworkPolicy periodic resync (#478)', () => {await watcher.stop()})})++describe('McpServerWatcher NetworkPolicy defaults-only tick (#488)', () => {+ async function startWatcherForDefaultsOnlyTick(): Promise<McpServerWatcher> {+ mocks.netPolFullReconcile.mockClear()+ mocks.ensureDefaultPolicies.mockClear()+ mocks.watch.mockReset().mockResolvedValue({ abort: vi.fn() })+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'communicationchannels') {+ return { metadata: { resourceVersion: 'netpol-defaults-cc-rv' }, items: [] }+ }+ return { items: [] }+ })+ const watcher = new McpServerWatcher()+ stubAuthoritativeInventoryWatch(watcher, 'McpServer')+ stubAuthoritativeInventoryWatch(watcher, 'Context')+ vi.spyOn(watcher as any, 'startSharedFileSystemWatch').mockResolvedValue(undefined)+ vi.spyOn(watcher as any, 'startGlobalFileSystemWatch').mockResolvedValue(undefined)+ vi.spyOn(watcher as any, 'startCommunicationChannelWatch').mockResolvedValue(undefined)+ vi.spyOn(watcher as any, 'startLlmHookWatch').mockResolvedValue(undefined)+ await watcher.start()+ await vi.advanceTimersByTimeAsync(0)+ return watcher+ }++ afterEach(() => {+ vi.useRealTimers()+ mockConfig.netPolResyncIntervalSec = 0+ mockConfig.netPolDefaultsResyncIntervalSec = 0+ mocks.ensureDefaultPolicies.mockReset().mockResolvedValue(undefined)+ mocks.netPolFullReconcile.mockReset().mockImplementation(async (...args: unknown[]) => {+ const options = args[2] as { onAuthoritativeRevocationComplete?: () => void } | undefined+ options?.onAuthoritativeRevocationComplete?.()+ })+ })++ it('default 0: registers no defaults-only timer and does not re-apply L0/L1', async () => {+ vi.useFakeTimers()+ mockConfig.netPolDefaultsResyncIntervalSec = 0+ const watcher = await startWatcherForDefaultsOnlyTick()+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(1)+ expect((watcher as any).netPolDefaultsResyncTimer).toBeNull()++ await vi.advanceTimersByTimeAsync(120_000)+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(1)+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(1)+ await watcher.stop()+ })++ it('interval > 0: tick calls ensureDefaultPolicies and never starts a fleet pass', async () => {+ vi.useFakeTimers()+ mockConfig.netPolDefaultsResyncIntervalSec = 60+ const watcher = await startWatcherForDefaultsOnlyTick()+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(1)+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(1)+ expect((watcher as any).netPolDefaultsResyncTimer).not.toBeNull()++ await vi.advanceTimersByTimeAsync(60_000)+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(2)+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(1)+ await watcher.stop()+ })++ it('full pass in flight: defaults-only still runs and does not increment pass-in-flight', async () => {+ vi.useFakeTimers()+ mockConfig.netPolDefaultsResyncIntervalSec = 60+ const activePass = deferred()+ mocks.netPolFullReconcile+ .mockReset()+ .mockImplementationOnce(async (...args: unknown[]) => {+ const options = args[2] as { onAuthoritativeRevocationComplete?: () => void } | undefined+ options?.onAuthoritativeRevocationComplete?.()+ await activePass.promise+ })+ .mockImplementation(async (...args: unknown[]) => {+ const options = args[2] as { onAuthoritativeRevocationComplete?: () => void } | undefined+ options?.onAuthoritativeRevocationComplete?.()+ })+ const watcher = await startWatcherForDefaultsOnlyTick()+ await vi.waitFor(() => expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(1))+ expect((watcher as any).initialConvergenceRuns.has('NetworkPolicy')).toBe(true)+ const defaultsAfterStart = mocks.ensureDefaultPolicies.mock.calls.length+ const passSkippedBefore = await readLabeledConvergenceMetric(+ 'clerum_hcc_netpol_resync_ticks_skipped_total',+ { reason: 'pass-in-flight' }+ )++ await vi.advanceTimersByTimeAsync(60_000)+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(defaultsAfterStart + 1)+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(1)+ expect(+ await readLabeledConvergenceMetric('clerum_hcc_netpol_resync_ticks_skipped_total', {+ reason: 'pass-in-flight',+ })+ ).toBe(passSkippedBefore)++ activePass.resolve()+ await flushMicrotasks()+ await watcher.stop()+ })++ it('overlapping defaults-only ticks serialize with defaults-only-in-flight', async () => {+ vi.useFakeTimers()+ mockConfig.netPolDefaultsResyncIntervalSec = 60+ const watcher = await startWatcherForDefaultsOnlyTick()+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(1)+ const held = deferred()+ mocks.ensureDefaultPolicies.mockImplementation(() => held.promise)+ const skippedBefore = await readLabeledConvergenceMetric(+ 'clerum_hcc_netpol_resync_ticks_skipped_total',+ { reason: 'defaults-only-in-flight' }+ )+ const passSkippedBefore = await readLabeledConvergenceMetric(+ 'clerum_hcc_netpol_resync_ticks_skipped_total',+ { reason: 'pass-in-flight' }+ )++ await vi.advanceTimersByTimeAsync(60_000)+ await flushMicrotasks()+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(2)++ await vi.advanceTimersByTimeAsync(60_000)+ await flushMicrotasks()+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(2)+ expect(+ await readLabeledConvergenceMetric('clerum_hcc_netpol_resync_ticks_skipped_total', {+ reason: 'defaults-only-in-flight',+ })+ ).toBe(skippedBefore + 1)+ expect(+ await readLabeledConvergenceMetric('clerum_hcc_netpol_resync_ticks_skipped_total', {+ reason: 'pass-in-flight',+ })+ ).toBe(passSkippedBefore)++ held.resolve()+ await flushMicrotasks()+ await watcher.stop()+ })++ it('event-driven full pass after a defaults-only tick still leaves ensureDefaults false', async () => {+ vi.useFakeTimers()+ mockConfig.netPolDefaultsResyncIntervalSec = 60+ const watcher = await startWatcherForDefaultsOnlyTick()+ expect(mocks.netPolFullReconcile.mock.calls[0]?.[2]).toEqual(+ expect.objectContaining({ ensureDefaults: false })+ )++ await vi.advanceTimersByTimeAsync(60_000)+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(2)+ expect((watcher as any).netPolConvergenceEnsureDefaults).toBe(false)++ await (watcher as any).runInitialNetworkPolicyConvergence()+ expect(mocks.netPolFullReconcile).toHaveBeenCalledTimes(2)+ expect(mocks.netPolFullReconcile).toHaveBeenLastCalledWith(+ expect.any(Array),+ expect.any(Array),+ expect.objectContaining({ ensureDefaults: false })+ )+ await watcher.stop()+ })++ it('stop() clears the defaults-only interval so later ticks do not re-apply L0/L1', async () => {+ vi.useFakeTimers()+ mockConfig.netPolDefaultsResyncIntervalSec = 60+ const watcher = await startWatcherForDefaultsOnlyTick()+ const defaultsAfterStart = mocks.ensureDefaultPolicies.mock.calls.length+ expect((watcher as any).netPolDefaultsResyncTimer).not.toBeNull()++ await watcher.stop()+ expect((watcher as any).netPolDefaultsResyncTimer).toBeNull()+ await vi.advanceTimersByTimeAsync(60_000)+ expect(mocks.ensureDefaultPolicies).toHaveBeenCalledTimes(defaultsAfterStart)+ })+})diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex 8d2c2256d..5ec53e040 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -894,6 +894,13 @@ export class McpServerWatcher implements McpServerProvider {// single-flight pass. Disabled by default (interval <= 0); startup still// runs one convergence. Never call netPolReconciler.fullReconcile from here.private netPolResyncTimer: ReturnType<typeof setInterval> | null = null+ // Periodic L0/L1 defaults-only tick (#488). Disabled by default+ // (interval <= 0). Never shares the full-pass in-flight skip; write sets+ // are disjoint from the typed sweep.+ private netPolDefaultsResyncTimer: ReturnType<typeof setInterval> | null = null+ // Serializes overlapping defaults-only ticks. Distinct from+ // initialConvergenceRuns.get('NetworkPolicy').+ private netPolDefaultsOnlyRun: Promise<void> | null = null// Set by a timer tick so the next coordinated NetworkPolicy pass re-applies// L0/L1 defaults (class D). Startup and event-driven entry leave this false// — start() already ran ensureDefaultPolicies as a bootstrap barrier.@@ -2875,6 +2882,19 @@ export class McpServerWatcher implements McpServerProvider {)}+ // Class-D cheap path (#488). Interval > 0 is an ops enable, not a merge+ // default. This timer never consults initialConvergenceRuns and never+ // calls runInitialNetworkPolicyConvergence / fullReconcile.+ const netPolDefaultsResyncSec = config.netPolDefaultsResyncIntervalSec+ if (netPolDefaultsResyncSec > 0) {+ this.netPolDefaultsResyncTimer = setInterval(() => {+ void this.runNetworkPolicyDefaultsOnly()+ }, netPolDefaultsResyncSec * 1000)+ console.log(+ `[K8s] NetworkPolicy defaults-only resync enabled (every ${netPolDefaultsResyncSec}s)`+ )+ }+const externalEgressResyncSec = config.externalEgressResyncIntervalSec// #205 delegates external-egress periodic resync to the convergence// coordinator. Its runResyncCore drives reconcileExternalEgress, so the@@ -3056,6 +3076,42 @@ export class McpServerWatcher implements McpServerProvider {return this.runInitialConvergence('NetworkPolicy')}+ /**+ * Class-D defaults-only tick (#488).+ *+ * `ensureDefaultPolicies` writes only L0/L1: `ensureDefaultDeny`,+ * `ensureInfrastructurePolicies`, `ensureAllowContextMapperApi`, and the+ * two `deleteLegacyStaticPolicy` calls. The fleet sweep lists typed+ * `policy-type ∈ {context-allow, rpc-proxy-egress, external-egress}`.+ * Baseline never appears in that list, so a concurrent full NetPol pass+ * is safe. Do not re-apply HARD REQUIREMENT 2 here and do not share+ * `initialConvergenceRuns.has('NetworkPolicy')`.+ *+ * Overlapping defaults-only ticks serialize: a second tick increments+ * `netPolResyncTicksSkippedTotal{reason="defaults-only-in-flight"}` and+ * joins the in-flight run. Never increment `pass-in-flight` from here.+ */+ private runNetworkPolicyDefaultsOnly(): Promise<void> {+ if (this.netPolDefaultsOnlyRun) {+ netPolResyncTicksSkippedTotal.inc({ reason: 'defaults-only-in-flight' })+ return this.netPolDefaultsOnlyRun+ }+ const run = (async () => {+ try {+ await this.netPolReconciler.ensureDefaultPolicies()+ } catch (error) {+ console.error('[K8s] NetworkPolicy defaults-only tick failed:', error)+ }+ })()+ this.netPolDefaultsOnlyRun = run+ void run.finally(() => {+ if (this.netPolDefaultsOnlyRun === run) {+ this.netPolDefaultsOnlyRun = null+ }+ })+ return run+ }+private runInitialConvergence(lane: InitialConvergenceLane): Promise<void> {const active = this.initialConvergenceRuns.get(lane)if (active) {@@ -4587,6 +4643,10 @@ export class McpServerWatcher implements McpServerProvider {clearInterval(this.netPolResyncTimer)this.netPolResyncTimer = null}+ if (this.netPolDefaultsResyncTimer) {+ clearInterval(this.netPolDefaultsResyncTimer)+ this.netPolDefaultsResyncTimer = null+ }this.netPolConvergenceEnsureDefaults = falsefor (const timer of this.initialConvergenceRetryTimers.values()) {clearTimeout(timer)diff --git a/host-context-controller/src/metrics.ts b/host-context-controller/src/metrics.tsindex 5f2accf79..c6e0b26a1 100644--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@ -151,7 +151,7 @@ export const netPolOrphanSweepCappedTotal = counter({export const netPolResyncTicksSkippedTotal = counter({name: 'clerum_hcc_netpol_resync_ticks_skipped_total',- help: 'Periodic NetworkPolicy resync ticks skipped because a convergence pass was already in flight.',+ help: 'Periodic NetworkPolicy resync ticks skipped because a full pass (`pass-in-flight`) or a defaults-only tick (`defaults-only-in-flight`) was already in flight.',labelNames: ['reason'] as const,})