Skip to content

fix(agent): stop logging the startup watch-stream handoff as an ERROR (#700) - #712

Merged
bpalermo merged 2 commits into
mainfrom
fix/700-startup-watch-ctx
Sep 5, 2026
Merged

bpalermo merged 2 commits into
mainfrom
fix/700-startup-watch-ctx

Conversation

@bpalermo

@bpalermo bpalermo commented Sep 5, 2026

Copy link
Copy Markdown
Owner

Fixes #700.

Root cause

The cancelled context is the agent's own, and the cancellation is deliberate — it is the demand-scoped filter assert racing the very first watch stream's dial.

  1. registry/internal/registrar/registrar.go:282 — Initialize starts watchLoop immediately. The agent calls it from agent/internal/cmd/root.go:251, long before it knows which services this node depends on, so the first stream is opened unfiltered (filterServices == nil).
  2. Opening a server-streaming RPC blocks in the gRPC picker until the connection is READY, so that first WatchEndpoints call is still in flight across the whole dial + SPIRE mTLS handshake to the registrar. That is the ~0.6s window in the issue, right after resolved workload trust domain from SPIRE.
  3. Inside that window the xDS server's PreListen asserts the node's dependency set: agent/internal/xds/server/server.go:104 → AssertWatchFilter → SetServiceFilter → registrar.go:222 cancelStream(). nil → []string{...} is always a filter change on a clean start, so the in-flight dial's per-stream context is cancelled.
  4. The in-flight call returns code = Canceled. The established-stream path already classified exactly this case as benign (handleStreamError, "watch stream ended for filter re-assertion", Debug), but the pre-connection path did not — it fell straight through to the generic branch at the old registrar.go:463: ERROR, an aether.agent.registry.watch_errors count, and a 1s+jitter backoff before the filtered stream could even be attempted.

So: one ERROR per agent start, one wasted reconnect, and ~1s of avoidable delay before the demand-scoped snapshot arrives (#612's reconnect-doubling concern).

Fix

Classify the failure before cancelling the per-stream context — while the call is in flight, only SetServiceFilter or the parent context can have cancelled it, never the loop itself:

  • parent context done → shutting down, return quietly (this also removes a spurious ERROR on every agent shutdown, which took the same branch);
  • per-stream context cancelled with codes.Canceled → a filter re-assert superseded the dial. Log at INFO with a startup marker (true for the process's first stream) and reconnect immediately — the backoff only delayed the filtered snapshot.

Real stream-open failures keep ERROR, the watch_errors metric and the exponential backoff, unchanged.

What an operator now sees

On a clean start, in place of the ERROR:

INFO registrar-registry watch stream superseded by a service-filter change before it connected; reconnecting startup=true

(startup=false if the same handoff ever happens mid-life, on a dependency-set change.) Nothing at all on shutdown. A registrar that genuinely will not serve the stream still logs the original ERROR line.

Validation

  • New registry/internal/registrar/watch_startup_test.go: an in-process registrar (bufconn) with a gated dialer makes the race deterministic — the first WatchEndpoints is provably blocked in the picker when SetServiceFilter lands — mirroring the agent's real sequence (Initialize → filter assert → WaitReady). It captures all records through a slog JSON handler into a buffer and asserts zero "level":"ERROR", the INFO supersede line with startup=true, and that the reconnect carried the new filter (filter.services == ["default/svc-a"]) with the superseded stream never reaching the server. A second test asserts a clean shutdown logs no ERROR.
  • Verified the test fails without the production change, with the issue's exact line:
    ERROR failed to start watch stream, retrying error="rpc error: code = Canceled desc = context canceled while waiting for connections to become ready" backoff=1018846651
  • bazel test --test_arg=-test.short //registry/... //agent/... → 39/39 pass; registrar_test also green at --runs_per_test=3.
  • make gazelle, make format-check clean.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

…#700)

A freshly started agent logged exactly one ERROR on an otherwise clean
startup:

  registrar/registrar.go:463 failed to start watch stream, retrying
  rpc error: code = Canceled desc = context canceled

The cancelled context is the agent's own, and the cancellation is
deliberate. registry/internal/registrar/registrar.go:282 starts the watch
loop from Initialize, which the agent calls long before it knows which
services this node depends on (agent/internal/cmd/root.go:251), so the
first stream is opened unfiltered. Opening a server-streaming RPC blocks
in the gRPC picker until the connection is READY, so that first call is
still in flight across the whole dial + SPIRE mTLS handshake — and inside
that window the xDS server's PreListen asserts the node's demand-scoped
filter (agent/internal/xds/server/server.go:104 -> SetServiceFilter ->
registrar.go:222 cancelStream()), cancelling the per-stream context. The
established-stream path already classified this (handleStreamError, ex
registrar.go:531), but the pre-connection path did not, so it fell
through to the generic error branch: ERROR, a watch_errors count, and a
1s+jitter backoff before the filtered stream could be opened.

Classify the cancellation before cancelling the per-stream context:
 - parent context done -> shutting down, return quietly (this also
   silenced a spurious ERROR on every agent shutdown);
 - per-stream context cancelled with codes.Canceled -> a filter
   re-assert superseded the dial. Log at INFO with a "startup" marker
   (true for the process's first stream) and reconnect immediately —
   backing off only delayed the demand-scoped snapshot.

Real stream-open failures keep ERROR, the metric and the backoff.

Test: an in-process registrar over bufconn with a gated dialer reproduces
the race deterministically (the first WatchEndpoints is blocked in the
picker when SetServiceFilter lands) and asserts zero ERROR-level records
on a clean start, plus that the reconnect carries the new filter. Without
the fix it fails with the exact production line. A second test asserts a
clean shutdown logs no ERROR either.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo merged commit 3093d6b into main Sep 5, 2026
16 checks passed
@bpalermo
bpalermo deleted the fix/700-startup-watch-ctx branch September 5, 2026 20:58
bpalermo added a commit that referenced this pull request Sep 5, 2026
…failure (#718) (#720)

On every registrar Deployment roll the draining replica sends a graceful
HTTP/2 GOAWAY (NO_ERROR) and the agent's watch stream dies with

  rpc error: code = Unavailable desc = closing transport due to: connection
  error: desc = "error reading from server: EOF", received prior goaway:
  code: NO_ERROR, debug data: "graceful_stop"

The agent reconnects to the surviving replica immediately, so this is a
handoff, not a failure — but it was the only ERROR an agent emitted in a
healthy deploy (after #712 quieted the startup case), tripping every
"zero ERROR lines" gate.

Classify it: status code Unavailable plus the `received prior goaway:
code: NO_ERROR` detail grpc-go renders into the status message (the code
is exposed nowhere structurally; internal/transport is not importable).
That case now logs INFO "watch stream closed by server drain;
reconnecting" with server_drain=true and the same error attr, counts no
watch_errors, and reconnects with no backoff.

Every other established-stream loss keeps the failure path, which the
established path never had: ERROR, watch_errors, and the jittered
backoff, now shared with the stream-open path via failStream.


Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

Co-authored-by: Claude Fable 5.1 <[email protected]>
bpalermo added a commit that referenced this pull request Sep 7, 2026
) (#741)

Agent startup no longer exits when SPIRE is not serving yet. The one-shot,
fatal `commonspire.NewSource` (25s bound, #668) is replaced by a
`WaitingSource` runnable that retries forever with bounded, jittered backoff,
serves `ErrNoSVIDYet` meanwhile, and announces the wait at INFO with
attempt/elapsed — escalating to WARN after `--spire-wait-warn-after` (2m).

Everything downstream already tolerated a late identity: the SDS bridge dials
lazily and now also serves the node SVID on the source's `Updated()` wake
rather than the next 30s tick; the registrar watch loop defers (INFO, no
`watch_errors`, no backoff escalation) while the SVID is pending; the xDS cache
omits upstream mTLS until `SetNodeIdentity` lands and Envoy tolerates the absent
secret (#715). The trust domain is seeded with the mesh domain through a small
atomic holder and reconciled against the real SVID when it arrives.

Readiness gains a `spire-svid` check beside `cni-chained`, with a 2m dwell equal
to the warn threshold: the controller's node-taint guard re-arms
`aether.io/agent-not-ready:NoSchedule` after 30s of NotReady and spire-server
does not tolerate that taint, so a hard-from-t=0 gate would fence the cluster
against spire-server's own rescheduling.

New metrics: `aether.agent.spire.wait_seconds` (seconds-oriented buckets, #732),
`aether.agent.spire.source_restarts` (expected 0), `aether.agent.spire.svid_ready`.
Chart: `spire.waitWarnAfter: 2m` threaded to all four components. Runbook: "The
agent is stuck waiting for SPIRE".

The `--spire-enabled=false` path (#421) is unchanged, and nothing in `runAgent`
or `PreListen` is reordered (#700/#712). The controller/registrar/edge sources
still create synchronously; PR 2 moves them.


Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

Co-authored-by: Claude Fable 5.1 <[email protected]>
bpalermo added a commit that referenced this pull request Sep 7, 2026
…#740) (#746)

On the rev211 deploy roll (2026-09-07 20:47Z) main-worker-02's agent published
its initial xDS snapshot 0.4s after acquiring its SVID, while its registrar
client's ClientConn was still recovering from the handshakes it had failed
before identity existed. The registry read failed, the snapshot went out with
no cross-node endpoints, and that node's prober logged 316 http_error over the
~30s until the next refresh repaired it — with SPIRE healthy and both registrar
replicas Ready since 20:46:45Z.

What registryReady meant: PreListen type-asserted registry.ReadyWaiter
(registry/registry.go:52-59) and called WaitReady
(registry/internal/registrar/registrar.go:207-214), which blocks on a ONE-SHOT
latch closed by readyOnce at registrar.go:799 on the first SNAPSHOT_COMPLETE.
So it meant "a complete snapshot arrived at some point" — not "the registry
will serve this read now". The read that follows takes a different path (the
RPC fallback at registrar.go:377-397 when the cache is not serving), and its
failure was handled by the local-only fallback, not by more waiting.

So the wait now ends on a SUCCESSFUL load: WaitReady, then
LoadClustersFromRegistry retried inside the same 15s budget the ready-wait
already had, logging `registry connected; generating the initial snapshot`
with the elapsed wait. A genuinely unreachable registrar costs exactly what it
cost before — the budget, then the unchanged local-only fallback and background
retry. Synchronous backends (no watch) keep the single attempt exactly.
Nothing else in PreListen moves: #700/#712's AssertWatchFilter ordering stands.

Classification, second half. `x509svid: could not get X509 bundle` is raised by
go-spiffe's own verifier against the LOCAL bundle source
(svid/x509svid/verify.go:59-61), so the identical text is produced whichever
party was short of an identity — and after a pre-identity attempt the
ClientConn hands it back from cache, so it is not even current. Text cannot
classify it; local state can. spire.ClassifyHandshake asks in the order the
answers are trustworthy: our own IdentityReady() first, then a transport
failure inside a 5s window after identity arrived (the reconnect), and only
then the peer's. Both the cluster-refresh path (reportReloadFailure, PR 4) and
the watch loop use it. New INFO
`registrar connection not yet re-established after identity; retrying`;
`registrar has no identity yet` now means what it says. #718's drain
classification is untouched (it never reaches failStream).

Tests, all hermetic: a watch-backed registry whose readiness latch is already
satisfied while reads still fail for 400ms — PreListen must not return before
it can serve, and the published snapshot must carry its cluster and endpoint;
a control proving the failed attempts publish nothing; the never-comes-up
registry still falling back local-only inside its bound; the synchronous-backend
control; and the three-way classification in common/spire, the refresher and
the registrar client.


Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

Co-authored-by: Claude Fable 5.1 <[email protected]>
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.

agent: first registrar watch-stream attempt logs ERROR 'context canceled' on a clean startup, then retries fine

1 participant