Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(egress): address zach88 review findings for #299

Alfredo Lopez17eb4d5b9c87
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 9a64a11d4..2c0eaeb04 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.167",
+ "version": "0.1.168",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.167",
+ "version": "0.1.168",
"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.json
index 17f38b785..5ed40074a 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.167",
+ "version": "0.1.168",
"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.externalEgressResync.test.ts b/host-context-controller/src/config.externalEgressResync.test.ts
index 5cff9906d..a0ed234ce 100644
--- a/host-context-controller/src/config.externalEgressResync.test.ts
+++ b/host-context-controller/src/config.externalEgressResync.test.ts
@@ -33,7 +33,7 @@ describe('external egress sliding-window config (issue #299)', () => {
expect(config.externalEgressMaxEntries).toBe(128)
})
- it('accepts a valid floor <= interval < overlap triple', async () => {
+ it('accepts a valid floor <= interval <= overlap/2 triple', async () => {
const { config } = await loadConfig({
HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC: '10',
HCC_EXTERNAL_EGRESS_RESYNC_SEC: '30',
@@ -44,7 +44,7 @@ describe('external egress sliding-window config (issue #299)', () => {
expect(config.externalEgressOverlapSec).toBe(120)
})
- it('fails loud when the refresh interval is NOT below the overlap', async () => {
+ it('fails loud when the refresh interval exceeds half the overlap', async () => {
await expect(
loadConfig({
HCC_EXTERNAL_EGRESS_RESYNC_SEC: '300',
@@ -118,12 +118,26 @@ describe('external egress sliding-window config (issue #299)', () => {
expect(config.externalEgressResyncIntervalSec).toBe(1800)
})
- it('fails loud when max entries exceed the 4096 cap (M-C annotation-size bound)', async () => {
- await expect(loadConfig({ HCC_EXTERNAL_EGRESS_MAX_ENTRIES: '4097' })).rejects.toThrow(/4096/)
+ // R1-M5: the ceiling is 1300 (aligned with WRC); the core's byte-aware
+ // eviction is the real annotation-size bound, not this count.
+ it('fails loud when max entries exceed the 1300 cap (R1-M5, aligned with WRC)', async () => {
+ await expect(loadConfig({ HCC_EXTERNAL_EGRESS_MAX_ENTRIES: '1301' })).rejects.toThrow(/1300/)
})
- it('accepts max entries exactly at the 4096 cap', async () => {
- const { config } = await loadConfig({ HCC_EXTERNAL_EGRESS_MAX_ENTRIES: '4096' })
- expect(config.externalEgressMaxEntries).toBe(4096)
+ it('accepts max entries exactly at the 1300 cap', async () => {
+ const { config } = await loadConfig({ HCC_EXTERNAL_EGRESS_MAX_ENTRIES: '1300' })
+ expect(config.externalEgressMaxEntries).toBe(1300)
+ })
+
+ // R1-L1: the four knobs use a LOUD parser that rejects non-canonical values,
+ // not parseInt (which silently coerces '60.5'->60 / '60abc'->60 and lets an
+ // in-range typo slip past the range invariant).
+ it('R1-L1: fails loud on a non-integer knob value instead of silently coercing', async () => {
+ await expect(loadConfig({ HCC_EXTERNAL_EGRESS_RESYNC_SEC: '60.5' })).rejects.toThrow(
+ /HCC_EXTERNAL_EGRESS_RESYNC_SEC/
+ )
+ await expect(loadConfig({ HCC_EXTERNAL_EGRESS_OVERLAP_SEC: '300abc' })).rejects.toThrow(
+ /HCC_EXTERNAL_EGRESS_OVERLAP_SEC/
+ )
})
})
diff --git a/host-context-controller/src/config.ts b/host-context-controller/src/config.ts
index 2aa403dd0..7b7632b75 100644
--- a/host-context-controller/src/config.ts
+++ b/host-context-controller/src/config.ts
@@ -245,6 +245,26 @@ function getEnvInt(key: string, defaultValue: number): number {
return isNaN(parsed) ? defaultValue : parsed
}
+/**
+ * Loud integer env parser for the external-egress knobs (audit R1-L1). Unlike
+ * getEnvInt (parseInt), this rejects non-canonical values instead of silently
+ * coercing them: '60.5'->60 or '60abc'->60 would pass getEnvInt AND the
+ * range invariant (which re-checks the already-truncated value), letting an
+ * in-range typo through quietly. Canonical unsigned base-10 only; empty -> default.
+ */
+function getExternalEgressEnvInt(key: string, defaultValue: number): number {
+ const raw = process.env[key]
+ if (raw === undefined || raw === '') return defaultValue
+ if (!/^\d+$/.test(raw)) {
+ throw new Error(`${key} must be an unsigned base-10 integer (seconds), got '${raw}'`)
+ }
+ const parsed = Number(raw)
+ if (!Number.isSafeInteger(parsed)) {
+ throw new Error(`${key} is out of the safe integer range, got '${raw}'`)
+ }
+ return parsed
+}
+
/**
* CONTEXT_MAPPER_HEARTBEAT_POLL_MS — cadence of HCC's control-api heartbeat
* poll. Fails config load loudly on a non-positive-integer value: a silent
@@ -385,19 +405,23 @@ validateRemovedStatelessCommunicationChannelPolicy(
/**
* Enforce the external-egress sliding-window invariant (issue #299):
* refreshFloor >= 1, overlap > 0, maxEntries >= 1, and when the periodic
- * resync is enabled (interval > 0): floor <= interval < overlap.
- * The interval MUST stay below the overlap so an accumulated /32 is refreshed
- * before it can expire; otherwise a gap reopens and the pod loses egress on the
- * next rotation. Fails loud at startup rather than degrading silently.
+ * resync is enabled (interval > 0): floor <= interval <= overlap/2.
+ * The interval MUST stay at or below HALF the overlap so an accumulated /32 is
+ * refreshed before it can expire (the renewal-write window is only overlap/2
+ * wide); otherwise a gap reopens and the pod loses egress on the next rotation.
+ * Fails loud at startup rather than degrading silently.
*/
// Upper bounds (audit M-C, port of commit 3f968956). The one-hour cadence
// ceiling keeps every timer far below Node's signed-32-bit setTimeout limit
// (2^31-1 ms ≈ 24.8 days) — an unbounded seconds value multiplied to ms would
// overflow and Node clamps it to 1ms, turning the self-rescheduling resync into
-// a back-to-back DNS hot loop. The 4096 entry ceiling bounds the serialized
-// state annotation and matches WRC's accumulator contract.
+// a back-to-back DNS hot loop. The entry ceiling is a coarse COUNT alarm cap
+// matching WRC (1300); the real bound on the annotation size is the core's
+// byte-aware eviction (MAX_ANNOTATION_BYTES in network-policy-core), which trims
+// long-FQDN sets well before this count is reached (R1-M5 — the previous 4096
+// claim of "matches WRC" was false; WRC is 1300 and 4096 never bounds bytes).
const MAX_EXTERNAL_EGRESS_CADENCE_SEC = 60 * 60
-const MAX_EXTERNAL_EGRESS_MAX_ENTRIES = 4096
+const MAX_EXTERNAL_EGRESS_MAX_ENTRIES = 1300
export function validateExternalEgressResyncInvariant(cfg: {
externalEgressResyncIntervalSec: number
@@ -689,10 +713,13 @@ export const config: Config = {
// it sits below the 300s overlap window: accumulated IPs are refreshed before
// they expire, closing the #299 rotation gap. 0 disables (reintroduces the
// stale-snapshot risk; only for operators who explicitly opt out).
- externalEgressResyncIntervalSec: getEnvInt('HCC_EXTERNAL_EGRESS_RESYNC_SEC', 60),
- externalEgressOverlapSec: getEnvInt('HCC_EXTERNAL_EGRESS_OVERLAP_SEC', 300),
- externalEgressRefreshFloorSec: getEnvInt('HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC', 5),
- externalEgressMaxEntries: getEnvInt('HCC_EXTERNAL_EGRESS_MAX_ENTRIES', 128),
+ externalEgressResyncIntervalSec: getExternalEgressEnvInt('HCC_EXTERNAL_EGRESS_RESYNC_SEC', 60),
+ externalEgressOverlapSec: getExternalEgressEnvInt('HCC_EXTERNAL_EGRESS_OVERLAP_SEC', 300),
+ externalEgressRefreshFloorSec: getExternalEgressEnvInt(
+ 'HCC_EXTERNAL_EGRESS_REFRESH_FLOOR_SEC',
+ 5
+ ),
+ externalEgressMaxEntries: getExternalEgressEnvInt('HCC_EXTERNAL_EGRESS_MAX_ENTRIES', 128),
// Plugin image-host allowlist (Phase 2.3). Permissive default = current
// fleet hosts + registry.evenfire.ai; enforce defaults to false (audit mode).
diff --git a/host-context-controller/src/externalEgressAccumulator.ts b/host-context-controller/src/externalEgressAccumulator.ts
index cbe124868..d863df558 100644
--- a/host-context-controller/src/externalEgressAccumulator.ts
+++ b/host-context-controller/src/externalEgressAccumulator.ts
@@ -60,7 +60,7 @@ export interface AccumulateHostEgressOutput {
cidrs: string[]
/** Annotations to stamp on the policy: serialized state + resolved-at. */
annotations: Record<string, string>
- /** True iff the (ip,port,protocol) set changed vs the previous state. */
+ /** True iff the (fqdn,ip,port,protocol) set changed vs the previous state. */
changed: boolean
/** True iff the persisted window is aging and must be re-persisted (audit M1). */
renewalDue: boolean
diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index 3e38c9c94..2aa0ccea4 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -48,22 +48,24 @@ const mocks = vi.hoisted(() => {
}
})
-vi.mock('./config', () => ({
- config: {
- devMode: false,
- namespace: 'mcp-server',
- hostNamespace: 'mcp-host',
- rpcProxyNamespace: 'rpc-proxy',
- channelsNamespace: 'channels',
- port: 8081,
- runtimeNamespaces: ['mcp-server', 'mcp-host', 'sandbox-recipes', 'rpc-proxy'],
- hostK8sRequestTimeoutMs: 30_000,
- hostResyncIntervalSec: 0,
- externalEgressResyncIntervalSec: 0,
- controlApiBaseUrl: 'http://control-api.test:8090',
- governedTracingEnabled: false,
- },
+// Mutable so a test can enable the external-egress resync timer (R1-M4); every
+// other test keeps externalEgressResyncIntervalSec: 0 (reset in afterEach).
+const mockConfig = vi.hoisted(() => ({
+ devMode: false,
+ namespace: 'mcp-server',
+ hostNamespace: 'mcp-host',
+ rpcProxyNamespace: 'rpc-proxy',
+ channelsNamespace: 'channels',
+ port: 8081,
+ runtimeNamespaces: ['mcp-server', 'mcp-host', 'sandbox-recipes', 'rpc-proxy'],
+ hostK8sRequestTimeoutMs: 30_000,
+ hostResyncIntervalSec: 0,
+ externalEgressResyncIntervalSec: 0,
+ externalEgressRefreshFloorSec: 5,
+ controlApiBaseUrl: 'http://control-api.test:8090',
+ governedTracingEnabled: false,
}))
+vi.mock('./config', () => ({ config: mockConfig }))
vi.mock('./administrativeOutcomeReporter', () => ({
createAdministrativeOutcomeReporter: mocks.createAdministrativeOutcomeReporter,
@@ -222,6 +224,7 @@ describe('McpServerWatcher startup', () => {
afterEach(() => {
vi.useRealTimers()
+ mockConfig.externalEgressResyncIntervalSec = 0 // R1-M4: keep the timer off by default
mocks.ensureDefaultPolicies.mockReset().mockResolvedValue(undefined)
mocks.netPolFullReconcile.mockReset().mockResolvedValue(undefined)
mocks.serverFullReconcile.mockReset().mockResolvedValue(undefined)
@@ -229,6 +232,52 @@ describe('McpServerWatcher startup', () => {
mocks.sfsFullReconcile.mockReset().mockResolvedValue(undefined)
})
+ // R1-M4 (zach88): the self-rescheduling resync timer (only the pure delay
+ // helper was covered). Assert the behavioral invariants the comments promise:
+ // arms once, reschedules only AFTER a pass resolves, and stop() ends the chain.
+ it('R1-M4: external-egress resync timer arms once, reschedules after each pass, and stops', async () => {
+ vi.useFakeTimers()
+ mockConfig.externalEgressResyncIntervalSec = 60
+ const watcher = new McpServerWatcher()
+ for (const m of [
+ 'startMcpServerWatch',
+ 'startContextWatch',
+ 'startSharedFileSystemWatch',
+ 'startGlobalFileSystemWatch',
+ 'startCommunicationChannelWatch',
+ ]) {
+ vi.spyOn(watcher as any, m).mockImplementation(async () => undefined)
+ }
+ // Control each resync pass's completion so we can prove the reschedule waits.
+ let pending = deferred()
+ const runSpy = vi
+ .spyOn(watcher as any, 'runExternalEgressResync')
+ .mockImplementation(() => pending.promise)
+
+ await watcher.start()
+ expect(runSpy).not.toHaveBeenCalled() // not until the first delay elapses
+
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(runSpy).toHaveBeenCalledTimes(1) // armed once, fired once
+
+ // The NEXT pass must not be scheduled until this one resolves.
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(runSpy).toHaveBeenCalledTimes(1) // still 1 — no overlap while pending
+
+ pending.resolve()
+ await Promise.resolve()
+ pending = deferred()
+ await vi.advanceTimersByTimeAsync(60_000)
+ expect(runSpy).toHaveBeenCalledTimes(2) // rescheduled after the pass resolved
+
+ // stop() ends the chain — no further fires.
+ watcher.stop()
+ pending.resolve()
+ await Promise.resolve()
+ await vi.advanceTimersByTimeAsync(60_000 * 5)
+ expect(runSpy).toHaveBeenCalledTimes(2)
+ })
+
it('passes the governed tracing switch to the administrative reporter factory', () => {
new McpServerWatcher()
diff --git a/packages/network-policy-core/index.cjs b/packages/network-policy-core/index.cjs
index b2373e8b8..0244b87ce 100644
Binary files a/packages/network-policy-core/index.cjs and b/packages/network-policy-core/index.cjs differ
diff --git a/packages/network-policy-core/index.d.ts b/packages/network-policy-core/index.d.ts
index 3390617a0..17369e5d9 100644
--- a/packages/network-policy-core/index.d.ts
+++ b/packages/network-policy-core/index.d.ts
@@ -69,7 +69,7 @@ export interface ReconcileOutput {
state: EgressState
/** live effective entries to render as ipBlocks (== state.entries) */
entries: EgressEntry[]
- /** true iff the (ip,port,protocol) set changed vs previous — else NO-OP write */
+ /** true iff the (fqdn,ip,port,protocol) set changed vs previous — else NO-OP write */
changed: boolean
/**
* true iff a SURVIVING entry's persisted window is within overlap/2 of lapsing
@@ -100,7 +100,7 @@ export declare function reconcileEgressState(
config: EgressCoreConfig
): ReconcileOutput
-/** Stable change hash over (ip,port,protocol) only — excludes expiresAt (H4). */
+/** Stable change hash over (fqdn,ip,port,protocol) only — excludes expiresAt (H4). */
export declare function stateHash(entries: EgressEntry[]): string
/** Deterministic, ordered annotation map for the policy (new format + human view). */
diff --git a/packages/network-policy-core/index.test.cjs b/packages/network-policy-core/index.test.cjs
index 6312ce88c..0ddc14cdd 100644
--- a/packages/network-policy-core/index.test.cjs
+++ b/packages/network-policy-core/index.test.cjs
@@ -418,14 +418,19 @@ test('H-B: without declarations, legacy falls back to the historical 443 grace',
// regardless of FQDN length. A fixed entry-count cap cannot bound bytes (a
// 253-char FQDN serializes ~5× a short one); an oversized annotation 422s at the
// apiserver and loops the reconcile.
-test('M-C byte cap: the serialized state never exceeds the byte budget', () => {
+// R1-M1 (zach88): the eviction must budget STATE **and** TARGETS together — the
+// 256KB apiserver cap is on the SUM of all annotations, and serializeState emits
+// both `egress-fqdn-state` and `egress-fqdn-targets` from the same entries. A
+// long-FQDN set that fits under a STATE-only budget can still blow the combined
+// limit and trigger the exact 422 reconcile loop the guard exists to prevent.
+test('R1-M1 byte cap: STATE + TARGETS together never exceed the 256KB apiserver limit', () => {
const longFqdn = `${'a'.repeat(240)}.example.com` // ~252 chars
const bigCfg = { overlapMs: 300_000, maxEntries: 4096 } // count cap won't bite first
- // 900 distinct /32s under the long FQDN ≈ ~300KB if all kept — over the 200KB budget.
const ips = Array.from({ length: 900 }, (_, i) => `10.${Math.floor(i / 256)}.${i % 256}.1`)
const out = core.reconcileEgressState(core.emptyState(), [obsOk(longFqdn, ips, TTL, 443)], 1000, bigCfg)
- const bytes = core.serializeState(out.state)[core.STATE_ANNOTATION].length
- assert.ok(bytes <= 200 * 1000, `serialized state is ${bytes} bytes, must be <= 200000`)
+ const ann = core.serializeState(out.state)
+ const total = ann[core.STATE_ANNOTATION].length + ann[core.TARGETS_ANNOTATION].length
+ assert.ok(total <= 262144, `STATE+TARGETS = ${total} bytes, must be <= 262144 (256KB)`)
assert.ok(out.entries.length > 0, 'not everything was evicted')
assert.ok(out.entries.length < 900, 'byte-budget eviction dropped the overflow')
assert.equal(out.overCap, true, 'overCap flags the eviction for the alarm/metric')
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index cf09c2004..f49b92a4b 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.284",
+ "version": "0.1.285",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.284",
+ "version": "0.1.285",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index b891d68e4..69f955e5e 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.284",
+ "version": "0.1.285",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/config.test.ts b/workflow-recipes/src/config.test.ts
index b6e482bf1..07a75b005 100644
--- a/workflow-recipes/src/config.test.ts
+++ b/workflow-recipes/src/config.test.ts
@@ -291,7 +291,7 @@ describe('loadConfig', () => {
expect(() => loadConfig()).toThrow(new RegExp(key))
})
- it('enforces the floor <= interval < overlap invariant (fail loud)', () => {
+ it('enforces the floor <= interval <= overlap/2 invariant (fail loud)', () => {
// floor > interval
process.env.WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = '40'
process.env.WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = '30'
@@ -299,12 +299,23 @@ describe('loadConfig', () => {
expect(() => loadConfig()).toThrow(/floor.*interval.*overlap|external egress/i)
})
- it('rejects an interval that is not strictly below the overlap', () => {
+ it('rejects an interval that exceeds half the overlap', () => {
process.env.WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = '5'
process.env.WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = '300'
process.env.WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS = '300'
expect(() => loadConfig()).toThrow(/floor.*interval.*overlap|external egress/i)
})
+
+ // R1-M6 boundary: the enforced contract is `interval <= overlap/2`, so exactly
+ // overlap/2 must pass and overlap/2 + 1 must throw.
+ it('accepts interval == overlap/2 and rejects overlap/2 + 1', () => {
+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = '5'
+ process.env.WRC_EXTERNAL_EGRESS_OVERLAP_SECONDS = '300'
+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = '150'
+ expect(() => loadConfig()).not.toThrow()
+ process.env.WRC_EXTERNAL_EGRESS_REFRESH_INTERVAL_SECONDS = '151'
+ expect(() => loadConfig()).toThrow(/floor.*interval.*overlap|external egress/i)
+ })
})
// An unset/unparseable CLERUM_REGISTRY_URL makes isPlatformRegistryImage() return false
diff --git a/workflow-recipes/src/config.ts b/workflow-recipes/src/config.ts
index 6d54f01ec..d927029ee 100644
--- a/workflow-recipes/src/config.ts
+++ b/workflow-recipes/src/config.ts
@@ -86,8 +86,10 @@ export interface OperatorConfig {
// externalEgressAccumulator). `overlap` is the grace kept after the DNS TTL;
// `refreshInterval` is the periodic requeue backstop; `refreshFloor` clamps
// the TTL-aware advance so a TTL=0/1 cannot hot-loop; `maxEntries` is the
- // per-policy alarm cap (evict, never reject). Invariant enforced at startup:
- // floor <= interval < overlap.
+ // per-policy alarm cap across ALL declared FQDNs of the recipe (evict, never
+ // reject) — HCC's identical knob is per-FQDN since HCC writes one policy per
+ // binding (R1-L2). Invariant enforced at startup: floor <= interval <=
+ // overlap/2 (the renewal-write window is only overlap/2 wide, R1-M6).
externalEgressOverlapSeconds: number
externalEgressRefreshIntervalSeconds: number
externalEgressRefreshFloorSeconds: number
@@ -134,9 +136,11 @@ export const MIN_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = 1
export const MAX_EXTERNAL_EGRESS_REFRESH_FLOOR_SECONDS = 60 * 60
export const DEFAULT_EXTERNAL_EGRESS_MAX_ENTRIES = 128
export const MIN_EXTERNAL_EGRESS_MAX_ENTRIES = 8
-// Audit L2: at ~150 B/entry across the state + targets annotations, the cap must
-// stay well under Kubernetes' 256KB total-annotation limit or the write fails
-// permanently with a 422. 1300 entries ~= 195KB, a safe ceiling (default is 128).
+// Audit L2 + R1-M1: this is a coarse COUNT alarm cap (default 128). The real
+// bound on annotation size — STATE **and** TARGETS together under Kubernetes'
+// 256KB total-annotation limit — is enforced by the core's byte-aware eviction
+// (MAX_ANNOTATION_BYTES in network-policy-core), which trims long-FQDN sets well
+// before 1300. Kept equal to HCC's ceiling so the two controllers can't drift.
export const MAX_EXTERNAL_EGRESS_MAX_ENTRIES = 1300
function getEnvBool(key: string, defaultValue: boolean): boolean {
diff --git a/workflow-recipes/src/k8sClient.ts b/workflow-recipes/src/k8sClient.ts
index 3d67281bc..6f7019923 100644
--- a/workflow-recipes/src/k8sClient.ts
+++ b/workflow-recipes/src/k8sClient.ts
@@ -420,7 +420,7 @@ export function recipeHasExternalExactHostEgress(recipe: WorkflowRecipeCRD): boo
* issue #299 §3.2/§5 — the external-egress refresh cadence in ms.
*
* `clamp(refreshInterval, floor)`: never tick faster than the floor. `loadConfig`
- * already enforces `floor <= interval < overlap`, but clamping here keeps the
+ * already enforces `floor <= interval <= overlap/2`, but clamping here keeps the
* timer correct even if a caller passes an unvalidated config (tests, future
* callers), so a sub-floor interval can never turn the timer into a busy loop.
*/
diff --git a/workflow-recipes/src/reconciler/externalEgressAccumulator.ts b/workflow-recipes/src/reconciler/externalEgressAccumulator.ts
index 2effbc5a9..1323142a1 100644
--- a/workflow-recipes/src/reconciler/externalEgressAccumulator.ts
+++ b/workflow-recipes/src/reconciler/externalEgressAccumulator.ts
@@ -19,8 +19,8 @@
* Guarantees delegated to the core (see plan §0/§3/§5):
* - H1 fail-static: a `transient` resolver failure FREEZES that FQDN's entries
* (never prunes them while DNS is failing) and surfaces it in `frozenFqdns`.
- * - H3 eviction: on overflow, evict soonest-to-expire, NEVER reject/truncate.
- * - H4 no-op: `changed` is over (ip,port,protocol) only — a timestamp-only
+ * - H3 eviction: on overflow, evict least-recently-observed (soonest-to-expire is only a tiebreak), NEVER reject/truncate.
+ * - H4 no-op: `changed` is over (fqdn,ip,port,protocol) only — a timestamp-only
* refresh writes nothing.
* - H5 rehydration: previous state is parsed from the policy's annotations; an
* unparseable/legacy format is NOT collapsed to an empty set.
@@ -63,7 +63,7 @@ export interface AccumulateOutput {
resolved: ResolvedExternalEgressInput[]
/** Annotations to stamp on the policy: serialized state + resolved-at. */
annotations: Record<string, string>
- /** True iff the (ip,port,protocol) set changed vs the previous state. */
+ /** True iff the (fqdn,ip,port,protocol) set changed vs the previous state. */
changed: boolean
/** True iff the persisted window is aging and must be re-persisted (audit M1). */
renewalDue: boolean
diff --git a/workflow-recipes/src/reconciler/reconciler.test.ts b/workflow-recipes/src/reconciler/reconciler.test.ts
index 92f58a0d0..6fa9a31ab 100644
--- a/workflow-recipes/src/reconciler/reconciler.test.ts
+++ b/workflow-recipes/src/reconciler/reconciler.test.ts
@@ -3896,6 +3896,113 @@ describe('WorkflowRecipeReconciler', () => {
expect(wroteUiEgress).toBe(true)
})
+ // R1-M2 (zach88): an internal-only ui-egress policy (no external[]) must reach
+ // the no-op gate on an unchanged reconcile. Before the fix the live-policy read
+ // sat inside the externals-only branch, so `existing` stayed null and the policy
+ // was rewritten every reconcile (amplified for mixed recipes by the 60s refresh).
+ it('R1-M2: an internal-only ui-egress policy is a no-op on the second reconcile', async () => {
+ const kc = new k8s.KubeConfig()
+ const rec = new WorkflowRecipeReconciler(kc, undefined, {})
+ const recipe = makeRecipe({
+ spec: {
+ workloads: [
+ { id: 'frontend', type: 'deployment', image: 'fe:1', port: 8080 },
+ { id: 'backend', type: 'deployment', image: 'be:1', port: 9090 },
+ ],
+ ui: {
+ workloadRef: 'frontend',
+ port: 8080,
+ egress: { internal: [{ workloadRef: 'backend', port: 9090 }] },
+ },
+ },
+ })
+ await rec.reconcile(recipe)
+ const p1 = mockNetworkingApi.createNamespacedNetworkPolicy.mock.calls
+ .map(c => c[0].body)
+ .find(b => b?.metadata?.name === 'ui-egress-test-recipe')
+ expect(p1).toBeTruthy()
+
+ // The policy is now live; a second identical reconcile must NOT rewrite it.
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockImplementation(({ name }: { name: string }) =>
+ Promise.resolve(
+ name === 'ui-egress-test-recipe' ? p1 : { metadata: { name, resourceVersion: '1' } }
+ )
+ )
+ mockNetworkingApi.createNamespacedNetworkPolicy.mockClear()
+ mockNetworkingApi.replaceNamespacedNetworkPolicy.mockClear()
+
+ await rec.reconcile(recipe)
+
+ const wroteUiEgress =
+ mockNetworkingApi.createNamespacedNetworkPolicy.mock.calls.some(
+ c => c[0]?.body?.metadata?.name === 'ui-egress-test-recipe'
+ ) ||
+ mockNetworkingApi.replaceNamespacedNetworkPolicy.mock.calls.some(
+ c =>
+ c[0]?.name === 'ui-egress-test-recipe' ||
+ c[0]?.body?.metadata?.name === 'ui-egress-test-recipe'
+ )
+ expect(wroteUiEgress).toBe(false)
+ })
+
+ // R1-M3 (zach88): the no-op gate must hold when the LIVE policy is apiserver-
+ // shaped — keys reordered ({ports,to} not {to,ports}) and protocol defaulted to
+ // TCP — which is exactly what the canonicalize/egressSignature fix motivates but
+ // R.8.24 (which feeds the builder's own output back) never exercised.
+ it('R1-M3: external egress is a no-op against an apiserver-normalized live policy', async () => {
+ const kc = new k8s.KubeConfig()
+ const rec = new WorkflowRecipeReconciler(kc, undefined, {
+ fqdnLookup: async () => ({ kind: 'ok', ipv4: ['93.184.216.10'], ipv6: [], ttlSeconds: 300 }),
+ })
+ const recipe = makeRecipe({
+ spec: {
+ workloads: [{ id: 'frontend', type: 'deployment', image: 'fe:1', port: 8080 }],
+ ui: {
+ workloadRef: 'frontend',
+ port: 8080,
+ egress: { external: [{ fqdn: 'api.example.com', port: 443 }] },
+ },
+ },
+ })
+ await rec.reconcile(recipe)
+ const p1 = mockNetworkingApi.createNamespacedNetworkPolicy.mock.calls
+ .map(c => c[0].body)
+ .find(b => b?.metadata?.name === 'ui-egress-test-recipe')
+ expect(p1).toBeTruthy()
+
+ // Reshape p1 the way the apiserver returns it: reorder each rule's keys and
+ // inject protocol:'TCP' on ports. The state annotation is preserved.
+ const live = JSON.parse(JSON.stringify(p1))
+ live.spec.egress = (live.spec.egress ?? []).map((rule: Record<string, unknown>) => ({
+ ports: ((rule.ports as Array<Record<string, unknown>>) ?? []).map(pt => ({
+ protocol: pt.protocol ?? 'TCP',
+ port: pt.port,
+ })),
+ to: (rule.to as Array<Record<string, unknown>>) ?? [],
+ }))
+
+ mockNetworkingApi.readNamespacedNetworkPolicy.mockImplementation(({ name }: { name: string }) =>
+ Promise.resolve(
+ name === 'ui-egress-test-recipe' ? live : { metadata: { name, resourceVersion: '1' } }
+ )
+ )
+ mockNetworkingApi.createNamespacedNetworkPolicy.mockClear()
+ mockNetworkingApi.replaceNamespacedNetworkPolicy.mockClear()
+
+ await rec.reconcile(recipe) // identical resolver output → same set → no-op
+
+ const wrote =
+ mockNetworkingApi.createNamespacedNetworkPolicy.mock.calls.some(
+ c => c[0]?.body?.metadata?.name === 'ui-egress-test-recipe'
+ ) ||
+ mockNetworkingApi.replaceNamespacedNetworkPolicy.mock.calls.some(
+ c =>
+ c[0]?.name === 'ui-egress-test-recipe' ||
+ c[0]?.body?.metadata?.name === 'ui-egress-test-recipe'
+ )
+ expect(wrote).toBe(false)
+ })
+
it('fails sandbox UI external egress in required mode when cluster enforcement is not confirmed', async () => {
const recipe = makeRecipe({
spec: {
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index f5eff8278..ac3c59229 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -3985,10 +3985,15 @@ export class WorkflowRecipeReconciler {
// annotation and losing the overlap grace when the new name later rotates.
// acc.changed is over (fqdn,ip,port,protocol), so it catches the rename.
let egressStateChanged = false
+ // R1-M2: read the live policy for ALL cases, not only external egress, so an
+ // internal-only sibling policy (ui.egress.internal[] with no external[]) can
+ // hit the no-op gate below instead of being rewritten on every reconcile —
+ // which the 60s external-egress refresh loop amplifies for mixed recipes. For
+ // external egress it also seeds the accumulator's rehydration (H5).
+ existing = await this.readNetworkPolicyOrNull(policyName, ns)
if (externals.length > 0) {
// issue #299: fold this DNS snapshot into the accumulated sliding-window
// set persisted on the live policy's annotations (rehydrate H5).
- existing = await this.readNetworkPolicyOrNull(policyName, ns)
const acc = accumulateExternalEgress({
externals: externals.map(e => ({ fqdn: e.fqdn, port: e.port })),
resolveResult: { resolved, failures },
@@ -4439,9 +4444,12 @@ export class WorkflowRecipeReconciler {
let wlEgressRenewalDue = false
let wlEgressStateChanged = false // H-E: catch fqdn-attribution-only changes
const wlPolicyName = rb.workloadEgressPolicyName(recipe.metadata.name, w.id)
+ // R1-M2: read the live policy for ALL cases so an internal-only (cluster-
+ // local) workload egress policy hits the no-op gate instead of churning
+ // every reconcile; for external egress it also seeds rehydration (H5).
+ existingWlPolicy = await this.readNetworkPolicyOrNull(wlPolicyName, wlNs)
if (externalDeclared.length > 0) {
// issue #299: accumulate the sliding-window egress set (rehydrate H5).
- existingWlPolicy = await this.readNetworkPolicyOrNull(wlPolicyName, wlNs)
const acc = accumulateExternalEgress({
externals: externalDeclared.map(e => ({ fqdn: e.fqdn, port: e.port })),
resolveResult: { resolved: resolvedExternal, failures },
@@ -4607,10 +4615,14 @@ export class WorkflowRecipeReconciler {
return true
}
// Rules are identical. Persist the new-format state annotation exactly once to
- // migrate a policy that predates it, so a controller restart can rehydrate
- // the accumulated window; thereafter (annotation present, egress unchanged)
- // it is a no-op.
- return !existing.metadata?.annotations?.[STATE_ANNOTATION]
+ // migrate an EXTERNAL-egress policy that predates it, so a controller restart
+ // can rehydrate the accumulated window; thereafter (annotation present, egress
+ // unchanged) it is a no-op. R1-M2: gate on the DESIRED carrying a state
+ // annotation — an internal-only policy never has one, so without this guard it
+ // would return true forever and be rewritten every reconcile (mirrors HCC's
+ // externalEgressWriteNeeded).
+ const desiredState = desired.metadata?.annotations?.[STATE_ANNOTATION]
+ return Boolean(desiredState) && !existing.metadata?.annotations?.[STATE_ANNOTATION]
}
/**