feat: add the EtcdMirror replication engine library (pkg/mirroragent)#407
feat: add the EtcdMirror replication engine library (pkg/mirroragent)#407xrl wants to merge 5 commits into
Conversation
Introduces the EtcdMirror CRD (schema only, no controller/agent) that will describe a continuous one-way key-range sync from a source etcd cluster to a target etcd cluster. Adds EtcdMirrorSpec/Status, the EtcdMirrorEndpoint/TLS/Auth/Sync/Checkpoint/Reconciliation sub-specs, phase and condition constants (including TargetThrottled and ReplicationLagExceeded), printer columns, and CEL XValidation rules for the destPrefix/noDestPrefix mutual exclusion, the endpointList/serviceRef oneOf, and the insecureSkipVerify/ insecureSkipVerifyAcknowledgeRisk companion-field requirement. Registers EtcdMirror/EtcdMirrorList in the scheme, regenerates zz_generated.deepcopy.go and the CRD manifest via controller-gen, and adds a realistic sample CR. CEL rules are covered by a table-driven envtest suite in etcdmirror_cel_test.go, following the tls_cel_test.go pattern, exercised against a real envtest apiserver. The design's Metrics field (reusing EtcdClusterSpec's MetricsSpec) is intentionally omitted: MetricsSpec does not exist on this branch yet and will land with pr/domain-metrics; it will be added in a later PR once that type is importable. No controller or agent logic in this PR -- types, generated code, and CRD schema only. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Signed-off-by: Xavier Lange <xrlange@gmail.com>
Reshape the EtcdMirror API for the Design-3 engine (checkpoint stored in
the target etcd, stateless agent) per the 48-finding cross-cloud review.
Deletions:
- checkpoint.storageSpec (no PVC; checkpoint lives in the target at a
reserved fenced key)
- expectEmptyPrefix (superseded by initialSync.mode)
- noDestPrefix (redundant; one anchored rewrite formula
key' = target.prefix + destPrefix + TrimPrefix(key, source.prefix))
- syncInterval
Additions/renames:
- spec.mode: Sync|Drain; status.cutover{drainTargetRevision,
drainedRevision, verifiedTime, counts, leasedKeyCount}
- initialSync.mode: RequireEmpty|Overwrite|OverwriteAndPrune,
startRevision
- sync: requestTimeout, excludePrefixes, pageKeyLimit,
watchBufferBytes; batching flushes only at source-revision boundaries
- TLS: secretRef pointerized (nil = system trust roots), caBundleRef
- pod resources; configurable reserved checkpoint key
- watermark-derived lag/liveness semantics; frozen condition vocabulary
(TargetQuotaExhausted, ResyncLoopDetected, CutoverReady,
InvariantsHeld, LearnerEndpoint, Prefix/DirectionConflict) and Event
Reason constants as API contract
- status: source/target versions and cluster IDs, leaseBackedKeyCount,
always-on source/target key counts, initialSyncTotalKeyCount
- CEL: scheme-vs-TLS rules, prefix/rewrite immutability
- docs/etcdmirror.md (fidelity caveats, one-way contract) and
regenerated API reference
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Xavier Lange <xrlange@gmail.com>
Purpose-built replication engine, zero k8s dependency; replaces the
clientv3 mirror.Syncer plan.
Architecture: unpinned chunked scan + watch-replay from R0 (reflector
pattern) — the watch starts at the revision observed before the scan
and events are buffered/replayed over the scanned base, eliminating
mid-scan compaction as a failure class. Pull-based single-page scan
with byte-bounded pages keeps agent memory bounded; the source watch
is cancelled on sustained target backoff and resumed from checkpoint.
Fence protocol: checkpoint/watermark stored in the target etcd at a
reserved key (\x00-after-prefix convention, exact-match excluded from
scans/counts/prune/RequireEmpty), written in the same Txn as each
applied batch and guarded by a mod_revision compare on every write
path (applies, reconciliation repairs, prune deletes). Fence value
carries {linkUID, epoch, role}; role flips to Primary at cutover so
straggler applies fail their compare loudly. Undecodable checkpoints
fail closed; prune-pending is durable across restarts.
Batching: flush only at source-revision boundaries (whole revisions
coalesced, never split), ~1MiB byte watermark, one MaxTxnOps slot
reserved for the checkpoint write.
Error taxonomy: ErrCompacted classified distinctly;
rpctypes.ErrNoSpace -> TargetQuotaExhausted (permanent until operator
acts); oversized-Txn InvalidArgument and >2MiB client send-cap
ResourceExhausted both permanent with the offending key surfaced
redacted; throttle-distinct backoff; N-consecutive-forced-resync
livelock detector.
Liveness: watermark-derived progress via WithProgressNotify +
WithRequireLeader, client-driven RequestProgress, gRPC keepalives on
both clients, per-unary-RPC deadlines (watch excluded). Version probe
at connect enforces the >=3.4 source floor and gates progress-notify
trust on 3.4.25/3.5.8. Anchored prefix rewrite via the single
documented formula. Lease-backed keys detected and counted
(kv.Lease != 0).
Tests: unit coverage per module plus an embedded-etcd integration
suite covering scan/tail convergence, fence overlap and epoch/role
rejection, compaction during scan and drain, forced-resync
mark-and-sweep, checkpoint resume, prune, and error classification.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Signed-off-by: Xavier Lange <xrlange@gmail.com>
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: xrl The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
|
Hi @xrl. Thanks for your PR. I'm waiting for a etcd-io member to verify that this patch is reasonable to test. If it is, they should reply with Regular contributors should join the org to skip this step. Once the patch is verified, the new status will be reflected by the I understand the commands that are listed here. DetailsInstructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. |
A single post-heal put can race the recovery attempt's restart backoff and land below the scan's R0: the scan applies it, the live tail has nothing to deliver, and no live apply ever clears the latch. Write a fresh key per poll tick so one is guaranteed to arrive via the tail. Signed-off-by: Xavier Lange <xrlange@gmail.com>
Data convergence and the checkpoint write that clears PrunePending are separate Txns; a one-shot fence read can land between them under load. Signed-off-by: Xavier Lange <xrlange@gmail.com> (cherry picked from commit e9d2e9f2e7327a355e09f0eadafb2ce03e8b834f)
Adds
pkg/mirroragent: the EtcdMirror replication engine as a standalone library with zero Kubernetes dependency — pure etcdclientv3against aConfig, consumed by the agent binary and controller in the next PRs of the series. Builds on the EtcdMirror API PR (types only); this PR adds no controller or workload wiring.Depends on: #406 (EtcdMirror CRD/API types — the previous rung of this series).
Architecture
Unpinned chunked scan + watch-replay from R0 (the reflector pattern), rather than
mirror.Syncer. Why mid-scan compaction cannot wedge the engine:WithCountOnly) returnsHeader.Revision = R0and the total count in a single RPC.R0+1before any scan page is read. R0 was observed this instant by a linearizable read, so it cannot already be compacted.WithRev).ErrCompactedis a property of reads pinned below the compact revision; an unpinned read is immune by construction, at every point during the scan, regardless of concurrent compactions. The failure class is removed, not detected-and-retried.Watch(WithRev(watermark+1))lands below the compact revision — identical in shape during InitialSync and steady state, handled by one mechanism: forced resync with a mandatory mark-and-sweep prune (durable across crashes via a prune-pending flag in the checkpoint).Scan and watch are not sequential phases with a handoff race: the watch is live for the entire scan, and scan writes may interleave with replayed watch writes because both write the same idempotent final value for a given key — convergence to the last-write value; a duplicate Put of identical content is a correctness no-op.
Fence protocol
The checkpoint/watermark is stored in the target etcd at a reserved key (
\x00-after-prefix convention; exact-match excluded from scans, counts, prune and RequireEmpty), written in the same Txn as each applied batch. All safety rests on one discipline, identical on every write path (apply, reconcile repair, prune delete, cutover role-flip):etcd's
Comparehas no JSON-field predicates, solinkUID/epoch/roleare payload for humans and the engine's state machine, never comparison predicates. Cutover safety falls out for free: the role-flip Txn bumps the fence's ModRevision, so any writer holding a pre-flipobservedModRevfails its next compare loudly — no special role-check code. An undecodable checkpoint fails closed (permanent, operator inspects and deletes the reserved key): a corrupt fence proves nothing about ownership, so no write — least of all a resync's prune — is provably safe.Retry ownership:
clientv3auto-retries Gets only oncodes.Unavailable; Txn/Put/Delete are write-at-most-once. The engine owns 100% of write-path retry/backoff, and a fenced-Txn retry after an ambiguous timeout re-reads the fence first (the Txn's own success bumped the fence ModRevision).Bounded memory, batching, error taxonomy
watchBufferBytes, on overflow the scan restarts from a fresh R0 (a bounded retry, not unbounded growth).codes.ResourceExhaustedis disambiguated three ways —ErrNoSpace→ quota (park until operator acts),ErrTooManyRequests→ throttle (distinct backoff curve), client send-cap → permanent — never classified by gRPC code alone. Keys surfaced in errors are redacted (spec-public prefix + sha256 stub); values never surface. An N-consecutive-forced-resync livelock detector catches retention-vs-throughput misconfiguration (ResyncLoopDetected).WithProgressNotify+WithRequireLeader+ client-drivenRequestProgress, gRPC keepalives on both clients, per-unary-RPC deadlines (watch excluded). A version probe at connect enforces the ≥3.4 source floor and gates progress-notify trust on 3.4.25/3.5.8.Tests
Unit tests per module (fence encode/decode + corruption fail-closed, error classification table incl. the three-way ResourceExhausted split, batch revision-boundary/flush accounting, rewrite formula, config validation, backoff curve mapping, key redaction) plus an embedded-etcd integration suite: cold start, live tail, mid-scan compaction, restart resume, fence overlap between two agents, role-flip cutover fencing, oversized revisions, all three initialSync modes, drain, target quota exhaustion, watch-buffer overflow restart, prune-pending crash-resume, cluster-ID-mismatch re-arm, resync-loop detection, excluded prefixes, corrupt/future-version checkpoints, version floor, progress-notify metadata regression, and idempotent replay.
Verified with
make testandmake verify.PR series — operability fixes, TLS & EtcdMirror
Small single-purpose PRs from live kind-cluster testing of the operator. Each stands alone unless an After is listed. → = this PR.
events.k8s.ioRBAC so operator Events are actually recordedmembers[]/leaderIDfrom one health snapshot (consistent leader)altNames.ipAddressesinto certificatesvalidityDuration(365d,100d12h) as documentedDegradedcondition (was empty status)--max-concurrent-reconciles)podTemplate.specscheduling fields: topologySpread, resources, priorityClass, schedulerNameconfig/surfacespec.tls.{peer,client}surfaces (breaking alpha API)TLSReadycondition + TLS lifecycle EventsPeerCANotSharedEtcdMirrorCRD: one-way cross-cluster replication API (types + CEL)pkg/mirroragentreplication engine (fenced checkpoint-in-target)mirror-agentbinary: config/TLS-reload/statusz/metrics + kind e2e/metricsendpointEtcdBackupCR → object storage (S3/GCS)🟢 ready · ⚪ draft