Skip to content

fix(registrar,node): copy cached endpoints out of the lock, never lose a watch-filter re-assert, atomic Diff+Replace, optimistic-lock taint patches (#772) - #781

Merged
bpalermo merged 4 commits into
mainfrom
fix/772-a6d-registrar-client-and-taints
Sep 16, 2026

Conversation

@bpalermo

Copy link
Copy Markdown
Owner

Phase A3 (registrar half) + A6d of #772.

fix(registry): hand out copies of the cached endpoint slices (#772, A3/S2)

The registrar client's watch goroutine mutates a service's endpoint slice in
place: upsertLocked overwrites eps[i] when an endpoint's IP already exists,
removeLocked left-shifts the tail over the hole. Both ListEndpoints and
ListAllEndpoints handed out that same slice — ListEndpoints returned the
cache's own slice header after dropping the RLock, and ListAllEndpoints
copied the map but aliased every value.

Consumers read them on another goroutine: agent/internal/xds/cache/cluster.go
builds CDS/EDS from both, and its cold-path RPC-fill appends into what it read.
This is not only a detector finding — a reader ranging the backing array while
the left-shift runs can see one endpoint twice and skip another, so it corrupts
EDS content.

  • registry/internal/registrar/registrar.go:385 and :414: slices.Clone the
    slice(s) under the read lock before returning.
  • State the ownership contract in both method docs: the slice/map is the
    caller's copy, the *registryv1.ServiceEndpoint elements are shared and must
    be treated as immutable (no consumer mutates them today — the only in-place
    writes are the two cache mutators, which swap the pointer rather than edit the
    message — so a shallow copy is sufficient and a proto.Clone per endpoint is
    not paid on the xDS rebuild path).
  • Note the in-place rewrite at upsertLocked/removeLocked so the coupling is
    visible from the mutating side too.

Verification: new registry/internal/registrar/cache_alias_test.go interleaves
a ListEndpoints/ListAllEndpoints consumer that appends and ranges with the
watch-apply path. Before the fix: 6 DATA RACE reports and both tests fail under
--config=race. After: //registry/internal/registrar:registrar_test passes
5/5 runs under --config=race; //registry/... and
//agent/internal/xds/cache/... green.

fix(registry,registrar): never lose a watch-filter re-assert; diff+replace atomically (#772, A6d/S8/S13)

S8 — lost watch-filter re-assert (registry/internal/registrar/registrar.go).
The watch loop read the filter to assert in one filterMu critical section
(currentFilter) and published the new stream's canceller in another. A
SetServiceFilter landing entirely between the two read the PREVIOUS stream's
streamCancel — already spent — so its cancel was a no-op, while the loop went
on to open a stream carrying the filter it had read before the update. Nothing
then cancels that stream, so the node's new dependency set is never asserted
until the stream dies for some other reason: the #682 "demand-set change
invisible until the next roll" shape.

assertFilter now publishes the canceller and reads the filter under one hold
of filterMu, leaving only two interleavings: SetServiceFilter runs entirely
before (this stream carries the new filter) or entirely after (it sees this
stream's canceller and cancels it). currentFilter is gone; its one test caller
uses assertFilter.

S13 — Diff/Replace TOCTOU (registrar/internal/server). DECISION: fixed, not
documented-around. The fix is local and safe — one production caller
(sync.go:168) — so Snapshot.DiffAndReplace now holds mu across both halves
(diffLocked + replaceLocked; the exported Diff/Replace keep their own
locking for their remaining callers). Previously a RegisterEndpoint → Apply
landing between them was broadcast as ENDPOINT_ADDED and then erased by a
replacement computed before it existed, with no compensating REMOVED. That hole
was masked by Syncer.writeBehind.Overlay re-adding the intent — i.e. the
invariant was held by the write-behind queue, not by the snapshot, and the
legacy constructor path (writeBehind nil) had nothing holding it at all. The
masking relationship is now stated at DiffAndReplace either way.

Verification:

  • registry/internal/registrar/watch_filter_test.go: drives the real watch loop
    against the in-process fake registrar and bursts filter updates at it; the
    fake holds every stream open, so a lost re-assert never self-heals. With the
    read and the publish split back into two critical sections (plus a
    runtime.Gosched() to widen a window that is otherwise a few instructions) it
    fails 2/10; with the fix, 10/10 green. Plus a unit-level invariant test over
    500 interleavings: a stream that asserted the stale filter must have had its
    canceller invoked.
  • registrar/internal/server/snapshot_toctou_test.go: 500 interleavings of
    DiffAndReplace against a concurrent Apply; an endpoint absent from the
    snapshot afterwards must have been announced REMOVED. Fails 5/5 with the
    halves split (iteration 57 on the first run), passes 10/10 with the fix.
  • //registrar/... and //registry/... green; //registry/internal/registrar
    green 5/5 under --config=race. //registrar/internal/server:server_test
    still trips the known pre-existing test-only race at server_test.go:26
    (report R2, owned by A2) under --config=race — unrelated to this change.

fix(agent,controller): optimistic-lock both node-taint writers (#772, A6d/S37)

spec.taints has no patch-merge key, so client.MergeFrom emits the WHOLE
array. Both taint writers read the node and then patched it without an
optimistic lock, which makes every write a lost-update candidate: a taint added
between the Get and the Patch — by the controller's guard, a drain,
node-problem-detector — is silently reverted by a writer that never saw it, and
symmetrically for the guard reverting the agent's removal. #743 removed the
SEMANTIC taint fight (both sides now read the same readiness verdict); this is
its residual on the write path.

  • agent/internal/node/taint.go: the removal moves into dropTaint, which
    patches with client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})
    and answers a 409 by re-reading the node and retrying via
    retry.RetryOnConflict (bounded — the precedent is
    agent/internal/edge/gatewayapi/status.go:320). A conflict that never clears
    is returned to controller-runtime, which requeues with backoff.
  • controller/internal/nodetaint/guard.go: armTaint takes the node NAME and
    re-Gets inside the same retry, skipping the write when the taint is already
    present (idempotent, no duplicate taint).

Semantics are unchanged and deliberately so: the agent still holds the taint
while its readyz aggregate says not-ready and only ever removes it; the guard
still only ever adds it, and only after 30s with no Ready agent pod.

Verification: new taint_conflict_test.go / guard_conflict_test.go drive the
fake client through an interceptor that returns a 409 on the first Patch. They
assert the patch body carries a resourceVersion (i.e. is actually locked),
that the conflict is retried exactly once more, and that the end state is
right; plus a persistent-conflict case pinning the retry bound, and an
already-armed case for the guard's idempotence. Reverting both writers to plain
MergeFrom with no retry fails both new tests. //agent/internal/node/... and
//controller/internal/nodetaint/... pass 3/3 under --config=race.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

bpalermo and others added 4 commits September 15, 2026 20:08
…3/S2)

The registrar client's watch goroutine mutates a service's endpoint slice in
place: `upsertLocked` overwrites `eps[i]` when an endpoint's IP already exists,
`removeLocked` left-shifts the tail over the hole. Both `ListEndpoints` and
`ListAllEndpoints` handed out that same slice — `ListEndpoints` returned the
cache's own slice header after dropping the RLock, and `ListAllEndpoints`
copied the map but aliased every value.

Consumers read them on another goroutine: `agent/internal/xds/cache/cluster.go`
builds CDS/EDS from both, and its cold-path RPC-fill appends into what it read.
This is not only a detector finding — a reader ranging the backing array while
the left-shift runs can see one endpoint twice and skip another, so it corrupts
EDS content.

- `registry/internal/registrar/registrar.go:385` and `:414`: `slices.Clone` the
  slice(s) under the read lock before returning.
- State the ownership contract in both method docs: the slice/map is the
  caller's copy, the `*registryv1.ServiceEndpoint` elements are shared and must
  be treated as immutable (no consumer mutates them today — the only in-place
  writes are the two cache mutators, which swap the pointer rather than edit the
  message — so a shallow copy is sufficient and a `proto.Clone` per endpoint is
  not paid on the xDS rebuild path).
- Note the in-place rewrite at `upsertLocked`/`removeLocked` so the coupling is
  visible from the mutating side too.

Verification: new `registry/internal/registrar/cache_alias_test.go` interleaves
a `ListEndpoints`/`ListAllEndpoints` consumer that appends and ranges with the
watch-apply path. Before the fix: 6 DATA RACE reports and both tests fail under
`--config=race`. After: `//registry/internal/registrar:registrar_test` passes
5/5 runs under `--config=race`; `//registry/...` and
`//agent/internal/xds/cache/...` green.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
…place atomically (#772, A6d/S8/S13)

S8 — lost watch-filter re-assert (registry/internal/registrar/registrar.go).
The watch loop read the filter to assert in one filterMu critical section
(`currentFilter`) and published the new stream's canceller in another. A
`SetServiceFilter` landing entirely between the two read the PREVIOUS stream's
`streamCancel` — already spent — so its cancel was a no-op, while the loop went
on to open a stream carrying the filter it had read before the update. Nothing
then cancels that stream, so the node's new dependency set is never asserted
until the stream dies for some other reason: the #682 "demand-set change
invisible until the next roll" shape.

`assertFilter` now publishes the canceller and reads the filter under one hold
of filterMu, leaving only two interleavings: SetServiceFilter runs entirely
before (this stream carries the new filter) or entirely after (it sees this
stream's canceller and cancels it). `currentFilter` is gone; its one test caller
uses `assertFilter`.

S13 — Diff/Replace TOCTOU (registrar/internal/server). DECISION: fixed, not
documented-around. The fix is local and safe — one production caller
(`sync.go:168`) — so `Snapshot.DiffAndReplace` now holds `mu` across both halves
(`diffLocked` + `replaceLocked`; the exported `Diff`/`Replace` keep their own
locking for their remaining callers). Previously a `RegisterEndpoint` → `Apply`
landing between them was broadcast as ENDPOINT_ADDED and then erased by a
replacement computed before it existed, with no compensating REMOVED. That hole
was masked by `Syncer.writeBehind.Overlay` re-adding the intent — i.e. the
invariant was held by the write-behind queue, not by the snapshot, and the
legacy constructor path (writeBehind nil) had nothing holding it at all. The
masking relationship is now stated at `DiffAndReplace` either way.

Verification:
- `registry/internal/registrar/watch_filter_test.go`: drives the real watch loop
  against the in-process fake registrar and bursts filter updates at it; the
  fake holds every stream open, so a lost re-assert never self-heals. With the
  read and the publish split back into two critical sections (plus a
  `runtime.Gosched()` to widen a window that is otherwise a few instructions) it
  fails 2/10; with the fix, 10/10 green. Plus a unit-level invariant test over
  500 interleavings: a stream that asserted the stale filter must have had its
  canceller invoked.
- `registrar/internal/server/snapshot_toctou_test.go`: 500 interleavings of
  `DiffAndReplace` against a concurrent `Apply`; an endpoint absent from the
  snapshot afterwards must have been announced REMOVED. Fails 5/5 with the
  halves split (iteration 57 on the first run), passes 10/10 with the fix.
- `//registrar/...` and `//registry/...` green; `//registry/internal/registrar`
  green 5/5 under `--config=race`. `//registrar/internal/server:server_test`
  still trips the known pre-existing test-only race at `server_test.go:26`
  (report R2, owned by A2) under `--config=race` — unrelated to this change.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
… A6d/S37)

`spec.taints` has no patch-merge key, so `client.MergeFrom` emits the WHOLE
array. Both taint writers read the node and then patched it without an
optimistic lock, which makes every write a lost-update candidate: a taint added
between the Get and the Patch — by the controller's guard, a drain,
node-problem-detector — is silently reverted by a writer that never saw it, and
symmetrically for the guard reverting the agent's removal. #743 removed the
SEMANTIC taint fight (both sides now read the same readiness verdict); this is
its residual on the write path.

- `agent/internal/node/taint.go`: the removal moves into `dropTaint`, which
  patches with `client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{})`
  and answers a 409 by re-reading the node and retrying via
  `retry.RetryOnConflict` (bounded — the precedent is
  `agent/internal/edge/gatewayapi/status.go:320`). A conflict that never clears
  is returned to controller-runtime, which requeues with backoff.
- `controller/internal/nodetaint/guard.go`: `armTaint` takes the node NAME and
  re-Gets inside the same retry, skipping the write when the taint is already
  present (idempotent, no duplicate taint).

Semantics are unchanged and deliberately so: the agent still holds the taint
while its readyz aggregate says not-ready and only ever removes it; the guard
still only ever adds it, and only after 30s with no Ready agent pod.

Verification: new `taint_conflict_test.go` / `guard_conflict_test.go` drive the
fake client through an interceptor that returns a 409 on the first Patch. They
assert the patch body carries a `resourceVersion` (i.e. is actually locked),
that the conflict is retried exactly once more, and that the end state is
right; plus a persistent-conflict case pinning the retry bound, and an
already-armed case for the guard's idempotence. Reverting both writers to plain
`MergeFrom` with no retry fails both new tests. `//agent/internal/node/...` and
`//controller/internal/nodetaint/...` pass 3/3 under `--config=race`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo merged commit 755f065 into main Sep 16, 2026
20 checks passed
@bpalermo
bpalermo deleted the fix/772-a6d-registrar-client-and-taints branch September 16, 2026 00:15
bpalermo added a commit that referenced this pull request Sep 16, 2026
…793)

VERDICT: test artefact, not a production bug. The watch loop is correct;
the in-process fake's request log is not ordered the way the assertion
assumed.

`TestWatchLoop_FilterReassertIsNeverLost` asserted that the LAST request
recorded by `fakeWatchServer` carried the newest filter. But the fake
appends to `s.requests` from inside `WatchEndpoints`, and grpc-go
dispatches every server stream on its own goroutine
(`watch_startup_test.go:51`). When the loop cancels stream N and
immediately opens stream N+1 — which is exactly what each of the test's
4-deep bursts makes it do — the two handler goroutines race to append,
and N's request can land after N+1's. Once the burst settles, the fake
holds the live stream open forever and no further request arrives, so
`lastRequest()` reports the superseded stream's filter permanently and
the 10s `require.Eventually` can never converge.

Interleaving trace, captured by instrumenting the fake to dump its whole
request log on failure (7/7 observed failures, identical shape):

    req[39] filter=[default/svc-33-3]
    req[40] filter=[default/svc-34-3]   <- the wanted filter DID reach the server
    req[41] filter=[default/svc-34-2]   <- an OLDER stream's handler appending late
    active streams: 1

i.e. the loop opened a stream asserting svc-34-3 and was sitting on it,
doing precisely the right thing, while the test reported it "stuck on a
stream with a stale filter". In all 7 failures the wanted filter was
present exactly once in the request log and the final entry was an
earlier round-member (svc-N-2 or svc-N-1).

Production is correct and no window remains:

  - `assertFilter` (registrar.go:284-290) publishes this stream's
    canceller and reads the filter under ONE `filterMu` hold, so a
    concurrent `SetServiceFilter` either completes first (the loop reads
    the new filter) or completes after (it captures THIS stream's
    canceller at registrar.go:238 and cancels it at registrar.go:257).
    "Neither" is unrepresentable — that is #781's fix, and it holds.
  - `SetServiceFilter` cancelling late (after the cache purge at
    registrar.go:245-255) is harmless: it cancels the exact stream it
    captured, and if the loop has already moved on, its next
    `assertFilter` necessarily read a filter at least as new, because
    the critical sections are totally ordered on `filterMu`.
  - Two rapid updates both capturing the same canceller (the test's
    burst) converge: whichever cancel lands first reconnects the loop,
    and the reconnect's `assertFilter` reads the newest filter; the
    second cancel is a no-op on a dead stream.
  - #612's reconnect semantics are untouched: a locally-cancelled stream
    is classified out of the failure path (registrar.go:843-847,
    registrar.go:585-590), so no backoff accumulates across the 40
    rounds and the cap-1 wake / CompareAndSwap paths are not involved.

Test changes only:

  - `watch_startup_test.go`: add `sawFilter`, the ordering-immune
    predicate — "some stream asserted exactly this filter". It loses no
    strength, because a genuinely lost re-assert leaves its filter in no
    request at all. Document the ordering hazard on `lastRequest`; its
    other caller asserts `requestCount() == 1` so it is unaffected.
  - `watch_filter_test.go`: assert on `sawFilter`, and pass `logs`
    (a Stringer) instead of `logs.String()` — testify evaluates message
    args eagerly, so the pre-rendered string captured the log from
    BEFORE the 10s wait and never showed what actually happened. That
    alone cost most of the diagnosis time on the original CI failure.

Failure rates (race detector, `taskset -c 0,1` to mimic a 2-core runner):

  before: 2/30 on the shipped test; 7/40 on an instrumented copy
  after:  0/60 on the test, 0/30 on the whole package

Also 30/30 green via
`bazel test //registry/internal/registrar:registrar_test --config=race
--runs_per_test=30 --nocache_test_results` (whole package, unfiltered).

Verification: `bazel build //... //test/e2e:e2e_test`, `bazel test //...`
(101/101), `bazel run //:format.check`, `bazel build --config=lint
--@aspect_rules_lint//lint:fail_on_violation //...`, `bazel run
//:gazelle` (no churn), `bazel mod tidy` (idempotent),
`scripts/go-deps-audit.sh` (exit 0).


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.

1 participant