Skip to content

agent: k8s: coordinate kubelet pod list fetching - #7085

Merged
MarcosDY merged 6 commits into
spiffe:mainfrom
c4rlo:kubelet-requests
Aug 6, 2026
Merged

MarcosDY merged 6 commits into
spiffe:mainfrom
c4rlo:kubelet-requests

Conversation

@c4rlo

@c4rlo c4rlo commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Move kubelet pod-list fetching, caching and backoff timing into a long-lived fetcher that versions pod-list responses, instead of using the singleflight package.

This now enables us to cache successful kubelet responses until another request is eligible to start, which makes more sense. Previously, they were cached for half the polling interval, which could lead to the following situation (illustrated with the default polling interval of 500 ms):

  • T = 0 ms: Attestation request 1 makes pod-list request, finds no result, sleeps for 500 ms.
  • T = 300 ms: Attestation request 2 finds cache expired, makes pod-list request that contains an entry that request 1 was looking for.
  • T = 500 ms: Only now does request 1 wake up and find the desired entry in the cached pod list.

Fixing this with the singleflight approach would not have been easily possible, as it could cause retries to re-use the same cached pod list response as in the previous iteration.

The new approach also enforces a minimum interval between kubelet request start times across concurrent attestations. Unlike the previous fixed delay after each request, this allows the next request to start immediately when the previous one took longer than the configured interval.

In addition, several other improvements (that could also have been implemented with the old singleflight mechanism):

  • kubelet requests: do not cancel an inflight request just because its original caller is no longer interested, as other callers may be waiting for it. (With singleflight, this could have been fixed via the Group.DoChan method.)
  • kubelet requests: retry failed fetches via the same backoff mechanism, rather than immediately returning a failure response. Previously, it was only used when the pod list did not contain the workload.
  • kubelet requests: when reloading the client, whether through an explicit Configure() call or periodically via reload_interval, only create a fresh http.Transport object if necessary based on config or certificate changes, ensuring we do not trash its connection pool unnecessarily.
  • kubelet requests: treat an invalid items JSON type in the response as an error instead of empty.
  • kubelet requests: replace the attempt log value rather than appending a new one with each attempt.
  • kubelet requests: report kubelet and malformed-response failures as Unavailable instead of Internal. (Failure to find the workload in the pod list after attempts are exhausted continues to be DeadlineExceeded.)
  • kubelet requests: use net.JoinHostPort for endpoints, enabling IPv6 support.
  • kube API server requests: correctly reflect runtime changes to the api_server.cache.enabled setting via Configure().
  • Validate(): perform more thorough validation, including checking that kubelet certificates can be read and parsed.
  • gRPC return codes: preserve whether caller termination was cancellation or deadline expiry.
  • gRPC return codes: report failed Sigstore policy verification as PermissionDenied instead of Internal.
  • tests: fix a flaky, order-dependent Sigstore selector test failure caused by mutating shared expected selectors.
  • misc: small code cleanups.
  • docs: add missing descriptions of max_poll_attempts, poll_retry_interval, and reload_interval.
  • docs: assorted fixes.

Open questions:

  1. I appreciate that this is quite a lot of new code and complexity. Is it worth the gain, maybe counting only the improvements we could not get with the existing singleflight approach? I think so, as it is a more principled approach with more logical semantics, but it is probably debatable.
  2. If we go with this new approach, do we want to change the default value for the poll_retry_interval config setting? Currently it is 500 ms. But its meaning changes with this PR: it used to be the sleep time between retry attempts, with the cache TTL being set to half that value (250 ms); now it is the minimum interval between fetch start times for both new requests and retries, with the cache TTL also being the same. I would be tempted to reduce the default value now, perhaps to 250 ms, but I do not have a strong opinion either.

@c4rlo
c4rlo force-pushed the kubelet-requests branch from 5c6c329 to 3e1fb4b Compare June 21, 2026 09:47
@c4rlo
c4rlo marked this pull request as ready for review June 21, 2026 09:58
@c4rlo
c4rlo requested a review from evan2645 as a code owner June 21, 2026 09:58
Copilot AI review requested due to automatic review settings June 21, 2026 09:58

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the Kubernetes workload attestor’s kubelet pod-list polling to use a long-lived “pod list fetcher” that coordinates concurrent callers, versions responses, caches successful results, and enforces a minimum interval between kubelet request start times (replacing the prior singleflight+TTL approach). It also extracts kubelet HTTP client construction into a dedicated component and updates related error handling, logging, and tests.

Changes:

  • Introduces podListFetcher to coordinate pod-list fetching (shared inflight requests, versioned cached results, backoff timing, client reload handling).
  • Extracts kubelet HTTP client creation/verification into kubeletclient.go and wires the plugin to configure/validate via the fetcher.
  • Updates attestation retry/error semantics and extends/adjusts unit tests accordingly.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
pkg/agent/plugin/workloadattestor/k8s/podlistfetcher.go New long-lived fetcher coordinating pod-list fetch/caching/backoff/versioning and kubelet client reloads
pkg/agent/plugin/workloadattestor/k8s/podlistfetcher_test.go New unit tests covering fetcher caching, sharing, timing, cancellation, reload, and parsing behavior
pkg/agent/plugin/workloadattestor/k8s/kubeletclient.go New kubelet client + transport-config comparison to preserve connection pools when possible
pkg/agent/plugin/workloadattestor/k8s/k8s.go Plugin updated to use the fetcher/client, revised retry flow and error codes, validate/configure integration
pkg/agent/plugin/workloadattestor/k8s/k8s_test.go Test updates/additions to match new retry/backoff semantics and validation behavior
pkg/agent/plugin/workloadattestor/k8s/k8s_posix.go Minor logging/spelling cleanup and small simplifications

}

func (f *podListFetcher) handleConfigResult(result podListConfigResult) {
f.config = new(result.config)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See #7086.

Comment on lines +322 to 329
if podListErr != nil {
if ctx.Err() != nil {
return nil, ctx.Err()
}
// Otherwise, we'll log podListErr below, and we may retry.
} else {
podListVersion = podListResult.version
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be unlikely to happen, but I've addressed it now.

@c4rlo
c4rlo force-pushed the kubelet-requests branch 2 times, most recently from 28118c6 to 5d15fc3 Compare June 21, 2026 22:12
@matheuscscp

Copy link
Copy Markdown
Contributor

Please hold this PR. The Broker API PR is changing many things in the k8s plugin, this PR should come on top of it.

@c4rlo
c4rlo force-pushed the kubelet-requests branch from 5d15fc3 to 180ffa6 Compare June 23, 2026 20:53
@c4rlo c4rlo mentioned this pull request Jun 28, 2026
3 tasks done
@matheuscscp

Copy link
Copy Markdown
Contributor

Hey @c4rlo, the Broker API is merged, pls rebase 🙏

@c4rlo
c4rlo force-pushed the kubelet-requests branch from 180ffa6 to d7d73f1 Compare July 4, 2026 09:06
@c4rlo

c4rlo commented Jul 4, 2026

Copy link
Copy Markdown
Contributor Author

Rebased, and included a few more small improvements; commit message & PR description updated accordingly.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Comment on lines +184 to +193
func (f *podListFetcher) registerFetchRequest(afterVersion uint64, resultCh chan<- podListFetchResult) {
if f.cachedPodList.pods != nil && afterVersion < f.cachedPodList.version &&
f.clock.Now().Before(f.cachedFetchStart.Add(f.config.pollRetryInterval)) {
resultCh <- podListFetchResult{versionedPodList: f.cachedPodList}
return
}

f.fetchWaiters[resultCh] = struct{}{}
f.scheduleFetch()
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't happen since Configure() gets called before any Attest() calls afaik, but still good to defend against this, hence addressed in cbf4385.

Comment on lines +373 to +380
for _, podValue := range items {
uid := string(podValue.Get("metadata", "uid").GetStringBytes())
if uid == "" {
f.log.Warn("Pod has no UID", "pod", podValue)
continue
}
result[uid] = podValue
}

@c4rlo c4rlo Jul 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@matheuscscp

Copy link
Copy Markdown
Contributor

Hey @c4rlo #7094 merged and introduced some conflicts, sorry about that, can you pls rebase again? 🙏

@sorindumitru We should try to review this one soon so @c4rlo doesn't have to keep solving conflicts 🙏

@c4rlo
c4rlo force-pushed the kubelet-requests branch from cbf4385 to e9e3863 Compare July 17, 2026 20:21
@c4rlo

c4rlo commented Jul 17, 2026

Copy link
Copy Markdown
Contributor Author

Rebased again.

@c4rlo
c4rlo force-pushed the kubelet-requests branch from e9e3863 to 9dd4834 Compare July 21, 2026 21:13
@c4rlo

c4rlo commented Jul 21, 2026

Copy link
Copy Markdown
Contributor Author

Rebased again.

@MarcosDY MarcosDY left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Open questions:

  1. I appreciate that this is quite a lot of new code and complexity. Is it worth the gain, maybe counting only the improvements we could not get with the existing singleflight approach? I think so, as it is a more principled approach with more logical semantics, but it is probably debatable.

The versioned-pod-list core is worth it; it fixes a real bug that singleflight structurally cannot. However, the PR bundles ~10 unrelated improvements (IPv6 JoinHostPort, Validate hardening, gRPC code changes, doc fixes, strconv.Itoa → %d, isValidCGroupPathMatches simplification, the flaky-test fix).
That increment the complexity of reviewing and things we need to verify.
However good work :D

  1. If we go with this new approach, do we want to change the default value for the poll_retry_interval config setting? Currently it is 500 ms. But its meaning changes with this PR: it used to be the sleep time between retry attempts, with the cache TTL being set to half that value (250 ms); now it is the minimum interval between fetch start times for both new requests and retries, with the cache TTL also being the same. I would be tempted to reduce the default value now, perhaps to 250 ms, but I do not have a strong opinion either.

Yeap, semantic changed, so we need to change the default, 500ms is going to go against your changes.
250ms preserves the current cache freshness, another option is to decouple them: a separate cache TTL from the rate limit would be clearer than overloading one knob, but that's more config surface...

// can match pod-specific fields like container images and service accounts
// that aren't present on a PartialObjectMetadata.
func (p *Plugin) attestByPodReference(ctx context.Context, brokerEntry *k8sBrokerEntry, objRef *broker.KubernetesObjectReference) (*attestReferenceResult, error) {
config, _, _, err := p.getConfig()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

get config can return return nil, nil, nil, status.Error(codes.FailedPrecondition, "not configured") thi s internal can cause backcompat since we are expecting another error in that case
can you revert return the returned error instead? (plz verify if there are more cases like this)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apologies, this was an unintentional change. Undone.

clock: pluginClock,
getenv: os.Getenv,
}
p.podListFetcher = newPodListFetcher(pluginClock, p.rootDir)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it is not a bug "now" but we are creating fetcher on new, no in configure,
in a possible scenario we allow rootDIr to be configurable, fetcher is not going to get the updated value

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't really see a reason why we'd ever want to change rootDir at runtime. Hence I'd prefer to keep this unchanged for simplicity.

_, notes, err := pluginconf.Build(req, p.buildConfig)
newConfig, notes, err := pluginconf.Build(req, p.buildConfig)
if err == nil && !newConfig.DisableKubeletClient {
err = p.podListFetcher.validate(newConfig.podListFetcherConfig)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks to me like validate no longer only validates but can performs disk I/O and can mutate fetcher state.
am i right?
so 2 topics here:

  • Validate now reads CA/token/cert files from disk. For spire-agent validate run outside a pod, /var/run/secrets/kubernetes.io/serviceaccount/token does not exist, so a config that is perfectly valid for the runtime environment will report Valid: false. This is a behavior change for the CLI validate path that isn't mentioned in the PR description. Is that intended?
  • Validate reads f.buildClient — a field owned by the run goroutine per the struct comment. In production nothing else writes it, but it breaks the stated ownership invariant, and the tests do reassign fetcher.buildClient from the test goroutine. May we make validate a free function over podListFetcherConfig + rootDir so it never touches fetcher state.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To your first point: I had assumed that Plugin.Validate() is something that would only be called on a real running agent, i.e. where it would be expected to have access to all its key material. However, on reflection one could imagine it also getting called in other scenarios. It looks like spire-agent validate does not actually call it, however spire-server validate does and so in future it seems quite possible spire-agent validate may also. And in that context one would probably expect validation to not require the key material to be in the configured locations.

Moreover, it looks like other plugins also don't do this kind of thing.

I've therefore changed it to not attempt to load any key material and only validate the config in the more usual less-thorough way.

}

func (p *Plugin) Close() error {
p.podListFetcher.close()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this may panic if we call twice, may we run int inside a sync.Once?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done as defence-in-depth.

}
// Otherwise, we'll log podListErr below, and we may retry.
} else {
podListVersion = podList.version

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a guaranty of that podList is not nil after an error?
when error podList is the zero versionedPodList, so podList.pods is nil and ranging is a no-op.
So it depends on fetchNext always returning the zero value on error.
Worth an explicit continue-style guard or at least a comment, since a future change returning a partial list would silently attest against stale data.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've expanded the comment to hopefully clarify it. I wanted to avoid making the loop conditional because that would add another level of indentation there, or cause other code complications.

case attempt >= config.MaxPollAttempts:
if podListErr != nil {
log.Warn("Unable to get pod list; giving up", telemetry.Error, podListErr)
return nil, status.Error(codes.Unavailable, podListErr.Error())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this catching context cancelation? (we used to return no selector found in that case)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes: see the error handling just after fetchNext above.

if ctx.Err() != nil {
return nil, ctx.Err()
}
return nil, status.Errorf(codes.PermissionDenied, "error verifying sigstore image signature for imageID %s: %v", containerStatus.ImageID, err)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

QQ: why to update the error code? can the change cause a regresion?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I though it would be a little more correct, but it's probably debatable since the error could signify various different things. I've therefore undone this change to be conservative.

| `use_anonymous_authentication` | If true, use anonymous authentication for kubelet communication. |
| `node_name_env` | The environment variable used to obtain the node name for kubelet requests. Defaults to `MY_NODE_NAME`. |
| `node_name` | The node name used for kubelet requests. Overrides the value obtained from the env var specified by `node_name_env`. |
| `max_poll_attempts` | The maximum number of kubelet polling attempts while locating the workload container/pod. Defaults to `60`. |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously max_poll_attempts counted "pod not yet found" polls, and a kubelet error returned immediately. Now kubelet errors consume attempts too.
But the interaction is worth flagging: with the default 60 × 500ms, a kubelet that's down for 30s will now hold an attestation request open for the full 30s instead of failing fast.
That's a behavior change for the "kubelet is genuinely broken" case, and it multiplies across concurrent workloads.
I think we need to mention that behavior or try to catch kubelet unrecoverable errors)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that is an intentional change; I feel it makes more sense to keep trying both if the pod isn't in the list, and if we couldn't talk to the kubelet.

In principle it would be nice if we could tell whether a kubelet error was recoverable or not. But I don't think we can:

  • Connection failure? Maybe temporary network glitch.
  • Authentication failure? Maybe our token expired but it's about to be renewed (via the ReloadInterval timer of due to a Configure() call).
  • Internal Server Error? Maybe someone broke Kubernetes but is already close to unbreaking it.

So given we have the retry loop, doesn't it make sense to use it for any such errors, for as long as the client's context isn't cancelled?

I'll admit this is a noteworthy change in behaviour and should perhaps be called out in the release notes...

@c4rlo

c4rlo commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author
  1. If we go with this new approach, do we want to change the default value for the poll_retry_interval config setting? Currently it is 500 ms. But its meaning changes with this PR: it used to be the sleep time between retry attempts, with the cache TTL being set to half that value (250 ms); now it is the minimum interval between fetch start times for both new requests and retries, with the cache TTL also being the same. I would be tempted to reduce the default value now, perhaps to 250 ms, but I do not have a strong opinion either.

Yeap, semantic changed, so we need to change the default, 500ms is going to go against your changes. 250ms preserves the current cache freshness, another option is to decouple them: a separate cache TTL from the rate limit would be clearer than overloading one knob, but that's more config surface...

I don't think the behaviour has changed that much that we completely need new config settings for this.

On reflection, perhaps it would be best to leave the default poll interval at 500 ms in order to minimise user-observable changes:

  • Keeping 500 ms means:
    • (Unchanged-ish) Requests keep waiting 500 ms between retries when pod isn't in the list (still a change here in that the 500 ms is now a minimum duration between request start times, which is less pessimistic). They will make up to 60 attempts, for a total of at least 30 sec.
    • (Changed) But requests may now be served from a cache that is allowed to be up to 500 ms stale, rather than 250 ms (though again the 500 ms is now measured from the request start time).
  • Changing to 250 ms would mean:
    • (Changed): Requests now wait for only 250 ms between retries when pod isn't in the list. Total attempt time is at least 15 sec.
    • (Unchanged) Requests are served from a cache that is allowed to be up to 250 ms stale.

I feel like the first option is the more minimal one and hence preferable.

If we want to tune behaviour further, that can wait for another PR.

c4rlo added 6 commits August 3, 2026 21:44
Move kubelet pod-list fetching, caching and backoff timing into a
long-lived fetcher that versions pod-list responses, instead of using
the singleflight package.

This now enables us to cache successful kubelet responses until another
request is eligible to start, which makes more sense. Previously, they
were cached for _half_ the polling interval, which could lead to the
following situation (illustrated with the default polling interval of
500 ms):

- T = 0 ms: Attestation request 1 makes pod-list request, finds no
  result, sleeps for 500 ms.
- T = 300 ms: Attestation request 2 finds cache expired, makes pod-list
  request that contains an entry that request 1 was looking for.
- T = 500 ms: Only now does request 1 wake up and find the desired entry
  in the cached pod list.

Fixing this with the singleflight approach would not have been easily
possible, as it could cause retries to re-use the same cached pod list
response as in the previous iteration.

The new approach also enforces a minimum interval between kubelet
request _start times_ across concurrent attestations. Unlike the
previous fixed delay after each request, this allows the next request to
start immediately when the previous one took longer than the configured
interval.

In addition, several other improvements (that could also have been
implemented with the old singleflight mechanism):

- kubelet requests: do not cancel an inflight request just because its
  _original_ caller is no longer interested, as other callers may be
  waiting for it. (With singleflight, this could have been fixed via the
  Group.DoChan method.)
- kubelet requests: retry failed fetches via the same backoff mechanism,
  rather than immediately returning a failure response. Previously, it
  was only used when the pod list did not contain the workload.
- kubelet requests: when reloading the client (whether through explicit
  Configure call or periodically via reload_interval), only create a
  fresh http.Transport object if necessary based on config/certificate
  changes, ensuring we don't trash its connection pool unnecessarily.
- kubelet requests: treat invalid "items" JSON type in reponse as error
  instead of empty.
- kubelet requests: replace "attempt" log value rather than appending a
  new one with each attempt.
- kubelet requests: report kubelet and malformed-response failures as
  Unavailable instead of Internal. (Failure to find the workload in the
  pod list after attempts exhausted continues to be DeadlineExceeded.)
- kubelet requests: use net.JoinHostPort for endpoints (enables IPv6
  support).
- kube API server requests: correctly reflect runtime changes to
  api_server.cache.enabled setting via Configure().
- Validate(): more thorough implementation that checks it can read and
  parse kubelet certificates, etc.
- gRPC return codes: preserve whether caller termination was
  cancellation or deadline expiry.
- gRPC return codes: report failed Sigstore policy verification as
  PermissionDenied instead of Internal.
- tests: fix a flakey (order-dependent) Sigstore selector test failure
  caused by mutating shared expected selectors.
- misc: small code cleanups.
- docs: add missing descriptions of max_poll_attempts,
  poll_retry_interval, reload_interval.
- docs: assorted fixes.

Signed-off-by: Carlo Teubner <[email protected]>
Signed-off-by: Carlo Teubner <[email protected]>
Signed-off-by: Carlo Teubner <[email protected]>
@c4rlo
c4rlo force-pushed the kubelet-requests branch from 96fc3b7 to fd4c7ba Compare August 3, 2026 20:45
@c4rlo

c4rlo commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

Btw, I've addressed all the comments via additional commits, per contribution guidelines. The original commit is unchanged except for a (conflict-free) rebase against main.

@c4rlo
c4rlo requested a review from MarcosDY August 3, 2026 20:45
@github-actions github-actions Bot assigned MarcosDY and unassigned c4rlo Aug 3, 2026
@MarcosDY
MarcosDY added this pull request to the merge queue Aug 6, 2026
@MarcosDY MarcosDY added this to the 1.15.3 milestone Aug 6, 2026
Merged via the queue into spiffe:main with commit 36c4469 Aug 6, 2026
54 checks passed
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.

4 participants