Skip to content

flaky: replicator e2e — endpoint withdrawal >30s when the designed path is watch-speed (sub-second) #597

Closed

Description

@bpalermo

Symptom

The replicator job in the e2e workflow intermittently fails at step 3/4 on the negative assertion:

✓ mirror expired in etcd-a 0s after origin death (origin-heartbeat lease lapse, no peer GC)
✓ origin data intact in etcd-b (only the mirror expired)
✗ client(a) still reaches echo after region-b mirror expired

Confirmed non-deterministic: run 30202321468 failed and an immediate re-run of the same job on the same commit (30202616455) passed. The 06:48 nightly on the preceding commit also passed. It is not a regression from #594/#595/#596.

What the assertion actually tests

After region-b's registrar (the replicator leader) is killed and its mirror expires from etcd-a, cluster a must lose reachability to echo in b. The registry half works reliably — the mirror expired at 0s, exactly as the origin-heartbeat lease design intends, and b's origin data correctly persisted. What is flaky is the data path outliving the registry state.

e2e/multicluster_replicator.sh:374-379 allows 6 attempts × 5s ≈ 30s for the call to stop returning 200.

Why 30s should already be enough — and why that makes this worth investigating

The withdrawal chain is: mirror lease lapses → a's registrar notices → snapshot update → broadcast to agents → agent xDS push → Envoy EDS drops the endpoint.

The registrar's poll interval is 5s (registrar/internal/cmd/config.go:11 defaultSyncInterval). So the dominant term is ~5s plus xDS propagation, comfortably inside the 30s budget. The fact that it occasionally exceeds 30s suggests one of:

  1. an intermittent stall somewhere in the withdrawal chain (registrar sync, broadcast, or xDS push) — a real product-behaviour question, since endpoint withdrawal latency matters for cross-cluster failover;
  2. Envoy retaining the endpoint after an empty/updated EDS response longer than expected;
  3. simply an under-budgeted window that is usually fine.

Distinguishing (1)/(2) from (3) is the point — a negative assertion that flakes can hide a genuine intermittent delay, and "just extend the timeout" would bury it.

Suggested fix

Follow the pattern that paid off in #590: make the failure self-explaining rather than just more patient.

  • On failure, dump the state of each link: a's registrar snapshot for echo, the agent's xDS/EDS view, and Envoy's endpoint state for the cluster — so the next red run names the stalled hop instead of costing a bisect.
  • Then, if the diagnostics show the chain is simply slower than 30s in the tail, widen the window with justification rather than arbitrarily.

Related: #554 (the other flaky test, since fixed — same principle: triage the mechanism before adjusting the test).

Activity

  1. bpalermo commented on Jul 26, 2026

    @bpalermo
    OwnerAuthor

    Correction: the propagation path is watch-speed, not 5s poll — which makes this anomaly ~2 orders of magnitude worse than first stated

    The original write-up said a ~30s budget "should be ample because the registrar polls every 5s (defaultSyncInterval)". That understates the problem. Reading the implementation:

    The registrar is push-driven end to end.

    • Local registry → registrar (registrar/internal/server/sync.go:86-127): the syncer selects on a 5s ticker, a watch-change channel, and a debounce timer. The etcd backend implements registry.ChangeNotifier through a real clientv3.Watch over the key prefix (registry/internal/etcd/etcd.go:190-215), coalescing into a size-1 buffered channel. It logs this at startup: "registry supports change notifications; syncing at watch speed (poll is backstop)".
    • Cross-region (registrar/internal/replicator/replicator.go:280): leader-elected, watches its OWN authoritative subtree with WithRequireLeader and replays changes verbatim (Put→Put, Delete→Delete) into each peer's etcd, after an initial full sync — sync-then-watch.

    So defaultSyncInterval = 5s is not the propagation path. It is a backstop for windows where a watch is legitimately unavailable (compaction, leader change, re-establish after a broken channel).

    Expected withdrawal latency is therefore sub-second plus debounce — not ~5s. A call still returning 200 30 seconds after the mirror expired is roughly two orders of magnitude outside the designed path, not a marginal overrun of a tight budget.

    What that implies

    "Just widen the window" is now clearly the wrong first move — it would paper over one of three materially different bugs:

    1. A watch broke and the run fell back to the 5s poll at exactly the wrong moment. Plausible and benign-ish, but then the observed delay should still be ~5s, not >30s — so this alone probably does not explain it.
    2. A replicator leader-election gap. The mirror stream is leader-elected; the test kills region-b's registrar, which is the replicator leader. If leadership handoff or the watch re-establish stalls, changes stop flowing while everything still looks healthy.
    3. The endpoint lingers downstream of the registry — the registrar dropped it correctly (the test already proves the mirror expired at 0s), but the agent's xDS push or Envoy's EDS did not remove the host promptly.

    (3) would be the most significant: it would mean cross-cluster failover latency is bounded by something other than the registry, which is the whole premise of the origin-heartbeat lease design.

    Revised fix

    Unchanged in shape, sharper in target — instrument the hops, then decide:

    • on failure, dump a's registrar snapshot for echo, the agent's xDS/EDS view, and Envoy's endpoint state for that cluster, so the next red run names which of (1)/(2)/(3) it was;
    • also capture whether the watch was connected at the time (the registrar logs watch re-establishment) — that discriminates (1) and (2) directly;
    • only after the mechanism is known, adjust the budget, with the measured tail as justification.

    This is the same approach that turned three nights of blind curl 000 into a same-run diagnosis in #589/#590.

  2. changed the title [-]flaky: replicator e2e — 'client(a) still reaches echo after region-b mirror expired' (intermittent)[/-] [+]flaky: replicator e2e — endpoint withdrawal >30s when the designed path is watch-speed (sub-second)[/+] on Jul 26, 2026
  3. bpalermo commented on Sep 20, 2026

    @bpalermo
    OwnerAuthor

    Two months on, here is the rate — which turns "intermittent" into something decidable.

    Replicator outcome across the last 19 nightly/dispatch e2e runs:

    window outcome
    2026-09-02 → 09-17 (16 runs) success, every one
    2026-09-18 failure
    2026-09-19 failure
    2026-09-20 (×2) success

    And the decisive datum: 09-17 and 09-18 built the SAME commit, 0459c2a4 — one passed, one failed. Identical bytes, opposite outcomes, 24 hours apart. That confirms at a larger scale what the original report established by re-running a single job: this is not a code regression and no commit bisect will find it.

    But it is also not scattered the way a coin-flip would be. Sixteen clean runs, then exactly two consecutive failures, then clean again, is a clustered flake — which points at an environmental or timing factor that was present on 09-18 and 09-19 and is not now, rather than at a constant low probability.

    What this changes about the issue

    It should stop being observed and start being measured. Watching further nightlies cannot distinguish the two hypotheses in the original report — an intermittent stall in the withdrawal chain versus a 30 s budget that is simply too tight for the real latency distribution — because both produce exactly this pattern.

    The missing number is the withdrawal latency itself. The designed path is registrar poll (5 s, defaultSyncInterval) → snapshot → broadcast → agent xDS push → Envoy EDS drop. Nobody has recorded how long that actually takes, so "occasionally exceeds 30 s" is measured against an assumption rather than a distribution.

    Concrete next step: instrument the harness to record the elapsed time from mirror-lease lapse to the first non-200, on every run including the passing ones, and emit it in the job output. Twenty runs of that gives a distribution. If the passing runs cluster at 5–8 s the 30 s budget is generous and the failures are a genuine stall worth chasing in the product; if they cluster at 20–25 s the budget is the bug and the fix is to widen it and say why.

    Either way the issue closes on evidence instead of on someone deciding it has been open long enough. Until that instrumentation exists, further nightly observations add nothing.

  4. bpalermo commented on Sep 20, 2026

    @bpalermo
    OwnerAuthor

    The answer is already in the two red runs' own logs — and it is neither of the two hypotheses

    I went to instrument this and found I did not have to: the diagnostics dump_failover_state() added are in the 09-18 and 09-19 job logs, and combined with the registrar's own timestamps they reconstruct the whole sequence to the millisecond. The mesh withdrew the endpoint in ~150 ms. The harness started its 30 s stopwatch 29.4 s before the event it claims to measure.

    So I was wrong in my last comment, and the framing in the issue body is wrong too. There is a third hypothesis and it is the right one:

    (c) mirror_present() cannot distinguish "the keys are gone" from "I could not read etcd", and step 3 anchors the entire 30 s budget to that reading.

    The 09-18 timeline (run 35327176927, job 105543522314)

    time event source
    09:05:17.49 test scales b's registrar to 0 job log
    ~09:05:47.9 b's registrar pod actually gone (full 30 s termination grace) kubectl wait --for=delete returns
    09:05:48.46 test declares "mirror expired in etcd-a 0s after origin death" job log
    09:05:48.018 / :53.017 / :58.018 / 09:06:03.017 / :08.017 / :13.017 a's registrar sync cycles — six consecutive no-ops, dead on the 5 s poll grid registrar log
    09:06:17.870 origin-heartbeat lease actually revokes → keys deleted from etcd-a inferred, see below
    09:06:17.879 a's registrar: sync detected changes version=28 events=2 — off the 5 s grid, i.e. debounce/watch-driven, +9 ms server/sync.go:189
    09:06:18.019 a's agent: service disappeared from registry; retaining empty cluster/vhost for grace period 1m30s — +150 ms cache/cluster.go:606
    09:06:20.37 test gives up, prints the 30 s die job log
    ~09:06:22 post-dump recheck: client(a) -> echo = 000 job log

    The inference on the revoke time is not a guess. DefaultLeaseTTLSeconds = 30 (registrar/internal/replicator/lease.go:16). The pod was gone at ~09:05:47.87. The registrar's first detection is at 09:06:17.879 — pod death + 30.00 s, to the millisecond, and it arrives off the poll grid, which means the clientv3 watch delivered it, not the backstop. There is no reading of that coincidence other than "the lease revoked right then".

    Which means the keys were still in etcd-a at 09:05:48.46, when mirror_present said they were not. That read returned empty for a reason that had nothing to do with the lease:

    mirror_present() {
    	docker exec "$(etcd_name "$1")" etcdctl get --prefix "/aether/v1/regions/$2/" --keys-only 2>/dev/null | grep -q .
    }

    2>/dev/null plus grep -q . makes a failed docker exec, an etcdctl dial timeout, or a command timeout indistinguishable from success-with-no-keys. The pipeline's exit status is grep's; etcdctl's is discarded. On a contended ubuntu-latest runner carrying two kind clusters, two SPIRE installs and two etcds, that read hiccuping once is entirely ordinary — and one hiccup is all it takes, because the loop breaks on the first false.

    09-19 (job 105870909512) is the same shape: declared expiry at 08:54:54.59, six no-op sync cycles on the *.910 grid, then sync detected changes at 08:55:03.213 — again off-grid, again watch-driven — and post-dump recheck = 503.

    Three further things the logs settle

    1. Both "failures" are near-misses that had already withdrawn. post-dump recheck: client(a) -> echo = 000 (09-18) and = 503 (09-19). The call stopped. There was never a stall. Hypothesis (a) is dead.

    2. The Envoy section of dump_failover_state() is a vacuous gate. It runs grep -i echo | head -40 over /clusters, then prints ^ cause (3): Envoy STILL holds echo hosts after the registry withdrew. In /clusters text output the per-host rows come after each cluster's config/stat rows. There are three echo clusters (:8080, bare, :18081) at ~15 config rows each = 45 rows, so head -40 is structurally incapable of reaching a single host row — and in the 09-18 dump it did not: zero ::hostname::/::health_flags::/::cx_active:: lines, yet the conclusion was printed anyway. Same defect in dump_echo_eds(). This is the same class as #853: a check that can only ever emit one verdict.

    3. Cause (3) is impossible by construction anyway. I traced the consumer side: a removed endpoint is omitted from the CLA entirely (agent/internal/xds/cache/cluster.go:459 buildHTTPEndpointBuckets — full rebuild from the registry listing, cluster.go:221-226), every mesh EDS cluster sets healthy_panic_threshold = 0 (agent/internal/xds/proxy/egress.go:264, :337, :378), ignore_health_on_host_removal = true (egress.go:302) and close_connections_on_host_health_failure = true (egress.go:286). The only retention is defaultServiceRetentionGrace = 90s (cluster.go:619), which holds an empty CLA — that is the 503, not stale routing. Registrar→agent→Envoy is one 250 ms trailing debounce (agent/internal/xds/server/refresh.go:20) plus RTT.

    The plan

    P1 — make the etcd read fail loudly (this is the fix). mirror_present must return three states, not two, and step 3 must never treat "could not read" as "gone":

    # 0 = keys present, 1 = keys absent, 2 = read failed
    mirror_present() {
    	local out rc
    	out="$(docker exec "$(etcd_name "$1")" etcdctl --command-timeout=5s \
    		get --prefix "/aether/v1/regions/$2/" --keys-only 2>&1)"; rc=$?
    	if [ "$rc" -ne 0 ]; then
    		printf '  !! etcdctl read of etcd-%s failed (rc=%d): %s\n' "$1" "$rc" "$out" >&2
    		return 2
    	fi
    	printf '%s' "$out" | grep -q . && return 0 || return 1
    }

    Step 3's expiry loop keeps polling on 2; steps 1 and 4 already retry, so they are unaffected. The stderr line alone would have named this in one red run.

    P2 — confirm the expiry before starting the clock. Require two consecutive absent reads ≥1 s apart, and refuse to start the budget earlier than the lease can physically lapse: the mirror cannot be gone before T_origin_death, and a declaration at T_scale + 31 s when LEASE_TTL=30 and the pod took ~30 s to terminate is arithmetically impossible. Emit a loud warning when T_declared − T_pod_gone < LEASE_TTL − keepalive_period and re-read rather than proceed. Cheap, and it catches exactly both red runs.

    P3 — measure the withdrawal, on every run, with one exec. Replace the 6×5 s client_code loop. Its granularity is {0,5,10,15,20,25} and each probe carries ~1.1 s of kubectl exec overhead, so it cannot produce a distribution. Run the sampler inside the client pod instead — one exec, no per-probe overhead, sub-second resolution, and it reports on pass and fail:

    out="$(kubectl --context "kind-$CLUSTER_A" -n "$TEST_NS" exec deploy/client -c curl -- sh -c '
      s=$(date +%s)
      while :; do
        c=$(curl -sS -o /dev/null -w "%{http_code}" --max-time 5 \
            "http://echo.'"$TEST_NS"'.'"$MESH_DOMAIN"':18081/" 2>/dev/null || echo 000)
        n=$(date +%s)
        [ "$c" != "200" ] && { echo "withdrawn=$((n-s)) code=$c"; exit 0; }
        [ $((n-s)) -ge '"$WITHDRAW_CAP"' ] && { echo "withdrawn=CAP code=200"; exit 0; }
        sleep 1
      done')"
    printf 'AETHER_METRIC replicator_withdraw_seconds=%s lease_lapse_seconds=%s budget=%s ttl=%s\n' \
    	"${out#*withdrawn=}" "$lapse" "$WITHDRAW_BUDGET" "$DefaultLeaseTTL"

    with WITHDRAW_CAP=120 ≫ the 30 s budget, so a failing run reports how far past rather than only past. That single bit — "31 s" vs "never" — discriminates (a) from (b) on one red run, without needing twenty. Tee the AETHER_METRIC line into $GITHUB_STEP_SUMMARY in .github/workflows/e2e.yaml so it is visible without opening the log.

    Also emit lease_lapse_seconds (scale-to-0 → confirmed expiry). That is the variable that actually moved across runs, and it is pod-termination-grace + TTL, i.e. nothing to do with the mesh:

    run scale-to-0 → declared expiry replicator job
    09-12 45.5 s pass
    09-15 56.5 s pass
    09-16 61.5 s pass
    09-17 61.6 s pass
    09-18 31.0 s fail
    09-19 50.9 s fail
    09-20a 61.4 s pass
    09-20b 62.0 s pass

    The four cleanest passes sit at ~61.5 s = 30 s grace + 30 s TTL, exactly as designed. Both failures are the two earliest declarations. (09-12/09-15 are early too and passed, because their probe loop happened to run past the real lapse — which is precisely the coin-flip this produces.)

    P4 — fix the vacuous Envoy dump. Filter to host rows and only print the cause-(3) verdict if one actually matched:

    hosts="$(docker exec "$node" curl -s --max-time 5 http://127.0.0.1:9901/clusters \
    	| grep -E '^echo[^:]*(:[0-9]+)?::[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+:[0-9]+::' | head -40)"
    [ -n "$hosts" ] && printf '%s\n' "$hosts" || echo '    (no echo HOSTS in Envoy — the CLA is empty; this is the 90s retention grace, cache/cluster.go:619)'

    P5 — close the false-pass path in client_code. The assertion is [ "$code" != "200" ], and client_code returns 000 on any failure including a failed kubectl exec. A broken exec is therefore an automatic pass of step 3. It is not what happened here (the post-dump rechecks corroborate real withdrawal), but it is live. P3's in-pod sampler removes the exec from the probe path entirely; additionally assert the code is one of 503/000 and record which, since 503 means "Envoy has the cluster with an empty CLA" and 000 means "the name stopped resolving" — two different correct outcomes that are worth telling apart.

    What each hypothesis now predicts, numerically

    • (a) genuine stall — replicator_withdraw_seconds is bimodal with a tail pinned at CAP (120). Already contradicted: both red runs' post-dump recheck was non-200 within ~2–4 s of the die.
    • (b) budget too tight — clusters in 20–35 s, straddling 30. Contradicted: measured registrar→agent reaction was 9 ms and 150 ms after the real lapse.
    • (c) wrong t=0 — once the clock is anchored to a confirmed lapse, replicator_withdraw_seconds is sub-second on every run, and all the run-to-run variance moves into lease_lapse_seconds (31–62 s). This is the prediction to try to falsify.

    I am not proposing to widen the 30 s budget, and after P1–P3 it should be reduced, not raised: measured end-to-end is ~150 ms, so 10 s is already ~60× headroom and a budget that large stops being an assertion. What would justify widening instead: replicator_withdraw_seconds landing repeatedly in the 20–35 s band with a correctly anchored t=0 — i.e. (b) turning out to be true after all.

    Harness non-determinism, for the record

    • runs-on: ubuntu-latest — shared GitHub-hosted runner carrying two kind clusters, two SPIRE installs and two etcd containers. Every docker exec / kubectl exec in the harness is exposed to that contention; mirror_present is the only one where a hiccup silently changes the verdict.
    • kubectl wait --for=delete pod --timeout=90s ... || true (line ~528) — its return time is t=0 for everything downstream, it varies with termination grace, and a timeout is swallowed by || true.
    • GitHub Actions timestamps the log on flush, not on write. Adjacent ok lines in these jobs show 66 ms gaps around a docker exec that cannot run that fast, so sub-second deltas inferred from the job log are not trustworthy — another reason the number has to be measured explicitly rather than read off timestamps.
    • fs.inotify is not implicated. I checked all six jobs: every one logs ✓ inotify limits raised, and raise_inotify() ran before any cluster creation. Ruling it out rather than leaving it on the list.
    • e2e/certs is regenerated per run (generating throwaway CA) — adds time, changes nothing about step 3.

    Closing criterion

    #597 closes when P1–P4 are merged and five consecutive nightlies print AETHER_METRIC replicator_withdraw_seconds with a sub-second value — i.e. the suite is asserting on a number it actually measured, from a t=0 it actually confirmed. If any of those five prints a value near or above the budget, the metric names which hypothesis survived and the issue re-opens with evidence instead of a re-run.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions