Skip to content

feat(placement): add the sie_placement planner, tuner and cluster appliers - #914

Merged
krisztian-gajdar merged 148 commits into
mainfrom
fix/sie-placement-review2-followups
Nov 9, 2026
Merged

krisztian-gajdar merged 148 commits into
mainfrom
fix/sie-placement-review2-followups

Conversation

@krisztian-gajdar

@krisztian-gajdar krisztian-gajdar commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Landing note

This branch contains every commit of the placement stack: #905 (planner), #906 (tuner), #907 (availability), #908 (packing), #909 (Helm values), #910 (KEDA applier), #911 (chart applier) and #913 (applier hardening), on top of #904, which has merged. The merge queue squashes each pull request, and these stacked branches conflict with their predecessors' squash commits, so the stack lands as one squash commit through this pull request. Each of those pull requests was reviewed on its own, and they close with a link here once this one merges. The merge of main (40e7757) keeps this branch's version of the sie_placement files, which are supersets of #904's, and regenerates uv.lock from main's lock.


Summary

This follow-up closes the six non-blocking findings of the second independent review of #913 (report, list), so #913 stays at its reviewed head. It is stacked on #913.

  1. Unquoted subchart references checked with Helm's YAML reader (7d6ae1a). Closes finding 1.

    • sie-cluster.secretKeyRef with unquoted no longer matches a regex of YAML scalars. After the character-set checks, it parses k: <value> with fromYaml, which uses sigs.k8s.io/yaml, the reader Helm and kubectl use for manifests. It refuses the value unless the result has no Error key and k is a string equal to the value.
    • The character-set checks still run first, so the value cannot add structure to the parsed document.
    • Now refused: names such as 0b-1 and 0b-10, and keys such as 1e_3, -_1 and 0_x1. YAML reads all of these as numbers, so Grafana's Deployment would have failed at apply. The key -, which made the rendered manifest unparseable, is now refused by the check.
    • Now accepted: strings that the regex refused but YAML reads as strings, such as the keys yEs, tRue and .1_ and the names 0b12 and 0bb.
    • .htpasswd, 1-graf and nullable still render.
  2. Render test values written as JSON (7d6ae1a). Closes finding 2. render_chart in tools/ci/tests/test_helm_render.py now writes its values file as JSON instead of with PyYAML. PyYAML left 1e3, -.5 and +.5e3 unquoted, so Helm read them as numbers before the chart saw them. The scalar tests now reach the check with the intended strings. They assert the check's own message and no longer accept Grafana's "wrong type for value" error. +.5e3 is dropped from the key cases because + already fails the data-key character set. .5e-3 replaces it.

  3. TLS strictness kept equal to httpx's default (b32000b). Closes finding 3.

    • From Python 3.13, ssl.create_default_context(), which httpx.create_ssl_context() calls, sets VERIFY_X509_STRICT and VERIFY_X509_PARTIAL_CHAIN.
    • _verification builds ssl.SSLContext(PROTOCOL_TLS_CLIENT) directly, so SSLKEYLOGFILE is never read. It now sets those two flags on Python 3.13 and later.
    • The parity test now also compares verify_flags, options and security_level with httpx.create_ssl_context(). It still compares the verify mode, host-name check and minimum version.
    • A second test sets sys.version_info to 3.13 and checks that both flags are set.
    • The package pins requires-python = ">=3.12,<3.13", so the new branch is not reached today.
  4. CA directories need a file, and the default-bundle error names the bundle (b32000b). Closes finding 4.

    • _holds_entries is now _holds_files, and it counts an entry only when entry.is_file() is true. A hash link to a certificate file counts.
    • An SSL_CERT_DIR whose directories hold only subdirectories or dangling links is now refused at start. Before, such a directory passed start-up and then failed every call with CERTIFICATE_VERIFY_FAILED. The package README already describes this check ("none of whose directories holds a file").
    • When neither CA variable is set and the certifi bundle cannot be loaded, the error is now the default CA bundle <path> cannot be loaded. It used to name SSL_CERT_DIR.
  5. Grafana admin Secret template allowlist documented, with whitespace accepted (a20396e). Closes finding 5.

    • The "Gateway token" credential-check section of the chart README and the kube-prometheus-stack.grafana comment in values.yaml now state the allowlist. A value that holds {{ may hold only lowercase letters, digits, -, ., whitespace and actions that name a field path of .Release, .Values (Grafana's values) or .Chart. Any other action fails the render.
    • The allowlist now accepts spaces, tabs and line breaks around an action's field path and between or around actions. This covers {{\t.Release.Name }}-graf and a YAML block value that ends in a newline.
    • Whitespace that ends up inside the evaluated name still fails the Secret-name check, and secretKeyRef trims the ends as YAML does.
    • Comments, printf and other function calls stay refused.
  6. NOTES names the Secret Grafana reads (a20396e). Closes finding 6.

    • sie-cluster.kubePrometheusStack.grafanaAdminSecretName, which NOTES.txt uses, now evaluates admin.existingSecret in the Grafana subchart context, as wiredSecretKeys does: .Template is merged into index .Subcharts "grafana". With no existingSecret it falls back to grafana.fullname, and it trims the result.
    • Before, {{ .Values.admin.userKey }}-admin failed the whole render in NOTES with a nil pointer, and {{ .Chart.Name }}-admin named sie-cluster-admin rather than the grafana-admin Secret that Grafana reads.
    • The comment on grafanaFullname no longer says it mirrors the admin Secret rules.
  7. Fixes from adversarial review run 1 (df7ac8f, 6a8ba70; report, dispositions).

    • _holds_files keeps scanning past an entry whose is_file() raises, such as a link loop or a link into an unreadable directory.
    • When the Grafana admin Secret name came from a template, the Secret-name errors show the template instead of its value, which for {{ .Values.YAML }} was all of Grafana's values.
    • NOTES prints the "Grafana password" line only when Grafana reads its admin password from the Secret.
    • Every values file the render tests write goes through one JSON helper that keeps non-ASCII unescaped.
  8. Fixes from adversarial review run 2 (b46e6af, 18e5688; report, dispositions).

    • A CA directory the applier may not list, such as an execute-only one, is left to OpenSSL instead of being refused at start.
    • values_json escapes the characters that YAML folds or refuses, and a probe-chart test checks that Helm reads values back exactly.
    • ruff format is applied, which CI's tools/ci check requires.
  9. Fix from adversarial review run 3 (50d702a; report, dispositions).

  10. CodeRabbit finding on the run 3 fix (d37c1ba): the search check for a CA directory that cannot be listed now uses the effective uid and gid, as OpenSSL does, where the platform supports it.

Review status at d37c1ba.

This changes the chart's credential separation checks and the TLS verification of the applier's gateway client. It therefore gets an independent adversarial review after the CodeRabbit review.

Refs #903

Verification

  • mise run lint and mise run typecheck: pass.
  • mise run test -- packages/sie_placement/tests: 1601 passed at d37c1ba (1596 at b32000b). New and changed tests:
    • The parity test compares six settings with httpx.create_ssl_context().
    • Strict flags are set when sys.version_info is 3.13.
    • A default bundle that cannot be loaded is refused by its path, for both an https and an http gateway.
    • SSL_CERT_DIR holding only a subdirectory or only a dangling link is refused.
    • A directory of hash links to certificate files is passed through.
    • Against the previous pools.py, the strict-flag test, both default-bundle cases and both new directory cases fail.
  • Standalone probe of the directly built context against ssl.create_default_context(). On Python 3.12.12 with OpenSSL 3.5.4, and on 3.13.7 and 3.14.5 with OpenSSL 3.6.2, the two contexts are equal in verify mode, host-name check, minimum and maximum version, verify flags, options and security level. The verify flags are 32768 on 3.12 and 557088 on 3.13 and 3.14.
  • mise run helm -- lint: pass.
  • tools/ci/tests/test_helm_render.py: 708 passed at 18e5688 (702 at b32000b). New and changed tests:
    • Names refused: null, true, no, 123, 1e3, 0x1f, 12.5, 0b-1, 0b-10.
    • Keys refused: .5, -.5, .5e-3, 1.5, true, y, 1e_3, -_1, 0_x1, -.
    • Keys that render, checked as the exact key: line: .htpasswd, .5x, admin-user, v1.5, yEs, tRue, .1_.
    • Names that render, checked as the exact name: line: 1-graf, graf-1.2.3, nullable, one, 0b12, 0bb.
    • Grafana templates that render: {{\t.Release.Name\t}}-graf, {{\n.Release.Name\n}}-graf and {{ .Release.Name }}-graf\n.
    • Collision: {{\t.Release.Name }}-graf\n collides with an applier client token in sie-graf/admin-password.
    • Templates still refused: a comment and printf.
    • NOTES: for an empty value, graf, {{ .Values.admin.userKey }}-admin, {{ .Chart.Name }}-admin and {{ .Release.Name }}-graf\n, NOTES names the Secret that Grafana's Deployment reads for GF_SECURITY_ADMIN_PASSWORD.
    • Against the previous _helpers.tpl, 31 of these cases fail. The refused-scalar cases that the old regex also caught fail there only on the new message. The ones that are new are 0b-1, 0b-10, 1e_3, -_1, 0_x1 and -, together with the accepted strings, the whitespace forms and the three NOTES template cases.
  • The JSON switch in render_chart changes no other test. An AST scan of the test module's string constants finds that only the scalar tests hold strings that PyYAML writes unquoted and Go YAML reads as something else (1e3, 0b-1, 0b-10, -.5, y). Under PyYAML, y would have reached Helm as a boolean.
  • Grafana template whitespace, checked end to end: the rendered Grafana Deployment was read back with Helm's own fromYaml. These forms all make Grafana read sie-graf, the name the check uses:
    • a line break followed by deep indentation before the template
    • a trailing \r, \n \n or \n\n
    • a leading tab
    • {{\r.Release.Name\r}}
    • A leading line break without that indentation breaks Grafana's own Deployment YAML, and helm template fails.
  • Byte identity of helm template against the fix(placement): keep the applier's tokens off proxies and harden plan parsing and subchart Secret checks #913 head 6b5b71a, in 15 value sets:
    • defaults, values-aws.yaml, values-gke.yaml and values-ha.yaml
    • kube-prometheus-stack alone, with Grafana admin, SMTP and LDAP Secrets, and with a .Release template
    • KEDA alone and with cert-manager
    • Loki
    • cert-manager with trust-manager
    • all subcharts
    • the applier with token auth and a client token, alone and with the subcharts
    • In every set, the only changed lines are generated Secret values (SIE_ADMIN_TOKEN, SIE_CONFIG_READ_TOKEN, the NATS password). The documents compare equal with Secret data masked.
    • A kube-prometheus-stack render with {{ .Values.admin.userKey }}-admin fails at base in NOTES.txt and renders at head.

Summary by CodeRabbit

  • New Features
    • Grafana Secret names support a restricted set of templates, including supported whitespace trimming. Invalid templates or names that do not resolve to a Secret stop rendering with a clear error.
  • Bug Fixes
    • Grafana setup and displayed commands reflect the Secret Grafana will use, and are omitted when a Secret is unnecessary.
    • Helm rendering better preserves unusual string values and keys. Certificate directory checks handle inaccessible entries more reliably, and certificate-loading errors identify the selected CA source. TLS verification settings are more consistent across Python versions.
  • Documentation
    • Added guidance on supported Grafana Secret name templates and certificate directory behavior.

Add sie-placement, a standard-library workspace package with strict,
versioned documents for a measured-only placement planner:

- service levels per served identity (comeAliveP95S, warmP99Ms or the
  ttftP99Ms and itlP99Ms pair for generation, queueWaitP99Ms), with
  optional named tiers that identities inherit and override
- receipt v1, keyed by machine profile and realized GPU product, with
  container shape, concurrency, request shape, throughput, latency
  percentiles and a source reference
- boot evidence v1 for cold boots, snapshot restores and resident loads
- price list v1 with per-profile accelerator, core and memory rates and
  a region multiplier per placement
- hourly demand per identity and operation over a UTC window
- the plan: lanes with cell, shape, concurrency, ceiling and envelope
  (floorMin, floorMax and optional buffer and scale-down window ranges),
  and each identity's lane and warmth

Every type parses from JSON-compatible dicts with path-qualified errors
and serializes back without loss. The package joins the workspace,
pytest, lint, typecheck and coverage lists. It stays out of the PyPI
distribution list and the release contract.
An integer beyond the float range in a number field raised OverflowError
from math.isfinite instead of a path-qualified SchemaError. Report it as
a non-finite number at its JSON path.

UTC hours matched any Unicode digit, so an hour written in non-ASCII
digits parsed and then serialized differently. Match ASCII digits only,
and format the hour explicitly so a year below 1000 keeps four digits on
every platform's strftime.
The plan lane's `pool` field was ambiguous: in the sie-cluster chart a
pool is a worker group (`workers.pools.<key>`), while a lane is named by
its queuePool, machineProfile and bundle tokens. Rename the wire key to
`queuePool`, the chart's lane token, and document the three tokens and
how they differ from the worker group key and an SDK logical pool.
Receipts and demand name the work primitive a lane runs, while gateway
telemetry labels requests by route. Document the fold an adapter
applies: `embeddings` is rewritten into an encode request and counts as
`encode`, `moderations` answers 501 without serving a model and carries
no demand, and `other` names no primitive. Also describe the service
level fields without a fixed count, since a generation identity declares
four.
Add sie_placement.tuner, a pure standard-library step function that an
online lane tuner calls once per tick:

- step(envelope, observation, current) returns one action (scale_up,
  scale_down, hold, hold_at_cap or raise_to_floor) and the floor,
  buffer and scale-down window to apply
- every returned setting lies inside the plan's envelope; a floor below
  floorMin is raised with raise_to_floor, and a floor above floorMax is
  lowered to it with hold_at_cap
- the floor moves one container per tick, falls only when nothing
  waits, nothing is in flight and the service level is not breached,
  and rises again only once the lane runs its current floor, so a slow
  boot does not ratchet it
- the buffer and window are tuned only when the envelope bounds them
  and the caller supplies them, so an applier that moves only the floor
  gets the same floor decisions
- an unmeasured attainment steers on the queue alone

The tests run the step over a grid of envelopes, current settings and
observations that covers every comparison the step makes, and check the
cap and minimum edges, idle-only scale-down, a slow boot and
re-convergence after a reset to the envelope minimum.
An Observation built from JSON, a database row or metric labels carries
the attainment as a plain string. The step compared it by identity
with Attainment.BREACHED, so a breach given as "breached" was never
seen as pressure. Observation now converts the attainment to the enum,
and an unknown value raises ValueError as a negative count does.
- current is the settings in force on the lane, read from the platform
  each tick or recorded again after a deploy resets them, never the
  previous Step.settings carried across a reset
- an applier applies Step.settings whenever they differ from current,
  whatever the action, and records the action as the audit label
- the action table now says that raise_to_floor, hold_at_cap and hold
  bring a buffer or window outside its range inside it, and that
  scale_up and scale_down stop at the edge of each range
Add sie_placement.planner.plan, a pure function from service levels,
receipts, boot evidence, a price list, demand, the current plan and
planner parameters to a plan and a report:

- refuse receipts and boot evidence whose realized GPU product differs
  from the product their machine profile requests or whose profile has
  no price, and receipts whose latency cannot answer the identity's
  service level
- block cells that miss the warm bounds; offer pinned, and
  cold-with-bound or snapshot-cold where boot evidence exists, with the
  slowest successful boot standing for the come-alive percentile, the
  environment's own evidence replacing borrowed evidence, and a
  comeAliveP95S of 0 admitting pinned only
- price at list times the region multiplier: one warm container plus
  the above-floor hours demand needs, or the work plus a burst tail held
  at the active floor for the cooldown; the fallback floor, cooldown,
  ceiling and buffer are parameters
- set the envelope floorMax to floorMin plus the declared buffer while
  queue wait is unmeasured, at realizable floors and capped by the
  reviewed ceiling
- report per identity the chosen cell, warmth, monthly cost and
  come-alive basis, and the nearest cheaper blocked option with the
  bounds that block it; per lane the floor and envelope-maximum cost;
  measurement requests ranked by their price-bounded saving; come-alive
  levers priced under the identity's bound and at the bound their
  measured come-alive permits; unattained queue-wait bounds; refusals;
  and the changes against the current plan

Boot evidence gains an optional borrowed flag. The rendered plan and
report are byte-stable under input reordering, and replanning over the
plan the planner wrote reports no change. Each identity gets its own
lane; co-packing is not part of this change.
An identity whose choice is its current placement now stays on its
current lane under its current name, beside whoever else that lane
hosts. The current placement also has to match the queue pool and the
bundle the parameters give the identity. Before this, the planner
renamed an unchanged lane and split a shared current lane into new
pinned floors, so an unchanged input could still produce a diff. Only
lanes for new or moved placements get minted names, and a minted name
widens its digest when a kept lane already holds it.

Kept lanes stay within the reviewed ceiling. Costs are now per lane:
each lane pays its floor once, plus its residents' demand above the
floor. A kept identity's demand is priced at its slowest receipt for
its lane's cell, shape and concurrency, under that lane's ceiling. The
totals cover every lane. totals.unpricedLanes lists each lane whose
cell has no price (with an unpricedReason) or that has a resident
whose demand no receipt can price. Each identity reports its monthly
cost on its lane. A kept identity's blockedBy names the bounds its
kept placement is known to miss.

The report also lists sharedChartLanes: every chart lane, by queue
pool, machine profile and bundle, that more than one plan lane names.

Boot seconds normalize to float, so an int and a float record of the
same boot render the same bytes in either order. New tests cover demand
summed over operations, saturated cold hours, the cheapest receipt for
levers and boot requests under shuffled input, the concurrency match of
the current placement, and snapshot restores, which are never requested.
helm_values turns a placement plan into a values overlay for the
sie-cluster chart: one worker group per machine profile, whose bundle
lanes carry minReplicas (the envelope's floorMin) and maxReplicas
(maxContainers), and one static queue pool per named queue pool, which
carries the lanes' floor as minimumWorkerCount and their pinned
identities as pinnedModels. Lane tuples are canonicalized as the chart's
lane-token helper does.

It refuses a plan the chart and the gateway would not realize as
planned: a zero-floor lane whose floorMax falls below the chart's
fallback floor, more lanes than the chart's release limit (192, or 96
when the release installs KEDA or Prometheus), plan lanes on one chart
lane or worker group that disagree on what it carries, pins on the
default queue pool, which has no static queue pool, and lanes on one
static queue pool that need different floors, pins or bundles.

A golden test pins the emitted overlay, and chart render tests render it
with helm template to check the lanes, the ScaledObject bounds, the
unchanged six-trigger list, the static queue pool environment and the
lane limits.
Add a `sie-placement tune` command that keeps each plan lane's warm
floor inside its envelope on a KEDA-scaled sie-cluster deployment:

- every tick it reads four lane series from Prometheus (lane queue
  depth, pending demand, warm floor and ready workers), reads the lane's
  floor-carrier pool with SIEClient.get_pool, and calls the tuner step
  with that pool's floor as current
- shadow mode is the default and writes nothing; with --apply it upserts
  one floor-carrier logical pool per lane through SIEClient.create_pool
  on every tick, which also renews the pool's lease
- a carrier is named placement-floor-<queuePool>-<machineProfile>-<bundle>
  and has gpus {<machineProfile>: 0}, the lane's queue pool and bundle,
  no pins, no caps and the gateway's default lease; a pool with that name
  and any other spec is reported and never written
- the applier writes only its carriers, so it never lowers another
  pool's floor, and each audit row reports a lane whose warm floor
  exceeds floorMax
- a lane missing a series is held and only brought inside its envelope
- the plan is refused before any call when an envelope's floorMax is
  above the gateway's per-pool floor limit, when it has more lanes than
  the gateway's API pool limit, or when its lane tokens cannot name a
  carrier

Pool reads use a gateway client token and pool writes the gateway admin
token, each read from a file or an environment variable. The admin
token is read only with --apply, is sent only on pool writes, and is
never printed or logged. The README documents the permission each call
needs.

The SIE SDK and httpx come from a new keda extra; the schema, tuner and
applier core keep to the standard library. Tests drive the applier with
a fake Prometheus and fake pools, and drive the command through the real
SDK against fake HTTP Prometheus and gateway servers.
The overlay merged onto worker groups that the chart's own values
already define, so enabling a group also enabled its stock bundles: a
release could run a lane the plan never placed, and the lane-limit
check undercounted. ChartParameters now takes base_pools, the
workers.pools beneath the overlay (the chart's own worker groups by
default, chart_pools()). Every bundle it enables under an emitted
group and the plan does not place is set to enabled: false, and the
enabled lanes of the groups the overlay leaves out count toward the
chart's lane limit.

Two plan lanes that canonicalize to one chart lane are refused, as the
chart refuses two entries on one canonical lane. Merging them realized
one floor, ceiling and pinned set for lanes the plan prices separately.

A container of more than one GPU is one device group or one worker per
GPU, which the plan does not say. device_groups names it per machine
profile, the overlay emits gpu.deviceGroup, and a multi-GPU lane on an
unnamed profile is refused.

The golden plan now has several bundles on one worker group, several
machine profiles on one static queue pool and a device group. It
renders over the chart's stock values without a masking base, and an
accepted plan at the lane limit renders. The order test compares the
rendered bytes. The README states that the overlay does not constrain
node selection and which planner plans these rules let through.
- refuse a token file, SIE_ADMIN_TOKEN or SIE_API_KEY that is not one
  run of printable ASCII without spaces, naming its source and never
  its value, and report a gateway transport failure by its exception
  type only, so no error text carries an Authorization header value
- map malformed Prometheus replies (a bad status line, a truncated
  body) to a failed series, so the tick holds its lanes and the loop
  keeps running, and refuse a Prometheus URL with an invalid port at
  startup
- join each gateway series to producers whose snapshot is at most 20
  seconds old, as the chart's KEDA triggers do: the lane's queue
  snapshot for queue depth, the capacity snapshot for pending demand
  and warm floor, so a stale producer's last point reads as missing
- write each carrier through its own SDK client and close it after the
  write, so the SDK's background lease renewal never runs and a
  carrier whose reads fail or whose name another pool holds lapses
  after its last write
- report a malformed pool reply from the gateway as a failed lane
  instead of ending the loop
- document that pending demand is a 0 or 1 flag that a publish in
  flight also sets, so steady traffic can read as pressure, and that
  the worker series has no freshness timestamp
A come-alive lever's savings are now the fall in the plan total found by
planning again from the plan the run wrote: savingAtPermittedBound with the
identity's come-alive bound loosened to permittedBoundS, and
savingUnderBound with the warmth's boot measured at the identity's bound.
A lever is listed only when loosening its bound lowers the plan total.

An identity that stays beside another resident of its current lane no
longer claims the lane's floor as a saving: leaving the lane leaves that
floor paid by the other residents, so loosening its bound raises the plan
total and the planner offers no lever for it.
A worker lane may declare envelope.floorMin and envelope.floorMax, the
warm-floor range a floor carrier may hold it at. The render fails unless
floorMin equals minReplicas, floorMax lies between floorMin and
maxReplicas, and, on an autoscaled lane with minReplicas 0, floorMax is 0
or at least the lane's fallback floor. An envelope renders nothing by
itself.

placementApplier.enabled renders one Deployment that runs
`sie-placement tune` against the placement plan given in
placementApplier.plan. It runs in shadow mode unless
placementApplier.apply is true. Every plan lane must name an enabled
worker lane whose envelope equals the plan lane's, so the plan cannot
move a floor outside the range the chart values bound. The ScaledObject
triggers are unchanged.

With apply, the pod mounts the gateway admin token as a read-only file
from the Secret named by gateway.auth.adminTokenSecretName; the chart
never creates the token or renders its value. Pool reads use a client
token from placementApplier.clientToken, which joins the token
separation check. The pod has its own ServiceAccount with no token
mounted and no RBAC, runs non-root with a read-only root filesystem, no
privilege escalation, every capability dropped and the RuntimeDefault
seccomp profile, and uses the Recreate strategy so one applier writes at
a time. Literal gateway pool limits in gateway.extraEnv are passed to the
applier.

The applier is disabled by default and the default renders are
unchanged.
nextCheaper.saving is now the fall in the plan total found by planning
again from the plan the run wrote, with each bound that blocks the option
loosened to what the option measured, rounded up and never below 1. It is
0 when the total would not fall. The loosened bounds may admit a cheaper
option still, and the saving counts it, as savingAtPermittedBound does for
a come-alive lever.

An identity that stays beside another resident of its current lane no
longer claims the lane's floor as a nextCheaper saving: leaving the lane
leaves that floor paid by the other residents. Levers and nextCheaper
share one cached replan per loosened bound set.
The applier presents its client token file whole, so a gateway token
Secret that lists several comma-separated tokens fails every pool read.
The render error now suggests the gateway token Secret only when the
chart generates it, which holds one token, and states that the key must
hold one token.

The chart README states that the applier reads both token files at
start and needs a restart after a gateway client or admin token
rotation, names the applier's client token in the gateway token
rotation steps, and states that the Helm values emitted from a plan
carry no lane envelopes, so they are copied from the plan.

New render tests cover a gateway auth mode known only at run time, apply
mode without gateway auth, the bundled Prometheus address, and the
--max-pools flag.
…esidents

A first plan over a running deployment should change nothing it has no
measured reason to change. Four selection rules make that hold:

- An identity whose current placement no option matches, because its lane
  has no receipt at its cell, container shape and concurrency, a cold lane
  has no successful boot, or a lazy resident has no load, keeps that
  placement unless it is known to miss a bound. It leaves only for an
  unblocked option at least a cent cheaper than the placement, priced at the
  lane's fastest receipt or, without one, at its floor alone. What the
  placement lacks is a measurement request at its lane, with the lane's name
  and concurrency. An identity that stays keeps its lane as it is, envelope
  included, capped by the reviewed ceiling.
- An identity that declares no warm bound has no bound to choose a class by:
  cells outside its current class are blocked by the undeclared bound, which
  the report lists, and an identity without a current lane is not placed.
- lazy-resident is selectable on a warm lane of the current plan, on the
  identity's queue pool and bundle, that a never-cold identity pins, when
  the identity has a receipt at that lane and a load onto its cell and
  container shape. Its come-alive is the load and its cost the demand above
  the host's floor. A missing load is a measurement request on that lane.
- A warmth's come-alive is the 95th percentile by nearest rank of its
  successful boots from 20 boots, and their slowest below that.

Kept identities now report the nearest cheaper option and price their
measurement requests against the current placement, and come-alive levers
include lazy-resident.
A lazy resident's option was hosted by any lane of the current plan on
which a never-cold identity was pinned, even when that identity moved
in the same run. The resident then sat alone on a warm-floor lane while
its option claimed to cost nothing beyond a floor nobody else paid.

Identities whose comeAliveP95S is 0 are now placed first, since no cold
or lazy option can meet that bound, and a lane hosts lazy residents only
when one of them stays pinned on it in this run. A resident's own lazy
lane without such a neighbour stays an option, priced at the lane's
floor as well.

A boot or load at the current lane that did not succeed now blocks the
current placement instead of holding it as unmeasured, and a current
placement kept on a lane the price list cannot price reports
current-unpriced rather than current-unmeasured.
@krisztian-gajdar

Copy link
Copy Markdown
Contributor Author

Adversarial review run 4 (agent-generated, independent of the authoring session)

  • Reviewer. A fresh Claude Code general-purpose subagent, different from the agents of runs 1 to 3. It started without the authoring session's context, with no fork, and with read-only instructions, working in a throwaway partial clone. This is run 4, on 2026-11-06/07. CodeRabbit had approved the reviewed head. The reviewer was given the reports and dispositions of runs 1 to 3 and the deferral list on Measured-only placement planner for worker pools (sie_placement) #903.
  • Reviewed head. d37c1ba75d7ea063dd0546cacec0deb273185baa. The range is origin/feat/sie-placement-applier-hardening...d37c1ba75d7ea063dd0546cacec0deb273185baa, the whole PR diff.
  • Full prompt, verbatim. feat(placement): add the sie_placement planner, tuner and cluster appliers #914 (comment)
  • Scope limits imposed by the author. None.
  • Verdict. No blocking findings. One finding is non-blocking. The unedited report follows. The author's dispositions are in the next comment.

Agent-generated adversarial security review (independent reviewer).

Reviewed head: d37c1ba
Reviewed range: origin/feat/sie-placement-applier-hardening...d37c1ba75d7ea063dd0546cacec0deb273185baa. The merge base is the base tip, 6b5b71a. The range has 9 commits and touches 8 files. Since run 3's head (18e5688), only pools.py, the package README and test_cli.py changed (git diff 18e5688 d37c1ba --stat). The chart and the render tests are unchanged since run 3.

What I read: the whole diff. In full: pools.py, the new and changed tests in test_cli.py, secretKeyRef, wiredSecretKeys, validateTokenSeparation and grafanaAdminSecretName in _helpers.tpl, NOTES.txt, the chart README credential section, and the package README TLS paragraph. I also read the vendored Grafana 8.8.2 templates in kube-prometheus-stack 67.11.0 that read admin.existingSecret (_pod.tpl, deployment.yaml, secret.yaml, _config.tpl), the #913 run 2 report, this PR's run 1 to 3 reports and dispositions, the #903 deferral comment, and the CodeRabbit thread on 50d702a.

How the probes ran: in a throwaway partial clone and separate temporary probe directories, using helm template, kubectl --local, kubectl kustomize and HTTPS servers on 127.0.0.1. Nothing touched a cluster, gateway or Prometheus. The clone, the base worktree and all probe files were deleted afterwards.

Probe environment: macOS, non-root user. Python 3.12.12 (OpenSSL 3.5.4), 3.13.7 and 3.14.5 (OpenSSL 3.6.2). httpx 0.28.1, certifi 2026.4.22. Helm 3.16.4 (Go 1.22.7; the binary links sigs.k8s.io/yaml v1.4.0 and apimachinery v0.31.3). kubectl 1.34.1 (sigs.k8s.io/yaml v1.6.0, go.yaml.in/yaml/v2 v2.4.2, kustomize v5.7.1). Certificates were made with the OpenSSL 4.1.0 CLI.

Earlier findings this PR claims to fix

#913 review run 2

1. The unquoted-scalar check missed forms: resolved.

  • _helpers.tpl:1240-1247 uses the fromYaml (printf "k: %s" v) oracle.
  • I copied the head secretKeyRef define verbatim into a probe chart, with fail turned into a marker. I ran it on 25,182 strings that pass the data-key character set; 4,267 of them also pass the name set. They cover:
    • every letter case of y/n/yes/no/on/off/true/false/null/nil/none/inf/nan/infinity, with ., -., +., -, _ and 0 prefixes and _, ., 0 and - suffixes
    • signed integers and floats, _ in several positions, exponents (including e_3 and e1000), and leading or trailing dots
    • int64 and uint64 overflows
    • 0b/0o/0x prefixes in both cases, with signs, _ and negative bodies
    • date and sexagesimal-like forms
    • strings starting with -, . or a digit
    • every string of length 1 to 3 over 15 characters, and length 4 over 9 characters
  • The chart accepted 3,984 names and 23,332 keys.
  • I wrote every string unquoted as name: and key: at Grafana's secretKeyRef position and read the manifest with kubectl. The chart's verdict and kubectl disagree on 0 strings, in either direction.
  • 10 strings fail kubectl's parse: - and the .inf/.nan forms. The chart refuses all 10.
  • Examples:
    • Refused: 0b-1 (kubectl reads -1), 08 (8), 1e_3 (1000), -_1, 0_x1, 0x_1f and y.
    • Accepted, and read back as the same string: 0b12, 0bb, yEs, tRue, .1_, -.NaN, 1e1000, 190.20.30.15 and 2001-12-14.

2. The scalar tests never reached the check: resolved.

  • I reran the render suite with a plugin that recorded every values_json input: 927 calls, 664 distinct objects.
  • I rendered all 664 objects through an echo chart twice: once as values_json writes them and once as yaml.safe_dump would.
    • With JSON, Helm reads all 664 exactly as the Python values.
    • With PyYAML, 9 objects would differ: the eight scalar cases (1e3, 0b-1, 0b-10, -.5, y, 1e_3, -_1, 0_x1) and the echo test's own 1e3/y keys.
  • The switch therefore changes the meaning of no other test. No safe_dump remains in the module.

3. The TLS context was looser than httpx's on Python 3.13+: resolved. See pools.py:69-70.

  • I compared the applier context with httpx.create_ssl_context() on 3.12, 3.13 and 3.14, with no CA variable, with SSL_CERT_FILE and with SSL_CERT_DIR.
  • They are equal in verify_mode, check_hostname, minimum and maximum version, verify_flags, options, security_level, post_handshake_auth, hostname_checks_common_name, protocol, num_tickets, the cipher list and the CA store statistics.
  • In the handshake matrix below, the verify flags also matched in every case on 3.13 and 3.14.

4. The CA directory check and the default-bundle message: resolved.

  • On all three interpreters, these are refused at start: a directory holding only a subdirectory, only a dangling link, or nothing.
  • test_a_default_ca_bundle_that_cannot_be_loaded_is_refused_by_its_path passes for both an https and an http gateway.
  • The pre-existing residual is Finding 1.

5. The allowlist was undocumented and refused whitespace: resolved.

  • The allowlist is documented at chart README.md:1836-1847 and values.yaml:2115-2119.
  • Tab and CRLF inside actions render, and so do trailing CR, LF and blank lines (probe below).

6. NOTES evaluated the template in the wrong context: resolved. See _helpers.tpl:179-191.

  • In 37 of the 39 Grafana forms that render, NOTES names the Secret that Grafana's Deployment reads.
  • The other 2 are a leading or a trailing NBSP from a .Values field (see deferred item 3).

This PR, run 1

1. A CA directory was refused depending on entry order: resolved.

  • _is_file (pools.py:39-43) catches OSError for each entry.
  • test_a_ca_directory_entry_that_cannot_be_inspected_does_not_hide_a_certificate_file passes.

2. The refusal printed the template's expansion: resolved.

  • {{ .Values.YAML }} with a sentinel adminPassword: the sentinel is absent from stderr.
  • .Values fields holding 123, "true" or 0b-1 are refused with "the value of "{{ .Values.x }}" (not shown...)".

3. NOTES evaluated admin.existingSecret when Grafana does not: resolved.

  • The guard at _helpers.tpl:183 is Grafana's own GF_SECURITY_ADMIN_PASSWORD condition (_pod.tpl:1106).
  • With only GF_SECURITY_ADMIN_USER set in another namespace, the line is kept and names graf, which Grafana still reads.
  • The three env tests pass.

4. Three helpers still wrote values with PyYAML: resolved. Every writer uses values_json.

This PR, run 2

1. ruff format --check tools/ci failed: resolved. ruff reports 55 files already formatted.

2. A valid execute-only CA directory was refused at start: resolved.

  • A mode-0311 directory holding hashed CA A passes start-up and verifies the A-signed server on all three interpreters, as httpx does.
  • This holds when it is named directly, through a symlink, or with a trailing /.

3. values_json was not faithful for some characters: resolved. The probe test passes, and the capture above shows 0 differences.

4. YAML 1.2 post-renderers (declined, then deferred): justified.

  • I passed every value the chart accepts through kubectl kustomize.
  • It rewrote 6 of the 3,984 accepted names and 7 of the 23,332 accepted keys:
    • 0o-0, 0o-1, 0o-10 and 0o-_1 became numbers
    • 2001-1-1, 2001-12-1 and 2001-12-14 became ...T00:00:00Z strings
  • None became another valid Secret name or data key.

This PR, run 3

1. _holds_files accepted locations that cannot supply any CA: resolved by 50d702a and d37c1ba.

  • With the real code on 3.12, 3.13 and 3.14, these are now refused at start:
    • a mode-0000 directory
    • an existing directory, and a missing path, below a mode-0600 parent
    • a symlink to a mode-0000 directory
    • a symlink to a directory below the unsearchable parent
    • a regular file, and an execute-only (0111) file, which scandir reports as NotADirectoryError, not PermissionError
  • Accepted: a mode-0311 directory with the CA, direct, through a link or with a trailing slash. It verifies.
  • An empty mode-0311 directory is accepted and then fails every call, as httpx's default client does.
  • Effective ids:
    • os.access in os.supports_effective_ids is True on the probe platform.
    • The real os.access(..., effective_ids=True) returned True for 0311 and False for 0000.
    • test_a_ca_directory_the_applier_cannot_list_is_checked_with_its_effective_ids passes.
  • The PermissionError branch therefore accepts a location exactly when the applier's effective ids can search it, which is what OpenSSL needs to open certificates there by name. The listing branch does not check search permission (Finding 1).

Accepted and deferred items (#903 comment 6697495550)

  1. wiredSecretKeys evaluates the template before Grafana's env conditions. Deferral justified. In that configuration Grafana reads no admin Secret, so the extra evaluation can only refuse a render, never let two credentials share a key.
  2. YAML 1.2 post-renderers. Deferral justified; see run 2, item 4 above.
  3. Leading NBSP or U+3000. Deferral justified, and it also covers a trailing NBSP.
    • Grafana writes sie-graf or sie-graf , which is not a valid Secret name.
    • The check and NOTES use the trimmed sie-graf.
    • All four holders set to Grafana's reference are refused.
    • So this causes extra refusals only.

Abuse cases considered

Oracle against the applier's reader

  • Helm's fromYaml and its manifest decoding run the same sigs.k8s.io/yaml v1.4.0 (yaml.v2 resolution) in the same binary. kubectl 1.34.1 agreed on all 25,182 strings.
  • A typed reader would turn a YAML number into a different string, for example 1e3 into "1000". The oracle refuses every value YAML reads as a non-string, so that conversion never applies to an accepted value.

Short-circuiting

  • {{ or (not (kindIs "string" $r.k)) (ne $r.k "1.5") }} with k: 1.5 renders true on Helm 3.16.4.
  • {{ ne 1.5 "x" }} fails with "incompatible types for comparison", so a mismatch would fail closed.
  • fromYaml sets Error for k: .inf and k: -.

Structure injection into k: <value>

  • The character-set checks run first and fail aborts the render, so only [-._a-zA-Z0-9] reaches the oracle.
  • --- and ... are read as strings (kubectl agrees).
  • A lone - is an Error.

Grafana allowlist end to end: 58 forms

  • Forms tried:
    • tab and CRLF inside actions; {{-/-}} with spaces, tabs and eaten newlines; $ and $ with trim markers; no spaces
    • leading LF or CRLF at shallow and deep indentation; leading tab; trailing LF, CR, blank lines, and space plus tab
    • two actions in one value
    • .Release.Name, .Namespace, .Revision and .IsInstall; .Chart.Name, .Version and .IsRoot
    • .Values.admin.userKey, fullnameOverride, a missing key and a missing nested key
    • .Values fields holding a leading LF (deep and shallow), leading spaces, a trailing LS or NEL, a leading NEL, a leading or trailing NBSP, VT, FF, \n---\nkind: Secret, an injected key: line, #c, a number, "true", 0b12, 0b-1 and template text
    • a self-reference, .Values.YAML, .Values.AsMap, an internal newline, a trimmed comment, a pipeline, literals and empty
  • 39 forms render.
    • In every one, all 8 Grafana references (GF_SECURITY_ADMIN_USER/PASSWORD and REQ_USERNAME/REQ_PASSWORD in the three sidecars, read with kubectl) name one Secret.
    • For each form I set each of four holders to Grafana's password reference: the applier client token, the MCP edge cluster API key, gateway.auth.tokenSecretName and the worker token. All 156 renders were refused as the same Secret key.
  • 19 forms fail:
    • 5 with a YAML parse error of Grafana's Deployment (leading LF at shallow indentation, from a literal or a field; leading NEL; VT; FF)
    • 1 with a tpl execution error (missing nested key)
    • 13 at the chart's own allowlist, name or oracle checks
  • No form changed the structure of Grafana's manifest while the check passed.
  • .Subcharts.grafana is the values map Grafana's own templates render with: .Chart.Name gives grafana-admin and .Chart.IsRoot gives false in both places. merge adds only .Template, which the allowlist excludes.

NOTES

  • With the subcharts off, or with Grafana disabled, NOTES renders with no Grafana line.
  • With Grafana in another namespace, an include "grafana.fullname" form names sie-grafana-admin, which matches Grafana.
  • A .Template.Name form differs. That is display only, and the allowlist does not apply in another namespace, as runs 1 and 3 noted.
  • A custom passwordKey matches.
  • NOTES prints the evaluated name by design. That is the Secret Grafana's own Deployment names, so it discloses nothing the manifest does not.

TLS against servers on 127.0.0.1: 555 cases

  • Servers: an A-signed leaf, a B-signed leaf, a leaf without an Authority Key Identifier, and an intermediate-issued leaf sent with and without its chain.
  • 37 CA settings:
    • SSL_CERT_FILE holding A, B, the intermediate, or a missing file; an empty SSL_CERT_FILE with a directory; both variables set
    • SSL_CERT_DIR with hashed names, hash links, a link to the directory, the intermediate, an unhashed file, only a subdirectory, only a dangling link, an empty directory
    • the 0311, 0000, 0600-listable, below-0600-parent (existing and missing), link and file cases above, an unreadable hashed file, a missing directory, and :
    • lists mixing these with a usable directory
    • neither variable (certifi)
  • Interpreters: 3.12 with the real pools.connect and get_pool sending a token; 3.13 and 3.14 with _verification extracted from head.
  • Wherever the applier builds a context, its outcome equals that of httpx's default client in the same environment.
  • In the 13 settings the applier refuses at start, httpx's default client also fails or verifies nothing.
  • No request reached a server whose handshake failed for the applier. No error message contained the token.
  • Nothing falls back to certifi or the system store. For example, with m000A:hashedB only B verifies.

Error messages

  • The only new text is the certifi path.
  • Chart name errors show the template, not its value.
  • Separation errors print name/key only when it equals another reference.

Test evidence

  • mise trust, mise install and mise run helm -- dependencies: succeeded (Helm v3.16.4).
  • mise exec -- uv run --frozen --package sie-placement --extra keda pytest packages/sie_placement/tests -q -p no:cacheprovider: 1601 passed, 1 warning (unknown pytest option asyncio_mode), 12.2 s.
  • mise exec -- uv run --frozen pytest tools/ci/tests/test_helm_render.py -q -p no:cacheprovider: 708 passed in 133 s. A second run with the capture plugin: 708 passed in 136 s.
  • mise exec -- uv run --frozen --project . --no-sync ruff format --check tools/ci: 55 files already formatted (ruff 0.15.12).
  • mise exec -- uv run --frozen --project . --no-sync ruff check --select E,F,I,UP,B tools/ci: all checks passed.
  • ruff format --check and ruff check on packages/sie_placement: passed.
  • mise run helm -- lint: passed.
  • I did not run CI's separate tools/ci pytest step, which needs the full workspace sync; the prompt did not require it.
  • Byte identity, base 6b5b71a against head: 24 value sets with --set payloadStore.enabled=false:
    • defaults; the aws, gke, ha, ack and aks overlays
    • kube-prometheus-stack alone; with admin/SMTP/LDAP Secrets; with .Release, .Values and tab templates; with Grafana in another namespace; with env passwords
    • KEDA alone and with cert-manager; Loki; cert-manager with trust-manager; all subcharts
    • the applier with token auth and a client token, alone and with all subcharts
    • Every set that renders at both base and head differs by exactly the 10 or 12 lines that differ between two head renders: SIE_ADMIN_TOKEN, SIE_CONFIG_READ_TOKEN and the NATS password.
  • Compatibility (from the 25,182-string probe, comparing base and head defines):
    • Rendered at base, refused at head:
      • 3 names: 0b-0, 0b-1 and 0b-10
      • 673 keys, such as -, -_1 and 1e_3
      • kubectl reads all of them as non-strings or fails to parse them, so applying them would have failed anyway
    • Refused at base, renders at head:
      • 67 names, such as 0b12 and 08e1000, and 328 keys, such as yEs and -.1e1000; kubectl reads all of them as themselves
      • Grafana templates with tabs, CR or LF
      • {{ .Values.admin.userKey }}-x, which failed at base in NOTES.txt with a nil pointer
    • Applier start-up:
      • Now refused: directories holding only subdirectories or dangling links.
      • Now accepted: execute-only directories.

Findings

1. Non-blocking (pre-existing, fails closed): a CA directory the applier can list but not search passes start-up.

Where: packages/sie_placement/src/sie_placement/pools.py:46-53, and the package README.md:399-405.

Cause:

  • Search permission is checked only in the PermissionError branch.
  • When scandir succeeds, DirEntry.is_file() answers from the directory entry's type without a stat for a regular file. It therefore reports files that OpenSSL cannot open by name, because opening a file needs search permission on the directory.

Failure scenario:

  • SSL_CERT_DIR names a mode-0600 (or 0400) directory holding the hashed CA.
  • _holds_files returns True and start-up passes.
  • Every gateway call then fails with CERTIFICATE_VERIFY_FAILED on 3.12, 3.13 and 3.14, exactly as httpx's default client does. No request reaches the server.
  • Base _holds_entries also accepted this directory.

Impact: diagnosis only. This is the listable counterpart of run 3's unsearchable-location finding. Verification is not weakened, and no token can reach another host. The README sentence "a directory whose files it cannot use fails each gateway call" already covers the behaviour.

Suggested fix: refuse any location that fails os.access(path, os.X_OK, effective_ids=_ACCESS_BY_EFFECTIVE_IDS) before scanning it, and keep returning True on PermissionError from scandir. Alternatively, accept the behaviour as documented.

Verdict

No blocking findings

@krisztian-gajdar

Copy link
Copy Markdown
Contributor Author

Author's dispositions of adversarial review run 4

Run 4 reported no blocking findings (report) and confirmed that every earlier finding is resolved or justifiably declined or deferred. Its one finding is non-blocking and pre-existing, and it is accepted and deferred. Nothing changes in this PR, so it stays at the reviewed head, d37c1ba75d7ea063dd0546cacec0deb273185baa, which run 4's report covers.

# Finding Disposition
1 A CA directory the applier can list but not search, such as mode 0600 or 0400, passes start-up and then fails every call Accepted and deferred. This is pre-existing: base _holds_entries accepted the same directory. It fails closed: every call fails with CERTIFICATE_VERIFY_FAILED, as with httpx's default client, verification is not weakened, and no request reaches the server. The package README already covers it ("a directory whose files it cannot use fails each gateway call with the TLS error"). It is neither a regression from this PR nor a credential exposure. The suggested fix, an os.access(..., X_OK) check before scanning, is item 4 on #903.

Review record for this PR

Run Head Prompt Report Dispositions
1 b32000b prompt report, no blocking fixed 4
2 6a8ba70 prompt report, no blocking fixed 3, declined 1
3 (attempt 1) 18e5688 prompt none: the reviewer stopped before reporting
3 (attempt 2) 18e5688 prompt report, no blocking fixed 1 (a regression from b46e6af), deferred 3
4 d37c1ba prompt report, no blocking this comment: deferred 1

Between runs 3 and 4, CodeRabbit raised one finding on 50d702a: check search permission with the effective IDs. It was fixed in d37c1ba, and the thread is resolved. CodeRabbit approved d37c1ba before run 4 started. Its only remaining note is the advisory docstring-coverage pre-merge check, declined because the touched private helpers and test helpers follow the modules' no-docstring style.

Deferred items, all non-blocking and fail-closed, are listed on #903: #903 (comment), with item 4 added in a follow-up comment there.

@krisztian-gajdar
krisztian-gajdar changed the base branch from feat/sie-placement-applier-hardening to main November 9, 2026 16:59
@krisztian-gajdar
krisztian-gajdar dismissed coderabbitai[bot]’s stale review November 9, 2026 16:59

The base branch was changed.

@krisztian-gajdar

Copy link
Copy Markdown
Contributor Author

@coderabbitai approve

coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 9, 2026
@coderabbitai

coderabbitai Bot commented Nov 9, 2026

Copy link
Copy Markdown
Action performed

Comments resolved and changes approved.

@krisztian-gajdar
krisztian-gajdar added this pull request to the merge queue Nov 9, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Nov 9, 2026
@krisztian-gajdar krisztian-gajdar changed the title fix: read unquoted subchart Secret refs with Helm's YAML parser and keep the applier's TLS as strict as httpx feat(placement): add the sie_placement planner, tuner and cluster appliers Nov 9, 2026
@krisztian-gajdar

Copy link
Copy Markdown
Contributor Author

The only commit since the approved head d37c1ba is 40e7757, a merge of main after #904 landed. It keeps this branch's sie_placement files, which git diff d37c1ba 40e7757 -- packages/sie_placement shows unchanged, and regenerates uv.lock from main's lock (the only lock difference from main is this package's keda extra). CI / Required passes on 40e7757.

@krisztian-gajdar

Copy link
Copy Markdown
Contributor Author

@coderabbitai approve

@coderabbitai

coderabbitai Bot commented Nov 9, 2026

Copy link
Copy Markdown
Action performed

Comments resolved and changes approved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant