Skip to content

Commit 05afb32

Browse files
Merge pull request #200 from brownjuly2003-code/fix/audit-post11
fix: post-11.07 audit — 8 findings (webhook keyset cursor, helm PG egress/PDB/selector, control-plane clock & retry, E4 settle window)
2 parents ecbac9a + 7d58215 commit 05afb32

23 files changed

Lines changed: 1188 additions & 177 deletions

‎.github/dependabot.yml‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ updates:
4646
# have explicit floors in pyproject.toml driven by CVE fixes
4747
# (see commit e8b1237 and the A06 dependency-profiles block).
4848
# Allow minor + patch within the >= floor, never major.
49+
#
50+
# NOTE (audit 2026-07-17 #8): a Dependabot `ignore` applies to BOTH
51+
# version updates AND security updates — there is no per-ignore
52+
# `applies-to` (that key exists only on `groups`). So a CVE fixed ONLY in
53+
# a major bump of these deps gets no automatic security-update PR. This is
54+
# an ACCEPTED tradeoff: the `safety` + `pip-audit` jobs in security.yml
55+
# scan these deps and FAIL on such a CVE, surfacing it for a deliberate
56+
# manual major bump (the whole reason their majors are gated). Do NOT
57+
# "fix" by dropping the ignore — that re-introduces the unwanted
58+
# major-version PR churn these floors exist to prevent.
4959
- dependency-name: "langchain-core"
5060
update-types: ["version-update:semver-major"]
5161
- dependency-name: "langchain-text-splitters"

‎CHANGELOG.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,54 @@ All notable changes to AgentFlow are documented in this file.
44

55
## [Unreleased]
66

7+
### Fixes — post-11.07 adversarial audit (2 latent P1, 4 P2, 1 low)
8+
9+
Four-surface adversarial review of everything merged since the 11.07 audit
10+
(control-plane, serving/webhook, helm/k8s, CI). All findings fixed and locally
11+
verified (ruff/lint/targeted unit tests + helm render); no live-cluster run.
12+
Full report: `audit_2026-07-17_post11.md`.
13+
14+
- **Webhook journal scan — composite keyset cursor (P1, was a silent wedge).**
15+
The scan cursor is now `(processed_at, event_id)` and fetches strictly after
16+
it, so a single second holding ≥ `scan_batch_size` rows can no longer re-pin a
17+
second-granular cursor and silently drop every later webhook. Portable
18+
OR-decomposition predicate (row-value tuples don't transpile to ClickHouse); a
19+
regression test seeds a larger-than-one-batch second and is red on the old
20+
code, green on the fix. Follow-up (adversarial review): a strict keyset alone
21+
would silently drop same-second rows that become visible after the frontier
22+
passed their second (UUID event ids are not monotonic; ClickHouse
23+
`processed_at` is second-granular), so every dispatcher fetch is bounded by a
24+
DB-clock **settle watermark** — `processed_at <= now() - INTERVAL
25+
AGENTFLOW_WEBHOOK_SETTLE_SECONDS` (default 3 s) — and the frontier crosses
26+
only closed seconds. The settle value must exceed writer stamp-to-visibility
27+
lag plus writer↔DB clock skew.
28+
- **NetworkPolicy — PostgreSQL egress (P1, was a hardened-prod outage).** A
29+
`:5432` egress rule now renders when `controlPlane.store=postgres`; without it,
30+
`networkPolicy.enabled=true` on the postgres profile denied every pod's PG
31+
connect and the control-plane pool never opened.
32+
- **Control-plane retry backoff — DB clock (P2).** `next_attempt_at` is computed
33+
in SQL (`now() + make_interval`) instead of the app pod's clock, mirroring the
34+
lease columns, so NTP skew no longer collapses or over-delays the
35+
webhook/outbox backoff.
36+
- **Replica-correctness verify — settle window (P2).** E4 Checks 3/4 dwell a
37+
settle window and assert the count never exceeds one, instead of asserting on
38+
the first sighting — which passed a delayed split delivery/page undetected.
39+
- **PodDisruptionBudget — api-scoped (P2).** The PDB selects `component: api`, so
40+
a drain cannot evict both API pods while a lone worker satisfies the budget.
41+
- **API Deployment selector — stable component label (P2).**
42+
`app.kubernetes.io/component: api` is now unconditional, so the immutable
43+
`spec.selector` no longer changes when `worker.enabled` is toggled. One-time
44+
recreate for pre-split installs is documented in
45+
`docs/migration/helm-component-selector.md` (no pre-upgrade hook — it would
46+
fire on every upgrade).
47+
- **Webhook outcome write — transient retry (P2).**
48+
`record_webhook_delivery_outcome` retries transient DB errors like
49+
`record_api_usage`, so a blip after a successful POST no longer strands the
50+
row+lease for the full claim window.
51+
- **Dependabot `ignore` — documented security-update scope (low).** Commented
52+
that an `ignore` also suppresses security-update PRs (there is no per-ignore
53+
`applies-to`); an accepted tradeoff, still caught by the safety/pip-audit jobs.
54+
755
### Perf — paced 1 h @ 100 eps produce (apply 99.5)
856

957
- Mac compose (1 Flink TM), fresh volumes: 360 000 events at `--pace-eps 100`
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
# Helm migration: API Deployment selector now carries `component: api` unconditionally
2+
3+
## Applies to
4+
5+
Operators upgrading an **existing** AgentFlow Helm release that was installed
6+
with a chart **before** this one, where `worker.enabled=false` (the default).
7+
Fresh installs and releases already running `worker.enabled=true` are **not**
8+
affected.
9+
10+
## What changed and why
11+
12+
The API Deployment (`templates/deployment.yaml`) now adds
13+
`app.kubernetes.io/component: api` to its pod template labels **and** its
14+
`spec.selector.matchLabels` **unconditionally**. Previously that label was added
15+
only when `worker.enabled=true`.
16+
17+
This fixes two audit findings:
18+
19+
- **#7 — immutable selector toggle-break.** `spec.selector` is immutable in
20+
Kubernetes. When the label was gated on `worker.enabled`, flipping that value
21+
on a live release changed the selector, so `helm upgrade` aborted with
22+
`spec.selector is immutable`. Making the label unconditional keeps the selector
23+
**constant** across the `worker.enabled` toggle, so the split can be enabled or
24+
disabled in place.
25+
- **#6 — component-scoped PodDisruptionBudget.** The PDB now selects
26+
`component: api`, guaranteeing at least one *API* pod survives a voluntary
27+
disruption. That guarantee only holds if API pods **always** carry the label,
28+
which is why the pod-template label had to become unconditional too.
29+
30+
It also keeps API and worker pods in disjoint selector sets, so the two
31+
Deployments can never adopt each other's pods.
32+
33+
## The one-time breaking upgrade
34+
35+
Because `spec.selector` is immutable, the **first** upgrade of a pre-existing
36+
`worker.enabled=false` release onto this chart changes the selector from
37+
`{name, instance}` to `{name, instance, component=api}`. The API server rejects
38+
the in-place change:
39+
40+
```
41+
Deployment.apps "<release>-agentflow" is invalid: spec.selector: Invalid value:
42+
v1.LabelSelector{...}: field is immutable
43+
```
44+
45+
`helm upgrade` fails and rolls back; nothing is left half-applied. Recreate the
46+
API Deployment **once** to move past it. This is a one-time step — subsequent
47+
upgrades are normal.
48+
49+
### Option A — zero-downtime (recommended for multi-replica / production)
50+
51+
Orphan the existing pods so they keep serving, let the recreated Deployment
52+
stand up new pods, then reap the orphans:
53+
54+
```bash
55+
kubectl delete deployment <release>-agentflow -n <namespace> --cascade=orphan
56+
helm upgrade <release> <chart> [same flags as before]
57+
# wait for the new (component=api) pods to become Ready, then remove the
58+
# orphaned old pods — they lack component=api so the new Deployment won't adopt
59+
# them and they will not be cleaned up automatically:
60+
kubectl get pods -n <namespace> -l app.kubernetes.io/name=agentflow \
61+
-L app.kubernetes.io/component
62+
kubectl delete pod <old-pod-names> -n <namespace>
63+
```
64+
65+
### Option B — simplest (brief serving gap)
66+
67+
For a single-replica default install where a short gap is acceptable:
68+
69+
```bash
70+
kubectl delete deployment <release>-agentflow -n <namespace>
71+
helm upgrade <release> <chart> [same flags as before]
72+
```
73+
74+
## Notes
75+
76+
- The chart does **not** ship a `pre-upgrade` hook to automate the delete. A hook
77+
that deletes the primary API Deployment would fire on **every** upgrade (helm
78+
hooks are not conditional on "did the selector change"), turning a one-time
79+
migration into a recurring outage. The manual step above runs exactly once, by
80+
operator decision.
81+
- The Service selector is unaffected (Service selectors are mutable): it already
82+
narrows to `component: api` when `worker.enabled=true` and otherwise selects on
83+
`{name, instance}`, which still matches the API pods.
84+
- Related NetworkPolicy change in the same release: a PostgreSQL `:5432` egress
85+
rule is now rendered when `controlPlane.store=postgres`. No migration action —
86+
it only adds an allowed egress.

‎docs/serving-bridge.md‎

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -177,16 +177,35 @@ scans and pushes kept one entry per event forever. All journal consumers are
177177
now bounded:
178178

179179
- **Webhook dispatcher** — incremental cursor scan: each pass fetches at most
180-
`scan_batch_size` (1000) rows at/after the `processed_at` high-water mark
181-
(`min_processed_at`, inclusive — the journal is second-granular on
182-
ClickHouse, and the seen-set dedups the re-fetched cursor second). The
183-
cursor advances over the contiguous prefix of rows that end the pass seen
184-
and **freezes at the first row whose durable enqueue failed**, so that row
185-
is re-fetched and retried next pass — the retry-forever semantics the full
186-
scan provided. An all-seen full batch still advances the cursor, so a seen
187-
frontier wider than one batch cannot pin the window. Startup
188-
(`mark_existing_events_seen`) seeds the cursor from the newest batch instead
189-
of enumerating the journal.
180+
`scan_batch_size` (1000) rows **strictly after** a composite
181+
`(processed_at, event_id)` keyset cursor, in `processed_at, event_id ASC`
182+
order. The cursor advances over the contiguous prefix of rows that end the
183+
pass seen and **freezes at the first row whose durable enqueue failed**, so
184+
that row is re-fetched and retried next pass — the retry-forever semantics the
185+
full scan provided. The keyset (not a bare second-granular high-water mark) is
186+
what lets the frontier advance **within** a single second: an inclusive
187+
`processed_at >=` cursor floored to the second was re-pinned forever by any
188+
second holding ≥ `scan_batch_size` rows, silently dropping every later webhook
189+
for every tenant (audit 2026-07-17 #1). The predicate is the portable
190+
OR-decomposition `t > ts OR (t = ts AND event_id > id)` — a row-value tuple
191+
does not transpile to ClickHouse. A strict keyset is only lossless over
192+
seconds no writer will stamp again — event ids are UUIDs (not monotonic), so
193+
a frontier inside the still-open second would permanently exclude any
194+
same-second row that becomes visible later with a lower id. Every dispatcher
195+
fetch is therefore bounded by a DB-clock **settle watermark**
196+
(`processed_at <= now() - INTERVAL N SECOND`,
197+
`AGENTFLOW_WEBHOOK_SETTLE_SECONDS`, default 3 s; `0` disables the bound
198+
entirely — tests only; must exceed writer stamp-to-visibility lag +
199+
writer↔DB clock skew, and a violation is silent (a late-visible row behind
200+
the frontier is simply never delivered), so treat the invariant as an
201+
operating requirement, not a tunable. On a non-UTC DuckDB host the
202+
session-local frame is non-monotonic across the autumn DST fold: delivery
203+
of rows stamped inside the fold window is delayed (never dropped) by up to
204+
the fold width. Worst-case added delivery latency = settle. Startup (`mark_existing_events_seen`) seeds the cursor
205+
from the newest **settled** batch instead of enumerating the journal —
206+
unsettled rows deliver once settled (a restart race is not lost; the durable
207+
enqueue's idempotent key suppresses re-POSTs); the seen-set is now a
208+
secondary safety net, with the keyset as the primary dedup.
190209
- **Seen-sets** — `BoundedSeenSet` (`src/serving/seen_events.py`): capped,
191210
FIFO-with-refresh eviction. Eviction is safe because webhook enqueue is
192211
idempotent on its primary key (inline delivery fires only for freshly

‎helm/agentflow/templates/NOTES.txt‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
AgentFlow {{ .Chart.AppVersion }} has been deployed as release "{{ .Release.Name }}".
2+
3+
Service (in-cluster):
4+
{{ include "agentflow.fullname" . }}.{{ .Release.Namespace }}.svc:{{ .Values.service.port }}
5+
6+
Control-plane store: {{ .Values.controlPlane.store }}
7+
{{- if .Values.worker.enabled }}
8+
Process-role split: ENABLED (API Deployment role=api, worker Deployment role=worker).
9+
{{- end }}
10+
{{- if .Values.networkPolicy.enabled }}
11+
NetworkPolicy: ENABLED (default-deny + explicit egress{{ if eq .Values.controlPlane.store "postgres" }}, including PostgreSQL:{{ .Values.networkPolicy.egressPorts.postgres }}{{ end }}).
12+
{{- end }}
13+
14+
{{- if .Release.IsUpgrade }}
15+
16+
>>> UPGRADE NOTE — one-time API Deployment recreate may be required <<<
17+
18+
This release makes the API Deployment's spec.selector carry
19+
`app.kubernetes.io/component: api` UNCONDITIONALLY. spec.selector is IMMUTABLE.
20+
If the release you just upgraded FROM was installed with an earlier chart where
21+
`worker.enabled=false` (selector was name+instance only), the API server will
22+
reject this upgrade with:
23+
24+
Deployment.apps "{{ include "agentflow.fullname" . }}" is invalid:
25+
spec.selector: Invalid value: ... field is immutable
26+
27+
If that happened, the upgrade did NOT apply. Recreate the API Deployment once —
28+
pick ONE:
29+
30+
# A) zero-downtime: orphan the old pods, let the new Deployment take over,
31+
# then reap the orphans after the new pods are Ready.
32+
kubectl delete deployment {{ include "agentflow.fullname" . }} \
33+
-n {{ .Release.Namespace }} --cascade=orphan
34+
helm upgrade {{ .Release.Name }} <chart> [same flags]
35+
# ...verify new pods Ready, then delete leftover old pods by hand.
36+
37+
# B) simplest (brief serving gap on a single-replica install):
38+
kubectl delete deployment {{ include "agentflow.fullname" . }} \
39+
-n {{ .Release.Namespace }}
40+
helm upgrade {{ .Release.Name }} <chart> [same flags]
41+
42+
Releases already running the split (worker.enabled=true) are unaffected — their
43+
selector already carried component=api. Fresh installs are unaffected.
44+
See docs/migration/helm-component-selector.md for detail.
45+
{{- end }}

‎helm/agentflow/templates/deployment.yaml‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@ metadata:
1515
name: {{ include "agentflow.fullname" . }}
1616
labels:
1717
{{- include "agentflow.labels" . | nindent 4 }}
18-
{{- if .Values.worker.enabled }}
18+
# component=api is UNCONDITIONAL (not gated on worker.enabled): it keeps this
19+
# Deployment's immutable spec.selector stable across a worker.enabled toggle
20+
# (helm upgrade would otherwise fail "spec.selector is immutable"), keeps API
21+
# vs worker pods disjoint so the two Deployments never adopt each other's
22+
# pods, and lets the api-scoped PodDisruptionBudget always match these pods.
1923
app.kubernetes.io/component: api
20-
{{- end }}
2124
spec:
2225
replicas: {{ .Values.replicaCount }}
2326
strategy:
@@ -28,16 +31,12 @@ spec:
2831
selector:
2932
matchLabels:
3033
{{- include "agentflow.selectorLabels" . | nindent 6 }}
31-
{{- if .Values.worker.enabled }}
3234
app.kubernetes.io/component: api
33-
{{- end }}
3435
template:
3536
metadata:
3637
labels:
3738
{{- include "agentflow.selectorLabels" . | nindent 8 }}
38-
{{- if .Values.worker.enabled }}
3939
app.kubernetes.io/component: api
40-
{{- end }}
4140
{{- with .Values.podLabels }}
4241
{{- toYaml . | nindent 8 }}
4342
{{- end }}

‎helm/agentflow/templates/networkpolicy.yaml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,12 @@ spec:
5050
- ports:
5151
- protocol: TCP
5252
port: {{ .Values.networkPolicy.egressPorts.otlp }}
53+
{{- if eq .Values.controlPlane.store "postgres" }}
54+
# PostgreSQL control-plane store (when controlPlane.store=postgres): the
55+
# shared webhook/alert/outbox/usage pool. Without this rule every API and
56+
# worker pod's connect to PG:5432 is denied and the pool never opens.
57+
- ports:
58+
- protocol: TCP
59+
port: {{ .Values.networkPolicy.egressPorts.postgres }}
60+
{{- end }}
5361
{{- end }}

‎helm/agentflow/templates/poddisruptionbudget.yaml‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,13 @@ spec:
1010
selector:
1111
matchLabels:
1212
{{- include "agentflow.selectorLabels" . | nindent 6 }}
13+
# Scope to the API role only. selectorLabels alone (name+instance) also
14+
# match the worker pods, so with worker.enabled a single minAvailable:1
15+
# budget spanning {api ∪ worker} lets a drain evict BOTH API pods while the
16+
# lone worker satisfies it → serving surface hits zero. component=api keeps
17+
# this budget a guarantee about request-serving pods. The worker is a
18+
# background singleton (delivery loops claim rows in PG and resume after a
19+
# reschedule); a minAvailable:1 PDB on a single-replica worker would instead
20+
# make its node undrainable, so workers deliberately get no PDB.
21+
app.kubernetes.io/component: api
1322
{{- end }}

‎helm/agentflow/values.yaml‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,10 @@ podDisruptionBudget:
101101

102102
# NetworkPolicy enforces a default-deny baseline plus explicit ingress on the
103103
# HTTP port and egress to dependencies (DNS, Kubernetes API, Redis, Kafka,
104-
# ClickHouse, OTLP collector). Disabled by default so existing clusters
105-
# without a NetworkPolicy controller are not broken; turn on per environment.
104+
# ClickHouse, OTLP collector, and — on the postgres control-plane profile —
105+
# PostgreSQL). Disabled by default so existing clusters without a NetworkPolicy
106+
# controller are not broken; turn on per environment. The postgres:5432 egress
107+
# rule is rendered only when controlPlane.store=postgres (harmless otherwise).
106108
networkPolicy:
107109
enabled: false
108110
ingressFromNamespaces:
@@ -112,6 +114,7 @@ networkPolicy:
112114
kafka: 9092
113115
clickhouse: 8123
114116
otlp: 4317
117+
postgres: 5432
115118

116119
# Serving engine (ADR 0006 / 0007 / 0009). The shipped demo runs ClickHouse;
117120
# the chart's default stays the safe single-node DuckDB profile because the

0 commit comments

Comments
 (0)