feat(m11): membership, snapshot install, and reseed (m11p5)
This commit is contained in:
parent
95461d3cf8
commit
bf57be18e1
145
CHANGELOG.md
145
CHANGELOG.md
@ -6,6 +6,151 @@ All notable changes to tidalDB will be documented in this file.
|
|||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
|
**Membership, discovery, elasticity (m11p5) — DNS peers, snapshot reseed, conf-changes on the one log, seed join, k8s reference**
|
||||||
|
- **Nodes are cattle; topology is data, not files.** `grpc_addr` is now an
|
||||||
|
**advertised** address — a hostname or an IP — split from a new optional
|
||||||
|
per-region `grpc_bind` (the local SocketAddr to bind). A literal `grpc_addr`
|
||||||
|
binds itself byte-for-byte as before (every existing topology keeps working);
|
||||||
|
a hostname binds `0.0.0.0:<port>`. `tidal-net`'s peer map retypes from
|
||||||
|
`SocketAddr` to `String`, so `Channel::from_shared` makes hyper **re-resolve
|
||||||
|
DNS on every reconnect** — the pod-rescheduled-onto-a-new-IP case the
|
||||||
|
`SocketAddr::parse`-only constraint made structurally impossible is now fixed
|
||||||
|
by construction. One shared topology file can name every region by its per-pod
|
||||||
|
DNS name (the per-pod static-ClusterIP ConfigMap hack dies). DNS peer names
|
||||||
|
require DNS-SAN certs under mTLS (SNI follows the URI host; documented, no code
|
||||||
|
change). Proven by `cluster_membership.rs::mp_dns_hostname_topology_replicates`
|
||||||
|
(a hostname topology a pre-p5 binary would have refused to parse boots,
|
||||||
|
replicates, and survives SIGKILL+restart) plus unit derivation-table tests.
|
||||||
|
- **A new node joins via snapshot + stream and serves quorum in minutes.**
|
||||||
|
`FetchSnapshot` is a new server-streaming RPC in the `WalShipping` service:
|
||||||
|
the leader stages `TidalDb::create_backup` under `<data_dir>/snapshots/` and
|
||||||
|
streams it term-stamped + term-fenced exactly like `StreamSegments`
|
||||||
|
(manifest + file chunks, each file BLAKE3-verified, identify-or-refuse end to
|
||||||
|
end). The handler answers a **no-snapshot-needed** header when the WAL can
|
||||||
|
still serve the puller's range and streams the artifact only when it cannot —
|
||||||
|
the `needed` decision is **baseline-aware** (`from_seqno ≤ stream_baseline OR
|
||||||
|
< earliest WAL seq`), because a "the WAL still covers it" answer is a lie at
|
||||||
|
or below a baseline the stream clamp will never serve, and looped marker boots
|
||||||
|
forever. Install is a **boot-time** operation (never a live data-dir swap):
|
||||||
|
fetch into a sibling staging dir, copy the node's own identity files
|
||||||
|
(`election_state`, `membership`) INTO staging, write a `COMPLETE` sentinel,
|
||||||
|
then rename — every crash window is an idempotent redo. A retention pin taken
|
||||||
|
at backup **start** keeps the segment chain covering the artifact alive while
|
||||||
|
any joiner streams, with a hard cap + `tidaldb_cluster_snapshot_pin_force_drops_total`
|
||||||
|
so a dead joiner can't freeze compaction forever.
|
||||||
|
- **Reseed is self-healing — no operator verb, no `wipe_data_dir`.** A running
|
||||||
|
follower that hits a **typed** snapshot-required refusal (the `StreamSegments`
|
||||||
|
trailer is now structured — `x-tidal-catchup: snapshot-required | rejoin |
|
||||||
|
stepping-down` — so an ordinary election term-mismatch never latches reseed
|
||||||
|
markers fleet-wide; the marker latches **only** on `snapshot-required`), or the
|
||||||
|
m11p4 divergence quarantine, durably latches `reseed_required` (ElectionStore
|
||||||
|
file discipline), surfaces it in `/cluster/status/local` and the
|
||||||
|
`tidaldb_cluster_reseed_required` gauge, and keeps serving degraded with
|
||||||
|
**voting enabled** (a reseed needs a leader, and the leader may need this
|
||||||
|
node's vote — reseed-blocks-voting would deadlock the cluster). The reseed
|
||||||
|
runs on the next boot; `replication.reseed_self_restart: true` (default
|
||||||
|
**false**; k8s sets it `true`) drains and clean-exits once the marker latches —
|
||||||
|
**refused** when the remaining voters can't sustain quorum without this node.
|
||||||
|
A successful reseed boot clears the quarantine latch and
|
||||||
|
`tidaldb_cluster_divergence_quarantined` — closing the m11p4 carried hazard
|
||||||
|
that quarantine clearing "rides m11p5's reseed machinery." `cluster_reseed.rs`
|
||||||
|
proves the full quarantine → marker → restart → converged → gauges-cleared
|
||||||
|
loop with no `wipe_data_dir` in the test.
|
||||||
|
- **The three-way term-join rule closes p4's last carried hazard** (pre-baseline
|
||||||
|
history was unreachable through a term's stream for followers behind at the
|
||||||
|
transfer). The first reseed drill exposed that such a follower jumps its
|
||||||
|
frontier past pre-baseline history with `lag=0` and never asks for the gap —
|
||||||
|
silently missing data with nothing to fire the refusal. The heartbeat now
|
||||||
|
carries the leader's election-time position in the previous stream's numbering
|
||||||
|
(`prev_log`), and the join check is three-way: `own > prev_log` → divergent
|
||||||
|
suffix → quarantine (p4); `own < prev_log` → genuinely missing committed-era
|
||||||
|
history → **latch `reseed_required`** (new); `own == prev_log` (or within-term
|
||||||
|
rejoin) → clean. A snapshot-installed node joins clean by construction (its WAL
|
||||||
|
is the leader's copy, so `tail_term` equals the leader's term).
|
||||||
|
- **Membership is data on the one log: kind-4 records, learner → voter.** A new
|
||||||
|
`MembershipRecord` WAL blob kind (kind-4, beside kind-0 signals, kind-1/2
|
||||||
|
item/embedding blobs, kind-3 term markers) is journaled by the leader,
|
||||||
|
replicated through the normal stream, and folded by followers into a
|
||||||
|
`ClusterMembership` cell (the `WalTermMark` pattern). Records carry the FULL
|
||||||
|
roster (latest record wins; no merge logic); membership **epoch 0 = the
|
||||||
|
topology file**, so a cluster with no kind-4 record behaves byte-for-byte as
|
||||||
|
today. `POST /cluster/join {name, grpc_addr, http_addr}` on any node forwards
|
||||||
|
to the leader, which assigns `id = max(all ids ever) + 1`, appends a **Learner**
|
||||||
|
record, and answers only after it is quorum-committed (idempotent by name);
|
||||||
|
member ids are **permanent** — removal tombstones (a `Removed` record) keep ids
|
||||||
|
burned, never renumbered or reused. **Auto-promotion is a standing leader duty**
|
||||||
|
(re-armed on every activation and apply, evaluated on commit-index publishes,
|
||||||
|
driven solely from the applied `ClusterMembership` — it survives the
|
||||||
|
joining-era leader's death) that promotes a learner within
|
||||||
|
`replication.learner_promote_lag` (default 1024) of the flushed frontier, or
|
||||||
|
the Raft "rounds stop shrinking" criterion. Conf-changes are Raft single-server
|
||||||
|
(one at a time, each same-term-quorum-commit-gated); on every leadership
|
||||||
|
activation the new leader **re-appends its full current membership** immediately
|
||||||
|
after the kind-3 term marker (the Raft no-op-entry analogue), which closes both
|
||||||
|
the vacuous-commit-gate and the baseline-jump-skip blockers at once. Verbs:
|
||||||
|
`GET /cluster/members`, `POST /cluster/members/remove`, `POST /cluster/reseed`.
|
||||||
|
- **The even-voter-count `majority()` arithmetic was a latent bug — fixed.**
|
||||||
|
`ElectionConfig::majority()` was `peers.len()/2 + 1`: correct at n=3, **wrong
|
||||||
|
for every even voter count** (n=4 → 2-of-4, so disjoint quorums {A,B} and {C,D}
|
||||||
|
could elect two leaders in one term; n=2 → 1-of-2, a follower self-elects with
|
||||||
|
zero RPCs). `CommitIndex` already used the correct `div_ceil` form — the two
|
||||||
|
formulas in one subsystem disagreed. Since p5 makes even sizes mandatory
|
||||||
|
transit states (3→4→5→4→3), this landed **first**, with even-n property tests:
|
||||||
|
`majority() = (peers.len() + 1).div_ceil(2) + 1` (true `floor(n/2)+1` over the
|
||||||
|
full voter set), spelled to read identically to the commit-index site so they
|
||||||
|
can never drift again.
|
||||||
|
- **Learner marks never count toward quorum.** A role-blind `CommitIndex` that
|
||||||
|
saw learner marks would treat two learners "committing" a write no voter holds
|
||||||
|
as acked — acked-write loss. `CommitIndex` is now role-aware: voter marks feed
|
||||||
|
the k-th-largest selection; learner marks live in a side map (promotion input,
|
||||||
|
transfer-wait input) and are excluded from `needed`. In-flight `ack=quorum`
|
||||||
|
waits are **re-evaluated** against a new config on every conf-change (a shrink
|
||||||
|
may satisfy waiters instantly), never failed; a report from an unknown id logs
|
||||||
|
at WARN with a counter instead of being silently dropped. `ElectionState`,
|
||||||
|
`ShipQueue`, and `PeerPool` reconfigure behind one fenced apply path so the
|
||||||
|
four peer-set copies can never disagree about the roster.
|
||||||
|
- **Seed-join boot.** `tidal-server cluster --region <name> --seed
|
||||||
|
http://host:port (repeatable) --advertise-grpc host:port --advertise-http
|
||||||
|
host:port --metrics addr`: the joiner skips the "every region declared"
|
||||||
|
topology gate, learns its roster + assigned id + current term from any
|
||||||
|
reachable seed, persists them to a durable membership cache + `election_state`
|
||||||
|
(persist-before-act), and installs a snapshot when behind. A restart boots from
|
||||||
|
the cache without the seed. A `--seed` boot **still requires the local
|
||||||
|
topology/config file** for the behavioral knob blocks (`replication:`, `wal:`,
|
||||||
|
`election:`, `timeouts:`, `grpc_tls`) — a bare `--seed` with neither
|
||||||
|
`--topology` nor `TIDAL_CONFIG` refuses to boot naming the rule (so a joiner
|
||||||
|
never silently inherits the wrong ack default or election timing).
|
||||||
|
- **Kubernetes reference: one StatefulSet.** `k8s/cluster/` (namespace
|
||||||
|
`tidaldb-cluster`, `replicas: 3`, `podManagementPolicy: Parallel`,
|
||||||
|
topology-spread, PDB `maxUnavailable: 1`) with ONE shared bootstrap topology
|
||||||
|
ConfigMap (per-pod DNS advertised addresses, `0.0.0.0` binds). Scaling past 3
|
||||||
|
does NOT edit it — pod N≥3 boots `--seed` + the same mounted file and joins as
|
||||||
|
a learner; rolling node replace is `kubectl delete pod` (PVC retained → boot
|
||||||
|
catch-up) or PVC-delete + pod-delete (fresh reseed via snapshot). Readiness:
|
||||||
|
`converged` (boot catch-up completed at least once AND `lag ≤
|
||||||
|
learner_promote_lag` — hysteresis, never `lag == 0` which an open-loop load
|
||||||
|
keeps perpetually false); a restarted existing voter is Ready on today's terms.
|
||||||
|
- Exit-gate suites (tier-3, `cluster-e2e`): `cluster_membership.rs`
|
||||||
|
(`mp_seed_join_snapshot_catchup`, `mp_scale_3_5_3_under_load_zero_loss` —
|
||||||
|
`lost=0`, max acked seq 1467, p99 impact <2× across the 3→5→3 joins,
|
||||||
|
`mp_dns_hostname_topology_replicates`) and `cluster_reseed.rs` (quarantine →
|
||||||
|
marker → restart → converged, gauges cleared). Localhost-loopback catch-up:
|
||||||
|
5000 heavy items join→converged 26.4s (large headroom under the ≤5-min budget);
|
||||||
|
the 100k-item Ref-A figure and the k8s pod-reschedule drill remain Ref-A line
|
||||||
|
items (k3s access still pending — the standing M11 caveat).
|
||||||
|
- **Mixed-version / downgrade caveats.** A kind-4 record shipped to a **pre-p5
|
||||||
|
follower** is an unknown batch kind → `WalError::Corruption` → its receiver's
|
||||||
|
torn-state halt latch, **permanent across restarts** (both followers halted =
|
||||||
|
quorum-write outage). So `HeartbeatResponse`/`ReportApplied` carry a
|
||||||
|
`capabilities` bit-field (proto3 zero-default = pre-p5 = incapable) and the
|
||||||
|
leader **refuses `JoinCluster` and every conf-change until all current voters
|
||||||
|
report kind-4 capability** — "complete the binary upgrade before the first
|
||||||
|
conf-change" is structurally enforced, not operator discipline. Pre-p5 peers
|
||||||
|
answer `Unimplemented` to `JoinCluster`/`FetchSnapshot` (the joiner reports it
|
||||||
|
loudly and retries the next seed). Downgrade rule (kind-3 precedent verbatim):
|
||||||
|
once any kind-4 record is in a node's WAL, **downgrade below p5 requires a
|
||||||
|
reseed**.
|
||||||
|
|
||||||
**Automatic failover: failure detection, Raft-style election, term fencing (m11p4) — closes ROADMAP gap G5**
|
**Automatic failover: failure detection, Raft-style election, term fencing (m11p4) — closes ROADMAP gap G5**
|
||||||
- **"A machine died" is a non-event.** Every multi-process cluster node runs a
|
- **"A machine died" is a non-event.** Every multi-process cluster node runs a
|
||||||
purpose-built election-only Raft (pre-vote + vote + check-quorum + fenced
|
purpose-built election-only Raft (pre-vote + vote + check-quorum + fenced
|
||||||
|
|||||||
2
Cargo.lock
generated
2
Cargo.lock
generated
@ -3566,6 +3566,7 @@ dependencies = [
|
|||||||
name = "tidal-net"
|
name = "tidal-net"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"blake3",
|
||||||
"criterion",
|
"criterion",
|
||||||
"prost",
|
"prost",
|
||||||
"rcgen",
|
"rcgen",
|
||||||
@ -3585,6 +3586,7 @@ name = "tidal-server"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"axum 0.8.8",
|
"axum 0.8.8",
|
||||||
|
"blake3",
|
||||||
"clap",
|
"clap",
|
||||||
"crossbeam",
|
"crossbeam",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
|||||||
@ -24,10 +24,10 @@ The authoritative component specifications (status: Implemented, M0–M8).
|
|||||||
|
|
||||||
## Planning — `planning/`
|
## Planning — `planning/`
|
||||||
|
|
||||||
- [**ROADMAP.md**](planning/ROADMAP.md) — milestones M0–M10, phase status, known gaps
|
- [**ROADMAP.md**](planning/ROADMAP.md) — milestones M0–M11, phase status, known gaps
|
||||||
- [**roadmap-to-cluster.md**](roadmap-to-cluster.md) — gap analysis + phase plan (M11 candidate) from the experimental multi-process cluster to an enterprise-grade one, grounded in the 2026-06-10 live stress-test baselines
|
- [**roadmap-to-cluster.md**](roadmap-to-cluster.md) — adopted M11 plan: gap analysis + phase specs taking the multi-process cluster from experimental to enterprise-grade (m11p1–p5 ✅; p6–p9 planned), grounded in the 2026-06-10 live stress-test baselines
|
||||||
- [PRODUCT_ROADMAP.md](planning/PRODUCT_ROADMAP.md) · [architecture-review.md](planning/architecture-review.md) · [roadmap-cohort-analysis.md](planning/roadmap-cohort-analysis.md) · [site-cohort-analysis.md](planning/site-cohort-analysis.md)
|
- [PRODUCT_ROADMAP.md](planning/PRODUCT_ROADMAP.md) · [architecture-review.md](planning/architecture-review.md) · [roadmap-cohort-analysis.md](planning/roadmap-cohort-analysis.md) · [site-cohort-analysis.md](planning/site-cohort-analysis.md)
|
||||||
- Per-milestone phase/task archive: `planning/milestone-0,1,2,3,5,7,8,9,10,p/`
|
- Per-milestone phase/task archive: `planning/milestone-0,1,2,3,5,7,8,9,10,11,p/`
|
||||||
|
|
||||||
## Code reviews — `reviews/`
|
## Code reviews — `reviews/`
|
||||||
|
|
||||||
|
|||||||
@ -38,7 +38,7 @@ tidal-server standalone \
|
|||||||
|
|
||||||
### Cluster — EXPERIMENTAL, not production HA
|
### Cluster — EXPERIMENTAL, not production HA
|
||||||
|
|
||||||
Cluster mode runs multiple "regions" behind one HTTP surface and replicates between them over the **real `tidal-net` gRPC transport**. It has two shapes: a **multi-process** mode (`--region`, one process per region, real gRPC peering between siblings, real process/host isolation — shipped in m8p10) and a single-process dev/demo default (all regions in one process over loopback). The critical caveat for BOTH: writes are **leader-durable, not quorum-acked**, and failover is **operator-driven** (`/cluster/promote`), not automatic election. **This is not yet production high availability.** The recommended production deployment remains a **single standalone node** until quorum-ack writes and automatic failover land (tracked as post-M8 follow-ups in the [ROADMAP](../planning/ROADMAP.md)).
|
Cluster mode runs multiple "regions" behind one HTTP surface and replicates between them over the **real `tidal-net` gRPC transport**. It has two shapes: a **multi-process** mode (`--region`, one process per region, real gRPC peering between siblings, real process/host isolation — shipped in m8p10) and a single-process dev/demo default (all regions in one process over loopback). Since M11 it is genuinely HA: **quorum-acked writes** (`ack=quorum`, m11p3), **automatic election/failover** (m11p4), and **elastic membership** — DNS peers, seed join, online add/remove/replace with snapshot+stream catch-up (m11p5) — all exist. It remains **`--experimental-cluster`-gated**, so the recommended default is still a **single standalone node** (simpler, scales vertically); reach for cluster mode deliberately when you need multi-node availability or read-scale. See the [cluster runbook](../runbooks/cluster.md) and [`k8s/cluster/`](../../k8s/cluster/) for the reference deployment.
|
||||||
|
|
||||||
The mode refuses to start unless you opt in explicitly (`--experimental-cluster` or `TIDAL_ALLOW_EXPERIMENTAL_CLUSTER=1`) and emits a loud `WARN` describing exactly what it is and is not. Cluster mode currently replicates **global signals only** — `user_id`/`creator_id` signal context is dropped on the cluster path so followers stay consistent with the leader's WAL.
|
The mode refuses to start unless you opt in explicitly (`--experimental-cluster` or `TIDAL_ALLOW_EXPERIMENTAL_CLUSTER=1`) and emits a loud `WARN` describing exactly what it is and is not. Cluster mode currently replicates **global signals only** — `user_id`/`creator_id` signal context is dropped on the cluster path so followers stay consistent with the leader's WAL.
|
||||||
|
|
||||||
@ -66,6 +66,12 @@ For everything cluster-specific (topology file, leader promotion, partition/heal
|
|||||||
| `--schema <path>` | — | compiled-in default | Schema/profile YAML. |
|
| `--schema <path>` | — | compiled-in default | Schema/profile YAML. |
|
||||||
| `--topology <path>` | — | compiled-in default | Cluster topology YAML (`regions`, `leader`). See the [cluster runbook](../runbooks/cluster.md). |
|
| `--topology <path>` | — | compiled-in default | Cluster topology YAML (`regions`, `leader`). See the [cluster runbook](../runbooks/cluster.md). |
|
||||||
| `--config-dir <dir>` | `TIDAL_CONFIG` | unset | Directory holding `default-schema.yaml` and `default-cluster.yaml`. |
|
| `--config-dir <dir>` | `TIDAL_CONFIG` | unset | Directory holding `default-schema.yaml` and `default-cluster.yaml`. |
|
||||||
|
| `--region <name>` | `TIDAL_REGION` | unset | Run **only this region** in this process (multi-process mode). Omit for the single-process dev/demo default. |
|
||||||
|
| `--data-dir <dir>` | — | **required (multi-process)** | Persistent data directory. The durable WAL is the replicated log itself, so multi-process mode rejects a node without one. |
|
||||||
|
| `--seed <url>` (repeatable) | — | unset | Seed-join boot (m11p5): contact a running peer's HTTP base URL to learn the roster + assigned id + term and join online as a learner — no topology entry of this node's own required. Still needs `--topology`/`TIDAL_CONFIG` for the behavioral knob blocks. |
|
||||||
|
| `--advertise-grpc <host:port>` | — | unset | This node's **advertised** gRPC address (what siblings dial; DNS-capable). Required with `--seed`. |
|
||||||
|
| `--advertise-http <host:port>` | — | unset | This node's advertised HTTP gateway (what peers forward to). Required with `--seed`. |
|
||||||
|
| `--metrics <addr>` | — | unset | Prometheus `/metrics` bind for a seed-joined node (which has no topology `metrics_addr`). Bind to loopback / cluster-internal only — unauthenticated. |
|
||||||
| `--experimental-cluster` | `TIDAL_ALLOW_EXPERIMENTAL_CLUSTER` | off | Required opt-in. Without it (flag or env `1`/`true`/`yes`), cluster mode refuses to start. |
|
| `--experimental-cluster` | `TIDAL_ALLOW_EXPERIMENTAL_CLUSTER` | off | Required opt-in. Without it (flag or env `1`/`true`/`yes`), cluster mode refuses to start. |
|
||||||
|
|
||||||
### Environment variables (all modes)
|
### Environment variables (all modes)
|
||||||
|
|||||||
@ -90,7 +90,7 @@ All metrics use the `tidaldb_` prefix. Metrics marked with "(feature-gated)" are
|
|||||||
|
|
||||||
**Normal range for `checkpoint_failures_total`:** Should be 0. Any non-zero value means signal durability is at risk -- the hot tier is not being persisted. Investigate storage errors (disk full, I/O errors).
|
**Normal range for `checkpoint_failures_total`:** Should be 0. Any non-zero value means signal durability is at risk -- the hot tier is not being persisted. Investigate storage errors (disk full, I/O errors).
|
||||||
|
|
||||||
**Cluster mode:** per-region replication lag is observable via the cluster HTTP surface, not a Prometheus metric -- poll `GET /cluster/status` and watch each region's `lag_events` (a growing value flags a partitioned or wedged follower). See the [cluster runbook](../runbooks/cluster.md#6-cluster-management-api).
|
**Cluster mode:** per-region replication lag is exported as Prometheus series since m11p1 (`tidaldb_cluster_peer_ship_queue_depth` and `tidaldb_cluster_peer_acked_seqno`, labeled by `peer_shard`; the quorum lag is `tidaldb_cluster_relay_last_seq − tidaldb_cluster_relay_durable_seq`) — see [Cluster Replication](#cluster-replication-feature-gated-m11p1m11p5) below. It is *also* observable via the cluster HTTP surface (`GET /cluster/status`, each region's `lag_events`); a growing value flags a partitioned or wedged follower. See the [cluster runbook](../runbooks/cluster.md#6-cluster-management-api).
|
||||||
|
|
||||||
### Index Health (feature-gated)
|
### Index Health (feature-gated)
|
||||||
|
|
||||||
@ -127,12 +127,12 @@ Index health metrics are refreshed every 10 seconds by the checkpoint thread (3x
|
|||||||
|
|
||||||
**Normal range for `degradation_level`:** Should be `0` during normal operation. Any value > 0 means the load detector has triggered degradation to protect latency. Investigate system load (CPU, memory pressure, I/O saturation).
|
**Normal range for `degradation_level`:** Should be `0` during normal operation. Any value > 0 means the load detector has triggered degradation to protect latency. Investigate system load (CPU, memory pressure, I/O saturation).
|
||||||
|
|
||||||
### Cluster Replication (feature-gated, m11p1)
|
### Cluster Replication (feature-gated, m11p1–m11p5)
|
||||||
|
|
||||||
Emitted only on cluster nodes (the series activate when cluster mode takes the
|
Emitted only on cluster nodes (the series activate when cluster mode takes the
|
||||||
metrics handle; standalone deployments keep their exact metric surface). In
|
metrics handle; standalone deployments keep their exact metric surface). In
|
||||||
multi-process cluster mode the listener binds the topology's per-region
|
multi-process cluster mode the listener binds the topology's per-region
|
||||||
`metrics_addr`.
|
`metrics_addr` (or, for a seed-joined node, the `--metrics` flag).
|
||||||
|
|
||||||
| Metric | Type | Unit | Description |
|
| Metric | Type | Unit | Description |
|
||||||
|:-------|:-----|:-----|:------------|
|
|:-------|:-----|:-----|:------------|
|
||||||
@ -150,6 +150,21 @@ multi-process cluster mode the listener binds the topology's per-region
|
|||||||
| `tidaldb_cluster_peer_ship_batches_total` | counter | count | Per peer: batches shipped. |
|
| `tidaldb_cluster_peer_ship_batches_total` | counter | count | Per peer: batches shipped. |
|
||||||
| `tidaldb_cluster_peer_ship_events_total` | counter | count | Per peer: events shipped. |
|
| `tidaldb_cluster_peer_ship_events_total` | counter | count | Per peer: events shipped. |
|
||||||
| `tidaldb_cluster_peer_ship_failures_total` | counter | count | Per peer: failed batch ship attempts (transient + permanent). |
|
| `tidaldb_cluster_peer_ship_failures_total` | counter | count | Per peer: failed batch ship attempts (transient + permanent). |
|
||||||
|
| `tidaldb_cluster_election_term` (m11p4) | gauge | term | This node's current election term (0 = the pre-election "topology era"). |
|
||||||
|
| `tidaldb_cluster_election_role` (m11p4) | gauge | enum | Election role: `0` follower, `1` pre-candidate, `2` candidate, `3` leader. |
|
||||||
|
| `tidaldb_cluster_elections_started_total` (m11p4) | counter | count | Elections (pre-vote rounds) this node has started. A nonzero `rate()` under a stable cluster flags election churn (flapping links). |
|
||||||
|
| `tidaldb_cluster_leader_changes_total` (m11p4) | counter | count | Leadership changes this node has observed. |
|
||||||
|
| `tidaldb_cluster_divergence_quarantined` (m11p4) | gauge | bool | Divergent-suffix quarantine latch (`1` = fenced from the data plane). Clears only after a genuine reseed (m11p5). |
|
||||||
|
| `tidaldb_cluster_reseed_required` (m11p5) | gauge | bool | Durable reseed-marker latch (`1` = a snapshot reseed is pending the next boot). |
|
||||||
|
| `tidaldb_cluster_snapshot_staged` (m11p5) | gauge | seqno | Seq of the currently-staged snapshot artifact (`0` = none staged). |
|
||||||
|
| `tidaldb_cluster_snapshot_fetches_total` (m11p5) | counter | count | `FetchSnapshot` streams served as the leader-side snapshot source. |
|
||||||
|
| `tidaldb_cluster_snapshot_pin_force_drops_total` (m11p5) | counter | count | Staged-artifact retention pins force-dropped past the hard cap (a dead joiner that never released — alert: a stuck reseed is freezing compaction). |
|
||||||
|
| `tidaldb_cluster_remove_delivery_giveups_total` (m11p5) | counter | count | Removal-delivery graces that expired before the removed peer acked the `Removed` record (the node was down/unreachable during decommission). |
|
||||||
|
|
||||||
|
> **Membership conf-version + learner promotion** are exposed as
|
||||||
|
> `/cluster/status/local` JSON fields (`membership_version`,
|
||||||
|
> `promotion_pending (lag=N)`), not registered Prometheus series — poll the
|
||||||
|
> status surface for scale-up progress and a stuck learner.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -170,6 +185,10 @@ multi-process cluster mode the listener binds the topology's per-region
|
|||||||
| Cluster Quorum Lag | `tidaldb_cluster_relay_last_seq - tidaldb_cluster_relay_durable_seq > 10000` | Critical | A majority of the replica set is not confirming durability (down/partitioned followers, or follower apply throughput exhausted). `ack=quorum` writes will 503; the bodies name the laggards. |
|
| Cluster Quorum Lag | `tidaldb_cluster_relay_last_seq - tidaldb_cluster_relay_durable_seq > 10000` | Critical | A majority of the replica set is not confirming durability (down/partitioned followers, or follower apply throughput exhausted). `ack=quorum` writes will 503; the bodies name the laggards. |
|
||||||
| Quorum Timeouts | `rate(tidaldb_cluster_quorum_timeouts_total[5m]) > 1` | Warning | `ack=quorum` writes are timing out (retryable 503s). Sustained timeouts = a laggard region or an over-budget `replication.quorum_timeout_ms` for the deployment's RTT. Elevated timeouts while `relay_durable_seq` (the commit index) holds steady and followers report healthy = the `ReportApplied` frontier pushes are being lost (packet loss / a pre-m11p3 leader) — followers WARN `applied-frontier report failed` on the first failure of a streak. |
|
| Quorum Timeouts | `rate(tidaldb_cluster_quorum_timeouts_total[5m]) > 1` | Warning | `ack=quorum` writes are timing out (retryable 503s). Sustained timeouts = a laggard region or an over-budget `replication.quorum_timeout_ms` for the deployment's RTT. Elevated timeouts while `relay_durable_seq` (the commit index) holds steady and followers report healthy = the `ReportApplied` frontier pushes are being lost (packet loss / a pre-m11p3 leader) — followers WARN `applied-frontier report failed` on the first failure of a streak. |
|
||||||
| Cluster Write Shedding | `rate(tidaldb_cluster_write_pool_rejections_total[5m]) > 100` | Warning | Sustained 429 shedding on the cluster write path. Raise `write_workers`/capacity or reduce offered write rate. |
|
| Cluster Write Shedding | `rate(tidaldb_cluster_write_pool_rejections_total[5m]) > 100` | Warning | Sustained 429 shedding on the cluster write path. Raise `write_workers`/capacity or reduce offered write rate. |
|
||||||
|
| Election Churn | `rate(tidaldb_cluster_elections_started_total[5m]) > 0.1` | Warning | A node keeps starting elections — flapping links, an over-tight `election.leader_lease_ms`, or a partial partition. Cross-check `tidaldb_cluster_leader_changes_total`. |
|
||||||
|
| Divergence Quarantine | `tidaldb_cluster_divergence_quarantined == 1` | Critical | A node fenced itself from the data plane after detecting a divergent suffix. Since m11p5 it auto-reseeds on its next boot; if the latch persists, the reseed is not completing — check `tidaldb_cluster_reseed_required` and the snapshot path. |
|
||||||
|
| Reseed Pending | `tidaldb_cluster_reseed_required == 1` for `> 10m` | Warning | A node has latched the reseed marker but has not completed a snapshot reseed. Expected briefly after a quarantine or a behind-a-compacted-leader restart; a persistent latch means the snapshot fetch is failing (no reachable leader, capability gate, or staging fault). |
|
||||||
|
| Snapshot Pin Force-Drop | `increase(tidaldb_cluster_snapshot_pin_force_drops_total[1h]) > 0` | Warning | A staged-snapshot retention pin was force-dropped past the hard cap — a joiner started a reseed and never released (died mid-fetch). The dropped pin protects compaction; the stranded joiner must be re-driven or removed. |
|
||||||
|
|
||||||
### Grafana Dashboard Suggestions
|
### Grafana Dashboard Suggestions
|
||||||
|
|
||||||
|
|||||||
@ -37,7 +37,7 @@ A single embeddable database can replace the 6-system content ranking stack by t
|
|||||||
| M8 | Distributed Fabric | Multi-region, multi-tenant replication keeps agent-memory semantics intact | Hosted tidalDB, cloud/edge deployments, shared agent substrate — **✅ COMPLETE**: in-process primitives + multi-node replication over real gRPC + true multi-process cluster mode (one process per region, real process isolation) with full tier-3 UAT (partition injection via TCP-proxy, clock-skew, rolling-upgrade, runbook verification); G1 + G2 resolved. Post-M8 follow-ups: quorum-ack writes, automatic failure detection / leader election |
|
| M8 | Distributed Fabric | Multi-region, multi-tenant replication keeps agent-memory semantics intact | Hosted tidalDB, cloud/edge deployments, shared agent substrate — **✅ COMPLETE**: in-process primitives + multi-node replication over real gRPC + true multi-process cluster mode (one process per region, real process isolation) with full tier-3 UAT (partition injection via TCP-proxy, clock-skew, rolling-upgrade, runbook verification); G1 + G2 resolved. Post-M8 follow-ups: quorum-ack writes, automatic failure detection / leader election |
|
||||||
| M9 | Community Sync & Revocation | Local embeddable profiles can opt into community personalization and safely leave/purge contributions | Community personalization, federated taste graphs, shared feeds — ✅ COMPLETE (2026-06-06) |
|
| M9 | Community Sync & Revocation | Local embeddable profiles can opt into community personalization and safely leave/purge contributions | Community personalization, federated taste graphs, shared feeds — ✅ COMPLETE (2026-06-06) |
|
||||||
| M10 | Governance & Agent Rights | Community rules and agent-scoped permissions control what signals influence ranking | User-owned AI personalization at scale, policy-compliant agents — ✅ COMPLETE (2026-06-06) |
|
| M10 | Governance & Agent Rights | Community rules and agent-scoped permissions control what signals influence ranking | User-owned AI personalization at scale, policy-compliant agents — ✅ COMPLETE (2026-06-06) |
|
||||||
| M11 | Enterprise-Grade Cluster | The multi-process cluster becomes a system of record: fast unified log, quorum-durable, self-healing, horizontally scalable, secured, observable, chaos-tested | Paying-customer cluster deployments — **IN PROGRESS**: m11p1 ✅ + m11p2 ✅ + m11p3 ✅ + m11p4 ✅ (automatic failover: Raft-style election + term fencing + divergence quarantine — closes **G5**; v0.9 "Credible HA" wave complete 2026-06-12); p5–p9 planned in [docs/roadmap-to-cluster.md](../roadmap-to-cluster.md) |
|
| M11 | Enterprise-Grade Cluster | The multi-process cluster becomes a system of record: fast unified log, quorum-durable, self-healing, horizontally scalable, secured, observable, chaos-tested | Paying-customer cluster deployments — **IN PROGRESS**: m11p1 ✅ + m11p2 ✅ + m11p3 ✅ + m11p4 ✅ (automatic failover: Raft-style election + term fencing + divergence quarantine — closes **G5**; v0.9 "Credible HA" wave complete 2026-06-12) + m11p5 ✅ (membership/discovery/elasticity: DNS peers, snapshot+stream reseed, kind-4 membership records, seed join, `k8s/cluster/` — 2026-06-12); p6–p9 planned in [docs/roadmap-to-cluster.md](../roadmap-to-cluster.md) |
|
||||||
|
|
||||||
### Embeddable → Distributed Path
|
### Embeddable → Distributed Path
|
||||||
|
|
||||||
@ -3280,8 +3280,8 @@ Full gap analysis, measured baselines, phase specs, and exit gates live in
|
|||||||
| m11p1 | Replication performance floor: decouple ack from ship, batch + pipeline per-peer shipping, follower group-commit coalescing, group-commit knobs, first `tidaldb_cluster_*` metrics + cluster `/metrics` listener | ✅ **COMPLETE (2026-06-11)** — 4,534 replicated signal-writes/s sustained within SLO on a 3-process localhost cluster (release build; ~50× the ~90/s baseline), replication lag ≤377 events (~80ms) through the full ramp, errors <1%. Leader fsync profiled (`tidaldb_cluster_wal_fsync_us`): macOS F_FULLFSYNC ≈7.4ms mean explains the local write-p99 tail; the ≤50ms p99 sub-gate validates on Linux fdatasync (Ref-A) where the fsync floor is far lower. Ref-A re-run pending infra access. |
|
| m11p1 | Replication performance floor: decouple ack from ship, batch + pipeline per-peer shipping, follower group-commit coalescing, group-commit knobs, first `tidaldb_cluster_*` metrics + cluster `/metrics` listener | ✅ **COMPLETE (2026-06-11)** — 4,534 replicated signal-writes/s sustained within SLO on a 3-process localhost cluster (release build; ~50× the ~90/s baseline), replication lag ≤377 events (~80ms) through the full ramp, errors <1%. Leader fsync profiled (`tidaldb_cluster_wal_fsync_us`): macOS F_FULLFSYNC ≈7.4ms mean explains the local write-p99 tail; the ≤50ms p99 sub-gate validates on Linux fdatasync (Ref-A) where the fsync floor is far lower. Ref-A re-run pending infra access. |
|
||||||
| m11p2 | One replicated log: items/embeddings ride the WAL, delete the HTTP broadcast side channel, implement `StreamSegments` catch-up | ✅ **COMPLETE (2026-06-11)** — the leader's WAL is THE replicated log (stream seqnos = WAL seqnos, restart-surviving); items/embeddings journal as kind-1/2 blob records on the same stream as signals; catch-up is follower-pulled `StreamSegments` over the durable segments (gap-triggered, boot-time, and heal-nudged); the m8p10 HTTP item broadcast + O(items) heal backfill are deleted (both 2026-06-10 bug classes impossible by construction); promote carries a persisted stream baseline. Tier-3 `mp_items_ride_the_log_and_catchup_stream` proves items via leader + follower gateways converge everywhere and a restarted follower self-heals via the stream with no operator verb. See [milestone-11/phase-2.md](milestone-11/phase-2.md). |
|
| m11p2 | One replicated log: items/embeddings ride the WAL, delete the HTTP broadcast side channel, implement `StreamSegments` catch-up | ✅ **COMPLETE (2026-06-11)** — the leader's WAL is THE replicated log (stream seqnos = WAL seqnos, restart-surviving); items/embeddings journal as kind-1/2 blob records on the same stream as signals; catch-up is follower-pulled `StreamSegments` over the durable segments (gap-triggered, boot-time, and heal-nudged); the m8p10 HTTP item broadcast + O(items) heal backfill are deleted (both 2026-06-10 bug classes impossible by construction); promote carries a persisted stream baseline. Tier-3 `mp_items_ride_the_log_and_catchup_stream` proves items via leader + follower gateways converge everywhere and a restarted follower self-heals via the stream with no operator verb. See [milestone-11/phase-2.md](milestone-11/phase-2.md). |
|
||||||
| m11p3 | Quorum-acked writes: `ack=leader\|quorum` (topology default + `x-tidal-ack` override), durable-frontier reports, commit index, retryable-503 timeout semantics, ledger checker | ✅ **COMPLETE (2026-06-11)** — followers push durably-applied frontiers (`ReportApplied`, batch-level, decoupled from ship acks); commit index = k-th largest durable mark, leadership-scoped; `ack=quorum` writes await it asynchronously and 503 with laggard names on budget expiry; every cluster write returns `x-tidal-seq`. Exit gate: 100/100 leader-SIGKILL kill-points with ZERO acknowledged loss (frontier + content proofs on the promoted max-applied survivor); quorum throughput 3,600 signal-writes/s within SLO locally (79% of p1's 4,534/s leader-ack figure, gate ≥50%). Also fixed en route: follower blob applies group-committed (22× item-seed speedup), async quorum waits (thread-per-wait collapsed at 1k rps). See [milestone-11/phase-3.md](milestone-11/phase-3.md). |
|
| m11p3 | Quorum-acked writes: `ack=leader\|quorum` (topology default + `x-tidal-ack` override), durable-frontier reports, commit index, retryable-503 timeout semantics, ledger checker | ✅ **COMPLETE (2026-06-11)** — followers push durably-applied frontiers (`ReportApplied`, batch-level, decoupled from ship acks); commit index = k-th largest durable mark, leadership-scoped; `ack=quorum` writes await it asynchronously and 503 with laggard names on budget expiry; every cluster write returns `x-tidal-seq`. Exit gate: 100/100 leader-SIGKILL kill-points with ZERO acknowledged loss (frontier + content proofs on the promoted max-applied survivor); quorum throughput 3,600 signal-writes/s within SLO locally (79% of p1's 4,534/s leader-ack figure, gate ≥50%). Also fixed en route: follower blob applies group-committed (22× item-seed speedup), async quorum waits (thread-per-wait collapsed at 1k rps). See [milestone-11/phase-3.md](milestone-11/phase-3.md). |
|
||||||
| m11p4 | Failure detection, election, term fencing — closes **G5** | Planned |
|
| m11p4 | Failure detection, election, term fencing — closes **G5** | ✅ **COMPLETE (2026-06-12)** — purpose-built election-only Raft (pre-vote + check-quorum + fenced transfer) over the existing transport, no raft crate: an elected leader's FIRST entry is a replicated kind-3 **term marker**, so `(lastLogTerm, lastLogIndex)` derives from one fsync stream (frontiers compared in the last joined term's STREAM numbering). Hard state `(term, voted_for)` in `data_dir/election_state` (corrupt → refuse boot; lost-with-WAL → forced follower), fsynced before any vote/claim. Term fencing on every RPC; the commit index folds only activation-term reports; a restarted ex-leader boots follower from durable state (the §1.4-1 split-brain incident closed by construction). Divergent suffixes QUARANTINE; promote is a fenced transfer that refuses lagging targets. Exit gates (local tier-3, 3 processes): elections 0.59–0.98s under ack=quorum kill loads with zero acked loss; a restarted partitioned ex-leader accepted 0 writes; 7 link flaps converged at term ≤15. See [milestone-11/phase-4.md](milestone-11/phase-4.md). |
|
||||||
| m11p5 | Membership, discovery, elasticity (DNS, seed join, snapshot + stream catch-up) | Planned |
|
| m11p5 | Membership, discovery, elasticity (DNS, seed join, snapshot + stream catch-up) | ✅ **COMPLETE (2026-06-12)** — `grpc_addr` is now an **advertised** address (hostname or IP) split from an optional `grpc_bind`; `tidal-net`'s peer map retyped `SocketAddr → String` so hyper re-resolves DNS on every reconnect (the pod-rescheduled-onto-a-new-IP case). New server-streaming `FetchSnapshot` RPC ships `create_backup` as a manifest + BLAKE3-verified chunks (term-fenced, identify-or-refuse) into a boot-time staging-dir install (every crash window an idempotent redo); reseed is self-healing — a typed `x-tidal-catchup: snapshot-required` refusal (or the p4 quarantine) latches a durable `reseed_required` marker that runs on the next boot and clears the divergence gauge, no `wipe_data_dir`. Membership is data on the one log: a new **kind-4** `MembershipRecord` folds into a `ClusterMembership` cell; `POST /cluster/join` appends a quorum-committed Learner that auto-promotes to Voter; the even-n `majority()` fix (`(n+1).div_ceil(2)+1`) closes a latent dual-leader bug; the three-way term-join rule (`own < prev_log` → latch reseed) closes p4's pre-baseline-history hazard. Seed-join boot (`--seed`/`--advertise-*`/`--metrics`) + `k8s/cluster/` (one StatefulSet, headless Service, PDB) make `kubectl delete pod` the node-replace drill. Exit-gate mechanics proven by tier-3 `cluster_membership.rs` (`mp_seed_join_snapshot_catchup`, `mp_scale_3_5_3_under_load_zero_loss` — lost=0, p99 <2× across the joins, `mp_dns_hostname_topology_replicates`) and `cluster_reseed.rs`. 100k-item catch-up + k8s pod-reschedule drill remain Ref-A line items (k3s access pending). See [milestone-11/phase-5.md](milestone-11/phase-5.md). |
|
||||||
| m11p6 | Sharding × replication + rebalancing | Planned |
|
| m11p6 | Sharding × replication + rebalancing | Planned |
|
||||||
| m11p7 | Security hardening (mTLS default, rotation, audit log) | Planned |
|
| m11p7 | Security hardening (mTLS default, rotation, audit log) | Planned |
|
||||||
| m11p8 | Observability + operations (complete metric set, self-driving heal, backup/PITR, rolling-upgrade gate) | Seeded in p1 (metrics listener + first series) |
|
| m11p8 | Observability + operations (complete metric set, self-driving heal, backup/PITR, rolling-upgrade gate) | Seeded in p1 (metrics listener + first series) |
|
||||||
|
|||||||
673
docs/planning/milestone-11/phase-5.md
Normal file
673
docs/planning/milestone-11/phase-5.md
Normal file
@ -0,0 +1,673 @@
|
|||||||
|
# m11p5 — Membership, Discovery, Elasticity (COMPLETE — 2026-06-12)
|
||||||
|
|
||||||
|
Phase spec and exit gate: [docs/roadmap-to-cluster.md §4/m11p5](../../roadmap-to-cluster.md).
|
||||||
|
Predecessors: [phase-2.md](phase-2.md) (StreamSegments — the catch-up stream the
|
||||||
|
snapshot resumes into), [phase-3.md](phase-3.md) (quorum commit index — the
|
||||||
|
arithmetic conf-changes mutate), [phase-4.md](phase-4.md) (terms, fencing, the
|
||||||
|
durable-state disciplines, and three carried hazards this phase closes:
|
||||||
|
quarantine-clearing rides reseed, reseeded nodes lack pre-baseline history,
|
||||||
|
pre-baseline data is unreachable through a term's stream).
|
||||||
|
|
||||||
|
**Goal:** nodes are cattle; topology is data, not files. A new node joins by
|
||||||
|
contacting any seed, catches up via snapshot + WAL stream in minutes, and
|
||||||
|
serves quorum; a dead node's replacement is `kubectl delete pod`; addresses
|
||||||
|
are DNS names; membership changes ride the replicated log under the m11p4
|
||||||
|
term machinery.
|
||||||
|
|
||||||
|
> **Design review:** a four-lens adversarial review (safety / crash-recovery /
|
||||||
|
> liveness / compatibility) of the first draft produced **33 findings (9
|
||||||
|
> BLOCKER, 13 MAJOR, 11 MINOR), all folded in below** before implementation.
|
||||||
|
> The blockers that reshaped the design: the even-voter-count `majority()`
|
||||||
|
> arithmetic error (§3.0), the vacuous cross-term conf-change gate and the
|
||||||
|
> baseline-jump record skip (both closed by the activation membership
|
||||||
|
> re-append, §3.2), learner marks poisoning the quorum (§3.3), and two
|
||||||
|
> crash windows in the reseed swap (§2.3).
|
||||||
|
|
||||||
|
## Design (as adopted)
|
||||||
|
|
||||||
|
### 1. DNS peer addresses: the bind/advertise split
|
||||||
|
|
||||||
|
`grpc_addr` becomes an **advertised** address — hostname or IP, validated by
|
||||||
|
the same syntactic `validate_host_port` that `http_addr` already passes
|
||||||
|
(hostnames accepted since m8p10). A new optional per-region `grpc_bind`
|
||||||
|
(SocketAddr) controls the local bind:
|
||||||
|
|
||||||
|
- `grpc_bind` present → bind it.
|
||||||
|
- Absent, `grpc_addr` parses as a literal SocketAddr → bind that (today's
|
||||||
|
behavior, byte-for-byte: every existing topology keeps working).
|
||||||
|
- Absent, `grpc_addr` is a hostname → bind `0.0.0.0:<port from grpc_addr>`.
|
||||||
|
|
||||||
|
`resolve_grpc_addr`'s dual use (own bind + every peer dial) splits: the bind
|
||||||
|
path stays SocketAddr; the peer path stops parsing entirely. `tidal-net`'s
|
||||||
|
`GrpcTransportConfig.peers` retypes from `HashMap<ShardId, SocketAddr>` to
|
||||||
|
`HashMap<ShardId, String>` (host:port); `PeerPool` builds the tonic URI from
|
||||||
|
the string — `Channel::from_shared` with a hostname makes hyper re-resolve
|
||||||
|
DNS on every reconnect, fixing the pod-rescheduled-onto-a-new-IP case the
|
||||||
|
SocketAddr type made structurally impossible. `grpc_server_ready` probes the
|
||||||
|
bind address, substituting `127.0.0.1` for an unspecified bind IP. TLS note:
|
||||||
|
SNI follows the URI host, so DNS peer names require DNS-SAN certs —
|
||||||
|
documented in the `grpc_tls` topology block; no code change.
|
||||||
|
|
||||||
|
This alone kills the per-pod ConfigMap variant: one shared topology file can
|
||||||
|
name every region by its per-pod DNS name while each pod binds `0.0.0.0`.
|
||||||
|
|
||||||
|
**Verification (review finding):** the re-resolution property is the entire
|
||||||
|
point of the retype and `localhost`-based tests cannot regress it. A tier-2
|
||||||
|
test exercises changed-address reconvergence where the platform permits
|
||||||
|
(dual-family `localhost` rebind), and the **k8s pod-reschedule drill (delete
|
||||||
|
pod, new pod IP, ship/stream traffic resumes with no peer restarts) is a
|
||||||
|
required line item of the exit-gate evidence**, not an incidental.
|
||||||
|
|
||||||
|
### 2. Snapshot transfer (`FetchSnapshot`): the reseed and joiner path
|
||||||
|
|
||||||
|
**Artifact = `TidalDb::create_backup`** (tidal/src/db/backup.rs:211) with
|
||||||
|
three review-driven hardenings:
|
||||||
|
|
||||||
|
- the WAL-checkpoint-marker write into the copy becomes **fatal** (a staged
|
||||||
|
artifact with a stale marker double-counts signals on the joiner);
|
||||||
|
- `create_backup` also refreshes the **replication-HWM row** in the same
|
||||||
|
step as the ledger checkpoint (the copied row otherwise understates the
|
||||||
|
artifact by up to one 30 s cycle → re-folds on the joiner);
|
||||||
|
- the snapshot-staging variant skips the non-fatal text-index flushes
|
||||||
|
(derived state, rebuilt on open) to shorten the quiesce window.
|
||||||
|
|
||||||
|
The leader stages the artifact under `<data_dir>/snapshots/` and serves it
|
||||||
|
as a new server-streaming RPC in the `WalShipping` service:
|
||||||
|
|
||||||
|
```
|
||||||
|
rpc FetchSnapshot(SnapshotRequest) returns (stream SnapshotChunk)
|
||||||
|
```
|
||||||
|
|
||||||
|
- `SnapshotRequest { shard_id, from_seqno, term }` — `from_seqno` is the
|
||||||
|
puller's frontier+1. The handler answers a **no-snapshot-needed** header
|
||||||
|
chunk when the WAL can still serve `from_seqno` (the joiner just streams),
|
||||||
|
else streams: manifest chunk (snapshot seq, file list with size + BLAKE3,
|
||||||
|
term, leader_region) then file chunks (path, offset, bytes), term-stamped
|
||||||
|
and term-fenced exactly like `StreamSegments` (same-term puller; stale
|
||||||
|
source steps down; puller gates every chunk).
|
||||||
|
- **Excluded from the manifest** (node-identity / node-local files):
|
||||||
|
`election_state`, `stream_baseline`, `membership` (the §3.6 cache),
|
||||||
|
`tidaldb.lock`, `snapshots/`, the reseed marker. Everything else ships
|
||||||
|
byte-identical (TSEG segments must arrive bit-exact or the joiner's open
|
||||||
|
refuses — identify-or-refuse end to end).
|
||||||
|
- **Caching + single-flight:** one staged artifact at a time; concurrent
|
||||||
|
joiners share it. A second `FetchSnapshot` arriving while staging is
|
||||||
|
mid-flight gets a **retryable** `UNAVAILABLE` (never
|
||||||
|
`FAILED_PRECONDITION`, which would mis-route it into the reseed class).
|
||||||
|
An artifact is reusable while the live WAL still covers
|
||||||
|
`artifact_seq + 1` (else refresh).
|
||||||
|
- **Quiesce honesty (review finding):** every `create_backup` 429s all
|
||||||
|
signal writes for checkpoint + flush + copy (seconds at 100k items).
|
||||||
|
Gate writers retry 429 honoring `retry_after_ms` — a retried-then-acked
|
||||||
|
write is neither lost nor an SLO violation (the established busy-writer
|
||||||
|
harness posture). The measured window is recorded in the gate evidence.
|
||||||
|
|
||||||
|
**2.1 Retention pin (review-corrected).** The pin is taken at backup
|
||||||
|
**start**, at the captured seq S, *before* any copying — a pin installed
|
||||||
|
after staging cannot protect the copy window from the 30 s checkpoint
|
||||||
|
thread. Pin semantics: online compaction must preserve the segment chain
|
||||||
|
covering `S + 1` onward (the pin clamps the floor such that the segment
|
||||||
|
*containing* `S + 1` survives — an off-by-one that deletes the straddling
|
||||||
|
segment is data loss inside the artifact; unit-tested). The pin holds
|
||||||
|
while: the artifact is staged, any `FetchSnapshot` stream is active, and
|
||||||
|
for a per-consumer grace until that puller's first successful
|
||||||
|
`StreamSegments` pull from `S + 1` (bounded by a hard cap + loud metric so
|
||||||
|
a dead joiner cannot pin retention forever). The reuse TTL
|
||||||
|
(`snapshot_artifact_ttl_ms`) governs artifact refresh only — **never**
|
||||||
|
the pin of an active consumer; consecutive reseed loops per peer are
|
||||||
|
counted and alerted at ≥ 2.
|
||||||
|
|
||||||
|
**2.2 Install is a boot-time operation** — no live data-dir swap under a
|
||||||
|
running engine, ever. The pre-open step runs **only** on (a) seed-join
|
||||||
|
boots and (b) `reseed_required`-marker boots — plain topology boots never
|
||||||
|
contact a peer before serving (boot-order independence at cold start is
|
||||||
|
load-bearing; a behind-a-compacted-leader restart is detected at runtime
|
||||||
|
per §2.4 and reseeds on the *next* boot). A marker boot that cannot
|
||||||
|
complete the handshake within a bounded window **falls back to opening the
|
||||||
|
existing data dir** — degraded, marker latched, quarantine fence intact,
|
||||||
|
**voting enabled** — because the reseed needs a leader and the leader may
|
||||||
|
need this node's vote (review finding: reseed-blocks-voting deadlocks the
|
||||||
|
cluster). Fresh joiners have nothing to fall back to and nothing to vote
|
||||||
|
with; they retry the seed loop indefinitely with bounded backoff.
|
||||||
|
|
||||||
|
**2.3 The swap protocol (review-corrected ordering).** Fetch into a sibling
|
||||||
|
staging dir, then:
|
||||||
|
|
||||||
|
1. Verify every file's BLAKE3 + manifest completeness.
|
||||||
|
2. **Copy the node's own identity files INTO staging**: `election_state`
|
||||||
|
(vote safety, §2.5) and `membership` cache — *before* the sentinel.
|
||||||
|
3. Write the `COMPLETE` sentinel into staging; fsync.
|
||||||
|
4. `rename(data_dir → data_dir.discard)`,
|
||||||
|
`rename(staging → data_dir)`, fsync parent, delete `.discard`.
|
||||||
|
|
||||||
|
**Filesystem constraint:** the swap renames `data_dir` itself, so `data_dir`
|
||||||
|
must not be a filesystem/volume mount root — staging and `.discard` live in
|
||||||
|
its parent, same filesystem (`EXDEV`/permission failures surface loudly at
|
||||||
|
reseed time, never silently). The k8s cluster manifests therefore mount the
|
||||||
|
PVC at `/data` and set `--data-dir /data/db`. Leader-side staging has the
|
||||||
|
inverse problem: it lives *inside* the data dir (`<data_dir>/snapshots/`) so
|
||||||
|
it stays on the PVC, which means `create_backup`'s recursive copy must
|
||||||
|
**exclude** it (along with the identity files) or it would copy itself.
|
||||||
|
|
||||||
|
Boot-time recovery (runs **before** `ElectionStore` classification — the
|
||||||
|
review found that classifying first re-opens restart amnesia):
|
||||||
|
staging-without-`COMPLETE` → delete staging, retry/fall back;
|
||||||
|
staging-with-`COMPLETE` + `data_dir` present → redo step 4 from the top;
|
||||||
|
staging-with-`COMPLETE` + `data_dir` absent (the mid-rename crash — the
|
||||||
|
window where a naive boot would classify `Fresh` at term 0 and re-vote) →
|
||||||
|
complete the rename, then classify; stray `.discard` → delete. Every
|
||||||
|
window is idempotent redo; the identity files travel inside staging so
|
||||||
|
there is no instant at which the canonical path lacks them post-swap.
|
||||||
|
|
||||||
|
**2.4 Runtime detection → durable marker, not live surgery.** A *running*
|
||||||
|
follower that hits a **typed** snapshot-required refusal (see below) — or
|
||||||
|
the m11p4 divergence quarantine — durably latches `reseed_required`
|
||||||
|
(ElectionStore file discipline: magic, version, checksum, tmp + fsync +
|
||||||
|
rename + dir fsync), surfaces `reseed_required: true` in
|
||||||
|
`/cluster/status/local` plus a `tidaldb_cluster_reseed_required` gauge,
|
||||||
|
and keeps serving degraded (the 30 s retry timer keeps its standing
|
||||||
|
wake-up). The reseed executes on the next boot. `POST /cluster/reseed`
|
||||||
|
sets the marker on demand; `replication.reseed_self_restart: true`
|
||||||
|
(default **false**; set in the k8s manifests) drains and exits cleanly
|
||||||
|
once the marker latches — **refused** (loudly, in status + gauge) when the
|
||||||
|
node's local view shows the remaining voters cannot sustain quorum without
|
||||||
|
it (review finding: self-restart during a 2-voter window is total write
|
||||||
|
unavailability). Quarantine clearing (the p4 carried hazard): quarantine
|
||||||
|
latches the marker; a successful reseed boot clears the quarantine latch
|
||||||
|
and `tidaldb_cluster_divergence`.
|
||||||
|
|
||||||
|
**The three-way term-join rule (found by the tier-3 gate, not the review).**
|
||||||
|
The first reseed drill exposed that a follower behind at a leadership change
|
||||||
|
never *asks* for its missing range: the term-join baseline jump advances its
|
||||||
|
frontier past pre-baseline history with `lag=0` — silently missing data,
|
||||||
|
exactly p4's carried hazard, with nothing to fire the snapshot-required
|
||||||
|
refusal. Detection cannot use the baseline (cross-numbering; p4 as-built
|
||||||
|
#2); it uses the comparison the join check already makes. The heartbeat
|
||||||
|
carries the leader's **election-time position in the previous stream's
|
||||||
|
numbering** (`prev_log`); the join check becomes three-way:
|
||||||
|
|
||||||
|
- `own > prev_log` → divergent suffix → **quarantine** (existing, p4);
|
||||||
|
- `own < prev_log` → the node lacks `(own, prev_log]` of the previous
|
||||||
|
stream, which is pre-baseline in the new stream and will never ship →
|
||||||
|
**latch `reseed_required`** (new); the vote restriction makes this exact:
|
||||||
|
an elected leader's position ≥ every granter's, so a strictly-smaller
|
||||||
|
position is genuinely missing committed-era history;
|
||||||
|
- `own == prev_log` (or `tail_term == T`, the within-term rejoin) → clean.
|
||||||
|
|
||||||
|
A snapshot-installed node joins clean by construction: its WAL is the
|
||||||
|
leader's copy, so its `tail_term` equals the leader's term. Two corollaries
|
||||||
|
from the same drill: the install boot must issue its post-install catch-up
|
||||||
|
pull toward the **discovered** leader (the boot self-heal targets the boot
|
||||||
|
topology leader — which can be the node itself), and the `FetchSnapshot`
|
||||||
|
`needed` decision must be **baseline-aware** (`needed = from_seqno ≤
|
||||||
|
stream_baseline OR from_seqno < earliest WAL seq`) — a "WAL still covers
|
||||||
|
it" answer is a lie when the stream clamp will never serve at or below the
|
||||||
|
baseline, and it loops the marker boot forever.
|
||||||
|
|
||||||
|
**Typed refusals (review finding — the conflation hazard):** today all
|
||||||
|
three `StreamSegments` refusal classes are `FAILED_PRECONDITION`, and a
|
||||||
|
term-mismatch during an ordinary election must NOT latch reseed markers
|
||||||
|
fleet-wide. The refusal gains structured trailer metadata
|
||||||
|
(`x-tidal-catchup: snapshot-required | rejoin | stepping-down`); the
|
||||||
|
marker latches **only** on `snapshot-required`. Pre-p5 sources emit no
|
||||||
|
trailer → no latch (conservative).
|
||||||
|
|
||||||
|
**2.5 Vote safety across reseed.** The node's own `election_state` (term,
|
||||||
|
voted_for) survives the swap *inside staging* (§2.3 step 2) — it is the
|
||||||
|
node's promise "I voted for X in term T"; wiping it would allow a re-vote
|
||||||
|
in an already-voted term (two leaders in one term). A fresh joiner has
|
||||||
|
none — it never voted. A **corrupt** `election_state` refuses boot even
|
||||||
|
with a reseed marker latched (a reseed does not restore term knowledge;
|
||||||
|
the m11p4 rule stands).
|
||||||
|
|
||||||
|
**2.6 Post-open seeding (review-corrected durability).** The install boot,
|
||||||
|
**before starting the receiver, transport serving, or any pull**: seed
|
||||||
|
`applied_seqno(leader_shard) = the installed artifact's recovered WAL
|
||||||
|
tail` (valid at the install instant only — own-WAL numbering diverges from
|
||||||
|
stream numbering as soon as applies begin; p4 as-built #1), then
|
||||||
|
**synchronously persist the replication-state checkpoint**, then delete
|
||||||
|
the install sentinel, then start replication. A crash anywhere before the
|
||||||
|
sentinel delete finds the WAL unchanged (no receiver ran) and re-derives
|
||||||
|
the same seed idempotently. The copied HWM row's other-shard entries are
|
||||||
|
kept (true for any copy-holder once §2's `create_backup` refreshes the row
|
||||||
|
in-step). `wal_term_mark` recovers from the copied log's kind-3 markers by
|
||||||
|
construction, so the node's `LogPosition` is consistent in the stream's
|
||||||
|
numbering with no new bookkeeping.
|
||||||
|
|
||||||
|
**2.7 Fresh-joiner term sequencing.** A seed-joiner learns `(term, leader)`
|
||||||
|
from the join response, persists `election_state {term}` **before**
|
||||||
|
pulling (persist-before-act), and stamps the snapshot fetch and subsequent
|
||||||
|
stream pulls with that term. The boot-time loop iterates
|
||||||
|
(seeds ∪ cached membership) → poll `/cluster/status` for the current
|
||||||
|
leader → handshake → fetch, with bounded backoff and indefinite
|
||||||
|
persistence, **re-resolving leadership after every aborted stream** (an
|
||||||
|
election mid-fetch aborts on the term fence; the loop re-discovers and
|
||||||
|
re-stamps — review finding: without re-discovery the joiner retries a
|
||||||
|
deposed source forever). "Backup already in progress" maps into the same
|
||||||
|
retry loop. Process exit is reserved for unrecoverable config errors —
|
||||||
|
crash-loop is never the retry mechanism.
|
||||||
|
|
||||||
|
### 3. Membership as data: kind-4 records on the one log
|
||||||
|
|
||||||
|
**3.0 Prerequisite arithmetic fix (review BLOCKER, exists today).**
|
||||||
|
`ElectionConfig::majority()` is `peers.len()/2 + 1` — correct at n=3,
|
||||||
|
**wrong for every even voter count**: n=4 → 2-of-4 (disjoint vote quorums
|
||||||
|
{A,B} and {C,D} elect two leaders in one term), n=2 → 1-of-2 (a follower
|
||||||
|
self-elects with zero RPCs while check-quorum keeps the old leader alive).
|
||||||
|
`CommitIndex` already uses the correct `div_ceil` form — the two formulas
|
||||||
|
in one subsystem disagree. p5 makes even sizes mandatory transit states
|
||||||
|
(3→4→5→4→3), so this lands **first**, with even-n property tests, before
|
||||||
|
any reconfigure work: `majority() = (peers.len() + 1)/2 + 1` (true
|
||||||
|
`floor(n/2)+1` over the full voter set).
|
||||||
|
|
||||||
|
A **`MembershipRecord`** is a new WAL blob kind (kind-4, beside kind-0
|
||||||
|
signals, kind-1/2 item/embedding blobs, kind-3 term markers), journaled by
|
||||||
|
the leader, replicated through the normal stream, folded by followers into a
|
||||||
|
`ClusterMembership` cell (the `WalTermMark` pattern: recovered from the WAL
|
||||||
|
at boot, advanced on apply, single-lock value):
|
||||||
|
|
||||||
|
```
|
||||||
|
MembershipRecord {
|
||||||
|
version: u64, // monotonic conf version; latest record wins
|
||||||
|
term: u64, // the appending leadership
|
||||||
|
members: Vec<MemberEntry {
|
||||||
|
id: u16, // PERMANENT — never renumbered, never reused
|
||||||
|
name: String,
|
||||||
|
grpc_addr: String, // advertised, DNS-capable
|
||||||
|
http_addr: String,
|
||||||
|
role: Voter | Learner | Removed, // tombstones keep ids burned
|
||||||
|
}>
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Records carry the FULL membership (not deltas): recovery folds the latest
|
||||||
|
record at-or-below the durable frontier, no merge logic. **Membership
|
||||||
|
epoch 0 = the topology file** — a cluster with no kind-4 record behaves
|
||||||
|
byte-for-byte as today. The first record snapshots the topology-derived
|
||||||
|
membership (ids = the existing positional ids, preserved) plus the change.
|
||||||
|
|
||||||
|
**3.1 Capability gating (review finding — the brick hazard).** A kind-4
|
||||||
|
record shipped to a pre-p5 follower is an unknown batch kind →
|
||||||
|
`WalError::Corruption` → the receiver's torn-state halt latch, **permanent
|
||||||
|
across restarts** (boot self-heal re-pulls the same record). The m11p4
|
||||||
|
kind-3 precedent does NOT transfer: term markers were self-gated by the
|
||||||
|
vote quorum needing upgraded binaries; kind-4 needs only one upgraded
|
||||||
|
leader plus one verb — and auto-promotion appends records autonomously.
|
||||||
|
Therefore: `HeartbeatResponse` and `ReportApplied` gain a `capabilities`
|
||||||
|
bit-field (proto3 zero-default = pre-p5 = incapable), and the leader
|
||||||
|
**refuses `JoinCluster` and every conf-change until all current voters
|
||||||
|
have reported kind-4 capability**. The failure mode is stated honestly in
|
||||||
|
runbook §8: a kind-4 record delivered to a pre-p5 follower halts its
|
||||||
|
receiver until binary upgrade; both-followers-halted = quorum-write
|
||||||
|
outage. Downgrade rule (kind-3 precedent verbatim): once any kind-4 record
|
||||||
|
is in a node's WAL, downgrade below p5 requires a reseed.
|
||||||
|
|
||||||
|
**3.2 The activation membership record (review BLOCKER ×2 — this is the
|
||||||
|
linchpin).** On every leadership activation, immediately after the kind-3
|
||||||
|
term marker, the new leader **re-appends its full current membership as a
|
||||||
|
fresh kind-4 record** (the Raft no-op-entry analogue, adapted to the
|
||||||
|
baseline-jump world). This single rule closes two blockers at once:
|
||||||
|
|
||||||
|
- *The vacuous gate:* `CommitIndex::activate` resets `committed` to the
|
||||||
|
new leader's baseline, so "commit index ≥ record seq" is trivially true
|
||||||
|
for every pre-baseline record — and pre-baseline records are
|
||||||
|
structurally unshippable (the stream clamp). The one-at-a-time gate
|
||||||
|
therefore requires **same-term quorum commitment of the activation
|
||||||
|
record** (and of each subsequent change), evaluated from
|
||||||
|
`update_peer_for_term` folds — never from the activation-reset
|
||||||
|
`committed()`.
|
||||||
|
- *The baseline-jump skip:* a follower behind at a transfer jumps its
|
||||||
|
frontier over any kind-4 record the old term committed, with no gap, no
|
||||||
|
signal, while staying electable under a stale roster. The activation
|
||||||
|
record sits **above** the new baseline, so every joiner of the term
|
||||||
|
receives the current roster in-stream before any same-term traffic.
|
||||||
|
|
||||||
|
**3.3 Conf-change discipline (Raft single-server changes):**
|
||||||
|
|
||||||
|
- **One at a time:** the leader refuses a new change until the prior
|
||||||
|
record's seq is same-term quorum-committed (§3.2 predicate). Majorities
|
||||||
|
of consecutive single-change configs overlap; the gate's integrity
|
||||||
|
across leadership changes is exactly what §3.2 restores.
|
||||||
|
- **Join → Learner → Voter:** `POST /cluster/join {name, grpc_addr,
|
||||||
|
http_addr}` on any node forwards to the leader, which assigns
|
||||||
|
`id = max(all ids ever) + 1`, appends a Learner record, and **answers
|
||||||
|
only after that record is quorum-committed** (bounded wait → retryable
|
||||||
|
503; review finding: answering pre-commit strands the joiner invisibly
|
||||||
|
when the leader dies). Joins are **idempotent by name**: a re-join from
|
||||||
|
a known member returns its existing id and current role, appending
|
||||||
|
nothing. The response carries membership, current term, leader
|
||||||
|
addresses, and the assigned id.
|
||||||
|
- **Learner marks (review BLOCKER):** the role-blind `CommitIndex` must
|
||||||
|
not see learner marks — two learners "committing" a write no voter
|
||||||
|
holds is acked-write loss. `CommitIndex` becomes role-aware: voter
|
||||||
|
marks feed the k-th-largest selection; learner marks are tracked in a
|
||||||
|
side map (promotion input, transfer-wait input) and **never** count
|
||||||
|
toward `needed`.
|
||||||
|
- **Auto-promotion is a standing leader duty** derived solely from the
|
||||||
|
applied `ClusterMembership` — re-armed on every leadership activation
|
||||||
|
and on every membership apply, evaluated on commit-index publishes
|
||||||
|
(review finding: a duty anchored to the join handler dies with the
|
||||||
|
joining-era leader, leaving a permanent learner). Promotion fires when
|
||||||
|
the learner's durable mark is within `learner_promote_lag` of
|
||||||
|
`flushed_seq` **or** has stayed within one ship-round for K consecutive
|
||||||
|
evaluations (the Raft "rounds stop shrinking" criterion — a fixed
|
||||||
|
distance alone starves under sustained load). A `promotion_pending
|
||||||
|
(lag=N)` status field + metric make a stuck scale-up diagnosable.
|
||||||
|
- **Remove:** an operator verb appends a `Removed` record (one at a
|
||||||
|
time, quorum-commit-gated like every change). The removed peer's ship
|
||||||
|
cell is retired **only after the record is quorum-committed AND
|
||||||
|
delivered to (or acked by) the removed peer**, with a bounded give-up
|
||||||
|
(review finding: retiring on append means the removed node never
|
||||||
|
learns, never stops campaigning, and zombie-serves as Ready).
|
||||||
|
Heartbeat/vote/pull refusals to a removed member carry a typed
|
||||||
|
`removed` signal that flips its readiness to 503, suppresses
|
||||||
|
campaigning, and is exempt from the reseed marker. Its id is burned.
|
||||||
|
- **Effective-set switching:** each node's effective peer sets derive
|
||||||
|
from its latest APPLIED record (leader: on append). The four
|
||||||
|
construction-frozen peer-set copies become mutable behind **one fenced
|
||||||
|
reconfigure path** executed inside a single membership-apply critical
|
||||||
|
section — the sets can never disagree about the roster:
|
||||||
|
- `CommitIndex::reconfigure(voters, learners)` — resize marks +
|
||||||
|
`needed` under the index's own lock. In-flight `ack=quorum` waits are
|
||||||
|
**re-evaluated against the new config**, not failed (review finding:
|
||||||
|
epoch-bump-as-Demoted on every conf-change is an availability dip
|
||||||
|
with wrong error semantics); a shrink may satisfy waiters instantly.
|
||||||
|
Unknown-peer reports stop being silently dropped: a report from a
|
||||||
|
known learner records its side-map mark; a report from an unknown id
|
||||||
|
logs at WARN with a counter metric.
|
||||||
|
- `ShipQueue::{add_peer, remove_peer}` — spawn/retire per-peer sender
|
||||||
|
cells and threads at runtime (removal per the delivery rule above).
|
||||||
|
- `PeerPool::{add_peer, remove_peer}` — peers map behind a RwLock;
|
||||||
|
channels are lazy; DNS strings mean no resolution at insert.
|
||||||
|
- `ElectionState::reconfigure(voters)` — a new pure-machine input:
|
||||||
|
recompute `majority()` from the post-change voter set, resize
|
||||||
|
`peer_ack`, and **clear in-flight prevote/vote grant sets** (review
|
||||||
|
finding: grants from just-removed voters must not count against the
|
||||||
|
resized majority). The driver's `peer_shards` and the node's HTTP
|
||||||
|
tables update in the same apply step.
|
||||||
|
- **Election interaction:** voters = `role == Voter` in the latest
|
||||||
|
applied record. Learners never campaign — enforced as a **gate in the
|
||||||
|
state machine** (auto-election suppressed while not a voter), not a
|
||||||
|
comment (the review found p4's quarantine election-suppression is
|
||||||
|
comment-only; that gap is verified and fixed in-phase with a unit
|
||||||
|
test). A node that hasn't applied the newest record may transiently
|
||||||
|
refuse a legitimate candidate — the next timeout retries; safety is
|
||||||
|
the overlap argument, liveness is the retry.
|
||||||
|
|
||||||
|
**3.4 Seed-join boot** (`--seed http://host:port`, repeatable): the joiner
|
||||||
|
skips `validate_multiproc`'s "every region declared" gate — its identity is
|
||||||
|
`--region <name>` + advertised addresses from new flags/env
|
||||||
|
(`--advertise-grpc`, `--advertise-http`, `--metrics`). It runs the §2.7
|
||||||
|
loop, persists the returned membership to the durable local cache, persists
|
||||||
|
the term, then proceeds through the normal boot with the fetched roster
|
||||||
|
(snapshot install per §2 when needed). A restart boots from the cache
|
||||||
|
without the seed.
|
||||||
|
|
||||||
|
**3.5 Knob source for seed boots (review finding).** A bare `--seed` boot
|
||||||
|
with no local config would silently fall back to the compiled-in
|
||||||
|
`default-cluster.yaml` — wrong ack default, wrong quorum timeout, wrong
|
||||||
|
election timing, no metrics listener, no TLS material. Rule: **a `--seed`
|
||||||
|
boot still requires the local topology/config file for the behavioral knob
|
||||||
|
blocks** (`replication:`, `wal:`, `election:`, `timeouts:`, `grpc_tls`) —
|
||||||
|
the k8s manifests already mount the shared bootstrap ConfigMap on every
|
||||||
|
pod including N≥3, so this costs nothing there — and a bare `--seed` with
|
||||||
|
neither `--topology` nor `TIDAL_CONFIG` **refuses to boot** naming the
|
||||||
|
rule. The `regions:` list in that file is ignored for the roster (the
|
||||||
|
join response is the roster); the C2 election-timing validation runs on
|
||||||
|
the knob blocks as always. The joiner's metrics listener comes from
|
||||||
|
`--metrics` (new flag, mirroring standalone's).
|
||||||
|
|
||||||
|
**3.6 Durable membership cache** (`data_dir/membership`, ElectionStore file
|
||||||
|
discipline: magic, version, checksum, tmp+fsync+rename+dir-fsync).
|
||||||
|
Precedence: the **WAL-recovered `ClusterMembership` cell wins** over the
|
||||||
|
cache at open (the cache exists for the pre-open boot loop — seed lists,
|
||||||
|
leader discovery — not as a second source of roster truth); the cache is
|
||||||
|
rewritten from the cell after every applied record. It is excluded from
|
||||||
|
snapshot manifests and survives the reseed swap inside staging (§2.3).
|
||||||
|
|
||||||
|
**3.7 Mixed-version rule:** §3.1's capability gate makes "complete the
|
||||||
|
binary upgrade before the first conf-change" structurally enforced, not
|
||||||
|
operator discipline. Pre-p5 peers answer `Unimplemented` to
|
||||||
|
`JoinCluster`/`FetchSnapshot`; the joiner reports it loudly and retries the
|
||||||
|
next seed.
|
||||||
|
|
||||||
|
### 4. Kubernetes reference: one StatefulSet
|
||||||
|
|
||||||
|
New `k8s/cluster/` kustomize set beside the standalone one. **Naming
|
||||||
|
(review finding — the lineages must not collide):** the cluster set lives
|
||||||
|
in its own namespace `tidaldb-cluster` with StatefulSet `tidaldb`, Services
|
||||||
|
`tidaldb-peers` (headless, `publishNotReadyAddresses: true`) and `tidaldb`
|
||||||
|
(client-facing, readiness-gated); the two kustomize sets are mutually
|
||||||
|
exclusive per namespace. **Secret shape:** `tidaldb-credentials` /
|
||||||
|
`TIDAL_API_KEY` (the stress/Ref-A lineage — the in-repo stress Jobs are the
|
||||||
|
exit-gate harness and already use it); the stress Jobs' literal-ClusterIP
|
||||||
|
`--target`s move to the new DNS names in this phase.
|
||||||
|
|
||||||
|
- **One StatefulSet**, `replicas: 3`, podManagementPolicy `Parallel`,
|
||||||
|
`TIDAL_REGION` from `POD_NAME` (fieldRef), args
|
||||||
|
`cluster --listen 0.0.0.0:9500 --data-dir /data ...`, gRPC
|
||||||
|
containerPort, topologySpreadConstraints.
|
||||||
|
- **Bootstrap topology ConfigMap** — ONE file shared by all pods (per-pod
|
||||||
|
DNS advertised addresses + `0.0.0.0` binds), naming the initial 3 regions
|
||||||
|
as `tidaldb-{0,1,2}.tidaldb-peers.tidaldb-cluster.svc.cluster.local`.
|
||||||
|
Scaling past 3 does NOT edit it: pod N ≥ 3 boots with
|
||||||
|
`--seed http://tidaldb-peers...` + the same mounted file for knob blocks
|
||||||
|
(§3.5) and joins as a learner.
|
||||||
|
- **Readiness (review-pinned predicate):** `converged :=` the boot
|
||||||
|
catch-up pull has completed at least once AND `lag_events ≤
|
||||||
|
learner_promote_lag` (hysteresis — **never** `lag == 0`, which an
|
||||||
|
open-loop load keeps perpetually false); `joiner :=` this boot installed
|
||||||
|
a snapshot or seed-joined with a fresh data dir (derivable at boot, no
|
||||||
|
new state). 503 while quarantined, removed, or a joiner-boot has not yet
|
||||||
|
first-converged (sticky-ready after). **A restarted existing voter is
|
||||||
|
Ready on today's terms** — no regression for PVC-retained restarts. The
|
||||||
|
predicate is recorded in the runbook so probe behavior is diagnosable.
|
||||||
|
- **PDB** `maxUnavailable: 1`; `reseed_self_restart: true`; rolling node
|
||||||
|
replace is `kubectl delete pod` (PVC retained → boot catch-up) or PVC
|
||||||
|
delete + pod delete (fresh reseed via snapshot).
|
||||||
|
- Scale-down drill: remove verb first, then `kubectl scale --replicas`,
|
||||||
|
lowest-ordinal-last.
|
||||||
|
|
||||||
|
### 5. What goes where
|
||||||
|
|
||||||
|
| Crate | Work |
|
||||||
|
|---|---|
|
||||||
|
| `tidal` | `majority()` even-n fix + property tests (FIRST); kind-4 `MembershipRecord` encode/decode/recover/apply + `ClusterMembership` cell; role-aware `CommitIndex` (`reconfigure`, learner side-map, waiter re-evaluation, WARN-counter for unknown reporters); `ShipQueue::{add_peer,remove_peer}`; `ElectionState::reconfigure` + learner campaign gate (+ verify/fix the p4 quarantine campaign gate); compaction retention pin (straddling-segment-safe, unit-tested); `create_backup` hardenings (fatal marker, HWM refresh in-step, staging variant skipping text flush) |
|
||||||
|
| `tidal-net` | proto: `FetchSnapshot`/`SnapshotChunk`, `JoinCluster`, `capabilities` on `HeartbeatResponse`/`AppliedReport`; typed catch-up refusal trailer (`x-tidal-catchup`); `SnapshotSource` trait (late-bound) + server handler (StreamSegments-shaped); standalone snapshot-fetch client + `PeerPool` verbs; `peers` retype to `String` + dynamic add/remove; changed-address reconvergence test |
|
||||||
|
| `tidal-server` | bind/advertise split; boot-time install (§2.2 scope, §2.3 swap + recovery, §2.5/§2.6 ordering); seed-join boot loop (§2.7) + flags (`--seed`, `--advertise-*`, `--metrics`) + §3.5 knob-source rule; membership runtime (one fenced apply path; activation record; capability gate; auto-promotion duty; removal delivery); `/cluster/join`, `/cluster/members` (+remove), `/cluster/reseed` verbs; reseed marker + quarantine wiring + self-restart quorum refusal; readiness predicate; metrics; status fields |
|
||||||
|
| `k8s/` | `k8s/cluster/` per §4; stress-Job retargeting |
|
||||||
|
| tests | unit: even-n majority properties, record/store round-trips, reconfigure paths (incl. grant-set clearing, learner marks, waiter re-evaluation), retention-pin straddle, swap-recovery windows, topology DNS derivation table; tidal-net sockets: snapshot stream (fake-source), join RPC, capability gate, typed refusal, changed-address; tier-3: `mp_seed_join_snapshot_catchup` (vs a compacted leader), reseed drill (quarantine → marker → restart → converged, gauges cleared, no `wipe_data_dir`), DNS-hostname topology + chaos, `mp_scale_3_5_3_under_load_zero_loss` (ledger invariants, 429-retrying writers, p99 probes) |
|
||||||
|
|
||||||
|
### 6. Configuration
|
||||||
|
|
||||||
|
| Knob | Default | Meaning |
|
||||||
|
|---|---|---|
|
||||||
|
| `regions[].grpc_bind` | derived (§1) | local gRPC bind when `grpc_addr` is a DNS name |
|
||||||
|
| `replication.reseed_self_restart` | false | drain + clean exit once `reseed_required` latches (k8s: true); refused when remaining voters can't sustain quorum |
|
||||||
|
| `replication.snapshot_artifact_ttl_ms` | 600000 | staged-artifact reuse window (never the active-consumer pin, §2.1) |
|
||||||
|
| `replication.learner_promote_lag` | 1024 | promotion distance; also the readiness hysteresis threshold (§4) |
|
||||||
|
| CLI `--seed <url>` (repeatable), `--advertise-grpc`, `--advertise-http`, `--metrics` | — | seed-join boot (requires the local knob file, §3.5) |
|
||||||
|
|
||||||
|
## Exit gate (from the roadmap, restated as tests)
|
||||||
|
|
||||||
|
1. **Seed join + snapshot catch-up:** a fresh node with an empty data dir
|
||||||
|
joins via `--seed` against a leader whose WAL has rotated AND compacted
|
||||||
|
past seq 1 → converges via snapshot + stream with zero operator verbs and
|
||||||
|
no full-log replay; tier-3 `mp_seed_join_snapshot_catchup`.
|
||||||
|
2. **Scale 3→5→3 online under load:** background `ack=quorum` writers
|
||||||
|
(WriterTally, lost==0, retrying 429s per §2) through both gateways while
|
||||||
|
two nodes join, promote to voters, then one is removed and
|
||||||
|
decommissioned → m11p3 ledger invariants (frontier + content) hold
|
||||||
|
throughout; the joiner serves quorum (its reports advance the commit
|
||||||
|
index); p99 impact <2× for <60 s; 100k-item joiner catch-up ≤5 min
|
||||||
|
(env-scaled gate run recorded here).
|
||||||
|
3. **Reseed self-healing:** a quarantined divergent node (p4 drill) latches
|
||||||
|
`reseed_required`, restarts, reseeds via snapshot, rejoins clean, and the
|
||||||
|
divergence gauge clears — no `wipe_data_dir` in the test.
|
||||||
|
4. **DNS:** a tier-3 cluster whose topology names peers by hostname boots,
|
||||||
|
replicates, and survives the existing chaos drills; unit tests pin the
|
||||||
|
bind/advertise derivation table; the k8s pod-reschedule drill is recorded
|
||||||
|
as exit-gate evidence (§1).
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
- [x] Design adopted — 33 adversarial-review findings (9 BLOCKER) folded in pre-implementation
|
||||||
|
- [x] §3.0 majority() fix + DNS/bind-advertise split — `tidal`, `tidal-net`, `tidal-server`
|
||||||
|
- [x] Snapshot transfer + boot-time install + reseed marker — all crates
|
||||||
|
- [x] Membership records + conf-changes + seed join — all crates
|
||||||
|
- [x] Kubernetes reference (`k8s/cluster/`)
|
||||||
|
- [x] Exit-gate suites green; gate evidence recorded
|
||||||
|
- [x] Docs (runbook §§1b/3/6/8/9/11, kubernetes.md, CHANGELOG, roadmap, spec 01 §2.2, monitoring.md)
|
||||||
|
|
||||||
|
## As built (deltas vs the adopted design)
|
||||||
|
|
||||||
|
1. **`majority()` even-n fix landed `div_ceil`-spelled, not the `(n+1)/2+1`
|
||||||
|
form the design wrote.** `(peers.len() + 1).div_ceil(2) + 1` is the exact
|
||||||
|
same `floor(n/2)+1` over the full voter set (`n = peers.len()+1`), but
|
||||||
|
spelled with `div_ceil` so the two arithmetic sites in the subsystem —
|
||||||
|
`ElectionConfig::majority()` and `CommitIndex` — now read identically
|
||||||
|
(the design's whole point: the two formulas can no longer drift). Even-n
|
||||||
|
property tests landed first, as planned.
|
||||||
|
|
||||||
|
2. **The three-way term-join rule is implemented, AND `FetchSnapshot`'s
|
||||||
|
`needed` decision is baseline-aware** (§2.4 as adopted). Both were found by
|
||||||
|
the first tier-3 reseed drill, not the pre-implementation review, and both
|
||||||
|
are in the shipped design above — recorded here too because they were the
|
||||||
|
single largest correctness delta from the first draft: a follower behind at
|
||||||
|
a leadership change advances its frontier past pre-baseline history with
|
||||||
|
`lag=0` and never asks for the gap, so detection rides the heartbeat's
|
||||||
|
`prev_log` comparison (`own < prev_log` → latch `reseed_required`), and the
|
||||||
|
snapshot handler answers `needed` from `from_seqno ≤ stream_baseline OR
|
||||||
|
from_seqno < earliest WAL seq` rather than a naive "the WAL still covers it"
|
||||||
|
(which loops a marker boot forever at or below the baseline).
|
||||||
|
|
||||||
|
3. **Three product bugs surfaced and were fixed during the C3 build** (the
|
||||||
|
membership-runtime + verb stage), all in the as-built behavior above:
|
||||||
|
(a) the membership-apply path had to enter the async reactor context
|
||||||
|
correctly before driving the fenced reconfigure — a stray non-reactor enter
|
||||||
|
wedged the first conf-change; (b) a freshly-joined Learner did not receive
|
||||||
|
leader heartbeats until its first applied record, so its promotion clock
|
||||||
|
never started — heartbeats now flow to learners (they are in the ship set,
|
||||||
|
just not the quorum); (c) boot-time reconcile of the durable membership
|
||||||
|
cache against the WAL-recovered `ClusterMembership` cell had to prefer the
|
||||||
|
cell unconditionally (§3.6) — an early version let a stale cache shadow a
|
||||||
|
newer in-stream roster on restart.
|
||||||
|
|
||||||
|
4. **Auto-promotion landed in the C3 stage, alongside the membership runtime**
|
||||||
|
— not as a separate increment. It is the standing leader duty of §3.3
|
||||||
|
(re-armed on every leadership activation and every membership apply,
|
||||||
|
evaluated on commit-index publishes), driven solely from the applied
|
||||||
|
`ClusterMembership`, so it survives the joining-era leader's death.
|
||||||
|
|
||||||
|
5. **Removal grace mechanics (D1).** The `Removed` record retires the peer's
|
||||||
|
ship cell only after the record is quorum-committed AND delivered-to /
|
||||||
|
acked-by the removed peer, with a bounded give-up that increments
|
||||||
|
`tidaldb_cluster_remove_delivery_giveups_total` and a typed `removed`
|
||||||
|
refusal that flips the removed node's readiness to 503 and suppresses its
|
||||||
|
campaigning (§3.3 as adopted; D1 is where the delivery-then-retire ordering
|
||||||
|
and the give-up counter were wired end to end).
|
||||||
|
|
||||||
|
6. **`needed_peers` moved from a construction-frozen constant to a function**
|
||||||
|
of the latest applied record. The four peer-set copies (CommitIndex,
|
||||||
|
ShipQueue, PeerPool, ElectionState) were `const`-derived at boot in p4; the
|
||||||
|
fenced reconfigure path (§3.3) made them a function of the applied
|
||||||
|
`ClusterMembership`, evaluated inside the single membership-apply critical
|
||||||
|
section so they can never disagree about the roster.
|
||||||
|
|
||||||
|
7. **Re-appending the activation membership record is non-fatal on failure.**
|
||||||
|
The §3.2 activation re-append (the linchpin that closes the vacuous gate and
|
||||||
|
the baseline-jump skip) logs and continues if the append itself fails rather
|
||||||
|
than aborting the activation — a leader that cannot journal its roster is
|
||||||
|
still a leader for fencing purposes, and the next apply/activation retries
|
||||||
|
the record. (The conf-change *gate* still requires same-term quorum
|
||||||
|
commitment of the record before the NEXT change, so safety is unaffected;
|
||||||
|
only the cosmetic "every activation always has a record" property degrades
|
||||||
|
gracefully under a write fault.)
|
||||||
|
|
||||||
|
8. **The faster election machinery changed `/cluster/promote`'s topology-era
|
||||||
|
behavior — fixed by gating the transfer leg on the era.** m11p4's promote
|
||||||
|
handler relied on a behavioral accident: in the term-0 topology era,
|
||||||
|
`transfer_to(target)` never took (the target couldn't acknowledge a
|
||||||
|
`TimeoutNow` at a term it hadn't joined), so the handler always fell
|
||||||
|
through to the legacy fan-out and its documented `{ok, leader, baseline,
|
||||||
|
acked, failed}` response shape. p5's election work made that same transfer
|
||||||
|
*succeed*, returning the elected-era `{ok, leader, term, transfer}` shape
|
||||||
|
early and breaking the runbook's deserialization plus the non-leader
|
||||||
|
forward leg (`cluster_runbook` ×2 + `cluster_lifecycle` ×1, surfaced by
|
||||||
|
the D2 regression sweep). Fix: a topology-era leader does not
|
||||||
|
fence-transfer — it falls through to the legacy fan-out as documented —
|
||||||
|
while the self-campaign leg (the reseed drill's re-leadership path) and
|
||||||
|
the genuinely-elected era keep the fenced transfer. `term`/`transfer`
|
||||||
|
remain additive fields on the elected path.
|
||||||
|
|
||||||
|
## Exit-gate evidence
|
||||||
|
|
||||||
|
All gate suites are tier-3 (`--features cluster-e2e`), real OS processes over
|
||||||
|
localhost loopback, release test binary + debug-spawned servers. The k3s
|
||||||
|
(Ref-A) re-run is **pending infra access** (the standing M11 caveat, see
|
||||||
|
Carried hazards) — the StatefulSet reference (`k8s/cluster/`) is the
|
||||||
|
deliverable, but the under-load gate numbers below are localhost, stated
|
||||||
|
honestly as such.
|
||||||
|
|
||||||
|
| Gate (roadmap, restated as test) | Suite / test | Result |
|
||||||
|
|---|---|---|
|
||||||
|
| 1. Seed join + snapshot catch-up (fresh node, leader compacted past seq 1, zero verbs, no full-log replay) | `cluster_reseed.rs` + `cluster_membership.rs::mp_seed_join_snapshot_catchup` | **ok** — converges via snapshot + stream; env-scaled: 320 items join→converged 5.3s / 44 MB, 2000 → 13.0s / 269 MB, 5000 → 26.4s / 655 MB, every probed item searchable. The catch-up metric is ~26s at 5000 heavy items, large headroom under the 5-min budget. |
|
||||||
|
| 2. Scale 3→5→3 online under load (ack=quorum writers retrying 429s, ledger invariants hold, joiner serves quorum, p99 <2× for <60s) | `cluster_membership.rs::mp_scale_3_5_3_under_load_zero_loss` | **ok** — `lost=0`, `max_acked_seq=1467`; INVARIANT A (max acked seq ≤ leader frontier) + INVARIANT B (sampled acked content searchable) held at every 3→4→5→4 transition; per-window write p99 before=54.6ms, join-A=105.5ms, join-B=68.6ms, after=102.6ms (all <2× steady, within the <2×-for-<60s Ref-A figure; recorded, not hard-asserted per the non-flaky posture). |
|
||||||
|
| 3. Reseed self-healing (quarantined divergent node latches `reseed_required`, restarts, reseeds via snapshot, gauge clears, no `wipe_data_dir`) | `cluster_reseed.rs` | **ok** — quarantine → marker → restart → converged; `tidaldb_cluster_divergence_quarantined` + `tidaldb_cluster_reseed_required` clear after a genuine reseed; no `wipe_data_dir` in the test. |
|
||||||
|
| 4. DNS (hostname-topology cluster boots, replicates, survives chaos; bind/advertise derivation table pinned) | `cluster_membership.rs::mp_dns_hostname_topology_replicates` + unit derivation tests | **ok** — a 3-node hostname topology (which a pre-m11p5 `SocketAddr::parse` would have refused) boots, replicates a leader write to a follower, and survives a SIGKILL+restart drill (the resolver re-dials on reconnect — the point of the String peer retype). The k8s pod-reschedule drill (changed pod IP) is the deliberate Ref-A line item, pending infra access. |
|
||||||
|
|
||||||
|
Full suite tail (2026-06-12): `cluster_membership` 5 passed / 0 failed (86.78s,
|
||||||
|
incl. "[scale] exit gate 2 met" and "[dns] exit gate 4 met"); `cluster_multiproc`
|
||||||
|
5 passed, `cluster_chaos` 4 passed, `cluster_quorum` 2 passed,
|
||||||
|
`cluster_election` 3 passed, `cluster_reseed` 2 passed. `cargo test -p tidaldb
|
||||||
|
--lib` 1896 passed / 0 failed; `cargo clippy --workspace --all-targets
|
||||||
|
--all-features -- -D warnings` clean; `cargo fmt --check -p tidal-server` exit 0.
|
||||||
|
|
||||||
|
> The D2 sweep surfaced a promote regression in `cluster_lifecycle` /
|
||||||
|
> `cluster_runbook` — **fixed post-D** (see As-built #8): all eight tier-3
|
||||||
|
> suites are green. Final post-fix sweep (2026-06-12): multiproc 5, chaos 4,
|
||||||
|
> lifecycle 2, runbook 9, quorum 2, election 3, reseed 2, membership 5 — all
|
||||||
|
> 0 failed when run per-suite; `tidaldb --lib` 1896 passed; tidal-net 10 +
|
||||||
|
> tidal-server 19 ok-binaries; workspace clippy `-D warnings` clean; fmt
|
||||||
|
> clean; `scripts/check-docs.sh` OK. The suites are load-marginal when run
|
||||||
|
> back-to-back on one saturated host (a colocated sweep flaked one runbook
|
||||||
|
> drill that passes 9/9 isolated) — the same documented sensitivity class as
|
||||||
|
> p4's `mp_rolling_upgrade` note; widen `TIDAL_TEST_CONVERGENCE_BUDGET_SECS`
|
||||||
|
> on slow runners.
|
||||||
|
|
||||||
|
## Carried hazards (tracked, not regressions)
|
||||||
|
|
||||||
|
1. **Ref-A (k3s) run pending infra access.** Every under-load and catch-up
|
||||||
|
number above is localhost loopback on a debug-spawned server, not Ref-A.
|
||||||
|
The k3s deployment has been unreachable from the local environment since
|
||||||
|
m11p1 (the standing caveat in p2/p3); p5's k8s-centric gate cannot fall back
|
||||||
|
to localhost the way p1–p3 did, so the StatefulSet reference (`k8s/cluster/`)
|
||||||
|
is the deliverable and the k8s pod-reschedule drill (gate 4, §1) +
|
||||||
|
100k-item Ref-A catch-up remain the named Ref-A line items. The 5000-item
|
||||||
|
localhost run is the largest that completed in reasonable wall time — the
|
||||||
|
ceiling was the ~13 items/sec HTTP **seed** rate against a debug server (the
|
||||||
|
seed cost, not the catch-up path the gate measures), not a catch-up limit.
|
||||||
|
|
||||||
|
2. **Tier-3 suites are load-marginal under colocation.** Each suite is green
|
||||||
|
in isolation (the way gate runs are recorded), but running all eight
|
||||||
|
back-to-back on one saturated host can flake a FAST_ELECTION-timed drill
|
||||||
|
(one runbook failure in a full-sweep run that passes 9/9 isolated, three
|
||||||
|
times over). Same class as p4's `mp_rolling_upgrade` note; the reseed
|
||||||
|
suite's content probes were widened from a fixed 15 s to the harness
|
||||||
|
`convergence_budget()` in-phase. m11p9's nightly CI should run suites
|
||||||
|
serially or on isolated runners.
|
||||||
|
|
||||||
|
3. **The quiesce window is recorded, not yet measured at 100k on Ref-A.**
|
||||||
|
§2's `create_backup` 429s signal writes for checkpoint + flush + copy; gate
|
||||||
|
writers retry 429 honoring `retry_after_ms` (neither lost nor an SLO
|
||||||
|
violation), and the localhost windows are within budget — but the
|
||||||
|
"seconds at 100k items" figure the design names is a Ref-A measurement
|
||||||
|
still owed once infra access returns.
|
||||||
|
|
||||||
|
4. **DNS changed-IP coverage is the k8s drill, not a localhost test.** The
|
||||||
|
re-resolution property (a pod rescheduled onto a new IP, ship/stream resumes
|
||||||
|
with no peer restarts) is the entire point of the `String`-peer retype and
|
||||||
|
cannot be regressed by a localhost test that never changes addresses. The
|
||||||
|
`mp_dns_hostname_topology_replicates` test proves the hostname-topology boot
|
||||||
|
+ reconnect re-dial; the changed-address reconvergence is the k8s
|
||||||
|
pod-reschedule line item under hazard 1.
|
||||||
@ -1,6 +1,6 @@
|
|||||||
# Roadmap to an Enterprise-Grade Cluster
|
# Roadmap to an Enterprise-Grade Cluster
|
||||||
|
|
||||||
**Status:** ADOPTED as M11 — m11p1 ✅, m11p2 ✅, m11p3 ✅, m11p4 ✅ complete (2026-06-12 — closes **G5**; v0.9 "Credible HA" wave done) · p5–p9 planned · **Date:** 2026-06-10 · **Baseline evidence:**
|
**Status:** ADOPTED as M11 — m11p1 ✅, m11p2 ✅, m11p3 ✅, m11p4 ✅, m11p5 ✅ complete (2026-06-12 — p4 closes **G5**; p5 ships membership/discovery/elasticity, the first leg of the v1.0 "Scalable" wave) · p6–p9 planned · **Date:** 2026-06-10 · **Baseline evidence:**
|
||||||
[stress-test-thepeach.md](ops/stress-test-thepeach.md), [cluster runbook](runbooks/cluster.md),
|
[stress-test-thepeach.md](ops/stress-test-thepeach.md), [cluster runbook](runbooks/cluster.md),
|
||||||
[ROADMAP M8 Known Gaps](planning/ROADMAP.md) (G4/G5/G6), live k3s deployment (3 regions × 2-vCPU pods).
|
[ROADMAP M8 Known Gaps](planning/ROADMAP.md) (G4/G5/G6), live k3s deployment (3 regions × 2-vCPU pods).
|
||||||
|
|
||||||
@ -56,7 +56,7 @@ enterprise floor; everything else is competitive or better.**
|
|||||||
| Replication unity | Signals ride the WAL; items/embeddings ride a best-effort HTTP side channel (source of both live bugs we fixed: marker-gated broadcast, 401'd heal backfill); heal is O(items) | **One replicated log** for all replicated data; heal = log catch-up | **p2** |
|
| Replication unity | Signals ride the WAL; items/embeddings ride a best-effort HTTP side channel (source of both live bugs we fixed: marker-gated broadcast, 401'd heal backfill); heal is O(items) | **One replicated log** for all replicated data; heal = log catch-up | **p2** |
|
||||||
| Durability | 2xx = leader fsync only; follower ship best-effort | `ack=quorum` mode: 2xx = majority-durable; zero acknowledged loss on any single-node kill | **p3** |
|
| Durability | 2xx = leader fsync only; follower ship best-effort | `ack=quorum` mode: 2xx = majority-durable; zero acknowledged loss on any single-node kill | **p3** |
|
||||||
| Availability | Operator-driven promote; **restarted node re-reads topology and believes the static leader again** (observed live: us-east rejoined claiming leadership while eu-west led — split-brain seed) | Failure detector + automatic election + **term fencing** + durable leadership | **p4** |
|
| Availability | Operator-driven promote; **restarted node re-reads topology and believes the static leader again** (observed live: us-east rejoined claiming leadership while eu-west led — split-brain seed) | Failure detector + automatic election + **term fencing** + durable leadership | **p4** |
|
||||||
| Membership | Static per-pod topology files with **literal IPs** (`grpc_addr` is `SocketAddr::parse` — no DNS); add/remove node = redeploy everything | Dynamic membership, DNS/seed discovery, online add/remove/replace with snapshot+stream catch-up (`StreamSegments` is declared but unimplemented) | **p5** |
|
| Membership | **✅ p5:** DNS/seed discovery (`grpc_addr` advertised + DNS-resolved, `grpc_bind` for the local bind), kind-4 membership records on the one log, online `/cluster/join`+remove with learner→voter auto-promotion, `FetchSnapshot` snapshot+stream catch-up, self-healing reseed, `k8s/cluster/` one-StatefulSet reference | Dynamic membership, DNS/seed discovery, online add/remove/replace with snapshot+stream catch-up | **p5 ✅** |
|
||||||
| Write scaling | EITHER replicated (1 leader for everything) OR sharded (no replication); shards conflated with regions | **Sharding × replication**: shard groups with RF and distributed leaders; rebalancing | **p6** |
|
| Write scaling | EITHER replicated (1 leader for everything) OR sharded (no replication); shards conflated with regions | **Sharding × replication**: shard groups with RF and distributed leaders; rebalancing | **p6** |
|
||||||
| Security | Plaintext gRPC replication (mTLS config exists, unexercised); one static bearer shared by all; internal marker as trust signal; no audit log | mTLS default + rotation, authenticated inter-node calls, admin audit, at-rest story | **p7** |
|
| Security | Plaintext gRPC replication (mTLS config exists, unexercised); one static bearer shared by all; internal marker as trust signal; no audit log | mTLS default + rotation, authenticated inter-node calls, admin audit, at-rest story | **p7** |
|
||||||
| Observability | **Cluster mode has no `/metrics` listener at all**; no request-id propagation on cluster routers; lag accounting wrong after promote (ShardId(0)-keyed); leader's own status row reads 0 | Per-node Prometheus metrics, tracing across forward/ship hops, truthful status, dashboards + alerts | **p8** (starts in p1) |
|
| Observability | **Cluster mode has no `/metrics` listener at all**; no request-id propagation on cluster routers; lag accounting wrong after promote (ShardId(0)-keyed); leader's own status row reads 0 | Per-node Prometheus metrics, tracing across forward/ship hops, truthful status, dashboards + alerts | **p8** (starts in p1) |
|
||||||
@ -336,6 +336,35 @@ channel (items/embeddings) is deleted.
|
|||||||
- **Exit gate:** scale 3→5→3 online under load: joiner catches up ≤5 min
|
- **Exit gate:** scale 3→5→3 online under load: joiner catches up ≤5 min
|
||||||
(100k items), serves quorum after; p99 impact <2× for <60 s; zero loss.
|
(100k items), serves quorum after; p99 impact <2× for <60 s; zero loss.
|
||||||
|
|
||||||
|
> **✅ COMPLETE (2026-06-12), as built:** `grpc_addr` became an **advertised**
|
||||||
|
> address (hostname or IP) split from an optional `grpc_bind`; `tidal-net`'s
|
||||||
|
> peer map retyped `SocketAddr → String` so hyper re-resolves DNS on every
|
||||||
|
> reconnect (the pod-rescheduled-onto-a-new-IP case the `SocketAddr::parse`
|
||||||
|
> constraint made impossible). A new server-streaming `FetchSnapshot` RPC ships
|
||||||
|
> `create_backup` as a manifest + BLAKE3-verified file chunks (term-stamped,
|
||||||
|
> term-fenced, identify-or-refuse) into a **boot-time** staging-dir install
|
||||||
|
> (every crash window an idempotent redo); reseed is self-healing — a typed
|
||||||
|
> `x-tidal-catchup: snapshot-required` refusal (or the p4 quarantine) latches a
|
||||||
|
> durable `reseed_required` marker that runs on the next boot and clears the
|
||||||
|
> divergence gauge, no `wipe_data_dir`. Membership is data on the one log: a new
|
||||||
|
> **kind-4** `MembershipRecord` (beside kind-0/1/2/3) folds into a
|
||||||
|
> `ClusterMembership` cell; `POST /cluster/join` appends a quorum-committed
|
||||||
|
> Learner that auto-promotes to Voter; conf-changes are Raft single-server with
|
||||||
|
> an activation-record re-append closing the vacuous-gate + baseline-jump
|
||||||
|
> blockers. The **three-way term-join rule** (`own < prev_log` → latch reseed)
|
||||||
|
> closes p4's pre-baseline-history carried hazard; the even-n `majority()` fix
|
||||||
|
> (`(n+1).div_ceil(2)+1`) closes a latent dual-leader bug. Seed-join boot
|
||||||
|
> (`--seed`/`--advertise-*`/`--metrics`, knob file still required) +
|
||||||
|
> `k8s/cluster/` (one StatefulSet, headless Service, PDB, topology-spread) make
|
||||||
|
> `kubectl delete pod` the node-replace drill. Exit-gate mechanics proven by
|
||||||
|
> tier-3 `cluster_membership.rs` (`mp_seed_join_snapshot_catchup`,
|
||||||
|
> `mp_scale_3_5_3_under_load_zero_loss` — lost=0, p99 <2× across the joins,
|
||||||
|
> `mp_dns_hostname_topology_replicates`) and `cluster_reseed.rs`. The 100k-item
|
||||||
|
> catch-up and the k8s pod-reschedule drill remain Ref-A line items (k3s access
|
||||||
|
> pending — the standing M11 caveat; the 5000-item localhost catch-up at 26.4s
|
||||||
|
> has large headroom under the ≤5-min budget). Details:
|
||||||
|
> [planning/milestone-11/phase-5.md](planning/milestone-11/phase-5.md).
|
||||||
|
|
||||||
### m11p6 — Sharding × replication + rebalancing (size: XL)
|
### m11p6 — Sharding × replication + rebalancing (size: XL)
|
||||||
**Goal:** writes scale horizontally **without** giving up replication — the
|
**Goal:** writes scale horizontally **without** giving up replication — the
|
||||||
current "replicated XOR sharded" split ends.
|
current "replicated XOR sharded" split ends.
|
||||||
|
|||||||
@ -36,12 +36,21 @@ write-durability contract.
|
|||||||
> gates success on a **majority of the replica set durably holding the
|
> gates success on a **majority of the replica set durably holding the
|
||||||
> write**, surviving permanent leader loss (see
|
> write**, surviving permanent leader loss (see
|
||||||
> [§8](#8-write-durability-contract-the-ack-knob-and-its-cost-m11p3)).
|
> [§8](#8-write-durability-contract-the-ack-knob-and-its-cost-m11p3)).
|
||||||
> * **Leadership is operator-driven, not automatic.** There is **no automatic
|
> * **Leadership is automatic** (m11p4). Every node runs a failure detector and
|
||||||
> failure detector and no automatic leader election.** `/cluster/promote` moves
|
> a Raft-style election (pre-vote + vote + check-quorum + fenced transfer):
|
||||||
> leadership and fans the new view out to peers; a node that misses the fan-out
|
> kill the leader and the survivors elect a successor — typically under a
|
||||||
> self-corrects on its next forwarded write / status poll. "Survive a machine
|
> second with the defaults — with **zero operator verbs** and zero
|
||||||
> dying" is an operator runbook step (detect → promote the max-applied
|
> acknowledged-write loss (see [§9.1](#91-automatic-failover-m11p4--the-default)).
|
||||||
> survivor), not an automatic failover (elections are m11p4).
|
> `/cluster/promote` is now a **fenced transfer** for maintenance/override, not
|
||||||
|
> the availability mechanism. `election.auto_election: false` preserves the
|
||||||
|
> pre-m11p4 operator-driven posture.
|
||||||
|
> * **Membership is elastic and addresses are DNS names** (m11p5). `grpc_addr`
|
||||||
|
> is an advertised hostname or IP (DNS-resolved on every reconnect); nodes join
|
||||||
|
> online via `--seed` and catch up via `FetchSnapshot` + the `StreamSegments`
|
||||||
|
> stream; add/remove ride kind-4 membership records on the replicated log
|
||||||
|
> (see [§1b](#1b-multi-process-one-process-per-region),
|
||||||
|
> [§3](#3-topology-yaml), [§6](#6-cluster-management-api),
|
||||||
|
> [§9.1](#91-automatic-failover-m11p4--the-default)).
|
||||||
>
|
>
|
||||||
> **For a production deployment today**, run a **single `tidal-server standalone`**
|
> **For a production deployment today**, run a **single `tidal-server standalone`**
|
||||||
> node backed by host-level redundancy and disk durability (see
|
> node backed by host-level redundancy and disk durability (see
|
||||||
@ -142,6 +151,58 @@ declaration order, so all processes agree on the region→id mapping. Each proce
|
|||||||
binds its own region's `grpc_addr`/`http_addr` and dials its siblings' addresses.
|
binds its own region's `grpc_addr`/`http_addr` and dials its siblings' addresses.
|
||||||
The `--listen` HTTP address is the public gateway for that region.
|
The `--listen` HTTP address is the public gateway for that region.
|
||||||
|
|
||||||
|
#### Seed-join boot (m11p5 — adding a node without editing the topology)
|
||||||
|
|
||||||
|
A node can join an existing cluster **online**, without appearing in any
|
||||||
|
declared topology, by contacting a running peer as a **seed**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
TIDAL_ALLOW_EXPERIMENTAL_CLUSTER=1 \
|
||||||
|
tidal-server cluster --experimental-cluster \
|
||||||
|
--region eu-2 \
|
||||||
|
--listen 0.0.0.0:9504 \
|
||||||
|
--schema /etc/tidal/schema.yaml \
|
||||||
|
--topology /etc/tidal/topology.yaml \
|
||||||
|
--data-dir /var/lib/tidal/eu-2 \
|
||||||
|
--seed http://10.0.1.10:9501 \
|
||||||
|
--seed http://10.0.2.10:9502 \
|
||||||
|
--advertise-grpc eu-2.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9600 \
|
||||||
|
--advertise-http eu-2.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9504 \
|
||||||
|
--metrics 0.0.0.0:9091
|
||||||
|
```
|
||||||
|
|
||||||
|
| Flag | Meaning |
|
||||||
|
|------|---------|
|
||||||
|
| `--seed <url>` (repeatable) | One or more seed HTTP base URLs. The joiner polls each for the current leader, then `POST /cluster/join`s through it. Any reachable seed works; list a few for resilience. |
|
||||||
|
| `--advertise-grpc <host:port>` | This node's **advertised** gRPC address — what siblings dial. Required with `--seed` (the joiner has no topology entry of its own). DNS-capable. |
|
||||||
|
| `--advertise-http <host:port>` | This node's advertised HTTP gateway — what peers forward writes/status to. Required with `--seed`. |
|
||||||
|
| `--metrics <addr>` | Prometheus `/metrics` bind (the joiner has no topology `metrics_addr`). |
|
||||||
|
|
||||||
|
What happens: the joiner skips the topology's "every region declared" gate,
|
||||||
|
learns its **roster + assigned id + current term** from the seed's join
|
||||||
|
response, appends a **Learner** record to the replicated log (the leader answers
|
||||||
|
only after it is quorum-committed), persists the roster to a durable membership
|
||||||
|
cache and the term to `election_state` (persist-before-act), installs a
|
||||||
|
[snapshot](#8-write-durability-contract-the-ack-knob-and-its-cost-m11p3) when it
|
||||||
|
is behind the leader's retained WAL, then streams the live tail. The leader's
|
||||||
|
**auto-promotion** duty flips it Learner → Voter once it is within
|
||||||
|
`replication.learner_promote_lag` (default 1024) of the flushed frontier. A
|
||||||
|
**restart** boots from the cache without the seed.
|
||||||
|
|
||||||
|
> **A `--seed` boot still requires the local topology/config file** for the
|
||||||
|
> behavioral knob blocks (`replication:`, `wal:`, `election:`, `timeouts:`,
|
||||||
|
> `grpc_tls`) — its `regions:` list is ignored for the roster (the join response
|
||||||
|
> is the roster), but a bare `--seed` with neither `--topology` nor
|
||||||
|
> `TIDAL_CONFIG` **refuses to boot** naming the rule, so a joiner never silently
|
||||||
|
> inherits the compiled-in defaults' wrong ack mode, quorum timeout, or election
|
||||||
|
> timing. The k8s manifests mount the shared bootstrap ConfigMap on every pod
|
||||||
|
> including N≥3, so this costs nothing there.
|
||||||
|
|
||||||
|
> **Capability gate (m11p5 mixed-version safety).** The leader **refuses
|
||||||
|
> `/cluster/join` and every conf-change until all current voters report kind-4
|
||||||
|
> capability** — see [§8](#8-write-durability-contract-the-ack-knob-and-its-cost-m11p3)'s
|
||||||
|
> downgrade rule. Complete the binary upgrade before adding or removing nodes.
|
||||||
|
|
||||||
**Auth:** set `TIDAL_API_KEY=<secret>` to require `Authorization: Bearer <secret>`
|
**Auth:** set `TIDAL_API_KEY=<secret>` to require `Authorization: Bearer <secret>`
|
||||||
on the data and `/cluster/*` mutation routes. If it is **unset the server runs
|
on the data and `/cluster/*` mutation routes. If it is **unset the server runs
|
||||||
UNAUTHENTICATED and logs a WARN** — never expose an unauthenticated cluster
|
UNAUTHENTICATED and logs a WARN** — never expose an unauthenticated cluster
|
||||||
@ -217,18 +278,27 @@ at startup — a missing or syntactically invalid `host:port` is a hard error na
|
|||||||
the region; reachability is deliberately not probed, since siblings boot in any
|
the region; reachability is deliberately not probed, since siblings boot in any
|
||||||
order):
|
order):
|
||||||
|
|
||||||
|
`grpc_addr` is an **advertised** address — a literal `host:port` OR a DNS
|
||||||
|
hostname (m11p5). A new optional per-region `grpc_bind` controls the local bind
|
||||||
|
independently of what siblings dial; the example below shows the DNS shape (one
|
||||||
|
shared file names every region by its per-pod DNS name while each pod binds
|
||||||
|
`0.0.0.0`):
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
regions:
|
regions:
|
||||||
- name: us-east
|
- name: us-east
|
||||||
grpc_addr: "10.0.1.10:9601" # this region's gRPC replication bind / dial addr
|
grpc_addr: "tidaldb-0.tidaldb-peers.svc.cluster.local:9601" # ADVERTISED (siblings dial; DNS re-resolved on reconnect)
|
||||||
|
grpc_bind: "0.0.0.0:9601" # LOCAL bind (optional; see derivation rule below)
|
||||||
http_addr: "10.0.1.10:9501" # this region's public HTTP gateway (forwarding + status)
|
http_addr: "10.0.1.10:9501" # this region's public HTTP gateway (forwarding + status)
|
||||||
metrics_addr: "10.0.1.10:9091" # optional Prometheus /metrics listener (set it in production)
|
metrics_addr: "10.0.1.10:9091" # optional Prometheus /metrics listener (set it in production)
|
||||||
- name: eu-west
|
- name: eu-west
|
||||||
grpc_addr: "10.0.2.10:9602"
|
grpc_addr: "tidaldb-1.tidaldb-peers.svc.cluster.local:9602"
|
||||||
|
grpc_bind: "0.0.0.0:9602"
|
||||||
http_addr: "10.0.2.10:9502"
|
http_addr: "10.0.2.10:9502"
|
||||||
metrics_addr: "10.0.2.10:9091"
|
metrics_addr: "10.0.2.10:9091"
|
||||||
- name: ap-south
|
- name: ap-south
|
||||||
grpc_addr: "10.0.3.10:9603"
|
grpc_addr: "tidaldb-2.tidaldb-peers.svc.cluster.local:9603"
|
||||||
|
grpc_bind: "0.0.0.0:9603"
|
||||||
http_addr: "10.0.3.10:9503"
|
http_addr: "10.0.3.10:9503"
|
||||||
metrics_addr: "10.0.3.10:9091"
|
metrics_addr: "10.0.3.10:9091"
|
||||||
leader: us-east
|
leader: us-east
|
||||||
@ -237,19 +307,39 @@ leader: us-east
|
|||||||
# batch_max_events: 256 # events coalesced per shipped batch (1-256)
|
# batch_max_events: 256 # events coalesced per shipped batch (1-256)
|
||||||
# window: 4 # in-flight batches per peer (1-64)
|
# window: 4 # in-flight batches per peer (1-64)
|
||||||
# retry_ms: 100 # backoff before a transiently-failed batch retries
|
# retry_ms: 100 # backoff before a transiently-failed batch retries
|
||||||
|
# catchup_retry_ms: 30000 # backoff before a FAILED catch-up pull re-pulls (m11p4)
|
||||||
|
# snapshot_artifact_ttl_ms: 600000 # staged-snapshot reuse window (m11p5; never unpins an active consumer)
|
||||||
|
# learner_promote_lag: 1024 # learner→voter promotion distance + readiness hysteresis (m11p5)
|
||||||
|
# reseed_self_restart: false # drain+exit(0) when reseed_required latches (m11p5; k8s sets true)
|
||||||
# wal:
|
# wal:
|
||||||
# batch_size: 100 # events per group-commit fsync (1-256)
|
# batch_size: 100 # events per group-commit fsync (1-256)
|
||||||
# batch_timeout_ms: 10 # max wait before a partial batch flushes
|
# batch_timeout_ms: 10 # max wait before a partial batch flushes
|
||||||
|
# election: # m11p4 failure-detector / election timers (defaults shown)
|
||||||
|
# heartbeat_interval_ms: 300
|
||||||
|
# election_timeout_min_ms: 1500 # validated: leader_lease_ms + heartbeat_interval_ms < this
|
||||||
|
# election_timeout_max_ms: 3000
|
||||||
|
# leader_lease_ms: 900
|
||||||
|
# auto_election: true # false → pre-m11p4 operator-driven failover
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**`grpc_bind` derivation (m11p5 §1):** `grpc_bind` present → bind it. Absent +
|
||||||
|
`grpc_addr` parses as a literal SocketAddr → bind that (today's behavior,
|
||||||
|
byte-for-byte — every existing IP topology keeps working). Absent + `grpc_addr`
|
||||||
|
is a hostname → bind `0.0.0.0:<port from grpc_addr>`. Because the peer-dial path
|
||||||
|
no longer parses `grpc_addr` as a SocketAddr, hyper re-resolves the hostname on
|
||||||
|
every reconnect — a pod rescheduled onto a new IP is reached with no peer
|
||||||
|
restarts. **TLS note:** SNI follows the URI host, so DNS peer names require
|
||||||
|
DNS-SAN certs (see `grpc_tls` below); no code change.
|
||||||
|
|
||||||
Fields:
|
Fields:
|
||||||
|
|
||||||
| Field | Single-process | Multi-process | Meaning |
|
| Field | Single-process | Multi-process | Meaning |
|
||||||
|-------|----------------|---------------|---------|
|
|-------|----------------|---------------|---------|
|
||||||
| `regions[].name` | required | required | Region name used everywhere in the HTTP API (`?region=`, `/cluster/promote`, etc.). Must be unique. |
|
| `regions[].name` | required | required | Region name used everywhere in the HTTP API (`?region=`, `/cluster/promote`, etc.). Must be unique. |
|
||||||
| `regions[].grpc_addr` | optional | **required** | This region's gRPC replication address. In single-process mode **omit it** — the server allocates a free loopback port and self-heals a bind race by retrying on a fresh port. In multi-process mode it is required (siblings dial it) and is tried exactly once. |
|
| `regions[].grpc_addr` | optional | **required** | This region's **advertised** gRPC replication address — what siblings dial. Since m11p5 it may be a literal `host:port` OR a **DNS hostname** (re-resolved on every reconnect). In single-process mode **omit it** — the server allocates a free loopback port and self-heals a bind race by retrying on a fresh port. In multi-process mode it is required and is tried exactly once. |
|
||||||
|
| `regions[].grpc_bind` | unused | optional | This region's **local** gRPC bind `host:port` (m11p5), independent of the advertised `grpc_addr`. Omitted: a literal `grpc_addr` binds itself; a hostname `grpc_addr` binds `0.0.0.0:<its port>`. Set it to bind a specific interface while advertising a DNS name. |
|
||||||
| `regions[].http_addr` | unused | **required** | This region's public HTTP gateway address, used by siblings for write/read forwarding and status aggregation. Unused in single-process mode. |
|
| `regions[].http_addr` | unused | **required** | This region's public HTTP gateway address, used by siblings for write/read forwarding and status aggregation. Unused in single-process mode. |
|
||||||
| `regions[].grpc_tls` | unused | optional | TLS material for this region's gRPC transport: `ca_cert`, `server_cert`, `server_key` (PEM paths), plus optional `client_cert`/`client_key` for mTLS. Omitted ⇒ plaintext, the right posture for loopback/VPC topologies. |
|
| `regions[].grpc_tls` | unused | optional | TLS material for this region's gRPC transport: `ca_cert`, `server_cert`, `server_key` (PEM paths), plus optional `client_cert`/`client_key` for mTLS. Omitted ⇒ plaintext, the right posture for loopback/VPC topologies. **DNS `grpc_addr` requires DNS-SAN certs** (SNI follows the dialed hostname). |
|
||||||
| `regions[].metrics_addr` | unused | optional | Bind address for this region's Prometheus `/metrics` listener (m11p1; cluster mode previously had none). Omitted ⇒ no metrics endpoint. Set it in every production topology, and bind it internally — the endpoint is unauthenticated. |
|
| `regions[].metrics_addr` | unused | optional | Bind address for this region's Prometheus `/metrics` listener (m11p1; cluster mode previously had none). Omitted ⇒ no metrics endpoint. Set it in every production topology, and bind it internally — the endpoint is unauthenticated. |
|
||||||
| `leader` | required | required | Must name one of the declared regions. The initial write leader. |
|
| `leader` | required | required | Must name one of the declared regions. The initial write leader. |
|
||||||
| `write_workers` | optional | optional | Size of the runtime-free OS-thread pool that admission-controls cluster writes (`/signals` staging) and runs `/cluster/heal`'s blocking redelivery. Bounded queue ⇒ 429 backpressure. Must be ≥ 1 when given. |
|
| `write_workers` | optional | optional | Size of the runtime-free OS-thread pool that admission-controls cluster writes (`/signals` staging) and runs `/cluster/heal`'s blocking redelivery. Bounded queue ⇒ 429 backpressure. Must be ≥ 1 when given. |
|
||||||
@ -259,6 +349,14 @@ Fields:
|
|||||||
| `replication.retry_ms` | unused | optional | Backoff (ms) before a transiently-failed batch ship retries. Default 100. |
|
| `replication.retry_ms` | unused | optional | Backoff (ms) before a transiently-failed batch ship retries. Default 100. |
|
||||||
| `replication.ack` | unused | optional | Deployment-default write acknowledgment: `leader` (default) or `quorum` (majority-durable — see [§8](#8-write-durability-contract-the-ack-knob-and-its-cost-m11p3)). Per-request override: the `x-tidal-ack` header. |
|
| `replication.ack` | unused | optional | Deployment-default write acknowledgment: `leader` (default) or `quorum` (majority-durable — see [§8](#8-write-durability-contract-the-ack-knob-and-its-cost-m11p3)). Per-request override: the `x-tidal-ack` header. |
|
||||||
| `replication.quorum_timeout_ms` | unused | optional | Budget an `ack=quorum` write waits for the commit index before the retryable 503 naming the laggards. Default 2000. |
|
| `replication.quorum_timeout_ms` | unused | optional | Budget an `ack=quorum` write waits for the commit index before the retryable 503 naming the laggards. Default 2000. |
|
||||||
|
| `replication.catchup_retry_ms` | unused | optional | Backoff (ms) before a FAILED catch-up pull re-pulls on a timer (m11p4) — lets an idle cluster self-heal a follower whose pull failed during a rolling restart. Default 30000. Must be ≥ 1 when given. |
|
||||||
|
| `replication.snapshot_artifact_ttl_ms` | unused | optional | Staged-snapshot reuse window (m11p5), counted from the last fetch's completion. Governs artifact REUSE only — **never** unpins the WAL retention of an active consumer; a hard cap (4×) force-drops a never-releasing pin (`tidaldb_cluster_snapshot_pin_force_drops_total`). Default 600000 (10 min). Must be ≥ 1. |
|
||||||
|
| `replication.learner_promote_lag` | unused | optional | Learner→voter promotion distance AND the readiness-convergence hysteresis threshold (m11p5), in events. Default 1024. Must be ≥ 1. |
|
||||||
|
| `replication.reseed_self_restart` | unused | optional | Drain + clean-exit(0) once the durable `reseed_required` marker latches (m11p5; k8s sets it `true`). **Refused** when the remaining voters can't sustain quorum without this node. Default `false`. |
|
||||||
|
| `election.heartbeat_interval_ms` | unused | optional | Leader heartbeat interval (m11p4). Default 300. |
|
||||||
|
| `election.election_timeout_min_ms` / `..max_ms` | unused | optional | Randomized follower election timeout window (m11p4). Defaults 1500 / 3000. Validated: `leader_lease_ms + heartbeat_interval_ms < election_timeout_min_ms`. |
|
||||||
|
| `election.leader_lease_ms` | unused | optional | Leader freshness lease — a leader that loses majority contact steps down within it (m11p4). Default 900. |
|
||||||
|
| `election.auto_election` | unused | optional | `true` (default) = automatic failover; `false` = pre-m11p4 operator-driven posture (no auto elections, no check-quorum step-down). |
|
||||||
| `wal.batch_size` | optional | optional | Events per WAL group-commit fsync (1–256). Default 100. |
|
| `wal.batch_size` | optional | optional | Events per WAL group-commit fsync (1–256). Default 100. |
|
||||||
| `wal.batch_timeout_ms` | optional | optional | Max ms a partial group-commit batch waits before flushing. Default 10. Tune against the measured `tidaldb_cluster_wal_fsync_us` on the deployment's volume. |
|
| `wal.batch_timeout_ms` | optional | optional | Max ms a partial group-commit batch waits before flushing. Default 10. Tune against the measured `tidaldb_cluster_wal_fsync_us` on the deployment's volume. |
|
||||||
|
|
||||||
@ -284,7 +382,7 @@ not in-process channels. The facts you need to operate and firewall it:
|
|||||||
|
|
||||||
| Property | Value | Notes |
|
| Property | Value | Notes |
|
||||||
|----------|-------|-------|
|
|----------|-------|-------|
|
||||||
| Service | `WalShipping` (proto `tidal.replication.v1`) | RPCs: **`ShipSegment`** (unary; the production replication path) and **`Heartbeat`** (ControlPlane health). `StreamSegments` is declared but **not implemented** — segment delivery is the unary `ShipSegment`. |
|
| Service | `WalShipping` (proto `tidal.replication.v1`) | RPCs: **`ShipSegment`** (unary; the live-tail push path), **`StreamSegments`** (server-streaming; the follower-pulled catch-up path since m11p2), **`FetchSnapshot`** (server-streaming; the m11p5 snapshot transfer for joiners + reseeds), **`JoinCluster`** (m11p5 conf-change), and **`Heartbeat`** (ControlPlane health). |
|
||||||
| Bind address | per-region `grpc_addr` (multi-process); an **auto-allocated** loopback port (single-process) | Default dev band `59520–59529` if you pin one. |
|
| Bind address | per-region `grpc_addr` (multi-process); an **auto-allocated** loopback port (single-process) | Default dev band `59520–59529` if you pin one. |
|
||||||
| Transport security | mTLS via `TlsConfig` (`ca_cert`, `server_cert`, `server_key`, optional `client_cert` / `client_key`) | `insecure = true` (plaintext) is the loopback/VPC default in this phase. A peer with no TLS config **must** set `insecure`. |
|
| Transport security | mTLS via `TlsConfig` (`ca_cert`, `server_cert`, `server_key`, optional `client_cert` / `client_key`) | `insecure = true` (plaintext) is the loopback/VPC default in this phase. A peer with no TLS config **must** set `insecure`. |
|
||||||
| Max payload | **64 MiB** | Both encoder and decoder codec limits are raised to this; pinned by a compile-time assert to the engine's `InProcessTransport` limit so both ends agree. WAL segments default to 16 MiB. |
|
| Max payload | **64 MiB** | Both encoder and decoder codec limits are raised to this; pinned by a compile-time assert to the engine's `InProcessTransport` limit so both ends agree. WAL segments default to 16 MiB. |
|
||||||
@ -507,8 +605,12 @@ in `failed` (e.g. a dead old leader) self-corrects — its first parked batch
|
|||||||
from the new stream triggers a catch-up pull whose chunks announce the
|
from the new stream triggers a catch-up pull whose chunks announce the
|
||||||
baseline. After promotion `/cluster/status` reports the new leader; new
|
baseline. After promotion `/cluster/status` reports the new leader; new
|
||||||
writes route there; the new leader's ship queue activates and the demoted
|
writes route there; the new leader's ship queue activates and the demoted
|
||||||
node's deactivates. An unknown region returns **400**. There is no automatic
|
node's deactivates. An unknown region returns **400**. Since m11p4 `promote` is
|
||||||
election — this is the operator's failover lever (m11p4 adds elections).
|
a **fenced transfer** (it drains the target, then sanctions an election), not
|
||||||
|
the availability mechanism — automatic failover handles a dead leader with no
|
||||||
|
operator action ([§9.1](#91-automatic-failover-m11p4--the-default)); this verb
|
||||||
|
is for maintenance and deliberate successor choice
|
||||||
|
([§9.2](#92-manual-promote-a-fenced-transfer-maintenance--override)).
|
||||||
|
|
||||||
### Simulate a partition & heal
|
### Simulate a partition & heal
|
||||||
|
|
||||||
@ -582,6 +684,65 @@ is an exact no-op on scores (no drift). `/cluster/reconcile/snapshot` is the
|
|||||||
INTERNAL snapshot-exchange leg this verb drives (marker required); operators never
|
INTERNAL snapshot-exchange leg this verb drives (marker required); operators never
|
||||||
call it directly.
|
call it directly.
|
||||||
|
|
||||||
|
### Membership verbs (m11p5 — online add / remove / inspect / reseed)
|
||||||
|
|
||||||
|
Membership is **data on the replicated log** (kind-4 records, latest wins,
|
||||||
|
folded into a `ClusterMembership` cell). All four verbs route to / are answered
|
||||||
|
by the leader and are **quorum-commit-gated**, one change at a time. The leader
|
||||||
|
**refuses every conf-change until all current voters report kind-4 capability**
|
||||||
|
(the mixed-version safety gate — complete the binary upgrade first).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Add a node (idempotent by name): forwards to the leader, which assigns the
|
||||||
|
# next id, appends a Learner record, and answers AFTER quorum-commit.
|
||||||
|
curl -X POST "$BASE/cluster/join" \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{ "name": "eu-2",
|
||||||
|
"grpc_addr": "eu-2.tidaldb-peers.svc.cluster.local:9600",
|
||||||
|
"http_addr": "eu-2.tidaldb-peers.svc.cluster.local:9504" }'
|
||||||
|
# → { "id": 4, "role": "learner", "term": 7, "leader": "us-east", "members": [ … ] }
|
||||||
|
```
|
||||||
|
|
||||||
|
The joiner normally seed-joins itself ([§1b](#1b-multi-process-one-process-per-region));
|
||||||
|
this verb is the same conf-change for tooling. A re-join from a known name
|
||||||
|
returns its existing id and current role and appends nothing. The leader's
|
||||||
|
**auto-promotion** duty (a standing duty, re-armed on every activation and
|
||||||
|
membership apply — it survives the joining-era leader's death) flips the learner
|
||||||
|
to Voter once it is within `replication.learner_promote_lag` of the flushed
|
||||||
|
frontier; `promotion_pending (lag=N)` in `/cluster/status/local` makes a stuck
|
||||||
|
scale-up diagnosable.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Inspect the applied roster (ids, names, addresses, roles, conf version).
|
||||||
|
curl "$BASE/cluster/members" | jq
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Remove a node: appends a Removed tombstone (quorum-commit-gated). The peer's
|
||||||
|
# ship cell is retired only AFTER the record is delivered-to/acked-by the removed
|
||||||
|
# peer (bounded give-up → tidaldb_cluster_remove_delivery_giveups_total); the
|
||||||
|
# removed node's readiness flips to 503 and it stops campaigning. Its id is BURNED
|
||||||
|
# (never renumbered, never reused).
|
||||||
|
curl -X POST "$BASE/cluster/members/remove" \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-d '{ "region": "eu-2" }'
|
||||||
|
# → { "removed": "eu-2", "membership_version": 9 }
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Force a reseed on demand: latches the durable reseed_required marker. The node
|
||||||
|
# keeps serving degraded (voting enabled) and reseeds via snapshot on its NEXT
|
||||||
|
# boot (or self-restarts if replication.reseed_self_restart is true and quorum
|
||||||
|
# can be sustained without it). See §9.1.
|
||||||
|
curl -X POST "$BASE/cluster/reseed"
|
||||||
|
# → { "reseed_required": true }
|
||||||
|
```
|
||||||
|
|
||||||
|
**Scale-down order (decommission):** call `/cluster/members/remove` **first**
|
||||||
|
(so the cluster's quorum math shrinks before the node disappears), wait for the
|
||||||
|
record to quorum-commit, then stop / delete the node — lowest ordinal last under
|
||||||
|
a StatefulSet.
|
||||||
|
|
||||||
## 7. Sharded scatter-gather API
|
## 7. Sharded scatter-gather API
|
||||||
|
|
||||||
The `/sharded/*` routes hash-partition entities across regions
|
The `/sharded/*` routes hash-partition entities across regions
|
||||||
@ -691,7 +852,7 @@ it silently applies **leader-ack semantics to a `quorum` request** — a
|
|||||||
durability downgrade the caller cannot see. Upgrade order:
|
durability downgrade the caller cannot see. Upgrade order:
|
||||||
|
|
||||||
1. Promote leadership off the leader node if needed, upgrade it, promote it
|
1. Promote leadership off the leader node if needed, upgrade it, promote it
|
||||||
back (or simply upgrade the standing leader per [§9](#9-failover-drill)'s
|
back (or simply upgrade the standing leader per [§9](#9-failover-multi-process)'s
|
||||||
restart procedure). From this moment `ack=quorum` is honored: the commit
|
restart procedure). From this moment `ack=quorum` is honored: the commit
|
||||||
index rides the m11p2 ship-ack floor hints from not-yet-upgraded
|
index rides the m11p2 ship-ack floor hints from not-yet-upgraded
|
||||||
followers (correct, just laggier).
|
followers (correct, just laggier).
|
||||||
@ -707,10 +868,12 @@ Other facts unchanged from m11p1/p2: the success code never waits on
|
|||||||
shipping for `ack=leader` (sender threads push the WAL flush feed's tail off
|
shipping for `ack=leader` (sender threads push the WAL flush feed's tail off
|
||||||
the request path; `replication.batch_max_events`/`window` tune it); a failed
|
the request path; `replication.batch_max_events`/`window` tune it); a failed
|
||||||
fsync errors that write and nothing unfsynced can ship; long-outage data is
|
fsync errors that write and nothing unfsynced can ship; long-outage data is
|
||||||
follower-pulled via `StreamSegments`; a leader crash is **not** an automatic
|
follower-pulled via `StreamSegments` (or, when it has rotated past the leader's
|
||||||
failover (an operator promotes a survivor — see [§9](#9-failover-drill), and
|
retained WAL, via the m11p5 `FetchSnapshot` snapshot transfer); a leader crash
|
||||||
under `ack=quorum` **promote the survivor with the highest `applied_events`**
|
is an **automatic failover** since m11p4 (the survivors elect the
|
||||||
— that rule is what makes the zero-acked-loss guarantee hold).
|
up-to-date successor — see [§9.1](#91-automatic-failover-m11p4--the-default);
|
||||||
|
the vote restriction only elects a node whose log covers every quorum-acked
|
||||||
|
write, which is what makes the zero-acked-loss guarantee hold).
|
||||||
|
|
||||||
In short: **`ack=leader` = leader durability. `ack=quorum` = failover-survivable
|
In short: **`ack=leader` = leader durability. `ack=quorum` = failover-survivable
|
||||||
durability, priced at one pipelined replication round trip and majority
|
durability, priced at one pipelined replication round trip and majority
|
||||||
@ -726,23 +889,41 @@ stay readable — no migration). Three behaviors follow:
|
|||||||
instead of booting with the data invisibly absent (`segments=0` — the
|
instead of booting with the data invisibly absent (`segments=0` — the
|
||||||
2026-06-11 p3 rollout failure mode). Remedy: run a compatible binary, or
|
2026-06-11 p3 rollout failure mode). Remedy: run a compatible binary, or
|
||||||
reseed the node (delete its PVC and let it pull from the leader).
|
reseed the node (delete its PVC and let it pull from the leader).
|
||||||
- **Unservable catch-up is a structured refusal.** A leader that cannot
|
- **Unservable catch-up resolves via snapshot transfer (m11p5).** A leader
|
||||||
serve a follower's requested range answers the `StreamSegments` pull with
|
that cannot serve a follower's requested range from its retained WAL answers
|
||||||
`FAILED_PRECONDITION` — `"segments not available from seq N; snapshot
|
the `StreamSegments` pull with `FAILED_PRECONDITION` — `"segments not
|
||||||
required"` — and the follower logs it as *catch-up unservable… needs a
|
available from seq N; snapshot required"`, carrying the typed trailer
|
||||||
snapshot (m11p5) or an operator reseed*. That log line repeating every
|
`x-tidal-catchup: snapshot-required`. Since m11p5 the follower **latches a
|
||||||
retry interval IS the alert; until snapshot transfer ships (m11p5), reseed
|
durable `reseed_required` marker** (only on that typed trailer — an ordinary
|
||||||
the follower.
|
election term-mismatch never latches it fleet-wide) and reseeds itself via the
|
||||||
|
`FetchSnapshot` snapshot stream on its next boot (or self-restarts if
|
||||||
|
`replication.reseed_self_restart` is set) — no operator verb, no
|
||||||
|
`wipe_data_dir`. See [§9.1](#91-automatic-failover-m11p4--the-default). The
|
||||||
|
marker is surfaced in `/cluster/status/local` (`reseed_required: true`) and the
|
||||||
|
`tidaldb_cluster_reseed_required` gauge.
|
||||||
- **Failed pulls self-heal on a timer.** A catch-up pull that fails (e.g.
|
- **Failed pulls self-heal on a timer.** A catch-up pull that fails (e.g.
|
||||||
the leader's gRPC server not yet ready during a rolling restart) retries
|
the leader's gRPC server not yet ready during a rolling restart) retries
|
||||||
every `replication.catchup_retry_ms` (default 30000) without waiting for
|
every `replication.catchup_retry_ms` (default 30000) without waiting for
|
||||||
a write to re-expose the gap — an idle cluster no longer strands lagged
|
a write to re-expose the gap — an idle cluster no longer strands lagged
|
||||||
followers.
|
followers.
|
||||||
|
|
||||||
**Downgrade hazard:** a pre-m11p4 binary reading a header-bearing segment
|
**Downgrade hazard (m11p4):** a pre-m11p4 binary reading a header-bearing
|
||||||
treats the header as a torn tail and may truncate the final segment.
|
segment treats the header as a torn tail and may truncate the final segment.
|
||||||
Downgrading across the m11p4 boundary requires reseeding the node's WAL.
|
Downgrading across the m11p4 boundary requires reseeding the node's WAL.
|
||||||
|
|
||||||
|
**Membership records + capability gate (m11p5).** A **kind-4 membership
|
||||||
|
record** is a new WAL blob kind. A kind-4 record shipped to a **pre-p5
|
||||||
|
follower** is an unknown batch kind → `WalError::Corruption` → that follower's
|
||||||
|
torn-state receiver halt, **permanent across restarts** (boot self-heal
|
||||||
|
re-pulls the same record). Both followers halted = a quorum-write outage. To
|
||||||
|
make this structurally impossible, `HeartbeatResponse`/`ReportApplied` carry a
|
||||||
|
`capabilities` bit-field (proto3 zero-default = pre-p5 = incapable) and the
|
||||||
|
leader **refuses `/cluster/join` and every conf-change until all current voters
|
||||||
|
report kind-4 capability** — so the first conf-change cannot fire mid-upgrade.
|
||||||
|
**Downgrade rule (kind-3 precedent verbatim): once any kind-4 record is in a
|
||||||
|
node's WAL, downgrading it below p5 requires a reseed.** Complete the binary
|
||||||
|
upgrade across all voters before adding, removing, or replacing a node.
|
||||||
|
|
||||||
## 9. Failover (multi-process)
|
## 9. Failover (multi-process)
|
||||||
|
|
||||||
### 9.1 Automatic failover (m11p4 — the default)
|
### 9.1 Automatic failover (m11p4 — the default)
|
||||||
@ -777,15 +958,35 @@ What the operator sees:
|
|||||||
`ack=leader` writes during a minority partition are bounded by the lease,
|
`ack=leader` writes during a minority partition are bounded by the lease,
|
||||||
and `ack=quorum` writes were never at risk.
|
and `ack=quorum` writes were never at risk.
|
||||||
|
|
||||||
**Divergent suffix / quarantine.** A node that held leader-acked (never
|
**Divergent suffix / quarantine → automated reseed (m11p5).** A node that
|
||||||
quorum-acked) writes when it died can rejoin into a cluster that elected
|
held leader-acked (never quorum-acked) writes when it died can rejoin into a
|
||||||
past them. It detects this at term-join and **quarantines**: it serves
|
cluster that elected past them. It detects this at term-join and
|
||||||
status (`quarantined: true`, metric
|
**quarantines**: it serves status (`quarantined: true`, metric
|
||||||
`tidaldb_cluster_divergence_quarantined`) and keeps voting, but refuses the
|
`tidaldb_cluster_divergence_quarantined`) and keeps voting, but refuses the
|
||||||
data plane. Recovery is a **reseed**: stop it, wipe its data dir, restart —
|
data plane. Since m11p5 recovery is **automatic and full-history** — no
|
||||||
it recovers the current log via the catch-up stream (m11p5's snapshot
|
`wipe_data_dir`: the quarantine latches the durable `reseed_required` marker,
|
||||||
transfer automates full-history reseeds). This is strictly leader-ack-only
|
the node reseeds via the `FetchSnapshot` snapshot stream on its next boot (or
|
||||||
data, within the documented `ack=leader` crash contract (§8).
|
self-restarts if `replication.reseed_self_restart` is set and quorum can be
|
||||||
|
sustained without it), rejoins clean, and the divergence gauge clears. This is
|
||||||
|
strictly leader-ack-only data, within the documented `ack=leader` crash
|
||||||
|
contract (§8). The tier-3 `cluster_reseed.rs` proves the full quarantine →
|
||||||
|
marker → restart → reseeded → gauges-cleared loop.
|
||||||
|
|
||||||
|
**The three-way term-join rule (m11p5).** The divergent-suffix check above is
|
||||||
|
one of three outcomes a node reaches when it joins a new term, comparing its own
|
||||||
|
stream position against the leader's election-time position (`prev_log`, carried
|
||||||
|
on the heartbeat):
|
||||||
|
|
||||||
|
- `own > prev_log` → **divergent suffix** → quarantine (above);
|
||||||
|
- `own < prev_log` → the node is genuinely **missing committed-era history**
|
||||||
|
that the new stream's baseline jump would silently skip (the p4 carried
|
||||||
|
hazard) → it latches `reseed_required` and reseeds via snapshot (no silent
|
||||||
|
gap);
|
||||||
|
- `own == prev_log` (or a within-term rejoin) → **clean**, catch-up via the
|
||||||
|
stream.
|
||||||
|
|
||||||
|
A snapshot-installed node always joins clean by construction (its WAL is the
|
||||||
|
leader's copy, so its tail term equals the leader's).
|
||||||
|
|
||||||
To run the pre-m11p4 posture (operator-driven failover, no automatic
|
To run the pre-m11p4 posture (operator-driven failover, no automatic
|
||||||
elections, no check-quorum step-down), set in the topology:
|
elections, no check-quorum step-down), set in the topology:
|
||||||
@ -888,6 +1089,28 @@ its boot-time `StreamSegments` catch-up request — no operator verb needed
|
|||||||
data dir with the new binary, heal) — see `cluster_lifecycle.rs::mp_rolling_upgrade_no_loss_no_stall`,
|
data dir with the new binary, heal) — see `cluster_lifecycle.rs::mp_rolling_upgrade_no_loss_no_stall`,
|
||||||
which proves zero acknowledged-write loss across a full rolling upgrade under load.
|
which proves zero acknowledged-write loss across a full rolling upgrade under load.
|
||||||
|
|
||||||
|
### Node-replace drill (m11p5)
|
||||||
|
|
||||||
|
Replacing a dead or recycled node is `kubectl delete pod` — no topology edit, no
|
||||||
|
operator verb:
|
||||||
|
|
||||||
|
- **PVC retained** (the data dir survives the pod): the replacement boots on the
|
||||||
|
same data dir and converges via its boot-time `StreamSegments` catch-up — the
|
||||||
|
ordinary restart path above. If it rotated past the leader's retained WAL while
|
||||||
|
down, it reseeds via `FetchSnapshot` automatically (the `reseed_required`
|
||||||
|
marker + snapshot path, [§9.1](#91-automatic-failover-m11p4--the-default)).
|
||||||
|
- **PVC deleted + pod deleted** (fresh node): the replacement comes up empty and
|
||||||
|
**seed-joins** ([§1b](#1b-multi-process-one-process-per-region)) — it `--seed`s
|
||||||
|
a survivor, `FetchSnapshot`s the current state, and the leader auto-promotes it
|
||||||
|
back to Voter. Under the `k8s/cluster/` StatefulSet this is the default: the
|
||||||
|
pod's args carry `--seed` against the headless Service, so a recreated pod
|
||||||
|
rejoins with no human in the loop.
|
||||||
|
|
||||||
|
**Add a node:** scale the StatefulSet up (pod N≥3 seed-joins as a learner and
|
||||||
|
auto-promotes). **Remove a node:** `POST /cluster/members/remove` **first**
|
||||||
|
([§6](#6-cluster-management-api)), wait for the record to quorum-commit, then
|
||||||
|
scale down (lowest ordinal last).
|
||||||
|
|
||||||
## Performance (measured over real localhost processes)
|
## Performance (measured over real localhost processes)
|
||||||
|
|
||||||
| Operation | SLA | Measured (p99 / typical) |
|
| Operation | SLA | Measured (p99 / typical) |
|
||||||
@ -908,19 +1131,22 @@ against the measured fsync histogram.
|
|||||||
## Cross-references
|
## Cross-references
|
||||||
|
|
||||||
- **Kubernetes deployment** — [docs/runbooks/kubernetes.md](kubernetes.md)
|
- **Kubernetes deployment** — [docs/runbooks/kubernetes.md](kubernetes.md)
|
||||||
(standalone single-replica is the recommended production deployment until
|
(the hardened standalone single-replica set in [`k8s/`](../../k8s/), and the
|
||||||
quorum-ack / auto-failover land; an experimental StatefulSet-per-region sketch
|
multi-region cluster reference in [`k8s/cluster/`](../../k8s/cluster/) — one
|
||||||
for multi-process cluster mode is noted there).
|
StatefulSet + headless Service peer discovery + PDB, with `--seed`-based scale
|
||||||
|
and `kubectl delete pod` node-replace, shipped in m11p5).
|
||||||
- **Server deployment guide** — [docs/guides/server-deployment.md](../guides/server-deployment.md)
|
- **Server deployment guide** — [docs/guides/server-deployment.md](../guides/server-deployment.md)
|
||||||
(standalone and cluster launch, config, env, health probes).
|
(standalone and cluster launch, config, env, health probes).
|
||||||
- **Monitoring & alerts** — [docs/ops/monitoring.md](../ops/monitoring.md)
|
- **Monitoring & alerts** — [docs/ops/monitoring.md](../ops/monitoring.md)
|
||||||
(Prometheus scrape config, replication-lag and WAL metrics, recommended alerts;
|
(Prometheus scrape config, replication-lag and WAL metrics, recommended alerts;
|
||||||
per-region replication lag is observable via `/cluster/status` `lag_events`;
|
per-region replication lag is observable via `/cluster/status` `lag_events`;
|
||||||
remember the `/metrics` endpoint is unauthenticated — bind it internally).
|
remember the `/metrics` endpoint is unauthenticated — bind it internally).
|
||||||
- **Roadmap / M8 status & known gaps** —
|
- **Roadmap / cluster status & known gaps** —
|
||||||
[docs/planning/ROADMAP.md](../planning/ROADMAP.md) for the distributed-fabric
|
[docs/planning/ROADMAP.md](../planning/ROADMAP.md) and
|
||||||
status (M8 COMPLETE), the m8p1–m8p10 phase history, and the post-M8 follow-ups
|
[docs/roadmap-to-cluster.md](../roadmap-to-cluster.md) for the M11 cluster
|
||||||
(quorum-ack writes, automatic failure detection / leader election).
|
status — quorum-ack writes (m11p3), automatic failover (m11p4), and
|
||||||
|
membership/discovery/elasticity (m11p5) all shipped; sharding × replication
|
||||||
|
(p6), security hardening (p7), and continuous correctness (p9) remain.
|
||||||
- **API & schema reference** — [API.md](../../API.md),
|
- **API & schema reference** — [API.md](../../API.md),
|
||||||
[QUICKSTART.md](../../QUICKSTART.md), and the live `/openapi.json` document.
|
[QUICKSTART.md](../../QUICKSTART.md), and the live `/openapi.json` document.
|
||||||
- **Scope & vision** — [VISION.md](../../VISION.md).
|
- **Scope & vision** — [VISION.md](../../VISION.md).
|
||||||
|
|||||||
@ -1,35 +1,34 @@
|
|||||||
# tidalDB on Kubernetes
|
# tidalDB on Kubernetes
|
||||||
|
|
||||||
How to run tidalDB on Kubernetes: a hardened, single-node **standalone**
|
How to run tidalDB on Kubernetes. Two manifest sets ship in this repo, mutually
|
||||||
deployment as a `StatefulSet` with a durable volume, the three health probes,
|
exclusive per namespace:
|
||||||
metrics, secret-backed auth, and graceful rolling updates. The manifests live in
|
|
||||||
[`k8s/`](../../k8s/) and apply with `kubectl apply -k k8s/`.
|
|
||||||
|
|
||||||
> ## Deploy the STANDALONE server, one replica
|
- **[`k8s/`](../../k8s/)** — the hardened single-node **standalone** deployment
|
||||||
|
(namespace `tidaldb`, `replicas: 1`). Apply with `kubectl apply -k k8s/`. This
|
||||||
|
is the recommended default: a `StatefulSet` with a durable volume, the three
|
||||||
|
health probes, metrics, secret-backed auth, and graceful rolling updates.
|
||||||
|
- **[`k8s/cluster/`](../../k8s/cluster/)** — the multi-region **cluster**
|
||||||
|
reference (namespace `tidaldb-cluster`, `replicas: 3`, automatic election,
|
||||||
|
quorum-ack writes, elastic membership). Apply with `kubectl apply -k
|
||||||
|
k8s/cluster/`. Still `--experimental-cluster`-gated. See
|
||||||
|
[Cluster mode on Kubernetes](#cluster-mode-on-kubernetes) below.
|
||||||
|
|
||||||
|
> ## Deploy the STANDALONE server, one replica (recommended default)
|
||||||
>
|
>
|
||||||
> tidalDB is single-node-first: the server wraps one embedded engine whose state
|
> tidalDB is single-node-first: the server wraps one embedded engine whose state
|
||||||
> (WAL + checkpoints + indexes) lives on a data dir. It scales **vertically**
|
> (WAL + checkpoints + indexes) lives on a data dir. It scales **vertically**
|
||||||
> (a bigger pod), not by adding replicas — there is no shared-storage multi-writer
|
> (a bigger pod), not by adding replicas — there is no shared-storage multi-writer
|
||||||
> mode, so `replicas: 1` in the StatefulSet is load-bearing. The experimental
|
> mode, so `replicas: 1` in the standalone StatefulSet is load-bearing. Run one
|
||||||
> multi-region `cluster` subcommand now has a **multi-process** mode (`--region`,
|
|
||||||
> one process per region, real gRPC peering, real process isolation — shipped in
|
|
||||||
> m8p10), but it is still **experimental**: writes are leader-durable, **not**
|
|
||||||
> quorum-acked, and failover is operator-driven (`/cluster/promote`), **not**
|
|
||||||
> automatic election. So it is not yet a production-HA story
|
|
||||||
> ([cluster runbook](cluster.md)). **The recommended production deployment remains
|
|
||||||
> a single STANDALONE pod** until quorum-ack writes and automatic failover land
|
|
||||||
> (tracked as post-M8 follow-ups in [ROADMAP.md](../planning/ROADMAP.md)). Run one
|
|
||||||
> standalone pod, back it with a durable `PersistentVolume`, and recover from the
|
> standalone pod, back it with a durable `PersistentVolume`, and recover from the
|
||||||
> WAL on restart (see [recovery](../ops/recovery.md)).
|
> WAL on restart (see [recovery](../ops/recovery.md)).
|
||||||
>
|
>
|
||||||
> **Experimental: cluster mode on Kubernetes.** Multi-process cluster mode maps to
|
> **The standalone pod remains the recommended deployment.** The multi-region
|
||||||
> a `StatefulSet` (or one StatefulSet *per region*) where each pod runs
|
> `cluster` mode is now genuinely HA — quorum-acked writes (m11p3), automatic
|
||||||
> `tidal-server cluster --region <name>` with its own `PersistentVolume` for
|
> election/failover (m11p4), and elastic membership (m11p5) all exist — but it is
|
||||||
> `--data-dir`, a stable `grpc_addr`/`http_addr` per region (a headless `Service`
|
> still `--experimental-cluster`-gated, so choose it deliberately when you need
|
||||||
> gives each pod stable DNS), and `TIDAL_ALLOW_EXPERIMENTAL_CLUSTER=1`. This is a
|
> multi-node availability, and keep a single standalone pod when you do not. The
|
||||||
> sketch, **not** a promised manifest set — `k8s/` ships only the hardened
|
> cluster reference is [`k8s/cluster/`](../../k8s/cluster/); see
|
||||||
> standalone deployment. Treat a cluster-mode k8s deployment as experimental and
|
> [Cluster mode on Kubernetes](#cluster-mode-on-kubernetes).
|
||||||
> operator-supervised (manual promote + heal), per the cluster runbook.
|
|
||||||
|
|
||||||
## What's in `k8s/`
|
## What's in `k8s/`
|
||||||
|
|
||||||
@ -211,9 +210,197 @@ your registry image.
|
|||||||
| `401 Unauthorized` on data routes | Wrong/empty `tidaldb-api-key` secret; clients must send `Authorization: Bearer <key>` |
|
| `401 Unauthorized` on data routes | Wrong/empty `tidaldb-api-key` secret; clients must send `Authorization: Bearer <key>` |
|
||||||
| Writes lost after restart | Data dir not on the PVC — confirm `--data-dir /data` and the `data` volume mount |
|
| Writes lost after restart | Data dir not on the PVC — confirm `--data-dir /data` and the `data` volume mount |
|
||||||
|
|
||||||
|
## Cluster mode on Kubernetes
|
||||||
|
|
||||||
|
The cluster reference is [`k8s/cluster/`](../../k8s/cluster/): **ONE `StatefulSet`
|
||||||
|
named `tidaldb`, `replicas: 3`**, in its own namespace `tidaldb-cluster`. Each
|
||||||
|
pod is a region; the three pods (`tidaldb-0/1/2`) form the initial voter set.
|
||||||
|
This is real HA — automatic election/failover, quorum-acked writes, and
|
||||||
|
membership changes that ride the replicated log — but the mode is still
|
||||||
|
`--experimental-cluster`-gated (set via `TIDAL_ALLOW_EXPERIMENTAL_CLUSTER=1` in
|
||||||
|
the manifest). It is **mutually exclusive** with the standalone set per namespace:
|
||||||
|
they share the StatefulSet name `tidaldb`, and the standalone set's `replicas: 1`
|
||||||
|
is load-bearing. Deploy one or the other.
|
||||||
|
|
||||||
|
### Why one StatefulSet (not one per region)
|
||||||
|
|
||||||
|
Before m11p5, a pod bound its own `grpc_addr` literally, and a pod cannot bind a
|
||||||
|
Service ClusterIP — so each region needed a per-pod topology variant, defeating
|
||||||
|
the "every process parses the same file" contract. The m11p5 **bind/advertise
|
||||||
|
split** removes that: `grpc_addr` is the address peers *dial* (a per-pod headless
|
||||||
|
DNS name, re-resolved by tonic on every reconnect, so a rescheduled pod on a new
|
||||||
|
IP is reachable with no peer restart), while `grpc_bind` is the local socket
|
||||||
|
(`0.0.0.0:9601`). One topology ConfigMap names all three regions by their stable
|
||||||
|
pod DNS, and every pod mounts it unmodified.
|
||||||
|
|
||||||
|
### What's in `k8s/cluster/`
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `namespace.yaml` | The `tidaldb-cluster` namespace (mutually exclusive with `tidaldb`) |
|
||||||
|
| `topology-configmap.yaml` | The ONE bootstrap topology shared by all pods: 3 regions by per-pod DNS (`grpc_addr` advertised, `grpc_bind` `0.0.0.0`), `replication.ack: quorum`, `replication.reseed_self_restart: true`, the election block |
|
||||||
|
| `schema-configmap.yaml` | The schema YAML every region loads (`--schema`) |
|
||||||
|
| `statefulset.yaml` | `replicas: 3`, `podManagementPolicy: Parallel`, `TIDAL_REGION` from `POD_NAME`, durable PVC at `/data` with `--data-dir /data/db`, the three probes (readiness now cluster-aware), uid 10001, `terminationGracePeriodSeconds: 60`, topology spread, and the ordinal-branching scale-up wrapper |
|
||||||
|
| `service-peers.yaml` | Headless peer Service (`publishNotReadyAddresses: true`) — stable per-pod DNS, keeps not-ready joiners resolvable for peers |
|
||||||
|
| `service-client.yaml` | Client Service — readiness-gated, drops not-ready/joining/quarantined pods from load balancing |
|
||||||
|
| `poddisruptionbudget.yaml` | `maxUnavailable: 1` — a 3-voter cluster keeps quorum across one disruption |
|
||||||
|
| `secret.example.yaml` | Template for the `tidaldb-credentials` / `TIDAL_API_KEY` secret (create the real one out-of-band) |
|
||||||
|
| `kustomization.yaml` | Ties it together for `kubectl apply -k k8s/cluster/` (secret excluded) |
|
||||||
|
|
||||||
|
### The two Services
|
||||||
|
|
||||||
|
- **`tidaldb-peers`** (headless, `clusterIP: None`, `publishNotReadyAddresses:
|
||||||
|
true`): gives each pod the stable DNS name
|
||||||
|
`tidaldb-N.tidaldb-peers.tidaldb-cluster.svc.cluster.local`, which the topology
|
||||||
|
advertises. `publishNotReadyAddresses: true` is load-bearing — a joiner is
|
||||||
|
*not ready* until it first converges, but peers must still resolve it to feed
|
||||||
|
it a snapshot + catch-up stream; without this the joiner could never reach a
|
||||||
|
seed to become ready (a deadlock).
|
||||||
|
- **`tidaldb`** (client-facing, VIP, readiness-gated): the address in-cluster
|
||||||
|
clients hit. Default readiness gating drops not-ready/joining/quarantined/
|
||||||
|
draining pods, so a client is never routed to a node that is still catching up.
|
||||||
|
|
||||||
|
### The readiness predicate (cluster-aware `/health`)
|
||||||
|
|
||||||
|
The `readinessProbe` stays `GET /health`, but in cluster mode it is now
|
||||||
|
predicate-driven (m11p5 §4). `/health` returns **503** when the node is:
|
||||||
|
|
||||||
|
- shutting down (SIGTERM drain — leaves both Services before it stops accepting);
|
||||||
|
- **quarantined** (an m11p4 divergent leader-acked suffix — serves status and
|
||||||
|
votes, refuses the data plane until reseeded);
|
||||||
|
- **removed / decommissioned** (a `Removed` membership record reached it, or a
|
||||||
|
voter's typed `removed` signal told it so);
|
||||||
|
- a **joiner** (seed-join learner) or **install boot** (snapshot-reseeded) that
|
||||||
|
has **not yet first-converged** — convergence means the boot catch-up pull
|
||||||
|
completed at least once AND lag fell to `≤ learner_promote_lag` (hysteresis;
|
||||||
|
**never** `lag == 0`, which an open-loop write load keeps perpetually false).
|
||||||
|
Sticky-ready after the first convergence.
|
||||||
|
|
||||||
|
A **restarted, PVC-retained voter is Ready on today's terms** — no regression for
|
||||||
|
ordinary pod restarts. `GET /cluster/status/local` surfaces the inputs
|
||||||
|
(`lag_events`, `quarantined`, `role`, `term`, `reseed_required`) for diagnosis,
|
||||||
|
plus the `tidaldb_cluster_reseed_required` and `tidaldb_cluster_divergence`
|
||||||
|
gauges.
|
||||||
|
|
||||||
|
### Deploy the cluster
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Build/publish an image whose runtime user is uid 10001 (matches the
|
||||||
|
# securityContext so the PVC is writable). One image serves every subcommand.
|
||||||
|
docker build -f docker/deploy/Dockerfile -t <registry>/tidaldb:<tag> .
|
||||||
|
docker push <registry>/tidaldb:<tag>
|
||||||
|
# Set image: in k8s/cluster/statefulset.yaml (pin by @sha256 in production).
|
||||||
|
|
||||||
|
# 2. Namespace + the credentials secret (stress/Ref-A shape: name
|
||||||
|
# tidaldb-credentials, key TIDAL_API_KEY). Same key on EVERY pod and client.
|
||||||
|
kubectl create namespace tidaldb-cluster
|
||||||
|
kubectl -n tidaldb-cluster create secret generic tidaldb-credentials \
|
||||||
|
--from-literal=TIDAL_API_KEY="$(openssl rand -hex 32)"
|
||||||
|
|
||||||
|
# 3. Apply and wait for the 3-pod voter set.
|
||||||
|
kubectl apply -k k8s/cluster/
|
||||||
|
kubectl -n tidaldb-cluster rollout status statefulset/tidaldb --timeout=300s
|
||||||
|
|
||||||
|
# 4. Confirm three reachable regions with low lag, and check each node's role.
|
||||||
|
kubectl -n tidaldb-cluster exec tidaldb-0 -- \
|
||||||
|
curl -s localhost:9500/cluster/status | jq '.regions[] | {name, lag_events, reachable}'
|
||||||
|
for p in tidaldb-0 tidaldb-1 tidaldb-2; do
|
||||||
|
kubectl -n tidaldb-cluster exec "$p" -- \
|
||||||
|
curl -s localhost:9500/cluster/status/local | jq '{role, term, membership_role, lag_events}'
|
||||||
|
done
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scale up (3 → N): seed-join as a learner, auto-promote
|
||||||
|
|
||||||
|
`kubectl scale` is the whole story — **no topology edits**. Pods with ordinal
|
||||||
|
`≥ 3` boot with `--seed` (the StatefulSet's ordinal-branching wrapper adds it
|
||||||
|
automatically) and learn their roster/id/term from a seed, joining as a
|
||||||
|
**learner**. The leader auto-promotes a learner to a voter once its durable mark
|
||||||
|
is within `learner_promote_lag` of the leader's frontier (or stops falling behind
|
||||||
|
for K rounds under sustained load).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Grow to 5 voters. Pods tidaldb-3 and tidaldb-4 seed-join + auto-promote.
|
||||||
|
kubectl -n tidaldb-cluster scale statefulset/tidaldb --replicas=5
|
||||||
|
kubectl -n tidaldb-cluster rollout status statefulset/tidaldb --timeout=600s
|
||||||
|
# Watch the new members converge and promote (promotion_pending shows the lag):
|
||||||
|
kubectl -n tidaldb-cluster exec tidaldb-0 -- \
|
||||||
|
curl -s localhost:9500/cluster/members | jq '.members[] | {id, name, role}'
|
||||||
|
```
|
||||||
|
|
||||||
|
A scaled pod still mounts the shared topology ConfigMap — a `--seed` boot
|
||||||
|
**requires** the local config for the behavioral knob blocks (`replication`,
|
||||||
|
`wal`, `election`, `timeouts`, `grpc_tls`); its `regions:` list is ignored for
|
||||||
|
the seed joiner's roster (the join response is authoritative).
|
||||||
|
|
||||||
|
### Scale down (N → fewer): remove verb FIRST, then scale
|
||||||
|
|
||||||
|
Decommission a member **before** removing its pod, so the cluster stops counting
|
||||||
|
it toward quorum cleanly. Remove the highest-ordinal members (StatefulSet deletes
|
||||||
|
lowest-ordinal-last on scale-down).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Going 5 -> 3: decommission tidaldb-4, then tidaldb-3, then scale.
|
||||||
|
# Remove verb: POST /cluster/members/remove {"region": "<name>"} (any node
|
||||||
|
# forwards to the leader; one-at-a-time, quorum-commit-gated).
|
||||||
|
kubectl -n tidaldb-cluster exec tidaldb-0 -- curl -s -X POST \
|
||||||
|
-H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
|
||||||
|
-d '{"region":"tidaldb-4"}' localhost:9500/cluster/members/remove
|
||||||
|
kubectl -n tidaldb-cluster exec tidaldb-0 -- curl -s -X POST \
|
||||||
|
-H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
|
||||||
|
-d '{"region":"tidaldb-3"}' localhost:9500/cluster/members/remove
|
||||||
|
# Each Remove is delivered to the removed peer (which flips to 503 and stops
|
||||||
|
# campaigning) before its ship cell retires. Only then is it safe to scale.
|
||||||
|
kubectl -n tidaldb-cluster scale statefulset/tidaldb --replicas=3
|
||||||
|
```
|
||||||
|
|
||||||
|
Removing pods without the remove verb leaves zombie members the cluster still
|
||||||
|
expects — never scale down before decommissioning.
|
||||||
|
|
||||||
|
### Node / pod replacement
|
||||||
|
|
||||||
|
- **`kubectl delete pod tidaldb-N` (PVC retained):** the StatefulSet recreates
|
||||||
|
the pod onto its existing PVC. It boots a follower, replays its WAL, and
|
||||||
|
catches up via the `StreamSegments` stream (boot-time + the 30 s catch-up
|
||||||
|
timer). No operator verb. This is the routine replace — already proven by the
|
||||||
|
p4 leader-kill regression (lag → 0 within ~10 s).
|
||||||
|
- **PVC + pod delete (fresh reseed):** delete the PVC *and* the pod. The new pod
|
||||||
|
comes up with an empty data dir, latches an install boot, and **reseeds via
|
||||||
|
snapshot** (`FetchSnapshot` + stream) from the leader, then rejoins clean. Use
|
||||||
|
this when the data dir is corrupt or the node fell behind a compacted leader.
|
||||||
|
Readiness stays 503 until the snapshot install first converges.
|
||||||
|
|
||||||
|
### Self-healing reseed (quarantine / behind-compaction)
|
||||||
|
|
||||||
|
`replication.reseed_self_restart: true` (set in the topology ConfigMap) makes a
|
||||||
|
node that durably latches `reseed_required` (an m11p4 divergence quarantine, or a
|
||||||
|
typed `snapshot-required` refusal) drain and exit(0); the StatefulSet restarts it
|
||||||
|
and the **boot-time install** reseeds it via snapshot, clearing the quarantine
|
||||||
|
and the divergence gauge with no operator verb and no PVC wipe. The self-restart
|
||||||
|
is **refused** (loudly, in `/cluster/status/local` + the gauge) when the
|
||||||
|
remaining voters cannot sustain quorum without this node — exiting during a
|
||||||
|
2-voter window would be a total write outage. `POST /cluster/reseed` latches the
|
||||||
|
marker on demand.
|
||||||
|
|
||||||
|
### PodDisruptionBudget and graceful shutdown
|
||||||
|
|
||||||
|
`maxUnavailable: 1` lets a voluntary disruption (node drain, autoscaler, rolling
|
||||||
|
upgrade) take at most one pod at a time, preserving quorum (2 of 3). On SIGTERM a
|
||||||
|
pod flips readiness to 503 (leaving both Services), drains, lets the leader
|
||||||
|
lease/heartbeat windows lapse so a successor is elected cleanly, then checkpoints
|
||||||
|
+ fsyncs the WAL; `terminationGracePeriodSeconds: 60` covers the sequence.
|
||||||
|
|
||||||
|
### The exit-gate harness
|
||||||
|
|
||||||
|
The in-cluster load Jobs in [`tidal-stress/k8s/`](../../tidal-stress/k8s/) target
|
||||||
|
the cluster by per-pod DNS (`tidaldb-N.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500`),
|
||||||
|
in namespace `tidaldb-cluster`, reading the `tidaldb-credentials` secret. They
|
||||||
|
run the capacity ramp, the quorum-throughput gate (`stress-job-t2a.yaml`,
|
||||||
|
`--ack quorum`), and the leader-kill chaos drill (`stress-job-t2b.yaml`).
|
||||||
|
|
||||||
## See also
|
## See also
|
||||||
|
|
||||||
- [Server deployment guide](../guides/server-deployment.md) — config, auth, the served OpenAPI spec
|
- [Server deployment guide](../guides/server-deployment.md) — config, auth, the served OpenAPI spec
|
||||||
- [Build a feed app](../guides/build-a-feed-app.md) — what to run against this server
|
- [Build a feed app](../guides/build-a-feed-app.md) — what to run against this server
|
||||||
- [Cluster runbook](cluster.md) — the experimental multi-region mode (not production HA)
|
- [Cluster runbook](cluster.md) — the multi-region mode's operational API (launch, promote, heal, reseed)
|
||||||
- [Monitoring](../ops/monitoring.md) · [Capacity planning](../ops/capacity-planning.md) · [Recovery](../ops/recovery.md)
|
- [Monitoring](../ops/monitoring.md) · [Capacity planning](../ops/capacity-planning.md) · [Recovery](../ops/recovery.md)
|
||||||
|
|||||||
@ -103,6 +103,10 @@ data/
|
|||||||
|
|
||||||
**As implemented (canonical: `tidal/src/wal/segment.rs` module docs).** Segment files are named `wal-{first_seq:020}.seg` (multi-shard: `wal-s{shard:05}-{first_seq:020}.seg`) and rotate at 16 MiB. Since m11p4 every new segment opens with an 8-byte version header — magic `TSEG`, a format-version byte (currently 1), three reserved zero bytes — followed by the 64-byte-header batch frames (`TIDL` magic, per-batch format version, BLAKE3). Headerless pre-m11p4 segments remain readable as the implicit version 0; no migration. A segment whose header version (or leading bytes, or `.seg` filename) this binary cannot identify surfaces as `WalError::SegmentFormatUnknown` at open — never silently scanned as empty, never "repaired" by truncation — so a cross-version upgrade mismatch fails the boot loudly instead of booting with the data invisibly absent. The replication catch-up path (`StreamSegments`) maps the same condition to a structured `FAILED_PRECONDITION` ("segments not available from seq N; snapshot required").
|
**As implemented (canonical: `tidal/src/wal/segment.rs` module docs).** Segment files are named `wal-{first_seq:020}.seg` (multi-shard: `wal-s{shard:05}-{first_seq:020}.seg`) and rotate at 16 MiB. Since m11p4 every new segment opens with an 8-byte version header — magic `TSEG`, a format-version byte (currently 1), three reserved zero bytes — followed by the 64-byte-header batch frames (`TIDL` magic, per-batch format version, BLAKE3). Headerless pre-m11p4 segments remain readable as the implicit version 0; no migration. A segment whose header version (or leading bytes, or `.seg` filename) this binary cannot identify surfaces as `WalError::SegmentFormatUnknown` at open — never silently scanned as empty, never "repaired" by truncation — so a cross-version upgrade mismatch fails the boot loudly instead of booting with the data invisibly absent. The replication catch-up path (`StreamSegments`) maps the same condition to a structured `FAILED_PRECONDITION` ("segments not available from seq N; snapshot required").
|
||||||
|
|
||||||
|
**Record kinds on the one log (m11p2/p4/p5).** Within those batch frames a record carries a kind discriminant: **kind-0** signal records (the original payload), **kind-1** item-metadata blobs and **kind-2** embedding blobs (m11p2 — items/embeddings ride the same replicated WAL as signals), **kind-3** term-marker records (m11p4 — an elected leader's first entry, replicated so every replica derives `(lastLogTerm, lastLogIndex)` from one fsync stream), and **kind-4** membership records (m11p5 — full-roster `MembershipRecord`s journaled by the leader and folded by followers into a `ClusterMembership` cell; latest record at-or-below the durable frontier wins, no merge logic). A record kind this binary does not recognize is a `WalError::Corruption` at apply — never silently skipped — which is why a kind-4 record shipped to a pre-m11p5 follower halts that follower's receiver until it is upgraded (the m11p5 capability gate refuses conf-changes until every voter reports kind-4 capability, making that hazard structurally unreachable). Downgrade across any new kind requires a reseed, the same identify-or-refuse posture as the segment header.
|
||||||
|
|
||||||
|
**Snapshot-stream resolution of the unservable-catch-up path (m11p5).** When a follower's requested range has rotated past the leader's retained WAL, the `FAILED_PRECONDITION` "snapshot required" refusal is no longer terminal: the typed trailer `x-tidal-catchup: snapshot-required` latches the follower's durable `reseed_required` marker, and on its next boot it pulls the leader's checkpoint artifact (§8) over the new `FetchSnapshot` server-streaming RPC — a manifest + BLAKE3-verified file chunks, term-stamped and term-fenced exactly like `StreamSegments` — installs it at boot into a staging dir, then resumes the live stream from the snapshot's seq. The snapshot ships every durable file byte-identical (TSEG segments must arrive bit-exact or the joiner's open refuses) except node-identity files (`election_state`, `stream_baseline`, the membership cache, the lock, `snapshots/`, the reseed marker), which are node-local and travel inside staging across the swap.
|
||||||
|
|
||||||
### 2.3 Crash Recovery
|
### 2.3 Crash Recovery
|
||||||
|
|
||||||
On startup, the storage engine:
|
On startup, the storage engine:
|
||||||
|
|||||||
30
k8s/cluster/kustomization.yaml
Normal file
30
k8s/cluster/kustomization.yaml
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
# tidalDB CLUSTER deployment (m11p5 §4). Apply with:
|
||||||
|
# kubectl apply -k k8s/cluster/
|
||||||
|
#
|
||||||
|
# MUTUALLY EXCLUSIVE with the standalone set (k8s/, namespace `tidaldb`). This
|
||||||
|
# set lives in namespace `tidaldb-cluster`. Deploy ONE or the OTHER per
|
||||||
|
# namespace — never both (they share the StatefulSet name `tidaldb` and the
|
||||||
|
# standalone set's replicas:1 is load-bearing).
|
||||||
|
#
|
||||||
|
# Create the API-key secret FIRST (deliberately excluded so no key is committed —
|
||||||
|
# see secret.example.yaml). Secret shape is the stress/Ref-A lineage:
|
||||||
|
# kubectl -n tidaldb-cluster create secret generic tidaldb-credentials \
|
||||||
|
# --from-literal=TIDAL_API_KEY="$(openssl rand -hex 32)"
|
||||||
|
apiVersion: kustomize.config.k8s.io/v1beta1
|
||||||
|
kind: Kustomization
|
||||||
|
|
||||||
|
namespace: tidaldb-cluster
|
||||||
|
|
||||||
|
resources:
|
||||||
|
- namespace.yaml
|
||||||
|
- schema-configmap.yaml
|
||||||
|
- topology-configmap.yaml
|
||||||
|
- service-peers.yaml
|
||||||
|
- service-client.yaml
|
||||||
|
- statefulset.yaml
|
||||||
|
- poddisruptionbudget.yaml
|
||||||
|
|
||||||
|
labels:
|
||||||
|
- pairs:
|
||||||
|
app.kubernetes.io/part-of: tidaldb
|
||||||
|
includeSelectors: false
|
||||||
15
k8s/cluster/namespace.yaml
Normal file
15
k8s/cluster/namespace.yaml
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
# tidalDB CLUSTER namespace (m11p5 §4).
|
||||||
|
#
|
||||||
|
# MUTUALLY EXCLUSIVE with the standalone set in k8s/: the standalone manifests
|
||||||
|
# live in namespace `tidaldb`, this cluster set lives in `tidaldb-cluster`. Pick
|
||||||
|
# ONE per namespace — they share resource names (StatefulSet `tidaldb`, Service
|
||||||
|
# `tidaldb`) and the standalone set's `replicas: 1` is load-bearing (no
|
||||||
|
# shared-storage multi-writer mode). Never `kubectl apply -k` both into the same
|
||||||
|
# namespace.
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Namespace
|
||||||
|
metadata:
|
||||||
|
name: tidaldb-cluster
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/part-of: tidaldb
|
||||||
25
k8s/cluster/poddisruptionbudget.yaml
Normal file
25
k8s/cluster/poddisruptionbudget.yaml
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
# maxUnavailable: 1 (m11p5 §4).
|
||||||
|
#
|
||||||
|
# Unlike the standalone set (maxUnavailable: 0 — a single node cannot stay
|
||||||
|
# available across a drain), a 3-voter cluster tolerates losing ONE voter and
|
||||||
|
# keeps quorum (2 of 3). This PDB lets a node drain/upgrade take at most one pod
|
||||||
|
# at a time so a voluntary disruption (node drain, autoscaler, rolling upgrade)
|
||||||
|
# never breaks quorum. It does NOT protect against involuntary loss of two nodes
|
||||||
|
# at once — spread the pods (topologySpreadConstraints) and keep PVCs durable.
|
||||||
|
#
|
||||||
|
# For a cluster scaled beyond 3, maxUnavailable: 1 stays correct (an odd voter
|
||||||
|
# set of 5/7 tolerates more, but 1-at-a-time is always quorum-safe).
|
||||||
|
apiVersion: policy/v1
|
||||||
|
kind: PodDisruptionBudget
|
||||||
|
metadata:
|
||||||
|
name: tidaldb
|
||||||
|
namespace: tidaldb-cluster
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/part-of: tidaldb
|
||||||
|
spec:
|
||||||
|
maxUnavailable: 1
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/component: cluster-node
|
||||||
51
k8s/cluster/schema-configmap.yaml
Normal file
51
k8s/cluster/schema-configmap.yaml
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
# The tidalDB schema the cluster pods load at startup with `--schema`.
|
||||||
|
#
|
||||||
|
# Identical SHAPE to the standalone set's k8s/schema-configmap.yaml (signal types
|
||||||
|
# + decay, text fields, embedding slots) — every region in the cluster MUST load
|
||||||
|
# the same schema. Mounting it as a ConfigMap lets you evolve the schema without
|
||||||
|
# rebuilding the image; the schema is read once at boot, so roll the StatefulSet
|
||||||
|
# (kubectl rollout restart) to apply changes, and only make backward-compatible
|
||||||
|
# changes on a populated data dir (see docs/ops/recovery.md § schema mismatch).
|
||||||
|
#
|
||||||
|
# Schema format reference: docs/guides/server-deployment.md and API.md.
|
||||||
|
apiVersion: v1
|
||||||
|
kind: ConfigMap
|
||||||
|
metadata:
|
||||||
|
name: tidaldb-schema
|
||||||
|
namespace: tidaldb-cluster
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/part-of: tidaldb
|
||||||
|
data:
|
||||||
|
schema.yaml: |
|
||||||
|
signals:
|
||||||
|
- name: view
|
||||||
|
entity: item
|
||||||
|
decay:
|
||||||
|
exponential:
|
||||||
|
half_life_seconds: 604800 # 7 days
|
||||||
|
windows: [one_hour, twenty_four_hours, seven_days]
|
||||||
|
velocity: true
|
||||||
|
positive_engagement: true # folds into the user preference vector
|
||||||
|
- name: like
|
||||||
|
entity: item
|
||||||
|
decay:
|
||||||
|
exponential:
|
||||||
|
half_life_seconds: 1209600 # 14 days
|
||||||
|
windows: [twenty_four_hours, seven_days, thirty_days, all_time]
|
||||||
|
velocity: false
|
||||||
|
positive_engagement: true
|
||||||
|
- name: skip
|
||||||
|
entity: item
|
||||||
|
decay:
|
||||||
|
permanent: true
|
||||||
|
velocity: false
|
||||||
|
text_fields:
|
||||||
|
- name: title
|
||||||
|
kind: text
|
||||||
|
- name: category
|
||||||
|
kind: keyword
|
||||||
|
embedding_slots:
|
||||||
|
- name: content_vector
|
||||||
|
entity: item
|
||||||
|
dimensions: 128
|
||||||
28
k8s/cluster/secret.example.yaml
Normal file
28
k8s/cluster/secret.example.yaml
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
# TEMPLATE ONLY — do NOT commit a real key. The real secret is created
|
||||||
|
# out-of-band and is deliberately excluded from kustomization.yaml so no key
|
||||||
|
# lands in git.
|
||||||
|
#
|
||||||
|
# Secret shape (m11p5 §4): `tidaldb-credentials` / key `TIDAL_API_KEY` — the
|
||||||
|
# stress/Ref-A lineage. The in-repo stress Jobs (tidal-stress/k8s/) are the
|
||||||
|
# exit-gate harness and already read this exact shape; the StatefulSet injects it
|
||||||
|
# as the `TIDAL_API_KEY` env var. EVERY pod and EVERY client uses the same key
|
||||||
|
# (forwarded requests pass the caller's Authorization verbatim).
|
||||||
|
#
|
||||||
|
# Create the real one (do not apply this file):
|
||||||
|
# kubectl -n tidaldb-cluster create secret generic tidaldb-credentials \
|
||||||
|
# --from-literal=TIDAL_API_KEY="$(openssl rand -hex 32)"
|
||||||
|
#
|
||||||
|
# In production manage it with External Secrets Operator / Sealed Secrets / Vault.
|
||||||
|
# If the key is empty the server runs UNAUTHENTICATED and logs a WARN — never do
|
||||||
|
# that on a shared network.
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: tidaldb-credentials
|
||||||
|
namespace: tidaldb-cluster
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/part-of: tidaldb
|
||||||
|
type: Opaque
|
||||||
|
stringData:
|
||||||
|
TIDAL_API_KEY: "replace-me-do-not-commit"
|
||||||
34
k8s/cluster/service-client.yaml
Normal file
34
k8s/cluster/service-client.yaml
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
# Client-facing Service (m11p5 §4) — readiness-gated load balancing.
|
||||||
|
#
|
||||||
|
# This is the address in-cluster clients hit for HTTP reads/writes. It is a
|
||||||
|
# normal (VIP) Service, so the default readiness gating applies: a pod that the
|
||||||
|
# m11p5 readiness predicate marks 503 (a joiner before first-convergence, a
|
||||||
|
# quarantined node, a removed/reseeding node, a draining node on SIGTERM) is
|
||||||
|
# REMOVED from this Service's endpoints and receives no client traffic. Only
|
||||||
|
# converged, serving voters answer clients here.
|
||||||
|
#
|
||||||
|
# Contrast with tidaldb-peers (headless, publishNotReadyAddresses: true): peers
|
||||||
|
# must still resolve a not-ready joiner to feed it a snapshot + stream, so that
|
||||||
|
# Service keeps not-ready pods. This Service must NOT — a client must never be
|
||||||
|
# routed to a node still catching up.
|
||||||
|
#
|
||||||
|
# Forwarding works regardless of which pod a client lands on: any region forwards
|
||||||
|
# writes to the current leader and reads serve locally. Front this with an
|
||||||
|
# Ingress/Gateway for external traffic; never expose :9091 metrics externally
|
||||||
|
# (unauthenticated).
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: tidaldb
|
||||||
|
namespace: tidaldb-cluster
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/part-of: tidaldb
|
||||||
|
spec:
|
||||||
|
selector:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/component: cluster-node
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
port: 9500
|
||||||
|
targetPort: http
|
||||||
41
k8s/cluster/service-peers.yaml
Normal file
41
k8s/cluster/service-peers.yaml
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
# Headless PEER-discovery Service (m11p5 §4).
|
||||||
|
#
|
||||||
|
# Gives every StatefulSet pod a stable per-pod DNS name
|
||||||
|
# tidaldb-N.tidaldb-peers.tidaldb-cluster.svc.cluster.local
|
||||||
|
# which is exactly what the topology ConfigMap advertises as each region's
|
||||||
|
# grpc_addr/http_addr. Peers dial these names; tonic re-resolves DNS on every
|
||||||
|
# reconnect so a pod rescheduled onto a new IP becomes reachable with no peer
|
||||||
|
# restart (the whole point of the m11p5 bind/advertise split).
|
||||||
|
#
|
||||||
|
# publishNotReadyAddresses: true is LOAD-BEARING. The m11p5 readiness predicate
|
||||||
|
# 503s a joiner/quarantined/reseeding pod (so the CLIENT Service drops it from
|
||||||
|
# load-balancing — see service-client.yaml). But peer discovery, snapshot fetch,
|
||||||
|
# and the catch-up stream must still RESOLVE a not-ready joiner's DNS, or the
|
||||||
|
# joiner can never reach a seed to converge and become ready — a deadlock. This
|
||||||
|
# Service keeps NOT-ready pods in its DNS A-records for exactly that reason.
|
||||||
|
#
|
||||||
|
# This Service is also `serviceName` for the StatefulSet (stable network ids).
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: tidaldb-peers
|
||||||
|
namespace: tidaldb-cluster
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/part-of: tidaldb
|
||||||
|
spec:
|
||||||
|
clusterIP: None # headless: per-pod DNS, no VIP
|
||||||
|
publishNotReadyAddresses: true # keep not-ready joiners resolvable for peers
|
||||||
|
selector:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/component: cluster-node
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
port: 9500
|
||||||
|
targetPort: http
|
||||||
|
- name: grpc
|
||||||
|
port: 9601
|
||||||
|
targetPort: grpc
|
||||||
|
- name: metrics
|
||||||
|
port: 9091
|
||||||
|
targetPort: metrics
|
||||||
216
k8s/cluster/statefulset.yaml
Normal file
216
k8s/cluster/statefulset.yaml
Normal file
@ -0,0 +1,216 @@
|
|||||||
|
# The tidalDB CLUSTER: ONE StatefulSet, every pod a region (m11p5 §4).
|
||||||
|
#
|
||||||
|
# MUTUALLY EXCLUSIVE with the standalone set in k8s/ (namespace `tidaldb`,
|
||||||
|
# replicas: 1, `standalone` subcommand). This is namespace `tidaldb-cluster`,
|
||||||
|
# replicas: 3, the `cluster --region` subcommand, real quorum-ack writes,
|
||||||
|
# automatic election, and elastic membership. Deploy ONE or the OTHER per
|
||||||
|
# namespace — never both.
|
||||||
|
#
|
||||||
|
# WHY ONE StatefulSet (not one-per-region): the m11p5 bind/advertise split lets
|
||||||
|
# every pod mount the SAME topology ConfigMap (peers are advertised by per-pod
|
||||||
|
# DNS; the local socket binds 0.0.0.0), so a single StatefulSet with stable pod
|
||||||
|
# identities tidaldb-{0,1,2} IS the three regions. Scaling is `kubectl scale`
|
||||||
|
# (see docs/runbooks/kubernetes.md): pod N>=3 auto-seed-joins as a learner and
|
||||||
|
# auto-promotes to a voter — no file edits, no per-pod manifests.
|
||||||
|
apiVersion: apps/v1
|
||||||
|
kind: StatefulSet
|
||||||
|
metadata:
|
||||||
|
name: tidaldb
|
||||||
|
namespace: tidaldb-cluster
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/component: cluster-node
|
||||||
|
spec:
|
||||||
|
serviceName: tidaldb-peers # the headless peer Service — stable per-pod DNS
|
||||||
|
replicas: 3 # the initial voter set; scale up/down per the runbook
|
||||||
|
# Parallel: bring all pods up at once. There is no ordered-bootstrap
|
||||||
|
# dependency — siblings boot in any order (an unreachable-at-startup peer is
|
||||||
|
# normal; the election + catch-up timer converge them). Ordered start would
|
||||||
|
# only serialize a 3-region cold boot for no benefit.
|
||||||
|
podManagementPolicy: Parallel
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/component: cluster-node
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/component: cluster-node
|
||||||
|
annotations:
|
||||||
|
# Plain-Prometheus scrape hints (per-pod :9091, unauthenticated — keep
|
||||||
|
# cluster-internal). The Operator-native path is a PodMonitor/ServiceMonitor.
|
||||||
|
prometheus.io/scrape: "true"
|
||||||
|
prometheus.io/port: "9091"
|
||||||
|
prometheus.io/path: "/metrics"
|
||||||
|
spec:
|
||||||
|
# SIGTERM flips readiness to 503 (pod leaves the client Service), drains
|
||||||
|
# in-flight requests, then checkpoints + fsyncs the WAL before exit. The
|
||||||
|
# cluster path also wants the leader-lease/heartbeat windows to lapse so a
|
||||||
|
# successor is elected cleanly. 60s covers the whole sequence.
|
||||||
|
terminationGracePeriodSeconds: 60
|
||||||
|
# Spread the three pods across distinct nodes so a single node loss takes
|
||||||
|
# at most one voter — preserving quorum (2 of 3). ScheduleAnyway (not
|
||||||
|
# DoNotSchedule) so a smaller cluster still schedules, just less spread.
|
||||||
|
topologySpreadConstraints:
|
||||||
|
- maxSkew: 1
|
||||||
|
topologyKey: kubernetes.io/hostname
|
||||||
|
whenUnsatisfiable: ScheduleAnyway
|
||||||
|
labelSelector:
|
||||||
|
matchLabels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/component: cluster-node
|
||||||
|
securityContext:
|
||||||
|
runAsNonRoot: true
|
||||||
|
runAsUser: 10001 # the fixed `tidal` uid (docker/deploy/Dockerfile)
|
||||||
|
runAsGroup: 10001
|
||||||
|
fsGroup: 10001 # makes the mounted PVC group-writable by the runtime user
|
||||||
|
seccompProfile:
|
||||||
|
type: RuntimeDefault
|
||||||
|
containers:
|
||||||
|
- name: tidaldb
|
||||||
|
# One image serves every subcommand (standalone AND cluster) via arg
|
||||||
|
# override — the image contract. For a real cluster, pin your registry
|
||||||
|
# image by digest and use a build whose runtime user is uid 10001
|
||||||
|
# (matches the securityContext above so the PVC is writable).
|
||||||
|
image: tidaldb:deploy
|
||||||
|
imagePullPolicy: IfNotPresent
|
||||||
|
# The image ENTRYPOINT is the bare binary. We override the command with
|
||||||
|
# a tiny /bin/sh wrapper (the bookworm-slim runtime HAS a shell) so we
|
||||||
|
# can branch on the pod ordinal: pods 0-2 are the initial voter set
|
||||||
|
# (plain topology boot); pods >=3 are SCALE-UP and must seed-join as
|
||||||
|
# learners. Keeping this in args (no initContainer, no extra image)
|
||||||
|
# means the whole scale story is readable in this one file.
|
||||||
|
#
|
||||||
|
# POD_NAME is e.g. "tidaldb-4"; ORD is its trailing ordinal. For ORD<3
|
||||||
|
# we boot from the topology file (the region IS this pod's name). For
|
||||||
|
# ORD>=3 we ALSO pass --seed (any peer; the headless Service load-
|
||||||
|
# balances to a live one) + this pod's advertised DNS addresses, and
|
||||||
|
# the node learns its roster/id/term from a seed and joins as a learner.
|
||||||
|
# The topology ConfigMap is STILL mounted+passed for the behavioral knob
|
||||||
|
# blocks (replication/election/...), required even for a --seed boot
|
||||||
|
# (m11p5 §3.5); its regions: list is ignored for a seed joiner's roster.
|
||||||
|
command: ["/bin/sh", "-c"]
|
||||||
|
args:
|
||||||
|
- |
|
||||||
|
set -eu
|
||||||
|
ORD="${POD_NAME##*-}"
|
||||||
|
DOMAIN="tidaldb-peers.tidaldb-cluster.svc.cluster.local"
|
||||||
|
# Common args for every pod.
|
||||||
|
set -- cluster \
|
||||||
|
--listen 0.0.0.0:9500 \
|
||||||
|
--data-dir /data/db \
|
||||||
|
--schema /etc/tidal-server/schema/schema.yaml \
|
||||||
|
--topology /etc/tidal-server/cluster-topology.yaml \
|
||||||
|
--experimental-cluster
|
||||||
|
if [ "$ORD" -ge 3 ]; then
|
||||||
|
# SCALE-UP pod: seed-join as a learner. Advertise THIS pod's
|
||||||
|
# stable per-pod DNS for gRPC (9601) and HTTP (9500); point --seed
|
||||||
|
# at the headless Service (it resolves to a live peer). --metrics
|
||||||
|
# gives the joiner a metrics listener (it has no topology entry).
|
||||||
|
set -- "$@" \
|
||||||
|
--seed "http://${DOMAIN}:9500" \
|
||||||
|
--advertise-grpc "${POD_NAME}.${DOMAIN}:9601" \
|
||||||
|
--advertise-http "${POD_NAME}.${DOMAIN}:9500" \
|
||||||
|
--metrics 0.0.0.0:9091
|
||||||
|
fi
|
||||||
|
exec tidal-server "$@"
|
||||||
|
env:
|
||||||
|
# Region identity == pod name (tidaldb-0/1/2/...). For ORD<3 this
|
||||||
|
# MUST match a region declared in the topology ConfigMap; the names
|
||||||
|
# line up by construction (regions are named after the pod identities).
|
||||||
|
- name: POD_NAME
|
||||||
|
valueFrom:
|
||||||
|
fieldRef:
|
||||||
|
fieldPath: metadata.name
|
||||||
|
- name: TIDAL_REGION
|
||||||
|
valueFrom:
|
||||||
|
fieldRef:
|
||||||
|
fieldPath: metadata.name
|
||||||
|
- name: TIDAL_API_KEY
|
||||||
|
valueFrom:
|
||||||
|
secretKeyRef:
|
||||||
|
name: tidaldb-credentials
|
||||||
|
key: TIDAL_API_KEY
|
||||||
|
- name: TIDAL_SERVER_LOG
|
||||||
|
value: info
|
||||||
|
- name: TIDAL_ALLOW_EXPERIMENTAL_CLUSTER
|
||||||
|
value: "1"
|
||||||
|
ports:
|
||||||
|
- name: http
|
||||||
|
containerPort: 9500
|
||||||
|
- name: grpc
|
||||||
|
containerPort: 9601
|
||||||
|
- name: metrics
|
||||||
|
containerPort: 9091
|
||||||
|
# Three probes map to the three health endpoints. The readinessProbe is
|
||||||
|
# now CLUSTER-AWARE (m11p5 §4): /health returns 503 while shutting down,
|
||||||
|
# quarantined, removed/decommissioned, or a joiner/install boot has not
|
||||||
|
# yet first-converged (lag <= learner_promote_lag, sticky-ready after).
|
||||||
|
# A restarted PVC-retained voter is Ready on today's terms (no
|
||||||
|
# regression). The full predicate is documented in the kubernetes.md
|
||||||
|
# runbook so probe behavior is diagnosable.
|
||||||
|
startupProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health/startup
|
||||||
|
port: http
|
||||||
|
periodSeconds: 5
|
||||||
|
failureThreshold: 60 # ~5 min for large-DB WAL replay / index load
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health/live
|
||||||
|
port: http
|
||||||
|
periodSeconds: 10
|
||||||
|
timeoutSeconds: 3
|
||||||
|
failureThreshold: 3
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health # cluster-aware: 503 joiner/quarantined/draining
|
||||||
|
port: http
|
||||||
|
periodSeconds: 10
|
||||||
|
timeoutSeconds: 3
|
||||||
|
failureThreshold: 3
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: "250m"
|
||||||
|
memory: 256Mi
|
||||||
|
limits:
|
||||||
|
cpu: "2"
|
||||||
|
memory: 2Gi # size from docs/ops/capacity-planning.md
|
||||||
|
securityContext:
|
||||||
|
allowPrivilegeEscalation: false
|
||||||
|
readOnlyRootFilesystem: true # writes only /data (PVC) and /tmp (emptyDir)
|
||||||
|
capabilities:
|
||||||
|
drop: ["ALL"]
|
||||||
|
volumeMounts:
|
||||||
|
- name: data
|
||||||
|
mountPath: /data
|
||||||
|
- name: schema
|
||||||
|
mountPath: /etc/tidal-server/schema
|
||||||
|
readOnly: true
|
||||||
|
- name: topology
|
||||||
|
mountPath: /etc/tidal-server/cluster-topology.yaml
|
||||||
|
subPath: cluster-topology.yaml
|
||||||
|
readOnly: true
|
||||||
|
- name: tmp
|
||||||
|
mountPath: /tmp
|
||||||
|
volumes:
|
||||||
|
- name: schema
|
||||||
|
configMap:
|
||||||
|
name: tidaldb-schema
|
||||||
|
- name: topology
|
||||||
|
configMap:
|
||||||
|
name: tidaldb-cluster-topology
|
||||||
|
- name: tmp
|
||||||
|
emptyDir: {}
|
||||||
|
volumeClaimTemplates:
|
||||||
|
- metadata:
|
||||||
|
name: data
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
spec:
|
||||||
|
accessModes: ["ReadWriteOnce"]
|
||||||
|
# storageClassName: "" # uncomment + set to pin a class; omitted = default
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
storage: 10Gi
|
||||||
85
k8s/cluster/topology-configmap.yaml
Normal file
85
k8s/cluster/topology-configmap.yaml
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
# The ONE bootstrap topology file, shared by EVERY pod (m11p5 §4).
|
||||||
|
#
|
||||||
|
# Before m11p5, k8s cluster mode needed a per-pod ConfigMap variant: a node bound
|
||||||
|
# its own `grpc_addr` LITERALLY and a pod cannot bind a Service ClusterIP, so each
|
||||||
|
# pod's self-entry had to be a bindable address while peers' entries stayed the
|
||||||
|
# routable ones — defeating the "every process parses the SAME file" contract.
|
||||||
|
#
|
||||||
|
# The m11p5 bind/advertise split kills that hack:
|
||||||
|
# - `grpc_addr` is the ADVERTISED address siblings DIAL (a per-pod DNS name);
|
||||||
|
# with a DNS name tonic re-resolves on every reconnect, so a rescheduled pod
|
||||||
|
# on a new IP is reachable again with NO peer restart.
|
||||||
|
# - `grpc_bind` is the LOCAL socket — `0.0.0.0:9601` on every pod. The local
|
||||||
|
# socket never tries to bind the DNS name.
|
||||||
|
# So one file names all three initial regions by their stable headless-Service
|
||||||
|
# DNS names, and every pod mounts THIS file unmodified.
|
||||||
|
#
|
||||||
|
# Region declaration order == RegionId (topology.rs:24-28). The three regions are
|
||||||
|
# named after the StatefulSet's stable pod identities tidaldb-{0,1,2}. The pod's
|
||||||
|
# `--region` comes from POD_NAME (statefulset.yaml fieldRef), so pod `tidaldb-0`
|
||||||
|
# is region `tidaldb-0`, etc. — the names line up by construction.
|
||||||
|
#
|
||||||
|
# SCALING PAST 3 DOES NOT EDIT THIS FILE: pod N>=3 boots with `--seed` and learns
|
||||||
|
# its roster/id/term from a seed (membership is data, on the replicated log). It
|
||||||
|
# still mounts THIS file for the behavioral knob blocks only — `--seed` boots
|
||||||
|
# REQUIRE a local config for `replication`/`wal`/`election`/`timeouts`/`grpc_tls`
|
||||||
|
# (m11p5 §3.5); the `regions:` list below is IGNORED for the roster of a seed
|
||||||
|
# joiner (the join response is authoritative), it supplies only those knobs.
|
||||||
|
#
|
||||||
|
# DNS form: <pod>.<headless-service>.<namespace>.svc.cluster.local
|
||||||
|
# tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local
|
||||||
|
apiVersion: v1
|
||||||
|
kind: ConfigMap
|
||||||
|
metadata:
|
||||||
|
name: tidaldb-cluster-topology
|
||||||
|
namespace: tidaldb-cluster
|
||||||
|
labels:
|
||||||
|
app.kubernetes.io/name: tidaldb
|
||||||
|
app.kubernetes.io/part-of: tidaldb
|
||||||
|
data:
|
||||||
|
cluster-topology.yaml: |
|
||||||
|
# Three initial regions, named by their per-pod headless-Service DNS.
|
||||||
|
# grpc_addr = ADVERTISED gRPC (DNS, port 9601) — what peers dial.
|
||||||
|
# grpc_bind = LOCAL gRPC bind (0.0.0.0:9601) — the pod can't bind the DNS.
|
||||||
|
# http_addr = ADVERTISED HTTP (DNS, port 9500) — peers forward writes/status.
|
||||||
|
# metrics_addr = per-region Prometheus listener (0.0.0.0:9091).
|
||||||
|
regions:
|
||||||
|
- name: tidaldb-0
|
||||||
|
grpc_addr: tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9601
|
||||||
|
grpc_bind: 0.0.0.0:9601
|
||||||
|
http_addr: tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500
|
||||||
|
metrics_addr: 0.0.0.0:9091
|
||||||
|
- name: tidaldb-1
|
||||||
|
grpc_addr: tidaldb-1.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9601
|
||||||
|
grpc_bind: 0.0.0.0:9601
|
||||||
|
http_addr: tidaldb-1.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500
|
||||||
|
metrics_addr: 0.0.0.0:9091
|
||||||
|
- name: tidaldb-2
|
||||||
|
grpc_addr: tidaldb-2.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9601
|
||||||
|
grpc_bind: 0.0.0.0:9601
|
||||||
|
http_addr: tidaldb-2.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500
|
||||||
|
metrics_addr: 0.0.0.0:9091
|
||||||
|
# Term-0 bootstrap leader only — post-election this field is dead config
|
||||||
|
# (durable election_state governs; a restart always boots a follower).
|
||||||
|
leader: tidaldb-0
|
||||||
|
replication:
|
||||||
|
# ack=quorum: a write succeeds once a MAJORITY of the replica set durably
|
||||||
|
# holds it (m11p3). Callers can still override per-request with x-tidal-ack.
|
||||||
|
ack: quorum
|
||||||
|
# reseed_self_restart=true (m11p5 §2.4): a node that latches the durable
|
||||||
|
# `reseed_required` marker drains and exits(0) so the StatefulSet restarts
|
||||||
|
# it and the boot-time install re-runs. The exit is REFUSED (loudly, in
|
||||||
|
# status + gauge) when the remaining voters can't sustain quorum without
|
||||||
|
# this node — exiting during a 2-voter window would be a total write outage.
|
||||||
|
reseed_self_restart: true
|
||||||
|
election:
|
||||||
|
# Defaults (300ms heartbeats, 1500-3000ms election timeout, 900ms lease,
|
||||||
|
# auto-election on) are right for an in-cluster (low-RTT) deployment. The
|
||||||
|
# C2 safety invariant lease+heartbeat < election_timeout_min holds for the
|
||||||
|
# defaults; spell the block out so an operator widening WAN budgets edits
|
||||||
|
# here, not the compiled-in defaults.
|
||||||
|
heartbeat_interval_ms: 300
|
||||||
|
election_timeout_min_ms: 1500
|
||||||
|
election_timeout_max_ms: 3000
|
||||||
|
leader_lease_ms: 900
|
||||||
|
auto_election: true
|
||||||
@ -49,6 +49,7 @@ thiserror = "2"
|
|||||||
tonic-build = "0.12"
|
tonic-build = "0.12"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
blake3 = "1"
|
||||||
criterion = { version = "0.5", features = ["html_reports"] }
|
criterion = { version = "0.5", features = ["html_reports"] }
|
||||||
rcgen = "0.13"
|
rcgen = "0.13"
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
|
|||||||
@ -70,14 +70,14 @@ fn bench_transports(c: &mut Criterion) {
|
|||||||
let config0 = GrpcTransportConfig {
|
let config0 = GrpcTransportConfig {
|
||||||
local_shard: ShardId(0),
|
local_shard: ShardId(0),
|
||||||
listen_addr: addr0,
|
listen_addr: addr0,
|
||||||
peers: HashMap::from([(ShardId(1), addr1)]),
|
peers: HashMap::from([(ShardId(1), addr1.to_string())]),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let config1 = GrpcTransportConfig {
|
let config1 = GrpcTransportConfig {
|
||||||
local_shard: ShardId(1),
|
local_shard: ShardId(1),
|
||||||
listen_addr: addr1,
|
listen_addr: addr1,
|
||||||
peers: HashMap::from([(ShardId(0), addr0)]),
|
peers: HashMap::from([(ShardId(0), addr0.to_string())]),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|||||||
@ -97,6 +97,21 @@ message HeartbeatResponse {
|
|||||||
// Whether the responder accepted the sender's leadership assertion
|
// Whether the responder accepted the sender's leadership assertion
|
||||||
// (false = the sender's term is stale).
|
// (false = the sender's term is stale).
|
||||||
bool accepted = 3;
|
bool accepted = 3;
|
||||||
|
// The responder binary's capability bit-field (m11p5). See the BIT REGISTRY
|
||||||
|
// below `WalShipping`. proto3 zero-default = a pre-m11p5 follower (incapable
|
||||||
|
// of folding kind-4 membership records): a `0` here gates the leader off
|
||||||
|
// appending any conf-change until every voter reports the kind-4 bit.
|
||||||
|
uint64 capabilities = 4;
|
||||||
|
// The TYPED REMOVED SIGNAL (m11p5 §3.3): true iff the responder's APPLIED
|
||||||
|
// roster lists the heartbeat SENDER (`region_id`) as a `Removed` member.
|
||||||
|
// proto3 zero-default = false = "not removed" = backward-compatible with a
|
||||||
|
// pre-m11p5 responder. A sender that sees `true` was decommissioned: it
|
||||||
|
// flips its readiness to 503 and suppresses campaigning WITHOUT latching a
|
||||||
|
// reseed marker (a remove is not a reseed). This is the delivery path for a
|
||||||
|
// node that MISSED the `Removed` record in the stream (it was down during
|
||||||
|
// the removal-delivery grace) — it learns of its removal from the leader's
|
||||||
|
// heartbeat refusal rather than the log.
|
||||||
|
bool removed = 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A follower's self-report of its durable frontier (m11p3).
|
// A follower's self-report of its durable frontier (m11p3).
|
||||||
@ -115,6 +130,12 @@ message AppliedReport {
|
|||||||
// quorum commit index ONLY when this matches the index's activation term —
|
// quorum commit index ONLY when this matches the index's activation term —
|
||||||
// a stale or cross-leadership report can never advance commitment.
|
// a stale or cross-leadership report can never advance commitment.
|
||||||
uint64 reporter_term = 4;
|
uint64 reporter_term = 4;
|
||||||
|
// The reporter binary's capability bit-field (m11p5). See the BIT REGISTRY
|
||||||
|
// below `WalShipping`. proto3 zero-default = a pre-m11p5 reporter. Reported
|
||||||
|
// on the frontier push (decoupled from heartbeats) so the leader learns a
|
||||||
|
// follower's capabilities even when it is the one being pulled from — the
|
||||||
|
// join/conf-change gate (§3.1) reads the leader's last-seen-per-peer map.
|
||||||
|
uint64 capabilities = 5;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Applied-report acknowledgement.
|
// Applied-report acknowledgement.
|
||||||
@ -144,6 +165,13 @@ message VoteResponse {
|
|||||||
// The voter's current term (above the candidate's = step-down signal).
|
// The voter's current term (above the candidate's = step-down signal).
|
||||||
uint64 term = 1;
|
uint64 term = 1;
|
||||||
bool granted = 2;
|
bool granted = 2;
|
||||||
|
// The TYPED REMOVED SIGNAL (m11p5 §3.3): true iff the voter's APPLIED roster
|
||||||
|
// lists the CANDIDATE (`candidate_region`) as a `Removed` member. proto3
|
||||||
|
// zero-default = false = backward-compatible. A candidate that sees `true`
|
||||||
|
// was decommissioned: it flips readiness to 503 and suppresses campaigning,
|
||||||
|
// exempt from the reseed marker. Vote refusals are a second delivery channel
|
||||||
|
// (alongside heartbeats) for a removed node that missed the `Removed` record.
|
||||||
|
bool removed = 3;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The current leader tells `target` to start an immediate transfer election
|
// The current leader tells `target` to start an immediate transfer election
|
||||||
@ -159,7 +187,142 @@ message TimeoutNowResponse {
|
|||||||
bool accepted = 1;
|
bool accepted = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Snapshot transfer (m11p5 §2): the reseed and joiner catch-up path ──────
|
||||||
|
//
|
||||||
|
// A joiner (or a node behind a compacted leader) cannot stream from the WAL
|
||||||
|
// when the leader has compacted past its `from_seqno` (the structural hole
|
||||||
|
// `StreamSegments` answers with FAILED_PRECONDITION + an `x-tidal-catchup`
|
||||||
|
// trailer). `FetchSnapshot` ships a staged `create_backup` artifact as a
|
||||||
|
// chunked server-stream, term-fenced exactly like `StreamSegments`, after
|
||||||
|
// which the joiner resumes `StreamSegments` from the snapshot's seqno.
|
||||||
|
|
||||||
|
// A puller's request for a snapshot to install before resuming the stream.
|
||||||
|
message SnapshotRequest {
|
||||||
|
uint32 shard_id = 1;
|
||||||
|
// The puller's frontier+1: the first seqno it still needs. The source
|
||||||
|
// answers `needed=false` (just stream) when the live WAL can still serve
|
||||||
|
// this, else stages an artifact whose recovered tail is >= from_seqno.
|
||||||
|
uint64 from_seqno = 2;
|
||||||
|
// The puller's current term (m11p5 fencing): a deposed source must step
|
||||||
|
// down rather than serve a snapshot of its possibly-divergent state; a
|
||||||
|
// stale puller must rejoin the current term first.
|
||||||
|
uint64 term = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One file entry in a snapshot manifest: a relative path under the artifact
|
||||||
|
// root plus its size and content hash. The BLAKE3 is the END-TO-END integrity
|
||||||
|
// contract — computed once when the artifact is staged (node-side), forwarded
|
||||||
|
// verbatim here, and verified by the installing puller. The server NEVER
|
||||||
|
// recomputes it per chunk (the manifest hash is authoritative).
|
||||||
|
message SnapshotFileEntry {
|
||||||
|
string path = 1;
|
||||||
|
uint64 size = 2;
|
||||||
|
bytes blake3 = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The leading chunk of a `FetchSnapshot` stream: either "no snapshot needed,
|
||||||
|
// just stream" or the manifest of files that follow.
|
||||||
|
message SnapshotHeader {
|
||||||
|
// false = the live WAL still serves `from_seqno`; the puller resumes
|
||||||
|
// `StreamSegments` directly and NO file chunks follow this header. true =
|
||||||
|
// the file chunks below install before the stream resumes.
|
||||||
|
bool needed = 1;
|
||||||
|
// The snapshot's recovered WAL tail: the seqno the installed artifact is
|
||||||
|
// valid at (the puller advances its frontier to this, then resumes from
|
||||||
|
// `snapshot_seq + 1`). 0 when `needed=false`.
|
||||||
|
uint64 snapshot_seq = 2;
|
||||||
|
// The term and region of the staging leader (m11p5 fencing visibility).
|
||||||
|
uint64 term = 3;
|
||||||
|
uint32 leader_region = 4;
|
||||||
|
// The complete manifest: every file the puller must receive and verify.
|
||||||
|
// Empty when `needed=false`.
|
||||||
|
repeated SnapshotFileEntry files = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
// One chunk of one file's bytes. Files stream in manifest order; a file is
|
||||||
|
// complete when a chunk with `last=true` arrives (offset + data.len() then
|
||||||
|
// equals the manifest size).
|
||||||
|
message SnapshotFileChunk {
|
||||||
|
string path = 1;
|
||||||
|
uint64 offset = 2;
|
||||||
|
bytes data = 3;
|
||||||
|
bool last = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A message in the `FetchSnapshot` stream: the header (always first) then file
|
||||||
|
// chunks.
|
||||||
|
message SnapshotChunk {
|
||||||
|
oneof chunk {
|
||||||
|
SnapshotHeader header = 1;
|
||||||
|
SnapshotFileChunk file = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Membership conf-changes (m11p5 §3.3): the join verb ────────────────────
|
||||||
|
//
|
||||||
|
// A joining node POSTs/dials any seed; a non-leader seed refuses with a leader
|
||||||
|
// hint and the joiner re-targets. The leader assigns a PERMANENT id, appends a
|
||||||
|
// Learner kind-4 record, waits for same-term quorum commit, and answers with
|
||||||
|
// the full roster so the joiner can build its peer tables before catching up.
|
||||||
|
|
||||||
|
// One member in a `JoinResponse` roster (the wire shape of a `MemberEntry`).
|
||||||
|
message MemberInfo {
|
||||||
|
uint32 id = 1;
|
||||||
|
string name = 2;
|
||||||
|
string grpc_addr = 3;
|
||||||
|
string http_addr = 4;
|
||||||
|
// 0 = Voter, 1 = Learner, 2 = Removed (matches MemberRole's on-disk byte).
|
||||||
|
uint32 role = 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A node's request to join the cluster (m11p5 §3.3). Idempotent by `name`:
|
||||||
|
// a re-join from a known member returns its existing id/role and appends
|
||||||
|
// nothing.
|
||||||
|
message JoinRequest {
|
||||||
|
string name = 1;
|
||||||
|
// Advertised gRPC address (host:port; DNS name or literal IP).
|
||||||
|
string grpc_addr = 2;
|
||||||
|
// Advertised HTTP address (scheme://host:port).
|
||||||
|
string http_addr = 3;
|
||||||
|
// The joiner binary's capability bit-field (m11p5 §3.1). A joiner that is
|
||||||
|
// not kind-4 capable can never participate in conf-changes; the leader's
|
||||||
|
// gate also requires every current voter to be capable.
|
||||||
|
uint64 capabilities = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The leader's answer to a join (m11p5 §3.3).
|
||||||
|
message JoinResponse {
|
||||||
|
// false = refused; `refusal_reason` says why and (for a non-leader seed)
|
||||||
|
// `leader_*` names where to re-target.
|
||||||
|
bool accepted = 1;
|
||||||
|
string refusal_reason = 2;
|
||||||
|
// The id the joiner was assigned (or its existing id on an idempotent
|
||||||
|
// re-join). Meaningful only when `accepted`.
|
||||||
|
uint32 assigned_id = 3;
|
||||||
|
// The current leadership term + the leader's addresses, so the joiner can
|
||||||
|
// persist the term and dial the leader directly.
|
||||||
|
uint64 term = 4;
|
||||||
|
string leader_region = 5;
|
||||||
|
string leader_grpc_addr = 6;
|
||||||
|
string leader_http_addr = 7;
|
||||||
|
// The full roster after the join (the joiner's source of truth for its peer
|
||||||
|
// tables), and the conf version it is at.
|
||||||
|
repeated MemberInfo members = 8;
|
||||||
|
uint64 membership_version = 9;
|
||||||
|
}
|
||||||
|
|
||||||
// WAL segment shipping service between tidalDB shards.
|
// WAL segment shipping service between tidalDB shards.
|
||||||
|
//
|
||||||
|
// ── CAPABILITY BIT REGISTRY (m11p5 §3.1) ───────────────────────────────────
|
||||||
|
// `capabilities` is a `uint64` bit-field on `HeartbeatResponse` and
|
||||||
|
// `AppliedReport`. proto3's zero-default means a pre-m11p5 binary reports `0`
|
||||||
|
// (no bits) — conservatively "incapable". Allocate bits append-only; NEVER
|
||||||
|
// reuse or renumber a retired bit.
|
||||||
|
// bit 0 (0x1): kind-4 membership record capable — this binary can fold a
|
||||||
|
// `MembershipRecord` WAL blob without halting its receiver. The
|
||||||
|
// leader refuses `JoinCluster`/conf-changes until every voter
|
||||||
|
// reports this bit (a kind-4 record to a pre-p5 follower is an
|
||||||
|
// unknown batch kind → permanent receiver halt).
|
||||||
service WalShipping {
|
service WalShipping {
|
||||||
// Ship a single WAL segment to a peer shard (unary).
|
// Ship a single WAL segment to a peer shard (unary).
|
||||||
rpc ShipSegment(ShipSegmentRequest) returns (ShipSegmentResponse);
|
rpc ShipSegment(ShipSegmentRequest) returns (ShipSegmentResponse);
|
||||||
@ -167,6 +330,10 @@ service WalShipping {
|
|||||||
// Stream WAL segments from a given sequence number (server-streaming).
|
// Stream WAL segments from a given sequence number (server-streaming).
|
||||||
rpc StreamSegments(StreamRequest) returns (stream ShipSegmentRequest);
|
rpc StreamSegments(StreamRequest) returns (stream ShipSegmentRequest);
|
||||||
|
|
||||||
|
// Stream a staged snapshot artifact to a joining/reseeding peer (m11p5).
|
||||||
|
// The header chunk arrives first (needed / manifest), then file chunks.
|
||||||
|
rpc FetchSnapshot(SnapshotRequest) returns (stream SnapshotChunk);
|
||||||
|
|
||||||
// Periodic health check for the ControlPlane; with m11p4, the leader's
|
// Periodic health check for the ControlPlane; with m11p4, the leader's
|
||||||
// lease assertion and the failure detector's input.
|
// lease assertion and the failure detector's input.
|
||||||
rpc Heartbeat(HeartbeatRequest) returns (HeartbeatResponse);
|
rpc Heartbeat(HeartbeatRequest) returns (HeartbeatResponse);
|
||||||
@ -179,4 +346,10 @@ service WalShipping {
|
|||||||
|
|
||||||
// Fenced leadership transfer: start an immediate election (m11p4).
|
// Fenced leadership transfer: start an immediate election (m11p4).
|
||||||
rpc TimeoutNow(TimeoutNowRequest) returns (TimeoutNowResponse);
|
rpc TimeoutNow(TimeoutNowRequest) returns (TimeoutNowResponse);
|
||||||
|
|
||||||
|
// Join the cluster (m11p5 §3.3). Dialled by a joiner against any seed; a
|
||||||
|
// non-leader seed refuses with a leader hint. The leader assigns a permanent
|
||||||
|
// id, appends a Learner kind-4 record, waits for same-term quorum commit, and
|
||||||
|
// answers with the roster. Idempotent by name.
|
||||||
|
rpc JoinCluster(JoinRequest) returns (JoinResponse);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,27 +1,63 @@
|
|||||||
//! gRPC client connection pool for shipping WAL segments to peers.
|
//! gRPC client connection pool for shipping WAL segments to peers.
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard};
|
||||||
|
|
||||||
use tidaldb::replication::{shard::ShardId, transport::WalSegmentPayload};
|
use tidaldb::replication::{shard::ShardId, transport::WalSegmentPayload};
|
||||||
use tonic::transport::Channel;
|
use tonic::transport::Channel;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
circuit_breaker::CircuitBreaker,
|
circuit_breaker::CircuitBreaker,
|
||||||
config::GrpcTransportConfig,
|
config::{GrpcTransportConfig, TlsConfig},
|
||||||
error::GrpcTransportError,
|
error::GrpcTransportError,
|
||||||
proto::{ShipSegmentRequest, wal_shipping_client::WalShippingClient},
|
proto::{
|
||||||
|
JoinRequest, JoinResponse, ShipSegmentRequest, SnapshotChunk, SnapshotRequest,
|
||||||
|
wal_shipping_client::WalShippingClient,
|
||||||
|
},
|
||||||
tls,
|
tls,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// A connection to a single peer shard.
|
/// A connection to a single peer shard.
|
||||||
struct PeerConnection {
|
///
|
||||||
|
/// Both fields are cheaply CLONABLE handles to shared state: the tonic client
|
||||||
|
/// clones over a shared channel, and the circuit breaker is an `Arc` so its
|
||||||
|
/// failure-count state is shared across clones. This lets an RPC clone the
|
||||||
|
/// pair out from under a brief read guard and operate WITHOUT holding the peer
|
||||||
|
/// map's `RwLock` across the `await` (m11p5 §3.3 — keep the hot path
|
||||||
|
/// lock-cheap while the peer set is mutable).
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct PeerHandle {
|
||||||
client: WalShippingClient<Channel>,
|
client: WalShippingClient<Channel>,
|
||||||
circuit_breaker: CircuitBreaker,
|
circuit_breaker: Arc<CircuitBreaker>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pool's stored per-peer connection.
|
||||||
|
struct PeerConnection {
|
||||||
|
handle: PeerHandle,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PeerConnection {
|
||||||
|
fn handle(&self) -> PeerHandle {
|
||||||
|
self.handle.clone()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Connection pool managing one gRPC channel per peer shard.
|
/// Connection pool managing one gRPC channel per peer shard.
|
||||||
|
///
|
||||||
|
/// The peer map is behind an `RwLock` (m11p5 §3.3): peers are added/removed at
|
||||||
|
/// runtime by a conf-change, but every RPC path takes only a brief READ guard
|
||||||
|
/// to clone the cheap tonic client (and its circuit-breaker handle) and then
|
||||||
|
/// releases it before the `await` — so the hot send path never blocks on the
|
||||||
|
/// rare write of [`add_peer`](Self::add_peer) / [`remove_peer`](Self::remove_peer).
|
||||||
|
/// Channels are LAZY (`connect_lazy`), so an insert costs no DNS resolution or
|
||||||
|
/// connect: the first RPC drives the connect, and a DNS-named peer re-resolves
|
||||||
|
/// on every reconnect.
|
||||||
pub struct PeerPool {
|
pub struct PeerPool {
|
||||||
peers: HashMap<ShardId, PeerConnection>,
|
peers: RwLock<HashMap<ShardId, PeerConnection>>,
|
||||||
|
/// The config the pool was built from, retained so [`add_peer`](Self::add_peer)
|
||||||
|
/// can build a new peer's channel with the SAME TLS / timeout / codec
|
||||||
|
/// settings the boot peers got.
|
||||||
|
config: GrpcTransportConfig,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PeerPool {
|
impl PeerPool {
|
||||||
@ -56,61 +92,57 @@ impl PeerPool {
|
|||||||
let mut peers = HashMap::new();
|
let mut peers = HashMap::new();
|
||||||
|
|
||||||
for (&shard_id, addr) in &config.peers {
|
for (&shard_id, addr) in &config.peers {
|
||||||
let scheme = if config.tls.is_some() {
|
peers.insert(shard_id, build_peer_connection(config, addr)?);
|
||||||
"https"
|
|
||||||
} else {
|
|
||||||
"http"
|
|
||||||
};
|
|
||||||
let uri = format!("{scheme}://{addr}");
|
|
||||||
|
|
||||||
// Build the endpoint with hard connect/request timeouts and HTTP/2
|
|
||||||
// keep-alive so a stalled peer fails fast (transient error → circuit
|
|
||||||
// breaker) instead of hanging the single-threaded WAL shipper. These
|
|
||||||
// apply on both the plaintext and TLS paths.
|
|
||||||
let mut endpoint = Channel::from_shared(uri)
|
|
||||||
.map_err(|e| GrpcTransportError::Internal(format!("invalid URI: {e}")))?
|
|
||||||
.connect_timeout(config.connect_timeout)
|
|
||||||
.timeout(config.request_timeout)
|
|
||||||
.tcp_keepalive(Some(config.keep_alive_interval))
|
|
||||||
.http2_keep_alive_interval(config.keep_alive_interval)
|
|
||||||
.keep_alive_timeout(config.keep_alive_timeout)
|
|
||||||
.keep_alive_while_idle(true);
|
|
||||||
|
|
||||||
// Configure client TLS if available.
|
|
||||||
if let Some(ref tls_config) = config.tls {
|
|
||||||
let client_tls = tls::client_tls_config(tls_config)?;
|
|
||||||
endpoint = endpoint
|
|
||||||
.tls_config(client_tls)
|
|
||||||
.map_err(GrpcTransportError::TonicTransport)?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let channel = endpoint.connect_lazy();
|
Ok(Self {
|
||||||
// Raise tonic's default 4 MiB codec limits to the configured max
|
peers: RwLock::new(peers),
|
||||||
// payload on BOTH directions. The client is the ENCODER for the
|
config: config.clone(),
|
||||||
// outbound ShipSegmentRequest (and the DECODER for any future
|
})
|
||||||
// server-streaming response). Without this the client encoder trips
|
|
||||||
// FIRST on a full-size WAL segment (16 MiB default, up to 64 MiB)
|
|
||||||
// before bytes ever leave the process, surfacing as a codec error
|
|
||||||
// the shipper would retry forever. Both ends must agree on the same
|
|
||||||
// ceiling the application already validates against.
|
|
||||||
let client = WalShippingClient::new(channel)
|
|
||||||
.max_encoding_message_size(config.max_payload_bytes)
|
|
||||||
.max_decoding_message_size(config.max_payload_bytes);
|
|
||||||
let circuit_breaker = CircuitBreaker::new(
|
|
||||||
config.circuit_breaker_threshold,
|
|
||||||
config.circuit_breaker_reset,
|
|
||||||
);
|
|
||||||
|
|
||||||
peers.insert(
|
|
||||||
shard_id,
|
|
||||||
PeerConnection {
|
|
||||||
client,
|
|
||||||
circuit_breaker,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Self { peers })
|
fn peers_read(&self) -> RwLockReadGuard<'_, HashMap<ShardId, PeerConnection>> {
|
||||||
|
self.peers.read().unwrap_or_else(PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clone the peer's handle out from under a brief read guard (released
|
||||||
|
/// before the caller's `await`), or `None` if the peer is not in the pool.
|
||||||
|
fn handle_for(&self, shard: ShardId) -> Option<PeerHandle> {
|
||||||
|
self.peers_read().get(&shard).map(PeerConnection::handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add (or replace) a peer's connection at runtime (m11p5 §3.3 conf-change).
|
||||||
|
/// The channel is LAZY, so this costs no DNS resolution or connect — the
|
||||||
|
/// first RPC drives the connect, and a DNS name re-resolves on reconnect.
|
||||||
|
/// Idempotent in effect: a re-add rebuilds the channel for `shard` with the
|
||||||
|
/// current config's TLS/timeout/codec settings.
|
||||||
|
///
|
||||||
|
/// `addr` is a bare `host:port` (a scheme prefix is tolerated and
|
||||||
|
/// re-derived from TLS, never doubled), matching [`new`](Self::new).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns [`GrpcTransportError`] if the URI is malformed or the client TLS
|
||||||
|
/// configuration cannot be built — the same failures [`new`](Self::new)
|
||||||
|
/// surfaces per peer.
|
||||||
|
pub fn add_peer(&self, shard: ShardId, addr: &str) -> Result<(), GrpcTransportError> {
|
||||||
|
let conn = build_peer_connection(&self.config, addr)?;
|
||||||
|
self.peers
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner)
|
||||||
|
.insert(shard, conn);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a peer's connection at runtime (m11p5 §3.3 conf-change): drops
|
||||||
|
/// the lazy channel. Returns whether a peer was present. After removal, an
|
||||||
|
/// RPC to `shard` surfaces as [`GrpcTransportError::PeerUnreachable`].
|
||||||
|
pub fn remove_peer(&self, shard: ShardId) -> bool {
|
||||||
|
self.peers
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner)
|
||||||
|
.remove(&shard)
|
||||||
|
.is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send a WAL segment to a peer shard.
|
/// Send a WAL segment to a peer shard.
|
||||||
@ -125,31 +157,31 @@ impl PeerPool {
|
|||||||
///
|
///
|
||||||
/// Returns [`GrpcTransportError`] if the peer is unknown, the circuit breaker
|
/// Returns [`GrpcTransportError`] if the peer is unknown, the circuit breaker
|
||||||
/// is open, the follower signals backpressure, or the gRPC call fails.
|
/// is open, the follower signals backpressure, or the gRPC call fails.
|
||||||
// `peer` is a plain `&PeerConnection` borrow into `self.peers` (no Drop of
|
|
||||||
// its own) used both before the await (clone the client) and after (record
|
|
||||||
// success/failure on its circuit breaker), so it legitimately spans the
|
|
||||||
// whole fn — significant_drop_tightening is a false positive for a borrow.
|
|
||||||
#[allow(clippy::significant_drop_tightening)]
|
|
||||||
pub async fn send_to(
|
pub async fn send_to(
|
||||||
&self,
|
&self,
|
||||||
shard: ShardId,
|
shard: ShardId,
|
||||||
payload: WalSegmentPayload,
|
payload: WalSegmentPayload,
|
||||||
) -> Result<(u64, u64), GrpcTransportError> {
|
) -> Result<(u64, u64), GrpcTransportError> {
|
||||||
let peer = self
|
// Clone the handle out from under a brief read guard, then drop the
|
||||||
.peers
|
// guard before the await: the peer map's RwLock is never held across
|
||||||
.get(&shard)
|
// the RPC, so a concurrent conf-change add/remove never contends with
|
||||||
|
// the hot ship path. Destructure into the cheap-cloned client and the
|
||||||
|
// shared `Arc<CircuitBreaker>` so the handle does not linger as a
|
||||||
|
// significant-Drop temporary across the await.
|
||||||
|
let PeerHandle {
|
||||||
|
mut client,
|
||||||
|
circuit_breaker,
|
||||||
|
} = self
|
||||||
|
.handle_for(shard)
|
||||||
.ok_or(GrpcTransportError::PeerUnreachable(shard))?;
|
.ok_or(GrpcTransportError::PeerUnreachable(shard))?;
|
||||||
|
|
||||||
// Check circuit breaker.
|
// Check circuit breaker.
|
||||||
peer.circuit_breaker
|
circuit_breaker
|
||||||
.check()
|
.check()
|
||||||
.map_err(|_| GrpcTransportError::CircuitOpen(shard))?;
|
.map_err(|_| GrpcTransportError::CircuitOpen(shard))?;
|
||||||
|
|
||||||
let request: ShipSegmentRequest = payload.into();
|
let request: ShipSegmentRequest = payload.into();
|
||||||
|
|
||||||
// Clone the client (tonic clients are cheap clones over a shared channel).
|
|
||||||
let mut client = peer.client.clone();
|
|
||||||
|
|
||||||
match client.ship_segment(request).await {
|
match client.ship_segment(request).await {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
// The follower signals backpressure with `accepted=false` when
|
// The follower signals backpressure with `accepted=false` when
|
||||||
@ -167,15 +199,15 @@ impl PeerPool {
|
|||||||
// arm below calls `record_failure`.
|
// arm below calls `record_failure`.
|
||||||
let inner = response.into_inner();
|
let inner = response.into_inner();
|
||||||
if inner.accepted {
|
if inner.accepted {
|
||||||
peer.circuit_breaker.record_success();
|
circuit_breaker.record_success();
|
||||||
Ok((inner.applied_seqno, inner.term))
|
Ok((inner.applied_seqno, inner.term))
|
||||||
} else {
|
} else {
|
||||||
peer.circuit_breaker.record_backpressure();
|
circuit_breaker.record_backpressure();
|
||||||
Err(GrpcTransportError::SegmentRejected(shard))
|
Err(GrpcTransportError::SegmentRejected(shard))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(status) => {
|
Err(status) => {
|
||||||
peer.circuit_breaker.record_failure();
|
circuit_breaker.record_failure();
|
||||||
Err(GrpcTransportError::Grpc(Box::new(status)))
|
Err(GrpcTransportError::Grpc(Box::new(status)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -196,7 +228,7 @@ impl PeerPool {
|
|||||||
applied: u64,
|
applied: u64,
|
||||||
reporter_term: u64,
|
reporter_term: u64,
|
||||||
) -> Result<(), GrpcTransportError> {
|
) -> Result<(), GrpcTransportError> {
|
||||||
let Some(peer) = self.peers.get(&to) else {
|
let Some(peer) = self.handle_for(to) else {
|
||||||
return Err(GrpcTransportError::PeerUnreachable(to));
|
return Err(GrpcTransportError::PeerUnreachable(to));
|
||||||
};
|
};
|
||||||
if peer.circuit_breaker.check().is_err() {
|
if peer.circuit_breaker.check().is_err() {
|
||||||
@ -208,6 +240,11 @@ impl PeerPool {
|
|||||||
source_shard: u32::from(to.0),
|
source_shard: u32::from(to.0),
|
||||||
applied_seqno: applied,
|
applied_seqno: applied,
|
||||||
reporter_term,
|
reporter_term,
|
||||||
|
// This binary's capabilities (m11p5 §3.1): the leader folds this
|
||||||
|
// into its per-peer capability view to gate conf-changes. Reported
|
||||||
|
// on every frontier push so the leader learns a follower's
|
||||||
|
// capabilities even when it is the one being pulled from.
|
||||||
|
capabilities: crate::CAPABILITIES,
|
||||||
});
|
});
|
||||||
client
|
client
|
||||||
.report_applied(request)
|
.report_applied(request)
|
||||||
@ -237,8 +274,7 @@ impl PeerPool {
|
|||||||
term: u64,
|
term: u64,
|
||||||
) -> Result<tonic::Streaming<ShipSegmentRequest>, GrpcTransportError> {
|
) -> Result<tonic::Streaming<ShipSegmentRequest>, GrpcTransportError> {
|
||||||
let peer = self
|
let peer = self
|
||||||
.peers
|
.handle_for(shard)
|
||||||
.get(&shard)
|
|
||||||
.ok_or(GrpcTransportError::PeerUnreachable(shard))?;
|
.ok_or(GrpcTransportError::PeerUnreachable(shard))?;
|
||||||
let mut client = peer.client.clone();
|
let mut client = peer.client.clone();
|
||||||
let request = crate::proto::StreamRequest {
|
let request = crate::proto::StreamRequest {
|
||||||
@ -252,6 +288,40 @@ impl PeerPool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Open a `FetchSnapshot` stream from `shard` (m11p5 §2: the joiner/reseed
|
||||||
|
/// catch-up path). `from_seqno` is the puller's frontier+1; `term` stamps
|
||||||
|
/// the request for the source's same-term fence.
|
||||||
|
///
|
||||||
|
/// Bypasses the circuit breaker for the same reason as
|
||||||
|
/// [`stream_from`](Self::stream_from): a snapshot fetch is rare, the path
|
||||||
|
/// is the recovery mechanism, and a breaker opened by live-ship
|
||||||
|
/// backpressure must not starve the very transfer that heals the follower.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns [`GrpcTransportError`] if the peer is unknown or the stream
|
||||||
|
/// cannot be opened (including `Unimplemented` from a pre-m11p5 peer).
|
||||||
|
pub async fn fetch_snapshot(
|
||||||
|
&self,
|
||||||
|
shard: ShardId,
|
||||||
|
from_seqno: u64,
|
||||||
|
term: u64,
|
||||||
|
) -> Result<tonic::Streaming<SnapshotChunk>, GrpcTransportError> {
|
||||||
|
let peer = self
|
||||||
|
.handle_for(shard)
|
||||||
|
.ok_or(GrpcTransportError::PeerUnreachable(shard))?;
|
||||||
|
let mut client = peer.client.clone();
|
||||||
|
let request = SnapshotRequest {
|
||||||
|
shard_id: u32::from(shard.0),
|
||||||
|
from_seqno,
|
||||||
|
term,
|
||||||
|
};
|
||||||
|
match client.fetch_snapshot(request).await {
|
||||||
|
Ok(response) => Ok(response.into_inner()),
|
||||||
|
Err(status) => Err(GrpcTransportError::Grpc(Box::new(status))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── Election RPCs (m11p4) ───────────────────────────────────────────────
|
// ── Election RPCs (m11p4) ───────────────────────────────────────────────
|
||||||
//
|
//
|
||||||
// None of these touch the circuit breaker: an election MUST be able to
|
// None of these touch the circuit breaker: an election MUST be able to
|
||||||
@ -271,7 +341,7 @@ impl PeerPool {
|
|||||||
to: ShardId,
|
to: ShardId,
|
||||||
request: crate::proto::VoteRequest,
|
request: crate::proto::VoteRequest,
|
||||||
) -> Result<crate::proto::VoteResponse, GrpcTransportError> {
|
) -> Result<crate::proto::VoteResponse, GrpcTransportError> {
|
||||||
let Some(peer) = self.peers.get(&to) else {
|
let Some(peer) = self.handle_for(to) else {
|
||||||
return Err(GrpcTransportError::PeerUnreachable(to));
|
return Err(GrpcTransportError::PeerUnreachable(to));
|
||||||
};
|
};
|
||||||
let mut client = peer.client.clone();
|
let mut client = peer.client.clone();
|
||||||
@ -292,7 +362,7 @@ impl PeerPool {
|
|||||||
to: ShardId,
|
to: ShardId,
|
||||||
request: crate::proto::HeartbeatRequest,
|
request: crate::proto::HeartbeatRequest,
|
||||||
) -> Result<crate::proto::HeartbeatResponse, GrpcTransportError> {
|
) -> Result<crate::proto::HeartbeatResponse, GrpcTransportError> {
|
||||||
let Some(peer) = self.peers.get(&to) else {
|
let Some(peer) = self.handle_for(to) else {
|
||||||
return Err(GrpcTransportError::PeerUnreachable(to));
|
return Err(GrpcTransportError::PeerUnreachable(to));
|
||||||
};
|
};
|
||||||
let mut client = peer.client.clone();
|
let mut client = peer.client.clone();
|
||||||
@ -313,7 +383,7 @@ impl PeerPool {
|
|||||||
to: ShardId,
|
to: ShardId,
|
||||||
request: crate::proto::TimeoutNowRequest,
|
request: crate::proto::TimeoutNowRequest,
|
||||||
) -> Result<crate::proto::TimeoutNowResponse, GrpcTransportError> {
|
) -> Result<crate::proto::TimeoutNowResponse, GrpcTransportError> {
|
||||||
let Some(peer) = self.peers.get(&to) else {
|
let Some(peer) = self.handle_for(to) else {
|
||||||
return Err(GrpcTransportError::PeerUnreachable(to));
|
return Err(GrpcTransportError::PeerUnreachable(to));
|
||||||
};
|
};
|
||||||
let mut client = peer.client.clone();
|
let mut client = peer.client.clone();
|
||||||
@ -323,6 +393,225 @@ impl PeerPool {
|
|||||||
.map(tonic::Response::into_inner)
|
.map(tonic::Response::into_inner)
|
||||||
.map_err(|status| GrpcTransportError::Grpc(Box::new(status)))
|
.map_err(|status| GrpcTransportError::Grpc(Box::new(status)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Send a `JoinCluster` request to a known peer (m11p5 §3.3). Used for the
|
||||||
|
/// operator/manual `/cluster/join` forward to the leader once the transport
|
||||||
|
/// exists; the pre-transport boot loop uses [`join_cluster_standalone`].
|
||||||
|
/// Bypasses the circuit breaker like the election RPCs — a join is rare,
|
||||||
|
/// self-limiting, and must reach a peer the data-plane breaker quarantined.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Unknown peer or transport/RPC failure (including `Unimplemented` from a
|
||||||
|
/// pre-m11p5 peer).
|
||||||
|
pub async fn join_cluster(
|
||||||
|
&self,
|
||||||
|
to: ShardId,
|
||||||
|
request: JoinRequest,
|
||||||
|
) -> Result<JoinResponse, GrpcTransportError> {
|
||||||
|
let Some(peer) = self.handle_for(to) else {
|
||||||
|
return Err(GrpcTransportError::PeerUnreachable(to));
|
||||||
|
};
|
||||||
|
let mut client = peer.client.clone();
|
||||||
|
client
|
||||||
|
.join_cluster(request)
|
||||||
|
.await
|
||||||
|
.map(tonic::Response::into_inner)
|
||||||
|
.map_err(|status| GrpcTransportError::Grpc(Box::new(status)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a one-off `FetchSnapshot` stream WITHOUT a [`PeerPool`] (m11p5 §2.7).
|
||||||
|
///
|
||||||
|
/// The boot-time seed-join install runs BEFORE the transport exists, so it
|
||||||
|
/// cannot go through the pool's per-peer channels. `uri_host_port` is a bare
|
||||||
|
/// `host:port` (a scheme prefix is tolerated and re-derived from `tls`, never
|
||||||
|
/// doubled); a DNS name re-resolves on connect exactly as the pool's channels
|
||||||
|
/// do. `tls.is_none()` builds a plaintext channel — the caller is responsible
|
||||||
|
/// for the same insecure opt-in the pool enforces (a boot install with a TLS
|
||||||
|
/// topology always passes `Some`).
|
||||||
|
///
|
||||||
|
/// Codec limits are pinned to [`MAX_PAYLOAD_BYTES`](crate::config::MAX_PAYLOAD_BYTES)
|
||||||
|
/// so a full-size file chunk decodes (the 1 MiB server cap stays well under,
|
||||||
|
/// but the manifest + future growth share the ceiling the rest of the
|
||||||
|
/// transport advertises).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns [`GrpcTransportError`] if the URI is malformed, the channel cannot
|
||||||
|
/// be built (bad TLS material), or the stream cannot be opened (`Unimplemented`
|
||||||
|
/// from a pre-m11p5 peer, a term-fence refusal, or transport failure).
|
||||||
|
pub async fn fetch_snapshot_standalone(
|
||||||
|
uri_host_port: &str,
|
||||||
|
tls: Option<&TlsConfig>,
|
||||||
|
shard: ShardId,
|
||||||
|
from_seqno: u64,
|
||||||
|
term: u64,
|
||||||
|
) -> Result<tonic::Streaming<SnapshotChunk>, GrpcTransportError> {
|
||||||
|
let scheme = if tls.is_some() { "https" } else { "http" };
|
||||||
|
// Strip any caller-supplied scheme so we never produce `http://http://…`
|
||||||
|
// (mirrors PeerPool::new); the scheme is derived from TLS, not trusted.
|
||||||
|
let bare = uri_host_port
|
||||||
|
.strip_prefix("http://")
|
||||||
|
.or_else(|| uri_host_port.strip_prefix("https://"))
|
||||||
|
.unwrap_or(uri_host_port);
|
||||||
|
let uri = format!("{scheme}://{bare}");
|
||||||
|
|
||||||
|
let mut endpoint = Channel::from_shared(uri)
|
||||||
|
.map_err(|e| GrpcTransportError::Internal(format!("invalid snapshot URI: {e}")))?
|
||||||
|
.connect_timeout(std::time::Duration::from_secs(5));
|
||||||
|
|
||||||
|
if let Some(tls_config) = tls {
|
||||||
|
let client_tls = tls::client_tls_config(tls_config)?;
|
||||||
|
endpoint = endpoint
|
||||||
|
.tls_config(client_tls)
|
||||||
|
.map_err(GrpcTransportError::TonicTransport)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// `connect_lazy` matches the pool: the first RPC drives the connect, so a
|
||||||
|
// not-yet-listening seed surfaces as a transport error the boot loop
|
||||||
|
// retries (§2.7) rather than failing channel construction.
|
||||||
|
let channel = endpoint.connect_lazy();
|
||||||
|
let mut client = WalShippingClient::new(channel)
|
||||||
|
.max_encoding_message_size(crate::config::MAX_PAYLOAD_BYTES)
|
||||||
|
.max_decoding_message_size(crate::config::MAX_PAYLOAD_BYTES);
|
||||||
|
|
||||||
|
let request = SnapshotRequest {
|
||||||
|
shard_id: u32::from(shard.0),
|
||||||
|
from_seqno,
|
||||||
|
term,
|
||||||
|
};
|
||||||
|
client
|
||||||
|
.fetch_snapshot(request)
|
||||||
|
.await
|
||||||
|
.map(tonic::Response::into_inner)
|
||||||
|
.map_err(|status| GrpcTransportError::Grpc(Box::new(status)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dial a `JoinCluster` request WITHOUT a [`PeerPool`] (m11p5 §3.3, the §2.7
|
||||||
|
/// pre-transport boot loop).
|
||||||
|
///
|
||||||
|
/// A seed-joiner has no peer table yet — it knows only the `--seed` host:port —
|
||||||
|
/// so it cannot go through the pool. Mirrors
|
||||||
|
/// [`fetch_snapshot_standalone`] exactly: a scheme prefix on `uri_host_port` is
|
||||||
|
/// tolerated and re-derived from `tls` (never doubled), a DNS name re-resolves
|
||||||
|
/// on connect, and `tls.is_none()` builds a plaintext channel (the caller owns
|
||||||
|
/// the insecure opt-in, exactly as the pool does).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns [`GrpcTransportError`] if the URI is malformed, the channel cannot
|
||||||
|
/// be built (bad TLS material), or the RPC fails (`Unimplemented` from a
|
||||||
|
/// pre-m11p5 peer, a non-leader refusal carried IN the response body, or
|
||||||
|
/// transport failure). A non-leader seed answers `accepted=false` with a leader
|
||||||
|
/// hint — that is a successful RPC, NOT an error; the caller re-targets.
|
||||||
|
pub async fn join_cluster_standalone(
|
||||||
|
uri_host_port: &str,
|
||||||
|
tls: Option<&TlsConfig>,
|
||||||
|
request: JoinRequest,
|
||||||
|
) -> Result<JoinResponse, GrpcTransportError> {
|
||||||
|
let scheme = if tls.is_some() { "https" } else { "http" };
|
||||||
|
let bare = uri_host_port
|
||||||
|
.strip_prefix("http://")
|
||||||
|
.or_else(|| uri_host_port.strip_prefix("https://"))
|
||||||
|
.unwrap_or(uri_host_port);
|
||||||
|
let uri = format!("{scheme}://{bare}");
|
||||||
|
|
||||||
|
let mut endpoint = Channel::from_shared(uri)
|
||||||
|
.map_err(|e| GrpcTransportError::Internal(format!("invalid join URI: {e}")))?
|
||||||
|
.connect_timeout(std::time::Duration::from_secs(5));
|
||||||
|
|
||||||
|
if let Some(tls_config) = tls {
|
||||||
|
let client_tls = tls::client_tls_config(tls_config)?;
|
||||||
|
endpoint = endpoint
|
||||||
|
.tls_config(client_tls)
|
||||||
|
.map_err(GrpcTransportError::TonicTransport)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let channel = endpoint.connect_lazy();
|
||||||
|
let mut client = WalShippingClient::new(channel)
|
||||||
|
.max_encoding_message_size(crate::config::MAX_PAYLOAD_BYTES)
|
||||||
|
.max_decoding_message_size(crate::config::MAX_PAYLOAD_BYTES);
|
||||||
|
|
||||||
|
client
|
||||||
|
.join_cluster(request)
|
||||||
|
.await
|
||||||
|
.map(tonic::Response::into_inner)
|
||||||
|
.map_err(|status| GrpcTransportError::Grpc(Box::new(status)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build one peer's lazy gRPC channel + circuit breaker from the pool config
|
||||||
|
/// and a bare `host:port` address. Shared by [`PeerPool::new`] (boot) and
|
||||||
|
/// [`PeerPool::add_peer`] (runtime conf-change) so a runtime-added peer's
|
||||||
|
/// channel is configured byte-for-byte like a boot peer (TLS, timeouts,
|
||||||
|
/// keep-alive, codec limits, DNS re-resolution).
|
||||||
|
fn build_peer_connection(
|
||||||
|
config: &GrpcTransportConfig,
|
||||||
|
addr: &str,
|
||||||
|
) -> Result<PeerConnection, GrpcTransportError> {
|
||||||
|
let scheme = if config.tls.is_some() {
|
||||||
|
"https"
|
||||||
|
} else {
|
||||||
|
"http"
|
||||||
|
};
|
||||||
|
// `addr` is a bare `host:port` (m11p5). The scheme is derived from TLS,
|
||||||
|
// never trusted from the stored value, so a scheme-prefixed input cannot
|
||||||
|
// be doubled into `http://http://…`. When `host` is a DNS name,
|
||||||
|
// `Channel::from_shared("http://host:port")` keeps the name in the URI:
|
||||||
|
// tonic's connector re-runs hyper's resolver on every (re)connect, so a
|
||||||
|
// peer that returns on a NEW IP (a k8s pod reschedule) becomes reachable
|
||||||
|
// again with no process restart — the entire reason `peers` is a `String`
|
||||||
|
// and not a pre-resolved `SocketAddr`. An IP literal re-resolves trivially
|
||||||
|
// to itself.
|
||||||
|
let bare = addr
|
||||||
|
.strip_prefix("http://")
|
||||||
|
.or_else(|| addr.strip_prefix("https://"))
|
||||||
|
.unwrap_or(addr);
|
||||||
|
let uri = format!("{scheme}://{bare}");
|
||||||
|
|
||||||
|
// Build the endpoint with hard connect/request timeouts and HTTP/2
|
||||||
|
// keep-alive so a stalled peer fails fast (transient error → circuit
|
||||||
|
// breaker) instead of hanging the single-threaded WAL shipper. These
|
||||||
|
// apply on both the plaintext and TLS paths.
|
||||||
|
let mut endpoint = Channel::from_shared(uri)
|
||||||
|
.map_err(|e| GrpcTransportError::Internal(format!("invalid URI: {e}")))?
|
||||||
|
.connect_timeout(config.connect_timeout)
|
||||||
|
.timeout(config.request_timeout)
|
||||||
|
.tcp_keepalive(Some(config.keep_alive_interval))
|
||||||
|
.http2_keep_alive_interval(config.keep_alive_interval)
|
||||||
|
.keep_alive_timeout(config.keep_alive_timeout)
|
||||||
|
.keep_alive_while_idle(true);
|
||||||
|
|
||||||
|
// Configure client TLS if available.
|
||||||
|
if let Some(ref tls_config) = config.tls {
|
||||||
|
let client_tls = tls::client_tls_config(tls_config)?;
|
||||||
|
endpoint = endpoint
|
||||||
|
.tls_config(client_tls)
|
||||||
|
.map_err(GrpcTransportError::TonicTransport)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let channel = endpoint.connect_lazy();
|
||||||
|
// Raise tonic's default 4 MiB codec limits to the configured max payload on
|
||||||
|
// BOTH directions. The client is the ENCODER for the outbound
|
||||||
|
// ShipSegmentRequest (and the DECODER for any server-streaming response).
|
||||||
|
// Without this the client encoder trips FIRST on a full-size WAL segment
|
||||||
|
// before bytes ever leave the process, surfacing as a codec error the
|
||||||
|
// shipper would retry forever. Both ends must agree on the same ceiling the
|
||||||
|
// application already validates against.
|
||||||
|
let client = WalShippingClient::new(channel)
|
||||||
|
.max_encoding_message_size(config.max_payload_bytes)
|
||||||
|
.max_decoding_message_size(config.max_payload_bytes);
|
||||||
|
let circuit_breaker = Arc::new(CircuitBreaker::new(
|
||||||
|
config.circuit_breaker_threshold,
|
||||||
|
config.circuit_breaker_reset,
|
||||||
|
));
|
||||||
|
|
||||||
|
Ok(PeerConnection {
|
||||||
|
handle: PeerHandle {
|
||||||
|
client,
|
||||||
|
circuit_breaker,
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@ -373,4 +662,60 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert!(PeerPool::new(&config).is_err());
|
assert!(PeerPool::new(&config).is_err());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// m11p5 §3.3: `add_peer` makes a previously-unknown shard reachable
|
||||||
|
/// (an RPC stops returning `PeerUnreachable`), and `remove_peer` drops it
|
||||||
|
/// (the RPC returns `PeerUnreachable` again). The channel is lazy, so no
|
||||||
|
/// connect happens — we only assert the routing changes, never a live RPC.
|
||||||
|
/// `connect_lazy` needs a runtime context, hence `#[tokio::test]`.
|
||||||
|
#[tokio::test]
|
||||||
|
async fn add_peer_and_remove_peer_change_routing() {
|
||||||
|
let config = GrpcTransportConfig {
|
||||||
|
tls: None,
|
||||||
|
insecure: true,
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
};
|
||||||
|
let pool = PeerPool::new(&config).expect("pool builds (no boot peers)");
|
||||||
|
let shard = ShardId(7);
|
||||||
|
|
||||||
|
// Unknown peer: a vote RPC routes nowhere → PeerUnreachable.
|
||||||
|
// `VoteRequest` is `Copy`, so each call gets its own copy.
|
||||||
|
let req = crate::proto::VoteRequest::default();
|
||||||
|
let err = pool
|
||||||
|
.request_vote(shard, req)
|
||||||
|
.await
|
||||||
|
.expect_err("unknown peer is unreachable");
|
||||||
|
assert!(
|
||||||
|
matches!(err, GrpcTransportError::PeerUnreachable(s) if s == shard),
|
||||||
|
"expected PeerUnreachable, got {err:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add the peer (lazy channel; a DNS name is fine, nothing connects).
|
||||||
|
pool.add_peer(shard, "tidaldb-7.peers.svc:9500")
|
||||||
|
.expect("add_peer builds the lazy channel");
|
||||||
|
let err = pool
|
||||||
|
.request_vote(shard, req)
|
||||||
|
.await
|
||||||
|
.expect_err("the lazy channel cannot reach a non-existent server");
|
||||||
|
assert!(
|
||||||
|
!matches!(err, GrpcTransportError::PeerUnreachable(_)),
|
||||||
|
"after add_peer the RPC must ROUTE (a transport error, not \
|
||||||
|
PeerUnreachable): {err:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Remove it: routing is gone again.
|
||||||
|
assert!(pool.remove_peer(shard), "the peer was present");
|
||||||
|
assert!(!pool.remove_peer(shard), "a second remove is a no-op");
|
||||||
|
let err = pool
|
||||||
|
.request_vote(shard, req)
|
||||||
|
.await
|
||||||
|
.expect_err("removed peer is unreachable again");
|
||||||
|
assert!(
|
||||||
|
matches!(err, GrpcTransportError::PeerUnreachable(s) if s == shard),
|
||||||
|
"after remove_peer the RPC must be PeerUnreachable again: {err:?}"
|
||||||
|
);
|
||||||
|
// `PeerPool` now holds an `RwLock` (a significant-Drop type); drop it
|
||||||
|
// explicitly so clippy's drop-tightening lint is satisfied.
|
||||||
|
drop(pool);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -36,8 +36,20 @@ pub struct GrpcTransportConfig {
|
|||||||
pub local_shard: ShardId,
|
pub local_shard: ShardId,
|
||||||
/// Address to bind the gRPC server on.
|
/// Address to bind the gRPC server on.
|
||||||
pub listen_addr: SocketAddr,
|
pub listen_addr: SocketAddr,
|
||||||
/// Peer shard addresses (`shard_id` -> address).
|
/// Peer shard advertised addresses (`shard_id` -> `host:port`).
|
||||||
pub peers: HashMap<ShardId, SocketAddr>,
|
///
|
||||||
|
/// A bare `host:port` string, NOT a pre-resolved [`SocketAddr`]. This is
|
||||||
|
/// load-bearing for DNS peers (m11p5): [`PeerPool::new`] builds the tonic
|
||||||
|
/// URI from the string, so `Channel::from_shared("http://hostname:port")`
|
||||||
|
/// makes hyper re-resolve DNS on every (re)connect. A pre-resolved IP
|
||||||
|
/// literal would pin the peer to whatever address it had at boot — the
|
||||||
|
/// k8s pod-rescheduled-onto-a-new-IP case becomes structurally
|
||||||
|
/// unreachable until process restart. A literal IP `host:port` is still
|
||||||
|
/// accepted (and re-resolves trivially to itself), so every pre-m11p5
|
||||||
|
/// topology keeps working byte-for-byte.
|
||||||
|
///
|
||||||
|
/// [`PeerPool::new`]: crate::client::PeerPool::new
|
||||||
|
pub peers: HashMap<ShardId, String>,
|
||||||
/// TLS configuration. `None` requires `insecure = true`.
|
/// TLS configuration. `None` requires `insecure = true`.
|
||||||
pub tls: Option<TlsConfig>,
|
pub tls: Option<TlsConfig>,
|
||||||
/// Allow plaintext connections (no TLS).
|
/// Allow plaintext connections (no TLS).
|
||||||
@ -101,6 +113,13 @@ impl GrpcTransportConfig {
|
|||||||
/// must agree on the same in-range bound.
|
/// must agree on the same in-range bound.
|
||||||
/// - `circuit_breaker_reset == Duration::ZERO`: a breaker that reopens with
|
/// - `circuit_breaker_reset == Duration::ZERO`: a breaker that reopens with
|
||||||
/// no cool-down hammers a down peer with no backoff.
|
/// no cool-down hammers a down peer with no backoff.
|
||||||
|
/// - any peer address is not a syntactic `host:port` (empty/malformed host
|
||||||
|
/// or a port outside `1..=65535`): a bad peer string surfaces only as
|
||||||
|
/// "invalid URI" deep in [`PeerPool::new`] otherwise — catch the config
|
||||||
|
/// typo here, naming the offending peer. The check is hostname-tolerant
|
||||||
|
/// (it mirrors the server crate's `validate_host_port`): a DNS name is a
|
||||||
|
/// valid peer address, an IP literal is too, but reachability is NOT
|
||||||
|
/// probed (siblings boot in any order).
|
||||||
///
|
///
|
||||||
/// `circuit_breaker_threshold == 0` is intentionally allowed: the breaker
|
/// `circuit_breaker_threshold == 0` is intentionally allowed: the breaker
|
||||||
/// treats a zero threshold as "open on the first failure" (fail-fast), a
|
/// treats a zero threshold as "open on the first failure" (fail-fast), a
|
||||||
@ -143,10 +162,50 @@ impl GrpcTransportConfig {
|
|||||||
.into(),
|
.into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
for (shard, addr) in &self.peers {
|
||||||
|
validate_peer_addr(*shard, addr)?;
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Syntactic check that a peer's advertised address is a `host:port` the tonic
|
||||||
|
/// URI builder ([`PeerPool::new`](crate::client::PeerPool::new)) can turn into
|
||||||
|
/// a valid endpoint, mirroring the server crate's `validate_host_port`:
|
||||||
|
///
|
||||||
|
/// - an optional `http://` / `https://` prefix is tolerated (the scheme the
|
||||||
|
/// pool prepends is derived from TLS, but a prefixed value must not be
|
||||||
|
/// silently doubled into `http://http://…`),
|
||||||
|
/// - the host must be non-empty and contain no whitespace or `/`,
|
||||||
|
/// - the port must parse as a non-zero `u16` (port 0 is never a peer-reachable
|
||||||
|
/// address).
|
||||||
|
///
|
||||||
|
/// A DNS name passes (the m11p5 point): reachability is NOT probed here —
|
||||||
|
/// siblings boot in any order, so an unresolvable-at-startup peer is normal.
|
||||||
|
fn validate_peer_addr(shard: ShardId, addr: &str) -> Result<(), GrpcTransportError> {
|
||||||
|
let bare = addr
|
||||||
|
.strip_prefix("http://")
|
||||||
|
.or_else(|| addr.strip_prefix("https://"))
|
||||||
|
.unwrap_or(addr)
|
||||||
|
.trim_end_matches('/');
|
||||||
|
let bad = |why: &str| {
|
||||||
|
Err(GrpcTransportError::Internal(format!(
|
||||||
|
"peer {shard:?} address '{addr}' is not a valid host:port ({why})"
|
||||||
|
)))
|
||||||
|
};
|
||||||
|
let Some((host, port)) = bare.rsplit_once(':') else {
|
||||||
|
return bad("missing ':port'");
|
||||||
|
};
|
||||||
|
if host.is_empty() || host.contains([' ', '/']) {
|
||||||
|
return bad("empty or malformed host");
|
||||||
|
}
|
||||||
|
match port.parse::<u16>() {
|
||||||
|
Ok(0) => bad("port 0 is not reachable by peers"),
|
||||||
|
Ok(_) => Ok(()),
|
||||||
|
Err(_) => bad("port must be 1-65535"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Default for GrpcTransportConfig {
|
impl Default for GrpcTransportConfig {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
@ -285,4 +344,51 @@ mod tests {
|
|||||||
};
|
};
|
||||||
assert!(cfg.validate().is_ok());
|
assert!(cfg.validate().is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn valid_peer_addresses_are_accepted() {
|
||||||
|
// IP literal, DNS name, fully-qualified k8s pod DNS, and a
|
||||||
|
// scheme-prefixed value must all pass — the m11p5 DNS-peer point is
|
||||||
|
// that hostnames are first-class peer addresses.
|
||||||
|
for addr in [
|
||||||
|
"127.0.0.1:9601",
|
||||||
|
"tidal-eu:9601",
|
||||||
|
"tidaldb-1.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9601",
|
||||||
|
"http://127.0.0.1:9601",
|
||||||
|
"https://tidal-eu:9601",
|
||||||
|
] {
|
||||||
|
let cfg = GrpcTransportConfig {
|
||||||
|
peers: HashMap::from([(ShardId(1), addr.to_string())]),
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
};
|
||||||
|
cfg.validate()
|
||||||
|
.unwrap_or_else(|e| panic!("peer addr '{addr}' must be accepted: {e:?}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_peer_addresses_are_rejected() {
|
||||||
|
// A bad peer string would otherwise surface only as an opaque
|
||||||
|
// "invalid URI" deep in PeerPool::new — the config check names the
|
||||||
|
// offending peer instead.
|
||||||
|
for (addr, why) in [
|
||||||
|
("127.0.0.1", "missing port"),
|
||||||
|
("127.0.0.1:0", "port 0"),
|
||||||
|
("127.0.0.1:99999", "port out of range"),
|
||||||
|
(":9601", "empty host"),
|
||||||
|
("10.0.0.1:port", "non-numeric port"),
|
||||||
|
] {
|
||||||
|
let cfg = GrpcTransportConfig {
|
||||||
|
peers: HashMap::from([(ShardId(1), addr.to_string())]),
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
};
|
||||||
|
let Err(err) = cfg.validate() else {
|
||||||
|
panic!("peer addr '{addr}' ({why}) must be rejected");
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
matches!(err, GrpcTransportError::Internal(_)),
|
||||||
|
"expected an Internal config error for '{addr}', got {err:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -31,6 +31,7 @@ pub mod transport;
|
|||||||
clippy::derive_partial_eq_without_eq,
|
clippy::derive_partial_eq_without_eq,
|
||||||
clippy::default_trait_access,
|
clippy::default_trait_access,
|
||||||
clippy::missing_const_for_fn,
|
clippy::missing_const_for_fn,
|
||||||
|
clippy::too_long_first_doc_paragraph,
|
||||||
clippy::too_many_lines
|
clippy::too_many_lines
|
||||||
)]
|
)]
|
||||||
pub mod proto {
|
pub mod proto {
|
||||||
@ -39,5 +40,21 @@ pub mod proto {
|
|||||||
|
|
||||||
pub use config::{GrpcTransportConfig, TlsConfig};
|
pub use config::{GrpcTransportConfig, TlsConfig};
|
||||||
pub use error::GrpcTransportError;
|
pub use error::GrpcTransportError;
|
||||||
pub use sources::{ClaimRejection, ElectionHooks, HeartbeatExchange};
|
pub use sources::{
|
||||||
|
ClaimRejection, ElectionHooks, HeartbeatExchange, JoinAsk, JoinHooks, JoinOutcome, MemberInfo,
|
||||||
|
SnapshotRequiredSink, SnapshotSource, SnapshotStageError, SnapshotStaging,
|
||||||
|
};
|
||||||
pub use transport::{ElectionNet, ElectionNetEvent, GrpcTransport, GrpcTransportFactory};
|
pub use transport::{ElectionNet, ElectionNetEvent, GrpcTransport, GrpcTransportFactory};
|
||||||
|
|
||||||
|
/// Capability bit: kind-4 `MembershipRecord` WAL blobs.
|
||||||
|
///
|
||||||
|
/// This binary can fold a kind-4 record without halting its receiver (m11p5
|
||||||
|
/// §3.1). See the BIT REGISTRY in `proto/wal_shipping.proto`. A pre-m11p5
|
||||||
|
/// binary reports `0` (proto3 zero-default) — conservatively incapable.
|
||||||
|
pub const CAP_KIND4_MEMBERSHIP: u64 = 0x1;
|
||||||
|
|
||||||
|
/// This binary's advertised capability bit-field (m11p5).
|
||||||
|
///
|
||||||
|
/// Stamped on outbound `HeartbeatResponse` and `AppliedReport`. The leader
|
||||||
|
/// reads peers' reported values to gate `JoinCluster`/conf-changes (§3.1).
|
||||||
|
pub const CAPABILITIES: u64 = CAP_KIND4_MEMBERSHIP;
|
||||||
|
|||||||
@ -10,9 +10,10 @@ use tonic::{Request, Response, Status};
|
|||||||
use crate::{
|
use crate::{
|
||||||
config::GrpcTransportConfig,
|
config::GrpcTransportConfig,
|
||||||
proto::{
|
proto::{
|
||||||
AppliedReport, AppliedReportAck, HeartbeatRequest, HeartbeatResponse, ShipSegmentRequest,
|
AppliedReport, AppliedReportAck, HeartbeatRequest, HeartbeatResponse, JoinRequest,
|
||||||
ShipSegmentResponse, StreamRequest, TimeoutNowRequest, TimeoutNowResponse, VoteRequest,
|
JoinResponse, MemberInfo, ShipSegmentRequest, ShipSegmentResponse, SnapshotChunk,
|
||||||
VoteResponse, WalSegmentId,
|
SnapshotFileChunk, SnapshotFileEntry, SnapshotHeader, SnapshotRequest, StreamRequest,
|
||||||
|
TimeoutNowRequest, TimeoutNowResponse, VoteRequest, VoteResponse, WalSegmentId,
|
||||||
wal_shipping_server::{WalShipping, WalShippingServer},
|
wal_shipping_server::{WalShipping, WalShippingServer},
|
||||||
},
|
},
|
||||||
sources::ServingSources,
|
sources::ServingSources,
|
||||||
@ -40,12 +41,79 @@ pub(crate) fn fold_peer_applied(map: &PeerAppliedMap, peer: ShardId, applied: u6
|
|||||||
drop(hints);
|
drop(hints);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Leader-side last-seen capability bit-field per reporting peer (m11p5 §3.1).
|
||||||
|
/// Folded from `AppliedReport`s. The join/conf-change gate (stage C) reads it
|
||||||
|
/// to refuse appending kind-4 records until every voter reports the kind-4 bit.
|
||||||
|
/// Last-write-wins: a node's capabilities are fixed for a process lifetime, so
|
||||||
|
/// the freshest report is authoritative (a restart onto a downgraded binary —
|
||||||
|
/// itself a reseed-gated event — reports the new value).
|
||||||
|
pub(crate) type PeerCapabilityMap = Arc<Mutex<HashMap<ShardId, u64>>>;
|
||||||
|
|
||||||
|
/// Record a peer's reported capability bit-field (last-write-wins).
|
||||||
|
fn record_peer_capabilities(map: &PeerCapabilityMap, peer: ShardId, capabilities: u64) {
|
||||||
|
map.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.insert(peer, capabilities);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The gRPC trailer key carrying the typed catch-up refusal class (m11p5 §2.4).
|
||||||
|
/// Values: `snapshot-required` | `rejoin` | `stepping-down`. A pre-m11p5 source
|
||||||
|
/// emits no trailer; the puller treats an absent/unknown value conservatively
|
||||||
|
/// (no reseed-marker latch) — a plain election term-mismatch must NOT poison a
|
||||||
|
/// fleet with reseed markers.
|
||||||
|
pub(crate) const CATCHUP_TRAILER: &str = "x-tidal-catchup";
|
||||||
|
|
||||||
|
/// Build a `FAILED_PRECONDITION` status carrying the typed catch-up trailer
|
||||||
|
/// (m11p5 §2.4). The trailer is metadata the puller reads to classify the
|
||||||
|
/// refusal; the message stays human-readable for logs.
|
||||||
|
fn catchup_refusal(class: &'static str, message: String) -> Status {
|
||||||
|
let mut status = Status::failed_precondition(message);
|
||||||
|
// `class` is a fixed ASCII literal (one of three known values), so the
|
||||||
|
// metadata-value parse never fails; on the impossible error path the
|
||||||
|
// status still carries the human-readable message (the puller falls back
|
||||||
|
// to today's log+retry behavior — never a panic).
|
||||||
|
if let Ok(value) = class.parse() {
|
||||||
|
status.metadata_mut().insert(CATCHUP_TRAILER, value);
|
||||||
|
}
|
||||||
|
status
|
||||||
|
}
|
||||||
|
|
||||||
/// Per-chunk caps for the `StreamSegments` catch-up path: small enough to
|
/// Per-chunk caps for the `StreamSegments` catch-up path: small enough to
|
||||||
/// stay far below the codec/payload ceilings, large enough that a 100k-item
|
/// stay far below the codec/payload ceilings, large enough that a 100k-item
|
||||||
/// catch-up is a few hundred messages, not a few hundred thousand.
|
/// catch-up is a few hundred messages, not a few hundred thousand.
|
||||||
const STREAM_CHUNK_MAX_EVENTS: u64 = 4096;
|
const STREAM_CHUNK_MAX_EVENTS: u64 = 4096;
|
||||||
const STREAM_CHUNK_MAX_BYTES: usize = 4 * 1024 * 1024;
|
const STREAM_CHUNK_MAX_BYTES: usize = 4 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// Per-chunk byte cap for the `FetchSnapshot` file stream (1 MiB): far below
|
||||||
|
/// the codec ceiling, large enough that a multi-GiB artifact is thousands of
|
||||||
|
/// messages, not millions. Each chunk is read off `spawn_blocking`, never on
|
||||||
|
/// the reactor.
|
||||||
|
const SNAPSHOT_FILE_CHUNK_BYTES: usize = 1024 * 1024;
|
||||||
|
|
||||||
|
/// Read up to `max` bytes from `path` starting at `offset` (m11p5 snapshot
|
||||||
|
/// file chunking). Returns fewer bytes only at end-of-file (a short read of a
|
||||||
|
/// regular file is the file's tail; the caller stops once it reaches the
|
||||||
|
/// manifest size). Runs on `spawn_blocking`, never the reactor.
|
||||||
|
fn read_file_range(path: &std::path::Path, offset: u64, max: usize) -> std::io::Result<Vec<u8>> {
|
||||||
|
use std::io::{Read, Seek, SeekFrom};
|
||||||
|
let mut file = std::fs::File::open(path)?;
|
||||||
|
file.seek(SeekFrom::Start(offset))?;
|
||||||
|
let mut buf = vec![0u8; max];
|
||||||
|
let mut filled = 0;
|
||||||
|
// Loop to fill the buffer: a single `read` may return short for reasons
|
||||||
|
// other than EOF, but a regular-file read on a local FS rarely does; the
|
||||||
|
// loop makes the chunk size deterministic regardless.
|
||||||
|
while filled < max {
|
||||||
|
let n = file.read(&mut buf[filled..])?;
|
||||||
|
if n == 0 {
|
||||||
|
break; // EOF
|
||||||
|
}
|
||||||
|
filled += n;
|
||||||
|
}
|
||||||
|
buf.truncate(filled);
|
||||||
|
Ok(buf)
|
||||||
|
}
|
||||||
|
|
||||||
/// The gRPC service that receives WAL segments from peers.
|
/// The gRPC service that receives WAL segments from peers.
|
||||||
pub struct WalShippingService {
|
pub struct WalShippingService {
|
||||||
inbound_tx: mpsc::Sender<WalSegmentPayload>,
|
inbound_tx: mpsc::Sender<WalSegmentPayload>,
|
||||||
@ -57,22 +125,27 @@ pub struct WalShippingService {
|
|||||||
/// Per-peer durable marks shared with the transport (m11p3): folded from
|
/// Per-peer durable marks shared with the transport (m11p3): folded from
|
||||||
/// `ReportApplied` pushes here and from ship acks on the client side.
|
/// `ReportApplied` pushes here and from ship acks on the client side.
|
||||||
peer_applied: PeerAppliedMap,
|
peer_applied: PeerAppliedMap,
|
||||||
|
/// Per-peer last-seen capability bit-field (m11p5 §3.1), folded from
|
||||||
|
/// `AppliedReport`s. Exposed to the leader's conf-change gate (stage C).
|
||||||
|
peer_capabilities: PeerCapabilityMap,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WalShippingService {
|
impl WalShippingService {
|
||||||
/// Create a new service that forwards received segments to the given channel.
|
/// Create a new service that forwards received segments to the given channel.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new(
|
pub(crate) const fn new(
|
||||||
inbound_tx: mpsc::Sender<WalSegmentPayload>,
|
inbound_tx: mpsc::Sender<WalSegmentPayload>,
|
||||||
max_payload_bytes: usize,
|
max_payload_bytes: usize,
|
||||||
sources: ServingSources,
|
sources: ServingSources,
|
||||||
peer_applied: PeerAppliedMap,
|
peer_applied: PeerAppliedMap,
|
||||||
|
peer_capabilities: PeerCapabilityMap,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self {
|
||||||
inbound_tx,
|
inbound_tx,
|
||||||
max_payload_bytes,
|
max_payload_bytes,
|
||||||
sources,
|
sources,
|
||||||
peer_applied,
|
peer_applied,
|
||||||
|
peer_capabilities,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,10 +188,8 @@ impl WalShipping for WalShippingService {
|
|||||||
// the apply path. A current/higher claim records leader contact (and
|
// the apply path. A current/higher claim records leader contact (and
|
||||||
// any adoption persisted before this returns).
|
// any adoption persisted before this returns).
|
||||||
let response_term = if let Some(hooks) = self.sources.election.get() {
|
let response_term = if let Some(hooks) = self.sources.election.get() {
|
||||||
let leader_region =
|
let leader_region = u16::try_from(req.leader_region)
|
||||||
u16::try_from(req.leader_region).map_err(|_| {
|
.map_err(|_| Status::invalid_argument("leader_region exceeds u16 range"))?;
|
||||||
Status::invalid_argument("leader_region exceeds u16 range")
|
|
||||||
})?;
|
|
||||||
let first_seq = req.id.as_ref().map_or(0, |id| id.seqno);
|
let first_seq = req.id.as_ref().map_or(0, |id| id.seqno);
|
||||||
match hooks.observe_leader_claim(req.term, leader_region, first_seq) {
|
match hooks.observe_leader_claim(req.term, leader_region, first_seq) {
|
||||||
Ok(()) => {}
|
Ok(()) => {}
|
||||||
@ -216,18 +287,33 @@ impl WalShipping for WalShippingService {
|
|||||||
let (current_term, self_region) = hooks.self_claim();
|
let (current_term, self_region) = hooks.self_claim();
|
||||||
if req.term > current_term {
|
if req.term > current_term {
|
||||||
hooks.on_observed_term(req.term);
|
hooks.on_observed_term(req.term);
|
||||||
return Err(Status::failed_precondition(format!(
|
// Typed refusal (m11p5 §2.4): `stepping-down` — this source is
|
||||||
|
// deposed, not behind on data. The puller must NOT latch a
|
||||||
|
// reseed marker; it re-discovers the current leader and
|
||||||
|
// re-stamps its pull. A plain election term-mismatch poisoning
|
||||||
|
// the fleet with reseed markers is the conflation hazard the
|
||||||
|
// trailer closes.
|
||||||
|
return Err(catchup_refusal(
|
||||||
|
"stepping-down",
|
||||||
|
format!(
|
||||||
"this source's term {current_term} is behind the puller's {}; \
|
"this source's term {current_term} is behind the puller's {}; \
|
||||||
stepping down — pull from the current leader",
|
stepping down — pull from the current leader",
|
||||||
req.term
|
req.term
|
||||||
)));
|
),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
if req.term < current_term {
|
if req.term < current_term {
|
||||||
return Err(Status::failed_precondition(format!(
|
// Typed refusal (m11p5 §2.4): `rejoin` — the puller is on a
|
||||||
|
// stale term; it rejoins the current term and re-pulls. Not a
|
||||||
|
// reseed condition.
|
||||||
|
return Err(catchup_refusal(
|
||||||
|
"rejoin",
|
||||||
|
format!(
|
||||||
"puller term {} is behind the source's {current_term}; \
|
"puller term {} is behind the source's {current_term}; \
|
||||||
rejoin the current term before pulling",
|
rejoin the current term before pulling",
|
||||||
req.term
|
req.term
|
||||||
)));
|
),
|
||||||
|
));
|
||||||
}
|
}
|
||||||
(current_term, u32::from(self_region))
|
(current_term, u32::from(self_region))
|
||||||
} else {
|
} else {
|
||||||
@ -276,11 +362,17 @@ impl WalShipping for WalShippingService {
|
|||||||
// tells the follower "stop expecting this stream; you
|
// tells the follower "stop expecting this stream; you
|
||||||
// need a snapshot", distinct from a retryable INTERNAL.
|
// need a snapshot", distinct from a retryable INTERNAL.
|
||||||
Ok(Err(crate::sources::SegmentReadError::Unavailable { detail })) => {
|
Ok(Err(crate::sources::SegmentReadError::Unavailable { detail })) => {
|
||||||
|
// Typed refusal (m11p5 §2.4): `snapshot-required` — the
|
||||||
|
// log can never serve this range; the puller latches a
|
||||||
|
// reseed marker and fetches a snapshot.
|
||||||
let _ = tx
|
let _ = tx
|
||||||
.send(Err(Status::failed_precondition(format!(
|
.send(Err(catchup_refusal(
|
||||||
|
"snapshot-required",
|
||||||
|
format!(
|
||||||
"segments not available from seq {cursor}; \
|
"segments not available from seq {cursor}; \
|
||||||
snapshot required ({detail})"
|
snapshot required ({detail})"
|
||||||
))))
|
),
|
||||||
|
)))
|
||||||
.await;
|
.await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -313,12 +405,18 @@ impl WalShipping for WalShippingService {
|
|||||||
if let Some(first) = chunks.first()
|
if let Some(first) = chunks.first()
|
||||||
&& first.first_seq > cursor
|
&& first.first_seq > cursor
|
||||||
{
|
{
|
||||||
|
// Typed refusal (m11p5 §2.4): `snapshot-required` — the
|
||||||
|
// history below the cursor was compacted; the puller
|
||||||
|
// latches a reseed marker and fetches a snapshot.
|
||||||
let _ = tx
|
let _ = tx
|
||||||
.send(Err(Status::failed_precondition(format!(
|
.send(Err(catchup_refusal(
|
||||||
|
"snapshot-required",
|
||||||
|
format!(
|
||||||
"WAL compacted below seqno {cursor} (earliest available {}); \
|
"WAL compacted below seqno {cursor} (earliest available {}); \
|
||||||
this follower needs a full resync (snapshot transfer, m11p5)",
|
this follower needs a full resync (snapshot transfer, m11p5)",
|
||||||
first.first_seq
|
first.first_seq
|
||||||
))))
|
),
|
||||||
|
)))
|
||||||
.await;
|
.await;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@ -349,6 +447,200 @@ impl WalShipping for WalShippingService {
|
|||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type FetchSnapshotStream =
|
||||||
|
tokio_stream::wrappers::ReceiverStream<Result<SnapshotChunk, Status>>;
|
||||||
|
|
||||||
|
async fn fetch_snapshot(
|
||||||
|
&self,
|
||||||
|
request: Request<SnapshotRequest>,
|
||||||
|
) -> Result<Response<Self::FetchSnapshotStream>, Status> {
|
||||||
|
let req = request.into_inner();
|
||||||
|
let Some(source) = self.sources.snapshots.get().cloned() else {
|
||||||
|
// No snapshot source wired (in-process tests, pre-m11p5 embedders).
|
||||||
|
// §3.7: a pre-m11p5 peer answers Unimplemented; the joiner reports
|
||||||
|
// it loudly and retries the next seed.
|
||||||
|
return Err(Status::unimplemented(
|
||||||
|
"FetchSnapshot: no snapshot source wired on this node",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Term fence (m11p5 §2): a deposed source must NOT serve a snapshot of
|
||||||
|
// its possibly-divergent state; a stale puller must rejoin first.
|
||||||
|
// Mirrors StreamSegments exactly — same-term puller only.
|
||||||
|
let (snap_term, leader_region) = if let Some(hooks) = self.sources.election.get() {
|
||||||
|
let (current_term, self_region) = hooks.self_claim();
|
||||||
|
if req.term > current_term {
|
||||||
|
hooks.on_observed_term(req.term);
|
||||||
|
return Err(catchup_refusal(
|
||||||
|
"stepping-down",
|
||||||
|
format!(
|
||||||
|
"this source's term {current_term} is behind the puller's {}; \
|
||||||
|
stepping down — fetch the snapshot from the current leader",
|
||||||
|
req.term
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if req.term < current_term {
|
||||||
|
return Err(catchup_refusal(
|
||||||
|
"rejoin",
|
||||||
|
format!(
|
||||||
|
"puller term {} is behind the source's {current_term}; \
|
||||||
|
rejoin the current term before fetching a snapshot",
|
||||||
|
req.term
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
(current_term, u32::from(self_region))
|
||||||
|
} else {
|
||||||
|
(0, 0)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Stage (or reuse) the artifact. This call must be cheap — it reuses an
|
||||||
|
// already-staged artifact when the live WAL still covers the request —
|
||||||
|
// so running it on the reactor is intentional. The pin (§2.1) is taken
|
||||||
|
// inside `stage` and released when this stream ends.
|
||||||
|
let staging = match source.stage(req.from_seqno) {
|
||||||
|
Ok(staging) => staging,
|
||||||
|
Err(crate::sources::SnapshotStageError::Busy) => {
|
||||||
|
// RETRYABLE (§2): a concurrent stage is mid-flight; the joiner
|
||||||
|
// retries and shares it. NEVER FAILED_PRECONDITION — that would
|
||||||
|
// mis-route the joiner into the reseed class.
|
||||||
|
return Err(Status::unavailable(
|
||||||
|
"snapshot staging in progress; retry shortly",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Err(crate::sources::SnapshotStageError::Failed(detail)) => {
|
||||||
|
return Err(Status::internal(format!(
|
||||||
|
"snapshot staging failed: {detail}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// A `needed=false` staging holds no pin (§2.1) — emit the header and
|
||||||
|
// finish without touching `release`. A `needed=true` staging owns a
|
||||||
|
// pin that the stream task releases on completion or client drop.
|
||||||
|
let header = SnapshotHeader {
|
||||||
|
needed: staging.needed,
|
||||||
|
snapshot_seq: staging.snapshot_seq,
|
||||||
|
term: snap_term,
|
||||||
|
leader_region,
|
||||||
|
files: staging
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.map(|(path, size, blake3)| SnapshotFileEntry {
|
||||||
|
path: path.clone(),
|
||||||
|
size: *size,
|
||||||
|
blake3: blake3.to_vec(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let (tx, rx) = mpsc::channel::<Result<SnapshotChunk, Status>>(4);
|
||||||
|
tokio::spawn(async move {
|
||||||
|
// The pin guard: a `needed=true` staging is released exactly once
|
||||||
|
// when this task ends, by ANY exit (header send failure, a file
|
||||||
|
// read error, the last chunk, or the client dropping mid-stream).
|
||||||
|
// A `needed=false` staging never took a pin, so it must not call
|
||||||
|
// `release` (the node-side impl is idempotent, but not pinning at
|
||||||
|
// all is cleaner). `ReleaseGuard` makes the single-release rule a
|
||||||
|
// structural property, not a discipline scattered across returns.
|
||||||
|
struct ReleaseGuard {
|
||||||
|
source: Arc<dyn crate::sources::SnapshotSource>,
|
||||||
|
armed: bool,
|
||||||
|
}
|
||||||
|
impl Drop for ReleaseGuard {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if self.armed {
|
||||||
|
self.source.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _guard = ReleaseGuard {
|
||||||
|
source: Arc::clone(&source),
|
||||||
|
armed: staging.needed,
|
||||||
|
};
|
||||||
|
|
||||||
|
if tx
|
||||||
|
.send(Ok(SnapshotChunk {
|
||||||
|
chunk: Some(crate::proto::snapshot_chunk::Chunk::Header(header)),
|
||||||
|
}))
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
{
|
||||||
|
return; // client went away before the header landed
|
||||||
|
}
|
||||||
|
if !staging.needed {
|
||||||
|
return; // no files follow a no-snapshot-needed header
|
||||||
|
}
|
||||||
|
|
||||||
|
for (rel_path, size, _blake3) in &staging.files {
|
||||||
|
let abs = staging.root.join(rel_path);
|
||||||
|
let mut offset: u64 = 0;
|
||||||
|
// Read the file in 1 MiB chunks off `spawn_blocking`. BLAKE3 is
|
||||||
|
// NOT recomputed here — the manifest hash (computed once when
|
||||||
|
// the artifact was staged) is the contract; the puller verifies
|
||||||
|
// the received bytes against it end to end.
|
||||||
|
loop {
|
||||||
|
let path = abs.clone();
|
||||||
|
let read = tokio::task::spawn_blocking(move || {
|
||||||
|
read_file_range(&path, offset, SNAPSHOT_FILE_CHUNK_BYTES)
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
let data = match read {
|
||||||
|
Ok(Ok(data)) => data,
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
let _ = tx
|
||||||
|
.send(Err(Status::internal(format!(
|
||||||
|
"snapshot file '{rel_path}' read failed at offset {offset}: {e}"
|
||||||
|
))))
|
||||||
|
.await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Err(join_err) => {
|
||||||
|
let _ = tx
|
||||||
|
.send(Err(Status::internal(format!(
|
||||||
|
"snapshot file read task failed: {join_err}"
|
||||||
|
))))
|
||||||
|
.await;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let read_len = data.len() as u64;
|
||||||
|
let next_offset = offset.saturating_add(read_len);
|
||||||
|
// `last` is true when this chunk reaches the manifest size,
|
||||||
|
// including the empty-file case (a zero-byte read at
|
||||||
|
// offset 0 must still emit one terminal chunk so the
|
||||||
|
// receiver sees the file).
|
||||||
|
let last = next_offset >= *size;
|
||||||
|
let send_ok = tx
|
||||||
|
.send(Ok(SnapshotChunk {
|
||||||
|
chunk: Some(crate::proto::snapshot_chunk::Chunk::File(
|
||||||
|
SnapshotFileChunk {
|
||||||
|
path: rel_path.clone(),
|
||||||
|
offset,
|
||||||
|
data,
|
||||||
|
last,
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
}))
|
||||||
|
.await
|
||||||
|
.is_ok();
|
||||||
|
if !send_ok {
|
||||||
|
return; // client went away mid-file
|
||||||
|
}
|
||||||
|
if last {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
offset = next_offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(Response::new(tokio_stream::wrappers::ReceiverStream::new(
|
||||||
|
rx,
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
async fn heartbeat(
|
async fn heartbeat(
|
||||||
&self,
|
&self,
|
||||||
request: Request<HeartbeatRequest>,
|
request: Request<HeartbeatRequest>,
|
||||||
@ -371,6 +663,14 @@ impl WalShipping for WalShippingService {
|
|||||||
if let Some(hooks) = self.sources.election.get() {
|
if let Some(hooks) = self.sources.election.get() {
|
||||||
let leader_region = u16::try_from(req.leader_region)
|
let leader_region = u16::try_from(req.leader_region)
|
||||||
.map_err(|_| Status::invalid_argument("leader_region exceeds u16 range"))?;
|
.map_err(|_| Status::invalid_argument("leader_region exceeds u16 range"))?;
|
||||||
|
// The typed removed signal (m11p5 §3.3): is the heartbeat SENDER
|
||||||
|
// (`region_id`, NOT the claimed `leader_region`) a `Removed` member
|
||||||
|
// in THIS node's applied roster? Computed from `region_id` so a
|
||||||
|
// removed FOLLOWER also learns it (not only when it claims
|
||||||
|
// leadership). A bad region_id (out of u16) cannot be a roster
|
||||||
|
// member, so it is trivially "not removed".
|
||||||
|
let removed =
|
||||||
|
u16::try_from(req.region_id).is_ok_and(|sender| hooks.is_removed_member(sender));
|
||||||
let verdict = hooks.on_heartbeat(
|
let verdict = hooks.on_heartbeat(
|
||||||
req.term,
|
req.term,
|
||||||
leader_region,
|
leader_region,
|
||||||
@ -384,14 +684,20 @@ impl WalShipping for WalShippingService {
|
|||||||
acknowledged: true,
|
acknowledged: true,
|
||||||
term: verdict.term,
|
term: verdict.term,
|
||||||
accepted: verdict.accepted,
|
accepted: verdict.accepted,
|
||||||
|
// This binary's capabilities (m11p5 §3.1): the sender folds
|
||||||
|
// this into its per-peer capability view to gate conf-changes.
|
||||||
|
capabilities: crate::CAPABILITIES,
|
||||||
|
removed,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
// Pre-m11p4 behavior (no election driver wired): a truthful
|
// Pre-m11p4 behavior (no election driver wired): a truthful
|
||||||
// reachability ack.
|
// reachability ack. No roster ⇒ no removed members.
|
||||||
Ok(Response::new(HeartbeatResponse {
|
Ok(Response::new(HeartbeatResponse {
|
||||||
acknowledged: true,
|
acknowledged: true,
|
||||||
term: 0,
|
term: 0,
|
||||||
accepted: true,
|
accepted: true,
|
||||||
|
capabilities: crate::CAPABILITIES,
|
||||||
|
removed: false,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -419,6 +725,12 @@ impl WalShipping for WalShippingService {
|
|||||||
segments.source_shard().0
|
segments.source_shard().0
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
// Record the reporter's capabilities (m11p5 §3.1) BEFORE the term
|
||||||
|
// gate: a capability bit is a term-independent fact about the
|
||||||
|
// reporter's binary, and the conf-change gate must learn it even from
|
||||||
|
// a reporter whose term is momentarily stale (an in-progress election
|
||||||
|
// must not blind the leader to who is kind-4 capable).
|
||||||
|
record_peer_capabilities(&self.peer_capabilities, reporter, report.capabilities);
|
||||||
// Term fence (m11p4, design-review C4/C8/C12): a report from any
|
// Term fence (m11p4, design-review C4/C8/C12): a report from any
|
||||||
// term but the current leadership's never reaches the hint map or
|
// term but the current leadership's never reaches the hint map or
|
||||||
// the commit index — a deposed leader's followers (or a delayed
|
// the commit index — a deposed leader's followers (or a delayed
|
||||||
@ -455,6 +767,10 @@ impl WalShipping for WalShippingService {
|
|||||||
let req = request.into_inner();
|
let req = request.into_inner();
|
||||||
let candidate = u16::try_from(req.candidate_region)
|
let candidate = u16::try_from(req.candidate_region)
|
||||||
.map_err(|_| Status::invalid_argument("candidate_region exceeds u16 range"))?;
|
.map_err(|_| Status::invalid_argument("candidate_region exceeds u16 range"))?;
|
||||||
|
// The typed removed signal (m11p5 §3.3): is the CANDIDATE a `Removed`
|
||||||
|
// member in this voter's applied roster? A removed node still campaigns
|
||||||
|
// until it learns of its removal; this refusal teaches it.
|
||||||
|
let removed = hooks.is_removed_member(candidate);
|
||||||
let reply = hooks.on_vote(tidaldb::replication::VoteRpc {
|
let reply = hooks.on_vote(tidaldb::replication::VoteRpc {
|
||||||
term: req.term,
|
term: req.term,
|
||||||
candidate: tidaldb::replication::shard::RegionId(candidate),
|
candidate: tidaldb::replication::shard::RegionId(candidate),
|
||||||
@ -468,6 +784,7 @@ impl WalShipping for WalShippingService {
|
|||||||
Ok(Response::new(VoteResponse {
|
Ok(Response::new(VoteResponse {
|
||||||
term: reply.term,
|
term: reply.term,
|
||||||
granted: reply.granted,
|
granted: reply.granted,
|
||||||
|
removed,
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -486,6 +803,54 @@ impl WalShipping for WalShippingService {
|
|||||||
let accepted = hooks.on_timeout_now(req.term, leader_region);
|
let accepted = hooks.on_timeout_now(req.term, leader_region);
|
||||||
Ok(Response::new(TimeoutNowResponse { accepted }))
|
Ok(Response::new(TimeoutNowResponse { accepted }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn join_cluster(
|
||||||
|
&self,
|
||||||
|
request: Request<JoinRequest>,
|
||||||
|
) -> Result<Response<JoinResponse>, Status> {
|
||||||
|
let Some(hooks) = self.sources.join.get().cloned() else {
|
||||||
|
// §3.7: a pre-m11p5 peer answers Unimplemented; the joiner reports
|
||||||
|
// it loudly and retries the next seed.
|
||||||
|
return Err(Status::unimplemented(
|
||||||
|
"JoinCluster: no membership runtime on this node (pre-m11p5 binary or bare \
|
||||||
|
transport)",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let req = request.into_inner();
|
||||||
|
let ask = crate::sources::JoinAsk {
|
||||||
|
name: req.name,
|
||||||
|
grpc_addr: req.grpc_addr,
|
||||||
|
http_addr: req.http_addr,
|
||||||
|
capabilities: req.capabilities,
|
||||||
|
};
|
||||||
|
// The hook BLOCKS on the bounded same-term commit wait (§3.3): run it on
|
||||||
|
// `spawn_blocking` so the reactor is never parked. A join task panic
|
||||||
|
// surfaces as INTERNAL rather than killing the worker.
|
||||||
|
let outcome = tokio::task::spawn_blocking(move || hooks.join(ask))
|
||||||
|
.await
|
||||||
|
.map_err(|e| Status::internal(format!("join task failed: {e}")))?;
|
||||||
|
Ok(Response::new(JoinResponse {
|
||||||
|
accepted: outcome.accepted,
|
||||||
|
refusal_reason: outcome.refusal_reason,
|
||||||
|
assigned_id: u32::from(outcome.assigned_id),
|
||||||
|
term: outcome.term,
|
||||||
|
leader_region: outcome.leader_region,
|
||||||
|
leader_grpc_addr: outcome.leader_grpc_addr,
|
||||||
|
leader_http_addr: outcome.leader_http_addr,
|
||||||
|
members: outcome
|
||||||
|
.members
|
||||||
|
.into_iter()
|
||||||
|
.map(|m| MemberInfo {
|
||||||
|
id: u32::from(m.id),
|
||||||
|
name: m.name,
|
||||||
|
grpc_addr: m.grpc_addr,
|
||||||
|
http_addr: m.http_addr,
|
||||||
|
role: u32::from(m.role),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
membership_version: outcome.membership_version,
|
||||||
|
}))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start the gRPC server on the given address.
|
/// Start the gRPC server on the given address.
|
||||||
@ -498,17 +863,23 @@ impl WalShipping for WalShippingService {
|
|||||||
/// Returns [`GrpcTransportError`](crate::error::GrpcTransportError) if TLS is
|
/// Returns [`GrpcTransportError`](crate::error::GrpcTransportError) if TLS is
|
||||||
/// requested but the server TLS config cannot be built, or if TLS is unset and
|
/// requested but the server TLS config cannot be built, or if TLS is unset and
|
||||||
/// `--insecure` was not opted into.
|
/// `--insecure` was not opted into.
|
||||||
pub fn start_server(
|
pub(crate) fn start_server(
|
||||||
config: &GrpcTransportConfig,
|
config: &GrpcTransportConfig,
|
||||||
inbound_tx: mpsc::Sender<WalSegmentPayload>,
|
inbound_tx: mpsc::Sender<WalSegmentPayload>,
|
||||||
sources: ServingSources,
|
sources: ServingSources,
|
||||||
peer_applied: PeerAppliedMap,
|
peer_applied: PeerAppliedMap,
|
||||||
|
peer_capabilities: PeerCapabilityMap,
|
||||||
) -> Result<
|
) -> Result<
|
||||||
tokio::task::JoinHandle<Result<(), tonic::transport::Error>>,
|
tokio::task::JoinHandle<Result<(), tonic::transport::Error>>,
|
||||||
crate::error::GrpcTransportError,
|
crate::error::GrpcTransportError,
|
||||||
> {
|
> {
|
||||||
let service =
|
let service = WalShippingService::new(
|
||||||
WalShippingService::new(inbound_tx, config.max_payload_bytes, sources, peer_applied);
|
inbound_tx,
|
||||||
|
config.max_payload_bytes,
|
||||||
|
sources,
|
||||||
|
peer_applied,
|
||||||
|
peer_capabilities,
|
||||||
|
);
|
||||||
let addr = config.listen_addr;
|
let addr = config.listen_addr;
|
||||||
|
|
||||||
let mut server_builder = tonic::transport::Server::builder();
|
let mut server_builder = tonic::transport::Server::builder();
|
||||||
@ -604,6 +975,7 @@ mod tests {
|
|||||||
max,
|
max,
|
||||||
ServingSources::default(),
|
ServingSources::default(),
|
||||||
Arc::new(Mutex::new(HashMap::new())),
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Exactly max: accepted, and forwarded onto the inbound channel.
|
// Exactly max: accepted, and forwarded onto the inbound channel.
|
||||||
@ -656,11 +1028,15 @@ mod tests {
|
|||||||
let sources = ServingSources {
|
let sources = ServingSources {
|
||||||
applied: Some(Arc::new(FixedApplied)),
|
applied: Some(Arc::new(FixedApplied)),
|
||||||
segments: None,
|
segments: None,
|
||||||
applied_sink: Arc::default(),
|
..ServingSources::default()
|
||||||
election: Arc::default(),
|
|
||||||
};
|
};
|
||||||
let service =
|
let service = WalShippingService::new(
|
||||||
WalShippingService::new(tx, 1024, sources, Arc::new(Mutex::new(HashMap::new())));
|
tx,
|
||||||
|
1024,
|
||||||
|
sources,
|
||||||
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
);
|
||||||
let mut req = make_request(8);
|
let mut req = make_request(8);
|
||||||
req.id.as_mut().unwrap().shard_id = 2;
|
req.id.as_mut().unwrap().shard_id = 2;
|
||||||
let resp = service
|
let resp = service
|
||||||
@ -714,19 +1090,25 @@ mod tests {
|
|||||||
let sources = ServingSources {
|
let sources = ServingSources {
|
||||||
applied: None,
|
applied: None,
|
||||||
segments: Some(Arc::new(FixedSegments)),
|
segments: Some(Arc::new(FixedSegments)),
|
||||||
applied_sink: Arc::default(),
|
..ServingSources::default()
|
||||||
election: Arc::default(),
|
|
||||||
};
|
};
|
||||||
sources.set_applied_sink(Arc::clone(&sink) as Arc<dyn crate::sources::AppliedSink>);
|
sources.set_applied_sink(Arc::clone(&sink) as Arc<dyn crate::sources::AppliedSink>);
|
||||||
let map: PeerAppliedMap = Arc::new(Mutex::new(HashMap::new()));
|
let map: PeerAppliedMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
let (tx, _rx) = mpsc::channel(4);
|
let (tx, _rx) = mpsc::channel(4);
|
||||||
let service = WalShippingService::new(tx, 1024, sources, Arc::clone(&map));
|
let service = WalShippingService::new(
|
||||||
|
tx,
|
||||||
|
1024,
|
||||||
|
sources,
|
||||||
|
Arc::clone(&map),
|
||||||
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
);
|
||||||
|
|
||||||
let report = |reporter, source, applied| AppliedReport {
|
let report = |reporter, source, applied| AppliedReport {
|
||||||
reporter_shard: reporter,
|
reporter_shard: reporter,
|
||||||
source_shard: source,
|
source_shard: source,
|
||||||
applied_seqno: applied,
|
applied_seqno: applied,
|
||||||
reporter_term: 0,
|
reporter_term: 0,
|
||||||
|
capabilities: crate::CAP_KIND4_MEMBERSHIP,
|
||||||
};
|
};
|
||||||
service
|
service
|
||||||
.report_applied(Request::new(report(2, 0, 9)))
|
.report_applied(Request::new(report(2, 0, 9)))
|
||||||
@ -808,11 +1190,15 @@ mod tests {
|
|||||||
let sources = ServingSources {
|
let sources = ServingSources {
|
||||||
applied: None,
|
applied: None,
|
||||||
segments: Some(Arc::new(FakeSegments)),
|
segments: Some(Arc::new(FakeSegments)),
|
||||||
applied_sink: Arc::default(),
|
..ServingSources::default()
|
||||||
election: Arc::default(),
|
|
||||||
};
|
};
|
||||||
let service =
|
let service = WalShippingService::new(
|
||||||
WalShippingService::new(tx, 1024, sources, Arc::new(Mutex::new(HashMap::new())));
|
tx,
|
||||||
|
1024,
|
||||||
|
sources,
|
||||||
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
);
|
||||||
|
|
||||||
// Request from seqno 1: the baseline (10) clamps the start to 11.
|
// Request from seqno 1: the baseline (10) clamps the start to 11.
|
||||||
let resp = service
|
let resp = service
|
||||||
@ -888,11 +1274,15 @@ mod tests {
|
|||||||
let sources = ServingSources {
|
let sources = ServingSources {
|
||||||
applied: None,
|
applied: None,
|
||||||
segments: Some(Arc::new(UnservableSegments)),
|
segments: Some(Arc::new(UnservableSegments)),
|
||||||
applied_sink: Arc::default(),
|
..ServingSources::default()
|
||||||
election: Arc::default(),
|
|
||||||
};
|
};
|
||||||
let service =
|
let service = WalShippingService::new(
|
||||||
WalShippingService::new(tx, 1024, sources, Arc::new(Mutex::new(HashMap::new())));
|
tx,
|
||||||
|
1024,
|
||||||
|
sources,
|
||||||
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
Arc::new(Mutex::new(HashMap::new())),
|
||||||
|
);
|
||||||
|
|
||||||
let resp = service
|
let resp = service
|
||||||
.stream_segments(Request::new(StreamRequest {
|
.stream_segments(Request::new(StreamRequest {
|
||||||
|
|||||||
@ -14,6 +14,7 @@
|
|||||||
//! adapters over its `TidalDb`); `None` preserves the pre-m11p2 behavior
|
//! adapters over its `TidalDb`); `None` preserves the pre-m11p2 behavior
|
||||||
//! (acks carry `applied_seqno = 0`, `StreamSegments` answers `Unimplemented`).
|
//! (acks carry `applied_seqno = 0`, `StreamSegments` answers `Unimplemented`).
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use tidaldb::replication::shard::ShardId;
|
use tidaldb::replication::shard::ShardId;
|
||||||
@ -122,6 +123,110 @@ pub trait SegmentSource: Send + Sync + 'static {
|
|||||||
) -> Result<Vec<SegmentChunk>, SegmentReadError>;
|
) -> Result<Vec<SegmentChunk>, SegmentReadError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A staged snapshot artifact ready to stream (m11p5 §2), from
|
||||||
|
/// [`SnapshotSource::stage`].
|
||||||
|
///
|
||||||
|
/// When `needed` is `false` the live
|
||||||
|
/// WAL can still serve the puller's `from_seqno` — the joiner just streams,
|
||||||
|
/// and `files`/`root` are empty/unused. When `true`, `files` is the complete
|
||||||
|
/// manifest (relative paths, sizes, content hashes) under `root`; the service
|
||||||
|
/// streams each file's bytes off `spawn_blocking` reads.
|
||||||
|
///
|
||||||
|
/// The BLAKE3 in each manifest entry is the end-to-end integrity contract:
|
||||||
|
/// computed ONCE when the artifact is staged, forwarded verbatim on the wire,
|
||||||
|
/// and verified by the installing puller (the server never recomputes it per
|
||||||
|
/// chunk — the manifest hash is authoritative).
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct SnapshotStaging {
|
||||||
|
/// `false` = no snapshot needed, just stream from `from_seqno`.
|
||||||
|
pub needed: bool,
|
||||||
|
/// The artifact's recovered WAL tail: the seqno the snapshot is valid at
|
||||||
|
/// (the puller advances its frontier to this, resumes from `+ 1`). 0 when
|
||||||
|
/// `needed` is `false`.
|
||||||
|
pub snapshot_seq: u64,
|
||||||
|
/// The staging directory the manifest's relative paths resolve against.
|
||||||
|
pub root: PathBuf,
|
||||||
|
/// The complete manifest: `(relative_path, size, blake3)` per file. Empty
|
||||||
|
/// when `needed` is `false`.
|
||||||
|
pub files: Vec<(String, u64, [u8; 32])>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a snapshot could not be staged for a `FetchSnapshot` request.
|
||||||
|
///
|
||||||
|
/// The split is the wire contract (m11p5 §2): [`Busy`](Self::Busy) maps to a
|
||||||
|
/// **retryable** `UNAVAILABLE` (a concurrent stage is mid-flight; a second
|
||||||
|
/// joiner shares the in-flight artifact moments later — NEVER
|
||||||
|
/// `FAILED_PRECONDITION`, which would mis-route the joiner into the reseed
|
||||||
|
/// class), and [`Failed`](Self::Failed) maps to `INTERNAL` (staging hit a real
|
||||||
|
/// fault — disk, checkpoint, copy — the puller retries on the next seed loop).
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum SnapshotStageError {
|
||||||
|
/// A stage is already in flight (single-flight artifact, §2 caching): the
|
||||||
|
/// puller retries and shares the result. Wire: retryable `UNAVAILABLE`.
|
||||||
|
Busy,
|
||||||
|
/// Staging failed for a concrete reason. Wire: `INTERNAL`.
|
||||||
|
Failed(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for SnapshotStageError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Busy => write!(f, "snapshot staging busy (single-flight; retry)"),
|
||||||
|
Self::Failed(detail) => write!(f, "snapshot staging failed: {detail}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A node-side staged snapshot artifact, served by the `FetchSnapshot` stream
|
||||||
|
/// (m11p5 §2).
|
||||||
|
///
|
||||||
|
/// Late-bound like [`SegmentSource`]: the embedding application
|
||||||
|
/// wires its `TidalDb`-backed adapter after the transport. `None` = the RPC
|
||||||
|
/// answers `Unimplemented` (a pre-m11p5 peer, or a bare transport).
|
||||||
|
///
|
||||||
|
/// Implementations are synchronous (they checkpoint + copy + read files); the
|
||||||
|
/// service calls [`stage`](Self::stage) on the reactor (it must be cheap —
|
||||||
|
/// reuse an already-staged artifact) and reads file bytes through
|
||||||
|
/// `spawn_blocking`.
|
||||||
|
pub trait SnapshotSource: Send + Sync + 'static {
|
||||||
|
/// Stage (or reuse) the snapshot artifact that covers `from_seqno`, and
|
||||||
|
/// pin its retention until [`release`](Self::release) (§2.1 per-consumer
|
||||||
|
/// pin grace). Returns the manifest the service streams.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`SnapshotStageError::Busy`] when a stage is already in flight (the
|
||||||
|
/// puller retries — retryable `UNAVAILABLE`); [`SnapshotStageError::Failed`]
|
||||||
|
/// when staging hit a concrete fault (`INTERNAL`).
|
||||||
|
fn stage(&self, from_seqno: u64) -> Result<SnapshotStaging, SnapshotStageError>;
|
||||||
|
|
||||||
|
/// Signal that a `FetchSnapshot` stream finished (success OR client drop):
|
||||||
|
/// the service calls this exactly once per [`stage`](Self::stage) that
|
||||||
|
/// returned a `needed=true` staging, releasing that consumer's retention
|
||||||
|
/// pin (§2.1). A `needed=false` staging holds no pin and is not released.
|
||||||
|
///
|
||||||
|
/// Idempotent — the node-side impl (stage B) reconciles double calls.
|
||||||
|
fn release(&self);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Late-bound consumer of a follower's typed "snapshot-required" catch-up
|
||||||
|
/// refusal (m11p5 §2.4).
|
||||||
|
///
|
||||||
|
/// When the puller's `StreamSegments` open is refused with `FAILED_PRECONDITION`
|
||||||
|
/// carrying the `x-tidal-catchup: snapshot-required` trailer, the transport
|
||||||
|
/// invokes this so the node can durably latch its `reseed_required` marker (the
|
||||||
|
/// reseed runs on the NEXT boot, never via live surgery). Absent (bare
|
||||||
|
/// transports, pre-m11p5) → today's behavior: log + the standing retry timer.
|
||||||
|
///
|
||||||
|
/// Wired like [`AppliedSink`] (an `OnceLock` on [`ServingSources`]): the node
|
||||||
|
/// builds it after the transport.
|
||||||
|
pub trait SnapshotRequiredSink: Send + Sync + 'static {
|
||||||
|
/// The catch-up stream from `shard` (starting at `from_seqno`) was refused
|
||||||
|
/// `snapshot-required`. Latch the reseed marker; the retry timer keeps its
|
||||||
|
/// standing wake-up regardless (the m11p4 re-arm-on-skip liveness fix).
|
||||||
|
fn snapshot_required(&self, shard: ShardId, from_seqno: u64);
|
||||||
|
}
|
||||||
|
|
||||||
/// The heartbeat exchange verdict an [`ElectionHooks`] implementation
|
/// The heartbeat exchange verdict an [`ElectionHooks`] implementation
|
||||||
/// returns: the responder's (possibly just-raised) term and whether the
|
/// returns: the responder's (possibly just-raised) term and whether the
|
||||||
/// sender's leadership assertion was accepted.
|
/// sender's leadership assertion was accepted.
|
||||||
@ -216,6 +321,89 @@ pub trait ElectionHooks: Send + Sync + 'static {
|
|||||||
/// quorum commit index / hint map (true iff it matches the current
|
/// quorum commit index / hint map (true iff it matches the current
|
||||||
/// leadership term).
|
/// leadership term).
|
||||||
fn report_term_acceptable(&self, reporter_term: u64) -> bool;
|
fn report_term_acceptable(&self, reporter_term: u64) -> bool;
|
||||||
|
|
||||||
|
/// The TYPED REMOVED SIGNAL (m11p5 §3.3): whether `region` is a `Removed`
|
||||||
|
/// member in THIS node's APPLIED roster. The heartbeat / vote handlers call
|
||||||
|
/// it with the inbound peer's region (`region_id` / `candidate_region`) and
|
||||||
|
/// stamp the `removed` bit on the response.
|
||||||
|
///
|
||||||
|
/// This is the out-of-band delivery channel for a removed node that MISSED
|
||||||
|
/// the `Removed` record in the stream (it was down during the removal-
|
||||||
|
/// delivery grace, §3.3): it learns of its removal from any voter's
|
||||||
|
/// heartbeat / vote refusal rather than the log, flips readiness to 503, and
|
||||||
|
/// suppresses campaigning — WITHOUT latching a reseed marker (a remove is
|
||||||
|
/// not a reseed). Defaults to `false` (the era-0 / pre-membership node has
|
||||||
|
/// no `Removed` members and a bare transport has no roster).
|
||||||
|
fn is_removed_member(&self, _region: u16) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The leader-side outcome of a [`JoinHooks::join`] (m11p5 §3.3).
|
||||||
|
///
|
||||||
|
/// Mirrors the `JoinResponse` proto, but in domain terms so tidal-net never
|
||||||
|
/// reaches into the engine's membership types. The transport adapter maps this
|
||||||
|
/// 1:1 onto the wire response.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct JoinOutcome {
|
||||||
|
/// `false` = refused; `refusal_reason` says why and (for a non-leader seed)
|
||||||
|
/// the `leader_*` fields name where to re-target.
|
||||||
|
pub accepted: bool,
|
||||||
|
/// Human-readable refusal cause (empty when `accepted`).
|
||||||
|
pub refusal_reason: String,
|
||||||
|
/// The id the joiner was assigned (or its existing id on a re-join).
|
||||||
|
pub assigned_id: u16,
|
||||||
|
/// The current leadership term.
|
||||||
|
pub term: u64,
|
||||||
|
/// The leader's region name + advertised addresses (for re-targeting and
|
||||||
|
/// the joiner's direct dial). Empty when no leader is known.
|
||||||
|
pub leader_region: String,
|
||||||
|
pub leader_grpc_addr: String,
|
||||||
|
pub leader_http_addr: String,
|
||||||
|
/// The full roster after the join: `(id, name, grpc_addr, http_addr, role)`
|
||||||
|
/// where `role` is the `MemberRole` discriminant byte (0/1/2).
|
||||||
|
pub members: Vec<MemberInfo>,
|
||||||
|
/// The conf version the roster is at.
|
||||||
|
pub membership_version: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One member in a [`JoinOutcome`] roster (the domain shape of the
|
||||||
|
/// `MemberInfo` proto).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct MemberInfo {
|
||||||
|
pub id: u16,
|
||||||
|
pub name: String,
|
||||||
|
pub grpc_addr: String,
|
||||||
|
pub http_addr: String,
|
||||||
|
/// `MemberRole` discriminant byte: 0 Voter, 1 Learner, 2 Removed.
|
||||||
|
pub role: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The joiner's request, as the leader-side hook sees it (m11p5 §3.3).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct JoinAsk {
|
||||||
|
pub name: String,
|
||||||
|
pub grpc_addr: String,
|
||||||
|
pub http_addr: String,
|
||||||
|
/// The joiner binary's capability bit-field.
|
||||||
|
pub capabilities: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Node-side `JoinCluster` integration (m11p5 §3.3), late-bound like
|
||||||
|
/// [`ElectionHooks`] (the `OnceLock` on [`ServingSources`]).
|
||||||
|
///
|
||||||
|
/// The gRPC service consults it to answer a join: a non-leader refuses with a
|
||||||
|
/// leader hint, the leader assigns a permanent id, appends a Learner record,
|
||||||
|
/// waits for same-term quorum commit, and returns the roster. Absent =
|
||||||
|
/// `JoinCluster` answers `Unimplemented` (a pre-m11p5 peer, or a bare
|
||||||
|
/// transport).
|
||||||
|
///
|
||||||
|
/// The implementation owns the membership runtime; this trait keeps the engine
|
||||||
|
/// types out of tidal-net (the adapter lives in tidal-server).
|
||||||
|
pub trait JoinHooks: Send + Sync + 'static {
|
||||||
|
/// Handle a join. The hook BLOCKS on the bounded same-term commit wait —
|
||||||
|
/// the service calls it on `spawn_blocking`, never the reactor.
|
||||||
|
fn join(&self, ask: JoinAsk) -> JoinOutcome;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The optional node-side sources handed to [`crate::GrpcTransport`].
|
/// The optional node-side sources handed to [`crate::GrpcTransport`].
|
||||||
@ -225,6 +413,14 @@ pub struct ServingSources {
|
|||||||
pub applied: Option<Arc<dyn AppliedSource>>,
|
pub applied: Option<Arc<dyn AppliedSource>>,
|
||||||
/// WAL read-back for `StreamSegments` (`None` = catch-up unimplemented).
|
/// WAL read-back for `StreamSegments` (`None` = catch-up unimplemented).
|
||||||
pub segments: Option<Arc<dyn SegmentSource>>,
|
pub segments: Option<Arc<dyn SegmentSource>>,
|
||||||
|
/// Staged-snapshot source for `FetchSnapshot` (m11p5). A `OnceLock`
|
||||||
|
/// because the node wires its `TidalDb`-backed adapter after the
|
||||||
|
/// transport (the snapshot artifact needs the live engine + data dir).
|
||||||
|
/// `None`/unset = `FetchSnapshot` answers `Unimplemented`.
|
||||||
|
pub snapshots: Arc<std::sync::OnceLock<Arc<dyn SnapshotSource>>>,
|
||||||
|
/// Late-bound consumer of typed `snapshot-required` catch-up refusals
|
||||||
|
/// (m11p5 §2.4). Unset = log + retry-timer only (pre-m11p5 behavior).
|
||||||
|
pub snapshot_required: Arc<std::sync::OnceLock<Arc<dyn SnapshotRequiredSink>>>,
|
||||||
/// Consumer of follower durable-frontier reports (m11p3). A `OnceLock`
|
/// Consumer of follower durable-frontier reports (m11p3). A `OnceLock`
|
||||||
/// because the embedding application can only build it AFTER the
|
/// because the embedding application can only build it AFTER the
|
||||||
/// transport exists (the ship queue takes the transport): fill it via
|
/// transport exists (the ship queue takes the transport): fill it via
|
||||||
@ -235,6 +431,10 @@ pub struct ServingSources {
|
|||||||
/// `applied_sink` (the election driver is built after the transport).
|
/// `applied_sink` (the election driver is built after the transport).
|
||||||
/// Absent = pre-m11p4 behavior (no fencing, vote RPCs unimplemented).
|
/// Absent = pre-m11p4 behavior (no fencing, vote RPCs unimplemented).
|
||||||
pub election: Arc<std::sync::OnceLock<Arc<dyn ElectionHooks>>>,
|
pub election: Arc<std::sync::OnceLock<Arc<dyn ElectionHooks>>>,
|
||||||
|
/// `JoinCluster` integration (m11p5 §3.3), late-bound: the membership
|
||||||
|
/// runtime is built after the transport. Absent = `JoinCluster` answers
|
||||||
|
/// `Unimplemented`.
|
||||||
|
pub join: Arc<std::sync::OnceLock<Arc<dyn JoinHooks>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ServingSources {
|
impl ServingSources {
|
||||||
@ -247,6 +447,24 @@ impl ServingSources {
|
|||||||
pub fn set_election_hooks(&self, hooks: Arc<dyn ElectionHooks>) {
|
pub fn set_election_hooks(&self, hooks: Arc<dyn ElectionHooks>) {
|
||||||
let _ = self.election.set(hooks);
|
let _ = self.election.set(hooks);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Late-bind the snapshot source for `FetchSnapshot` (idempotent; first
|
||||||
|
/// set wins). Until set, `FetchSnapshot` answers `Unimplemented`.
|
||||||
|
pub fn set_snapshot_source(&self, source: Arc<dyn SnapshotSource>) {
|
||||||
|
let _ = self.snapshots.set(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Late-bind the `snapshot-required` refusal sink (idempotent; first set
|
||||||
|
/// wins). Until set, a `snapshot-required` trailer is log + retry only.
|
||||||
|
pub fn set_snapshot_required_sink(&self, sink: Arc<dyn SnapshotRequiredSink>) {
|
||||||
|
let _ = self.snapshot_required.set(sink);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Late-bind the `JoinCluster` hooks (idempotent; first set wins). Until
|
||||||
|
/// set, `JoinCluster` answers `Unimplemented`.
|
||||||
|
pub fn set_join_hooks(&self, hooks: Arc<dyn JoinHooks>) {
|
||||||
|
let _ = self.join.set(hooks);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for ServingSources {
|
impl std::fmt::Debug for ServingSources {
|
||||||
@ -254,8 +472,11 @@ impl std::fmt::Debug for ServingSources {
|
|||||||
f.debug_struct("ServingSources")
|
f.debug_struct("ServingSources")
|
||||||
.field("applied", &self.applied.is_some())
|
.field("applied", &self.applied.is_some())
|
||||||
.field("segments", &self.segments.is_some())
|
.field("segments", &self.segments.is_some())
|
||||||
|
.field("snapshots", &self.snapshots.get().is_some())
|
||||||
.field("applied_sink", &self.applied_sink.get().is_some())
|
.field("applied_sink", &self.applied_sink.get().is_some())
|
||||||
.field("election", &self.election.get().is_some())
|
.field("election", &self.election.get().is_some())
|
||||||
|
.field("snapshot_required", &self.snapshot_required.get().is_some())
|
||||||
|
.field("join", &self.join.get().is_some())
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -22,7 +22,10 @@ use tidaldb::replication::{
|
|||||||
use tokio::sync::{Notify, mpsc};
|
use tokio::sync::{Notify, mpsc};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
client::PeerPool, config::GrpcTransportConfig, error::GrpcTransportError, server,
|
client::PeerPool,
|
||||||
|
config::GrpcTransportConfig,
|
||||||
|
error::GrpcTransportError,
|
||||||
|
server,
|
||||||
sources::{ElectionHooks, ServingSources},
|
sources::{ElectionHooks, ServingSources},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -68,6 +71,10 @@ pub struct GrpcTransport {
|
|||||||
/// monotonic max of ship-ack hints (client side) and `ReportApplied`
|
/// monotonic max of ship-ack hints (client side) and `ReportApplied`
|
||||||
/// pushes (server side). Read by [`Transport::peer_applied_hint`].
|
/// pushes (server side). Read by [`Transport::peer_applied_hint`].
|
||||||
peer_applied: crate::server::PeerAppliedMap,
|
peer_applied: crate::server::PeerAppliedMap,
|
||||||
|
/// Per-peer last-seen capability bit-field, shared with the gRPC service
|
||||||
|
/// (m11p5 §3.1): folded from inbound `AppliedReport`s. Read by
|
||||||
|
/// [`peer_capabilities`](Self::peer_capabilities) for the conf-change gate.
|
||||||
|
peer_capabilities: crate::server::PeerCapabilityMap,
|
||||||
/// Last frontier reported per source shard by [`Transport::notify_applied`]
|
/// Last frontier reported per source shard by [`Transport::notify_applied`]
|
||||||
/// (dedup: unchanged rounds send nothing).
|
/// (dedup: unchanged rounds send nothing).
|
||||||
last_reported: Mutex<HashMap<ShardId, u64>>,
|
last_reported: Mutex<HashMap<ShardId, u64>>,
|
||||||
@ -157,6 +164,11 @@ struct CatchupRunner {
|
|||||||
/// term, and every received chunk's leadership claim is gated BEFORE the
|
/// term, and every received chunk's leadership claim is gated BEFORE the
|
||||||
/// inbound channel — a stale source can never inject history.
|
/// inbound channel — a stale source can never inject history.
|
||||||
election: Arc<std::sync::OnceLock<Arc<dyn ElectionHooks>>>,
|
election: Arc<std::sync::OnceLock<Arc<dyn ElectionHooks>>>,
|
||||||
|
/// Late-bound `snapshot-required` refusal sink (m11p5 §2.4): a pull whose
|
||||||
|
/// open is refused with an `x-tidal-catchup: snapshot-required` trailer
|
||||||
|
/// invokes it so the node latches a reseed marker. Absent → today's
|
||||||
|
/// behavior (log + the standing retry timer).
|
||||||
|
snapshot_required: Arc<std::sync::OnceLock<Arc<dyn crate::sources::SnapshotRequiredSink>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CatchupRunner {
|
impl CatchupRunner {
|
||||||
@ -223,10 +235,7 @@ impl CatchupRunner {
|
|||||||
async fn run_pull(&self, from_shard: ShardId, from_seqno: u64) -> PullOutcome {
|
async fn run_pull(&self, from_shard: ShardId, from_seqno: u64) -> PullOutcome {
|
||||||
// The puller's current term (m11p4): the source serves only a
|
// The puller's current term (m11p4): the source serves only a
|
||||||
// same-term pull, and every received chunk re-proves its claim.
|
// same-term pull, and every received chunk re-proves its claim.
|
||||||
let term = self
|
let term = self.election.get().map_or(0, |hooks| hooks.self_claim().0);
|
||||||
.election
|
|
||||||
.get()
|
|
||||||
.map_or(0, |hooks| hooks.self_claim().0);
|
|
||||||
let mut stream = match self.pool.stream_from(from_shard, from_seqno, term).await {
|
let mut stream = match self.pool.stream_from(from_shard, from_seqno, term).await {
|
||||||
Ok(stream) => stream,
|
Ok(stream) => stream,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
@ -238,6 +247,13 @@ impl CatchupRunner {
|
|||||||
"catch-up stream open failed; will retry on the next \
|
"catch-up stream open failed; will retry on the next \
|
||||||
detected gap or the retry timer, whichever first"
|
detected gap or the retry timer, whichever first"
|
||||||
);
|
);
|
||||||
|
// A refusal can also arrive on OPEN (a deposed/stale-term
|
||||||
|
// source rejects before the stream spawns); classify its
|
||||||
|
// trailer the same way so a snapshot-required open-refusal
|
||||||
|
// latches the reseed marker (m11p5 §2.4).
|
||||||
|
if let GrpcTransportError::Grpc(status) = &e {
|
||||||
|
self.handle_catchup_trailer(from_shard, from_seqno, status);
|
||||||
|
}
|
||||||
return PullOutcome::Failed;
|
return PullOutcome::Failed;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -312,6 +328,14 @@ impl CatchupRunner {
|
|||||||
follower needs a snapshot (m11p5) or an operator \
|
follower needs a snapshot (m11p5) or an operator \
|
||||||
reseed; replication stays degraded until then"
|
reseed; replication stays degraded until then"
|
||||||
);
|
);
|
||||||
|
// m11p5 §2.4: a `snapshot-required` trailer latches the
|
||||||
|
// node's reseed marker (the reseed runs on the next
|
||||||
|
// boot). A `rejoin`/`stepping-down` trailer (a plain
|
||||||
|
// election term-mismatch) or an absent trailer (pre-p5
|
||||||
|
// source) does NOT — that conflation would poison the
|
||||||
|
// fleet with reseed markers during an ordinary
|
||||||
|
// election. The retry timer fires REGARDLESS.
|
||||||
|
self.handle_catchup_trailer(from_shard, from_seqno, &status);
|
||||||
} else {
|
} else {
|
||||||
tracing::error!(
|
tracing::error!(
|
||||||
shard = from_shard.0,
|
shard = from_shard.0,
|
||||||
@ -328,6 +352,34 @@ impl CatchupRunner {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Classify a `FAILED_PRECONDITION` catch-up refusal by its
|
||||||
|
/// `x-tidal-catchup` trailer (m11p5 §2.4) and, when it is
|
||||||
|
/// `snapshot-required`, invoke the late-bound sink so the node latches its
|
||||||
|
/// reseed marker. Any other value — `rejoin`, `stepping-down` — or an
|
||||||
|
/// absent trailer (a pre-m11p5 source) is conservatively a no-op: only a
|
||||||
|
/// genuine snapshot-required refusal may latch the marker. The standing
|
||||||
|
/// retry timer is unaffected (the caller arms it regardless).
|
||||||
|
fn handle_catchup_trailer(&self, from_shard: ShardId, from_seqno: u64, status: &tonic::Status) {
|
||||||
|
let Some(value) = status.metadata().get(crate::server::CATCHUP_TRAILER) else {
|
||||||
|
return; // pre-m11p5 source / untyped refusal: no latch
|
||||||
|
};
|
||||||
|
if value.as_bytes() != b"snapshot-required" {
|
||||||
|
return; // rejoin / stepping-down / unknown: not a reseed condition
|
||||||
|
}
|
||||||
|
let Some(sink) = self.snapshot_required.get() else {
|
||||||
|
// No sink wired (bare transport): the marker mechanism lives in
|
||||||
|
// the node (stage B). The log line above is the visibility.
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
tracing::error!(
|
||||||
|
shard = from_shard.0,
|
||||||
|
from_seqno,
|
||||||
|
"catch-up refused snapshot-required; latching the reseed marker \
|
||||||
|
(the reseed runs on the next boot)"
|
||||||
|
);
|
||||||
|
sink.snapshot_required(from_shard, from_seqno);
|
||||||
|
}
|
||||||
|
|
||||||
/// Arm the timer retry for `from_shard` (m11p4): after
|
/// Arm the timer retry for `from_shard` (m11p4): after
|
||||||
/// [`retry_interval`](Self::retry_interval), re-enter [`try_start`] from
|
/// [`retry_interval`](Self::retry_interval), re-enter [`try_start`] from
|
||||||
/// the freshest known frontier. At most one timer is armed per shard.
|
/// the freshest known frontier. At most one timer is armed per shard.
|
||||||
@ -489,14 +541,22 @@ impl GrpcTransport {
|
|||||||
let server_tx = inbound_tx.clone();
|
let server_tx = inbound_tx.clone();
|
||||||
let peer_applied: crate::server::PeerAppliedMap = Arc::new(Mutex::new(HashMap::new()));
|
let peer_applied: crate::server::PeerAppliedMap = Arc::new(Mutex::new(HashMap::new()));
|
||||||
let server_map = Arc::clone(&peer_applied);
|
let server_map = Arc::clone(&peer_applied);
|
||||||
|
let peer_capabilities: crate::server::PeerCapabilityMap =
|
||||||
|
Arc::new(Mutex::new(HashMap::new()));
|
||||||
|
let server_caps = Arc::clone(&peer_capabilities);
|
||||||
// The catch-up retry timer reads this node's applied frontier through
|
// The catch-up retry timer reads this node's applied frontier through
|
||||||
// the same source the server piggybacks on acks (m11p4).
|
// the same source the server piggybacks on acks (m11p4).
|
||||||
let applied_for_catchup = sources.applied.clone();
|
let applied_for_catchup = sources.applied.clone();
|
||||||
// The election hooks cell is shared with the gRPC service (late-bound
|
// The election hooks cell is shared with the gRPC service (late-bound
|
||||||
// by the embedding application alongside the applied sink).
|
// by the embedding application alongside the applied sink).
|
||||||
let election = Arc::clone(&sources.election);
|
let election = Arc::clone(&sources.election);
|
||||||
|
// The snapshot-required sink cell (m11p5 §2.4): the catch-up pull
|
||||||
|
// surfaces a `snapshot-required` trailer to it so the node latches a
|
||||||
|
// reseed marker. Late-bound, shared with the gRPC service.
|
||||||
|
let snapshot_required = Arc::clone(&sources.snapshot_required);
|
||||||
let (server_handle, pool) = runtime.block_on(async {
|
let (server_handle, pool) = runtime.block_on(async {
|
||||||
let handle = server::start_server(&config, server_tx, sources, server_map)?;
|
let handle =
|
||||||
|
server::start_server(&config, server_tx, sources, server_map, server_caps)?;
|
||||||
let pool = PeerPool::new(&config)?;
|
let pool = PeerPool::new(&config)?;
|
||||||
Ok::<_, GrpcTransportError>((handle, pool))
|
Ok::<_, GrpcTransportError>((handle, pool))
|
||||||
})?;
|
})?;
|
||||||
@ -511,6 +571,7 @@ impl GrpcTransport {
|
|||||||
retry_interval: config.catchup_retry_interval,
|
retry_interval: config.catchup_retry_interval,
|
||||||
applied: applied_for_catchup,
|
applied: applied_for_catchup,
|
||||||
election: Arc::clone(&election),
|
election: Arc::clone(&election),
|
||||||
|
snapshot_required,
|
||||||
});
|
});
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
@ -519,6 +580,7 @@ impl GrpcTransport {
|
|||||||
inbound_rx: Mutex::new(inbound_rx),
|
inbound_rx: Mutex::new(inbound_rx),
|
||||||
pool,
|
pool,
|
||||||
peer_applied,
|
peer_applied,
|
||||||
|
peer_capabilities,
|
||||||
last_reported: Mutex::new(HashMap::new()),
|
last_reported: Mutex::new(HashMap::new()),
|
||||||
report_failing: Arc::new(Mutex::new(HashSet::new())),
|
report_failing: Arc::new(Mutex::new(HashSet::new())),
|
||||||
catchup,
|
catchup,
|
||||||
@ -542,6 +604,101 @@ impl GrpcTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This peer's last-seen capability bit-field (m11p5 §3.1), or `None` if
|
||||||
|
/// no `AppliedReport` from it has been folded yet. The leader's
|
||||||
|
/// conf-change gate (stage C) reads this to refuse appending kind-4
|
||||||
|
/// records until every voter reports the [`CAP_KIND4_MEMBERSHIP`] bit.
|
||||||
|
///
|
||||||
|
/// [`CAP_KIND4_MEMBERSHIP`]: crate::CAP_KIND4_MEMBERSHIP
|
||||||
|
#[must_use]
|
||||||
|
pub fn peer_capabilities(&self, peer: ShardId) -> Option<u64> {
|
||||||
|
self.peer_capabilities
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.get(&peer)
|
||||||
|
.copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a peer's gRPC connection at runtime (m11p5 §3.3 conf-change). The
|
||||||
|
/// channel is LAZY, so the insert costs no DNS resolution or connect: a
|
||||||
|
/// DNS-named peer re-resolves on its first RPC and on every reconnect. The
|
||||||
|
/// new connection inherits this transport's config (TLS/timeouts/codec
|
||||||
|
/// limits). `addr` is a bare `host:port`.
|
||||||
|
///
|
||||||
|
/// Shared with the [`ElectionNet`] and [`CatchupRunner`] (both hold the
|
||||||
|
/// same `Arc<PeerPool>`), so a peer added here is immediately reachable by
|
||||||
|
/// election RPCs, ships, and catch-up pulls.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns [`GrpcTransportError`] if the URI is malformed or the client
|
||||||
|
/// TLS configuration cannot be built.
|
||||||
|
pub fn add_peer(&self, shard: ShardId, addr: &str) -> Result<(), GrpcTransportError> {
|
||||||
|
// `PeerPool::add_peer` builds a tonic channel via `connect_lazy`, which
|
||||||
|
// registers background tasks and therefore REQUIRES a Tokio reactor in
|
||||||
|
// scope. A membership conf-change applies this from the election driver
|
||||||
|
// thread — a plain `std::thread` with NO ambient runtime — so enter the
|
||||||
|
// transport's OWN embedded runtime first (without it, `connect_lazy`
|
||||||
|
// panics with "there is no reactor running"). The guard is dropped as
|
||||||
|
// soon as `add_peer` returns; no task is spawned that outlives it.
|
||||||
|
let _guard = self.runtime().enter();
|
||||||
|
self.pool.add_peer(shard, addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a peer's gRPC connection at runtime (m11p5 §3.3 conf-change):
|
||||||
|
/// drops the lazy channel. Returns whether a peer was present. After
|
||||||
|
/// removal, every RPC to `shard` surfaces as
|
||||||
|
/// [`TransportError::PeerUnreachable`]-equivalent at the call site.
|
||||||
|
pub fn remove_peer(&self, shard: ShardId) -> bool {
|
||||||
|
// Enter the embedded runtime for the same reason as `add_peer`: dropping
|
||||||
|
// a tonic channel tears down its background connection task, which is
|
||||||
|
// reactor-aware. A conf-change removal applies from the election thread
|
||||||
|
// (no ambient runtime), so scope the transport's own runtime here.
|
||||||
|
let _guard = self.runtime().enter();
|
||||||
|
self.pool.remove_peer(shard)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `FetchSnapshot` server-stream from `shard` (m11p5 §2): the joiner/
|
||||||
|
/// reseed catch-up path. `from_seqno` is the puller's frontier+1; `term`
|
||||||
|
/// stamps the request for the source's same-term fence. Bypasses the
|
||||||
|
/// circuit breaker for the same reason as [`stream_from`](crate::client::PeerPool::stream_from).
|
||||||
|
///
|
||||||
|
/// The returned stream yields a header chunk first (needed / manifest)
|
||||||
|
/// then file chunks; the caller (stage B node-side install) verifies each
|
||||||
|
/// file's BLAKE3 against the manifest and advances its frontier to the
|
||||||
|
/// snapshot seq before resuming `StreamSegments`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns [`GrpcTransportError`] if the peer is unknown or the stream
|
||||||
|
/// cannot be opened (including `Unimplemented` from a pre-m11p5 peer).
|
||||||
|
pub fn fetch_snapshot(
|
||||||
|
&self,
|
||||||
|
shard: ShardId,
|
||||||
|
from_seqno: u64,
|
||||||
|
term: u64,
|
||||||
|
) -> Result<tonic::Streaming<crate::proto::SnapshotChunk>, GrpcTransportError> {
|
||||||
|
self.runtime()
|
||||||
|
.block_on(self.pool.fetch_snapshot(shard, from_seqno, term))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send a `JoinCluster` request to a known peer (m11p5 §3.3): the
|
||||||
|
/// operator/manual `/cluster/join` forward to the leader once the transport
|
||||||
|
/// exists. Blocks on this transport's runtime; callable from any thread.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns [`GrpcTransportError`] if the peer is unknown or the RPC fails
|
||||||
|
/// (including `Unimplemented` from a pre-m11p5 peer). A non-leader refusal
|
||||||
|
/// is carried IN the response body (`accepted=false`), not as an error.
|
||||||
|
pub fn join_cluster(
|
||||||
|
&self,
|
||||||
|
to: ShardId,
|
||||||
|
request: crate::proto::JoinRequest,
|
||||||
|
) -> Result<crate::proto::JoinResponse, GrpcTransportError> {
|
||||||
|
self.runtime().block_on(self.pool.join_cluster(to, request))
|
||||||
|
}
|
||||||
|
|
||||||
/// The embedded tokio runtime.
|
/// The embedded tokio runtime.
|
||||||
///
|
///
|
||||||
/// # Infallible by construction
|
/// # Infallible by construction
|
||||||
@ -874,6 +1031,10 @@ pub enum ElectionNetEvent {
|
|||||||
prevote: bool,
|
prevote: bool,
|
||||||
term: u64,
|
term: u64,
|
||||||
granted: bool,
|
granted: bool,
|
||||||
|
/// The typed removed signal (m11p5 §3.3): the voter's applied roster
|
||||||
|
/// lists THIS candidate as `Removed`. The driver flips readiness 503 +
|
||||||
|
/// suppresses campaigning, exempt from the reseed marker.
|
||||||
|
removed: bool,
|
||||||
},
|
},
|
||||||
/// The vote RPC failed (unreachable, timeout, or `Unimplemented` from a
|
/// The vote RPC failed (unreachable, timeout, or `Unimplemented` from a
|
||||||
/// pre-m11p4 peer) — counts as not-granted.
|
/// pre-m11p4 peer) — counts as not-granted.
|
||||||
@ -883,6 +1044,10 @@ pub enum ElectionNetEvent {
|
|||||||
from: ShardId,
|
from: ShardId,
|
||||||
term: u64,
|
term: u64,
|
||||||
accepted: bool,
|
accepted: bool,
|
||||||
|
/// The typed removed signal (m11p5 §3.3): the responder's applied
|
||||||
|
/// roster lists THIS node (the heartbeat sender) as `Removed`. The
|
||||||
|
/// driver flips readiness 503 + suppresses campaigning, no reseed.
|
||||||
|
removed: bool,
|
||||||
},
|
},
|
||||||
/// The heartbeat RPC failed — no ack for the check-quorum lease.
|
/// The heartbeat RPC failed — no ack for the check-quorum lease.
|
||||||
HeartbeatUnreachable { from: ShardId },
|
HeartbeatUnreachable { from: ShardId },
|
||||||
@ -938,6 +1103,7 @@ impl ElectionNet {
|
|||||||
prevote,
|
prevote,
|
||||||
term: reply.term,
|
term: reply.term,
|
||||||
granted: reply.granted,
|
granted: reply.granted,
|
||||||
|
removed: reply.removed,
|
||||||
},
|
},
|
||||||
Ok(Err(_)) | Err(_) => ElectionNetEvent::VoteUnreachable {
|
Ok(Err(_)) | Err(_) => ElectionNetEvent::VoteUnreachable {
|
||||||
from: peer,
|
from: peer,
|
||||||
@ -971,6 +1137,7 @@ impl ElectionNet {
|
|||||||
from: peer,
|
from: peer,
|
||||||
term: reply.term,
|
term: reply.term,
|
||||||
accepted: reply.accepted,
|
accepted: reply.accepted,
|
||||||
|
removed: reply.removed,
|
||||||
},
|
},
|
||||||
Ok(Err(_)) | Err(_) => ElectionNetEvent::HeartbeatUnreachable { from: peer },
|
Ok(Err(_)) | Err(_) => ElectionNetEvent::HeartbeatUnreachable { from: peer },
|
||||||
};
|
};
|
||||||
|
|||||||
@ -71,7 +71,8 @@ fn follower_config(listen: SocketAddr, leader: SocketAddr) -> GrpcTransportConfi
|
|||||||
GrpcTransportConfig {
|
GrpcTransportConfig {
|
||||||
local_shard: ShardId(1),
|
local_shard: ShardId(1),
|
||||||
listen_addr: listen,
|
listen_addr: listen,
|
||||||
peers: std::iter::once((ShardId(0), leader)).collect(),
|
// m11p5: `peers` is now a `host:port` string, not a SocketAddr.
|
||||||
|
peers: std::iter::once((ShardId(0), leader.to_string())).collect(),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
// Short enough to keep the test fast; the re-arm-on-skip logic walks
|
// Short enough to keep the test fast; the re-arm-on-skip logic walks
|
||||||
// it past MIN_CATCHUP_INTERVAL's 2s rate limit regardless.
|
// it past MIN_CATCHUP_INTERVAL's 2s rate limit regardless.
|
||||||
@ -106,6 +107,9 @@ fn failed_pull_retries_on_timer_with_no_push() {
|
|||||||
})),
|
})),
|
||||||
applied_sink: Arc::default(),
|
applied_sink: Arc::default(),
|
||||||
election: Arc::default(),
|
election: Arc::default(),
|
||||||
|
snapshots: Arc::default(),
|
||||||
|
snapshot_required: Arc::default(),
|
||||||
|
join: Arc::default(),
|
||||||
};
|
};
|
||||||
let _leader = GrpcTransport::new_with_sources(
|
let _leader = GrpcTransport::new_with_sources(
|
||||||
GrpcTransportConfig {
|
GrpcTransportConfig {
|
||||||
@ -159,6 +163,9 @@ fn clean_completion_does_not_keep_retrying() {
|
|||||||
})),
|
})),
|
||||||
applied_sink: Arc::default(),
|
applied_sink: Arc::default(),
|
||||||
election: Arc::default(),
|
election: Arc::default(),
|
||||||
|
snapshots: Arc::default(),
|
||||||
|
snapshot_required: Arc::default(),
|
||||||
|
join: Arc::default(),
|
||||||
};
|
};
|
||||||
let _leader = GrpcTransport::new_with_sources(
|
let _leader = GrpcTransport::new_with_sources(
|
||||||
GrpcTransportConfig {
|
GrpcTransportConfig {
|
||||||
|
|||||||
@ -24,8 +24,9 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use tidal_net::{
|
use tidal_net::{
|
||||||
ClaimRejection, ElectionHooks, ElectionNetEvent, GrpcTransport, HeartbeatExchange,
|
ClaimRejection, ElectionHooks, ElectionNetEvent, GrpcTransport, HeartbeatExchange, JoinAsk,
|
||||||
config::GrpcTransportConfig, proto, sources::ServingSources,
|
JoinHooks, JoinOutcome, MemberInfo, config::GrpcTransportConfig, proto,
|
||||||
|
sources::ServingSources,
|
||||||
};
|
};
|
||||||
use tidaldb::replication::{
|
use tidaldb::replication::{
|
||||||
VoteReply, VoteRpc, WalSegmentId,
|
VoteReply, VoteRpc, WalSegmentId,
|
||||||
@ -46,7 +47,9 @@ fn make_config(
|
|||||||
GrpcTransportConfig {
|
GrpcTransportConfig {
|
||||||
local_shard: shard,
|
local_shard: shard,
|
||||||
listen_addr: listen,
|
listen_addr: listen,
|
||||||
peers,
|
// m11p5: `peers` is now `host:port` strings; the fixtures hand us
|
||||||
|
// resolved loopback `SocketAddr`s, so stringify at the boundary.
|
||||||
|
peers: peers.into_iter().map(|(s, a)| (s, a.to_string())).collect(),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}
|
}
|
||||||
@ -58,6 +61,9 @@ struct ScriptedHooks {
|
|||||||
term: u64,
|
term: u64,
|
||||||
region: u16,
|
region: u16,
|
||||||
grant_votes: bool,
|
grant_votes: bool,
|
||||||
|
/// Regions this node's roster lists as `Removed` (m11p5 §3.3 typed removed
|
||||||
|
/// signal): a heartbeat/vote from one of these is answered `removed=true`.
|
||||||
|
removed_regions: Vec<u16>,
|
||||||
seen: Mutex<Vec<String>>,
|
seen: Mutex<Vec<String>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,9 +73,19 @@ impl ScriptedHooks {
|
|||||||
term,
|
term,
|
||||||
region,
|
region,
|
||||||
grant_votes,
|
grant_votes,
|
||||||
|
removed_regions: Vec::new(),
|
||||||
seen: Mutex::new(Vec::new()),
|
seen: Mutex::new(Vec::new()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// As [`new`](Self::new), but the named regions are `Removed` in this node's
|
||||||
|
/// roster — every heartbeat/vote from them carries the typed removed signal.
|
||||||
|
fn with_removed(term: u64, region: u16, grant_votes: bool, removed: Vec<u16>) -> Self {
|
||||||
|
Self {
|
||||||
|
removed_regions: removed,
|
||||||
|
..Self::new(term, region, grant_votes)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ElectionHooks for ScriptedHooks {
|
impl ElectionHooks for ScriptedHooks {
|
||||||
@ -138,6 +154,10 @@ impl ElectionHooks for ScriptedHooks {
|
|||||||
fn report_term_acceptable(&self, reporter_term: u64) -> bool {
|
fn report_term_acceptable(&self, reporter_term: u64) -> bool {
|
||||||
reporter_term == self.term
|
reporter_term == self.term
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_removed_member(&self, region: u16) -> bool {
|
||||||
|
self.removed_regions.contains(®ion)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Two transports; node 1 carries scripted hooks, node 0 carries none.
|
/// Two transports; node 1 carries scripted hooks, node 0 carries none.
|
||||||
@ -216,6 +236,7 @@ fn vote_roundtrip_grant_and_refusal_through_hooks() {
|
|||||||
prevote: true,
|
prevote: true,
|
||||||
term: 3,
|
term: 3,
|
||||||
granted: true,
|
granted: true,
|
||||||
|
removed: false,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -229,6 +250,7 @@ fn vote_roundtrip_grant_and_refusal_through_hooks() {
|
|||||||
prevote: false,
|
prevote: false,
|
||||||
term: 3,
|
term: 3,
|
||||||
granted: false,
|
granted: false,
|
||||||
|
removed: false,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -328,6 +350,7 @@ fn heartbeat_exchange_carries_term_and_acceptance() {
|
|||||||
from: ShardId(1),
|
from: ShardId(1),
|
||||||
term: 7,
|
term: 7,
|
||||||
accepted: true,
|
accepted: true,
|
||||||
|
removed: false,
|
||||||
}),
|
}),
|
||||||
"current-term heartbeat accepted: {events:?}"
|
"current-term heartbeat accepted: {events:?}"
|
||||||
);
|
);
|
||||||
@ -336,6 +359,7 @@ fn heartbeat_exchange_carries_term_and_acceptance() {
|
|||||||
from: ShardId(1),
|
from: ShardId(1),
|
||||||
term: 7,
|
term: 7,
|
||||||
accepted: false,
|
accepted: false,
|
||||||
|
removed: false,
|
||||||
}),
|
}),
|
||||||
"stale-term heartbeat refused with the responder term: {events:?}"
|
"stale-term heartbeat refused with the responder term: {events:?}"
|
||||||
);
|
);
|
||||||
@ -347,6 +371,94 @@ fn heartbeat_exchange_carries_term_and_acceptance() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The TYPED REMOVED SIGNAL round-trips over a real socket (m11p5 §3.3): a node
|
||||||
|
/// (region 0) whose region the responder's roster lists as `Removed` gets
|
||||||
|
/// `removed=true` on BOTH a heartbeat reply (keyed on `region_id`) and a vote
|
||||||
|
/// reply (keyed on `candidate_region`) — the out-of-band channel a node that
|
||||||
|
/// missed the `Removed` record uses to learn of its decommission. A peer NOT in
|
||||||
|
/// the removed set gets `removed=false` (proto3 default = compatible).
|
||||||
|
#[test]
|
||||||
|
fn removed_signal_round_trips_on_heartbeat_and_vote() {
|
||||||
|
// Node 1's roster lists region 0 as Removed; node 1 accepts term 4 traffic.
|
||||||
|
let hooks = Arc::new(ScriptedHooks::with_removed(4, 1, true, vec![0]));
|
||||||
|
let (t0, _t1) = build_pair_with_hooks(Arc::clone(&hooks));
|
||||||
|
|
||||||
|
let net = t0.election_net();
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
|
||||||
|
// A heartbeat FROM region 0 (the removed node): the reply carries removed=true.
|
||||||
|
net.fan_heartbeats(
|
||||||
|
&[ShardId(1)],
|
||||||
|
&proto::HeartbeatRequest {
|
||||||
|
shard_id: 0,
|
||||||
|
region_id: 0,
|
||||||
|
term: 4,
|
||||||
|
leader_region: 0,
|
||||||
|
stream_baseline: 0,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&tx,
|
||||||
|
);
|
||||||
|
let events = drain_events(&rx, 1);
|
||||||
|
assert_eq!(
|
||||||
|
events[0],
|
||||||
|
ElectionNetEvent::HeartbeatReply {
|
||||||
|
from: ShardId(1),
|
||||||
|
term: 4,
|
||||||
|
accepted: true,
|
||||||
|
removed: true,
|
||||||
|
},
|
||||||
|
"a heartbeat from a Removed region is answered removed=true: {events:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// A VOTE from candidate region 0 (the removed node): the reply carries
|
||||||
|
// removed=true (a removed node keeps campaigning until a refusal teaches it).
|
||||||
|
net.fan_votes(&[ShardId(1)], vote_request(5, false), &tx);
|
||||||
|
let events = drain_events(&rx, 1);
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
events[0],
|
||||||
|
ElectionNetEvent::VoteReply {
|
||||||
|
from: ShardId(1),
|
||||||
|
removed: true,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
),
|
||||||
|
"a vote from a Removed candidate is answered removed=true: {events:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A heartbeat/vote from a region the responder does NOT list as Removed carries
|
||||||
|
/// `removed=false` (proto3 zero-default — backward-compatible).
|
||||||
|
#[test]
|
||||||
|
fn non_removed_peer_gets_removed_false() {
|
||||||
|
let hooks = Arc::new(ScriptedHooks::with_removed(4, 1, true, vec![9]));
|
||||||
|
let (t0, _t1) = build_pair_with_hooks(Arc::clone(&hooks));
|
||||||
|
|
||||||
|
let net = t0.election_net();
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
net.fan_heartbeats(
|
||||||
|
&[ShardId(1)],
|
||||||
|
&proto::HeartbeatRequest {
|
||||||
|
shard_id: 0,
|
||||||
|
region_id: 0,
|
||||||
|
term: 4,
|
||||||
|
leader_region: 0,
|
||||||
|
stream_baseline: 0,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
&tx,
|
||||||
|
);
|
||||||
|
let events = drain_events(&rx, 1);
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
events[0],
|
||||||
|
ElectionNetEvent::HeartbeatReply { removed: false, .. }
|
||||||
|
),
|
||||||
|
"a heartbeat from a non-Removed region is removed=false: {events:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn timeout_now_reaches_hooks_and_unreachable_peer_reports() {
|
fn timeout_now_reaches_hooks_and_unreachable_peer_reports() {
|
||||||
let hooks = Arc::new(ScriptedHooks::new(5, 1, false));
|
let hooks = Arc::new(ScriptedHooks::new(5, 1, false));
|
||||||
@ -417,3 +529,186 @@ fn stale_term_frontier_report_is_refused() {
|
|||||||
"a stale-term report must not fold into the responder's hint map"
|
"a stale-term report must not fold into the responder's hint map"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── m11p5 §3.3: JoinCluster RPC over a real socket ───────────────────────────
|
||||||
|
|
||||||
|
/// A scriptable join-hooks impl recording every ask and answering a fixed
|
||||||
|
/// outcome (leader-accept or non-leader-refuse).
|
||||||
|
struct ScriptedJoinHooks {
|
||||||
|
outcome: JoinOutcome,
|
||||||
|
seen: Mutex<Vec<JoinAsk>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl JoinHooks for ScriptedJoinHooks {
|
||||||
|
fn join(&self, ask: JoinAsk) -> JoinOutcome {
|
||||||
|
self.seen.lock().unwrap().push(ask);
|
||||||
|
self.outcome.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a single transport (node 1) carrying scripted JOIN hooks, plus a
|
||||||
|
/// hook-less transport (node 0) the joiner dials to see `Unimplemented`.
|
||||||
|
fn build_pair_with_join_hooks(hooks: Arc<ScriptedJoinHooks>) -> (GrpcTransport, GrpcTransport) {
|
||||||
|
let addr0 = free_addr();
|
||||||
|
let addr1 = free_addr();
|
||||||
|
|
||||||
|
let t0 = GrpcTransport::new(make_config(
|
||||||
|
ShardId(0),
|
||||||
|
addr0,
|
||||||
|
HashMap::from([(ShardId(1), addr1)]),
|
||||||
|
))
|
||||||
|
.expect("transport 0");
|
||||||
|
|
||||||
|
let sources = ServingSources::default();
|
||||||
|
sources.set_join_hooks(hooks as Arc<dyn JoinHooks>);
|
||||||
|
let t1 = GrpcTransport::new_with_sources(
|
||||||
|
make_config(ShardId(1), addr1, HashMap::from([(ShardId(0), addr0)])),
|
||||||
|
sources,
|
||||||
|
)
|
||||||
|
.expect("transport 1");
|
||||||
|
|
||||||
|
thread::sleep(Duration::from_millis(100));
|
||||||
|
(t0, t1)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn join_cluster_roundtrips_the_roster_through_hooks() {
|
||||||
|
let outcome = JoinOutcome {
|
||||||
|
accepted: true,
|
||||||
|
refusal_reason: String::new(),
|
||||||
|
assigned_id: 3,
|
||||||
|
term: 7,
|
||||||
|
leader_region: "us-east".into(),
|
||||||
|
leader_grpc_addr: "tidaldb-0.peers.svc:9500".into(),
|
||||||
|
leader_http_addr: "http://tidaldb-0.peers.svc:9501".into(),
|
||||||
|
members: vec![
|
||||||
|
MemberInfo {
|
||||||
|
id: 0,
|
||||||
|
name: "us-east".into(),
|
||||||
|
grpc_addr: "tidaldb-0.peers.svc:9500".into(),
|
||||||
|
http_addr: "http://tidaldb-0.peers.svc:9501".into(),
|
||||||
|
role: 0, // Voter
|
||||||
|
},
|
||||||
|
MemberInfo {
|
||||||
|
id: 3,
|
||||||
|
name: "joiner".into(),
|
||||||
|
grpc_addr: "tidaldb-3.peers.svc:9500".into(),
|
||||||
|
http_addr: "http://tidaldb-3.peers.svc:9501".into(),
|
||||||
|
role: 1, // Learner
|
||||||
|
},
|
||||||
|
],
|
||||||
|
membership_version: 4,
|
||||||
|
};
|
||||||
|
let hooks = Arc::new(ScriptedJoinHooks {
|
||||||
|
outcome,
|
||||||
|
seen: Mutex::new(Vec::new()),
|
||||||
|
});
|
||||||
|
// Node 0 dials node 1 (the leader carrying the join hooks).
|
||||||
|
let (t0, _t1) = build_pair_with_join_hooks(Arc::clone(&hooks));
|
||||||
|
|
||||||
|
let resp = t0
|
||||||
|
.join_cluster(
|
||||||
|
ShardId(1),
|
||||||
|
proto::JoinRequest {
|
||||||
|
name: "joiner".into(),
|
||||||
|
grpc_addr: "tidaldb-3.peers.svc:9500".into(),
|
||||||
|
http_addr: "http://tidaldb-3.peers.svc:9501".into(),
|
||||||
|
capabilities: tidal_net::CAP_KIND4_MEMBERSHIP,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("join RPC reached the leader hooks");
|
||||||
|
|
||||||
|
assert!(resp.accepted);
|
||||||
|
assert_eq!(resp.assigned_id, 3);
|
||||||
|
assert_eq!(resp.term, 7);
|
||||||
|
assert_eq!(resp.membership_version, 4);
|
||||||
|
assert_eq!(resp.leader_region, "us-east");
|
||||||
|
assert_eq!(resp.members.len(), 2);
|
||||||
|
assert_eq!(resp.members[1].name, "joiner");
|
||||||
|
assert_eq!(resp.members[1].role, 1, "the joiner came back a Learner");
|
||||||
|
|
||||||
|
// The ask reached the hooks verbatim, capabilities and all.
|
||||||
|
let seen = hooks.seen.lock().unwrap();
|
||||||
|
assert_eq!(seen.len(), 1);
|
||||||
|
assert_eq!(seen[0].name, "joiner");
|
||||||
|
assert_eq!(seen[0].capabilities, tidal_net::CAP_KIND4_MEMBERSHIP);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn join_cluster_non_leader_refusal_is_a_response_not_an_error() {
|
||||||
|
// A non-leader seed answers accepted=false WITH a leader hint — a
|
||||||
|
// successful RPC the joiner re-targets, never a transport error.
|
||||||
|
let outcome = JoinOutcome {
|
||||||
|
accepted: false,
|
||||||
|
refusal_reason: "not the leader; re-target the hint".into(),
|
||||||
|
assigned_id: 0,
|
||||||
|
term: 9,
|
||||||
|
leader_region: "eu-west".into(),
|
||||||
|
leader_grpc_addr: "tidaldb-1.peers.svc:9500".into(),
|
||||||
|
leader_http_addr: "http://tidaldb-1.peers.svc:9501".into(),
|
||||||
|
members: Vec::new(),
|
||||||
|
membership_version: 0,
|
||||||
|
};
|
||||||
|
let hooks = Arc::new(ScriptedJoinHooks {
|
||||||
|
outcome,
|
||||||
|
seen: Mutex::new(Vec::new()),
|
||||||
|
});
|
||||||
|
let (t0, _t1) = build_pair_with_join_hooks(Arc::clone(&hooks));
|
||||||
|
|
||||||
|
let resp = t0
|
||||||
|
.join_cluster(
|
||||||
|
ShardId(1),
|
||||||
|
proto::JoinRequest {
|
||||||
|
name: "joiner".into(),
|
||||||
|
grpc_addr: "j:9500".into(),
|
||||||
|
http_addr: "http://j:9501".into(),
|
||||||
|
capabilities: tidal_net::CAP_KIND4_MEMBERSHIP,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("a non-leader refusal is still a successful RPC");
|
||||||
|
assert!(!resp.accepted);
|
||||||
|
assert_eq!(resp.leader_region, "eu-west");
|
||||||
|
assert_eq!(
|
||||||
|
resp.leader_grpc_addr, "tidaldb-1.peers.svc:9500",
|
||||||
|
"the joiner re-targets the hinted leader"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn join_cluster_without_hooks_is_unimplemented() {
|
||||||
|
// Node 0 has no join hooks (a pre-m11p5 binary, or a bare transport): the
|
||||||
|
// RPC answers Unimplemented and the joiner retries the next seed (§3.7).
|
||||||
|
let outcome = JoinOutcome {
|
||||||
|
accepted: true,
|
||||||
|
refusal_reason: String::new(),
|
||||||
|
assigned_id: 1,
|
||||||
|
term: 1,
|
||||||
|
leader_region: "x".into(),
|
||||||
|
leader_grpc_addr: "x:1".into(),
|
||||||
|
leader_http_addr: "http://x:2".into(),
|
||||||
|
members: Vec::new(),
|
||||||
|
membership_version: 1,
|
||||||
|
};
|
||||||
|
let hooks = Arc::new(ScriptedJoinHooks {
|
||||||
|
outcome,
|
||||||
|
seen: Mutex::new(Vec::new()),
|
||||||
|
});
|
||||||
|
// node 1 carries hooks; node 0 does NOT. Dial node 0 from node 1.
|
||||||
|
let (_t0, t1) = build_pair_with_join_hooks(Arc::clone(&hooks));
|
||||||
|
let err = t1
|
||||||
|
.join_cluster(
|
||||||
|
ShardId(0),
|
||||||
|
proto::JoinRequest {
|
||||||
|
name: "joiner".into(),
|
||||||
|
grpc_addr: "j:9500".into(),
|
||||||
|
http_addr: "http://j:9501".into(),
|
||||||
|
capabilities: 0,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect_err("a hook-less node answers Unimplemented");
|
||||||
|
let msg = format!("{err:?}");
|
||||||
|
assert!(
|
||||||
|
msg.contains("Unimplemented") || msg.to_lowercase().contains("unimplemented"),
|
||||||
|
"pre-m11p5 join is Unimplemented, never a crash: {msg}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@ -36,7 +36,9 @@ fn make_config(
|
|||||||
GrpcTransportConfig {
|
GrpcTransportConfig {
|
||||||
local_shard: shard,
|
local_shard: shard,
|
||||||
listen_addr: listen,
|
listen_addr: listen,
|
||||||
peers,
|
// m11p5: `peers` is now `host:port` strings; the test fixtures hand us
|
||||||
|
// resolved loopback `SocketAddr`s, so stringify at the boundary.
|
||||||
|
peers: peers.into_iter().map(|(s, a)| (s, a.to_string())).collect(),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -140,7 +140,7 @@ fn untrusted_client_cert_is_rejected() {
|
|||||||
|
|
||||||
// Client (shard 0) presents a cert signed by a rogue CA.
|
// Client (shard 0) presents a cert signed by a rogue CA.
|
||||||
let client_cfg = GrpcTransportConfig {
|
let client_cfg = GrpcTransportConfig {
|
||||||
peers: HashMap::from([(ShardId(1), addr_server)]),
|
peers: HashMap::from([(ShardId(1), addr_server.to_string())]),
|
||||||
..server_config(ShardId(0), addr_client, rogue)
|
..server_config(ShardId(0), addr_client, rogue)
|
||||||
};
|
};
|
||||||
let client = GrpcTransport::new(client_cfg).expect("client with rogue cert");
|
let client = GrpcTransport::new(client_cfg).expect("client with rogue cert");
|
||||||
@ -199,7 +199,7 @@ fn absent_client_cert_is_rejected() {
|
|||||||
client_key: None,
|
client_key: None,
|
||||||
};
|
};
|
||||||
let client_cfg = GrpcTransportConfig {
|
let client_cfg = GrpcTransportConfig {
|
||||||
peers: HashMap::from([(ShardId(1), addr_server)]),
|
peers: HashMap::from([(ShardId(1), addr_server.to_string())]),
|
||||||
..server_config(ShardId(0), addr_client, no_client_id)
|
..server_config(ShardId(0), addr_client, no_client_id)
|
||||||
};
|
};
|
||||||
let client = GrpcTransport::new(client_cfg).expect("client without identity");
|
let client = GrpcTransport::new(client_cfg).expect("client without identity");
|
||||||
@ -243,7 +243,7 @@ fn mtls_send_and_receive() {
|
|||||||
let config0 = GrpcTransportConfig {
|
let config0 = GrpcTransportConfig {
|
||||||
local_shard: ShardId(0),
|
local_shard: ShardId(0),
|
||||||
listen_addr: addr0,
|
listen_addr: addr0,
|
||||||
peers: HashMap::from([(ShardId(1), addr1)]),
|
peers: HashMap::from([(ShardId(1), addr1.to_string())]),
|
||||||
tls: Some(tls.clone()),
|
tls: Some(tls.clone()),
|
||||||
insecure: false,
|
insecure: false,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@ -252,7 +252,7 @@ fn mtls_send_and_receive() {
|
|||||||
let config1 = GrpcTransportConfig {
|
let config1 = GrpcTransportConfig {
|
||||||
local_shard: ShardId(1),
|
local_shard: ShardId(1),
|
||||||
listen_addr: addr1,
|
listen_addr: addr1,
|
||||||
peers: HashMap::from([(ShardId(0), addr0)]),
|
peers: HashMap::from([(ShardId(0), addr0.to_string())]),
|
||||||
tls: Some(tls),
|
tls: Some(tls),
|
||||||
insecure: false,
|
insecure: false,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
|
|||||||
@ -98,7 +98,7 @@ fn build_pair() -> (GrpcNode, GrpcNode, HashMap<String, u8>) {
|
|||||||
let t0 = GrpcTransport::new(GrpcTransportConfig {
|
let t0 = GrpcTransport::new(GrpcTransportConfig {
|
||||||
local_shard: ShardId(0),
|
local_shard: ShardId(0),
|
||||||
listen_addr: addr0,
|
listen_addr: addr0,
|
||||||
peers: HashMap::from([(ShardId(1), addr1)]),
|
peers: HashMap::from([(ShardId(1), addr1.to_string())]),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
})
|
||||||
@ -107,7 +107,7 @@ fn build_pair() -> (GrpcNode, GrpcNode, HashMap<String, u8>) {
|
|||||||
let t1 = GrpcTransport::new(GrpcTransportConfig {
|
let t1 = GrpcTransport::new(GrpcTransportConfig {
|
||||||
local_shard: ShardId(1),
|
local_shard: ShardId(1),
|
||||||
listen_addr: addr1,
|
listen_addr: addr1,
|
||||||
peers: HashMap::from([(ShardId(0), addr0)]),
|
peers: HashMap::from([(ShardId(0), addr0.to_string())]),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
})
|
||||||
@ -385,7 +385,8 @@ fn uat_step5_three_node_replication() {
|
|||||||
let mut peers = HashMap::new();
|
let mut peers = HashMap::new();
|
||||||
for j in 0..3u16 {
|
for j in 0..3u16 {
|
||||||
if i != j {
|
if i != j {
|
||||||
peers.insert(ShardId(j), addrs[j as usize]);
|
// m11p5: `peers` holds `host:port` strings, not SocketAddrs.
|
||||||
|
peers.insert(ShardId(j), addrs[j as usize].to_string());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
GrpcTransport::new(GrpcTransportConfig {
|
GrpcTransport::new(GrpcTransportConfig {
|
||||||
|
|||||||
@ -30,7 +30,9 @@ fn make_config(
|
|||||||
GrpcTransportConfig {
|
GrpcTransportConfig {
|
||||||
local_shard: shard,
|
local_shard: shard,
|
||||||
listen_addr: listen,
|
listen_addr: listen,
|
||||||
peers,
|
// m11p5: `peers` is now `host:port` strings; the fixtures hand us
|
||||||
|
// resolved loopback `SocketAddr`s, so stringify at the boundary.
|
||||||
|
peers: peers.into_iter().map(|(s, a)| (s, a.to_string())).collect(),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
// Shorter circuit breaker for testing.
|
// Shorter circuit breaker for testing.
|
||||||
circuit_breaker_threshold: 3,
|
circuit_breaker_threshold: 3,
|
||||||
|
|||||||
537
tidal-net/tests/snapshot_fetch.rs
Normal file
537
tidal-net/tests/snapshot_fetch.rs
Normal file
@ -0,0 +1,537 @@
|
|||||||
|
//! m11p5 §2: `FetchSnapshot` over real sockets.
|
||||||
|
//!
|
||||||
|
//! A joiner (or a node behind a compacted leader) installs a staged snapshot
|
||||||
|
//! artifact before resuming the catch-up stream. These tests drive the REAL
|
||||||
|
//! `GrpcTransport` over real sockets with a fake [`SnapshotSource`] serving a
|
||||||
|
//! staged tempdir, and assert the wire contract end to end:
|
||||||
|
//!
|
||||||
|
//! - the manifest's BLAKE3 + sizes match the bytes the client receives, and
|
||||||
|
//! the reassembled files are byte-identical;
|
||||||
|
//! - `needed=false` emits a header and NO file chunks;
|
||||||
|
//! - `Busy` maps to a RETRYABLE `UNAVAILABLE` (never `FAILED_PRECONDITION`,
|
||||||
|
//! which would mis-route a joiner into the reseed class);
|
||||||
|
//! - the same-term term fence refuses a stale/newer puller;
|
||||||
|
//! - a `snapshot-required` catch-up trailer surfaces through the transport to
|
||||||
|
//! the late-bound [`SnapshotRequiredSink`] (the seam the node latches its
|
||||||
|
//! reseed marker on in stage B), while the standing retry timer keeps firing.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used)] // test assertions on known-good fixtures
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
net::SocketAddr,
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{
|
||||||
|
Arc, Mutex,
|
||||||
|
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||||
|
},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
use tidal_net::{
|
||||||
|
GrpcTransport, GrpcTransportConfig,
|
||||||
|
client::fetch_snapshot_standalone,
|
||||||
|
proto::snapshot_chunk::Chunk,
|
||||||
|
sources::{
|
||||||
|
SegmentChunk, SegmentReadError, SegmentSource, ServingSources, SnapshotRequiredSink,
|
||||||
|
SnapshotSource, SnapshotStageError, SnapshotStaging,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use tidaldb::replication::{shard::ShardId, transport::Transport};
|
||||||
|
|
||||||
|
/// Bind port 0 to obtain a free, OS-assigned address (tonic cannot bind 0
|
||||||
|
/// directly, so we resolve a concrete port up front).
|
||||||
|
fn free_addr() -> SocketAddr {
|
||||||
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||||
|
listener.local_addr().expect("local_addr")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A staged snapshot artifact: a tempdir holding `files` (relative path ->
|
||||||
|
/// bytes), with the manifest's BLAKE3/size computed from the bytes on disk.
|
||||||
|
struct StagedDir {
|
||||||
|
_dir: tempfile::TempDir,
|
||||||
|
root: PathBuf,
|
||||||
|
manifest: Vec<(String, u64, [u8; 32])>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StagedDir {
|
||||||
|
fn new(files: &[(&str, &[u8])]) -> Self {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let root = dir.path().to_path_buf();
|
||||||
|
let mut manifest = Vec::new();
|
||||||
|
for (rel, bytes) in files {
|
||||||
|
let abs = root.join(rel);
|
||||||
|
if let Some(parent) = abs.parent() {
|
||||||
|
std::fs::create_dir_all(parent).expect("mkdir");
|
||||||
|
}
|
||||||
|
std::fs::write(&abs, bytes).expect("write file");
|
||||||
|
let hash = blake3::hash(bytes);
|
||||||
|
manifest.push(((*rel).to_string(), bytes.len() as u64, *hash.as_bytes()));
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
_dir: dir,
|
||||||
|
root,
|
||||||
|
manifest,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `SnapshotSource` serving a fixed [`StagedDir`] with a recorded
|
||||||
|
/// release-count (so a test can assert the per-consumer pin grace is signaled
|
||||||
|
/// exactly once). `needed` toggles the no-snapshot-needed path.
|
||||||
|
struct FakeSnapshots {
|
||||||
|
staged: Arc<StagedDir>,
|
||||||
|
needed: bool,
|
||||||
|
snapshot_seq: u64,
|
||||||
|
releases: Arc<AtomicU64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SnapshotSource for FakeSnapshots {
|
||||||
|
fn stage(&self, _from_seqno: u64) -> Result<SnapshotStaging, SnapshotStageError> {
|
||||||
|
Ok(SnapshotStaging {
|
||||||
|
needed: self.needed,
|
||||||
|
snapshot_seq: self.snapshot_seq,
|
||||||
|
root: self.staged.root.clone(),
|
||||||
|
files: if self.needed {
|
||||||
|
self.staged.manifest.clone()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn release(&self) {
|
||||||
|
self.releases.fetch_add(1, Ordering::AcqRel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `SnapshotSource` that is always `Busy` — exercises the retryable
|
||||||
|
/// `UNAVAILABLE` mapping.
|
||||||
|
struct BusySnapshots;
|
||||||
|
impl SnapshotSource for BusySnapshots {
|
||||||
|
fn stage(&self, _from_seqno: u64) -> Result<SnapshotStaging, SnapshotStageError> {
|
||||||
|
Err(SnapshotStageError::Busy)
|
||||||
|
}
|
||||||
|
fn release(&self) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn leader_with_snapshots(listen: SocketAddr, source: Arc<dyn SnapshotSource>) -> GrpcTransport {
|
||||||
|
let sources = ServingSources::default();
|
||||||
|
sources.set_snapshot_source(source);
|
||||||
|
GrpcTransport::new_with_sources(
|
||||||
|
GrpcTransportConfig {
|
||||||
|
local_shard: ShardId(0),
|
||||||
|
listen_addr: listen,
|
||||||
|
insecure: true,
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
},
|
||||||
|
sources,
|
||||||
|
)
|
||||||
|
.expect("leader transport")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drain a `FetchSnapshot` stream into `(header, reassembled files)`.
|
||||||
|
async fn drain_snapshot(
|
||||||
|
mut stream: tonic::Streaming<tidal_net::proto::SnapshotChunk>,
|
||||||
|
) -> (tidal_net::proto::SnapshotHeader, HashMap<String, Vec<u8>>) {
|
||||||
|
let mut header = None;
|
||||||
|
let mut files: HashMap<String, Vec<u8>> = HashMap::new();
|
||||||
|
while let Some(msg) = stream.message().await.expect("stream chunk") {
|
||||||
|
match msg.chunk.expect("chunk variant") {
|
||||||
|
Chunk::Header(h) => header = Some(h),
|
||||||
|
Chunk::File(f) => {
|
||||||
|
let buf = files.entry(f.path.clone()).or_default();
|
||||||
|
assert_eq!(
|
||||||
|
f.offset as usize,
|
||||||
|
buf.len(),
|
||||||
|
"file chunks must arrive in contiguous offset order"
|
||||||
|
);
|
||||||
|
buf.extend_from_slice(&f.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(header.expect("a header chunk must arrive first"), files)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The happy path: a 2-file artifact streams; the manifest BLAKE3 + sizes
|
||||||
|
/// match the received bytes exactly; the reassembled files are byte-identical;
|
||||||
|
/// and the per-consumer pin is released once on stream end.
|
||||||
|
#[test]
|
||||||
|
#[allow(clippy::significant_drop_tightening)] // transports intentionally live to test end
|
||||||
|
fn fetch_snapshot_streams_verified_files() {
|
||||||
|
let file_a: &[u8] = b"the quick brown fox jumps over the lazy dog";
|
||||||
|
let file_b: Vec<u8> = (0u8..=255).cycle().take(3_000_000).collect(); // > 1 MiB: multi-chunk
|
||||||
|
let staged = Arc::new(StagedDir::new(&[
|
||||||
|
("ledger/000001.sst", file_a),
|
||||||
|
("wal/seg-0001.seg", &file_b),
|
||||||
|
]));
|
||||||
|
let releases = Arc::new(AtomicU64::new(0));
|
||||||
|
let leader_addr = free_addr();
|
||||||
|
let _leader = leader_with_snapshots(
|
||||||
|
leader_addr,
|
||||||
|
Arc::new(FakeSnapshots {
|
||||||
|
staged: Arc::clone(&staged),
|
||||||
|
needed: true,
|
||||||
|
snapshot_seq: 4096,
|
||||||
|
releases: Arc::clone(&releases),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
runtime.block_on(async {
|
||||||
|
let stream = fetch_snapshot_standalone(&leader_addr.to_string(), None, ShardId(0), 1, 0)
|
||||||
|
.await
|
||||||
|
.expect("fetch opens");
|
||||||
|
let (header, files) = drain_snapshot(stream).await;
|
||||||
|
|
||||||
|
assert!(header.needed, "a staged artifact reports needed=true");
|
||||||
|
assert_eq!(header.snapshot_seq, 4096);
|
||||||
|
assert_eq!(header.files.len(), 2, "the manifest lists both files");
|
||||||
|
|
||||||
|
// Every manifest entry's size + BLAKE3 matches the received bytes.
|
||||||
|
for entry in &header.files {
|
||||||
|
let bytes = files
|
||||||
|
.get(&entry.path)
|
||||||
|
.unwrap_or_else(|| panic!("file {} streamed", entry.path));
|
||||||
|
assert_eq!(
|
||||||
|
bytes.len() as u64,
|
||||||
|
entry.size,
|
||||||
|
"received byte count must match the manifest size for {}",
|
||||||
|
entry.path
|
||||||
|
);
|
||||||
|
let hash = blake3::hash(bytes);
|
||||||
|
assert_eq!(
|
||||||
|
hash.as_bytes().as_slice(),
|
||||||
|
entry.blake3.as_slice(),
|
||||||
|
"received BLAKE3 must match the manifest hash for {}",
|
||||||
|
entry.path
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Byte equality against the original sources.
|
||||||
|
assert_eq!(files.get("ledger/000001.sst").unwrap().as_slice(), file_a);
|
||||||
|
assert_eq!(files.get("wal/seg-0001.seg").unwrap().as_slice(), &file_b);
|
||||||
|
});
|
||||||
|
|
||||||
|
// The per-consumer pin (§2.1) is released exactly once when the stream
|
||||||
|
// ends. Allow a moment for the server task's guard to drop after the
|
||||||
|
// client finished draining.
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(5);
|
||||||
|
while releases.load(Ordering::Acquire) == 0 && Instant::now() < deadline {
|
||||||
|
std::thread::sleep(Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
releases.load(Ordering::Acquire),
|
||||||
|
1,
|
||||||
|
"the staging pin must be released exactly once on stream end"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `needed=false`: the live WAL still serves the puller. The header says so and
|
||||||
|
/// NO file chunks follow; the no-pin staging is not released.
|
||||||
|
#[test]
|
||||||
|
#[allow(clippy::significant_drop_tightening)]
|
||||||
|
fn fetch_snapshot_not_needed_emits_header_only() {
|
||||||
|
let staged = Arc::new(StagedDir::new(&[("ignored", b"unused")]));
|
||||||
|
let releases = Arc::new(AtomicU64::new(0));
|
||||||
|
let leader_addr = free_addr();
|
||||||
|
let _leader = leader_with_snapshots(
|
||||||
|
leader_addr,
|
||||||
|
Arc::new(FakeSnapshots {
|
||||||
|
staged,
|
||||||
|
needed: false,
|
||||||
|
snapshot_seq: 0,
|
||||||
|
releases: Arc::clone(&releases),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
runtime.block_on(async {
|
||||||
|
let stream = fetch_snapshot_standalone(&leader_addr.to_string(), None, ShardId(0), 1, 0)
|
||||||
|
.await
|
||||||
|
.expect("fetch opens");
|
||||||
|
let (header, files) = drain_snapshot(stream).await;
|
||||||
|
assert!(!header.needed, "the WAL can still serve: needed=false");
|
||||||
|
assert!(
|
||||||
|
header.files.is_empty(),
|
||||||
|
"no manifest on the needed=false path"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
files.is_empty(),
|
||||||
|
"no file chunks follow a needed=false header"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
// A needed=false staging holds no pin, so release is never called.
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
assert_eq!(
|
||||||
|
releases.load(Ordering::Acquire),
|
||||||
|
0,
|
||||||
|
"a needed=false staging must not release a pin it never took"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Busy` staging maps to a RETRYABLE `UNAVAILABLE` — never
|
||||||
|
/// `FAILED_PRECONDITION` (which would mis-route a joiner into the reseed
|
||||||
|
/// class, §2).
|
||||||
|
#[test]
|
||||||
|
#[allow(clippy::significant_drop_tightening)]
|
||||||
|
fn fetch_snapshot_busy_is_unavailable() {
|
||||||
|
let leader_addr = free_addr();
|
||||||
|
let _leader = leader_with_snapshots(leader_addr, Arc::new(BusySnapshots));
|
||||||
|
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
runtime.block_on(async {
|
||||||
|
// The open-time refusal surfaces as a Grpc status. `let-else` on the
|
||||||
|
// Result directly (Streaming is not Debug, so `expect_err` is out).
|
||||||
|
let Err(tidal_net::GrpcTransportError::Grpc(status)) =
|
||||||
|
fetch_snapshot_standalone(&leader_addr.to_string(), None, ShardId(0), 1, 0).await
|
||||||
|
else {
|
||||||
|
panic!("Busy must surface a gRPC status (retryable open refusal)");
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
status.code(),
|
||||||
|
tonic::Code::Unavailable,
|
||||||
|
"Busy is retryable UNAVAILABLE, not FAILED_PRECONDITION"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// No snapshot source wired (a pre-m11p5 peer, §3.7): the RPC answers
|
||||||
|
/// `Unimplemented` so the joiner reports it loudly and retries the next seed.
|
||||||
|
#[test]
|
||||||
|
#[allow(clippy::significant_drop_tightening)]
|
||||||
|
fn fetch_snapshot_unimplemented_without_source() {
|
||||||
|
let leader_addr = free_addr();
|
||||||
|
let _leader = GrpcTransport::new(GrpcTransportConfig {
|
||||||
|
local_shard: ShardId(0),
|
||||||
|
listen_addr: leader_addr,
|
||||||
|
insecure: true,
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
})
|
||||||
|
.expect("leader transport");
|
||||||
|
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
runtime.block_on(async {
|
||||||
|
let Err(tidal_net::GrpcTransportError::Grpc(status)) =
|
||||||
|
fetch_snapshot_standalone(&leader_addr.to_string(), None, ShardId(0), 1, 0).await
|
||||||
|
else {
|
||||||
|
panic!("a node with no snapshot source must refuse with a gRPC status");
|
||||||
|
};
|
||||||
|
assert_eq!(status.code(), tonic::Code::Unimplemented);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same-term term fence (§2): a leader at term 5 refuses a puller stamping
|
||||||
|
/// term 3 with a `rejoin` typed trailer (rejoin the current term, not reseed).
|
||||||
|
#[test]
|
||||||
|
#[allow(clippy::significant_drop_tightening)]
|
||||||
|
fn fetch_snapshot_term_fence_refuses_stale_puller() {
|
||||||
|
// An election-hooks stub claiming a fixed term.
|
||||||
|
struct FixedTerm(u64);
|
||||||
|
impl tidal_net::ElectionHooks for FixedTerm {
|
||||||
|
fn self_claim(&self) -> (u64, u16) {
|
||||||
|
(self.0, 0)
|
||||||
|
}
|
||||||
|
fn observe_leader_claim(
|
||||||
|
&self,
|
||||||
|
_term: u64,
|
||||||
|
_leader_region: u16,
|
||||||
|
_first_seq: u64,
|
||||||
|
) -> Result<(), tidal_net::ClaimRejection> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn on_heartbeat(
|
||||||
|
&self,
|
||||||
|
_term: u64,
|
||||||
|
_leader_region: u16,
|
||||||
|
_stream_baseline: u64,
|
||||||
|
_prev_log: tidaldb::replication::LogPosition,
|
||||||
|
) -> tidal_net::HeartbeatExchange {
|
||||||
|
tidal_net::HeartbeatExchange {
|
||||||
|
term: self.0,
|
||||||
|
accepted: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn on_vote(&self, _rpc: tidaldb::replication::VoteRpc) -> tidaldb::replication::VoteReply {
|
||||||
|
tidaldb::replication::VoteReply {
|
||||||
|
term: self.0,
|
||||||
|
granted: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn on_timeout_now(&self, _term: u64, _leader_region: u16) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
fn on_observed_term(&self, _term: u64) {}
|
||||||
|
fn report_term_acceptable(&self, reporter_term: u64) -> bool {
|
||||||
|
reporter_term == self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let staged = Arc::new(StagedDir::new(&[("f", b"x")]));
|
||||||
|
let leader_addr = free_addr();
|
||||||
|
let sources = ServingSources::default();
|
||||||
|
sources.set_snapshot_source(Arc::new(FakeSnapshots {
|
||||||
|
staged,
|
||||||
|
needed: true,
|
||||||
|
snapshot_seq: 1,
|
||||||
|
releases: Arc::new(AtomicU64::new(0)),
|
||||||
|
}));
|
||||||
|
sources.set_election_hooks(Arc::new(FixedTerm(5)));
|
||||||
|
let _leader = GrpcTransport::new_with_sources(
|
||||||
|
GrpcTransportConfig {
|
||||||
|
local_shard: ShardId(0),
|
||||||
|
listen_addr: leader_addr,
|
||||||
|
insecure: true,
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
},
|
||||||
|
sources,
|
||||||
|
)
|
||||||
|
.expect("leader transport");
|
||||||
|
|
||||||
|
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
runtime.block_on(async {
|
||||||
|
// Puller stamps term 3, below the source's 5.
|
||||||
|
let Err(tidal_net::GrpcTransportError::Grpc(status)) =
|
||||||
|
fetch_snapshot_standalone(&leader_addr.to_string(), None, ShardId(0), 1, 3).await
|
||||||
|
else {
|
||||||
|
panic!("a stale-term puller must be refused with a gRPC status");
|
||||||
|
};
|
||||||
|
assert_eq!(status.code(), tonic::Code::FailedPrecondition);
|
||||||
|
assert_eq!(
|
||||||
|
status
|
||||||
|
.metadata()
|
||||||
|
.get("x-tidal-catchup")
|
||||||
|
.map(|v| v.as_bytes().to_vec()),
|
||||||
|
Some(b"rejoin".to_vec()),
|
||||||
|
"a stale puller gets the `rejoin` typed trailer, never reseed"
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Typed catch-up refusal → snapshot-required sink (§2.4) ──────────────────
|
||||||
|
|
||||||
|
/// A leader-side `SegmentSource` that always answers `Unavailable` — the
|
||||||
|
/// server maps this to `FAILED_PRECONDITION` + the `snapshot-required` trailer.
|
||||||
|
struct UnservableSegments;
|
||||||
|
impl SegmentSource for UnservableSegments {
|
||||||
|
fn source_shard(&self) -> ShardId {
|
||||||
|
ShardId(0)
|
||||||
|
}
|
||||||
|
fn stream_baseline(&self) -> u64 {
|
||||||
|
0
|
||||||
|
}
|
||||||
|
fn flushed_seq(&self) -> u64 {
|
||||||
|
100
|
||||||
|
}
|
||||||
|
fn collect_from(
|
||||||
|
&self,
|
||||||
|
_from_seq: u64,
|
||||||
|
_max_events: u64,
|
||||||
|
_max_bytes: usize,
|
||||||
|
) -> Result<Vec<SegmentChunk>, SegmentReadError> {
|
||||||
|
Err(SegmentReadError::Unavailable {
|
||||||
|
detail: "WAL segment format unknown".into(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A scripted `SnapshotRequiredSink` recording whether it was invoked.
|
||||||
|
struct ScriptedSink {
|
||||||
|
fired: Arc<AtomicBool>,
|
||||||
|
shard: Arc<Mutex<Option<ShardId>>>,
|
||||||
|
}
|
||||||
|
impl SnapshotRequiredSink for ScriptedSink {
|
||||||
|
fn snapshot_required(&self, shard: ShardId, _from_seqno: u64) {
|
||||||
|
*self.shard.lock().unwrap() = Some(shard);
|
||||||
|
self.fired.store(true, Ordering::Release);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn follower_config(listen: SocketAddr, leader: SocketAddr) -> GrpcTransportConfig {
|
||||||
|
GrpcTransportConfig {
|
||||||
|
local_shard: ShardId(1),
|
||||||
|
listen_addr: listen,
|
||||||
|
peers: std::iter::once((ShardId(0), leader.to_string())).collect(),
|
||||||
|
insecure: true,
|
||||||
|
catchup_retry_interval: Duration::from_millis(300),
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The seam stage B latches its reseed marker on: a `StreamSegments` pull that
|
||||||
|
/// is refused `snapshot-required` surfaces through the transport to the
|
||||||
|
/// late-bound [`SnapshotRequiredSink`]. The standing retry timer keeps firing
|
||||||
|
/// regardless (the m11p4 re-arm-on-skip liveness fix must never be removed),
|
||||||
|
/// which is exactly why the sink can be invoked more than once — we assert it
|
||||||
|
/// fires AT LEAST once and carries the right shard.
|
||||||
|
#[test]
|
||||||
|
#[allow(clippy::significant_drop_tightening)] // transports intentionally live to test end
|
||||||
|
fn snapshot_required_trailer_surfaces_to_the_sink() {
|
||||||
|
let leader_addr = free_addr();
|
||||||
|
// The leader's segment source always answers Unavailable → the server maps
|
||||||
|
// it to FAILED_PRECONDITION + the `snapshot-required` trailer.
|
||||||
|
let leader_sources = ServingSources {
|
||||||
|
segments: Some(Arc::new(UnservableSegments)),
|
||||||
|
..ServingSources::default()
|
||||||
|
};
|
||||||
|
let _leader = GrpcTransport::new_with_sources(
|
||||||
|
GrpcTransportConfig {
|
||||||
|
local_shard: ShardId(0),
|
||||||
|
listen_addr: leader_addr,
|
||||||
|
insecure: true,
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
},
|
||||||
|
leader_sources,
|
||||||
|
)
|
||||||
|
.expect("leader transport");
|
||||||
|
|
||||||
|
// The follower wires its snapshot-required sink BEFORE constructing the
|
||||||
|
// transport (the cell is shared with the catch-up runner). Cloning the
|
||||||
|
// ServingSources shares the same OnceLock cells, so setting on the clone
|
||||||
|
// is visible to the runner.
|
||||||
|
let fired = Arc::new(AtomicBool::new(false));
|
||||||
|
let seen_shard = Arc::new(Mutex::new(None));
|
||||||
|
let follower_sources = ServingSources::default();
|
||||||
|
follower_sources.set_snapshot_required_sink(Arc::new(ScriptedSink {
|
||||||
|
fired: Arc::clone(&fired),
|
||||||
|
shard: Arc::clone(&seen_shard),
|
||||||
|
}));
|
||||||
|
let follower = GrpcTransport::new_with_sources(
|
||||||
|
follower_config(free_addr(), leader_addr),
|
||||||
|
follower_sources,
|
||||||
|
)
|
||||||
|
.expect("follower transport");
|
||||||
|
|
||||||
|
// Trigger a catch-up pull: the leader refuses snapshot-required, the
|
||||||
|
// transport reads the trailer and invokes the sink.
|
||||||
|
follower.request_catchup(ShardId(0), 1);
|
||||||
|
|
||||||
|
let deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
while !fired.load(Ordering::Acquire) {
|
||||||
|
assert!(
|
||||||
|
Instant::now() < deadline,
|
||||||
|
"the snapshot-required trailer never reached the sink: a follower \
|
||||||
|
behind a compacted leader would never latch its reseed marker"
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(25));
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
*seen_shard.lock().unwrap(),
|
||||||
|
Some(ShardId(0)),
|
||||||
|
"the sink learns which source shard demanded a snapshot"
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -39,7 +39,9 @@ fn make_config(
|
|||||||
GrpcTransportConfig {
|
GrpcTransportConfig {
|
||||||
local_shard: shard,
|
local_shard: shard,
|
||||||
listen_addr: listen,
|
listen_addr: listen,
|
||||||
peers,
|
// m11p5: `peers` is now `host:port` strings; the fixtures hand us
|
||||||
|
// resolved loopback `SocketAddr`s, so stringify at the boundary.
|
||||||
|
peers: peers.into_iter().map(|(s, a)| (s, a.to_string())).collect(),
|
||||||
insecure: true,
|
insecure: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -33,6 +33,11 @@ unwrap_used = "deny"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
axum = "0.8"
|
axum = "0.8"
|
||||||
|
# Snapshot-artifact manifest hashing (m11p5 §2): the leader-side
|
||||||
|
# NodeSnapshotSource BLAKE3-hashes every staged file once; the puller verifies
|
||||||
|
# against the manifest. Same crate + version tidaldb already uses, so no new
|
||||||
|
# transitive surface.
|
||||||
|
blake3 = "1"
|
||||||
clap = { version = "4.5", features = ["derive", "env"] }
|
clap = { version = "4.5", features = ["derive", "env"] }
|
||||||
crossbeam = "0.8"
|
crossbeam = "0.8"
|
||||||
# Concurrent peer fan-out for cluster broadcast / promote / status aggregation
|
# Concurrent peer fan-out for cluster broadcast / promote / status aggregation
|
||||||
|
|||||||
@ -26,7 +26,7 @@
|
|||||||
//! comparison, so it can never win.
|
//! comparison, so it can never win.
|
||||||
|
|
||||||
use std::sync::{
|
use std::sync::{
|
||||||
Arc, Mutex, OnceLock, Weak,
|
Arc, Mutex, OnceLock, RwLock, Weak,
|
||||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||||
mpsc,
|
mpsc,
|
||||||
};
|
};
|
||||||
@ -34,8 +34,8 @@ use std::time::{Duration, Instant};
|
|||||||
|
|
||||||
use tidal_net::{ClaimRejection, ElectionNet, ElectionNetEvent, HeartbeatExchange, proto};
|
use tidal_net::{ClaimRejection, ElectionNet, ElectionNetEvent, HeartbeatExchange, proto};
|
||||||
use tidaldb::replication::{
|
use tidaldb::replication::{
|
||||||
ElectionAction, ElectionConfig, ElectionState, HardState, LogPosition, Role, VoteReply,
|
ElectionAction, ElectionConfig, ElectionState, HardState, LogPosition, ReseedReason, Role,
|
||||||
VoteRpc,
|
VoteReply, VoteRpc,
|
||||||
shard::{RegionId, ShardId},
|
shard::{RegionId, ShardId},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -67,7 +67,12 @@ pub struct ElectionRuntime {
|
|||||||
/// The driver's inbox for async RPC outcomes.
|
/// The driver's inbox for async RPC outcomes.
|
||||||
inbox_tx: mpsc::Sender<ElectionNetEvent>,
|
inbox_tx: mpsc::Sender<ElectionNetEvent>,
|
||||||
/// Peer shards for fan-outs (1:1 with the machine's peer regions).
|
/// Peer shards for fan-outs (1:1 with the machine's peer regions).
|
||||||
peer_shards: Vec<ShardId>,
|
/// Mutable at runtime (m11p5 §3.3 conf-change): a join/remove updates this
|
||||||
|
/// in the same fenced apply step as the machine's voter set, so the fan-out
|
||||||
|
/// targets and the quorum math can never disagree about the roster. The
|
||||||
|
/// `RwLock` is taken briefly to snapshot the vec before each fan-out (the
|
||||||
|
/// driver thread is the only reader; conf-changes are the rare writer).
|
||||||
|
peer_shards: RwLock<Vec<ShardId>>,
|
||||||
stop: AtomicBool,
|
stop: AtomicBool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -110,6 +115,51 @@ impl ElectionRuntime {
|
|||||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Snapshot the current fan-out peer shards (a brief read lock; the driver
|
||||||
|
/// thread is the only reader).
|
||||||
|
fn peer_shards_snapshot(&self) -> Vec<ShardId> {
|
||||||
|
self.peer_shards
|
||||||
|
.read()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Apply a membership conf-change to the election surfaces (m11p5 §3.3): the
|
||||||
|
/// pure machine's voter set + majority, the campaign gate (self voter-ness),
|
||||||
|
/// AND the driver's fan-out targets — all in one step so the quorum math and
|
||||||
|
/// the vote/heartbeat fan-out can never disagree about the roster. Called
|
||||||
|
/// from the node's one fenced apply path.
|
||||||
|
///
|
||||||
|
/// `voters` is every OTHER voter region (self excluded, like
|
||||||
|
/// [`ElectionConfig::peers`]) — the VOTING set (majority math, vote-grant
|
||||||
|
/// counting). `learners` is every OTHER learner region; learners are NOT in
|
||||||
|
/// the machine's voter set (they never count toward a quorum) but ARE in the
|
||||||
|
/// heartbeat fan-out so a learner LEARNS the leader and JOINS THE TERM
|
||||||
|
/// (without a heartbeat a learner never sets its leadership view, never joins
|
||||||
|
/// the term, and never reports its applied frontier — so it can never be
|
||||||
|
/// auto-promoted, §3.3). `self_is_voter` drives the campaign gate (a learner /
|
||||||
|
/// removed node cannot self-start an election or honor a `TimeoutNow`).
|
||||||
|
pub fn reconfigure_voters(
|
||||||
|
&self,
|
||||||
|
voters: Vec<RegionId>,
|
||||||
|
learners: &[RegionId],
|
||||||
|
self_is_voter: bool,
|
||||||
|
) {
|
||||||
|
// The heartbeat fan-out reaches voters AND learners; the machine's voting
|
||||||
|
// set is voters only.
|
||||||
|
let mut fan_out: Vec<ShardId> = voters.iter().map(|r| shard_of_region(*r)).collect();
|
||||||
|
fan_out.extend(learners.iter().map(|r| shard_of_region(*r)));
|
||||||
|
{
|
||||||
|
let mut machine = self.lock_machine();
|
||||||
|
machine.reconfigure(voters);
|
||||||
|
machine.set_voter(self_is_voter);
|
||||||
|
}
|
||||||
|
*self
|
||||||
|
.peer_shards
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner) = fan_out;
|
||||||
|
}
|
||||||
|
|
||||||
/// This node's log position: `(wal_tail_term, durable_frontier)`, both
|
/// This node's log position: `(wal_tail_term, durable_frontier)`, both
|
||||||
/// read from the node's WAL state (§1b — the same fsync stream).
|
/// read from the node's WAL state (§1b — the same fsync stream).
|
||||||
fn my_log(&self) -> LogPosition {
|
fn my_log(&self) -> LogPosition {
|
||||||
@ -147,15 +197,31 @@ impl ElectionRuntime {
|
|||||||
any
|
any
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The term-join divergence check (phase-4.md §5), run once per term —
|
/// The three-way term-join rule (phase-4.md §5; m11p5 §2 "The three-way
|
||||||
/// and ONLY from a heartbeat, which carries the leader's ELECTION-TIME
|
/// term-join rule"), run once per term — and ONLY from a heartbeat, which
|
||||||
/// log position (`prev_log`): this node is divergent iff its own
|
/// carries the leader's ELECTION-TIME log position (`prev_log`). Both
|
||||||
/// position exceeds the leader's lexicographically — it holds entries
|
/// positions are in the PREVIOUS stream's numbering (the vote restriction's
|
||||||
/// the new leadership's history does not subsume. Both positions are in
|
/// comparison), the only cross-node-comparable space; the new term's
|
||||||
/// the PREVIOUS stream's numbering (the vote restriction's comparison),
|
/// baseline is in the NEW leader's numbering and is used solely for the
|
||||||
/// the only cross-node-comparable space; the new term's baseline is in
|
/// frontier jump. The node's `own` position is compared lexicographically
|
||||||
/// the NEW leader's numbering and is used solely for the frontier jump.
|
/// (on `(tail_term, frontier)`) against `prev_log`:
|
||||||
/// Returns `false` when the node is (or just became) quarantined.
|
///
|
||||||
|
/// * `own > prev_log` → a DIVERGENT suffix the new leadership's history does
|
||||||
|
/// not subsume → **quarantine** (existing, phase-4.md). The node refuses
|
||||||
|
/// the data plane while still voting.
|
||||||
|
/// * `own < prev_log` → the node LACKS `(own, prev_log]` of the previous
|
||||||
|
/// stream, which is pre-baseline in the new stream and will never ship →
|
||||||
|
/// **latch `reseed_required`** (m11p5 §2; new). The vote restriction makes
|
||||||
|
/// this exact: an elected leader's position ≥ every granter's, so a
|
||||||
|
/// strictly-smaller position is genuinely missing committed-era history.
|
||||||
|
/// The join is NOT blocked and the node is NOT quarantined — it keeps
|
||||||
|
/// serving degraded reads and voting; the reseed runs on its next boot
|
||||||
|
/// (automatically when `reseed_self_restart` is wired).
|
||||||
|
/// * `own == prev_log` (or `tail_term == term`, the within-term rejoin) →
|
||||||
|
/// **clean**.
|
||||||
|
///
|
||||||
|
/// Returns `false` only when the node is (or just became) quarantined; the
|
||||||
|
/// reseed-latch path returns `true` (the join proceeds).
|
||||||
fn join_term_check(&self, term: u64, prev_log: LogPosition) -> bool {
|
fn join_term_check(&self, term: u64, prev_log: LogPosition) -> bool {
|
||||||
if term == 0 || term <= self.joined_term.load(Ordering::Acquire) {
|
if term == 0 || term <= self.joined_term.load(Ordering::Acquire) {
|
||||||
return !self.is_quarantined();
|
return !self.is_quarantined();
|
||||||
@ -167,25 +233,54 @@ impl ElectionRuntime {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
let position = node.election_log_position();
|
let position = node.election_log_position();
|
||||||
// A tail already carrying THIS term's marker is manifestly part of
|
match decide_join(term, position, prev_log) {
|
||||||
// this term's history — the restart-within-term rejoin (phase-4.md
|
JoinDecision::Quarantine => {
|
||||||
// §5, third clause). Without this, a mid-term rejoiner whose tail
|
// Preserve the existing quarantine semantics: set the latch, note
|
||||||
// term (T) exceeds the leader's election-time tail (T-1) would
|
// the divergence (metric + reseed marker), and refuse the data
|
||||||
// false-quarantine on every restart.
|
// plane (return false).
|
||||||
let rejoining_own_term = position.tail_term == term;
|
|
||||||
if !rejoining_own_term && position > prev_log {
|
|
||||||
self.quarantined.store(true, Ordering::Release);
|
self.quarantined.store(true, Ordering::Release);
|
||||||
|
// Suppress campaigning in the pure machine (m11p5 §3.3 close-out
|
||||||
|
// of the stage-C deviation): a quarantined node has a divergent
|
||||||
|
// suffix the elected term's history does not subsume — it must
|
||||||
|
// never self-start an election or honor a `TimeoutNow` (its stale
|
||||||
|
// WAL-tail term makes it lose every up-to-date comparison anyway,
|
||||||
|
// but suppressing is the explicit, testable gate rather than an
|
||||||
|
// emergent property). Taken under the machine lock, matching the
|
||||||
|
// driver's lock discipline. A reseed boot (fresh process) starts
|
||||||
|
// the machine un-suppressed, so the latch naturally clears once
|
||||||
|
// the divergence is healed.
|
||||||
|
self.lock_machine().set_campaign_suppressed(true);
|
||||||
node.note_quarantined(
|
node.note_quarantined(
|
||||||
term,
|
term,
|
||||||
position.tail_term,
|
position.tail_term,
|
||||||
position.frontier,
|
position.frontier,
|
||||||
Some(prev_log.frontier),
|
Some(prev_log.frontier),
|
||||||
);
|
);
|
||||||
return false;
|
false
|
||||||
}
|
}
|
||||||
|
JoinDecision::ReseedRequired => {
|
||||||
|
// The node is BEHIND a leadership change: it lacks
|
||||||
|
// `(own, prev_log]` of the previous stream — pre-baseline in the
|
||||||
|
// new stream, never shippable. Latch the durable reseed marker
|
||||||
|
// (reason `snapshot_required`: a pre-baseline gap, not a
|
||||||
|
// divergent suffix) + the gauge, but DO NOT quarantine and DO
|
||||||
|
// NOT block the join. The resume seqno is the first seqno this
|
||||||
|
// node is missing in the PREVIOUS stream's numbering
|
||||||
|
// (`own.frontier + 1`); the marker boot re-baselines onto the
|
||||||
|
// leader's stream via the snapshot regardless.
|
||||||
|
node.latch_reseed_marker(
|
||||||
|
ReseedReason::SnapshotRequired,
|
||||||
|
position.frontier.saturating_add(1),
|
||||||
|
);
|
||||||
self.joined_term.store(term, Ordering::Release);
|
self.joined_term.store(term, Ordering::Release);
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
JoinDecision::Clean => {
|
||||||
|
self.joined_term.store(term, Ordering::Release);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Execute a step's actions IN ORDER. A failed hard-state persist drops
|
/// Execute a step's actions IN ORDER. A failed hard-state persist drops
|
||||||
/// every remaining action: no send may escape that durable state does
|
/// every remaining action: no send may escape that durable state does
|
||||||
@ -224,7 +319,7 @@ impl ElectionRuntime {
|
|||||||
node.cluster_metrics().incr_elections_started();
|
node.cluster_metrics().incr_elections_started();
|
||||||
}
|
}
|
||||||
self.net.fan_votes(
|
self.net.fan_votes(
|
||||||
&self.peer_shards,
|
&self.peer_shards_snapshot(),
|
||||||
proto::VoteRequest {
|
proto::VoteRequest {
|
||||||
term: rpc.term,
|
term: rpc.term,
|
||||||
candidate_region: u32::from(rpc.candidate.0),
|
candidate_region: u32::from(rpc.candidate.0),
|
||||||
@ -265,7 +360,7 @@ impl ElectionRuntime {
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
self.net.fan_heartbeats(
|
self.net.fan_heartbeats(
|
||||||
&self.peer_shards,
|
&self.peer_shards_snapshot(),
|
||||||
&node.election_heartbeat(term),
|
&node.election_heartbeat(term),
|
||||||
&self.inbox_tx,
|
&self.inbox_tx,
|
||||||
);
|
);
|
||||||
@ -298,16 +393,45 @@ impl ElectionRuntime {
|
|||||||
/// Feed one async RPC outcome into the machine.
|
/// Feed one async RPC outcome into the machine.
|
||||||
fn on_net_event(&self, event: ElectionNetEvent, now: Instant) {
|
fn on_net_event(&self, event: ElectionNetEvent, now: Instant) {
|
||||||
let my_log = self.my_log();
|
let my_log = self.my_log();
|
||||||
|
// The typed removed signal (m11p5 §3.3): a heartbeat / vote reply
|
||||||
|
// carrying `removed=true` means a voter's APPLIED roster lists THIS node
|
||||||
|
// as `Removed`. Detected here (the inbox is the only place these replies
|
||||||
|
// arrive) so a node that MISSED the `Removed` record — it was down during
|
||||||
|
// the removal-delivery grace — still learns it is decommissioned. The
|
||||||
|
// latch is applied AFTER the machine step below (the campaign suppression
|
||||||
|
// rides the same lock the step holds).
|
||||||
|
let removed_signal = matches!(
|
||||||
|
event,
|
||||||
|
ElectionNetEvent::VoteReply { removed: true, .. }
|
||||||
|
| ElectionNetEvent::HeartbeatReply { removed: true, .. }
|
||||||
|
);
|
||||||
let actions = {
|
let actions = {
|
||||||
let mut machine = self.lock_machine();
|
let mut machine = self.lock_machine();
|
||||||
|
// Suppress campaigning UNDER THE SAME LOCK as the step (the driver's
|
||||||
|
// lock discipline): a removed node must never self-start an election
|
||||||
|
// or honor a TimeoutNow. A reseed boot does not clear this — there is
|
||||||
|
// no reseed; a removed node stays decommissioned until the operator
|
||||||
|
// tears it down (runbook §8). It is harmless if this node is not a
|
||||||
|
// member of the responder's roster for an unrelated reason: the
|
||||||
|
// server only sets `removed` for a genuine `Removed` tombstone.
|
||||||
|
if removed_signal {
|
||||||
|
machine.set_campaign_suppressed(true);
|
||||||
|
}
|
||||||
match event {
|
match event {
|
||||||
ElectionNetEvent::VoteReply {
|
ElectionNetEvent::VoteReply {
|
||||||
from,
|
from,
|
||||||
prevote,
|
prevote,
|
||||||
term,
|
term,
|
||||||
granted,
|
granted,
|
||||||
|
removed: _,
|
||||||
} => {
|
} => {
|
||||||
tracing::info!(from = from.0, prevote, term, granted, "election: vote reply");
|
tracing::info!(
|
||||||
|
from = from.0,
|
||||||
|
prevote,
|
||||||
|
term,
|
||||||
|
granted,
|
||||||
|
"election: vote reply"
|
||||||
|
);
|
||||||
machine.on_vote_response(
|
machine.on_vote_response(
|
||||||
RegionId(from.0),
|
RegionId(from.0),
|
||||||
VoteReply { term, granted },
|
VoteReply { term, granted },
|
||||||
@ -325,6 +449,7 @@ impl ElectionRuntime {
|
|||||||
from,
|
from,
|
||||||
term,
|
term,
|
||||||
accepted,
|
accepted,
|
||||||
|
removed: _,
|
||||||
} => {
|
} => {
|
||||||
tracing::trace!(from = from.0, term, accepted, "heartbeat reply");
|
tracing::trace!(from = from.0, term, accepted, "heartbeat reply");
|
||||||
machine.on_heartbeat_ack(RegionId(from.0), term, accepted, now)
|
machine.on_heartbeat_ack(RegionId(from.0), term, accepted, now)
|
||||||
@ -348,6 +473,13 @@ impl ElectionRuntime {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
self.execute(actions, now);
|
self.execute(actions, now);
|
||||||
|
// Apply the node-side half of the removed signal OUTSIDE the machine
|
||||||
|
// lock: flip readiness to 503 + log the decommission runbook pointer.
|
||||||
|
// Idempotent (the node's latch is a one-way AtomicBool), and explicitly
|
||||||
|
// NOT a reseed (a remove is not a reseed; §3.3).
|
||||||
|
if removed_signal && let Some(node) = self.node.upgrade() {
|
||||||
|
node.note_removed_by_peer_signal();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -358,11 +490,7 @@ pub struct NodeElectionHooks {
|
|||||||
|
|
||||||
impl tidal_net::ElectionHooks for NodeElectionHooks {
|
impl tidal_net::ElectionHooks for NodeElectionHooks {
|
||||||
fn self_claim(&self) -> (u64, u16) {
|
fn self_claim(&self) -> (u64, u16) {
|
||||||
let region = self
|
let region = self.runtime.node.upgrade().map_or(0, |n| n.self_region().0);
|
||||||
.runtime
|
|
||||||
.node
|
|
||||||
.upgrade()
|
|
||||||
.map_or(0, |n| n.self_region().0);
|
|
||||||
(self.runtime.current_term(), region)
|
(self.runtime.current_term(), region)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -409,8 +537,8 @@ impl tidal_net::ElectionHooks for NodeElectionHooks {
|
|||||||
tracing::debug!(term, first_seq, "payload deferred: term not joined yet");
|
tracing::debug!(term, first_seq, "payload deferred: term not joined yet");
|
||||||
return Err(ClaimRejection::JoinPending);
|
return Err(ClaimRejection::JoinPending);
|
||||||
}
|
}
|
||||||
let actions = self
|
let actions =
|
||||||
.runtime
|
self.runtime
|
||||||
.lock_machine()
|
.lock_machine()
|
||||||
.on_leader_contact(term, RegionId(leader_region), now);
|
.on_leader_contact(term, RegionId(leader_region), now);
|
||||||
self.runtime.execute(actions, now);
|
self.runtime.execute(actions, now);
|
||||||
@ -429,8 +557,7 @@ impl tidal_net::ElectionHooks for NodeElectionHooks {
|
|||||||
// Same topology-era allowance as the payload gate: a term-0 leader's
|
// Same topology-era allowance as the payload gate: a term-0 leader's
|
||||||
// lease must not be broken by a peer whose own failed candidacy
|
// lease must not be broken by a peer whose own failed candidacy
|
||||||
// inflated its term without any elected leadership existing.
|
// inflated its term without any elected leadership existing.
|
||||||
let topology_era_claim =
|
let topology_era_claim = term == 0 && self.runtime.joined_term.load(Ordering::Acquire) == 0;
|
||||||
term == 0 && self.runtime.joined_term.load(Ordering::Acquire) == 0;
|
|
||||||
if term < current && !topology_era_claim {
|
if term < current && !topology_era_claim {
|
||||||
return HeartbeatExchange {
|
return HeartbeatExchange {
|
||||||
term: current,
|
term: current,
|
||||||
@ -448,8 +575,8 @@ impl tidal_net::ElectionHooks for NodeElectionHooks {
|
|||||||
{
|
{
|
||||||
node.note_term_joined(term, RegionId(leader_region), stream_baseline);
|
node.note_term_joined(term, RegionId(leader_region), stream_baseline);
|
||||||
}
|
}
|
||||||
let actions = self
|
let actions =
|
||||||
.runtime
|
self.runtime
|
||||||
.lock_machine()
|
.lock_machine()
|
||||||
.on_leader_contact(term, RegionId(leader_region), now);
|
.on_leader_contact(term, RegionId(leader_region), now);
|
||||||
self.runtime.execute(actions, now);
|
self.runtime.execute(actions, now);
|
||||||
@ -514,6 +641,56 @@ impl tidal_net::ElectionHooks for NodeElectionHooks {
|
|||||||
.upgrade()
|
.upgrade()
|
||||||
.is_some_and(|node| node.commit_active_term() == reporter_term)
|
.is_some_and(|node| node.commit_active_term() == reporter_term)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_removed_member(&self, region: u16) -> bool {
|
||||||
|
// The typed removed signal (m11p5 §3.3): does THIS node's applied roster
|
||||||
|
// list `region` as a `Removed` tombstone? Read from the membership view
|
||||||
|
// (the single source of roster truth). A node that has not begun the
|
||||||
|
// membership era has no `Removed` members → always false.
|
||||||
|
self.runtime
|
||||||
|
.node
|
||||||
|
.upgrade()
|
||||||
|
.is_some_and(|node| node.is_member_removed(RegionId(region)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pure outcome of the three-way term-join rule (m11p5 §2): a deterministic
|
||||||
|
/// function of `(term, own, prev_log)` with no I/O, so it is exhaustively
|
||||||
|
/// unit-testable. The driver translates each variant into side effects
|
||||||
|
/// ([`ElectionRuntime::join_term_check`]).
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum JoinDecision {
|
||||||
|
/// `own > prev_log` and not a within-term rejoin: a divergent suffix the new
|
||||||
|
/// leadership's history does not subsume → quarantine.
|
||||||
|
Quarantine,
|
||||||
|
/// `own < prev_log` and not a within-term rejoin: the node is BEHIND a
|
||||||
|
/// leadership change, missing pre-baseline history that will never ship →
|
||||||
|
/// latch the reseed marker (the join still proceeds).
|
||||||
|
ReseedRequired,
|
||||||
|
/// `own == prev_log`, or `own.tail_term == term` (the within-term rejoin):
|
||||||
|
/// the node's tail is part of this term's history → join clean.
|
||||||
|
Clean,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pure three-way term-join rule (m11p5 §2 "The three-way term-join rule").
|
||||||
|
///
|
||||||
|
/// `own` and `prev_log` are both in the PREVIOUS stream's numbering (the vote
|
||||||
|
/// restriction's `(tail_term, frontier)` comparison). A tail already carrying
|
||||||
|
/// THIS term's marker (`own.tail_term == term`) is manifestly part of this
|
||||||
|
/// term's history — the restart-within-term rejoin (phase-4.md §5, third
|
||||||
|
/// clause): without it, a mid-term rejoiner whose tail term (T) exceeds the
|
||||||
|
/// leader's election-time tail (T-1) would false-quarantine on every restart.
|
||||||
|
/// Otherwise the lexicographic comparison decides: strictly-greater diverges
|
||||||
|
/// (quarantine), strictly-smaller is genuinely behind (reseed), equal is clean.
|
||||||
|
fn decide_join(term: u64, own: LogPosition, prev_log: LogPosition) -> JoinDecision {
|
||||||
|
if own.tail_term == term {
|
||||||
|
return JoinDecision::Clean;
|
||||||
|
}
|
||||||
|
match own.cmp(&prev_log) {
|
||||||
|
std::cmp::Ordering::Greater => JoinDecision::Quarantine,
|
||||||
|
std::cmp::Ordering::Less => JoinDecision::ReseedRequired,
|
||||||
|
std::cmp::Ordering::Equal => JoinDecision::Clean,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build the runtime + hooks, late-bind the hooks into the transport, and
|
/// Build the runtime + hooks, late-bind the hooks into the transport, and
|
||||||
@ -551,7 +728,7 @@ pub fn start(
|
|||||||
node: Arc::downgrade(node),
|
node: Arc::downgrade(node),
|
||||||
net: node.election_net(),
|
net: node.election_net(),
|
||||||
inbox_tx,
|
inbox_tx,
|
||||||
peer_shards,
|
peer_shards: RwLock::new(peer_shards),
|
||||||
stop: AtomicBool::new(false),
|
stop: AtomicBool::new(false),
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -585,6 +762,27 @@ pub fn start(
|
|||||||
};
|
};
|
||||||
node.cluster_metrics()
|
node.cluster_metrics()
|
||||||
.set_election_view(driver.current_term(), role);
|
.set_election_view(driver.current_term(), role);
|
||||||
|
// m11p5 §3.3 follower-side membership apply: the engine folds
|
||||||
|
// kind-4 records into its `ClusterMembership` cell as they
|
||||||
|
// stream in; here the 50ms tick compares the cell's version
|
||||||
|
// to the applied view's and drives the one fenced apply path
|
||||||
|
// on change (a cheap version compare; no new cross-crate
|
||||||
|
// callback). The leader applied synchronously at append, so
|
||||||
|
// its cell and view already agree — this is a no-op there.
|
||||||
|
node.maybe_apply_membership_from_cell();
|
||||||
|
// m11p5 §3.3 auto-promotion: a STANDING LEADER DUTY re-armed
|
||||||
|
// every tick — promote a caught-up learner to Voter with no
|
||||||
|
// operator verb. A no-op off the leader / with no learner, and
|
||||||
|
// a detached (write-pool-style) job since the promotion's
|
||||||
|
// append + commit wait BLOCK; one at a time via the inflight
|
||||||
|
// guard.
|
||||||
|
node.submit_auto_promote();
|
||||||
|
// m11p5 §3.3 removal-delivery grace: retire a removed peer's
|
||||||
|
// ship cell only once it has learned of its removal through
|
||||||
|
// the log (its applied mark covers the Removed record) or the
|
||||||
|
// bounded grace elapses. A cheap no-op when nothing is pending
|
||||||
|
// (only the leader arms a grace, on a remove verb).
|
||||||
|
node.poll_deferred_retires();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
tracing::info!("election driver stopped");
|
tracing::info!("election driver stopped");
|
||||||
@ -611,3 +809,88 @@ pub fn election_config(
|
|||||||
auto_election: spec.auto() && auto_override,
|
auto_election: spec.auto() && auto_override,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::{JoinDecision, decide_join};
|
||||||
|
use tidaldb::replication::LogPosition;
|
||||||
|
|
||||||
|
fn pos(tail_term: u64, frontier: u64) -> LogPosition {
|
||||||
|
LogPosition {
|
||||||
|
tail_term,
|
||||||
|
frontier,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The three-way term-join rule (m11p5 §2). `own > prev_log` quarantines (a
|
||||||
|
/// divergent suffix), `own < prev_log` latches reseed (genuinely behind),
|
||||||
|
/// and equal / within-term is clean.
|
||||||
|
#[test]
|
||||||
|
fn three_way_join_rule_classifies_each_case() {
|
||||||
|
// Joining term T = 1; both positions in the PREVIOUS stream's numbering
|
||||||
|
// (tail_term 0 here — the topology-era stream).
|
||||||
|
let t = 1;
|
||||||
|
|
||||||
|
// own > prev_log (higher frontier, same tail term) → divergent suffix.
|
||||||
|
// (This is test 1's exact shape: own=(0,970) vs leader prev=(0,9) —
|
||||||
|
// except here own LEADS, the quarantine direction.)
|
||||||
|
assert_eq!(
|
||||||
|
decide_join(t, pos(0, 970), pos(0, 9)),
|
||||||
|
JoinDecision::Quarantine,
|
||||||
|
"a strictly-greater own position is a divergent suffix → quarantine"
|
||||||
|
);
|
||||||
|
// own > prev_log via a higher tail term (lexicographic), NOT the
|
||||||
|
// within-term rejoin (own.tail_term 1 != joining term 2) → quarantine.
|
||||||
|
assert_eq!(
|
||||||
|
decide_join(2, pos(1, 0), pos(0, u64::MAX)),
|
||||||
|
JoinDecision::Quarantine,
|
||||||
|
"a higher tail term outranks any frontier → quarantine"
|
||||||
|
);
|
||||||
|
|
||||||
|
// own < prev_log (lower frontier, same tail term) → genuinely behind:
|
||||||
|
// the node lacks (own, prev_log] of the previous stream → reseed. This
|
||||||
|
// is test 1's REAL shape: own=(0,9) (stopped early) vs leader's
|
||||||
|
// election-time prev=(0,970) (full history) → reseed, not quarantine.
|
||||||
|
assert_eq!(
|
||||||
|
decide_join(t, pos(0, 9), pos(0, 970)),
|
||||||
|
JoinDecision::ReseedRequired,
|
||||||
|
"a strictly-smaller own position is genuinely missing history → reseed"
|
||||||
|
);
|
||||||
|
// own < prev_log via a lower tail term, NOT within-term (own.tail_term 1
|
||||||
|
// != joining term 2) → reseed.
|
||||||
|
assert_eq!(
|
||||||
|
decide_join(2, pos(1, 0), pos(1, u64::MAX)),
|
||||||
|
JoinDecision::ReseedRequired,
|
||||||
|
"a lower frontier under the same sub-term loses → reseed"
|
||||||
|
);
|
||||||
|
|
||||||
|
// own == prev_log → clean.
|
||||||
|
assert_eq!(
|
||||||
|
decide_join(t, pos(0, 9), pos(0, 9)),
|
||||||
|
JoinDecision::Clean,
|
||||||
|
"an equal position is clean"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The within-term rejoin (phase-4.md §5, third clause): a tail already
|
||||||
|
/// carrying THIS term's marker is part of this term's history regardless of
|
||||||
|
/// the `prev_log` comparison — it must NOT quarantine or reseed on restart.
|
||||||
|
#[test]
|
||||||
|
fn within_term_rejoin_is_always_clean() {
|
||||||
|
let t = 3;
|
||||||
|
// own.tail_term == term, even with a frontier far above prev_log (which
|
||||||
|
// is the leader's election-time tail at T-1) → clean, never quarantine.
|
||||||
|
assert_eq!(
|
||||||
|
decide_join(t, pos(3, 500), pos(2, 10)),
|
||||||
|
JoinDecision::Clean,
|
||||||
|
"a tail carrying this term's marker is the within-term rejoin → clean"
|
||||||
|
);
|
||||||
|
// And clean even with a frontier below prev_log (a mid-term restart that
|
||||||
|
// applied the marker but then lost suffix) — still within-term, no reseed.
|
||||||
|
assert_eq!(
|
||||||
|
decide_join(t, pos(3, 1), pos(2, 999)),
|
||||||
|
JoinDecision::Clean,
|
||||||
|
"within-term rejoin wins over the < comparison too"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
904
tidal-server/src/cluster/join_boot.rs
Normal file
904
tidal-server/src/cluster/join_boot.rs
Normal file
@ -0,0 +1,904 @@
|
|||||||
|
//! Seed-join boot (m11p5 §3.4–§3.6): a node that is NOT declared in the local
|
||||||
|
//! topology joins an existing cluster by contacting a `--seed`.
|
||||||
|
//!
|
||||||
|
//! # The boot sequence (§2.7 / §3.4)
|
||||||
|
//!
|
||||||
|
//! For a FRESH data dir + `--seed`, on a dedicated boot thread:
|
||||||
|
//!
|
||||||
|
//! 1. **Discover a leader** over `(seeds ∪ MembershipStore cache)` HTTP status
|
||||||
|
//! endpoints (the cache wins precedence for discovery once it exists — a
|
||||||
|
//! restart-of-a-joiner knows its peers without the seed).
|
||||||
|
//! 2. **Join** via the standalone `JoinCluster` gRPC verb. Idempotent by name: a
|
||||||
|
//! re-join on retry returns the existing id/role, appends nothing. A
|
||||||
|
//! non-leader seed answers `accepted=false` with a leader hint → re-target.
|
||||||
|
//! 3. **Persist before act**: write the returned roster to the `MembershipStore`
|
||||||
|
//! cache AND the `ElectionStore {term}` (the joiner stamps the snapshot fetch
|
||||||
|
//! and stream pulls with this term).
|
||||||
|
//! 4. **FetchSnapshot** `from_seqno=1`: `needed=true` → staged install (reuse the
|
||||||
|
//! §2.3 staging/verify/swap machinery; a fresh dir makes the swap trivial);
|
||||||
|
//! `needed=false` → proceed empty (the small-cluster case where the stream
|
||||||
|
//! serves from 1).
|
||||||
|
//! 5. **Synthesize a topology** from the JOIN-RESPONSE roster (this node's
|
||||||
|
//! `--region` = its assigned id), carrying the local file's behavioral knob
|
||||||
|
//! blocks (§3.5). `RegionClusterState::new` builds the transport/ship/election
|
||||||
|
//! peer tables from THIS, not the local topology's `regions:` list.
|
||||||
|
//!
|
||||||
|
//! A **restart of a joiner** (the data dir already has a WAL + a membership
|
||||||
|
//! cache) skips the seed loop: it boots from the cache roster (no leader
|
||||||
|
//! discovery, no fetch) and the runtime catch-up self-heal converges it. The
|
||||||
|
//! authoritative roster once the WAL opens is the recovered `ClusterMembership`
|
||||||
|
//! cell (§3.6 precedence, resolved inside `RegionClusterState::new`); the cache
|
||||||
|
//! and the synthesized topology only feed the pre-open peer-table construction,
|
||||||
|
//! and the cache is rewritten from the cell after every applied record.
|
||||||
|
//!
|
||||||
|
//! # A joiner is a LEARNER
|
||||||
|
//!
|
||||||
|
//! The join response role is `Learner`. The synthesized topology marks the
|
||||||
|
//! joiner's role so `RegionClusterState`'s era-0 view (when no cell exists yet)
|
||||||
|
//! does not mistake it for a voter — but in practice a snapshot install always
|
||||||
|
//! carries the leader's WAL with the kind-4 Learner record, so the view boots
|
||||||
|
//! `from_record` with the correct role. `ElectionState` boots with `self` NOT in
|
||||||
|
//! the voter set (campaign-gated) until a `Voter` record applies (the leader's
|
||||||
|
//! auto-promotion duty appends one once the joiner catches up).
|
||||||
|
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use tidaldb::replication::{ElectionStore, HardState, MembershipSnapshot, MembershipStore};
|
||||||
|
use tidaldb::wal::format::{MemberEntry, MemberRole};
|
||||||
|
|
||||||
|
use super::reseed::{self, SeedInstallError};
|
||||||
|
use super::topology::{
|
||||||
|
ElectionSpec, GrpcTlsSpec, RegionSpec, ReplicationSpec, TimeoutsSpec, TopologySpec, WalSpec,
|
||||||
|
};
|
||||||
|
use crate::error::{Result, ServerError};
|
||||||
|
|
||||||
|
/// Per-status-poll HTTP timeout (the discovery loop iterates).
|
||||||
|
const STATUS_POLL_TIMEOUT: Duration = Duration::from_millis(500);
|
||||||
|
/// Per-join RPC timeout (the leader's bounded same-term commit wait is itself
|
||||||
|
/// bounded by `quorum_timeout`, so allow generous headroom).
|
||||||
|
const JOIN_RPC_TIMEOUT: Duration = Duration::from_secs(10);
|
||||||
|
/// Backoff bounds for the join loop.
|
||||||
|
const BACKOFF_MIN: Duration = Duration::from_millis(250);
|
||||||
|
const BACKOFF_MAX: Duration = Duration::from_secs(5);
|
||||||
|
/// Default join window before the boot gives up (env-overridable for tests via
|
||||||
|
/// `TIDAL_SEED_JOIN_MS`). A fresh joiner has nothing to fall back to, so on
|
||||||
|
/// timeout it returns an error and the process exits — the orchestrator restarts
|
||||||
|
/// it and the loop runs again (crash-loop is the orchestration's retry, not the
|
||||||
|
/// in-process mechanism). 120 s gives a slow loopback discover+join+fetch room.
|
||||||
|
const DEFAULT_JOIN_WINDOW_MS: u64 = 120_000;
|
||||||
|
|
||||||
|
/// The synthesized topology a seed-join boot constructs for
|
||||||
|
/// `RegionClusterState::new` (§3.4).
|
||||||
|
///
|
||||||
|
/// The join-response roster becomes the `regions:` list, the local file's knob
|
||||||
|
/// blocks are carried verbatim, and this node is included at its assigned id.
|
||||||
|
pub struct SeedJoinBoot {
|
||||||
|
/// The synthesized topology (roster from the join, knobs from the local file).
|
||||||
|
pub topology: TopologySpec,
|
||||||
|
/// This node's region name (echoed for `RegionClusterState::new`).
|
||||||
|
pub region: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inputs to [`seed_join_boot`].
|
||||||
|
pub struct SeedJoinInput<'a> {
|
||||||
|
/// The `--seed` HTTP base URLs.
|
||||||
|
pub seeds: &'a [String],
|
||||||
|
/// The local topology file, parsed — the knob source (§3.5). Its `regions:`
|
||||||
|
/// list is IGNORED for the roster.
|
||||||
|
pub knobs: &'a TopologySpec,
|
||||||
|
/// This node's `--region` name.
|
||||||
|
pub region: &'a str,
|
||||||
|
/// This node's advertised gRPC `host:port`.
|
||||||
|
pub advertise_grpc: &'a str,
|
||||||
|
/// This node's advertised HTTP `host:port`.
|
||||||
|
pub advertise_http: &'a str,
|
||||||
|
/// This node's `--metrics` bind (seed-join's only metrics source, §3.5).
|
||||||
|
pub metrics: Option<&'a str>,
|
||||||
|
/// The data dir (already validated as a mount subdirectory for the swap).
|
||||||
|
pub data_dir: &'a Path,
|
||||||
|
/// The API key for the seed status/join HTTP/gRPC calls (forwarded verbatim).
|
||||||
|
pub api_key: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the seed-join boot (§3.4). See the module docs for the sequence.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`ServerError::Cluster`] when the join window elapses without a successful
|
||||||
|
/// join+install (a fresh joiner has nothing to fall back to), or for any
|
||||||
|
/// unrecoverable durable-persist / swap fault.
|
||||||
|
// One linear boot sequence (cache fast-path → discover → join → persist → fetch
|
||||||
|
// → synthesize); splitting it would scatter the §2.7 ordering it documents.
|
||||||
|
#[allow(clippy::too_many_lines)]
|
||||||
|
pub fn seed_join_boot(input: &SeedJoinInput<'_>) -> Result<SeedJoinBoot> {
|
||||||
|
let store = MembershipStore::new(input.data_dir);
|
||||||
|
|
||||||
|
// §3.6 precedence for the PRE-OPEN loop: a restart of a joiner whose data dir
|
||||||
|
// already carries a WAL boots from the cache WITHOUT the seed. The
|
||||||
|
// authoritative roster once the WAL opens is the recovered cell (resolved
|
||||||
|
// inside `RegionClusterState::new`); this cache only seeds the peer tables.
|
||||||
|
let wal_exists = input
|
||||||
|
.data_dir
|
||||||
|
.join("wal")
|
||||||
|
.read_dir()
|
||||||
|
.map(|mut it| it.next().is_some())
|
||||||
|
.unwrap_or(false);
|
||||||
|
if wal_exists {
|
||||||
|
match store.load() {
|
||||||
|
Ok(Some(snap)) => {
|
||||||
|
tracing::info!(
|
||||||
|
region = input.region,
|
||||||
|
version = snap.version,
|
||||||
|
members = snap.members.len(),
|
||||||
|
"seed-join restart: a WAL + membership cache exist — booting from the cache \
|
||||||
|
roster without contacting a seed (§3.6; the WAL-recovered cell wins once \
|
||||||
|
opened, the runtime catch-up self-heal converges)"
|
||||||
|
);
|
||||||
|
// The restart path has no fresh join to name the current leader;
|
||||||
|
// the WAL cell wins at open and heartbeats correct the leader hint.
|
||||||
|
let topology = synthesize_topology(input, &snap.members, None)?;
|
||||||
|
return Ok(SeedJoinBoot {
|
||||||
|
topology,
|
||||||
|
region: input.region.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(None) => {
|
||||||
|
tracing::warn!(
|
||||||
|
region = input.region,
|
||||||
|
"seed-join restart: a WAL exists but the membership cache is missing — \
|
||||||
|
re-running the seed loop to recover the roster before opening"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
// A corrupt cache must be DETECTED, never guessed around — but a
|
||||||
|
// re-join recovers the roster, so do not refuse boot: log loudly
|
||||||
|
// and fall through to the seed loop.
|
||||||
|
tracing::error!(
|
||||||
|
region = input.region,
|
||||||
|
error = %e,
|
||||||
|
"seed-join restart: the membership cache is corrupt — re-running the seed \
|
||||||
|
loop to recover the roster (the corrupt cache is overwritten on success)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The TLS posture the joiner advertises (from the knob file's own region
|
||||||
|
// block, when one names this region; else plaintext — the loopback/VPC
|
||||||
|
// default every shipped topology uses).
|
||||||
|
let tls = own_grpc_tls(input.knobs, input.region);
|
||||||
|
let join_window = join_window();
|
||||||
|
let deadline = Instant::now() + join_window;
|
||||||
|
let mut backoff = BACKOFF_MIN;
|
||||||
|
|
||||||
|
let status_client = reqwest::blocking::Client::builder()
|
||||||
|
.timeout(STATUS_POLL_TIMEOUT)
|
||||||
|
.build()
|
||||||
|
.map_err(|e| ServerError::Cluster(format!("seed-join: build status client: {e}")))?;
|
||||||
|
|
||||||
|
while Instant::now() < deadline {
|
||||||
|
// (1) Discover a leader over (seeds ∪ cache). The cache (when present)
|
||||||
|
// contributes its members' HTTP addresses so a restart-of-a-joiner that
|
||||||
|
// lost its cache-only fast path still finds the leader.
|
||||||
|
let candidates = discovery_candidates(input.seeds, &store);
|
||||||
|
let Some(leader) = discover_leader(&status_client, &candidates, input.api_key.as_deref())
|
||||||
|
else {
|
||||||
|
std::thread::sleep(backoff);
|
||||||
|
backoff = (backoff * 2).min(BACKOFF_MAX);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
|
||||||
|
// (2) Join via the standalone gRPC verb (idempotent by name).
|
||||||
|
let join = match join_via_leader(
|
||||||
|
&leader,
|
||||||
|
input.region,
|
||||||
|
input.advertise_grpc,
|
||||||
|
input.advertise_http,
|
||||||
|
) {
|
||||||
|
Ok(JoinAttempt::Joined(resp)) => resp,
|
||||||
|
Ok(JoinAttempt::RetargetOrRetry(reason)) => {
|
||||||
|
tracing::info!(reason = %reason, "seed-join: join not accepted; re-discovering");
|
||||||
|
std::thread::sleep(backoff);
|
||||||
|
backoff = (backoff * 2).min(BACKOFF_MAX);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!(error = %e, "seed-join: join RPC failed; re-discovering");
|
||||||
|
std::thread::sleep(backoff);
|
||||||
|
backoff = (backoff * 2).min(BACKOFF_MAX);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// (3) Persist-before-act: the cache, then the term, BEFORE any fetch.
|
||||||
|
let snapshot = MembershipSnapshot {
|
||||||
|
version: join.membership_version,
|
||||||
|
term: join.term,
|
||||||
|
members: join.members.clone(),
|
||||||
|
};
|
||||||
|
if let Err(e) = store.persist(&snapshot) {
|
||||||
|
// A failed cache persist is non-fatal to the join itself (the cell
|
||||||
|
// installed via snapshot is the source of truth); log loudly and
|
||||||
|
// continue — the cache is rewritten from the cell after open.
|
||||||
|
tracing::error!(error = %e, "seed-join: persist membership cache failed (non-fatal)");
|
||||||
|
}
|
||||||
|
adopt_term(input.data_dir, join.term)?;
|
||||||
|
|
||||||
|
// (4) FetchSnapshot from_seqno=1: needed → install, else proceed empty.
|
||||||
|
match reseed::install_snapshot_from_leader(
|
||||||
|
input.data_dir,
|
||||||
|
&join.leader_grpc_addr,
|
||||||
|
join.leader_region_id,
|
||||||
|
join.term,
|
||||||
|
1,
|
||||||
|
tls.as_ref(),
|
||||||
|
) {
|
||||||
|
Ok(Some(seq)) => {
|
||||||
|
tracing::info!(
|
||||||
|
region = input.region,
|
||||||
|
assigned_id = join.assigned_id,
|
||||||
|
snapshot_seq = seq,
|
||||||
|
term = join.term,
|
||||||
|
"seed-join: snapshot installed; constructing the node from the join roster"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(None) => {
|
||||||
|
tracing::info!(
|
||||||
|
region = input.region,
|
||||||
|
assigned_id = join.assigned_id,
|
||||||
|
term = join.term,
|
||||||
|
"seed-join: leader reports needed=false (the stream serves from 1) — \
|
||||||
|
proceeding empty; the post-open catch-up pull converges the joiner"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(SeedInstallError::Retry) => {
|
||||||
|
tracing::warn!("seed-join: snapshot fetch retryable; re-discovering the leader");
|
||||||
|
std::thread::sleep(backoff);
|
||||||
|
backoff = (backoff * 2).min(BACKOFF_MAX);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Err(SeedInstallError::Fatal(e)) => return Err(e),
|
||||||
|
}
|
||||||
|
|
||||||
|
// (5) Synthesize the topology from the join roster + the local knobs,
|
||||||
|
// naming the CURRENT leader (so the `needed=false` boot self-heal pulls
|
||||||
|
// from the live stream).
|
||||||
|
let topology = synthesize_topology(input, &join.members, Some(join.leader_region_id))?;
|
||||||
|
return Ok(SeedJoinBoot {
|
||||||
|
topology,
|
||||||
|
region: input.region.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(ServerError::Cluster(format!(
|
||||||
|
"seed-join: could not join via any seed within {join_window:?} (a fresh joiner has \
|
||||||
|
nothing to fall back to). The orchestrator restarts this process and the loop runs \
|
||||||
|
again — crash-loop is the retry mechanism, never an in-process spin."
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The join window (env-overridable for tests).
|
||||||
|
fn join_window() -> Duration {
|
||||||
|
let ms = std::env::var("TIDAL_SEED_JOIN_MS")
|
||||||
|
.ok()
|
||||||
|
.and_then(|v| v.trim().parse::<u64>().ok())
|
||||||
|
.unwrap_or(DEFAULT_JOIN_WINDOW_MS);
|
||||||
|
Duration::from_millis(ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This region's advertised gRPC TLS material, when the knob file names this
|
||||||
|
/// region with a `grpc_tls` block (the seed dial uses the same posture).
|
||||||
|
fn own_grpc_tls(knobs: &TopologySpec, region: &str) -> Option<tidal_net::config::TlsConfig> {
|
||||||
|
knobs
|
||||||
|
.regions
|
||||||
|
.iter()
|
||||||
|
.find(|r| r.name == region)
|
||||||
|
.and_then(|r| r.grpc_tls.as_ref())
|
||||||
|
.map(GrpcTlsSpec::to_tls_config)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One discovery candidate: an HTTP status base + (when known) the gRPC address
|
||||||
|
/// the same node advertises.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct Candidate {
|
||||||
|
http_addr: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the discovery candidate set: the `--seed` URLs plus the cache's
|
||||||
|
/// members' HTTP addresses (deduplicated). Seeds first (the operator-named
|
||||||
|
/// bootstrap), then the cache (a restart-of-a-joiner's known peers).
|
||||||
|
fn discovery_candidates(seeds: &[String], store: &MembershipStore) -> Vec<Candidate> {
|
||||||
|
let mut out: Vec<Candidate> = Vec::new();
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
for s in seeds {
|
||||||
|
if seen.insert(s.clone()) {
|
||||||
|
out.push(Candidate {
|
||||||
|
http_addr: s.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(Some(snap)) = store.load() {
|
||||||
|
for m in &snap.members {
|
||||||
|
if m.role != MemberRole::Removed
|
||||||
|
&& !m.http_addr.is_empty()
|
||||||
|
&& seen.insert(m.http_addr.clone())
|
||||||
|
{
|
||||||
|
out.push(Candidate {
|
||||||
|
http_addr: m.http_addr.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the discovery loop learned (§2.7): the current leader's advertised gRPC
|
||||||
|
/// address + its term + region id, so a join can dial it directly.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct LeaderInfo {
|
||||||
|
http_addr: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll every candidate's `/cluster/status/local`; return the first that either
|
||||||
|
/// reports ITSELF the leader OR names a leader (whose HTTP address the roster
|
||||||
|
/// resolves). The join RPC is forwarded by a non-leader anyway, so any reachable
|
||||||
|
/// member is a usable join target — but preferring a leader avoids an extra hop.
|
||||||
|
fn discover_leader(
|
||||||
|
client: &reqwest::blocking::Client,
|
||||||
|
candidates: &[Candidate],
|
||||||
|
api_key: Option<&str>,
|
||||||
|
) -> Option<LeaderInfo> {
|
||||||
|
// First pass: a candidate that reports itself the leader (direct target).
|
||||||
|
let mut any_reachable: Option<LeaderInfo> = None;
|
||||||
|
for cand in candidates {
|
||||||
|
let url = super::forward::peer_url(&cand.http_addr, "/cluster/status/local");
|
||||||
|
let mut req = client.get(&url);
|
||||||
|
if let Some(key) = api_key {
|
||||||
|
req = req.bearer_auth(key);
|
||||||
|
}
|
||||||
|
let Ok(resp) = req.send() else { continue };
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Ok(json) = resp.json::<serde_json::Value>() else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
// Any reachable member is a fallback join target (it forwards to the
|
||||||
|
// leader); a self-reported leader is preferred (one fewer hop).
|
||||||
|
any_reachable.get_or_insert_with(|| LeaderInfo {
|
||||||
|
http_addr: cand.http_addr.clone(),
|
||||||
|
});
|
||||||
|
if json.get("is_leader").and_then(serde_json::Value::as_bool) == Some(true) {
|
||||||
|
return Some(LeaderInfo {
|
||||||
|
http_addr: cand.http_addr.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
any_reachable
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A successful join: the assigned id/role + the roster + the leader's
|
||||||
|
/// dial-able addresses + term.
|
||||||
|
struct Joined {
|
||||||
|
assigned_id: u16,
|
||||||
|
term: u64,
|
||||||
|
membership_version: u64,
|
||||||
|
leader_grpc_addr: String,
|
||||||
|
leader_region_id: u16,
|
||||||
|
members: Vec<MemberEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The outcome of one join attempt.
|
||||||
|
enum JoinAttempt {
|
||||||
|
Joined(Joined),
|
||||||
|
/// Not accepted (a non-leader seed, a held conf-change): re-discover.
|
||||||
|
RetargetOrRetry(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Join via the candidate over the HTTP `/cluster/join` verb — which wraps the
|
||||||
|
/// same leader-side logic the gRPC `JoinCluster` uses and is FORWARDED by a
|
||||||
|
/// non-leader, so the joiner never needs a peer's gRPC address for the join
|
||||||
|
/// itself (it learns the snapshot-source gRPC address from the returned roster).
|
||||||
|
/// Idempotent by name.
|
||||||
|
///
|
||||||
|
/// gRPC TLS is NOT used here (the HTTP gateway terminates its own TLS); the
|
||||||
|
/// snapshot fetch that follows dials the returned `leader_grpc_addr` with the
|
||||||
|
/// joiner's gRPC TLS posture.
|
||||||
|
fn join_via_leader(
|
||||||
|
leader: &LeaderInfo,
|
||||||
|
region: &str,
|
||||||
|
advertise_grpc: &str,
|
||||||
|
advertise_http: &str,
|
||||||
|
) -> Result<JoinAttempt> {
|
||||||
|
let client = reqwest::blocking::Client::builder()
|
||||||
|
.timeout(JOIN_RPC_TIMEOUT)
|
||||||
|
.build()
|
||||||
|
.map_err(|e| ServerError::Cluster(format!("seed-join: build join client: {e}")))?;
|
||||||
|
|
||||||
|
let url = super::forward::peer_url(&leader.http_addr, "/cluster/join");
|
||||||
|
let body = serde_json::json!({
|
||||||
|
"name": region,
|
||||||
|
"grpc_addr": advertise_grpc,
|
||||||
|
"http_addr": advertise_http,
|
||||||
|
});
|
||||||
|
let mut req = client.post(&url).json(&body);
|
||||||
|
if let Ok(key) = std::env::var("TIDAL_API_KEY") {
|
||||||
|
req = req.bearer_auth(key);
|
||||||
|
}
|
||||||
|
let resp = req
|
||||||
|
.send()
|
||||||
|
.map_err(|e| ServerError::Cluster(format!("seed-join: POST /cluster/join: {e}")))?;
|
||||||
|
let status = resp.status();
|
||||||
|
if !status.is_success() {
|
||||||
|
// A 503 (not leader / conf-change held) is RETRYABLE; surface the body.
|
||||||
|
let body = resp.text().unwrap_or_default();
|
||||||
|
return Ok(JoinAttempt::RetargetOrRetry(format!(
|
||||||
|
"/cluster/join returned {status}: {body}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let json: serde_json::Value = resp
|
||||||
|
.json()
|
||||||
|
.map_err(|e| ServerError::Cluster(format!("seed-join: /cluster/join body: {e}")))?;
|
||||||
|
let assigned_id = u16::try_from(json["assigned_id"].as_u64().unwrap_or(0)).unwrap_or(0);
|
||||||
|
let term = json["term"].as_u64().unwrap_or(0);
|
||||||
|
let membership_version = json["membership_version"].as_u64().unwrap_or(0);
|
||||||
|
|
||||||
|
// The HTTP /cluster/join body is intentionally lean (it does not echo the
|
||||||
|
// full roster). Fetch the full roster from /cluster/members on the same
|
||||||
|
// gateway (it serves the effective roster from any node) so the joiner can
|
||||||
|
// build its peer tables.
|
||||||
|
let members = fetch_roster(&client, &leader.http_addr)?;
|
||||||
|
// The snapshot SOURCE must be the CURRENT leader — not just any voter — so
|
||||||
|
// the post-install catch-up resumes from the live stream (a re-election may
|
||||||
|
// have moved leadership since the topology declared region 0 the leader). The
|
||||||
|
// gateway's /cluster/status/local names the current leader; resolve its gRPC
|
||||||
|
// address + region from the roster. Fall back to the lowest-id voter only if
|
||||||
|
// the leader is momentarily unknown (mid-election) — the install retries.
|
||||||
|
let (leader_grpc_addr, leader_region_id) =
|
||||||
|
current_leader_dial_target(&client, &leader.http_addr, &members)
|
||||||
|
.unwrap_or_else(|| leader_dial_target(&members));
|
||||||
|
|
||||||
|
Ok(JoinAttempt::Joined(Joined {
|
||||||
|
assigned_id,
|
||||||
|
term,
|
||||||
|
membership_version,
|
||||||
|
leader_grpc_addr,
|
||||||
|
leader_region_id,
|
||||||
|
members,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve the CURRENT leader's gRPC dial target from the gateway's
|
||||||
|
/// `/cluster/status/local` (the `leader` field names it) + the roster (resolves
|
||||||
|
/// its advertised gRPC address + id). `None` when the leader is unknown
|
||||||
|
/// (mid-election) or not in the roster — the caller falls back to a voter and the
|
||||||
|
/// install retries.
|
||||||
|
fn current_leader_dial_target(
|
||||||
|
client: &reqwest::blocking::Client,
|
||||||
|
gateway_http: &str,
|
||||||
|
members: &[MemberEntry],
|
||||||
|
) -> Option<(String, u16)> {
|
||||||
|
let url = super::forward::peer_url(gateway_http, "/cluster/status/local");
|
||||||
|
let mut req = client.get(&url);
|
||||||
|
if let Ok(key) = std::env::var("TIDAL_API_KEY") {
|
||||||
|
req = req.bearer_auth(key);
|
||||||
|
}
|
||||||
|
let json: serde_json::Value = req.send().ok()?.json().ok()?;
|
||||||
|
let leader_name = json.get("leader").and_then(serde_json::Value::as_str)?;
|
||||||
|
members
|
||||||
|
.iter()
|
||||||
|
.find(|m| m.name == leader_name && m.role != MemberRole::Removed)
|
||||||
|
.map(|m| (m.grpc_addr.clone(), m.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch the effective roster from `/cluster/members` (served from any node).
|
||||||
|
fn fetch_roster(client: &reqwest::blocking::Client, http_addr: &str) -> Result<Vec<MemberEntry>> {
|
||||||
|
let url = super::forward::peer_url(http_addr, "/cluster/members");
|
||||||
|
let mut req = client.get(&url);
|
||||||
|
if let Ok(key) = std::env::var("TIDAL_API_KEY") {
|
||||||
|
req = req.bearer_auth(key);
|
||||||
|
}
|
||||||
|
let resp = req
|
||||||
|
.send()
|
||||||
|
.map_err(|e| ServerError::Cluster(format!("seed-join: GET /cluster/members: {e}")))?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return Err(ServerError::Cluster(format!(
|
||||||
|
"seed-join: /cluster/members returned {}",
|
||||||
|
resp.status()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let json: serde_json::Value = resp
|
||||||
|
.json()
|
||||||
|
.map_err(|e| ServerError::Cluster(format!("seed-join: /cluster/members body: {e}")))?;
|
||||||
|
let arr = json["members"].as_array().ok_or_else(|| {
|
||||||
|
ServerError::Cluster("seed-join: /cluster/members has no members array".into())
|
||||||
|
})?;
|
||||||
|
let mut members = Vec::with_capacity(arr.len());
|
||||||
|
for m in arr {
|
||||||
|
let id = u16::try_from(m["id"].as_u64().unwrap_or(0)).unwrap_or(0);
|
||||||
|
let name = m["name"].as_str().unwrap_or_default().to_string();
|
||||||
|
let grpc_addr = m["grpc_addr"].as_str().unwrap_or_default().to_string();
|
||||||
|
let http_addr_m = m["http_addr"].as_str().unwrap_or_default().to_string();
|
||||||
|
let role = match m["role"].as_str() {
|
||||||
|
Some("learner") => MemberRole::Learner,
|
||||||
|
Some("removed") => MemberRole::Removed,
|
||||||
|
_ => MemberRole::Voter,
|
||||||
|
};
|
||||||
|
members.push(MemberEntry {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
grpc_addr,
|
||||||
|
http_addr: http_addr_m,
|
||||||
|
role,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if members.is_empty() {
|
||||||
|
return Err(ServerError::Cluster(
|
||||||
|
"seed-join: /cluster/members returned an empty roster".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(members)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The snapshot-fetch target: a current VOTER's advertised gRPC address + its
|
||||||
|
/// region id (the snapshot source is the leader; any voter serves it, and the
|
||||||
|
/// `FetchSnapshot` handler resolves its own shard regardless of the requested
|
||||||
|
/// id). Prefers the lowest-id voter for determinism.
|
||||||
|
fn leader_dial_target(members: &[MemberEntry]) -> (String, u16) {
|
||||||
|
members
|
||||||
|
.iter()
|
||||||
|
.filter(|m| m.role == MemberRole::Voter)
|
||||||
|
.min_by_key(|m| m.id)
|
||||||
|
.map(|m| (m.grpc_addr.clone(), m.id))
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adopt the discovered leadership term durably BEFORE pulling (§2.7
|
||||||
|
/// persist-before-act). A fresh joiner has no `election_state`; a restart-of-a-
|
||||||
|
/// joiner adopts only a HIGHER term (never regresses).
|
||||||
|
fn adopt_term(data_dir: &Path, term: u64) -> Result<()> {
|
||||||
|
let store = ElectionStore::new(data_dir);
|
||||||
|
let wal_exists = data_dir
|
||||||
|
.join("wal")
|
||||||
|
.read_dir()
|
||||||
|
.map(|mut it| it.next().is_some())
|
||||||
|
.unwrap_or(false);
|
||||||
|
let durable = match store.load(wal_exists) {
|
||||||
|
Ok(tidaldb::replication::BootState::Rejoin(h)) => h.current_term,
|
||||||
|
Ok(_) => 0,
|
||||||
|
Err(e) => {
|
||||||
|
return Err(ServerError::Cluster(format!(
|
||||||
|
"seed-join: refusing to adopt a term — corrupt election_state ({e}); a join \
|
||||||
|
does not restore term knowledge (the m11p4 corrupt-state rule stands, §2.5)"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if term > durable {
|
||||||
|
store
|
||||||
|
.persist(HardState {
|
||||||
|
current_term: term,
|
||||||
|
voted_for: None,
|
||||||
|
})
|
||||||
|
.map_err(|e| {
|
||||||
|
ServerError::Cluster(format!(
|
||||||
|
"seed-join: persist discovered term {term} (persist-before-act): {e}"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Synthesize the topology `RegionClusterState::new` consumes (§3.4): the
|
||||||
|
/// join-response roster as `regions:` (in id order so the positional `RegionId`
|
||||||
|
/// MATCHES the assigned member id — the seam every durable id depends on), this
|
||||||
|
/// node's `--region` carried, the local file's knob blocks copied verbatim
|
||||||
|
/// (§3.5), this node's `metrics_addr` from `--metrics`.
|
||||||
|
///
|
||||||
|
/// Removed tombstones are EXCLUDED (they are not live peers) — but excluding a
|
||||||
|
/// tombstone whose id is below a live member's would shift positional ids. The
|
||||||
|
/// 1:1 region↔shard mapping (`shard_of_region`) requires the positional index to
|
||||||
|
/// equal the member id, so we keep the roster id-DENSE by emitting a placeholder
|
||||||
|
/// region for each burned id below the max live id. A placeholder declares the
|
||||||
|
/// tombstone's name + addresses but is never dialed (it is excluded from the
|
||||||
|
/// live peer set by the membership view's `from_record` once the WAL opens, and
|
||||||
|
/// the era-0 synthesized view treats it as present-but-addressless).
|
||||||
|
fn synthesize_topology(
|
||||||
|
input: &SeedJoinInput<'_>,
|
||||||
|
members: &[MemberEntry],
|
||||||
|
current_leader_region: Option<u16>,
|
||||||
|
) -> Result<TopologySpec> {
|
||||||
|
// The roster's id range. RegionId = positional index, and
|
||||||
|
// `shard_of_region(RegionId(n)) = ShardId(n)`, so the regions list must be
|
||||||
|
// dense from 0..=max_id with each member at its own id index.
|
||||||
|
let max_id = members.iter().map(|m| m.id).max().unwrap_or(0);
|
||||||
|
let mut by_id: std::collections::HashMap<u16, &MemberEntry> = std::collections::HashMap::new();
|
||||||
|
for m in members {
|
||||||
|
by_id.insert(m.id, m);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut regions: Vec<RegionSpec> = Vec::with_capacity(usize::from(max_id) + 1);
|
||||||
|
for id in 0..=max_id {
|
||||||
|
if let Some(m) = by_id.get(&id) {
|
||||||
|
// This node's own entry carries its real advertised addresses (the
|
||||||
|
// roster already holds them from the join, but be explicit for self).
|
||||||
|
let is_self = m.name == input.region;
|
||||||
|
let grpc = if is_self {
|
||||||
|
input.advertise_grpc.to_string()
|
||||||
|
} else {
|
||||||
|
m.grpc_addr.clone()
|
||||||
|
};
|
||||||
|
let http = if is_self {
|
||||||
|
input.advertise_http.to_string()
|
||||||
|
} else {
|
||||||
|
m.http_addr.clone()
|
||||||
|
};
|
||||||
|
regions.push(RegionSpec {
|
||||||
|
name: m.name.clone(),
|
||||||
|
grpc_addr: Some(grpc),
|
||||||
|
grpc_bind: None,
|
||||||
|
http_addr: Some(http),
|
||||||
|
grpc_tls: self_tls_spec(input.knobs, &m.name),
|
||||||
|
metrics_addr: if is_self {
|
||||||
|
input.metrics.map(str::to_string)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// A burned id with no member entry at all (a gap that should not
|
||||||
|
// happen — ids are assigned densely as max+1). Emit a placeholder so
|
||||||
|
// the positional index stays aligned; it is never a live peer.
|
||||||
|
regions.push(RegionSpec {
|
||||||
|
name: format!("__burned-{id}"),
|
||||||
|
grpc_addr: Some(format!("0.0.0.0:{}", 1u16.wrapping_add(id))),
|
||||||
|
grpc_bind: None,
|
||||||
|
http_addr: Some(format!("http://0.0.0.0:{}", 1u16.wrapping_add(id))),
|
||||||
|
grpc_tls: None,
|
||||||
|
metrics_addr: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The leader for the synthesized topology: the CURRENT leader the join
|
||||||
|
// resolved (so the `needed=false` boot self-heal pulls from the live stream,
|
||||||
|
// not a stale lowest-voter — the catch-up targets `shard_of_region(leader)`).
|
||||||
|
// Fall back to the lowest-id voter when the join could not resolve a leader
|
||||||
|
// (mid-election). A joiner is never the term-0 leader, so it must not name
|
||||||
|
// itself here; the durable election state + heartbeats correct the hint.
|
||||||
|
let leader = current_leader_region
|
||||||
|
.and_then(|id| {
|
||||||
|
members
|
||||||
|
.iter()
|
||||||
|
.find(|m| m.id == id && m.role != MemberRole::Removed)
|
||||||
|
.map(|m| m.name.clone())
|
||||||
|
})
|
||||||
|
.filter(|name| name != input.region)
|
||||||
|
.or_else(|| {
|
||||||
|
members
|
||||||
|
.iter()
|
||||||
|
.filter(|m| m.role == MemberRole::Voter)
|
||||||
|
.min_by_key(|m| m.id)
|
||||||
|
.map(|m| m.name.clone())
|
||||||
|
})
|
||||||
|
.ok_or_else(|| {
|
||||||
|
ServerError::Cluster("seed-join: the join roster has no voter to name as leader".into())
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Carry the local file's knob blocks verbatim (§3.5).
|
||||||
|
Ok(TopologySpec {
|
||||||
|
regions,
|
||||||
|
leader,
|
||||||
|
write_workers: input.knobs.write_workers,
|
||||||
|
timeouts: clone_timeouts(&input.knobs.timeouts),
|
||||||
|
replication: clone_replication(&input.knobs.replication),
|
||||||
|
wal: clone_wal(&input.knobs.wal),
|
||||||
|
election: clone_election(&input.knobs.election),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This region's TLS spec from the knob file, when it names this region (the
|
||||||
|
/// joiner's own region is NOT in the knob file in the k8s shared-ConfigMap case,
|
||||||
|
/// so this is `None` there — plaintext, the loopback/VPC default).
|
||||||
|
fn self_tls_spec(knobs: &TopologySpec, name: &str) -> Option<GrpcTlsSpec> {
|
||||||
|
knobs
|
||||||
|
.regions
|
||||||
|
.iter()
|
||||||
|
.find(|r| r.name == name)
|
||||||
|
.and_then(|r| r.grpc_tls.as_ref())
|
||||||
|
.map(|t| GrpcTlsSpec {
|
||||||
|
ca_cert: t.ca_cert.clone(),
|
||||||
|
server_cert: t.server_cert.clone(),
|
||||||
|
server_key: t.server_key.clone(),
|
||||||
|
client_cert: t.client_cert.clone(),
|
||||||
|
client_key: t.client_key.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// The knob blocks have no `Clone`; rebuild them field-by-field from the loaded
|
||||||
|
// file so the synthesized topology carries the operator's exact knobs (§3.5).
|
||||||
|
const fn clone_timeouts(t: &TimeoutsSpec) -> TimeoutsSpec {
|
||||||
|
TimeoutsSpec {
|
||||||
|
broadcast_peer_secs: t.broadcast_peer_secs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clone_replication(r: &ReplicationSpec) -> ReplicationSpec {
|
||||||
|
ReplicationSpec {
|
||||||
|
batch_max_events: r.batch_max_events,
|
||||||
|
window: r.window,
|
||||||
|
retry_ms: r.retry_ms,
|
||||||
|
ack: r.ack.clone(),
|
||||||
|
quorum_timeout_ms: r.quorum_timeout_ms,
|
||||||
|
catchup_retry_ms: r.catchup_retry_ms,
|
||||||
|
snapshot_artifact_ttl_ms: r.snapshot_artifact_ttl_ms,
|
||||||
|
reseed_self_restart: r.reseed_self_restart,
|
||||||
|
learner_promote_lag: r.learner_promote_lag,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn clone_wal(w: &WalSpec) -> WalSpec {
|
||||||
|
WalSpec {
|
||||||
|
batch_size: w.batch_size,
|
||||||
|
batch_timeout_ms: w.batch_timeout_ms,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn clone_election(e: &ElectionSpec) -> ElectionSpec {
|
||||||
|
ElectionSpec {
|
||||||
|
heartbeat_interval_ms: e.heartbeat_interval_ms,
|
||||||
|
election_timeout_min_ms: e.election_timeout_min_ms,
|
||||||
|
election_timeout_max_ms: e.election_timeout_max_ms,
|
||||||
|
leader_lease_ms: e.leader_lease_ms,
|
||||||
|
auto_election: e.auto_election,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn knobs_with(ack: &str) -> TopologySpec {
|
||||||
|
TopologySpec {
|
||||||
|
// The knob file's regions are IGNORED for the roster — a single
|
||||||
|
// declared region proves we do not read them.
|
||||||
|
regions: vec![RegionSpec {
|
||||||
|
name: "us-east".into(),
|
||||||
|
grpc_addr: Some("127.0.0.1:9000".into()),
|
||||||
|
grpc_bind: None,
|
||||||
|
http_addr: Some("127.0.0.1:9001".into()),
|
||||||
|
grpc_tls: None,
|
||||||
|
metrics_addr: None,
|
||||||
|
}],
|
||||||
|
leader: "us-east".into(),
|
||||||
|
write_workers: None,
|
||||||
|
timeouts: TimeoutsSpec::default(),
|
||||||
|
replication: ReplicationSpec {
|
||||||
|
ack: Some(ack.to_string()),
|
||||||
|
quorum_timeout_ms: Some(1500),
|
||||||
|
..ReplicationSpec::default()
|
||||||
|
},
|
||||||
|
wal: WalSpec::default(),
|
||||||
|
election: ElectionSpec::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn member(id: u16, name: &str, role: MemberRole) -> MemberEntry {
|
||||||
|
MemberEntry {
|
||||||
|
id,
|
||||||
|
name: name.to_string(),
|
||||||
|
grpc_addr: format!("{name}.svc:9500"),
|
||||||
|
http_addr: format!("http://{name}.svc:9501"),
|
||||||
|
role,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The synthesized topology carries the join roster as `regions:` (id-dense,
|
||||||
|
/// positional index == member id), this node's advertised addresses for self,
|
||||||
|
/// the knob file's behavioral blocks (NOT its regions), and the metrics flag.
|
||||||
|
#[test]
|
||||||
|
fn synthesize_topology_uses_roster_and_local_knobs() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let knobs = knobs_with("quorum");
|
||||||
|
let members = vec![
|
||||||
|
member(0, "us-east", MemberRole::Voter),
|
||||||
|
member(1, "eu-west", MemberRole::Voter),
|
||||||
|
member(3, "joiner", MemberRole::Learner), // id 2 was burned
|
||||||
|
];
|
||||||
|
let input = SeedJoinInput {
|
||||||
|
seeds: &["http://us-east.svc:9501".to_string()],
|
||||||
|
knobs: &knobs,
|
||||||
|
region: "joiner",
|
||||||
|
advertise_grpc: "joiner.real:9500",
|
||||||
|
advertise_http: "http://joiner.real:9501",
|
||||||
|
metrics: Some("0.0.0.0:9091"),
|
||||||
|
data_dir: tmp.path(),
|
||||||
|
api_key: None,
|
||||||
|
};
|
||||||
|
// Name the current leader region 0 (us-east) explicitly.
|
||||||
|
let synth = synthesize_topology(&input, &members, Some(0)).unwrap();
|
||||||
|
|
||||||
|
// The regions list is id-dense 0..=3 (a burned id 2 gets a placeholder),
|
||||||
|
// so the positional RegionId equals the assigned member id.
|
||||||
|
assert_eq!(synth.regions.len(), 4);
|
||||||
|
assert_eq!(synth.regions[0].name, "us-east");
|
||||||
|
assert_eq!(synth.regions[1].name, "eu-west");
|
||||||
|
assert!(
|
||||||
|
synth.regions[2].name.starts_with("__burned-"),
|
||||||
|
"id 2 burned"
|
||||||
|
);
|
||||||
|
assert_eq!(synth.regions[3].name, "joiner");
|
||||||
|
// Self carries its REAL advertised addresses + the --metrics bind.
|
||||||
|
assert_eq!(
|
||||||
|
synth.regions[3].grpc_addr.as_deref(),
|
||||||
|
Some("joiner.real:9500")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
synth.regions[3].http_addr.as_deref(),
|
||||||
|
Some("http://joiner.real:9501")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
synth.regions[3].metrics_addr.as_deref(),
|
||||||
|
Some("0.0.0.0:9091")
|
||||||
|
);
|
||||||
|
// The knob file's behavioral block is carried, NOT its single region.
|
||||||
|
assert_eq!(synth.replication.ack.as_deref(), Some("quorum"));
|
||||||
|
assert_eq!(synth.replication.quorum_timeout_ms, Some(1500));
|
||||||
|
// The leader is the lowest-id voter (a joiner never names itself).
|
||||||
|
assert_eq!(synth.leader, "us-east");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `discovery_candidates` lists seeds first, then the cache's live members'
|
||||||
|
/// HTTP addresses, deduplicated.
|
||||||
|
#[test]
|
||||||
|
fn discovery_candidates_merges_seeds_and_cache() {
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let store = MembershipStore::new(tmp.path());
|
||||||
|
store
|
||||||
|
.persist(&MembershipSnapshot {
|
||||||
|
version: 2,
|
||||||
|
term: 1,
|
||||||
|
members: vec![
|
||||||
|
member(0, "us-east", MemberRole::Voter),
|
||||||
|
member(1, "eu-west", MemberRole::Voter),
|
||||||
|
member(2, "gone", MemberRole::Removed),
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let seeds = vec![
|
||||||
|
"http://seed-a:9501".to_string(),
|
||||||
|
"http://us-east.svc:9501".to_string(),
|
||||||
|
];
|
||||||
|
let cands = discovery_candidates(&seeds, &store);
|
||||||
|
let addrs: Vec<&str> = cands.iter().map(|c| c.http_addr.as_str()).collect();
|
||||||
|
// Seeds first.
|
||||||
|
assert_eq!(addrs[0], "http://seed-a:9501");
|
||||||
|
// us-east is in both; it appears once (seed wins position).
|
||||||
|
assert_eq!(
|
||||||
|
addrs
|
||||||
|
.iter()
|
||||||
|
.filter(|a| **a == "http://us-east.svc:9501")
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
// eu-west comes from the cache.
|
||||||
|
assert!(addrs.contains(&"http://eu-west.svc:9501"));
|
||||||
|
// The removed tombstone is excluded.
|
||||||
|
assert!(!addrs.iter().any(|a| a.contains("gone")));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `leader_dial_target` is the lowest-id voter's gRPC address (the snapshot
|
||||||
|
/// source); learners/tombstones are not dial targets.
|
||||||
|
#[test]
|
||||||
|
fn leader_dial_target_is_lowest_id_voter() {
|
||||||
|
let members = vec![
|
||||||
|
member(0, "us-east", MemberRole::Voter),
|
||||||
|
member(1, "eu-west", MemberRole::Voter),
|
||||||
|
member(3, "joiner", MemberRole::Learner),
|
||||||
|
];
|
||||||
|
let (grpc, id) = leader_dial_target(&members);
|
||||||
|
assert_eq!(grpc, "us-east.svc:9500");
|
||||||
|
assert_eq!(id, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
1148
tidal-server/src/cluster/membership.rs
Normal file
1148
tidal-server/src/cluster/membership.rs
Normal file
File diff suppressed because it is too large
Load Diff
@ -35,8 +35,23 @@
|
|||||||
|
|
||||||
pub(crate) mod election_driver;
|
pub(crate) mod election_driver;
|
||||||
pub(crate) mod forward;
|
pub(crate) mod forward;
|
||||||
|
/// Seed-join boot (m11p5 §3.4–§3.6): a node not declared in the local topology
|
||||||
|
/// joins an existing cluster by contacting a `--seed`.
|
||||||
|
///
|
||||||
|
/// Public so the binary's `run_seed_join_cluster` can invoke `seed_join_boot`
|
||||||
|
/// before `RegionClusterState::new`.
|
||||||
|
pub mod join_boot;
|
||||||
|
/// The membership runtime (m11p5 §3.1–§3.3): effective roster, the one fenced
|
||||||
|
/// apply path, conf-change gates, and leader-side join/remove planning.
|
||||||
|
pub(crate) mod membership;
|
||||||
pub(crate) mod node;
|
pub(crate) mod node;
|
||||||
|
/// Boot-time snapshot install + swap-recovery (m11p5 §2.2–§2.7).
|
||||||
|
///
|
||||||
|
/// Public so the binary's `run_region_cluster` can invoke `run_boot_install`
|
||||||
|
/// before `RegionClusterState::new`.
|
||||||
|
pub mod reseed;
|
||||||
pub(crate) mod routes;
|
pub(crate) mod routes;
|
||||||
|
pub(crate) mod snapshot;
|
||||||
mod state;
|
mod state;
|
||||||
mod topology;
|
mod topology;
|
||||||
mod transport;
|
mod transport;
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
1376
tidal-server/src/cluster/reseed.rs
Normal file
1376
tidal-server/src/cluster/reseed.rs
Normal file
File diff suppressed because it is too large
Load Diff
779
tidal-server/src/cluster/snapshot.rs
Normal file
779
tidal-server/src/cluster/snapshot.rs
Normal file
@ -0,0 +1,779 @@
|
|||||||
|
//! `NodeSnapshotSource`: the leader-side `FetchSnapshot` source (m11p5 §2).
|
||||||
|
//!
|
||||||
|
//! A joiner with an empty data dir — or a follower behind a leader whose WAL
|
||||||
|
//! has compacted past its frontier — installs a staged whole-database snapshot
|
||||||
|
//! before resuming the catch-up stream. This is the source the gRPC
|
||||||
|
//! `FetchSnapshot` handler streams from: it stages (or reuses) the artifact,
|
||||||
|
//! hands back the manifest, and holds a WAL retention pin so the joiner's resume
|
||||||
|
//! range survives compaction.
|
||||||
|
//!
|
||||||
|
//! # What it owns vs. what the engine owns
|
||||||
|
//!
|
||||||
|
//! The engine ([`TidalDb::stage_snapshot`]) owns the consistency-critical half:
|
||||||
|
//! it PINS WAL retention at the captured tail BEFORE the copy (§2.1 — a pin
|
||||||
|
//! installed after staging cannot protect the copy window from the 30 s
|
||||||
|
//! checkpoint thread), runs `create_backup_with` (signal-write quiesce, ledger +
|
||||||
|
//! replication-HWM checkpoint, fjall flush, exclusion-aware copy, WAL marker
|
||||||
|
//! into the copy), and returns the artifact's seq. This source owns the
|
||||||
|
//! POLICY half: single-flight staging, artifact REUSE while the live WAL still
|
||||||
|
//! covers `artifact_seq + 1`, TTL-from-last-fetch, active-fetch accounting, and
|
||||||
|
//! the hard-cap force-drop that stops a dead joiner from pinning compaction
|
||||||
|
//! forever.
|
||||||
|
//!
|
||||||
|
//! # The pin lifecycle (§2.1)
|
||||||
|
//!
|
||||||
|
//! The pin is taken when an artifact is staged and held until the artifact is
|
||||||
|
//! reaped. An artifact is reaped only when ALL of these hold — no active fetch
|
||||||
|
//! holds it (`active == 0`), its TTL (from the LAST fetch completion) has
|
||||||
|
//! expired, AND a NEWER artifact is needed (the live WAL no longer covers
|
||||||
|
//! `artifact_seq + 1`, so a fresh stage must replace it) — OR the hard cap (4×
|
||||||
|
//! TTL since the last fetch) elapses, a force-drop with a loud WARN + metric:
|
||||||
|
//! the safety valve against a never-releasing consumer.
|
||||||
|
//!
|
||||||
|
//! [`TidalDb::stage_snapshot`]: tidaldb::TidalDb::stage_snapshot
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{
|
||||||
|
Arc, Mutex, Weak,
|
||||||
|
atomic::{AtomicU64, Ordering},
|
||||||
|
},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
use tidal_net::sources::{SnapshotSource, SnapshotStageError, SnapshotStaging};
|
||||||
|
use tidaldb::{TidalDb, db::metrics::cluster::ClusterMetrics, replication::RESEED_REQUIRED_MARKER};
|
||||||
|
|
||||||
|
/// The top-level data-dir entries the snapshot copy must skip (§2.3): the
|
||||||
|
/// staging area itself (else the copy recurses into its own destination) plus
|
||||||
|
/// the node-identity / node-local files that must NOT travel to another node.
|
||||||
|
/// `tidaldb.lock` is already skipped by the engine's copy unconditionally.
|
||||||
|
///
|
||||||
|
/// Centralized here as the ONE list the source passes to `stage_snapshot`, so
|
||||||
|
/// the exclusion set is named in exactly one place on the server side (the
|
||||||
|
/// reseed-marker name itself is the engine's `RESEED_REQUIRED_MARKER` constant,
|
||||||
|
/// so the producer and the install path can never drift).
|
||||||
|
fn snapshot_exclusions() -> Vec<&'static str> {
|
||||||
|
vec![
|
||||||
|
SNAPSHOTS_DIR,
|
||||||
|
"election_state",
|
||||||
|
"stream_baseline",
|
||||||
|
"membership",
|
||||||
|
RESEED_REQUIRED_MARKER,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The staging directory name, a top-level entry under the data dir (so it
|
||||||
|
/// stays on the same PVC, §2.3). Excluded from the copy by name.
|
||||||
|
const SNAPSHOTS_DIR: &str = "snapshots";
|
||||||
|
|
||||||
|
/// A staged artifact and its pin/consumer bookkeeping.
|
||||||
|
struct CachedArtifact {
|
||||||
|
/// The artifact's WAL seq (the frontier a joiner resumes from `+ 1`).
|
||||||
|
seq: u64,
|
||||||
|
/// The staging directory the manifest's relative paths resolve against.
|
||||||
|
root: PathBuf,
|
||||||
|
/// `(relative_path, size, blake3)` per file — computed once at staging,
|
||||||
|
/// forwarded verbatim on the wire, verified by the installing puller.
|
||||||
|
manifest: Vec<(String, u64, [u8; 32])>,
|
||||||
|
/// Number of in-flight `FetchSnapshot` streams holding this artifact. The
|
||||||
|
/// pin (and the artifact) cannot be reaped while this is non-zero.
|
||||||
|
active: u64,
|
||||||
|
/// When the last fetch completed (`release`d) — the TTL anchor. Seeded to
|
||||||
|
/// the stage time so a never-fetched artifact still ages out.
|
||||||
|
last_fetch: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mutable state behind the source's lock.
|
||||||
|
struct State {
|
||||||
|
/// The single cached artifact (single-flight: at most one at a time).
|
||||||
|
artifact: Option<CachedArtifact>,
|
||||||
|
/// `true` while a `stage_snapshot` is mid-flight — single-flight at the
|
||||||
|
/// source level so a second `stage()` returns `Busy` immediately rather
|
||||||
|
/// than blocking on the lock or racing the engine CAS.
|
||||||
|
staging: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The leader-side `FetchSnapshot` source. A `Weak<TidalDb>` (like
|
||||||
|
/// `NodeSegmentSource`) so the transport can never keep the database alive past
|
||||||
|
/// shutdown.
|
||||||
|
pub struct NodeSnapshotSource {
|
||||||
|
db: Weak<TidalDb>,
|
||||||
|
/// The node's data dir; staging lives at `<data_dir>/snapshots/`.
|
||||||
|
data_dir: PathBuf,
|
||||||
|
/// This node's outbound stream baseline (shared `Arc` with
|
||||||
|
/// [`NodeSegmentSource`](super::node) and the node), in the CURRENT
|
||||||
|
/// leadership's stream numbering. The `needed` decision is baseline-aware:
|
||||||
|
/// the `StreamSegments` clamp never serves at or below it, so a puller
|
||||||
|
/// resuming from `from_seqno <= baseline` genuinely needs a snapshot even
|
||||||
|
/// when the raw WAL still contains that seqno (§2 / §2.6).
|
||||||
|
stream_baseline: Arc<AtomicU64>,
|
||||||
|
/// Artifact reuse window, from the LAST fetch completion (§2.1). Never
|
||||||
|
/// unpins an active consumer.
|
||||||
|
ttl: Duration,
|
||||||
|
/// Hard cap on the pin's lifetime since the last fetch (4× TTL): force-drop
|
||||||
|
/// past it so a dead joiner cannot freeze compaction forever.
|
||||||
|
hard_cap: Duration,
|
||||||
|
metrics: Arc<ClusterMetrics>,
|
||||||
|
state: Mutex<State>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NodeSnapshotSource {
|
||||||
|
/// Build the source over a weak db handle. Deletes any stale `snapshots/`
|
||||||
|
/// entries from a previous process at construction (boot cleanup): a staged
|
||||||
|
/// dir from a crashed prior run holds no live pin and must not be reused.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(
|
||||||
|
db: &Arc<TidalDb>,
|
||||||
|
data_dir: PathBuf,
|
||||||
|
stream_baseline: Arc<AtomicU64>,
|
||||||
|
ttl: Duration,
|
||||||
|
metrics: Arc<ClusterMetrics>,
|
||||||
|
) -> Self {
|
||||||
|
let staging_root = data_dir.join(SNAPSHOTS_DIR);
|
||||||
|
// Boot cleanup: a `snapshots/` left by a previous process is stale (its
|
||||||
|
// pin died with that process). Remove it so a fresh stage starts clean.
|
||||||
|
// A missing dir is the common case (NotFound); any other error is
|
||||||
|
// non-fatal — a leftover dir wastes disk but the next stage writes a
|
||||||
|
// fresh `staged-<seq>` sibling and the reuse check never trusts an
|
||||||
|
// artifact it did not itself stage this run.
|
||||||
|
if let Err(e) = std::fs::remove_dir_all(&staging_root)
|
||||||
|
&& e.kind() != std::io::ErrorKind::NotFound
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
path = %staging_root.display(),
|
||||||
|
error = %e,
|
||||||
|
"could not remove stale snapshot staging dir at boot; \
|
||||||
|
a fresh stage will write a new artifact alongside it"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
db: Arc::downgrade(db),
|
||||||
|
data_dir,
|
||||||
|
stream_baseline,
|
||||||
|
// The hard cap is 4× TTL (design §2.1): a comfortable multiple of a
|
||||||
|
// healthy fetch so only a truly stuck consumer trips it.
|
||||||
|
hard_cap: ttl.saturating_mul(4),
|
||||||
|
ttl,
|
||||||
|
metrics,
|
||||||
|
state: Mutex::new(State {
|
||||||
|
artifact: None,
|
||||||
|
staging: false,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The staging dir for an artifact at `seq`: `<data_dir>/snapshots/staged-<seq>/`.
|
||||||
|
fn staged_dir(&self, seq: u64) -> PathBuf {
|
||||||
|
self.data_dir
|
||||||
|
.join(SNAPSHOTS_DIR)
|
||||||
|
.join(format!("staged-{seq}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the live WAL can still serve a puller resuming from `from_seqno`
|
||||||
|
/// (no snapshot needed). True ONLY when `from_seqno` falls inside this WAL's
|
||||||
|
/// servable window `[earliest_servable, last_wal_seq + 1]`.
|
||||||
|
///
|
||||||
|
/// # Why the UPPER bound is load-bearing (m11p5 §2.4, reseed correctness)
|
||||||
|
///
|
||||||
|
/// The lower bound alone (`from_seqno >= earliest`) is the "behind a
|
||||||
|
/// compacted leader" case: a frontier below the earliest on-disk segment
|
||||||
|
/// needs a snapshot. But a frontier ABOVE `last_wal_seq + 1` is just as
|
||||||
|
/// unservable — and far more dangerous, because a naive `from_seqno >=
|
||||||
|
/// earliest` answers `true` for it (any large seqno is `>= 1`).
|
||||||
|
///
|
||||||
|
/// That is exactly the DIVERGENT-node reseed shape: a quarantined ex-leader
|
||||||
|
/// latches its marker at `from_seqno = divergent_frontier + 1`, a seqno in
|
||||||
|
/// the OLD leadership's stream numbering. The new elected leader's stream is
|
||||||
|
/// a DIFFERENT numbering whose tail is typically far below that value. If
|
||||||
|
/// `wal_covers` returned `true` here, the source would answer
|
||||||
|
/// `needed=false`, the reseed boot would CLEAR the marker, reopen the
|
||||||
|
/// divergent data dir, and re-quarantine — forever (the node can never
|
||||||
|
/// self-heal). A `from_seqno` past this WAL's own tail cannot be a position
|
||||||
|
/// in this WAL's stream, so it is a foreign/old numbering ⇒ a snapshot is
|
||||||
|
/// required to re-baseline the puller onto this leader's stream.
|
||||||
|
///
|
||||||
|
/// `last_wal_seq + 1` (not `last_wal_seq`) is the upper bound because a
|
||||||
|
/// fully-caught-up puller legitimately resumes at `tail + 1` (nothing to
|
||||||
|
/// stream; `StreamSegments` returns complete). Anything strictly above that
|
||||||
|
/// is ahead of this log.
|
||||||
|
///
|
||||||
|
/// # Why the BASELINE lower bound is load-bearing (m11p5 §2 / §2.6)
|
||||||
|
///
|
||||||
|
/// The raw earliest-servable seq is NOT the true floor of what
|
||||||
|
/// `StreamSegments` will serve: that handler clamps its start to
|
||||||
|
/// `max(from_seqno, baseline + 1)` — seqnos at or below `stream_baseline`
|
||||||
|
/// are pre-stream history it NEVER serves (a promoted leader's
|
||||||
|
/// pre-promotion WAL). So a `from_seqno <= stream_baseline` answer of
|
||||||
|
/// "the WAL still covers it" is a lie: the stream clamp jumps past that
|
||||||
|
/// range, the puller's hole is never filled, and a marker boot that trusts
|
||||||
|
/// `needed=false` here CLEARS the marker, reopens the behind/divergent data
|
||||||
|
/// dir, and re-fails — looping the marker boot forever. The fix per the
|
||||||
|
/// design: `needed = from_seqno <= stream_baseline OR from_seqno < earliest`
|
||||||
|
/// (plus the upper-bound divergence guard). At or below the baseline ⇒ a
|
||||||
|
/// snapshot re-baselines the puller onto this leader's stream.
|
||||||
|
fn wal_covers(db: &TidalDb, baseline: u64, from_seqno: u64) -> bool {
|
||||||
|
// At or below the stream baseline the StreamSegments clamp never serves
|
||||||
|
// this seqno: a snapshot is required regardless of what the raw WAL
|
||||||
|
// still physically contains.
|
||||||
|
if from_seqno <= baseline {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match db.earliest_servable_seq() {
|
||||||
|
Ok(earliest) => {
|
||||||
|
let resume_ceiling = db.last_wal_seq().saturating_add(1);
|
||||||
|
from_seqno >= earliest && from_seqno <= resume_ceiling
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
// A format-unknown / unreadable log can never serve the range →
|
||||||
|
// a snapshot IS needed (conservative: stage rather than wrongly
|
||||||
|
// claim the WAL covers it).
|
||||||
|
tracing::warn!(
|
||||||
|
error = %e,
|
||||||
|
"earliest_servable_seq failed; treating as snapshot-required"
|
||||||
|
);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a cached artifact at `artifact_seq` is still reusable: the live
|
||||||
|
/// WAL must still cover `artifact_seq + 1` (the joiner resumes the stream
|
||||||
|
/// there — if that seq was compacted away, the artifact is too old and a
|
||||||
|
/// fresh stage is required).
|
||||||
|
fn artifact_reusable(db: &TidalDb, baseline: u64, artifact_seq: u64) -> bool {
|
||||||
|
let resume_from = artifact_seq.saturating_add(1);
|
||||||
|
Self::wal_covers(db, baseline, resume_from)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current stream baseline (the `StreamSegments` clamp floor).
|
||||||
|
fn baseline(&self) -> u64 {
|
||||||
|
self.stream_baseline.load(Ordering::Acquire)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build the manifest by walking `root`: BLAKE3 each file, relative path,
|
||||||
|
/// size. Mirrors the engine's copy: directories are descended, regular
|
||||||
|
/// files hashed.
|
||||||
|
fn build_manifest(root: &std::path::Path) -> Result<Vec<(String, u64, [u8; 32])>, String> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
Self::walk_manifest(root, root, &mut out)?;
|
||||||
|
// Deterministic order (the wire does not require it, but a stable
|
||||||
|
// manifest makes the artifact's hash set reproducible for tests/debug).
|
||||||
|
out.sort_by(|a, b| a.0.cmp(&b.0));
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk_manifest(
|
||||||
|
root: &std::path::Path,
|
||||||
|
dir: &std::path::Path,
|
||||||
|
out: &mut Vec<(String, u64, [u8; 32])>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let entries = std::fs::read_dir(dir)
|
||||||
|
.map_err(|e| format!("read staged dir {}: {e}", dir.display()))?;
|
||||||
|
for entry in entries {
|
||||||
|
let entry = entry.map_err(|e| format!("read staged entry: {e}"))?;
|
||||||
|
let path = entry.path();
|
||||||
|
let file_type = entry
|
||||||
|
.file_type()
|
||||||
|
.map_err(|e| format!("file_type {}: {e}", path.display()))?;
|
||||||
|
if file_type.is_dir() {
|
||||||
|
Self::walk_manifest(root, &path, out)?;
|
||||||
|
} else if file_type.is_file() {
|
||||||
|
let bytes = std::fs::read(&path)
|
||||||
|
.map_err(|e| format!("read staged file {}: {e}", path.display()))?;
|
||||||
|
let rel = path
|
||||||
|
.strip_prefix(root)
|
||||||
|
.map_err(|e| format!("relativize {}: {e}", path.display()))?
|
||||||
|
.to_string_lossy()
|
||||||
|
.replace('\\', "/"); // forward slashes on the wire
|
||||||
|
let hash = *blake3::hash(&bytes).as_bytes();
|
||||||
|
let size = bytes.len() as u64;
|
||||||
|
out.push((rel, size, hash));
|
||||||
|
}
|
||||||
|
// Symlinks / specials: skipped, same as the engine copy.
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reap the artifact at `seq`: release the engine's pin, delete its staged
|
||||||
|
/// dir, clear the gauge. Idempotent on the directory (a missing dir is fine).
|
||||||
|
fn reap(&self, db: &TidalDb, dir: &std::path::Path) {
|
||||||
|
db.unpin_wal_retention();
|
||||||
|
if let Err(e) = std::fs::remove_dir_all(dir)
|
||||||
|
&& e.kind() != std::io::ErrorKind::NotFound
|
||||||
|
{
|
||||||
|
tracing::warn!(
|
||||||
|
path = %dir.display(),
|
||||||
|
error = %e,
|
||||||
|
"could not delete reaped snapshot artifact; disk may leak until \
|
||||||
|
the next boot cleanup"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.metrics.set_snapshot_staged(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The outcome of the locked cache decision: hand back a warm artifact, refuse
|
||||||
|
/// retryable, or go stage a fresh one (lock released).
|
||||||
|
enum Decision {
|
||||||
|
/// Reuse a warm artifact (already active-counted + gauged under the lock).
|
||||||
|
Reuse(SnapshotStaging),
|
||||||
|
/// A stage is already mid-flight: refuse retryable.
|
||||||
|
Busy,
|
||||||
|
/// No reusable artifact; the caller claimed the single-flight slot and must
|
||||||
|
/// stage outside the lock.
|
||||||
|
Stage,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NodeSnapshotSource {
|
||||||
|
/// The locked half of `stage`: reap a stale/force-droppable artifact, then
|
||||||
|
/// either reuse a still-good one, refuse `Busy`, or claim the single-flight
|
||||||
|
/// slot. NEVER stages under the lock (staging is slow; a second caller must
|
||||||
|
/// get `Busy`, not block).
|
||||||
|
fn decide(&self, db: &TidalDb) -> Decision {
|
||||||
|
let baseline = self.baseline();
|
||||||
|
let mut st = self
|
||||||
|
.state
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
|
||||||
|
// Opportunistically reap a stale/force-droppable artifact so a reuse
|
||||||
|
// decision never hands back a too-old artifact.
|
||||||
|
if let Some(art) = &st.artifact {
|
||||||
|
let age = art.last_fetch.elapsed();
|
||||||
|
let reusable = Self::artifact_reusable(db, baseline, art.seq);
|
||||||
|
let hard_capped = art.active == 0 && age >= self.hard_cap;
|
||||||
|
let ttl_expired_idle = art.active == 0 && age >= self.ttl;
|
||||||
|
if hard_capped {
|
||||||
|
// A consumer never released and the pin outlived the hard cap:
|
||||||
|
// force-drop, loud, so compaction is never frozen by a dead
|
||||||
|
// joiner. (active==0 here, so no live stream is cut.)
|
||||||
|
tracing::warn!(
|
||||||
|
artifact_seq = art.seq,
|
||||||
|
age_ms = age.as_millis(),
|
||||||
|
"force-dropping a staged snapshot artifact whose retention pin \
|
||||||
|
outlived the hard cap (a consumer never released)"
|
||||||
|
);
|
||||||
|
self.metrics.incr_snapshot_pin_force_drops();
|
||||||
|
let dir = art.root.clone();
|
||||||
|
st.artifact = None;
|
||||||
|
self.reap(db, &dir);
|
||||||
|
} else if !reusable && ttl_expired_idle {
|
||||||
|
// Idle + TTL expired + a newer artifact is needed: reap and
|
||||||
|
// restage.
|
||||||
|
let dir = art.root.clone();
|
||||||
|
st.artifact = None;
|
||||||
|
self.reap(db, &dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match &mut st.artifact {
|
||||||
|
Some(art) if Self::artifact_reusable(db, baseline, art.seq) => {
|
||||||
|
// Warm hit: hand it back, bump the active count + refresh gauges.
|
||||||
|
art.active += 1;
|
||||||
|
art.last_fetch = Instant::now();
|
||||||
|
self.metrics.set_snapshot_staged(art.seq);
|
||||||
|
self.metrics.incr_snapshot_fetches();
|
||||||
|
Decision::Reuse(SnapshotStaging {
|
||||||
|
needed: true,
|
||||||
|
snapshot_seq: art.seq,
|
||||||
|
root: art.root.clone(),
|
||||||
|
files: art.manifest.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
if st.staging {
|
||||||
|
return Decision::Busy;
|
||||||
|
}
|
||||||
|
st.staging = true;
|
||||||
|
Decision::Stage
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The unlocked half of `stage`: pin-and-copy (engine, §2.1), hash the
|
||||||
|
/// manifest, install the artifact. The caller holds the single-flight claim;
|
||||||
|
/// `stage` always clears it afterward.
|
||||||
|
fn perform_stage(&self, db: &TidalDb) -> Result<SnapshotStaging, SnapshotStageError> {
|
||||||
|
// The staged dir is named by the current tail; `stage_snapshot` copies
|
||||||
|
// into it and returns the exact artifact seq (the tail is monotonic, so
|
||||||
|
// the artifact seq is >= this).
|
||||||
|
let tail = db.last_wal_seq();
|
||||||
|
let dir = self.staged_dir(tail);
|
||||||
|
// A leftover dir from a prior failed stage at this exact seq would make
|
||||||
|
// the copy append into it; remove it first.
|
||||||
|
if dir.exists() {
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
let artifact_seq = db
|
||||||
|
.stage_snapshot(&dir, snapshot_exclusions())
|
||||||
|
.map_err(|e| {
|
||||||
|
let msg = e.to_string();
|
||||||
|
if msg.contains("already in progress") {
|
||||||
|
// A concurrent create_backup (operator backup, or another stage)
|
||||||
|
// — the puller retries and shares the result (§2). Retryable.
|
||||||
|
SnapshotStageError::Busy
|
||||||
|
} else {
|
||||||
|
SnapshotStageError::Failed(msg)
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let manifest = Self::build_manifest(&dir).map_err(|e| {
|
||||||
|
// The artifact is on disk but we cannot hash it: release the pin and
|
||||||
|
// surface a real fault (INTERNAL → the puller retries).
|
||||||
|
db.unpin_wal_retention();
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
SnapshotStageError::Failed(format!("manifest build failed: {e}"))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
{
|
||||||
|
let mut st = self
|
||||||
|
.state
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
st.artifact = Some(CachedArtifact {
|
||||||
|
seq: artifact_seq,
|
||||||
|
root: dir.clone(),
|
||||||
|
manifest: manifest.clone(),
|
||||||
|
active: 1,
|
||||||
|
last_fetch: Instant::now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.metrics.set_snapshot_staged(artifact_seq);
|
||||||
|
self.metrics.incr_snapshot_fetches();
|
||||||
|
Ok(SnapshotStaging {
|
||||||
|
needed: true,
|
||||||
|
snapshot_seq: artifact_seq,
|
||||||
|
root: dir,
|
||||||
|
files: manifest,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SnapshotSource for NodeSnapshotSource {
|
||||||
|
fn stage(&self, from_seqno: u64) -> Result<SnapshotStaging, SnapshotStageError> {
|
||||||
|
let db = self
|
||||||
|
.db
|
||||||
|
.upgrade()
|
||||||
|
.ok_or_else(|| SnapshotStageError::Failed("database closed".into()))?;
|
||||||
|
|
||||||
|
// (a) No snapshot needed: the live WAL still serves the puller's
|
||||||
|
// frontier. Cheap, no pin, no manifest — the joiner just streams.
|
||||||
|
// Baseline-aware: a `from_seqno <= stream_baseline` is below the
|
||||||
|
// StreamSegments clamp floor and always needs a snapshot (§2 / §2.6).
|
||||||
|
if Self::wal_covers(&db, self.baseline(), from_seqno) {
|
||||||
|
return Ok(SnapshotStaging {
|
||||||
|
needed: false,
|
||||||
|
snapshot_seq: 0,
|
||||||
|
root: PathBuf::new(),
|
||||||
|
files: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// (b) Locked decision: reuse a warm artifact, refuse Busy, or claim the
|
||||||
|
// single-flight slot.
|
||||||
|
match self.decide(&db) {
|
||||||
|
Decision::Reuse(staging) => return Ok(staging),
|
||||||
|
Decision::Busy => return Err(SnapshotStageError::Busy),
|
||||||
|
Decision::Stage => {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// (c) Stage OUTSIDE the lock. We hold the single-flight claim; clear it
|
||||||
|
// whatever the outcome.
|
||||||
|
let result = self.perform_stage(&db);
|
||||||
|
{
|
||||||
|
let mut st = self
|
||||||
|
.state
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
st.staging = false;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release(&self) {
|
||||||
|
// Decrement the active count and refresh the TTL anchor (a fetch just
|
||||||
|
// completed). The pin/artifact are NOT reaped here even at active==0 —
|
||||||
|
// §2.1: the TTL governs reuse, never an active consumer, and a freshly
|
||||||
|
// idle artifact stays warm for the next joiner until TTL or a newer
|
||||||
|
// artifact is needed (the reap decision lives in `stage`). This keeps
|
||||||
|
// `release` cheap (no WAL read) and idempotent (a double call from a
|
||||||
|
// server-side retry never underflows).
|
||||||
|
let mut st = self
|
||||||
|
.state
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
if let Some(art) = &mut st.artifact {
|
||||||
|
art.active = art.active.saturating_sub(1);
|
||||||
|
art.last_fetch = Instant::now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use tidaldb::schema::{
|
||||||
|
DecaySpec, EntityId, EntityKind, Schema, SchemaBuilder, Timestamp, Window,
|
||||||
|
};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn minimal_schema() -> Schema {
|
||||||
|
let mut builder = SchemaBuilder::new();
|
||||||
|
let _ = builder
|
||||||
|
.signal(
|
||||||
|
"view",
|
||||||
|
EntityKind::Item,
|
||||||
|
DecaySpec::Exponential {
|
||||||
|
half_life: Duration::from_secs(3600),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.windows(&[Window::AllTime])
|
||||||
|
.velocity(false)
|
||||||
|
.add();
|
||||||
|
builder.build().expect("schema valid")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a real cluster-mode `TidalDb` in `dir` with a few signals, so the
|
||||||
|
/// WAL tail is non-zero and the artifact round-trips.
|
||||||
|
fn open_db(dir: &std::path::Path) -> Arc<TidalDb> {
|
||||||
|
use tidaldb::db::config::{NodeConfig, NodeRole};
|
||||||
|
use tidaldb::replication::shard::ShardId;
|
||||||
|
let db = TidalDb::builder()
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.with_cluster(NodeConfig {
|
||||||
|
role: NodeRole::Single,
|
||||||
|
shard_id: ShardId(0),
|
||||||
|
peer_shards: vec![ShardId(1)],
|
||||||
|
..NodeConfig::default()
|
||||||
|
})
|
||||||
|
.with_data_dir(dir)
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
for i in 1u64..=5 {
|
||||||
|
db.signal("view", EntityId::new(i), 1.0, Timestamp::now())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
Arc::new(db)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a source whose stream baseline starts at 0 (the topology-era
|
||||||
|
/// stream — the existing tests' frontiers are all in this numbering).
|
||||||
|
fn source(db: &Arc<TidalDb>, dir: &std::path::Path) -> NodeSnapshotSource {
|
||||||
|
source_with_baseline(db, dir, Arc::new(AtomicU64::new(0)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build a source over an explicit shared baseline `Arc` (so a test can move
|
||||||
|
/// the baseline and observe the `needed` decision change).
|
||||||
|
fn source_with_baseline(
|
||||||
|
db: &Arc<TidalDb>,
|
||||||
|
dir: &std::path::Path,
|
||||||
|
baseline: Arc<AtomicU64>,
|
||||||
|
) -> NodeSnapshotSource {
|
||||||
|
// The metrics handle comes from the db itself (the production path), so
|
||||||
|
// the source's `set_snapshot_staged`/`incr_*` updates a real cell.
|
||||||
|
NodeSnapshotSource::new(
|
||||||
|
db,
|
||||||
|
dir.to_path_buf(),
|
||||||
|
baseline,
|
||||||
|
Duration::from_secs(600),
|
||||||
|
db.cluster_metrics(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// stage (the staged path, driven by a frontier the WAL cannot serve) →
|
||||||
|
/// the manifest's sizes + BLAKE3 verify against the bytes on disk, and the
|
||||||
|
/// artifact opens + round-trips every acked signal.
|
||||||
|
#[test]
|
||||||
|
fn stage_produces_a_verifiable_manifest_and_round_trips() {
|
||||||
|
let data = tempfile::tempdir().unwrap();
|
||||||
|
let db = open_db(data.path());
|
||||||
|
let src = source(&db, data.path());
|
||||||
|
|
||||||
|
// `from_seqno = 0` is below the fresh WAL's earliest servable seq (1),
|
||||||
|
// so the source stages a real artifact (the "behind a compacted leader"
|
||||||
|
// shape, simulated by an unservable frontier).
|
||||||
|
let staging = src.stage(0).unwrap();
|
||||||
|
assert!(
|
||||||
|
staging.needed,
|
||||||
|
"frontier 0 is below earliest: snapshot needed"
|
||||||
|
);
|
||||||
|
assert!(!staging.files.is_empty(), "the artifact has files");
|
||||||
|
assert!(
|
||||||
|
staging.root.starts_with(data.path().join(SNAPSHOTS_DIR)),
|
||||||
|
"staged under <data_dir>/snapshots/"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Every manifest entry's size + BLAKE3 matches the bytes under `root`.
|
||||||
|
for (rel, size, hash) in &staging.files {
|
||||||
|
let bytes = std::fs::read(staging.root.join(rel)).unwrap();
|
||||||
|
assert_eq!(bytes.len() as u64, *size, "manifest size matches {rel}");
|
||||||
|
assert_eq!(
|
||||||
|
blake3::hash(&bytes).as_bytes(),
|
||||||
|
hash,
|
||||||
|
"manifest BLAKE3 matches the bytes for {rel}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The gauge reflects the staged artifact.
|
||||||
|
// (The metrics cell is the db's; we just assert the source set it.)
|
||||||
|
src.release();
|
||||||
|
|
||||||
|
// The artifact opens and round-trips every signal.
|
||||||
|
let restored = TidalDb::builder()
|
||||||
|
.with_data_dir(&staging.root)
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
for i in 1u64..=5 {
|
||||||
|
assert!(
|
||||||
|
restored
|
||||||
|
.read_decay_score(EntityId::new(i), "view", 0)
|
||||||
|
.unwrap()
|
||||||
|
.is_some_and(|s| s > 0.0),
|
||||||
|
"signal {i} survives the staged artifact"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
restored.close().unwrap();
|
||||||
|
// Release the engine's pin (held by the staged artifact) before dropping.
|
||||||
|
db.unpin_wal_retention();
|
||||||
|
Arc::try_unwrap(db).ok().unwrap().close().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The needed=false path: a puller whose frontier the live WAL still serves
|
||||||
|
/// gets `needed=false`, no pin, no manifest.
|
||||||
|
#[test]
|
||||||
|
fn needed_false_when_wal_covers_the_frontier() {
|
||||||
|
let data = tempfile::tempdir().unwrap();
|
||||||
|
let db = open_db(data.path());
|
||||||
|
let src = source(&db, data.path());
|
||||||
|
|
||||||
|
let earliest = db.earliest_servable_seq().unwrap();
|
||||||
|
let staging = src.stage(earliest).unwrap();
|
||||||
|
assert!(!staging.needed, "WAL covers earliest: no snapshot");
|
||||||
|
assert_eq!(staging.snapshot_seq, 0);
|
||||||
|
assert!(staging.files.is_empty());
|
||||||
|
// No pin taken on the needed=false path.
|
||||||
|
Arc::try_unwrap(db).ok().unwrap().close().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Baseline-aware `needed` decision (m11p5 §2 / §2.6): a `from_seqno` AT OR
|
||||||
|
/// BELOW the stream baseline is below the `StreamSegments` clamp floor — the
|
||||||
|
/// stream never serves it — so the source must answer `needed=true` (stage a
|
||||||
|
/// snapshot) even though the raw WAL still physically contains that seqno.
|
||||||
|
///
|
||||||
|
/// Without this, a marker boot resuming from a below-baseline seqno would get
|
||||||
|
/// `needed=false`, clear its marker, reopen the behind/divergent dir, and
|
||||||
|
/// re-fail forever (the loop the fix closes).
|
||||||
|
#[test]
|
||||||
|
fn needed_true_at_or_below_the_baseline_even_when_the_wal_has_the_seq() {
|
||||||
|
let data = tempfile::tempdir().unwrap();
|
||||||
|
let db = open_db(data.path());
|
||||||
|
let baseline = Arc::new(AtomicU64::new(0));
|
||||||
|
let src = source_with_baseline(&db, data.path(), Arc::clone(&baseline));
|
||||||
|
|
||||||
|
// Pick a seqno the raw WAL physically covers: earliest..=tail. On a fresh
|
||||||
|
// WAL with 5 signals, earliest=1 and a low seqno like 2 is servable.
|
||||||
|
let earliest = db.earliest_servable_seq().unwrap();
|
||||||
|
let in_wal = earliest.max(2);
|
||||||
|
// Baseline 0: that seqno is above the baseline AND inside the WAL window
|
||||||
|
// ⇒ needed=false (the live stream still serves it).
|
||||||
|
assert!(
|
||||||
|
!src.stage(in_wal).unwrap().needed,
|
||||||
|
"above baseline + inside WAL window ⇒ no snapshot (needed=false)"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Now lift the baseline above that seqno: the StreamSegments clamp would
|
||||||
|
// skip past it (pre-stream history), so a snapshot IS required even
|
||||||
|
// though the WAL still holds the seq.
|
||||||
|
baseline.store(in_wal, Ordering::Release); // from_seqno == baseline ⇒ at-or-below
|
||||||
|
let staging = src.stage(in_wal).unwrap();
|
||||||
|
assert!(
|
||||||
|
staging.needed,
|
||||||
|
"from_seqno == baseline is below the stream clamp floor ⇒ snapshot needed"
|
||||||
|
);
|
||||||
|
assert!(!staging.files.is_empty(), "a real artifact was staged");
|
||||||
|
src.release();
|
||||||
|
|
||||||
|
// And strictly below the baseline is likewise needed=true.
|
||||||
|
baseline.store(in_wal + 5, Ordering::Release);
|
||||||
|
assert!(
|
||||||
|
src.stage(in_wal).unwrap().needed,
|
||||||
|
"from_seqno strictly below baseline ⇒ snapshot needed"
|
||||||
|
);
|
||||||
|
src.release();
|
||||||
|
|
||||||
|
db.unpin_wal_retention();
|
||||||
|
Arc::try_unwrap(db).ok().unwrap().close().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reuse: a second stage for a frontier the WAL no longer covers shares the
|
||||||
|
/// SAME staged artifact (same seq, same root) while the live WAL still
|
||||||
|
/// covers `artifact_seq + 1`.
|
||||||
|
#[test]
|
||||||
|
fn reuse_while_coverable_shares_one_artifact() {
|
||||||
|
let data = tempfile::tempdir().unwrap();
|
||||||
|
let db = open_db(data.path());
|
||||||
|
let src = source(&db, data.path());
|
||||||
|
|
||||||
|
// Force the staged path: pretend a puller is behind a compacted leader by
|
||||||
|
// asking from a seqno BELOW earliest. earliest is 1 on a fresh WAL, so we
|
||||||
|
// cannot go below it — instead drive the source's staged branch by
|
||||||
|
// staging once via a from_seqno of 0 (below earliest's 1 ⇒ needed).
|
||||||
|
let a = src.stage(0).unwrap();
|
||||||
|
assert!(
|
||||||
|
a.needed,
|
||||||
|
"from_seqno 0 is below earliest (1): snapshot needed"
|
||||||
|
);
|
||||||
|
let first_seq = a.snapshot_seq;
|
||||||
|
let first_root = a.root; // last use of `a`; move, don't clone
|
||||||
|
// Release the first fetch so active==0, but the artifact stays warm.
|
||||||
|
src.release();
|
||||||
|
|
||||||
|
// A second stage for the same (uncoverable) frontier reuses the artifact.
|
||||||
|
let b = src.stage(0).unwrap();
|
||||||
|
assert!(b.needed);
|
||||||
|
assert_eq!(b.snapshot_seq, first_seq, "reused the same artifact seq");
|
||||||
|
assert_eq!(b.root, first_root, "reused the same staged dir");
|
||||||
|
src.release();
|
||||||
|
|
||||||
|
// Release the engine's pin held by the warm artifact before dropping.
|
||||||
|
db.unpin_wal_retention();
|
||||||
|
Arc::try_unwrap(db).ok().unwrap().close().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Busy mapping: a second `stage()` while the engine reports a backup
|
||||||
|
/// already in progress maps to `SnapshotStageError::Busy` (retryable
|
||||||
|
/// `UNAVAILABLE` on the wire — never `FAILED_PRECONDITION`).
|
||||||
|
#[test]
|
||||||
|
fn busy_maps_when_backup_in_progress() {
|
||||||
|
let data = tempfile::tempdir().unwrap();
|
||||||
|
let db = open_db(data.path());
|
||||||
|
let src = source(&db, data.path());
|
||||||
|
|
||||||
|
// Latch the engine's backup CAS to simulate a concurrent create_backup
|
||||||
|
// (operator backup, or another in-flight stage). The source has no warm
|
||||||
|
// artifact yet, so it must reach `stage_snapshot`, which the CAS refuses
|
||||||
|
// with "already in progress" → Busy.
|
||||||
|
db.set_backup_in_progress_for_test(true);
|
||||||
|
let err = src
|
||||||
|
.stage(0)
|
||||||
|
.expect_err("a concurrent backup must refuse the stage");
|
||||||
|
assert!(
|
||||||
|
matches!(err, SnapshotStageError::Busy),
|
||||||
|
"an in-progress backup maps to Busy (retryable), got {err:?}"
|
||||||
|
);
|
||||||
|
db.set_backup_in_progress_for_test(false);
|
||||||
|
|
||||||
|
// The single-flight flag was cleared on the Busy exit, so a subsequent
|
||||||
|
// stage can proceed.
|
||||||
|
let ok = src.stage(0).unwrap();
|
||||||
|
assert!(ok.needed, "after the CAS clears, the stage succeeds");
|
||||||
|
src.release();
|
||||||
|
db.unpin_wal_retention();
|
||||||
|
Arc::try_unwrap(db).ok().unwrap().close().unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -153,6 +153,34 @@ pub struct ReplicationSpec {
|
|||||||
/// arrive. Default 30000. Must be ≥ 1 when given.
|
/// arrive. Default 30000. Must be ≥ 1 when given.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub catchup_retry_ms: Option<u64>,
|
pub catchup_retry_ms: Option<u64>,
|
||||||
|
/// Milliseconds a staged snapshot artifact is REUSED before it is refreshed
|
||||||
|
/// (m11p5 §2.1). Counted from the LAST fetch's completion, not creation, so
|
||||||
|
/// a steady stream of joiners keeps one artifact warm. This governs only
|
||||||
|
/// artifact REUSE — it NEVER unpins the WAL retention of an active consumer
|
||||||
|
/// (a mid-fetch joiner holds the pin until it releases); a separate hard cap
|
||||||
|
/// (4× this) force-drops a never-releasing pin so a dead joiner cannot
|
||||||
|
/// freeze compaction forever. Default 600000 (10 min). Must be ≥ 1 when
|
||||||
|
/// given (0 would expire an artifact the instant it is staged, defeating the
|
||||||
|
/// single-flight share for concurrent joiners).
|
||||||
|
#[serde(default)]
|
||||||
|
pub snapshot_artifact_ttl_ms: Option<u64>,
|
||||||
|
/// Drain + clean-exit(0) once the durable `reseed_required` marker latches
|
||||||
|
/// (m11p5 §2.4). Default `false`; the k8s cluster manifests set it `true` so
|
||||||
|
/// a node that needs a reseed restarts itself (the PVC/pod orchestration
|
||||||
|
/// then re-runs boot-time install). Even with this `true`, the self-restart
|
||||||
|
/// is REFUSED (loudly, in status + gauge) when the node's local view shows
|
||||||
|
/// the remaining voters cannot sustain quorum without it — exiting during a
|
||||||
|
/// 2-voter window would be total write unavailability.
|
||||||
|
#[serde(default)]
|
||||||
|
pub reseed_self_restart: Option<bool>,
|
||||||
|
/// Learner promotion distance AND the readiness-convergence hysteresis
|
||||||
|
/// threshold (m11p5 §3.3 / §4), in events. A learner is promotion-eligible
|
||||||
|
/// once its durable mark is within this many events of the leader's flushed
|
||||||
|
/// frontier; an install-boot node is readiness-converged once its catch-up
|
||||||
|
/// lag first falls at or below this threshold (never `lag == 0`, which an
|
||||||
|
/// open-loop load keeps perpetually false). Default 1024.
|
||||||
|
#[serde(default)]
|
||||||
|
pub learner_promote_lag: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// WAL group-commit tuning (the optional `wal:` YAML block).
|
/// WAL group-commit tuning (the optional `wal:` YAML block).
|
||||||
@ -183,13 +211,34 @@ pub struct TimeoutsSpec {
|
|||||||
pub struct RegionSpec {
|
pub struct RegionSpec {
|
||||||
/// Human-readable region name (e.g. `"us-east"`). Unique within the topology.
|
/// Human-readable region name (e.g. `"us-east"`). Unique within the topology.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// Address this region's gRPC replication server binds to, e.g.
|
/// This region's **advertised** gRPC replication address — a `host:port`
|
||||||
/// `"127.0.0.1:9601"`. When omitted, an OS-assigned loopback port is used —
|
/// that may be a literal IP (`"127.0.0.1:9601"`) OR a DNS name
|
||||||
/// the right default for a single-process cluster where peers never need a
|
/// (`"tidaldb-1.tidaldb-peers.ns.svc.cluster.local:9601"`, m11p5). This is
|
||||||
/// stable address. Explicit addresses are REQUIRED in multi-process mode
|
/// the address SIBLING processes dial; with a DNS name tonic re-resolves
|
||||||
/// (see [`validate_multiproc`]) so sibling processes can reach each other.
|
/// it on every reconnect, so a pod rescheduled onto a new IP becomes
|
||||||
|
/// reachable again without a peer restart. When omitted, an OS-assigned
|
||||||
|
/// loopback port is used — the right default for a single-process cluster
|
||||||
|
/// where peers never need a stable address. Explicit addresses are REQUIRED
|
||||||
|
/// in multi-process mode (see [`validate_multiproc`]) so sibling processes
|
||||||
|
/// can reach each other.
|
||||||
|
///
|
||||||
|
/// In multi-process mode this address also drives THIS region's local bind
|
||||||
|
/// UNLESS [`grpc_bind`](Self::grpc_bind) is set: a literal-IP `grpc_addr`
|
||||||
|
/// binds itself (today's behavior, byte-for-byte); a DNS `grpc_addr` (which
|
||||||
|
/// the local socket cannot bind) binds `0.0.0.0:<its port>`. See
|
||||||
|
/// [`super::transport::resolve_grpc_bind_addr`] for the derivation table.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub grpc_addr: Option<String>,
|
pub grpc_addr: Option<String>,
|
||||||
|
/// Optional explicit **local** gRPC bind address (a `SocketAddr`-parseable
|
||||||
|
/// `host:port`), distinct from the advertised [`grpc_addr`](Self::grpc_addr).
|
||||||
|
/// Set it when the advertised address is a DNS name the local socket cannot
|
||||||
|
/// bind and the default `0.0.0.0:<port>` is not what you want (e.g. binding
|
||||||
|
/// a specific interface). Absent ⇒ the bind is derived from `grpc_addr` per
|
||||||
|
/// the [`super::transport::resolve_grpc_bind_addr`] table. Validated as a
|
||||||
|
/// `SocketAddr` when present (a hostname here is rejected — a bind target
|
||||||
|
/// must be a concrete local address).
|
||||||
|
#[serde(default)]
|
||||||
|
pub grpc_bind: Option<String>,
|
||||||
/// This region's public HTTP address (host:port). Required in multi-process
|
/// This region's public HTTP address (host:port). Required in multi-process
|
||||||
/// mode for write/read forwarding and status aggregation (task 03);
|
/// mode for write/read forwarding and status aggregation (task 03);
|
||||||
/// unused in single-process mode.
|
/// unused in single-process mode.
|
||||||
@ -274,6 +323,9 @@ pub fn load_topology(path: Option<&Path>) -> Result<TopologySpec> {
|
|||||||
/// Mode-independent value validation for a parsed topology (both cluster modes
|
/// Mode-independent value validation for a parsed topology (both cluster modes
|
||||||
/// load through [`load_topology`]). Rejects values that would otherwise be
|
/// load through [`load_topology`]). Rejects values that would otherwise be
|
||||||
/// silently coerced at runtime (e.g. `write_workers: 0` clamping to 1).
|
/// silently coerced at runtime (e.g. `write_workers: 0` clamping to 1).
|
||||||
|
// One flat sequence of independent knob range-checks; splitting it would only
|
||||||
|
// scatter the validation table that operators read top-to-bottom.
|
||||||
|
#[allow(clippy::too_many_lines)]
|
||||||
fn validate_spec_values(spec: &TopologySpec) -> Result<()> {
|
fn validate_spec_values(spec: &TopologySpec) -> Result<()> {
|
||||||
if spec.write_workers == Some(0) {
|
if spec.write_workers == Some(0) {
|
||||||
return Err(ServerError::SchemaConfig(
|
return Err(ServerError::SchemaConfig(
|
||||||
@ -324,6 +376,22 @@ fn validate_spec_values(spec: &TopologySpec) -> Result<()> {
|
|||||||
"replication.quorum_timeout_ms must be >= 1 (omit it for the 2000ms default)".into(),
|
"replication.quorum_timeout_ms must be >= 1 (omit it for the 2000ms default)".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
if spec.replication.snapshot_artifact_ttl_ms == Some(0) {
|
||||||
|
return Err(ServerError::SchemaConfig(
|
||||||
|
"replication.snapshot_artifact_ttl_ms must be >= 1 (omit it for the 600000ms \
|
||||||
|
default); 0 would expire a staged snapshot the instant it is created, defeating \
|
||||||
|
the single-flight artifact share for concurrent joiners"
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if spec.replication.learner_promote_lag == Some(0) {
|
||||||
|
return Err(ServerError::SchemaConfig(
|
||||||
|
"replication.learner_promote_lag must be >= 1 (omit it for the 1024 default); \
|
||||||
|
0 is the same perpetually-false `lag == 0` readiness hysteresis the design \
|
||||||
|
explicitly avoids (an open-loop load never converges to exactly 0 lag)"
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
if let Some(n) = spec.wal.batch_size
|
if let Some(n) = spec.wal.batch_size
|
||||||
&& !(1..=256).contains(&n)
|
&& !(1..=256).contains(&n)
|
||||||
{
|
{
|
||||||
@ -454,13 +522,42 @@ pub fn validate_multiproc(topology: &TopologySpec, my_region: &str) -> Result<()
|
|||||||
region.name
|
region.name
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
if region.grpc_addr.as_deref().unwrap_or("").is_empty() {
|
// `grpc_addr` is the ADVERTISED replication address (m11p5): it must be
|
||||||
|
// a syntactic `host:port` but MAY be a DNS name — exactly the
|
||||||
|
// hostname-tolerant check `http_addr` already passes. The old
|
||||||
|
// parse-as-SocketAddr gate (the former `resolve_grpc_addr`) rejected
|
||||||
|
// hostnames at startup; that gate moves here so a DNS topology
|
||||||
|
// validates, and the bind-vs-advertise split (`resolve_grpc_bind_addr`)
|
||||||
|
// handles the local socket separately.
|
||||||
|
match region.grpc_addr.as_deref() {
|
||||||
|
None | Some("") => {
|
||||||
return Err(ServerError::SchemaConfig(format!(
|
return Err(ServerError::SchemaConfig(format!(
|
||||||
"region '{}' must declare a grpc_addr in multi-process mode \
|
"region '{}' must declare a grpc_addr in multi-process mode \
|
||||||
(siblings replicate over it)",
|
(siblings replicate over it)",
|
||||||
region.name
|
region.name
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
Some(addr) => validate_host_port(®ion.name, "grpc_addr", addr)?,
|
||||||
|
}
|
||||||
|
// `grpc_bind`, when present, is the LOCAL bind socket — it must be a
|
||||||
|
// concrete `SocketAddr` (a hostname cannot be bound). Absent ⇒ derived
|
||||||
|
// from `grpc_addr` at boot (see `resolve_grpc_bind_addr`).
|
||||||
|
if let Some(bind) = region.grpc_bind.as_deref() {
|
||||||
|
if bind.is_empty() {
|
||||||
|
return Err(ServerError::SchemaConfig(format!(
|
||||||
|
"region '{}' grpc_bind must be a host:port SocketAddr when present \
|
||||||
|
(omit it to derive the bind from grpc_addr)",
|
||||||
|
region.name
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
bind.parse::<std::net::SocketAddr>().map_err(|e| {
|
||||||
|
ServerError::SchemaConfig(format!(
|
||||||
|
"region '{}' grpc_bind '{bind}' must parse as a bindable SocketAddr \
|
||||||
|
(a hostname is not a valid local bind target): {e}",
|
||||||
|
region.name
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
}
|
||||||
match region.http_addr.as_deref() {
|
match region.http_addr.as_deref() {
|
||||||
None | Some("") => {
|
None | Some("") => {
|
||||||
return Err(ServerError::SchemaConfig(format!(
|
return Err(ServerError::SchemaConfig(format!(
|
||||||
@ -527,6 +624,7 @@ mod tests {
|
|||||||
RegionSpec {
|
RegionSpec {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
grpc_addr: grpc.map(str::to_string),
|
grpc_addr: grpc.map(str::to_string),
|
||||||
|
grpc_bind: None,
|
||||||
http_addr: http.map(str::to_string),
|
http_addr: http.map(str::to_string),
|
||||||
grpc_tls: None,
|
grpc_tls: None,
|
||||||
metrics_addr: None,
|
metrics_addr: None,
|
||||||
@ -610,6 +708,63 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multiproc_accepts_hostname_grpc_addr() {
|
||||||
|
// m11p5: `grpc_addr` is the ADVERTISED address and may be a DNS name —
|
||||||
|
// the old SocketAddr-parse gate rejected this at startup, the whole
|
||||||
|
// point of the bind/advertise split.
|
||||||
|
for addr in [
|
||||||
|
"127.0.0.1:9601",
|
||||||
|
"tidaldb-1:9601",
|
||||||
|
"tidaldb-1.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9601",
|
||||||
|
] {
|
||||||
|
let mut t = full_topology();
|
||||||
|
t.regions[1].grpc_addr = Some(addr.into());
|
||||||
|
validate_multiproc(&t, "us-east")
|
||||||
|
.unwrap_or_else(|e| panic!("grpc_addr '{addr}' must be accepted: {e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multiproc_rejects_malformed_grpc_addr() {
|
||||||
|
for (addr, why) in [
|
||||||
|
("127.0.0.1", "missing port"),
|
||||||
|
("127.0.0.1:0", "port 0"),
|
||||||
|
("127.0.0.1:99999", "port out of range"),
|
||||||
|
(":9601", "empty host"),
|
||||||
|
("10.0.0.1:port", "non-numeric port"),
|
||||||
|
] {
|
||||||
|
let mut t = full_topology();
|
||||||
|
t.regions[1].grpc_addr = Some(addr.into());
|
||||||
|
let Err(err) = validate_multiproc(&t, "us-east") else {
|
||||||
|
panic!("grpc_addr '{addr}' ({why}) must be rejected");
|
||||||
|
};
|
||||||
|
assert!(err.to_string().contains("grpc_addr"), "got {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multiproc_accepts_socketaddr_grpc_bind() {
|
||||||
|
// An explicit local bind must be a concrete SocketAddr.
|
||||||
|
let mut t = full_topology();
|
||||||
|
t.regions[1].grpc_bind = Some("0.0.0.0:9601".into());
|
||||||
|
validate_multiproc(&t, "us-east").expect("a SocketAddr grpc_bind is valid");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multiproc_rejects_hostname_grpc_bind() {
|
||||||
|
// A hostname is NOT a bindable local address — `grpc_bind` is the bind,
|
||||||
|
// not the advertise, so it must parse as a SocketAddr.
|
||||||
|
for bind in ["tidaldb-1:9601", "0.0.0.0", ""] {
|
||||||
|
let mut t = full_topology();
|
||||||
|
t.regions[1].grpc_bind = Some(bind.into());
|
||||||
|
let Err(err) = validate_multiproc(&t, "us-east") else {
|
||||||
|
panic!("grpc_bind '{bind}' must be rejected (not a SocketAddr)");
|
||||||
|
};
|
||||||
|
assert!(err.to_string().contains("grpc_bind"), "got {err}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn multiproc_accepts_scheme_prefixed_and_hostname_http_addr() {
|
fn multiproc_accepts_scheme_prefixed_and_hostname_http_addr() {
|
||||||
for addr in [
|
for addr in [
|
||||||
@ -635,6 +790,17 @@ mod tests {
|
|||||||
t.timeouts.broadcast_peer_secs = Some(0);
|
t.timeouts.broadcast_peer_secs = Some(0);
|
||||||
let err = validate_spec_values(&t).expect_err("broadcast_peer_secs: 0 must be rejected");
|
let err = validate_spec_values(&t).expect_err("broadcast_peer_secs: 0 must be rejected");
|
||||||
assert!(err.to_string().contains("broadcast_peer_secs"), "got {err}");
|
assert!(err.to_string().contains("broadcast_peer_secs"), "got {err}");
|
||||||
|
|
||||||
|
// m11p5: a 0 snapshot-artifact TTL would expire an artifact the instant
|
||||||
|
// it is staged, defeating the single-flight share — rejected by name.
|
||||||
|
let mut t = full_topology();
|
||||||
|
t.replication.snapshot_artifact_ttl_ms = Some(0);
|
||||||
|
let err =
|
||||||
|
validate_spec_values(&t).expect_err("snapshot_artifact_ttl_ms: 0 must be rejected");
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("snapshot_artifact_ttl_ms"),
|
||||||
|
"got {err}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
net::{SocketAddr, TcpStream},
|
net::{IpAddr, SocketAddr, TcpStream},
|
||||||
time::{Duration, Instant},
|
time::{Duration, Instant},
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -94,9 +94,13 @@ fn build_ready_follower_transport(
|
|||||||
let mut last = String::new();
|
let mut last = String::new();
|
||||||
|
|
||||||
for attempt in 1..=attempts {
|
for attempt in 1..=attempts {
|
||||||
let addr = resolve_grpc_addr(addr_spec, region_name)?;
|
// Single-process self-loop: the bind address IS the ship target. The
|
||||||
|
// bind resolver yields a concrete SocketAddr (literal `grpc_addr`, or an
|
||||||
|
// auto-allocated loopback port when unset); the peer entry is that same
|
||||||
|
// address stringified (m11p5: `peers` is now `host:port` strings).
|
||||||
|
let addr = resolve_grpc_bind_addr(None, addr_spec, region_name)?;
|
||||||
let mut peers = HashMap::new();
|
let mut peers = HashMap::new();
|
||||||
peers.insert(shard, addr); // self-loop: ship target == own server
|
peers.insert(shard, addr.to_string()); // self-loop: ship target == own server
|
||||||
|
|
||||||
let transport = GrpcTransport::new(GrpcTransportConfig {
|
let transport = GrpcTransport::new(GrpcTransportConfig {
|
||||||
local_shard: shard,
|
local_shard: shard,
|
||||||
@ -127,13 +131,22 @@ fn build_ready_follower_transport(
|
|||||||
Err(ServerError::Cluster(last))
|
Err(ServerError::Cluster(last))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Block until `addr` accepts a TCP connection, or [`GRPC_READY_TIMEOUT`]
|
/// Block until `bind_addr`'s gRPC listener accepts a TCP connection, or
|
||||||
/// elapses. A successful connect proves the gRPC listener is bound, which is
|
/// [`GRPC_READY_TIMEOUT`] elapses. A successful connect proves the listener is
|
||||||
/// enough for the lazily-connected client's first `ship_segment`.
|
/// bound, which is enough for the lazily-connected client's first
|
||||||
pub(super) fn grpc_server_ready(addr: SocketAddr) -> bool {
|
/// `ship_segment`.
|
||||||
|
///
|
||||||
|
/// **Unspecified-bind probe (m11p5):** a `0.0.0.0` / `[::]` bind cannot be
|
||||||
|
/// *connected to* as a destination on every platform — it is a bind wildcard,
|
||||||
|
/// not a routable address. When the bind IP is unspecified we probe
|
||||||
|
/// `127.0.0.1:<port>` (resp. `[::1]:<port>`) instead, which the wildcard bind
|
||||||
|
/// also accepts. A concrete bind IP (loopback or a specific interface) is
|
||||||
|
/// probed as-is, preserving the single-process behavior byte-for-byte.
|
||||||
|
pub(super) fn grpc_server_ready(bind_addr: SocketAddr) -> bool {
|
||||||
|
let probe = probe_addr_for_bind(bind_addr);
|
||||||
let deadline = Instant::now() + GRPC_READY_TIMEOUT;
|
let deadline = Instant::now() + GRPC_READY_TIMEOUT;
|
||||||
loop {
|
loop {
|
||||||
if TcpStream::connect_timeout(&addr, GRPC_READY_POLL).is_ok() {
|
if TcpStream::connect_timeout(&probe, GRPC_READY_POLL).is_ok() {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if Instant::now() > deadline {
|
if Instant::now() > deadline {
|
||||||
@ -143,25 +156,93 @@ pub(super) fn grpc_server_ready(addr: SocketAddr) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve a follower's gRPC bind address: parse the topology `grpc_addr`, or
|
/// Map a bind address to the address a readiness probe should *connect* to:
|
||||||
/// allocate an OS-assigned loopback port when unset.
|
/// an unspecified wildcard bind (`0.0.0.0` / `[::]`) is substituted with the
|
||||||
pub(super) fn resolve_grpc_addr(spec: Option<&str>, region_name: &str) -> Result<SocketAddr> {
|
/// matching loopback (`127.0.0.1` / `[::1]`); any concrete address is probed
|
||||||
spec.map_or_else(
|
/// unchanged.
|
||||||
|| {
|
const fn probe_addr_for_bind(bind_addr: SocketAddr) -> SocketAddr {
|
||||||
free_loopback_addr().map_err(|e| {
|
if bind_addr.ip().is_unspecified() {
|
||||||
|
let loopback = match bind_addr.ip() {
|
||||||
|
IpAddr::V4(_) => IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
|
||||||
|
IpAddr::V6(_) => IpAddr::V6(std::net::Ipv6Addr::LOCALHOST),
|
||||||
|
};
|
||||||
|
SocketAddr::new(loopback, bind_addr.port())
|
||||||
|
} else {
|
||||||
|
bind_addr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve THIS region's local gRPC **bind** address (a concrete, bindable
|
||||||
|
/// [`SocketAddr`]) from the bind/advertise split (m11p5 §1). `grpc_addr` is the
|
||||||
|
/// ADVERTISED address siblings dial — it may be a DNS name the local socket
|
||||||
|
/// cannot bind — so the bind is derived separately by this table:
|
||||||
|
///
|
||||||
|
/// | `grpc_bind` | `grpc_addr` | bind result |
|
||||||
|
/// |--------------------|------------------------|------------------------------|
|
||||||
|
/// | present | (any) | parse `grpc_bind` |
|
||||||
|
/// | absent | literal `SocketAddr` | parse `grpc_addr` (today's) |
|
||||||
|
/// | absent | hostname `host:port` | `0.0.0.0:<port-of-grpc_addr>`|
|
||||||
|
/// | absent | hostname, no port | **reject** |
|
||||||
|
/// | absent | absent | auto-allocated loopback port |
|
||||||
|
///
|
||||||
|
/// The literal-IP row is byte-for-byte today's behavior: every existing
|
||||||
|
/// topology keeps binding exactly what it bound before. The hostname rows are
|
||||||
|
/// new — one shared topology file can name every region by its per-pod DNS
|
||||||
|
/// name while each pod binds `0.0.0.0`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns [`ServerError::Cluster`] if `grpc_bind` does not parse as a
|
||||||
|
/// [`SocketAddr`], if a hostname `grpc_addr` has no parseable `:port`, or if a
|
||||||
|
/// loopback port cannot be allocated.
|
||||||
|
pub(super) fn resolve_grpc_bind_addr(
|
||||||
|
grpc_bind: Option<&str>,
|
||||||
|
grpc_addr: Option<&str>,
|
||||||
|
region_name: &str,
|
||||||
|
) -> Result<SocketAddr> {
|
||||||
|
// 1. Explicit bind wins outright — it is a concrete local socket.
|
||||||
|
if let Some(bind) = grpc_bind {
|
||||||
|
return bind.parse().map_err(|e| {
|
||||||
|
ServerError::Cluster(format!(
|
||||||
|
"invalid grpc_bind '{bind}' for region '{region_name}': {e}"
|
||||||
|
))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2/5. No advertised address either → single-process auto-allocation.
|
||||||
|
let Some(advertised) = grpc_addr else {
|
||||||
|
return free_loopback_addr().map_err(|e| {
|
||||||
ServerError::Cluster(format!(
|
ServerError::Cluster(format!(
|
||||||
"allocate loopback gRPC port for region '{region_name}': {e}"
|
"allocate loopback gRPC port for region '{region_name}': {e}"
|
||||||
))
|
))
|
||||||
})
|
});
|
||||||
},
|
};
|
||||||
|s| {
|
|
||||||
s.parse().map_err(|e| {
|
// 2. A literal SocketAddr advertised address binds itself (today's path).
|
||||||
|
if let Ok(addr) = advertised.parse::<SocketAddr>() {
|
||||||
|
return Ok(addr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3/4. A hostname advertised address cannot be bound; derive
|
||||||
|
// `0.0.0.0:<port>` from its port. No port → reject (an advertise address
|
||||||
|
// without a port is meaningless and `validate_multiproc` already rejects
|
||||||
|
// it; this is the defense-in-depth boundary at the bind seam).
|
||||||
|
let Some((_host, port_str)) = advertised.rsplit_once(':') else {
|
||||||
|
return Err(ServerError::Cluster(format!(
|
||||||
|
"grpc_addr '{advertised}' for region '{region_name}' is a hostname with no \
|
||||||
|
':port' — cannot derive a local bind (set grpc_bind explicitly or add a port)"
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
let port: u16 = port_str.parse().map_err(|e| {
|
||||||
ServerError::Cluster(format!(
|
ServerError::Cluster(format!(
|
||||||
"invalid grpc_addr '{s}' for region '{region_name}': {e}"
|
"grpc_addr '{advertised}' for region '{region_name}' has an invalid port \
|
||||||
|
'{port_str}': {e}"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
Ok(SocketAddr::new(
|
||||||
|
IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
|
||||||
|
port,
|
||||||
))
|
))
|
||||||
})
|
|
||||||
},
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reserve a free loopback port by binding `127.0.0.1:0` and reading back the
|
/// Reserve a free loopback port by binding `127.0.0.1:0` and reading back the
|
||||||
@ -172,3 +253,84 @@ fn free_loopback_addr() -> std::io::Result<SocketAddr> {
|
|||||||
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
|
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
|
||||||
listener.local_addr()
|
listener.local_addr()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Parse a `SocketAddr` test fixture, panicking with a clear message on a
|
||||||
|
/// malformed literal (these are all compile-time-known good inputs).
|
||||||
|
fn sa(s: &str) -> SocketAddr {
|
||||||
|
s.parse()
|
||||||
|
.unwrap_or_else(|e| panic!("test fixture '{s}' must parse as a SocketAddr: {e}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The m11p5 §1 bind/advertise derivation table, exhaustively.
|
||||||
|
#[test]
|
||||||
|
fn bind_derivation_table() {
|
||||||
|
// grpc_bind present → it (advertise is ignored for the bind).
|
||||||
|
let addr = resolve_grpc_bind_addr(Some("10.0.0.5:9601"), Some("tidaldb-1:9601"), "r")
|
||||||
|
.expect("explicit grpc_bind binds itself");
|
||||||
|
assert_eq!(addr, sa("10.0.0.5:9601"));
|
||||||
|
|
||||||
|
// grpc_bind absent + grpc_addr is a literal SocketAddr → grpc_addr
|
||||||
|
// (today's behavior, byte-for-byte).
|
||||||
|
let addr = resolve_grpc_bind_addr(None, Some("127.0.0.1:9601"), "r")
|
||||||
|
.expect("literal grpc_addr binds itself");
|
||||||
|
assert_eq!(addr, sa("127.0.0.1:9601"));
|
||||||
|
|
||||||
|
// grpc_bind absent + grpc_addr is a hostname → 0.0.0.0:<port>.
|
||||||
|
let addr = resolve_grpc_bind_addr(None, Some("tidaldb-1.peers.svc:9601"), "r")
|
||||||
|
.expect("hostname grpc_addr binds 0.0.0.0:<port>");
|
||||||
|
assert_eq!(addr, sa("0.0.0.0:9601"));
|
||||||
|
|
||||||
|
// grpc_bind absent + grpc_addr is a hostname with NO port → reject.
|
||||||
|
let err = resolve_grpc_bind_addr(None, Some("tidaldb-1"), "r")
|
||||||
|
.expect_err("a portless hostname grpc_addr cannot derive a bind");
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("no") && err.to_string().contains("port"),
|
||||||
|
"error must name the missing port: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_grpc_bind_is_rejected() {
|
||||||
|
// A hostname is not a bindable local socket — grpc_bind must parse.
|
||||||
|
let err = resolve_grpc_bind_addr(Some("tidaldb-1:9601"), None, "r")
|
||||||
|
.expect_err("a hostname grpc_bind must be rejected");
|
||||||
|
assert!(err.to_string().contains("grpc_bind"), "got {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_addresses_auto_allocates_loopback() {
|
||||||
|
// Single-process default: neither bind nor advertise declared → an
|
||||||
|
// OS-assigned loopback port (the behavior the single-process cluster
|
||||||
|
// relies on, byte-for-byte).
|
||||||
|
let addr = resolve_grpc_bind_addr(None, None, "r")
|
||||||
|
.expect("an unset address auto-allocates a loopback port");
|
||||||
|
assert!(
|
||||||
|
addr.ip().is_loopback(),
|
||||||
|
"auto-allocation is loopback: {addr}"
|
||||||
|
);
|
||||||
|
assert_ne!(addr.port(), 0, "a concrete port was assigned");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn probe_substitutes_loopback_for_unspecified_bind() {
|
||||||
|
// A wildcard bind is probed via loopback (it is not itself a routable
|
||||||
|
// destination); a concrete bind is probed unchanged.
|
||||||
|
assert_eq!(
|
||||||
|
probe_addr_for_bind(sa("0.0.0.0:9601")),
|
||||||
|
sa("127.0.0.1:9601")
|
||||||
|
);
|
||||||
|
assert_eq!(probe_addr_for_bind(sa("[::]:9601")), sa("[::1]:9601"));
|
||||||
|
assert_eq!(
|
||||||
|
probe_addr_for_bind(sa("127.0.0.1:9601")),
|
||||||
|
sa("127.0.0.1:9601")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
probe_addr_for_bind(sa("10.0.0.5:9601")),
|
||||||
|
sa("10.0.0.5:9601")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -22,4 +22,5 @@ pub mod offload;
|
|||||||
pub mod openapi;
|
pub mod openapi;
|
||||||
pub mod router;
|
pub mod router;
|
||||||
pub mod scatter_gather;
|
pub mod scatter_gather;
|
||||||
|
pub mod self_exit;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
|
|||||||
@ -4,7 +4,7 @@ use clap::{Args, Parser, Subcommand};
|
|||||||
use tidal_server::{
|
use tidal_server::{
|
||||||
cluster::{
|
cluster::{
|
||||||
ClusterMode, ClusterState, RegionClusterState, build_cluster_router, build_region_router,
|
ClusterMode, ClusterState, RegionClusterState, build_cluster_router, build_region_router,
|
||||||
ensure_experimental_enabled, load_topology,
|
ensure_experimental_enabled, join_boot, load_topology,
|
||||||
},
|
},
|
||||||
config::{CONFIG_DIR_SCHEMA_FILE, CONFIG_DIR_TOPOLOGY_FILE, load_schema, resolve_config_path},
|
config::{CONFIG_DIR_SCHEMA_FILE, CONFIG_DIR_TOPOLOGY_FILE, load_schema, resolve_config_path},
|
||||||
error::{Result, ServerError},
|
error::{Result, ServerError},
|
||||||
@ -61,6 +61,33 @@ struct ClusterArgs {
|
|||||||
/// Omitted ⇒ ephemeral.
|
/// Omitted ⇒ ephemeral.
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
data_dir: Option<PathBuf>,
|
data_dir: Option<PathBuf>,
|
||||||
|
/// Seed-join boot (m11p5 §3.4): one or more seed HTTP base URLs
|
||||||
|
/// (`http://host:port`, repeatable; or `TIDAL_SEEDS` comma-separated). When
|
||||||
|
/// present, this node does NOT need its `--region` declared in the topology
|
||||||
|
/// file — it learns its roster, id, and term from any reachable seed and
|
||||||
|
/// joins as a Learner. The local topology/config file is still REQUIRED for
|
||||||
|
/// the behavioral knob blocks (`replication`/`wal`/`election`/`timeouts`/`grpc_tls`);
|
||||||
|
/// a bare `--seed` with neither `--topology` nor `TIDAL_CONFIG` refuses to
|
||||||
|
/// boot (§3.5) rather than silently falling back to the compiled-in defaults.
|
||||||
|
#[arg(long, env = "TIDAL_SEEDS", value_delimiter = ',')]
|
||||||
|
seed: Vec<String>,
|
||||||
|
/// This node's ADVERTISED gRPC `host:port` (seed-join, §3.4). Siblings dial
|
||||||
|
/// it; a DNS name re-resolves on reconnect. The local gRPC socket binds the
|
||||||
|
/// derived address (`0.0.0.0:<port>` for a DNS advertise, or the literal IP).
|
||||||
|
/// Required with `--seed` (the joiner has no topology entry of its own to
|
||||||
|
/// read it from).
|
||||||
|
#[arg(long)]
|
||||||
|
advertise_grpc: Option<String>,
|
||||||
|
/// This node's ADVERTISED HTTP `host:port` (seed-join, §3.4): the address
|
||||||
|
/// peers forward writes/status to. Required with `--seed`.
|
||||||
|
#[arg(long)]
|
||||||
|
advertise_http: Option<String>,
|
||||||
|
/// Bind address for this node's Prometheus `/metrics` endpoint
|
||||||
|
/// (e.g. `0.0.0.0:9091`), mirroring standalone's `--metrics`. In seed-join
|
||||||
|
/// mode the joiner has no topology entry, so its metrics listener comes from
|
||||||
|
/// this flag (§3.5).
|
||||||
|
#[arg(long)]
|
||||||
|
metrics: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Args)]
|
#[derive(Args)]
|
||||||
@ -156,6 +183,7 @@ async fn run_cluster(args: ClusterArgs) -> Result<()> {
|
|||||||
// and peers with siblings over real gRPC); without it the existing
|
// and peers with siblings over real gRPC); without it the existing
|
||||||
// single-process cluster runs byte-for-byte unchanged.
|
// single-process cluster runs byte-for-byte unchanged.
|
||||||
match args.region.clone() {
|
match args.region.clone() {
|
||||||
|
Some(region) if !args.seed.is_empty() => run_seed_join_cluster(args, region).await,
|
||||||
Some(region) => run_region_cluster(args, region).await,
|
Some(region) => run_region_cluster(args, region).await,
|
||||||
None => run_single_process_cluster(args).await,
|
None => run_single_process_cluster(args).await,
|
||||||
}
|
}
|
||||||
@ -243,11 +271,24 @@ async fn run_region_cluster(args: ClusterArgs, region: String) -> Result<()> {
|
|||||||
let data_dir = args.data_dir.clone();
|
let data_dir = args.data_dir.clone();
|
||||||
let api_key = read_api_key();
|
let api_key = read_api_key();
|
||||||
// `RegionClusterState::new` builds the GrpcTransport via `GrpcTransport::new`,
|
// `RegionClusterState::new` builds the GrpcTransport via `GrpcTransport::new`,
|
||||||
// which blocks on its own tokio runtime — must run off this reactor. Build it
|
// which blocks on its own tokio runtime — must run off this reactor. The
|
||||||
// on a dedicated thread, exactly like the single-process path.
|
// m11p5 boot-time snapshot install (§2.2–§2.7) ALSO blocks (a leader-
|
||||||
|
// discovery loop + a synchronous snapshot fetch), so both run on the same
|
||||||
|
// dedicated thread, install FIRST: swap-recovery and the snapshot swap must
|
||||||
|
// complete BEFORE `RegionClusterState::new` opens the engine (a marker boot
|
||||||
|
// opens the NEW data dir; a fallback opens the existing one degraded).
|
||||||
let state = std::thread::Builder::new()
|
let state = std::thread::Builder::new()
|
||||||
.name("region-build".into())
|
.name("region-build".into())
|
||||||
.spawn(move || {
|
.spawn(move || -> Result<RegionClusterState> {
|
||||||
|
// §2.2: the install pre-open step runs ONLY when a reseed marker is
|
||||||
|
// present (plain topology boots never contact a peer before serving).
|
||||||
|
// `run_boot_install` returns immediately (NotNeeded) when no marker
|
||||||
|
// exists, after performing the always-safe swap-recovery.
|
||||||
|
if let Some(ref dir) = data_dir {
|
||||||
|
let outcome =
|
||||||
|
tidal_server::cluster::reseed::run_boot_install(&topology, ®ion, dir)?;
|
||||||
|
tracing::info!(?outcome, region = %region, "boot-time reseed install evaluated");
|
||||||
|
}
|
||||||
RegionClusterState::new(
|
RegionClusterState::new(
|
||||||
&topology,
|
&topology,
|
||||||
®ion,
|
®ion,
|
||||||
@ -264,6 +305,132 @@ async fn run_region_cluster(args: ClusterArgs, region: String) -> Result<()> {
|
|||||||
serve_state(state, &args.listen, api_key, build_region_router).await
|
serve_state(state, &args.listen, api_key, build_region_router).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Seed-join boot (m11p5 §3.4–§3.6): this node is NOT declared in the local
|
||||||
|
/// topology file. It learns its roster, assigned id, and term from a `--seed`,
|
||||||
|
/// installs a snapshot when needed, then constructs `RegionClusterState` from
|
||||||
|
/// the LEARNED roster (not the topology's `regions:` list).
|
||||||
|
///
|
||||||
|
/// §3.5 knob-source rule: the local topology/config file is STILL required for
|
||||||
|
/// the behavioral knob blocks (`replication`/`wal`/`election`/`timeouts`/
|
||||||
|
/// `grpc_tls`). A bare `--seed` with neither `--topology` nor `TIDAL_CONFIG`
|
||||||
|
/// REFUSES to boot, naming the rule — silently falling back to the compiled-in
|
||||||
|
/// `default-cluster.yaml` would give the wrong ack default, quorum timeout,
|
||||||
|
/// election timing, and no metrics/TLS material.
|
||||||
|
async fn run_seed_join_cluster(args: ClusterArgs, region: String) -> Result<()> {
|
||||||
|
ensure_experimental_enabled(args.experimental_cluster, ClusterMode::MultiProcess)?;
|
||||||
|
|
||||||
|
// §3.5: refuse a bare `--seed` with no knob source. The joiner reads its
|
||||||
|
// own id/roster/term from the seed, but the BEHAVIORAL knobs must come from
|
||||||
|
// a real file — never the compiled-in default.
|
||||||
|
if args.topology.is_none() && args.config_dir.is_none() {
|
||||||
|
return Err(ServerError::Cluster(
|
||||||
|
"a --seed boot still requires the local topology/config file for the behavioral knob \
|
||||||
|
blocks (replication/wal/election/timeouts/grpc_tls): pass --topology <file> or set \
|
||||||
|
TIDAL_CONFIG (m11p5 §3.5). Refusing to boot rather than silently using the \
|
||||||
|
compiled-in default-cluster.yaml (wrong ack default, quorum timeout, election \
|
||||||
|
timing, and no metrics/TLS material)."
|
||||||
|
.into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let schema_path = resolve_config_path(
|
||||||
|
args.schema.as_deref(),
|
||||||
|
args.config_dir.as_deref(),
|
||||||
|
CONFIG_DIR_SCHEMA_FILE,
|
||||||
|
)?;
|
||||||
|
let topology_path = resolve_config_path(
|
||||||
|
args.topology.as_deref(),
|
||||||
|
args.config_dir.as_deref(),
|
||||||
|
CONFIG_DIR_TOPOLOGY_FILE,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let (schema, profiles) = load_schema(schema_path.as_deref())?;
|
||||||
|
// `load_topology` runs `validate_spec_values` (the knob value validation +
|
||||||
|
// the C2 election lease bound) on the loaded file — exactly what §3.5 keeps.
|
||||||
|
// We do NOT call `validate_multiproc` on this file's `regions:` (it would
|
||||||
|
// demand the joiner be declared there); the runtime roster is the join
|
||||||
|
// response, and the synthesized topology IS validated by `validate_multiproc`
|
||||||
|
// inside `RegionClusterState::new`.
|
||||||
|
let knobs = load_topology(topology_path.as_deref())?;
|
||||||
|
|
||||||
|
let advertise_grpc = args.advertise_grpc.clone().ok_or_else(|| {
|
||||||
|
ServerError::Cluster(
|
||||||
|
"a --seed boot requires --advertise-grpc (this node's advertised gRPC host:port — \
|
||||||
|
siblings dial it; §3.4)"
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let advertise_http = args.advertise_http.clone().ok_or_else(|| {
|
||||||
|
ServerError::Cluster(
|
||||||
|
"a --seed boot requires --advertise-http (this node's advertised HTTP host:port — \
|
||||||
|
peers forward to it; §3.4)"
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let data_dir = args.data_dir.clone().ok_or_else(|| {
|
||||||
|
ServerError::Cluster(
|
||||||
|
"a --seed boot requires --data-dir: the durable WAL is the replication stream and a \
|
||||||
|
snapshot install swaps the data dir, so it must be a subdirectory of a mount (§2.3)"
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
let hlc_offset_ms = match std::env::var("TIDAL_HLC_SKEW_MS") {
|
||||||
|
Ok(raw) => raw.trim().parse::<i64>().map_err(|e| {
|
||||||
|
ServerError::SchemaConfig(format!("invalid TIDAL_HLC_SKEW_MS '{raw}': {e}"))
|
||||||
|
})?,
|
||||||
|
Err(_) => 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
region = %region,
|
||||||
|
seeds = args.seed.len(),
|
||||||
|
%advertise_grpc,
|
||||||
|
%advertise_http,
|
||||||
|
"seed-join boot (m11p5 §3.4): discovering a leader to join through"
|
||||||
|
);
|
||||||
|
|
||||||
|
let api_key = read_api_key();
|
||||||
|
let api_key_for_join = api_key.as_deref().map(str::to_string);
|
||||||
|
let metrics = args.metrics.clone();
|
||||||
|
let seeds = args.seed.clone();
|
||||||
|
// The §2.7 join loop + snapshot install BLOCK (leader discovery, a
|
||||||
|
// synchronous JoinCluster, a snapshot fetch), and `RegionClusterState::new`
|
||||||
|
// builds the GrpcTransport on its own runtime — both must run off this
|
||||||
|
// reactor, on the same dedicated thread, install FIRST.
|
||||||
|
let state = std::thread::Builder::new()
|
||||||
|
.name("region-seed-join-build".into())
|
||||||
|
.spawn(move || -> Result<RegionClusterState> {
|
||||||
|
let join_boot::SeedJoinBoot {
|
||||||
|
topology: synth,
|
||||||
|
region: synth_region,
|
||||||
|
} = join_boot::seed_join_boot(&join_boot::SeedJoinInput {
|
||||||
|
seeds: &seeds,
|
||||||
|
knobs: &knobs,
|
||||||
|
region: ®ion,
|
||||||
|
advertise_grpc: &advertise_grpc,
|
||||||
|
advertise_http: &advertise_http,
|
||||||
|
metrics: metrics.as_deref(),
|
||||||
|
data_dir: &data_dir,
|
||||||
|
api_key: api_key_for_join,
|
||||||
|
})?;
|
||||||
|
RegionClusterState::new(
|
||||||
|
&synth,
|
||||||
|
&synth_region,
|
||||||
|
schema,
|
||||||
|
profiles,
|
||||||
|
Some(data_dir),
|
||||||
|
hlc_offset_ms,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.map_err(|e| ServerError::Cluster(format!("spawn seed-join builder thread: {e}")))?
|
||||||
|
.join()
|
||||||
|
.map_err(|_| ServerError::Cluster("seed-join builder thread panicked".into()))??;
|
||||||
|
|
||||||
|
serve_state(state, &args.listen, api_key, build_region_router).await
|
||||||
|
}
|
||||||
|
|
||||||
/// The serve/shutdown contract every server mode (standalone, single-process
|
/// The serve/shutdown contract every server mode (standalone, single-process
|
||||||
/// cluster, multi-process region) satisfies, so the socket-bind → serve →
|
/// cluster, multi-process region) satisfies, so the socket-bind → serve →
|
||||||
/// drain → deterministic-shutdown plumbing is written ONCE in [`serve_state`].
|
/// drain → deterministic-shutdown plumbing is written ONCE in [`serve_state`].
|
||||||
@ -398,6 +565,11 @@ async fn shutdown_signal<S: ServeState>(state: Arc<S>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
() = sigterm => {}
|
() = sigterm => {}
|
||||||
|
// m11p5 §2.4: a reseed self-restart requests this latch, so a
|
||||||
|
// self-triggered exit runs the IDENTICAL graceful drain a SIGTERM would.
|
||||||
|
() = tidal_server::self_exit::wait_self_exit() => {
|
||||||
|
tracing::info!("graceful self-exit requested (reseed self-restart §2.4)");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Flip readiness BEFORE axum starts draining.
|
// Flip readiness BEFORE axum starts draining.
|
||||||
|
|||||||
@ -198,6 +198,7 @@ pub struct ClusterApiDoc;
|
|||||||
crate::cluster::node::cluster_promote,
|
crate::cluster::node::cluster_promote,
|
||||||
crate::cluster::node::cluster_partition,
|
crate::cluster::node::cluster_partition,
|
||||||
crate::cluster::node::cluster_heal,
|
crate::cluster::node::cluster_heal,
|
||||||
|
crate::cluster::node::cluster_reseed,
|
||||||
crate::cluster::node::cluster_reconcile,
|
crate::cluster::node::cluster_reconcile,
|
||||||
crate::cluster::node::cluster_reconcile_snapshot,
|
crate::cluster::node::cluster_reconcile_snapshot,
|
||||||
crate::cluster::node::create_item,
|
crate::cluster::node::create_item,
|
||||||
|
|||||||
67
tidal-server/src/self_exit.rs
Normal file
67
tidal-server/src/self_exit.rs
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
//! Process-wide graceful self-exit latch (m11p5 §2.4 reseed self-restart).
|
||||||
|
//!
|
||||||
|
//! A node that latches its `reseed_required` marker with
|
||||||
|
//! `replication.reseed_self_restart: true` (and passes the §2.4 quorum-refusal
|
||||||
|
//! check) must drain and exit cleanly so the orchestrator restarts it and the
|
||||||
|
//! next boot reseeds via snapshot. The exit MUST run the SAME graceful path a
|
||||||
|
//! SIGTERM from the orchestrator would — readiness 503 → drain in-flight
|
||||||
|
//! requests → checkpoint + WAL fsync — and NEVER `process::abort` (which would
|
||||||
|
//! skip the checkpoint and risk an inconsistent restart).
|
||||||
|
//!
|
||||||
|
//! Rather than send the process a signal (which would need a non-portable
|
||||||
|
//! `unsafe` syscall or a new dependency), this module exposes a one-shot latch
|
||||||
|
//! the serve loop selects on alongside SIGTERM/ctrl-c. `request_self_exit`
|
||||||
|
//! flips it; `wait_self_exit` resolves once flipped. The latch is a
|
||||||
|
//! [`tokio::sync::Notify`] behind a process-global `OnceLock`, so any component
|
||||||
|
//! (the cluster node's reseed path) can request the exit and the single serve
|
||||||
|
//! loop observes it.
|
||||||
|
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
|
use tokio::sync::Notify;
|
||||||
|
|
||||||
|
/// The process-global self-exit notifier. `OnceLock` so the first waiter
|
||||||
|
/// initializes it; `request_self_exit` initializes-or-reads the same cell.
|
||||||
|
static SELF_EXIT: OnceLock<Notify> = OnceLock::new();
|
||||||
|
|
||||||
|
fn cell() -> &'static Notify {
|
||||||
|
SELF_EXIT.get_or_init(Notify::new)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request a graceful self-exit (m11p5 §2.4).
|
||||||
|
///
|
||||||
|
/// Idempotent: a second request before the serve loop reacts is harmless (the
|
||||||
|
/// stored `notify_one` permit coalesces). Safe to call from any thread.
|
||||||
|
pub fn request_self_exit() {
|
||||||
|
// `notify_one` stores a permit even if no waiter is parked yet, so a request
|
||||||
|
// that races the serve loop's `await` is never lost.
|
||||||
|
cell().notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve once a graceful self-exit has been requested. The serve loop selects
|
||||||
|
/// on this alongside SIGTERM/ctrl-c.
|
||||||
|
pub async fn wait_self_exit() {
|
||||||
|
cell().notified().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn request_before_wait_is_not_lost() {
|
||||||
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("runtime");
|
||||||
|
rt.block_on(async {
|
||||||
|
// Request BEFORE awaiting: `notify_one` stores a permit, so the
|
||||||
|
// subsequent wait resolves immediately (the race the reseed path
|
||||||
|
// must survive — the request can land before the serve loop parks).
|
||||||
|
request_self_exit();
|
||||||
|
tokio::time::timeout(std::time::Duration::from_secs(1), wait_self_exit())
|
||||||
|
.await
|
||||||
|
.expect("a pre-stored notify permit must wake the waiter");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -26,6 +26,7 @@ fn three_region_topology() -> TopologySpec {
|
|||||||
.map(|name| RegionSpec {
|
.map(|name| RegionSpec {
|
||||||
name: name.into(),
|
name: name.into(),
|
||||||
grpc_addr: None,
|
grpc_addr: None,
|
||||||
|
grpc_bind: None,
|
||||||
http_addr: None,
|
http_addr: None,
|
||||||
grpc_tls: None,
|
grpc_tls: None,
|
||||||
metrics_addr: None,
|
metrics_addr: None,
|
||||||
|
|||||||
@ -377,7 +377,8 @@ fn mp_clock_skew_reconciliation_stays_causal() {
|
|||||||
// into a genuine election win.
|
// into a genuine election win.
|
||||||
let (rewrite, proxies) = proxied_rewrite(&["us-east", "eu-west", "ap-south"]);
|
let (rewrite, proxies) = proxied_rewrite(&["us-east", "eu-west", "ap-south"]);
|
||||||
let cluster = MultiProcCluster::start_with(
|
let cluster = MultiProcCluster::start_with(
|
||||||
ClusterOptions::new(3).with_topology_extra(LEGACY_ELECTION_YAML)
|
ClusterOptions::new(3)
|
||||||
|
.with_topology_extra(LEGACY_ELECTION_YAML)
|
||||||
.with_env(LEADER, "TIDAL_HLC_SKEW_MS", "500")
|
.with_env(LEADER, "TIDAL_HLC_SKEW_MS", "500")
|
||||||
.with_env(EU_WEST, "TIDAL_HLC_SKEW_MS", "0")
|
.with_env(EU_WEST, "TIDAL_HLC_SKEW_MS", "0")
|
||||||
.with_env(AP_SOUTH, "TIDAL_HLC_SKEW_MS", "-500")
|
.with_env(AP_SOUTH, "TIDAL_HLC_SKEW_MS", "-500")
|
||||||
@ -751,7 +752,8 @@ fn mp_rolling_upgrade_no_loss_no_stall() {
|
|||||||
// stays owned on THIS thread (restarts need &mut self); the writer thread gets
|
// stays owned on THIS thread (restarts need &mut self); the writer thread gets
|
||||||
// only the stable node base URLs + its own client, so the two never alias.
|
// only the stable node base URLs + its own client, so the two never alias.
|
||||||
let mut cluster = MultiProcCluster::start_with(
|
let mut cluster = MultiProcCluster::start_with(
|
||||||
ClusterOptions::new(3).with_topology_extra(LEGACY_ELECTION_YAML)
|
ClusterOptions::new(3)
|
||||||
|
.with_topology_extra(LEGACY_ELECTION_YAML)
|
||||||
.with_env(LEADER, "TIDAL_VERSION_TAG", "N")
|
.with_env(LEADER, "TIDAL_VERSION_TAG", "N")
|
||||||
.with_env(EU_WEST, "TIDAL_VERSION_TAG", "N")
|
.with_env(EU_WEST, "TIDAL_VERSION_TAG", "N")
|
||||||
.with_env(AP_SOUTH, "TIDAL_VERSION_TAG", "N"),
|
.with_env(AP_SOUTH, "TIDAL_VERSION_TAG", "N"),
|
||||||
|
|||||||
1401
tidal-server/tests/cluster_membership.rs
Normal file
1401
tidal-server/tests/cluster_membership.rs
Normal file
File diff suppressed because it is too large
Load Diff
@ -119,7 +119,11 @@ fn post_acked(
|
|||||||
#[test]
|
#[test]
|
||||||
fn mp_quorum_writes_gate_and_recover_under_partition() {
|
fn mp_quorum_writes_gate_and_recover_under_partition() {
|
||||||
let (rewrite, proxies) = proxied_rewrite(&["eu-west", "ap-south"]);
|
let (rewrite, proxies) = proxied_rewrite(&["eu-west", "ap-south"]);
|
||||||
let cluster = MultiProcCluster::start_with(ClusterOptions::new(3).with_topology_extra(LEGACY_ELECTION_YAML).with_rewrite(rewrite));
|
let cluster = MultiProcCluster::start_with(
|
||||||
|
ClusterOptions::new(3)
|
||||||
|
.with_topology_extra(LEGACY_ELECTION_YAML)
|
||||||
|
.with_rewrite(rewrite),
|
||||||
|
);
|
||||||
let client = reqwest::blocking::Client::builder()
|
let client = reqwest::blocking::Client::builder()
|
||||||
.timeout(Duration::from_secs(8))
|
.timeout(Duration::from_secs(8))
|
||||||
.build()
|
.build()
|
||||||
|
|||||||
@ -24,10 +24,11 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use tidal_server::cluster::{
|
use tidal_server::cluster::{
|
||||||
RegionClusterState, ElectionSpec, RegionSpec, ReplicationSpec, TimeoutsSpec, TopologySpec, WalSpec,
|
ElectionSpec, RegionClusterState, RegionSpec, ReplicationSpec, TimeoutsSpec, TopologySpec,
|
||||||
build_region_router,
|
WalSpec, build_region_router,
|
||||||
};
|
};
|
||||||
use tidaldb::schema::{DecaySpec, EntityKind, Schema, SchemaBuilder, Window};
|
use tidaldb::schema::{DecaySpec, EntityKind, Schema, SchemaBuilder, Window};
|
||||||
|
use tidaldb::wal::format::{MemberEntry, MemberRole, MembershipRecord};
|
||||||
|
|
||||||
/// A single-`view`-signal schema with a `hide` hard-negative signal (so the
|
/// A single-`view`-signal schema with a `hide` hard-negative signal (so the
|
||||||
/// `/hardnegs` route's `signal_with_context("hide", …)` resolves).
|
/// `/hardnegs` route's `signal_with_context("hide", …)` resolves).
|
||||||
@ -90,6 +91,7 @@ impl Pair {
|
|||||||
RegionSpec {
|
RegionSpec {
|
||||||
name: self.leader_name.clone(),
|
name: self.leader_name.clone(),
|
||||||
grpc_addr: Some(self.leader_grpc.to_string()),
|
grpc_addr: Some(self.leader_grpc.to_string()),
|
||||||
|
grpc_bind: None,
|
||||||
http_addr: Some(self.leader_http.to_string()),
|
http_addr: Some(self.leader_http.to_string()),
|
||||||
grpc_tls: None,
|
grpc_tls: None,
|
||||||
metrics_addr: None,
|
metrics_addr: None,
|
||||||
@ -97,6 +99,7 @@ impl Pair {
|
|||||||
RegionSpec {
|
RegionSpec {
|
||||||
name: self.follower_name.clone(),
|
name: self.follower_name.clone(),
|
||||||
grpc_addr: Some(self.follower_grpc.to_string()),
|
grpc_addr: Some(self.follower_grpc.to_string()),
|
||||||
|
grpc_bind: None,
|
||||||
http_addr: Some(self.follower_http.to_string()),
|
http_addr: Some(self.follower_http.to_string()),
|
||||||
grpc_tls: None,
|
grpc_tls: None,
|
||||||
metrics_addr: None,
|
metrics_addr: None,
|
||||||
@ -666,6 +669,7 @@ impl Trio {
|
|||||||
.map(|i| RegionSpec {
|
.map(|i| RegionSpec {
|
||||||
name: self.names[i].clone(),
|
name: self.names[i].clone(),
|
||||||
grpc_addr: Some(self.grpc[i].to_string()),
|
grpc_addr: Some(self.grpc[i].to_string()),
|
||||||
|
grpc_bind: None,
|
||||||
http_addr: Some(self.http[i].to_string()),
|
http_addr: Some(self.http[i].to_string()),
|
||||||
grpc_tls: None,
|
grpc_tls: None,
|
||||||
metrics_addr: None,
|
metrics_addr: None,
|
||||||
@ -1181,3 +1185,270 @@ fn region_node_quorum_forward_and_blob_writes() {
|
|||||||
|
|
||||||
rt.shutdown_timeout(Duration::from_secs(2));
|
rt.shutdown_timeout(Duration::from_secs(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// m11p5 §3 (tier-2.5): the membership runtime is wired end-to-end through real
|
||||||
|
/// HTTP and the effective roster. A 2-node cluster with NO conf-change is in
|
||||||
|
/// era 0: `/cluster/members` returns both regions as VOTERS at version 0, the
|
||||||
|
/// status surface reports `membership_version: 0` + `membership_role: voter`,
|
||||||
|
/// and a join dialled at the NON-leader is refused WITH a leader hint (the
|
||||||
|
/// conf-change gate's `NotLeader` path — the joiner re-targets). This proves the
|
||||||
|
/// `MembershipView` derives the era-0 roster byte-for-byte from the topology and
|
||||||
|
/// that the join/members verbs reach the runtime.
|
||||||
|
#[test]
|
||||||
|
fn region_membership_era0_roster_and_join_gate() {
|
||||||
|
let pair = Pair::new();
|
||||||
|
|
||||||
|
let leader_dir = region_dir();
|
||||||
|
let leader = build_region(pair.topology(), &pair.leader_name, &leader_dir);
|
||||||
|
let follower_dir = region_dir();
|
||||||
|
let follower = build_region(pair.topology(), &pair.follower_name, &follower_dir);
|
||||||
|
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(2)
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
serve(
|
||||||
|
&rt,
|
||||||
|
build_region_router(Arc::new(leader), None),
|
||||||
|
pair.leader_http,
|
||||||
|
);
|
||||||
|
serve(
|
||||||
|
&rt,
|
||||||
|
build_region_router(Arc::new(follower), None),
|
||||||
|
pair.follower_http,
|
||||||
|
);
|
||||||
|
|
||||||
|
let client = reqwest::blocking::Client::new();
|
||||||
|
let leader_base = format!("http://{}", pair.leader_http);
|
||||||
|
let follower_base = format!("http://{}", pair.follower_http);
|
||||||
|
|
||||||
|
// ── Era-0 roster via /cluster/members on the leader ──────────────────────
|
||||||
|
let members: serde_json::Value = client
|
||||||
|
.get(format!("{leader_base}/cluster/members"))
|
||||||
|
.send()
|
||||||
|
.unwrap()
|
||||||
|
.json()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
members["membership_version"].as_u64(),
|
||||||
|
Some(0),
|
||||||
|
"no conf-change → era 0 (version 0): {members}"
|
||||||
|
);
|
||||||
|
let roster = members["members"].as_array().expect("members array");
|
||||||
|
assert_eq!(roster.len(), 2, "both topology regions are in the roster");
|
||||||
|
// Both are voters, with positional ids 0 and 1, names from the topology.
|
||||||
|
let by_id: std::collections::HashMap<u64, &serde_json::Value> = roster
|
||||||
|
.iter()
|
||||||
|
.map(|m| (m["id"].as_u64().unwrap(), m))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(by_id[&0]["name"].as_str(), Some(pair.leader_name.as_str()));
|
||||||
|
assert_eq!(by_id[&0]["role"].as_str(), Some("voter"));
|
||||||
|
assert_eq!(
|
||||||
|
by_id[&1]["name"].as_str(),
|
||||||
|
Some(pair.follower_name.as_str())
|
||||||
|
);
|
||||||
|
assert_eq!(by_id[&1]["role"].as_str(), Some("voter"));
|
||||||
|
|
||||||
|
// ── Status surface carries the membership fields ─────────────────────────
|
||||||
|
let leader_status: serde_json::Value = client
|
||||||
|
.get(format!("{leader_base}/cluster/status/local"))
|
||||||
|
.send()
|
||||||
|
.unwrap()
|
||||||
|
.json()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(leader_status["membership_version"].as_u64(), Some(0));
|
||||||
|
assert_eq!(
|
||||||
|
leader_status["membership_role"].as_str(),
|
||||||
|
Some("voter"),
|
||||||
|
"an era-0 node is a voter: {leader_status}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The follower's /cluster/members agrees (it derives the SAME era-0 roster
|
||||||
|
// from the same topology — the view is internally consistent on every node).
|
||||||
|
let follower_members: serde_json::Value = client
|
||||||
|
.get(format!("{follower_base}/cluster/members"))
|
||||||
|
.send()
|
||||||
|
.unwrap()
|
||||||
|
.json()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
follower_members["members"].as_array().map(Vec::len),
|
||||||
|
Some(2),
|
||||||
|
"every node derives the same era-0 roster: {follower_members}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── A join dialled at the NON-leader is refused with a leader hint ───────
|
||||||
|
// The follower is not the leader (no election driver started → topology
|
||||||
|
// leader leads). The conf-change gate's NotLeader path forwards to the
|
||||||
|
// leader; since the leader has no election driver either, the join hooks are
|
||||||
|
// unbound there and it surfaces as a non-2xx — what matters for THIS test is
|
||||||
|
// that the membership runtime is REACHED (the era-0 roster is served and the
|
||||||
|
// status fields are populated), not that a full conf-change commits (that
|
||||||
|
// needs the election machinery the tier-3 suites drive).
|
||||||
|
let join_resp = client
|
||||||
|
.post(format!("{follower_base}/cluster/join"))
|
||||||
|
.json(&serde_json::json!({
|
||||||
|
"name": "ap-south",
|
||||||
|
"grpc_addr": "ap.svc:9500",
|
||||||
|
"http_addr": "http://ap.svc:9501"
|
||||||
|
}))
|
||||||
|
.send()
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
!join_resp.status().is_success(),
|
||||||
|
"a join with no elected leadership cannot commit a conf-change (era-0 \
|
||||||
|
topology era): {}",
|
||||||
|
join_resp.status()
|
||||||
|
);
|
||||||
|
|
||||||
|
rt.shutdown_timeout(Duration::from_secs(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// m11p5 §3.6 precedence: a node booting with BOTH a stale durable membership
|
||||||
|
/// cache file AND a newer WAL-recovered `ClusterMembership` cell adopts the
|
||||||
|
/// CELL's roster (the cell wins) and REWRITES the cache from the cell.
|
||||||
|
///
|
||||||
|
/// We seed a persistent data dir with a v5 kind-4 record (the cell), drop the
|
||||||
|
/// seeding engine, write a STALE v3 cache claiming a different roster, then build
|
||||||
|
/// the region node on that dir. Its effective roster must reflect v5 (the cell),
|
||||||
|
/// and the on-disk cache must have been rewritten to v5.
|
||||||
|
#[test]
|
||||||
|
fn region_membership_cell_wins_over_stale_cache_and_rewrites_it() {
|
||||||
|
use tidaldb::db::config::{NodeConfig, NodeRole};
|
||||||
|
use tidaldb::replication::{MembershipSnapshot, MembershipStore, ShardId};
|
||||||
|
|
||||||
|
let pair = Pair::new();
|
||||||
|
let dir = region_dir();
|
||||||
|
let data_dir = dir.path().to_path_buf();
|
||||||
|
|
||||||
|
// ── (1) Seed the WAL with a v5 kind-4 record (the CELL). Roster: us-east a
|
||||||
|
// Voter, eu-west a LEARNER (a role distinct from era-0's all-voters, so a
|
||||||
|
// wrong source is observable). Drop the engine to release the data-dir lock.
|
||||||
|
let v5 = MembershipRecord {
|
||||||
|
version: 5,
|
||||||
|
term: 3,
|
||||||
|
members: vec![
|
||||||
|
MemberEntry {
|
||||||
|
id: 0,
|
||||||
|
name: pair.leader_name.clone(),
|
||||||
|
grpc_addr: pair.leader_grpc.to_string(),
|
||||||
|
http_addr: pair.leader_http.to_string(),
|
||||||
|
role: MemberRole::Voter,
|
||||||
|
},
|
||||||
|
MemberEntry {
|
||||||
|
id: 1,
|
||||||
|
name: pair.follower_name.clone(),
|
||||||
|
grpc_addr: pair.follower_grpc.to_string(),
|
||||||
|
http_addr: pair.follower_http.to_string(),
|
||||||
|
role: MemberRole::Learner,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
{
|
||||||
|
let db = tidaldb::TidalDb::builder()
|
||||||
|
.with_data_dir(&data_dir)
|
||||||
|
.with_schema(region_schema())
|
||||||
|
.with_cluster(NodeConfig {
|
||||||
|
role: NodeRole::Single,
|
||||||
|
shard_id: ShardId(0),
|
||||||
|
peer_shards: vec![ShardId(1)],
|
||||||
|
..NodeConfig::default()
|
||||||
|
})
|
||||||
|
.open()
|
||||||
|
.expect("seed engine opens");
|
||||||
|
db.append_membership_record(v5).expect("append v5 record");
|
||||||
|
assert_eq!(
|
||||||
|
db.cluster_membership().map(|(v, ..)| v),
|
||||||
|
Some(5),
|
||||||
|
"the cell folded v5"
|
||||||
|
);
|
||||||
|
// Drop releases the WAL/lock so the node can re-open the same dir.
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── (2) Write a STALE v3 cache claiming BOTH regions are voters (an older
|
||||||
|
// boot's roster, pre the eu-west→Learner change).
|
||||||
|
let store = MembershipStore::new(&data_dir);
|
||||||
|
let stale = MembershipSnapshot {
|
||||||
|
version: 3,
|
||||||
|
term: 2,
|
||||||
|
members: vec![
|
||||||
|
MemberEntry {
|
||||||
|
id: 0,
|
||||||
|
name: pair.leader_name.clone(),
|
||||||
|
grpc_addr: pair.leader_grpc.to_string(),
|
||||||
|
http_addr: pair.leader_http.to_string(),
|
||||||
|
role: MemberRole::Voter,
|
||||||
|
},
|
||||||
|
MemberEntry {
|
||||||
|
id: 1,
|
||||||
|
name: pair.follower_name.clone(),
|
||||||
|
grpc_addr: pair.follower_grpc.to_string(),
|
||||||
|
http_addr: pair.follower_http.to_string(),
|
||||||
|
role: MemberRole::Voter,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
store.persist(&stale).expect("write stale cache");
|
||||||
|
assert_eq!(store.load().unwrap().map(|s| s.version), Some(3));
|
||||||
|
|
||||||
|
// ── (3) Build the node on that dir. The view boots FROM THE CELL (v5), and
|
||||||
|
// the boot-time reconcile rewrites the cache to v5.
|
||||||
|
let node = build_region(pair.topology(), &pair.leader_name, &dir);
|
||||||
|
|
||||||
|
// The membership runtime serves the CELL's roster (v5), not the stale cache.
|
||||||
|
let rt = tokio::runtime::Builder::new_multi_thread()
|
||||||
|
.worker_threads(2)
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
serve(
|
||||||
|
&rt,
|
||||||
|
build_region_router(Arc::new(node), None),
|
||||||
|
pair.leader_http,
|
||||||
|
);
|
||||||
|
let client = reqwest::blocking::Client::new();
|
||||||
|
let members: serde_json::Value = client
|
||||||
|
.get(format!("http://{}/cluster/members", pair.leader_http))
|
||||||
|
.send()
|
||||||
|
.unwrap()
|
||||||
|
.json()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
members["membership_version"].as_u64(),
|
||||||
|
Some(5),
|
||||||
|
"the cell (v5) wins over the stale cache (v3): {members}"
|
||||||
|
);
|
||||||
|
let roster: std::collections::HashMap<u64, String> = members["members"]
|
||||||
|
.as_array()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|m| {
|
||||||
|
(
|
||||||
|
m["id"].as_u64().unwrap(),
|
||||||
|
m["role"].as_str().unwrap().to_string(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(roster.get(&0).map(String::as_str), Some("voter"));
|
||||||
|
assert_eq!(
|
||||||
|
roster.get(&1).map(String::as_str),
|
||||||
|
Some("learner"),
|
||||||
|
"the cell's eu-west→Learner role wins, not the stale cache's voter"
|
||||||
|
);
|
||||||
|
|
||||||
|
// ── The on-disk cache was REWRITTEN from the cell (v5), correcting the stale
|
||||||
|
// v3 (§3.6 "rewritten from the cell after every applied record" — here at the
|
||||||
|
// boot reconcile).
|
||||||
|
let rewritten = store.load().unwrap().expect("cache still present");
|
||||||
|
assert_eq!(
|
||||||
|
rewritten.version, 5,
|
||||||
|
"the stale cache was rewritten to the cell's v5"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
rewritten.members.iter().find(|m| m.id == 1).map(|m| m.role),
|
||||||
|
Some(MemberRole::Learner),
|
||||||
|
"the rewritten cache carries the cell's eu-west→Learner role"
|
||||||
|
);
|
||||||
|
|
||||||
|
rt.shutdown_timeout(Duration::from_secs(2));
|
||||||
|
}
|
||||||
|
|||||||
653
tidal-server/tests/cluster_reseed.rs
Normal file
653
tidal-server/tests/cluster_reseed.rs
Normal file
@ -0,0 +1,653 @@
|
|||||||
|
//! m11p5 §2.2–§2.7 — the RESEED path over real OS processes (tier 3, B3).
|
||||||
|
//!
|
||||||
|
//! Two tier-3 proofs that a behind-or-divergent node self-heals through a
|
||||||
|
//! boot-time snapshot install + catch-up stream, with ZERO operator verbs other
|
||||||
|
//! than process restarts (no `wipe_data_dir`, no manual data-dir surgery):
|
||||||
|
//!
|
||||||
|
//! 1. `mp_follower_reseeds_via_snapshot_after_compaction` — exit-gate 1's
|
||||||
|
//! *mechanics* minus seed-join. A follower stops; the leader writes a batch
|
||||||
|
//! big enough to ROTATE its WAL past one segment, then gracefully restarts so
|
||||||
|
//! its clean shutdown COMPACTS the WAL below the stopped follower's resume
|
||||||
|
//! seq. The follower restarts: its boot-time catch-up pull hits the leader's
|
||||||
|
//! typed `snapshot-required` refusal (the segments below its frontier were
|
||||||
|
//! compacted away), durably latches `reseed_required`, and keeps serving
|
||||||
|
//! degraded. A second restart performs the marker boot — discover the leader,
|
||||||
|
//! adopt its term, fetch the snapshot, swap it in — then converges via the
|
||||||
|
//! catch-up stream. Every written item is then readable on the reseeded
|
||||||
|
//! follower and its status no longer reports `reseed_required`.
|
||||||
|
//!
|
||||||
|
//! Auto-election is pinned OFF (`auto_election: false`): the reseed + the
|
||||||
|
//! legacy `/cluster/promote` re-leadership both work in the term-0 topology
|
||||||
|
//! era, and a manual drill must not race the m11p4 failure detector.
|
||||||
|
//!
|
||||||
|
//! 2. `mp_quarantined_node_reseeds_without_wipe` — exit-gate 3. Under
|
||||||
|
//! `ack=leader` load (a divergent suffix the cluster never quorum-acked), the
|
||||||
|
//! leader is `SIGKILL`ed; the survivors elect; the old leader restarts and
|
||||||
|
//! QUARANTINES on its divergent suffix — which now latches the reseed marker
|
||||||
|
//! (`quarantined: true` AND `reseed_required: true`). Restarting it once more
|
||||||
|
//! performs the marker boot: it snapshot-installs from the CURRENT ELECTED
|
||||||
|
//! leader (the discovery loop + term-adoption path), converges, serves reads,
|
||||||
|
//! and reports `quarantined: false` + `reseed_required: false` with the
|
||||||
|
//! process-local divergence gauge cleared — and NO `wipe_data_dir` anywhere.
|
||||||
|
//!
|
||||||
|
//! # Budget
|
||||||
|
//!
|
||||||
|
//! Tier-3 over real OS processes. Two tests; each boots one fresh 3-process
|
||||||
|
//! cluster (the binary build is amortized to a `cargo build` no-op), writes a
|
||||||
|
//! bounded batch, and performs a bounded number of restarts + convergence waits.
|
||||||
|
//! Every wait is poll-with-deadline (no bare sleeps as correctness gates).
|
||||||
|
//! Whole-suite wall budget < 3 minutes on a developer laptop; each test's waits
|
||||||
|
//! sum well under 90s.
|
||||||
|
//!
|
||||||
|
//! ```bash
|
||||||
|
//! cargo test -p tidal-server --features cluster-e2e --test cluster_reseed -- --nocapture
|
||||||
|
//! ```
|
||||||
|
#![cfg(feature = "cluster-e2e")]
|
||||||
|
// Tier-3 harness allows, mirroring the sibling suites: `unwrap` on known-good
|
||||||
|
// fixtures is idiomatic test noise; the lossy numeric casts are the same
|
||||||
|
// pervasive-and-intentional scoring/sizing math the crate config documents.
|
||||||
|
#![allow(
|
||||||
|
clippy::unwrap_used,
|
||||||
|
clippy::missing_panics_doc,
|
||||||
|
clippy::too_many_lines,
|
||||||
|
clippy::cast_precision_loss,
|
||||||
|
clippy::cast_possible_truncation
|
||||||
|
)]
|
||||||
|
|
||||||
|
mod support;
|
||||||
|
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use support::multiproc::{ClusterOptions, MultiProcCluster, convergence_budget};
|
||||||
|
|
||||||
|
/// Region 0 is the initial topology leader.
|
||||||
|
const LEADER: usize = 0;
|
||||||
|
/// Region 1 (`eu-west`) stays up throughout test 1 (a continuously-live voter).
|
||||||
|
const EU_WEST: usize = 1;
|
||||||
|
/// Region 2 (`ap-south`) is the follower that stops, falls behind a compacted
|
||||||
|
/// leader, and reseeds.
|
||||||
|
const AP_SOUTH: usize = 2;
|
||||||
|
|
||||||
|
/// Operator-driven determinism: pin auto-election OFF so the legacy
|
||||||
|
/// `/cluster/promote` verb (a term-0 topology-era fan-out) works and the m11p4
|
||||||
|
/// failure detector cannot race the manual drill. The reseed itself is the same
|
||||||
|
/// `FetchSnapshot` path in both eras — test 2 exercises the elected era.
|
||||||
|
const LEGACY_ELECTION_YAML: &str = "election:\n auto_election: false";
|
||||||
|
|
||||||
|
/// The fast election block test 2 runs with (the elected-era reseed). Constraint
|
||||||
|
/// (the C2 bound enforced at topology load): `lease (350) + heartbeat (100) <
|
||||||
|
/// timeout_min (500)`.
|
||||||
|
const FAST_ELECTION_YAML: &str = "election:\n heartbeat_interval_ms: 100\n election_timeout_min_ms: 500\n election_timeout_max_ms: 1000\n leader_lease_ms: 350";
|
||||||
|
|
||||||
|
/// Items the leader writes while the follower is offline. Enough to MATTER
|
||||||
|
/// (well past a handful) and — paired with the per-item metadata blob (see
|
||||||
|
/// [`blob_value`]) — to push the WAL past one 16 MiB segment so the
|
||||||
|
/// graceful-shutdown compaction actually deletes the segments below the
|
||||||
|
/// follower's frontier (a single segment is never deleted; the snapshot path
|
||||||
|
/// only triggers once history is genuinely compacted away).
|
||||||
|
///
|
||||||
|
/// Sizing: ~56 KiB of non-indexed metadata per item × 320 items ≈ 18 MiB of
|
||||||
|
/// metadata bytes (plus kind-1/2 blob overhead) > the 16 MiB segment size ⇒
|
||||||
|
/// ≥ 2 segments ⇒ compaction deletes the earlier one(s).
|
||||||
|
const OFFLINE_ITEMS: u64 = 320;
|
||||||
|
|
||||||
|
/// The engine caps item metadata at 8 KiB per VALUE and 64 KiB TOTAL per item
|
||||||
|
/// (a hard query-index-integrity invariant — never to be weakened). So the WAL
|
||||||
|
/// inflation rides MULTIPLE non-indexed values just under those caps: 8 keys ×
|
||||||
|
/// ~7 KiB ≈ 56 KiB total per item, comfortably below the 64 KiB total cap.
|
||||||
|
const BLOB_KEYS: usize = 8;
|
||||||
|
/// Bytes per blob value (< the 8 KiB per-value cap).
|
||||||
|
const BLOB_VALUE_BYTES: usize = 7 * 1024;
|
||||||
|
|
||||||
|
/// Build the per-item non-indexed metadata blob: [`BLOB_KEYS`] keys, each a
|
||||||
|
/// [`BLOB_VALUE_BYTES`]-byte filler value. Only `title` is a schema text field,
|
||||||
|
/// so these `blobN` keys ride the WAL (kind-1 item blob) without any Tantivy
|
||||||
|
/// indexing cost.
|
||||||
|
fn blob_value() -> String {
|
||||||
|
"z".repeat(BLOB_VALUE_BYTES)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A handshake window LOW enough that the marker-boot install completes (or
|
||||||
|
/// falls back) inside the test budget rather than the 60 s production default.
|
||||||
|
/// 30 s is comfortably above a loopback discover+fetch yet bounded.
|
||||||
|
const RESEED_HANDSHAKE_MS: &str = "30000";
|
||||||
|
|
||||||
|
/// The harness's fixed region roster (mirrors `multiproc::region_name`): the
|
||||||
|
/// `proxied_rewrite` set and the proxy-edge lookups key on these names, and they
|
||||||
|
/// are stable across the cluster's lifetime.
|
||||||
|
fn cluster_region_name(idx: usize) -> String {
|
||||||
|
const ROSTER: [&str; 3] = ["us-east", "eu-west", "ap-south"];
|
||||||
|
ROSTER[idx].to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A unique all-alpha search token for an entity id (digits 0-9 → letters a-j),
|
||||||
|
/// so `/search?query=<token>` is an exact item-presence probe (mirrors the
|
||||||
|
/// m11p3/m11p4 ledger checkers).
|
||||||
|
fn item_token(entity_id: u64) -> String {
|
||||||
|
let mut token = String::from("rsd");
|
||||||
|
for d in entity_id.to_string().bytes() {
|
||||||
|
token.push(char::from(b'a' + (d - b'0')));
|
||||||
|
}
|
||||||
|
token
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write one item (small searchable `title` token + several large non-indexed
|
||||||
|
/// `blobN` values that inflate the WAL within the engine's metadata caps) plus
|
||||||
|
/// its 4-dim embedding and a `view` signal to the node at `idx`, asserting the
|
||||||
|
/// leader-durable contract (201 / 204 / 204). `blob` is the shared filler value
|
||||||
|
/// (built once by the caller); `heavy` toggles the WAL-inflating blob keys.
|
||||||
|
fn write_heavy_item(
|
||||||
|
cluster: &MultiProcCluster,
|
||||||
|
idx: usize,
|
||||||
|
entity_id: u64,
|
||||||
|
blob: &str,
|
||||||
|
heavy: bool,
|
||||||
|
) {
|
||||||
|
let mut metadata = serde_json::Map::new();
|
||||||
|
metadata.insert("title".into(), item_token(entity_id).into());
|
||||||
|
if heavy {
|
||||||
|
for k in 0..BLOB_KEYS {
|
||||||
|
metadata.insert(format!("blob{k}"), blob.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let resp = cluster.post(
|
||||||
|
idx,
|
||||||
|
"/items",
|
||||||
|
&serde_json::json!({ "entity_id": entity_id, "metadata": metadata }),
|
||||||
|
);
|
||||||
|
assert_eq!(resp.status().as_u16(), 201, "leader /items must 201");
|
||||||
|
|
||||||
|
let v = entity_id as f32;
|
||||||
|
let resp = cluster.post(
|
||||||
|
idx,
|
||||||
|
"/embeddings",
|
||||||
|
&serde_json::json!({ "entity_id": entity_id, "values": [v, v + 1.0, v + 2.0, v + 3.0] }),
|
||||||
|
);
|
||||||
|
assert_eq!(resp.status().as_u16(), 204, "leader /embeddings must 204");
|
||||||
|
|
||||||
|
let resp = cluster.post(
|
||||||
|
idx,
|
||||||
|
"/signals",
|
||||||
|
&serde_json::json!({ "entity_id": entity_id, "signal": "view", "weight": 1.0 }),
|
||||||
|
);
|
||||||
|
assert_eq!(resp.status().as_u16(), 204, "leader /signals must 204");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `/search?query=<token>` on node `idx` returns `entity_id` (an exact
|
||||||
|
/// item-presence probe — the content invariant).
|
||||||
|
fn item_searchable(cluster: &MultiProcCluster, idx: usize, entity_id: u64) -> bool {
|
||||||
|
let token = item_token(entity_id);
|
||||||
|
let found = cluster.get_json(idx, &format!("/search?query={token}&limit=5"));
|
||||||
|
found["items"]
|
||||||
|
.as_array()
|
||||||
|
.is_some_and(|r| r.iter().any(|x| x["entity_id"].as_u64() == Some(entity_id)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read a status field as a bool (defaulting `false` when the node is
|
||||||
|
/// unreachable or the field is absent).
|
||||||
|
fn status_bool(cluster: &MultiProcCluster, idx: usize, field: &str) -> bool {
|
||||||
|
cluster
|
||||||
|
.local_status(idx)
|
||||||
|
.and_then(|s| s[field].as_bool())
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll node `idx`'s own `/cluster/status/local` until `field == expected`, or
|
||||||
|
/// the deadline. Returns on success; panics with the last seen status on
|
||||||
|
/// timeout.
|
||||||
|
fn await_status_bool(
|
||||||
|
cluster: &MultiProcCluster,
|
||||||
|
idx: usize,
|
||||||
|
field: &str,
|
||||||
|
expected: bool,
|
||||||
|
budget: Duration,
|
||||||
|
what: &str,
|
||||||
|
) {
|
||||||
|
let deadline = Instant::now() + budget;
|
||||||
|
loop {
|
||||||
|
if status_bool(cluster, idx, field) == expected {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
Instant::now() < deadline,
|
||||||
|
"{what}: node {idx} did not report {field}={expected} within {budget:?}; \
|
||||||
|
last status: {:?}",
|
||||||
|
cluster.local_status(idx)
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll until node `idx`'s OWN status reports zero lag and an applied frontier
|
||||||
|
/// at or above the live leader's `last_seq` (convergence proven against the
|
||||||
|
/// node's own process boundary, never the leader's aggregate view).
|
||||||
|
fn await_self_converged(cluster: &MultiProcCluster, idx: usize, budget: Duration, what: &str) {
|
||||||
|
let deadline = Instant::now() + budget;
|
||||||
|
loop {
|
||||||
|
let leader_seq = cluster.leader_last_seq();
|
||||||
|
if let (Some(target), Some(st)) = (leader_seq, cluster.local_status(idx)) {
|
||||||
|
let applied = st["applied_events"].as_u64().unwrap_or(0);
|
||||||
|
let lag = st["lag_events"].as_u64().unwrap_or(u64::MAX);
|
||||||
|
if lag == 0 && applied >= target {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
Instant::now() < deadline,
|
||||||
|
"{what}: node {idx} did not converge (lag 0 vs leader last_seq) within {budget:?}; \
|
||||||
|
leader_seq={leader_seq:?} status={:?}",
|
||||||
|
cluster.local_status(idx)
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Promote `region` to leader via the legacy `/cluster/promote` verb, asserting
|
||||||
|
/// the 200, then wait for every LIVE node to agree on the leader. Used in the
|
||||||
|
/// legacy (term-0) drill to restore a leader after the original leader's
|
||||||
|
/// graceful restart booted it as a follower (the durable-state §1.4-1 rule).
|
||||||
|
fn promote_and_agree(cluster: &MultiProcCluster, via_idx: usize, region: &str) {
|
||||||
|
let resp = cluster.post(
|
||||||
|
via_idx,
|
||||||
|
"/cluster/promote",
|
||||||
|
&serde_json::json!({ "region": region }),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
resp.status().as_u16(),
|
||||||
|
200,
|
||||||
|
"/cluster/promote must 200: {}",
|
||||||
|
resp.status()
|
||||||
|
);
|
||||||
|
cluster.wait_leader_agreed(region, convergence_budget());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gate-1 mechanics (minus seed-join): a follower that fell behind a leader
|
||||||
|
/// whose WAL has been COMPACTED past its resume seq reseeds via the boot-time
|
||||||
|
/// snapshot install — zero operator verbs other than restarts.
|
||||||
|
#[test]
|
||||||
|
fn mp_follower_reseeds_via_snapshot_after_compaction() {
|
||||||
|
// Pin auto-election OFF: legacy promote + reseed both ride the term-0 era.
|
||||||
|
// Give the AP_SOUTH node the LOW handshake window so its marker boot does
|
||||||
|
// not wait the 60 s production default before installing.
|
||||||
|
let opts = ClusterOptions::new(3)
|
||||||
|
.with_topology_extra(LEGACY_ELECTION_YAML)
|
||||||
|
.with_env(AP_SOUTH, "TIDAL_RESEED_HANDSHAKE_MS", RESEED_HANDSHAKE_MS);
|
||||||
|
let mut cluster = MultiProcCluster::start_with(opts);
|
||||||
|
|
||||||
|
// A couple of baseline items, fully converged, so every node shares a
|
||||||
|
// common prefix before the follower goes offline.
|
||||||
|
for entity in 1..=3u64 {
|
||||||
|
write_heavy_item(&cluster, LEADER, entity, "", false);
|
||||||
|
}
|
||||||
|
cluster.wait_converged_all(convergence_budget());
|
||||||
|
println!("[reseed] baseline converged on all three nodes");
|
||||||
|
|
||||||
|
// ── Stop one follower gracefully: its applied frontier latches here. ──────
|
||||||
|
cluster.stop_graceful(AP_SOUTH);
|
||||||
|
let frontier_at_stop = cluster
|
||||||
|
.local_status(LEADER)
|
||||||
|
.and_then(|s| s["last_seq"].as_u64())
|
||||||
|
.unwrap_or(0);
|
||||||
|
println!("[reseed] ap-south stopped; leader frontier at stop = {frontier_at_stop}");
|
||||||
|
|
||||||
|
// ── The leader writes a batch big enough to ROTATE its WAL past one
|
||||||
|
// segment (large non-indexed blobs), so the graceful-restart compaction
|
||||||
|
// below actually deletes the segments holding the follower's resume range.
|
||||||
|
let blob = blob_value();
|
||||||
|
for entity in 4..=(3 + OFFLINE_ITEMS) {
|
||||||
|
write_heavy_item(&cluster, LEADER, entity, &blob, true);
|
||||||
|
}
|
||||||
|
// EU_WEST (continuously live) must converge the batch, so a leader exists to
|
||||||
|
// reseed from after the original leader restarts.
|
||||||
|
await_self_converged(
|
||||||
|
&cluster,
|
||||||
|
EU_WEST,
|
||||||
|
convergence_budget(),
|
||||||
|
"eu-west catches the offline batch",
|
||||||
|
);
|
||||||
|
println!("[reseed] leader wrote {OFFLINE_ITEMS} heavy items; eu-west converged");
|
||||||
|
|
||||||
|
// ── GRACEFULLY restart the LEADER: clean shutdown writes the WAL checkpoint
|
||||||
|
// marker and COMPACTS the WAL — the stopped follower's resume seq is now
|
||||||
|
// below the leader's earliest servable seq. The restarted leader boots as a
|
||||||
|
// FOLLOWER (durable §1.4-1 rule), so re-promote it (legacy term-0 verb) to
|
||||||
|
// restore a leader for the follower to reseed from.
|
||||||
|
cluster.restart_graceful(LEADER, &[]);
|
||||||
|
promote_and_agree(&cluster, LEADER, cluster.region_name(LEADER));
|
||||||
|
println!("[reseed] leader gracefully restarted (WAL compacted) and re-promoted");
|
||||||
|
|
||||||
|
// ── Restart the stopped follower (first boot: NO marker yet). Its runtime
|
||||||
|
// boot-time catch-up pull requests from its frontier+1, which the leader's
|
||||||
|
// compacted WAL cannot serve → typed `snapshot-required` refusal → the
|
||||||
|
// durable marker latches. The node keeps serving degraded.
|
||||||
|
cluster.restart(AP_SOUTH, &[]);
|
||||||
|
await_status_bool(
|
||||||
|
&cluster,
|
||||||
|
AP_SOUTH,
|
||||||
|
"reseed_required",
|
||||||
|
true,
|
||||||
|
convergence_budget() + Duration::from_secs(10),
|
||||||
|
"the boot-time pull against a compacted leader latches reseed_required",
|
||||||
|
);
|
||||||
|
println!("[reseed] ap-south restarted behind a compacted leader → reseed_required latched");
|
||||||
|
|
||||||
|
// ── Restart the follower ONCE MORE: the marker boot performs the snapshot
|
||||||
|
// install (discover leader → adopt term → fetch → swap), then converges via
|
||||||
|
// the catch-up stream. `reseed_self_restart` defaults to false, so the test
|
||||||
|
// restarts it explicitly (the LOW handshake window keeps the install bounded).
|
||||||
|
cluster.restart(AP_SOUTH, &[]);
|
||||||
|
await_self_converged(
|
||||||
|
&cluster,
|
||||||
|
AP_SOUTH,
|
||||||
|
convergence_budget() + Duration::from_secs(20),
|
||||||
|
"the marker boot installs the snapshot and the follower converges",
|
||||||
|
);
|
||||||
|
println!("[reseed] ap-south marker boot installed the snapshot and converged (lag 0)");
|
||||||
|
|
||||||
|
// ── CONTENT: every offline-written item is readable on the reseeded
|
||||||
|
// follower (the snapshot carried the compacted history; the stream carried
|
||||||
|
// the suffix). Poll past the ~2 s text-index auto-commit.
|
||||||
|
// Convergence-class wait: the snapshot install + text-index rebuild +
|
||||||
|
// ~2 s auto-commit compete with suite-parallel load, so a fixed short
|
||||||
|
// budget flakes on busy hosts; use the harness convergence budget
|
||||||
|
// (30 s default, TIDAL_TEST_CONVERGENCE_BUDGET_SECS to widen).
|
||||||
|
let probe_deadline = Instant::now() + convergence_budget();
|
||||||
|
for entity in [4u64, 50, 120, 200, 3 + OFFLINE_ITEMS] {
|
||||||
|
loop {
|
||||||
|
if item_searchable(&cluster, AP_SOUTH, entity) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
Instant::now() < probe_deadline,
|
||||||
|
"reseeded follower is missing item {entity} (snapshot+stream must \
|
||||||
|
deliver every written item)"
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println!("[reseed] every probed offline item is searchable on the reseeded follower");
|
||||||
|
|
||||||
|
// ── The marker is gone: the swap discarded the old data dir (with the
|
||||||
|
// marker) and the new dir from staging carries none.
|
||||||
|
assert!(
|
||||||
|
!status_bool(&cluster, AP_SOUTH, "reseed_required"),
|
||||||
|
"the reseeded follower must no longer report reseed_required: {:?}",
|
||||||
|
cluster.local_status(AP_SOUTH)
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!status_bool(&cluster, AP_SOUTH, "quarantined"),
|
||||||
|
"the reseeded follower must not be quarantined: {:?}",
|
||||||
|
cluster.local_status(AP_SOUTH)
|
||||||
|
);
|
||||||
|
println!("[reseed] ap-south reseeded clean: reseed_required=false, quarantined=false");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST with the `x-tidal-ack` header through a dedicated client. `Some(seq)`
|
||||||
|
/// only for a 2xx carrying `x-tidal-seq` (the ledger's "acknowledged").
|
||||||
|
fn post_acked(
|
||||||
|
client: &reqwest::blocking::Client,
|
||||||
|
base: &str,
|
||||||
|
path: &str,
|
||||||
|
ack: &str,
|
||||||
|
body: &serde_json::Value,
|
||||||
|
) -> Option<u64> {
|
||||||
|
let resp = client
|
||||||
|
.post(format!("{base}{path}"))
|
||||||
|
.header("x-tidal-ack", ack)
|
||||||
|
.json(body)
|
||||||
|
.send()
|
||||||
|
.ok()?;
|
||||||
|
if !resp.status().is_success() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
resp.headers()
|
||||||
|
.get("x-tidal-seq")?
|
||||||
|
.to_str()
|
||||||
|
.ok()?
|
||||||
|
.parse()
|
||||||
|
.ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Poll the LIVE candidate nodes for an elected leader at a term above
|
||||||
|
/// `after_term`. Returns `(node_idx, term)`.
|
||||||
|
fn await_elected_leader(
|
||||||
|
cluster: &MultiProcCluster,
|
||||||
|
candidates: &[usize],
|
||||||
|
after_term: u64,
|
||||||
|
budget: Duration,
|
||||||
|
) -> (usize, u64) {
|
||||||
|
let deadline = Instant::now() + budget;
|
||||||
|
loop {
|
||||||
|
for &idx in candidates {
|
||||||
|
if let Some(status) = cluster.local_status(idx) {
|
||||||
|
let term = status["term"].as_u64().unwrap_or(0);
|
||||||
|
if status["role"].as_str() == Some("leader") && term > after_term {
|
||||||
|
return (idx, term);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
Instant::now() < deadline,
|
||||||
|
"no leader elected among {candidates:?} above term {after_term} within {budget:?}"
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gate 3: a quarantined divergent node reseeds via the boot-time snapshot
|
||||||
|
/// install — NO `wipe_data_dir`. Cribbed from `cluster_election.rs`'s
|
||||||
|
/// quarantine drill (`FAST_ELECTION_YAML`; a divergent suffix exists; survivors
|
||||||
|
/// elect; restart the old leader → it quarantines), then closes the loop the
|
||||||
|
/// m11p4 drill left to a wipe: the quarantine latch now writes the reseed
|
||||||
|
/// marker, and a second restart marker-boots a snapshot install from the
|
||||||
|
/// CURRENT ELECTED leader.
|
||||||
|
///
|
||||||
|
/// The divergent suffix is made DETERMINISTIC (not timing-probabilistic) by
|
||||||
|
/// severing the leader's OUTBOUND gRPC ship to both followers BEFORE the
|
||||||
|
/// suffix writes: those `ack=leader` writes are durably journaled on the
|
||||||
|
/// leader but never reach a follower, so the survivors — starved of the
|
||||||
|
/// leader's heartbeats — election-timeout and elect a new leader whose
|
||||||
|
/// election-time position EXCLUDES the suffix. When the old leader restarts
|
||||||
|
/// and joins the new term, the §5 divergence check sees its WAL tail exceed
|
||||||
|
/// the new leadership's history → quarantine.
|
||||||
|
#[test]
|
||||||
|
fn mp_quarantined_node_reseeds_without_wipe() {
|
||||||
|
use support::partition::{ProxyController, proxied_rewrite};
|
||||||
|
|
||||||
|
/// Sever the leader's outbound gRPC to a follower (its own view of the
|
||||||
|
/// peer): cuts ship + heartbeat so the suffix never replicates and the
|
||||||
|
/// follower's election timer is no longer reset.
|
||||||
|
fn sever_ship(proxies: &ProxyController, leader: &str, follower: &str) {
|
||||||
|
proxies.edge(leader, follower).grpc.sever();
|
||||||
|
}
|
||||||
|
|
||||||
|
let regions = [
|
||||||
|
cluster_region_name(LEADER),
|
||||||
|
cluster_region_name(EU_WEST),
|
||||||
|
cluster_region_name(AP_SOUTH),
|
||||||
|
];
|
||||||
|
let region_refs: Vec<&str> = regions.iter().map(String::as_str).collect();
|
||||||
|
let (rewrite, proxies) = proxied_rewrite(®ion_refs);
|
||||||
|
// Give the (to-be-quarantined) leader region the LOW handshake window so its
|
||||||
|
// eventual marker boot installs inside budget.
|
||||||
|
let opts = ClusterOptions::new(3)
|
||||||
|
.with_topology_extra(FAST_ELECTION_YAML)
|
||||||
|
.with_rewrite(rewrite)
|
||||||
|
.with_env(LEADER, "TIDAL_RESEED_HANDSHAKE_MS", RESEED_HANDSHAKE_MS);
|
||||||
|
let mut cluster = MultiProcCluster::start_with(opts);
|
||||||
|
let client = reqwest::blocking::Client::builder()
|
||||||
|
.timeout(Duration::from_secs(3))
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// A committed prefix every node shares (quorum-acked while links are intact).
|
||||||
|
for entity in 1..=5u64 {
|
||||||
|
post_acked(
|
||||||
|
&client,
|
||||||
|
&cluster.node(LEADER),
|
||||||
|
"/items",
|
||||||
|
"quorum",
|
||||||
|
&serde_json::json!({ "entity_id": entity, "metadata": { "title": item_token(entity) } }),
|
||||||
|
)
|
||||||
|
.expect("committed-prefix quorum write");
|
||||||
|
}
|
||||||
|
cluster.wait_converged_all(convergence_budget());
|
||||||
|
|
||||||
|
// ── Sever the leader's OUTBOUND ship to both followers, then write a burst
|
||||||
|
// of `ack=leader` items: durably journaled on the leader, never shipped —
|
||||||
|
// the deterministic DIVERGENT SUFFIX.
|
||||||
|
let leader_region = cluster_region_name(LEADER);
|
||||||
|
sever_ship(&proxies, &leader_region, &cluster_region_name(EU_WEST));
|
||||||
|
sever_ship(&proxies, &leader_region, &cluster_region_name(AP_SOUTH));
|
||||||
|
let mut suffix_writes = 0u32;
|
||||||
|
let burst_deadline = Instant::now() + Duration::from_millis(700);
|
||||||
|
let mut entity = 100u64;
|
||||||
|
while Instant::now() < burst_deadline {
|
||||||
|
if post_acked(
|
||||||
|
&client,
|
||||||
|
&cluster.node(LEADER),
|
||||||
|
"/items",
|
||||||
|
"leader",
|
||||||
|
&serde_json::json!({ "entity_id": entity, "metadata": { "title": item_token(entity) } }),
|
||||||
|
)
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
suffix_writes += 1;
|
||||||
|
}
|
||||||
|
entity += 1;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
suffix_writes > 0,
|
||||||
|
"the severed leader must have journaled an unshipped divergent suffix"
|
||||||
|
);
|
||||||
|
println!("[quarantine] severed leader ship; journaled {suffix_writes} unshipped suffix writes");
|
||||||
|
|
||||||
|
// SIGKILL the leader (the suffix stays on its WAL, unshipped) and stop the
|
||||||
|
// writer.
|
||||||
|
cluster.kill_hard(LEADER);
|
||||||
|
|
||||||
|
// ── The survivors elect on their own (zero operator verbs). They never saw
|
||||||
|
// the suffix, so the elected leader's position excludes it.
|
||||||
|
let survivors = [EU_WEST, AP_SOUTH];
|
||||||
|
let (new_leader, new_term) =
|
||||||
|
await_elected_leader(&cluster, &survivors, 0, Duration::from_secs(15));
|
||||||
|
// Writes resume on the new leadership so the elected term is real and
|
||||||
|
// advancing (the reseed needs a live leader to fetch from).
|
||||||
|
let resume_deadline = Instant::now() + Duration::from_secs(10);
|
||||||
|
loop {
|
||||||
|
if post_acked(
|
||||||
|
&client,
|
||||||
|
&cluster.node(new_leader),
|
||||||
|
"/signals",
|
||||||
|
"quorum",
|
||||||
|
&serde_json::json!({ "entity_id": 900_001, "signal": "view", "weight": 1.0 }),
|
||||||
|
)
|
||||||
|
.is_some()
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
Instant::now() < resume_deadline,
|
||||||
|
"quorum writes did not resume on the elected leader"
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
}
|
||||||
|
println!("[quarantine] survivors elected node {new_leader} at term {new_term}; writes resumed");
|
||||||
|
|
||||||
|
// ── Restart the old leader with its OUTBOUND catch-up to the followers
|
||||||
|
// STILL severed (the `edge(leader, follower)` links from the suffix step).
|
||||||
|
//
|
||||||
|
// Why this is the load-bearing determinism, not an artifice: the divergence
|
||||||
|
// quarantine is detected by `join_term_check`, which runs ONLY on a
|
||||||
|
// heartbeat carrying the new leader's election-time position and compares it
|
||||||
|
// against this node's `election_log_position()`. That position reads the
|
||||||
|
// node's OWN term-0 suffix frontier ONLY while its WAL tail term is still 0.
|
||||||
|
// If the node's INDEPENDENT catch-up pull applies the new leader's term-N
|
||||||
|
// marker FIRST, the tail term flips to N and the position reads the new
|
||||||
|
// stream's (lower) applied frontier instead — masking the divergent suffix,
|
||||||
|
// so the node silently converges and never quarantines (a real race, also
|
||||||
|
// why `cluster_election.rs` treats quarantine as conditional). Heartbeats are
|
||||||
|
// the leader DIALING us (`edge(follower, leader)`, intact); catch-up is US
|
||||||
|
// dialing the leader (`edge(leader, follower)`, severed). Keeping the
|
||||||
|
// OUTBOUND severed lets the heartbeat-driven check run against the intact
|
||||||
|
// term-0 suffix → DETERMINISTIC quarantine. The links heal before the
|
||||||
|
// marker boot, which needs to dial the leader for discovery + snapshot.
|
||||||
|
cluster.restart(LEADER, &[]);
|
||||||
|
await_status_bool(
|
||||||
|
&cluster,
|
||||||
|
LEADER,
|
||||||
|
"quarantined",
|
||||||
|
true,
|
||||||
|
convergence_budget() + Duration::from_secs(10),
|
||||||
|
"the restarted old leader quarantines on its divergent suffix",
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
status_bool(&cluster, LEADER, "reseed_required"),
|
||||||
|
"the quarantine latch must also write the reseed marker (m11p5 §2.4): {:?}",
|
||||||
|
cluster.local_status(LEADER)
|
||||||
|
);
|
||||||
|
println!("[quarantine] old leader quarantined AND latched reseed_required (no wipe)");
|
||||||
|
|
||||||
|
// ── Heal the leader's outbound so the marker boot can dial the elected
|
||||||
|
// leader (HTTP status discovery + the gRPC snapshot fetch).
|
||||||
|
proxies
|
||||||
|
.edge(&leader_region, &cluster_region_name(EU_WEST))
|
||||||
|
.grpc
|
||||||
|
.heal_link();
|
||||||
|
proxies
|
||||||
|
.edge(&leader_region, &cluster_region_name(AP_SOUTH))
|
||||||
|
.grpc
|
||||||
|
.heal_link();
|
||||||
|
|
||||||
|
// ── Restart it ONCE MORE → marker boot → snapshot install from the CURRENT
|
||||||
|
// ELECTED leader (the discovery loop polls peers for is_leader, adopts the
|
||||||
|
// elected term, fetches, swaps). NO wipe_data_dir anywhere.
|
||||||
|
cluster.restart(LEADER, &[]);
|
||||||
|
await_self_converged(
|
||||||
|
&cluster,
|
||||||
|
LEADER,
|
||||||
|
convergence_budget() + Duration::from_secs(20),
|
||||||
|
"the marker boot installs the snapshot from the elected leader and converges",
|
||||||
|
);
|
||||||
|
println!("[quarantine] old leader marker-booted, reseeded from the elected leader, converged");
|
||||||
|
|
||||||
|
// ── Clean rejoin: serves reads, no quarantine, no marker. The process-local
|
||||||
|
// divergence gauge is cleared by the fresh process + the install removing
|
||||||
|
// the divergent suffix (so the next term-join does not re-quarantine); the
|
||||||
|
// `quarantined` status field mirrors that gauge — both fresh-false after the
|
||||||
|
// reseed boot. No `/metrics` port is wired in the harness, so the status
|
||||||
|
// field is the in-budget proxy for the gauge (it cannot read `false` while
|
||||||
|
// the gauge reads `true` — they are set from the same code path).
|
||||||
|
assert!(
|
||||||
|
!status_bool(&cluster, LEADER, "quarantined"),
|
||||||
|
"the reseeded node must clear its quarantine: {:?}",
|
||||||
|
cluster.local_status(LEADER)
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
!status_bool(&cluster, LEADER, "reseed_required"),
|
||||||
|
"the reseeded node must clear its reseed marker: {:?}",
|
||||||
|
cluster.local_status(LEADER)
|
||||||
|
);
|
||||||
|
|
||||||
|
// It serves reads (an item the elected leader wrote during/after the kill is
|
||||||
|
// visible on the reseeded node — the snapshot+stream delivered it).
|
||||||
|
// Convergence-class wait: the snapshot install + text-index rebuild +
|
||||||
|
// ~2 s auto-commit compete with suite-parallel load, so a fixed short
|
||||||
|
// budget flakes on busy hosts; use the harness convergence budget
|
||||||
|
// (30 s default, TIDAL_TEST_CONVERGENCE_BUDGET_SECS to widen).
|
||||||
|
let probe_deadline = Instant::now() + convergence_budget();
|
||||||
|
loop {
|
||||||
|
// Item 1 was written by the original leader's load; it is part of the
|
||||||
|
// committed prefix the elected leader carried, so the reseeded node must
|
||||||
|
// serve it.
|
||||||
|
if item_searchable(&cluster, LEADER, 1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
Instant::now() < probe_deadline,
|
||||||
|
"the reseeded node does not serve a committed item — reads are broken"
|
||||||
|
);
|
||||||
|
std::thread::sleep(Duration::from_millis(200));
|
||||||
|
}
|
||||||
|
println!("[quarantine] reseeded node serves reads; quarantined=false, reseed_required=false");
|
||||||
|
}
|
||||||
@ -26,8 +26,8 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use tidal_server::cluster::{
|
use tidal_server::cluster::{
|
||||||
RegionClusterState, ElectionSpec, RegionSpec, ReplicationSpec, TimeoutsSpec, TopologySpec, WalSpec,
|
ElectionSpec, RegionClusterState, RegionSpec, ReplicationSpec, TimeoutsSpec, TopologySpec,
|
||||||
build_region_router,
|
WalSpec, build_region_router,
|
||||||
};
|
};
|
||||||
use tidaldb::schema::{DecaySpec, EntityKind, Schema, SchemaBuilder, Window};
|
use tidaldb::schema::{DecaySpec, EntityKind, Schema, SchemaBuilder, Window};
|
||||||
|
|
||||||
@ -83,6 +83,7 @@ impl Cluster3 {
|
|||||||
.map(|i| RegionSpec {
|
.map(|i| RegionSpec {
|
||||||
name: self.names[i].clone(),
|
name: self.names[i].clone(),
|
||||||
grpc_addr: Some(self.grpc[i].to_string()),
|
grpc_addr: Some(self.grpc[i].to_string()),
|
||||||
|
grpc_bind: None,
|
||||||
http_addr: Some(self.http[i].to_string()),
|
http_addr: Some(self.http[i].to_string()),
|
||||||
grpc_tls: None,
|
grpc_tls: None,
|
||||||
metrics_addr: None,
|
metrics_addr: None,
|
||||||
|
|||||||
375
tidal-server/tests/reseed_install.rs
Normal file
375
tidal-server/tests/reseed_install.rs
Normal file
@ -0,0 +1,375 @@
|
|||||||
|
//! m11p5 §2.2–§2.7: boot-time snapshot install end to end (B2/B3 slice).
|
||||||
|
//!
|
||||||
|
//! Drives the REAL `run_boot_install`: a fresh node with a latched
|
||||||
|
//! `reseed_required` marker discovers a leader over HTTP `/cluster/status/local`,
|
||||||
|
//! adopts the leader's term durably, fetches a snapshot from the leader's gRPC
|
||||||
|
//! `FetchSnapshot` (a fake `SnapshotSource` serving a staged tempdir), verifies
|
||||||
|
//! BLAKE3 + completeness, copies its identity files into staging, writes the
|
||||||
|
//! sentinels, and swaps the staged dir in.
|
||||||
|
//!
|
||||||
|
//! Asserts the wire contract end to end:
|
||||||
|
//! - `Installed`: the staged bytes are now canonical in the data dir, the
|
||||||
|
//! install sentinel is present (drives the §2.6 post-open seed), the reseed
|
||||||
|
//! marker is gone, and the node's own `election_state` survived inside staging
|
||||||
|
//! (§2.5 vote safety);
|
||||||
|
//! - the term was adopted durably BEFORE the fetch (§2.7 persist-before-act);
|
||||||
|
//! - `needed=false`: the marker is CLEARED and nothing is swapped (the
|
||||||
|
//! self-correcting "retry the normal boot" path, §2.2d).
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used)] // test assertions on known-good fixtures
|
||||||
|
|
||||||
|
use std::io::Write;
|
||||||
|
use std::net::SocketAddr;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use tidal_net::{
|
||||||
|
GrpcTransport, GrpcTransportConfig,
|
||||||
|
sources::{ServingSources, SnapshotSource, SnapshotStageError, SnapshotStaging},
|
||||||
|
};
|
||||||
|
use tidal_server::cluster::reseed::{self, InstallOutcome};
|
||||||
|
use tidaldb::replication::{
|
||||||
|
ElectionStore, HardState, ReseedMarker, ReseedMarkerStore, ReseedReason, shard::ShardId,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Bind port 0 to obtain a free, OS-assigned address.
|
||||||
|
fn free_addr() -> SocketAddr {
|
||||||
|
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||||
|
listener.local_addr().expect("local_addr")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A staged snapshot artifact: a tempdir holding files, manifest BLAKE3/size
|
||||||
|
/// computed from the bytes on disk.
|
||||||
|
struct StagedDir {
|
||||||
|
_dir: tempfile::TempDir,
|
||||||
|
root: std::path::PathBuf,
|
||||||
|
manifest: Vec<(String, u64, [u8; 32])>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StagedDir {
|
||||||
|
fn new(files: &[(&str, &[u8])]) -> Self {
|
||||||
|
let dir = tempfile::tempdir().expect("tempdir");
|
||||||
|
let root = dir.path().to_path_buf();
|
||||||
|
let mut manifest = Vec::new();
|
||||||
|
for (rel, bytes) in files {
|
||||||
|
let abs = root.join(rel);
|
||||||
|
if let Some(parent) = abs.parent() {
|
||||||
|
std::fs::create_dir_all(parent).expect("mkdir");
|
||||||
|
}
|
||||||
|
std::fs::write(&abs, bytes).expect("write file");
|
||||||
|
let hash = blake3::hash(bytes);
|
||||||
|
manifest.push(((*rel).to_string(), bytes.len() as u64, *hash.as_bytes()));
|
||||||
|
}
|
||||||
|
Self {
|
||||||
|
_dir: dir,
|
||||||
|
root,
|
||||||
|
manifest,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `SnapshotSource` serving a fixed staged dir; `needed` toggles the
|
||||||
|
/// no-snapshot-needed path.
|
||||||
|
struct FakeSnapshots {
|
||||||
|
staged: Arc<StagedDir>,
|
||||||
|
needed: bool,
|
||||||
|
snapshot_seq: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SnapshotSource for FakeSnapshots {
|
||||||
|
fn stage(&self, _from_seqno: u64) -> Result<SnapshotStaging, SnapshotStageError> {
|
||||||
|
Ok(SnapshotStaging {
|
||||||
|
needed: self.needed,
|
||||||
|
snapshot_seq: self.snapshot_seq,
|
||||||
|
root: self.staged.root.clone(),
|
||||||
|
files: if self.needed {
|
||||||
|
self.staged.manifest.clone()
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn release(&self) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a real gRPC leader serving `FetchSnapshot` from `source`.
|
||||||
|
fn leader_grpc(listen: SocketAddr, source: Arc<dyn SnapshotSource>) -> GrpcTransport {
|
||||||
|
let sources = ServingSources::default();
|
||||||
|
sources.set_snapshot_source(source);
|
||||||
|
GrpcTransport::new_with_sources(
|
||||||
|
GrpcTransportConfig {
|
||||||
|
local_shard: ShardId(0),
|
||||||
|
listen_addr: listen,
|
||||||
|
insecure: true,
|
||||||
|
..GrpcTransportConfig::default()
|
||||||
|
},
|
||||||
|
sources,
|
||||||
|
)
|
||||||
|
.expect("leader transport")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start a tiny HTTP server on a dedicated thread that answers
|
||||||
|
/// `GET /cluster/status/local` with `{is_leader, term}`. Returns the address +
|
||||||
|
/// a runtime handle kept alive for the test.
|
||||||
|
fn leader_http_status(is_leader: bool, term: u64) -> (SocketAddr, std::thread::JoinHandle<()>) {
|
||||||
|
use axum::{Json, Router, routing::get};
|
||||||
|
|
||||||
|
let addr = free_addr();
|
||||||
|
let handle = std::thread::Builder::new()
|
||||||
|
.name("test-status-http".into())
|
||||||
|
.spawn(move || {
|
||||||
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
rt.block_on(async move {
|
||||||
|
let app = Router::new().route(
|
||||||
|
"/cluster/status/local",
|
||||||
|
get(move || async move {
|
||||||
|
Json(serde_json::json!({
|
||||||
|
"is_leader": is_leader,
|
||||||
|
"term": term,
|
||||||
|
"region": "leader",
|
||||||
|
}))
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
});
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
// Give the server a moment to bind.
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||||
|
(addr, handle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a 2-region topology naming the leader's HTTP + gRPC addresses.
|
||||||
|
fn write_topology(
|
||||||
|
dir: &Path,
|
||||||
|
leader_http: SocketAddr,
|
||||||
|
leader_grpc: SocketAddr,
|
||||||
|
) -> std::path::PathBuf {
|
||||||
|
let path = dir.join("topology.yaml");
|
||||||
|
let mut f = std::fs::File::create(&path).unwrap();
|
||||||
|
// `joiner` is this node; `leader` is the discovered leader. The joiner's
|
||||||
|
// addresses are placeholders (it never dials itself during discovery).
|
||||||
|
writeln!(f, "regions:").unwrap();
|
||||||
|
writeln!(f, " - name: joiner").unwrap();
|
||||||
|
writeln!(f, " grpc_addr: 127.0.0.1:1").unwrap();
|
||||||
|
writeln!(f, " http_addr: 127.0.0.1:2").unwrap();
|
||||||
|
writeln!(f, " - name: leader").unwrap();
|
||||||
|
writeln!(f, " grpc_addr: {leader_grpc}").unwrap();
|
||||||
|
writeln!(f, " http_addr: {leader_http}").unwrap();
|
||||||
|
writeln!(f, "leader: leader").unwrap();
|
||||||
|
path
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `data_dir` that is a SUBDIRECTORY of a tempdir (§2.3: the swap renames the
|
||||||
|
/// data dir, so it must not be a mount root).
|
||||||
|
fn data_dir_in(tmp: &Path) -> std::path::PathBuf {
|
||||||
|
let d = tmp.join("db");
|
||||||
|
std::fs::create_dir_all(&d).unwrap();
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn boot_install_discovers_fetches_and_swaps() {
|
||||||
|
let _ = tracing_subscriber::fmt::try_init();
|
||||||
|
let file_a: &[u8] = b"snapshot ledger bytes";
|
||||||
|
let file_b: Vec<u8> = (0u8..=255).cycle().take(2_500_000).collect(); // multi-chunk
|
||||||
|
let staged = Arc::new(StagedDir::new(&[
|
||||||
|
("ledger/000001.sst", file_a),
|
||||||
|
("wal/seg-0001.seg", &file_b),
|
||||||
|
]));
|
||||||
|
|
||||||
|
let grpc_addr = free_addr();
|
||||||
|
let _grpc = leader_grpc(
|
||||||
|
grpc_addr,
|
||||||
|
Arc::new(FakeSnapshots {
|
||||||
|
staged: Arc::clone(&staged),
|
||||||
|
needed: true,
|
||||||
|
snapshot_seq: 4096,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let (http_addr, _http) = leader_http_status(true, 7);
|
||||||
|
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let data_dir = data_dir_in(tmp.path());
|
||||||
|
let topo_path = write_topology(tmp.path(), http_addr, grpc_addr);
|
||||||
|
let topology = tidal_server::cluster::load_topology(Some(&topo_path)).unwrap();
|
||||||
|
|
||||||
|
// The node's own identity: a durable election_state at term 3 that MUST
|
||||||
|
// survive the swap inside staging (§2.5), and a WAL dir (so the node looks
|
||||||
|
// like it has run before).
|
||||||
|
std::fs::create_dir_all(data_dir.join("wal")).unwrap();
|
||||||
|
let estore = ElectionStore::new(&data_dir);
|
||||||
|
estore
|
||||||
|
.persist(HardState {
|
||||||
|
current_term: 3,
|
||||||
|
voted_for: None,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Latch a snapshot-required marker recorded at from_seqno 100.
|
||||||
|
let marker_store = ReseedMarkerStore::new(&data_dir);
|
||||||
|
marker_store
|
||||||
|
.persist(ReseedMarker {
|
||||||
|
reason: ReseedReason::SnapshotRequired,
|
||||||
|
from_seqno: 100,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let outcome = reseed::run_boot_install_with(
|
||||||
|
&topology,
|
||||||
|
"joiner",
|
||||||
|
&data_dir,
|
||||||
|
std::time::Duration::from_secs(8),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(outcome, InstallOutcome::Installed, "the snapshot installs");
|
||||||
|
|
||||||
|
// The staged bytes are now canonical in the data dir.
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(data_dir.join("ledger/000001.sst")).unwrap(),
|
||||||
|
file_a
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(data_dir.join("wal/seg-0001.seg")).unwrap(),
|
||||||
|
file_b
|
||||||
|
);
|
||||||
|
|
||||||
|
// The install sentinel is present and records the artifact seq AND the
|
||||||
|
// discovered leader's region (drives §2.6 + the post-install catch-up pull).
|
||||||
|
// `leader` is region index 1 in the topology (`joiner` is 0).
|
||||||
|
let sentinel = reseed::read_install_sentinel(&data_dir).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
sentinel,
|
||||||
|
Some(reseed::InstallSentinel {
|
||||||
|
snapshot_seq: 4096,
|
||||||
|
leader_region: Some(1),
|
||||||
|
}),
|
||||||
|
"install sentinel carries the artifact seq + discovered leader region"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The reseed marker is GONE (it lived in the old dir, discarded by the swap).
|
||||||
|
assert_eq!(
|
||||||
|
marker_store.load().unwrap(),
|
||||||
|
None,
|
||||||
|
"marker consumed by the swap"
|
||||||
|
);
|
||||||
|
|
||||||
|
// §2.5: the node's own election_state survived INSIDE staging — term 3, and
|
||||||
|
// the discovered term 7 was adopted durably (persist-before-act, §2.7),
|
||||||
|
// overwriting it (7 > 3).
|
||||||
|
let recovered = match estore.load(true).unwrap() {
|
||||||
|
tidaldb::replication::BootState::Rejoin(h) => h,
|
||||||
|
other => panic!("expected Rejoin, got {other:?}"),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
recovered.current_term, 7,
|
||||||
|
"the discovered leader term was adopted durably before the fetch (§2.7)"
|
||||||
|
);
|
||||||
|
|
||||||
|
// No staging or discard dirs leak after a successful swap.
|
||||||
|
let dirs = reseed::SwapDirs::derive(&data_dir).unwrap();
|
||||||
|
assert!(!dirs.staging.exists(), "staging consumed");
|
||||||
|
assert!(!dirs.discard.exists(), "discard cleaned up");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn boot_install_needed_false_clears_marker_and_does_not_swap() {
|
||||||
|
let _ = tracing_subscriber::fmt::try_init();
|
||||||
|
// A leader whose live WAL still covers the frontier → needed=false.
|
||||||
|
let staged = Arc::new(StagedDir::new(&[("unused", b"x")]));
|
||||||
|
let grpc_addr = free_addr();
|
||||||
|
let _grpc = leader_grpc(
|
||||||
|
grpc_addr,
|
||||||
|
Arc::new(FakeSnapshots {
|
||||||
|
staged,
|
||||||
|
needed: false,
|
||||||
|
snapshot_seq: 0,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
let (http_addr, _http) = leader_http_status(true, 2);
|
||||||
|
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let data_dir = data_dir_in(tmp.path());
|
||||||
|
let topo_path = write_topology(tmp.path(), http_addr, grpc_addr);
|
||||||
|
let topology = tidal_server::cluster::load_topology(Some(&topo_path)).unwrap();
|
||||||
|
|
||||||
|
std::fs::write(data_dir.join("existing"), b"keep me").unwrap();
|
||||||
|
let marker_store = ReseedMarkerStore::new(&data_dir);
|
||||||
|
marker_store
|
||||||
|
.persist(ReseedMarker {
|
||||||
|
reason: ReseedReason::SnapshotRequired,
|
||||||
|
from_seqno: 50,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let outcome = reseed::run_boot_install_with(
|
||||||
|
&topology,
|
||||||
|
"joiner",
|
||||||
|
&data_dir,
|
||||||
|
std::time::Duration::from_secs(8),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
outcome,
|
||||||
|
InstallOutcome::NotNeeded,
|
||||||
|
"needed=false clears the marker, no swap"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
marker_store.load().unwrap(),
|
||||||
|
None,
|
||||||
|
"marker cleared (self-correcting)"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
data_dir.join("existing").exists(),
|
||||||
|
"the existing data dir is untouched (no swap)"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
reseed::read_install_sentinel(&data_dir).unwrap().is_none(),
|
||||||
|
"no install sentinel on the needed=false path"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A marker boot whose leader is unreachable FALLS BACK (degraded), never blocks
|
||||||
|
/// boot forever — the review-blocker fix (§2.2). The marker stays latched.
|
||||||
|
#[test]
|
||||||
|
fn boot_install_falls_back_when_no_leader_reachable() {
|
||||||
|
let _ = tracing_subscriber::fmt::try_init();
|
||||||
|
// A status server that reports is_leader=FALSE (no leader to be found), and
|
||||||
|
// an unbound gRPC port. Discovery never succeeds → fall back.
|
||||||
|
let (http_addr, _http) = leader_http_status(false, 0);
|
||||||
|
let grpc_addr = free_addr(); // nothing listening here
|
||||||
|
|
||||||
|
let tmp = tempfile::tempdir().unwrap();
|
||||||
|
let data_dir = data_dir_in(tmp.path());
|
||||||
|
let topo_path = write_topology(tmp.path(), http_addr, grpc_addr);
|
||||||
|
let topology = tidal_server::cluster::load_topology(Some(&topo_path)).unwrap();
|
||||||
|
|
||||||
|
let marker_store = ReseedMarkerStore::new(&data_dir);
|
||||||
|
marker_store
|
||||||
|
.persist(ReseedMarker {
|
||||||
|
reason: ReseedReason::SnapshotRequired,
|
||||||
|
from_seqno: 10,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let outcome = reseed::run_boot_install_with(
|
||||||
|
&topology,
|
||||||
|
"joiner",
|
||||||
|
&data_dir,
|
||||||
|
std::time::Duration::from_millis(600),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
outcome,
|
||||||
|
InstallOutcome::FellBack,
|
||||||
|
"an unreachable leader falls back to opening the existing dir (never blocks boot)"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
marker_store.load().unwrap().is_some(),
|
||||||
|
"the marker stays latched on fallback (the reseed retries next boot)"
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -118,6 +118,28 @@ pub fn identity_rewrite() -> AddrRewrite {
|
|||||||
Box::new(|_observer, _peer, _kind, addr| addr.to_string())
|
Box::new(|_observer, _peer, _kind, addr| addr.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// DNS-hostname rewrite (m11p5 §1, exit gate 4): every PEER `grpc_addr` is
|
||||||
|
/// published as `localhost:<port>` — a HOSTNAME, not a literal `SocketAddr` — so
|
||||||
|
/// the full dial stack must route through the DNS resolver (`Channel::from_shared`
|
||||||
|
/// re-resolution, the entire point of the `String` peer retype). The loopback
|
||||||
|
/// loses no reachability (`localhost` resolves to `127.0.0.1`), but a peer entry
|
||||||
|
/// that the pre-m11p5 `SocketAddr::parse` would have REJECTED at boot now must
|
||||||
|
/// boot, replicate, and survive restarts — proving the resolver is in the path.
|
||||||
|
///
|
||||||
|
/// HTTP peer entries keep the real IP: the test client dials each node's HTTP
|
||||||
|
/// addr DIRECTLY (no rewrite on the operator console), and forwarding between
|
||||||
|
/// nodes is exercised separately; the gate is the gRPC *replication* dial. A
|
||||||
|
/// process's OWN region entry is never rewritten ([`write_topology_for`]), so the
|
||||||
|
/// bind side stays a real `0.0.0.0`/loopback `SocketAddr` and only the advertised
|
||||||
|
/// peer name is a hostname — the exact bind/advertise split §1 specifies.
|
||||||
|
#[must_use]
|
||||||
|
pub fn hostname_rewrite() -> AddrRewrite {
|
||||||
|
Box::new(|_observer, _peer, kind, addr| match kind {
|
||||||
|
AddrKind::Grpc => format!("localhost:{}", addr.port()),
|
||||||
|
AddrKind::Http => addr.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// Options for [`MultiProcCluster::start_with`].
|
/// Options for [`MultiProcCluster::start_with`].
|
||||||
pub struct ClusterOptions {
|
pub struct ClusterOptions {
|
||||||
/// Number of regions (one OS process each). Must be >= 2.
|
/// Number of regions (one OS process each). Must be >= 2.
|
||||||
@ -446,6 +468,29 @@ impl MultiProcCluster {
|
|||||||
&self.client
|
&self.client
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Total on-disk size (bytes) of node `idx`'s data dir — the engine's
|
||||||
|
/// recursive footprint after a snapshot install + catch-up. The exit-gate-2
|
||||||
|
/// "≤5 min @ 100k items" evidence run records this as the installed-artifact
|
||||||
|
/// proxy (a freshly seed-joined node's data dir IS the fetched snapshot plus
|
||||||
|
/// the streamed suffix). Best-effort: unreadable entries are skipped.
|
||||||
|
#[must_use]
|
||||||
|
pub fn data_dir_bytes(&self, idx: usize) -> u64 {
|
||||||
|
fn dir_bytes(path: &Path) -> u64 {
|
||||||
|
let Ok(entries) = std::fs::read_dir(path) else {
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
entries
|
||||||
|
.flatten()
|
||||||
|
.map(|e| match e.file_type() {
|
||||||
|
Ok(ft) if ft.is_dir() => dir_bytes(&e.path()),
|
||||||
|
Ok(_) => e.metadata().map(|m| m.len()).unwrap_or(0),
|
||||||
|
Err(_) => 0,
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
dir_bytes(&self.plans[idx].data_dir)
|
||||||
|
}
|
||||||
|
|
||||||
// ── HTTP helpers ─────────────────────────────────────────────────────────
|
// ── HTTP helpers ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
/// `GET {node(idx)}{path}`.
|
/// `GET {node(idx)}{path}`.
|
||||||
@ -593,6 +638,153 @@ impl MultiProcCluster {
|
|||||||
self.wait_health_inner(idx, deadline);
|
self.wait_health_inner(idx, deadline);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Elasticity: seed-join add / remove (m11p5 §3.4) ────────────────────────
|
||||||
|
|
||||||
|
/// Add a NEW node that seed-joins the cluster (m11p5 §3.4): allocate ports +
|
||||||
|
/// a data dir, write a knob-only topology variant (node `seed_of`'s topology
|
||||||
|
/// file — the joiner reads its `regions:` list for KNOBS only, the join
|
||||||
|
/// response is the roster), then spawn `cluster --region region-N
|
||||||
|
/// --seed http://<seed http_addr> --advertise-grpc <p> --advertise-http <p2>
|
||||||
|
/// --topology <knob file>`. Waits for `/health/startup` (the joiner reports
|
||||||
|
/// 503 until first-converged, then 200 — so health gates on convergence,
|
||||||
|
/// proving the snapshot+stream catch-up landed). Returns the new node's index.
|
||||||
|
///
|
||||||
|
/// The data dir is a SUBDIRECTORY of the harness tempdir (a mount root would
|
||||||
|
/// fail the §2.3 swap), so a snapshot install's rename siblings have a parent.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// Panics if `seed_of` is out of range, files cannot be written, the binary
|
||||||
|
/// cannot be spawned, or the joiner does not become healthy within
|
||||||
|
/// [`boot_budget`] (a join+install over loopback).
|
||||||
|
pub fn add_node(&mut self, seed_of: usize) -> usize {
|
||||||
|
assert!(
|
||||||
|
seed_of < self.plans.len(),
|
||||||
|
"add_node: seed {seed_of} out of range"
|
||||||
|
);
|
||||||
|
let spawn_guard = spawn_lock()
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
|
||||||
|
let idx = self.plans.len();
|
||||||
|
let name = region_name(idx);
|
||||||
|
let grpc = free_addr();
|
||||||
|
let http = free_addr();
|
||||||
|
// The harness tempdir is the parent of every node's data dir (the `_tmp`
|
||||||
|
// field is underscore-held for Drop ordering; reach the path through an
|
||||||
|
// existing plan to avoid touching the underscore binding directly).
|
||||||
|
let tmp_root = self.plans[0]
|
||||||
|
.data_dir
|
||||||
|
.parent()
|
||||||
|
.expect("a node data dir always has the tempdir as its parent")
|
||||||
|
.to_path_buf();
|
||||||
|
let data_dir = tmp_root.join(format!("region-{idx}"));
|
||||||
|
std::fs::create_dir_all(&data_dir).expect("create joiner data dir");
|
||||||
|
|
||||||
|
// The knob source (§3.5): a topology file whose `regions:` is the INITIAL
|
||||||
|
// roster (NOT this joiner) — the joiner's own region is learned from the
|
||||||
|
// join response, not this file. Reusing the seed node's topology file is
|
||||||
|
// exactly the k8s shared-ConfigMap shape. We write a fresh copy so a
|
||||||
|
// concurrent restart of the seed never races this file handle.
|
||||||
|
let knob_path = {
|
||||||
|
let path = tmp_root.join(format!("topology-seed-{idx}.yaml"));
|
||||||
|
let body = std::fs::read_to_string(&self.topology_paths[seed_of])
|
||||||
|
.expect("read seed topology for knobs");
|
||||||
|
std::fs::write(&path, body).expect("write joiner knob topology");
|
||||||
|
path
|
||||||
|
};
|
||||||
|
|
||||||
|
let seed_http = self.plans[seed_of].http;
|
||||||
|
let bin = tidal_server_bin();
|
||||||
|
let mut cmd = Command::new(&bin);
|
||||||
|
cmd.arg("cluster")
|
||||||
|
.arg("--region")
|
||||||
|
.arg(&name)
|
||||||
|
.arg("--listen")
|
||||||
|
.arg(http.to_string())
|
||||||
|
.arg("--schema")
|
||||||
|
.arg(&self.schema_path)
|
||||||
|
.arg("--topology")
|
||||||
|
.arg(&knob_path)
|
||||||
|
.arg("--data-dir")
|
||||||
|
.arg(&data_dir)
|
||||||
|
.arg("--seed")
|
||||||
|
.arg(format!("http://{seed_http}"))
|
||||||
|
.arg("--advertise-grpc")
|
||||||
|
.arg(grpc.to_string())
|
||||||
|
.arg("--advertise-http")
|
||||||
|
.arg(http.to_string())
|
||||||
|
.env("TIDAL_ALLOW_EXPERIMENTAL_CLUSTER", "1")
|
||||||
|
.env("TIDAL_SERVER_LOG", &self.log)
|
||||||
|
// Bound the join + the (rare) install handshake inside the test budget
|
||||||
|
// rather than the production defaults.
|
||||||
|
.env("TIDAL_SEED_JOIN_MS", "60000")
|
||||||
|
.env("TIDAL_RESEED_HANDSHAKE_MS", "30000");
|
||||||
|
let inherit_logs = std::env::var("TIDAL_TEST_NODE_LOGS").is_ok_and(|v| v == "inherit");
|
||||||
|
if inherit_logs {
|
||||||
|
cmd.stdout(std::process::Stdio::inherit())
|
||||||
|
.stderr(std::process::Stdio::inherit());
|
||||||
|
} else {
|
||||||
|
cmd.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null());
|
||||||
|
}
|
||||||
|
let child = cmd
|
||||||
|
.spawn()
|
||||||
|
.unwrap_or_else(|e| panic!("failed to spawn seed-join node {name}: {e}"));
|
||||||
|
|
||||||
|
// Register the new node in the harness tables (so `local_status`,
|
||||||
|
// convergence polls, and Drop all see it).
|
||||||
|
self.plans.push(RegionPlan {
|
||||||
|
name: name.clone(),
|
||||||
|
grpc,
|
||||||
|
http,
|
||||||
|
data_dir,
|
||||||
|
});
|
||||||
|
self.topology_paths.push(knob_path);
|
||||||
|
self.nodes.push(NodeHandle {
|
||||||
|
name,
|
||||||
|
http,
|
||||||
|
process: Some(child),
|
||||||
|
});
|
||||||
|
drop(spawn_guard);
|
||||||
|
|
||||||
|
std::thread::sleep(SETTLE);
|
||||||
|
// The joiner's /health/startup is 503 until first-converged (§4 sticky
|
||||||
|
// readiness), so this wait proves the snapshot+stream catch-up landed.
|
||||||
|
// Give it the convergence budget on top of the boot budget (a join +
|
||||||
|
// possible install + catch-up).
|
||||||
|
let deadline = Instant::now() + boot_budget() + convergence_budget();
|
||||||
|
self.wait_health_inner(idx, deadline);
|
||||||
|
idx
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove (decommission) a member via the `/cluster/members/remove` verb
|
||||||
|
/// (m11p5 §3.3): POST to the current leader (the verb forwards from a
|
||||||
|
/// follower, but targeting the leader avoids a hop). After this the leader
|
||||||
|
/// appends a `Removed` record; the removed node learns via the stream and
|
||||||
|
/// flips to readiness 503 + stops campaigning. Returns the leader's response
|
||||||
|
/// status code.
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// Panics if no live leader can be found.
|
||||||
|
pub fn remove_node(&self, name: &str) -> u16 {
|
||||||
|
let leader_idx = self
|
||||||
|
.live_indices()
|
||||||
|
.into_iter()
|
||||||
|
.find(|&i| {
|
||||||
|
self.local_status(i)
|
||||||
|
.is_some_and(|s| s["is_leader"].as_bool() == Some(true))
|
||||||
|
})
|
||||||
|
.expect("remove_node: no live leader found to issue the remove verb");
|
||||||
|
let resp = self.post(
|
||||||
|
leader_idx,
|
||||||
|
"/cluster/members/remove",
|
||||||
|
&serde_json::json!({ "region": name }),
|
||||||
|
);
|
||||||
|
resp.status().as_u16()
|
||||||
|
}
|
||||||
|
|
||||||
// ── Health / convergence / leadership polling ──────────────────────────────
|
// ── Health / convergence / leadership polling ──────────────────────────────
|
||||||
|
|
||||||
/// Block until node `idx` reports healthy, or [`boot_budget`] elapses.
|
/// Block until node `idx` reports healthy, or [`boot_budget`] elapses.
|
||||||
|
|||||||
@ -3,13 +3,13 @@
|
|||||||
# Compare to T1 leader-ack ceiling (≥2,000/s); expect ≥50% of that number.
|
# Compare to T1 leader-ack ceiling (≥2,000/s); expect ≥50% of that number.
|
||||||
#
|
#
|
||||||
# Apply: kubectl apply -f tidal-stress/k8s/stress-job-t2a.yaml
|
# Apply: kubectl apply -f tidal-stress/k8s/stress-job-t2a.yaml
|
||||||
# Watch: kubectl logs -f job/tidal-stress-t2a -n tidaldb
|
# Watch: kubectl logs -f job/tidal-stress-t2a -n tidaldb-cluster
|
||||||
# Rearm: kubectl delete job tidal-stress-t2a -n tidaldb
|
# Rearm: kubectl delete job tidal-stress-t2a -n tidaldb-cluster
|
||||||
apiVersion: batch/v1
|
apiVersion: batch/v1
|
||||||
kind: Job
|
kind: Job
|
||||||
metadata:
|
metadata:
|
||||||
name: tidal-stress-t2a
|
name: tidal-stress-t2a
|
||||||
namespace: tidaldb
|
namespace: tidaldb-cluster
|
||||||
labels:
|
labels:
|
||||||
app.kubernetes.io/name: tidal-stress
|
app.kubernetes.io/name: tidal-stress
|
||||||
app.kubernetes.io/part-of: tidaldb
|
app.kubernetes.io/part-of: tidaldb
|
||||||
@ -26,10 +26,11 @@ spec:
|
|||||||
automountServiceAccountToken: false
|
automountServiceAccountToken: false
|
||||||
affinity:
|
affinity:
|
||||||
podAntiAffinity:
|
podAntiAffinity:
|
||||||
|
# Keep the generator off the leader's node (pod tidaldb-0).
|
||||||
requiredDuringSchedulingIgnoredDuringExecution:
|
requiredDuringSchedulingIgnoredDuringExecution:
|
||||||
- labelSelector:
|
- labelSelector:
|
||||||
matchLabels:
|
matchLabels:
|
||||||
tidaldb.region: us-east
|
statefulset.kubernetes.io/pod-name: tidaldb-0
|
||||||
topologyKey: kubernetes.io/hostname
|
topologyKey: kubernetes.io/hostname
|
||||||
securityContext:
|
securityContext:
|
||||||
runAsNonRoot: true
|
runAsNonRoot: true
|
||||||
@ -43,13 +44,13 @@ spec:
|
|||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
args:
|
args:
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.11:9500 # us-east (leader)
|
- http://tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-0 (initial leader)
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.12:9500 # eu-west
|
- http://tidaldb-1.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-1
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.13:9500 # ap-south
|
- http://tidaldb-2.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-2
|
||||||
- --leader-url
|
- --leader-url
|
||||||
- http://10.43.99.11:9500
|
- http://tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500
|
||||||
- --ack
|
- --ack
|
||||||
- quorum
|
- quorum
|
||||||
- --ramp
|
- --ramp
|
||||||
|
|||||||
@ -3,13 +3,13 @@
|
|||||||
# Kill the leader pod mid-run, promote a survivor, observe recovery.
|
# Kill the leader pod mid-run, promote a survivor, observe recovery.
|
||||||
#
|
#
|
||||||
# Apply: kubectl apply -f tidal-stress/k8s/stress-job-t2b.yaml
|
# Apply: kubectl apply -f tidal-stress/k8s/stress-job-t2b.yaml
|
||||||
# Watch: kubectl logs -f job/tidal-stress-t2b -n tidaldb
|
# Watch: kubectl logs -f job/tidal-stress-t2b -n tidaldb-cluster
|
||||||
# Rearm: kubectl delete job tidal-stress-t2b -n tidaldb
|
# Rearm: kubectl delete job tidal-stress-t2b -n tidaldb-cluster
|
||||||
apiVersion: batch/v1
|
apiVersion: batch/v1
|
||||||
kind: Job
|
kind: Job
|
||||||
metadata:
|
metadata:
|
||||||
name: tidal-stress-t2b
|
name: tidal-stress-t2b
|
||||||
namespace: tidaldb
|
namespace: tidaldb-cluster
|
||||||
labels:
|
labels:
|
||||||
app.kubernetes.io/name: tidal-stress
|
app.kubernetes.io/name: tidal-stress
|
||||||
app.kubernetes.io/part-of: tidaldb
|
app.kubernetes.io/part-of: tidaldb
|
||||||
@ -26,10 +26,14 @@ spec:
|
|||||||
automountServiceAccountToken: false
|
automountServiceAccountToken: false
|
||||||
affinity:
|
affinity:
|
||||||
podAntiAffinity:
|
podAntiAffinity:
|
||||||
|
# Keep the generator off the initial leader's node (pod tidaldb-0).
|
||||||
|
# NOTE: this kill drill deposes that leader mid-run; the antiaffinity
|
||||||
|
# pins the generator off tidaldb-0's node only — after failover the new
|
||||||
|
# leader may share the generator's node (acceptable for a recovery drill).
|
||||||
requiredDuringSchedulingIgnoredDuringExecution:
|
requiredDuringSchedulingIgnoredDuringExecution:
|
||||||
- labelSelector:
|
- labelSelector:
|
||||||
matchLabels:
|
matchLabels:
|
||||||
tidaldb.region: us-east
|
statefulset.kubernetes.io/pod-name: tidaldb-0
|
||||||
topologyKey: kubernetes.io/hostname
|
topologyKey: kubernetes.io/hostname
|
||||||
securityContext:
|
securityContext:
|
||||||
runAsNonRoot: true
|
runAsNonRoot: true
|
||||||
@ -43,13 +47,13 @@ spec:
|
|||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
args:
|
args:
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.11:9500 # us-east (initial leader)
|
- http://tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-0 (initial leader)
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.12:9500 # eu-west
|
- http://tidaldb-1.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-1
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.13:9500 # ap-south
|
- http://tidaldb-2.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-2
|
||||||
- --leader-url
|
- --leader-url
|
||||||
- http://10.43.99.11:9500
|
- http://tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500
|
||||||
- --ack
|
- --ack
|
||||||
- quorum
|
- quorum
|
||||||
- --ramp
|
- --ramp
|
||||||
|
|||||||
@ -1,14 +1,17 @@
|
|||||||
# In-cluster capacity ramp for the tidalDB multi-process cluster.
|
# In-cluster capacity ramp for the tidalDB multi-process cluster (m11p5 k8s/cluster/).
|
||||||
#
|
#
|
||||||
# Runs the load generator AS A POD so requests take the real cluster network path
|
# Runs the load generator AS A POD so requests take the real cluster network path
|
||||||
# (a `kubectl port-forward` serializes everything through the API server and adds
|
# (a `kubectl port-forward` serializes everything through the API server and adds
|
||||||
# tens of ms — useless for capacity numbers). Targets the three region ClusterIPs
|
# tens of ms — useless for capacity numbers). Targets the three region pods by
|
||||||
# directly; reads round-robin across them (each serves locally), leader-path
|
# their per-pod headless-Service DNS (tidaldb-N.tidaldb-peers...); reads
|
||||||
# writes are pinned to us-east (10.43.99.11) to measure the single-leader funnel.
|
# round-robin across them (each serves locally), leader-path writes are pinned to
|
||||||
|
# tidaldb-0 to measure the single-leader funnel. (Post-election the leader can
|
||||||
|
# move; for a long elasticity run let writes forward — every pod forwards to the
|
||||||
|
# current leader — or re-point --leader-url after a deliberate promote.)
|
||||||
#
|
#
|
||||||
# Apply: kubectl apply -f tidal-stress/k8s/stress-job.yaml
|
# Apply: kubectl apply -f tidal-stress/k8s/stress-job.yaml
|
||||||
# Watch: kubectl logs -f job/tidal-stress -n tidaldb
|
# Watch: kubectl logs -f job/tidal-stress -n tidaldb-cluster
|
||||||
# Re-run: kubectl delete job tidal-stress -n tidaldb; kubectl apply -f ...
|
# Re-run: kubectl delete job tidal-stress -n tidaldb-cluster; kubectl apply -f ...
|
||||||
#
|
#
|
||||||
# To compare the horizontally-scaled path, change `--write-path leader` to
|
# To compare the horizontally-scaled path, change `--write-path leader` to
|
||||||
# `--write-path sharded` (hash-partitions writes across all 3 regions, no funnel).
|
# `--write-path sharded` (hash-partitions writes across all 3 regions, no funnel).
|
||||||
@ -16,7 +19,7 @@ apiVersion: batch/v1
|
|||||||
kind: Job
|
kind: Job
|
||||||
metadata:
|
metadata:
|
||||||
name: tidal-stress
|
name: tidal-stress
|
||||||
namespace: tidaldb
|
namespace: tidaldb-cluster
|
||||||
labels:
|
labels:
|
||||||
app.kubernetes.io/name: tidal-stress
|
app.kubernetes.io/name: tidal-stress
|
||||||
app.kubernetes.io/part-of: tidaldb
|
app.kubernetes.io/part-of: tidaldb
|
||||||
@ -34,11 +37,12 @@ spec:
|
|||||||
affinity:
|
affinity:
|
||||||
podAntiAffinity:
|
podAntiAffinity:
|
||||||
# Keep the generator OFF the leader's node so it never steals CPU from
|
# Keep the generator OFF the leader's node so it never steals CPU from
|
||||||
# the write bottleneck we are measuring.
|
# the write bottleneck we are measuring. The leader is pod tidaldb-0;
|
||||||
|
# StatefulSet pods carry the auto label statefulset.kubernetes.io/pod-name.
|
||||||
requiredDuringSchedulingIgnoredDuringExecution:
|
requiredDuringSchedulingIgnoredDuringExecution:
|
||||||
- labelSelector:
|
- labelSelector:
|
||||||
matchLabels:
|
matchLabels:
|
||||||
tidaldb.region: us-east
|
statefulset.kubernetes.io/pod-name: tidaldb-0
|
||||||
topologyKey: kubernetes.io/hostname
|
topologyKey: kubernetes.io/hostname
|
||||||
securityContext:
|
securityContext:
|
||||||
runAsNonRoot: true
|
runAsNonRoot: true
|
||||||
@ -52,13 +56,13 @@ spec:
|
|||||||
imagePullPolicy: IfNotPresent
|
imagePullPolicy: IfNotPresent
|
||||||
args:
|
args:
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.11:9500 # us-east (leader)
|
- http://tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-0 (initial leader)
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.12:9500 # eu-west
|
- http://tidaldb-1.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-1
|
||||||
- --target
|
- --target
|
||||||
- http://10.43.99.13:9500 # ap-south
|
- http://tidaldb-2.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500 # region tidaldb-2
|
||||||
- --leader-url
|
- --leader-url
|
||||||
- http://10.43.99.11:9500
|
- http://tidaldb-0.tidaldb-peers.tidaldb-cluster.svc.cluster.local:9500
|
||||||
- --ramp
|
- --ramp
|
||||||
- peach-100k
|
- peach-100k
|
||||||
- --stage-secs
|
- --stage-secs
|
||||||
|
|||||||
@ -187,6 +187,10 @@ required-features = ["test-utils"]
|
|||||||
name = "review_pass2_zone_a_sessions"
|
name = "review_pass2_zone_a_sessions"
|
||||||
required-features = ["test-utils"]
|
required-features = ["test-utils"]
|
||||||
|
|
||||||
|
[[test]]
|
||||||
|
name = "m11p5_membership_record"
|
||||||
|
required-features = ["test-utils"]
|
||||||
|
|
||||||
[[bench]]
|
[[bench]]
|
||||||
name = "signals"
|
name = "signals"
|
||||||
harness = false
|
harness = false
|
||||||
|
|||||||
@ -1,7 +1,11 @@
|
|||||||
//! Backup support for tidalDB.
|
//! Backup support for tidalDB.
|
||||||
//!
|
//!
|
||||||
//! Provides [`TidalDb::create_backup`] which quiesces writes, flushes all
|
//! Provides [`TidalDb::create_backup`] which quiesces writes, flushes all
|
||||||
//! durable state, and copies the data directory to a destination path.
|
//! durable state, and copies the data directory to a destination path. The
|
||||||
|
//! internal [`TidalDb::create_backup_with`] takes the same path under a
|
||||||
|
//! [`BackupOptions`] knob set; the m11p5 snapshot-staging path uses it to skip
|
||||||
|
//! the (non-fatal, derived) text-index flush and so shorten the signal-write
|
||||||
|
//! quiesce window.
|
||||||
//!
|
//!
|
||||||
//! During the backup window, signal writes return
|
//! During the backup window, signal writes return
|
||||||
//! [`TidalError::Backpressure`] so callers know to retry. The window is
|
//! [`TidalError::Backpressure`] so callers know to retry. The window is
|
||||||
@ -14,6 +18,15 @@
|
|||||||
//! artifact is durable (not merely sitting in the page cache) the moment the
|
//! artifact is durable (not merely sitting in the page cache) the moment the
|
||||||
//! call completes. It is not taken under a hot write path; any signals written
|
//! call completes. It is not taken under a hot write path; any signals written
|
||||||
//! after the backup resumes are not included.
|
//! after the backup resumes are not included.
|
||||||
|
//!
|
||||||
|
//! The artifact double-counts no signal on restore: the signal ledger is
|
||||||
|
//! checkpointed at the captured seq and the WAL checkpoint marker in the copy is
|
||||||
|
//! written at the SAME seq, so WAL replay on the next open skips exactly the
|
||||||
|
//! events already folded into the checkpoint. Writing that marker is therefore
|
||||||
|
//! **fatal** — a staged artifact opened by a joiner with a stale (or missing)
|
||||||
|
//! marker re-folds checkpointed signals on top of the checkpoint, inflating
|
||||||
|
//! every aggregate it covers. See the consistency proof on
|
||||||
|
//! [`TidalDb::create_backup_with`].
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
fs::File,
|
fs::File,
|
||||||
@ -59,6 +72,44 @@ pub struct BackupInfo {
|
|||||||
pub size_bytes: u64,
|
pub size_bytes: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tunable knobs for [`TidalDb::create_backup_with`].
|
||||||
|
///
|
||||||
|
/// The public [`TidalDb::create_backup`] uses [`BackupOptions::default`]
|
||||||
|
/// (everything off) so its behavior is unchanged. The m11p5 snapshot-staging
|
||||||
|
/// path flips `skip_text_flush` to shorten the quiesce window and lists
|
||||||
|
/// `exclude_top_level` to keep node-identity / node-local files (and the
|
||||||
|
/// staging area itself) out of the artifact.
|
||||||
|
///
|
||||||
|
/// `Default` is `{ skip_text_flush: false, exclude_top_level: [] }` — byte-for-
|
||||||
|
/// byte today's behavior (`exclude_top_level` empty ⇒ nothing extra skipped,
|
||||||
|
/// only the always-skipped `tidaldb.lock` and fjall `.tmp` temps).
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
pub struct BackupOptions {
|
||||||
|
/// Skip the text-index flushes (step 5). Text indexes are derived state
|
||||||
|
/// rebuilt on open (the joiner regenerates them from durable entity rows),
|
||||||
|
/// so their on-disk freshness in the artifact is immaterial to correctness;
|
||||||
|
/// skipping the flush removes the only non-trivial cost between the signal
|
||||||
|
/// checkpoint and the copy, shortening how long signal writes are 429'd.
|
||||||
|
pub skip_text_flush: bool,
|
||||||
|
/// Top-level entries of the data dir (files OR directories, by exact name)
|
||||||
|
/// the recursive copy must skip. Matched ONLY at the data dir's top level —
|
||||||
|
/// a nested file that happens to share one of these names is copied (e.g. a
|
||||||
|
/// signal whose entity row lives deep in the fjall keyspace is never a
|
||||||
|
/// top-level entry, so `exclude_top_level` can never accidentally drop
|
||||||
|
/// payload).
|
||||||
|
///
|
||||||
|
/// The m11p5 snapshot-staging path lists the node-identity / node-local
|
||||||
|
/// files that must not travel to another node (`election_state`,
|
||||||
|
/// `stream_baseline`, `membership`, the `reseed_required` marker) PLUS the
|
||||||
|
/// staging area itself (`snapshots`) — without that last exclusion the copy
|
||||||
|
/// would recurse into the destination it is writing and copy itself (the
|
||||||
|
/// staging dir lives INSIDE the data dir so it stays on the same PVC, §2.3).
|
||||||
|
///
|
||||||
|
/// `&'static str` because every caller's exclusion set is a fixed list of
|
||||||
|
/// compile-time-known names (the constants above), never runtime-derived.
|
||||||
|
pub exclude_top_level: Vec<&'static str>,
|
||||||
|
}
|
||||||
|
|
||||||
/// RAII guard that clears the `backup_in_progress` flag on drop.
|
/// RAII guard that clears the `backup_in_progress` flag on drop.
|
||||||
///
|
///
|
||||||
/// Ensures the flag is always reset even if `create_backup` returns early
|
/// Ensures the flag is always reset even if `create_backup` returns early
|
||||||
@ -76,7 +127,15 @@ impl Drop for BackupGuard<'_> {
|
|||||||
/// Recursively copy all files and subdirectories from `src` to `dest`.
|
/// Recursively copy all files and subdirectories from `src` to `dest`.
|
||||||
///
|
///
|
||||||
/// Returns the total number of bytes copied. Skips `tidaldb.lock` (the
|
/// Returns the total number of bytes copied. Skips `tidaldb.lock` (the
|
||||||
/// advisory lock file is process-specific and will be recreated on open).
|
/// advisory lock file is process-specific and will be recreated on open) and
|
||||||
|
/// any TOP-LEVEL entry named in `exclude_top_level` (m11p5: the staging area
|
||||||
|
/// plus node-identity / node-local files — `election_state`, `stream_baseline`,
|
||||||
|
/// `membership`, the reseed marker — that must not travel inside a snapshot).
|
||||||
|
///
|
||||||
|
/// `exclude_top_level` is honored ONLY at this (top) level: the recursive calls
|
||||||
|
/// pass `&[]`, so a nested entry sharing one of those names is still copied.
|
||||||
|
/// This is deliberate — the exclusions are about top-level data-dir residents,
|
||||||
|
/// never about content deep in a keyspace.
|
||||||
///
|
///
|
||||||
/// Every copied file is `fsync`ed after its bytes are written, and `dest`
|
/// Every copied file is `fsync`ed after its bytes are written, and `dest`
|
||||||
/// itself is `fsync`ed once the level is fully populated so the new directory
|
/// itself is `fsync`ed once the level is fully populated so the new directory
|
||||||
@ -89,7 +148,11 @@ impl Drop for BackupGuard<'_> {
|
|||||||
///
|
///
|
||||||
/// Returns `TidalError::Durability` if any filesystem operation (copy, create,
|
/// Returns `TidalError::Durability` if any filesystem operation (copy, create,
|
||||||
/// or `fsync`) fails.
|
/// or `fsync`) fails.
|
||||||
fn copy_dir_recursive(src: &Path, dest: &Path) -> crate::Result<u64> {
|
fn copy_dir_recursive(
|
||||||
|
src: &Path,
|
||||||
|
dest: &Path,
|
||||||
|
exclude_top_level: &[&'static str],
|
||||||
|
) -> crate::Result<u64> {
|
||||||
let mut total_bytes: u64 = 0;
|
let mut total_bytes: u64 = 0;
|
||||||
// Whether this level received at least one entry (file copied or subdir
|
// Whether this level received at least one entry (file copied or subdir
|
||||||
// created). If so, we must fsync `dest` to make the new dirents durable.
|
// created). If so, we must fsync `dest` to make the new dirents durable.
|
||||||
@ -123,6 +186,12 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> crate::Result<u64> {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Skip any caller-requested top-level entry (m11p5 §2.3). Top-level
|
||||||
|
// only: the recursive calls below pass `&[]`.
|
||||||
|
if exclude_top_level.iter().any(|&ex| file_name_str == ex) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
let src_path = entry.path();
|
let src_path = entry.path();
|
||||||
let dest_path = dest.join(&file_name);
|
let dest_path = dest.join(&file_name);
|
||||||
|
|
||||||
@ -146,7 +215,10 @@ fn copy_dir_recursive(src: &Path, dest: &Path) -> crate::Result<u64> {
|
|||||||
message: format!("failed to create directory {}: {e}", dest_path.display()),
|
message: format!("failed to create directory {}: {e}", dest_path.display()),
|
||||||
})
|
})
|
||||||
})?;
|
})?;
|
||||||
total_bytes += copy_dir_recursive(&src_path, &dest_path)?;
|
// Recurse with NO exclusions: the exclusion list is a top-level
|
||||||
|
// contract only (a nested entry sharing one of those names is real
|
||||||
|
// payload and must be copied).
|
||||||
|
total_bytes += copy_dir_recursive(&src_path, &dest_path, &[])?;
|
||||||
dest_dirty = true;
|
dest_dirty = true;
|
||||||
} else if file_type.is_file() {
|
} else if file_type.is_file() {
|
||||||
match std::fs::copy(&src_path, &dest_path) {
|
match std::fs::copy(&src_path, &dest_path) {
|
||||||
@ -209,6 +281,54 @@ impl super::TidalDb {
|
|||||||
/// - `TidalError::Internal` if a backup is already in progress.
|
/// - `TidalError::Internal` if a backup is already in progress.
|
||||||
/// - `TidalError::Durability` if the flush or file copy fails.
|
/// - `TidalError::Durability` if the flush or file copy fails.
|
||||||
pub fn create_backup(&self, dest: &Path) -> crate::Result<BackupInfo> {
|
pub fn create_backup(&self, dest: &Path) -> crate::Result<BackupInfo> {
|
||||||
|
self.create_backup_with(dest, &BackupOptions::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a backup, parameterized by [`BackupOptions`].
|
||||||
|
///
|
||||||
|
/// This is the implementation [`create_backup`](Self::create_backup)
|
||||||
|
/// delegates to; public callers go through `create_backup` (options
|
||||||
|
/// defaulted). The m11p5 snapshot-staging path calls this directly with
|
||||||
|
/// `skip_text_flush: true` (text indexes are derived state, rebuilt on the
|
||||||
|
/// joiner's open) to shorten the signal-write quiesce window.
|
||||||
|
///
|
||||||
|
/// # Consistency proof (why the artifact never double-counts a signal)
|
||||||
|
///
|
||||||
|
/// The signal aggregate the artifact restores comes from exactly two
|
||||||
|
/// sources, fenced by ONE seq `S = last_wal_seq`:
|
||||||
|
///
|
||||||
|
/// 1. the signal-ledger **checkpoint** (step 4), which materializes every
|
||||||
|
/// aggregate as of `S` into fjall, and
|
||||||
|
/// 2. **WAL replay** of events with `seq > S` (step 8 writes the WAL
|
||||||
|
/// checkpoint marker at `S`; `reader::recover` replays strictly above
|
||||||
|
/// the marker).
|
||||||
|
///
|
||||||
|
/// The two are disjoint and cover the whole history, so the restored
|
||||||
|
/// aggregate equals the live one. This hinges on the marker being present
|
||||||
|
/// AND equal to the checkpoint seq. A marker BEHIND `S` (or absent) replays
|
||||||
|
/// events `≤ S` that the checkpoint already folded — double-counting every
|
||||||
|
/// signal those events carry, on top of the checkpoint. A marker AHEAD of
|
||||||
|
/// `S` suppresses replay of acked events the checkpoint did not capture —
|
||||||
|
/// lost acked signals. Because a staged snapshot artifact is opened by a
|
||||||
|
/// *joiner* (which then serves the resulting aggregate to a whole region),
|
||||||
|
/// step 8's marker write is therefore **fatal**: an artifact we cannot prove
|
||||||
|
/// consistent must not exist.
|
||||||
|
///
|
||||||
|
/// The in-flight-WAL-event analysis (an enqueued-but-unacked write missing
|
||||||
|
/// from the copy is an acceptable un-acked loss; a torn tail batch is
|
||||||
|
/// repaired on open) is unchanged — see the block comment at step 5b.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// - `TidalError::Internal` if the database is ephemeral (no data directory).
|
||||||
|
/// - `TidalError::Internal` if a backup is already in progress.
|
||||||
|
/// - `TidalError::Durability` if the flush, file copy, or the WAL checkpoint
|
||||||
|
/// marker / replication-HWM write fails.
|
||||||
|
pub(crate) fn create_backup_with(
|
||||||
|
&self,
|
||||||
|
dest: &Path,
|
||||||
|
opts: &BackupOptions,
|
||||||
|
) -> crate::Result<BackupInfo> {
|
||||||
// 1. Guard: only works for persistent mode.
|
// 1. Guard: only works for persistent mode.
|
||||||
let data_dir = self.config.data_dir.as_ref().ok_or_else(|| {
|
let data_dir = self.config.data_dir.as_ref().ok_or_else(|| {
|
||||||
TidalError::internal(
|
TidalError::internal(
|
||||||
@ -266,16 +386,42 @@ impl super::TidalDb {
|
|||||||
// secondary derived state with no WAL backstop; log and continue
|
// secondary derived state with no WAL backstop; log and continue
|
||||||
// rather than aborting the backup if any fails.
|
// rather than aborting the backup if any fails.
|
||||||
self.checkpoint_secondary_state(storage, meta);
|
self.checkpoint_secondary_state(storage, meta);
|
||||||
|
|
||||||
|
// 4b. Persist the replication high-water-mark row IN THE SAME STEP as
|
||||||
|
// the ledger checkpoint, so the copied row is current as of the
|
||||||
|
// artifact rather than up to one 30 s periodic-checkpoint cycle
|
||||||
|
// stale. m11p5 §2: a joiner that finds a stale HWM row inherits a
|
||||||
|
// too-low idempotency boundary for the shards it does apply and
|
||||||
|
// re-folds already-applied segments. This is fatal for the same
|
||||||
|
// reason the ledger checkpoint is: the artifact must be internally
|
||||||
|
// consistent for the node that opens it. (The joiner additionally
|
||||||
|
// OVERRIDES the leader_shard entry from its own recovered WAL tail
|
||||||
|
// per §2.6 — but the OTHER-shard entries it keeps must be current.)
|
||||||
|
crate::db::state_rebuild::checkpoint_replication_state(
|
||||||
|
storage.items_engine(),
|
||||||
|
self.replication_state.as_ref(),
|
||||||
|
)
|
||||||
|
.map_err(|e| {
|
||||||
|
TidalError::Durability(DurabilityError {
|
||||||
|
message: format!("backup: replication-state checkpoint failed: {e}"),
|
||||||
|
})
|
||||||
|
})?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Flush text indexes (non-fatal: search indexes are rebuilt on
|
// 5. Flush text indexes (non-fatal: search indexes are rebuilt on
|
||||||
// demand; their absence does not affect data integrity).
|
// demand; their absence does not affect data integrity). The m11p5
|
||||||
|
// snapshot-staging path skips this entirely — the joiner rebuilds the
|
||||||
|
// text index from durable entity rows on open, so flushing it into the
|
||||||
|
// artifact only lengthens the signal-write quiesce window for state the
|
||||||
|
// restore discards.
|
||||||
|
if !opts.skip_text_flush {
|
||||||
if let Err(e) = self.flush_text_index() {
|
if let Err(e) = self.flush_text_index() {
|
||||||
tracing::warn!(error = %e, "backup: text index flush failed (non-fatal)");
|
tracing::warn!(error = %e, "backup: text index flush failed (non-fatal)");
|
||||||
}
|
}
|
||||||
if let Err(e) = self.flush_creator_text_index() {
|
if let Err(e) = self.flush_creator_text_index() {
|
||||||
tracing::warn!(error = %e, "backup: creator text index flush failed (non-fatal)");
|
tracing::warn!(error = %e, "backup: creator text index flush failed (non-fatal)");
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// 5b. WAL writer in-flight events: why the copy below is still consistent.
|
// 5b. WAL writer in-flight events: why the copy below is still consistent.
|
||||||
//
|
//
|
||||||
@ -321,14 +467,21 @@ impl super::TidalDb {
|
|||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 7. Copy data directory to destination.
|
// 7. Copy data directory to destination, skipping the caller's
|
||||||
let size_bytes = copy_dir_recursive(data_dir, dest)?;
|
// top-level exclusions (m11p5 staging excludes the staging area
|
||||||
|
// itself plus the node-identity / node-local files).
|
||||||
|
let size_bytes = copy_dir_recursive(data_dir, dest, &opts.exclude_top_level)?;
|
||||||
|
|
||||||
// 8. Write a WAL checkpoint marker into the backup's WAL directory
|
// 8. Write a WAL checkpoint marker into the backup's WAL directory so
|
||||||
// so that WAL replay on the next open of the backup skips events
|
// that WAL replay on the next open of the backup skips events already
|
||||||
// that were already materialized by the signal checkpoint above.
|
// materialized by the signal checkpoint above (step 4). This is
|
||||||
// Without this, signals would be double-counted (once from the
|
// **FATAL**: a staged artifact with a stale/missing marker re-folds
|
||||||
// checkpoint, once from WAL replay).
|
// checkpointed signals on top of the checkpoint when a joiner opens it,
|
||||||
|
// inflating every aggregate the marker should have suppressed (the
|
||||||
|
// consistency proof on this method's rustdoc). A WAL with no segments
|
||||||
|
// at all (seq == 0 or no wal/ dir) has nothing to replay and so needs
|
||||||
|
// no marker — that is the only no-marker case, and it is consistent by
|
||||||
|
// construction (empty replay set).
|
||||||
if seq > 0 {
|
if seq > 0 {
|
||||||
let backup_wal_dir = dest.join("wal");
|
let backup_wal_dir = dest.join("wal");
|
||||||
if backup_wal_dir.exists() {
|
if backup_wal_dir.exists() {
|
||||||
@ -337,14 +490,14 @@ impl super::TidalDb {
|
|||||||
// WAL-marker time, the ledger checkpoint time (step 4), and the
|
// WAL-marker time, the ledger checkpoint time (step 4), and the
|
||||||
// returned `BackupInfo.timestamp_ns` all share one clock source.
|
// returned `BackupInfo.timestamp_ns` all share one clock source.
|
||||||
let ts_u64 = Timestamp::now().as_nanos();
|
let ts_u64 = Timestamp::now().as_nanos();
|
||||||
if let Err(e) =
|
|
||||||
crate::wal::checkpoint::CheckpointManager::write(&backup_wal_dir, seq, ts_u64)
|
crate::wal::checkpoint::CheckpointManager::write(&backup_wal_dir, seq, ts_u64)
|
||||||
{
|
.map_err(|e| {
|
||||||
tracing::warn!(
|
TidalError::Durability(DurabilityError {
|
||||||
error = %e,
|
message: format!(
|
||||||
"backup: failed to write WAL checkpoint marker (non-fatal)"
|
"backup: WAL checkpoint marker write failed at seq {seq}: {e}"
|
||||||
);
|
),
|
||||||
}
|
})
|
||||||
|
})?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -366,6 +519,78 @@ impl super::TidalDb {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Pin WAL retention at seq `S` (m11p5 §2.1).
|
||||||
|
///
|
||||||
|
/// While pinned, the periodic online compaction preserves the segment chain
|
||||||
|
/// covering `S + 1` onward (see [`compact_wal_online_pinned`]), so a snapshot
|
||||||
|
/// artifact captured at `S` stays servable: a joiner that installs the
|
||||||
|
/// artifact resumes the live WAL stream from `S + 1`, and the leader must not
|
||||||
|
/// compact that resume range out from under it.
|
||||||
|
///
|
||||||
|
/// The pin is taken at backup **start**, at the captured seq, *before* any
|
||||||
|
/// copying — a pin installed after staging cannot protect the copy window
|
||||||
|
/// from the 30 s checkpoint thread (which may compact between the ledger
|
||||||
|
/// checkpoint and the marker write). The caller holds the pin while the
|
||||||
|
/// artifact is staged and any joiner is mid-catch-up, then releases it via
|
||||||
|
/// [`unpin_wal_retention`](Self::unpin_wal_retention).
|
||||||
|
///
|
||||||
|
/// Idempotent semantics: this stores `S` unconditionally, overwriting any
|
||||||
|
/// prior pin. A single staged-artifact-at-a-time discipline (one pin owner)
|
||||||
|
/// is assumed; concurrent pinning of two distinct artifacts is the caller's
|
||||||
|
/// (server-side) coordination problem, not this primitive's.
|
||||||
|
///
|
||||||
|
/// [`compact_wal_online_pinned`]: crate::wal::compaction::compact_wal_online_pinned
|
||||||
|
// Public for the tidal-server snapshot path (stage B1): the
|
||||||
|
// `NodeSnapshotSource` releases the pin when an artifact is reaped. The
|
||||||
|
// PIN-before-copy half is owned by [`stage_snapshot`](Self::stage_snapshot)
|
||||||
|
// so the §2.1 ordering invariant cannot be mis-sequenced by a caller.
|
||||||
|
pub fn pin_wal_retention(&self, seq: u64) {
|
||||||
|
// Release: pairs with the Acquire load in the checkpoint thread. A thread
|
||||||
|
// that raises the pin before staging an artifact must be guaranteed the
|
||||||
|
// next periodic compaction observes the pin — otherwise the artifact's
|
||||||
|
// tail could be compacted between staging and the first joiner pull. The
|
||||||
|
// marker/checkpoint writes that follow staging are themselves Release-
|
||||||
|
// ordered through fjall's fsync, so the pin store ordering-before them is
|
||||||
|
// sufficient.
|
||||||
|
self.wal_retention_pin.store(seq, Ordering::Release);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Release the WAL retention pin (m11p5 §2.1), restoring unpinned
|
||||||
|
/// compaction — segments below the checkpoint floor become reclaimable on
|
||||||
|
/// the next periodic compaction.
|
||||||
|
///
|
||||||
|
/// Storing the `0` sentinel: [`compact_wal_online_pinned`] treats `pin == 0`
|
||||||
|
/// as unpinned, recovering plain online-compaction behavior byte-for-byte.
|
||||||
|
///
|
||||||
|
/// [`compact_wal_online_pinned`]: crate::wal::compaction::compact_wal_online_pinned
|
||||||
|
// Public for the tidal-server snapshot path (stage B1): pairs with
|
||||||
|
// `pin_wal_retention`, called when the cached artifact is dropped.
|
||||||
|
pub fn unpin_wal_retention(&self) {
|
||||||
|
// Release: the un-pin must be observable to the compaction thread on its
|
||||||
|
// next pass; storing 0 can only ever ALLOW more compaction, never delete a
|
||||||
|
// segment the unpinned path would keep, so a delayed observation is at
|
||||||
|
// worst a few extra retained segments for one more cycle — never data loss.
|
||||||
|
self.wal_retention_pin.store(0, Ordering::Release);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The currently pinned WAL retention seq, or `0` if unpinned. Test/observability hook.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) fn wal_retention_pin(&self) -> u64 {
|
||||||
|
self.wal_retention_pin.load(Ordering::Acquire)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Latch (or clear) the `backup_in_progress` CAS flag directly, WITHOUT
|
||||||
|
/// running a backup. Test-only (`test-utils`): lets a caller-side test
|
||||||
|
/// (tidal-server's `NodeSnapshotSource`) drive the "a stage arriving while
|
||||||
|
/// `create_backup` is mid-flight maps to `Busy`" path deterministically, by
|
||||||
|
/// simulating the in-flight backup the real path would hold under its RAII
|
||||||
|
/// guard. Never compiled into a production binary.
|
||||||
|
#[cfg(any(test, feature = "test-utils"))]
|
||||||
|
pub fn set_backup_in_progress_for_test(&self, in_progress: bool) {
|
||||||
|
self.backup_in_progress
|
||||||
|
.store(in_progress, Ordering::Release);
|
||||||
|
}
|
||||||
|
|
||||||
/// Checkpoint the secondary derived ledgers (cohort, co-engagement,
|
/// Checkpoint the secondary derived ledgers (cohort, co-engagement,
|
||||||
/// community, preference vectors) into `storage`.
|
/// community, preference vectors) into `storage`.
|
||||||
///
|
///
|
||||||
@ -407,7 +632,7 @@ mod tests {
|
|||||||
std::fs::create_dir(src.path().join("subdir")).unwrap();
|
std::fs::create_dir(src.path().join("subdir")).unwrap();
|
||||||
std::fs::write(src.path().join("subdir").join("nested.txt"), "world").unwrap();
|
std::fs::write(src.path().join("subdir").join("nested.txt"), "world").unwrap();
|
||||||
|
|
||||||
let bytes = copy_dir_recursive(src.path(), dest.path()).unwrap();
|
let bytes = copy_dir_recursive(src.path(), dest.path(), &[]).unwrap();
|
||||||
assert!(bytes > 0);
|
assert!(bytes > 0);
|
||||||
assert!(dest.path().join("test.txt").exists());
|
assert!(dest.path().join("test.txt").exists());
|
||||||
assert!(dest.path().join("subdir").join("nested.txt").exists());
|
assert!(dest.path().join("subdir").join("nested.txt").exists());
|
||||||
@ -447,7 +672,7 @@ mod tests {
|
|||||||
std::fs::create_dir(src.path().join("a").join("b")).unwrap();
|
std::fs::create_dir(src.path().join("a").join("b")).unwrap();
|
||||||
std::fs::write(src.path().join("a").join("b").join("deep.txt"), "deep").unwrap();
|
std::fs::write(src.path().join("a").join("b").join("deep.txt"), "deep").unwrap();
|
||||||
|
|
||||||
let bytes = copy_dir_recursive(src.path(), dest.path()).unwrap();
|
let bytes = copy_dir_recursive(src.path(), dest.path(), &[]).unwrap();
|
||||||
assert!(bytes > 0);
|
assert!(bytes > 0);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
std::fs::read_to_string(dest.path().join("top.txt")).unwrap(),
|
std::fs::read_to_string(dest.path().join("top.txt")).unwrap(),
|
||||||
@ -471,11 +696,64 @@ mod tests {
|
|||||||
std::fs::write(src.path().join("tidaldb.lock"), "").unwrap();
|
std::fs::write(src.path().join("tidaldb.lock"), "").unwrap();
|
||||||
std::fs::write(src.path().join("data.db"), "data").unwrap();
|
std::fs::write(src.path().join("data.db"), "data").unwrap();
|
||||||
|
|
||||||
copy_dir_recursive(src.path(), dest.path()).unwrap();
|
copy_dir_recursive(src.path(), dest.path(), &[]).unwrap();
|
||||||
assert!(!dest.path().join("tidaldb.lock").exists());
|
assert!(!dest.path().join("tidaldb.lock").exists());
|
||||||
assert!(dest.path().join("data.db").exists());
|
assert!(dest.path().join("data.db").exists());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `exclude_top_level` drops the named TOP-LEVEL entries (a dir and a file)
|
||||||
|
/// while every sibling — and a nested file sharing an excluded name — is
|
||||||
|
/// copied. This is the contract the m11p5 snapshot-staging path relies on:
|
||||||
|
/// the staging area (`snapshots`) and node-identity files
|
||||||
|
/// (`election_state`, `stream_baseline`, `membership`, the reseed marker)
|
||||||
|
/// never enter the artifact, but real payload deep in the tree always does.
|
||||||
|
#[test]
|
||||||
|
fn copy_dir_recursive_excludes_named_top_level_entries() {
|
||||||
|
let src = tempfile::tempdir().unwrap();
|
||||||
|
let dest = tempfile::tempdir().unwrap();
|
||||||
|
|
||||||
|
// Two excluded top-level entries: a directory and a file.
|
||||||
|
std::fs::create_dir(src.path().join("snapshots")).unwrap();
|
||||||
|
std::fs::write(src.path().join("snapshots").join("staged.bin"), "x").unwrap();
|
||||||
|
std::fs::write(src.path().join("election_state"), "term").unwrap();
|
||||||
|
|
||||||
|
// Siblings that MUST survive.
|
||||||
|
std::fs::write(src.path().join("data.db"), "data").unwrap();
|
||||||
|
std::fs::create_dir(src.path().join("wal")).unwrap();
|
||||||
|
std::fs::write(src.path().join("wal").join("seg-1.seg"), "seg").unwrap();
|
||||||
|
// A NESTED file sharing an excluded name — top-level-only matching means
|
||||||
|
// it is still copied (it is real payload, not the node-identity file).
|
||||||
|
std::fs::write(src.path().join("wal").join("election_state"), "nested").unwrap();
|
||||||
|
|
||||||
|
copy_dir_recursive(
|
||||||
|
src.path(),
|
||||||
|
dest.path(),
|
||||||
|
&[
|
||||||
|
"snapshots",
|
||||||
|
"election_state",
|
||||||
|
"stream_baseline",
|
||||||
|
"membership",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Excluded top-level entries are absent.
|
||||||
|
assert!(
|
||||||
|
!dest.path().join("snapshots").exists(),
|
||||||
|
"the staging dir must not copy itself into the artifact"
|
||||||
|
);
|
||||||
|
assert!(!dest.path().join("election_state").exists());
|
||||||
|
// Siblings survive.
|
||||||
|
assert!(dest.path().join("data.db").exists());
|
||||||
|
assert!(dest.path().join("wal").join("seg-1.seg").exists());
|
||||||
|
// The nested same-named file is copied (top-level matching only).
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read_to_string(dest.path().join("wal").join("election_state")).unwrap(),
|
||||||
|
"nested",
|
||||||
|
"a nested entry sharing an excluded name is real payload and must be copied"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn backup_fails_for_ephemeral() {
|
fn backup_fails_for_ephemeral() {
|
||||||
let db = crate::TidalDb::builder().ephemeral().open().unwrap();
|
let db = crate::TidalDb::builder().ephemeral().open().unwrap();
|
||||||
@ -560,4 +838,255 @@ mod tests {
|
|||||||
}
|
}
|
||||||
restored.close().unwrap();
|
restored.close().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The snapshot-staging variant (`skip_text_flush: true`) must produce an
|
||||||
|
/// artifact that is byte-equivalent for correctness: every acked signal still
|
||||||
|
/// survives the round-trip. The skipped text flush is derived state rebuilt on
|
||||||
|
/// open, so it cannot affect the signal aggregate the restore reconstructs.
|
||||||
|
#[test]
|
||||||
|
fn create_backup_with_skip_text_flush_still_round_trips() {
|
||||||
|
use crate::schema::{EntityId, Timestamp};
|
||||||
|
|
||||||
|
let src = tempfile::tempdir().unwrap();
|
||||||
|
let bak = tempfile::tempdir().unwrap();
|
||||||
|
let backup_path = bak.path().join("backup");
|
||||||
|
|
||||||
|
let db = crate::TidalDb::builder()
|
||||||
|
.with_data_dir(src.path())
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
for i in 1u64..=4 {
|
||||||
|
db.signal("view", EntityId::new(i), 1.0, Timestamp::now())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let info = db
|
||||||
|
.create_backup_with(
|
||||||
|
&backup_path,
|
||||||
|
&BackupOptions {
|
||||||
|
skip_text_flush: true,
|
||||||
|
..BackupOptions::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(info.size_bytes > 0);
|
||||||
|
db.close().unwrap();
|
||||||
|
|
||||||
|
let restored = crate::TidalDb::builder()
|
||||||
|
.with_data_dir(&backup_path)
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
for i in 1u64..=4 {
|
||||||
|
let score = restored
|
||||||
|
.read_decay_score(EntityId::new(i), "view", 0)
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
score.is_some_and(|s| s > 0.0),
|
||||||
|
"acked signal for entity {i} must survive the skip-text-flush backup"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
restored.close().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The backup must persist the replication high-water-mark row IN-STEP, so a
|
||||||
|
/// restored artifact carries a current (not up-to-30s-stale) HWM. We advance
|
||||||
|
/// the live replication state, take a backup, reopen it, and assert the
|
||||||
|
/// restored frontier matches what was live at backup time — proving the row
|
||||||
|
/// was written by `create_backup`, not left to the periodic thread.
|
||||||
|
#[test]
|
||||||
|
fn backup_persists_current_replication_hwm() {
|
||||||
|
use crate::replication::ShardId;
|
||||||
|
use crate::schema::{EntityId, Timestamp};
|
||||||
|
|
||||||
|
let src = tempfile::tempdir().unwrap();
|
||||||
|
let bak = tempfile::tempdir().unwrap();
|
||||||
|
let backup_path = bak.path().join("backup");
|
||||||
|
|
||||||
|
let db = crate::TidalDb::builder()
|
||||||
|
.with_data_dir(src.path())
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
db.signal("view", EntityId::new(1), 1.0, Timestamp::now())
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Advance the live replication frontier for the local shard. `advance`
|
||||||
|
// jumps the contiguous prefix — exactly the snapshot/baseline entry point.
|
||||||
|
let shard = ShardId::SINGLE;
|
||||||
|
db.replication_state().advance(shard, 42);
|
||||||
|
let live_hwm = db.replication_state().applied_seqno(shard);
|
||||||
|
|
||||||
|
db.create_backup(&backup_path).unwrap();
|
||||||
|
db.close().unwrap();
|
||||||
|
|
||||||
|
let restored = crate::TidalDb::builder()
|
||||||
|
.with_data_dir(&backup_path)
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
let restored_hwm = restored.replication_state().applied_seqno(shard);
|
||||||
|
assert_eq!(
|
||||||
|
restored_hwm, live_hwm,
|
||||||
|
"restored replication HWM must equal the frontier live at backup time \
|
||||||
|
(the row is written in-step, not 30s stale)"
|
||||||
|
);
|
||||||
|
restored.close().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `stage_snapshot` pins WAL retention at the captured tail BEFORE the copy
|
||||||
|
/// (§2.1), excludes the named top-level files from the artifact, and returns
|
||||||
|
/// the artifact's WAL seq. We seed signals (so the tail is non-zero), drop a
|
||||||
|
/// node-identity file + a `snapshots/` staging dir into the data dir, stage,
|
||||||
|
/// and assert: the pin is held (non-zero, ≤ tail), the artifact omits the
|
||||||
|
/// excluded entries, and the artifact opens and round-trips every signal.
|
||||||
|
#[test]
|
||||||
|
fn stage_snapshot_pins_excludes_and_round_trips() {
|
||||||
|
use crate::replication::RESEED_REQUIRED_MARKER;
|
||||||
|
use crate::schema::{EntityId, Timestamp};
|
||||||
|
|
||||||
|
let src = tempfile::tempdir().unwrap();
|
||||||
|
let bak = tempfile::tempdir().unwrap();
|
||||||
|
let staged = bak.path().join("staged-snapshot");
|
||||||
|
|
||||||
|
let db = crate::TidalDb::builder()
|
||||||
|
.with_data_dir(src.path())
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
for i in 1u64..=3 {
|
||||||
|
db.signal("view", EntityId::new(i), 1.0, Timestamp::now())
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let tail = db.last_wal_seq();
|
||||||
|
assert!(tail > 0, "seeded signals must advance the WAL tail");
|
||||||
|
|
||||||
|
// Node-identity / node-local files + the staging area, all top-level in
|
||||||
|
// the data dir — the exclusions the snapshot path lists.
|
||||||
|
std::fs::write(src.path().join("election_state"), b"term").unwrap();
|
||||||
|
std::fs::write(src.path().join("stream_baseline"), [0u8; 8]).unwrap();
|
||||||
|
std::fs::write(src.path().join("membership"), b"roster").unwrap();
|
||||||
|
std::fs::write(src.path().join(RESEED_REQUIRED_MARKER), b"").unwrap();
|
||||||
|
std::fs::create_dir_all(src.path().join("snapshots").join("old")).unwrap();
|
||||||
|
std::fs::write(src.path().join("snapshots").join("old").join("x"), b"stale").unwrap();
|
||||||
|
|
||||||
|
let artifact_seq = db
|
||||||
|
.stage_snapshot(
|
||||||
|
&staged,
|
||||||
|
vec![
|
||||||
|
"snapshots",
|
||||||
|
"election_state",
|
||||||
|
"stream_baseline",
|
||||||
|
"membership",
|
||||||
|
RESEED_REQUIRED_MARKER,
|
||||||
|
],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// The pin is held (§2.1: pin BEFORE copy), at or below the captured tail.
|
||||||
|
let pin = db.wal_retention_pin();
|
||||||
|
assert!(pin > 0, "stage_snapshot must hold a retention pin");
|
||||||
|
assert!(
|
||||||
|
pin <= tail,
|
||||||
|
"the pin can only be held at or lowered below the captured tail, never raised"
|
||||||
|
);
|
||||||
|
// The artifact seq is at least the tail at stage start (the tail is
|
||||||
|
// monotonic; create_backup captures its own >= ours).
|
||||||
|
assert!(
|
||||||
|
artifact_seq >= tail,
|
||||||
|
"the artifact seq is captured at-or-after the pin"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Excluded entries are absent from the artifact.
|
||||||
|
for excluded in [
|
||||||
|
"election_state",
|
||||||
|
"stream_baseline",
|
||||||
|
"membership",
|
||||||
|
RESEED_REQUIRED_MARKER,
|
||||||
|
"snapshots",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
!staged.join(excluded).exists(),
|
||||||
|
"{excluded} must be excluded from the snapshot artifact"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release the pin and prove the artifact opens + round-trips.
|
||||||
|
db.unpin_wal_retention();
|
||||||
|
assert_eq!(db.wal_retention_pin(), 0);
|
||||||
|
db.close().unwrap();
|
||||||
|
|
||||||
|
let restored = crate::TidalDb::builder()
|
||||||
|
.with_data_dir(&staged)
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
for i in 1u64..=3 {
|
||||||
|
let score = restored
|
||||||
|
.read_decay_score(EntityId::new(i), "view", 0)
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
score.is_some_and(|s| s > 0.0),
|
||||||
|
"every acked signal must survive the snapshot stage/install for entity {i}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
restored.close().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A second `stage_snapshot` while a backup is already in flight maps to the
|
||||||
|
/// engine's "already in progress" error — the caller turns it into
|
||||||
|
/// `SnapshotStageError::Busy`. We can prove the CAS rejects a re-entrant
|
||||||
|
/// stage by holding the flag, since the real concurrency is server-side.
|
||||||
|
#[test]
|
||||||
|
fn stage_snapshot_busy_when_backup_in_progress() {
|
||||||
|
let src = tempfile::tempdir().unwrap();
|
||||||
|
let bak = tempfile::tempdir().unwrap();
|
||||||
|
let db = crate::TidalDb::builder()
|
||||||
|
.with_data_dir(src.path())
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
// Simulate an in-flight backup by latching the CAS flag (the real path
|
||||||
|
// holds it under a RAII guard for the copy window).
|
||||||
|
db.backup_in_progress.store(true, Ordering::Release);
|
||||||
|
let err = db
|
||||||
|
.stage_snapshot(&bak.path().join("staged"), vec![])
|
||||||
|
.expect_err("a concurrent backup must refuse a second stage");
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("already in progress"),
|
||||||
|
"the error must name the in-progress backup so the caller maps it to Busy: {err}"
|
||||||
|
);
|
||||||
|
// The pin must NOT leak when the stage refuses (it released on error).
|
||||||
|
assert_eq!(
|
||||||
|
db.wal_retention_pin(),
|
||||||
|
0,
|
||||||
|
"a refused stage must not leave a retention pin behind"
|
||||||
|
);
|
||||||
|
db.backup_in_progress.store(false, Ordering::Release);
|
||||||
|
db.close().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The retention pin accessors are a straight atomic set/clear with the `0`
|
||||||
|
/// sentinel meaning unpinned — the property the checkpoint thread relies on.
|
||||||
|
#[test]
|
||||||
|
fn wal_retention_pin_set_and_clear() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let db = crate::TidalDb::builder()
|
||||||
|
.with_data_dir(dir.path())
|
||||||
|
.with_schema(minimal_schema())
|
||||||
|
.open()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(db.wal_retention_pin(), 0, "starts unpinned");
|
||||||
|
db.pin_wal_retention(123);
|
||||||
|
assert_eq!(db.wal_retention_pin(), 123);
|
||||||
|
// Re-pinning overwrites (single staged-artifact discipline).
|
||||||
|
db.pin_wal_retention(456);
|
||||||
|
assert_eq!(db.wal_retention_pin(), 456);
|
||||||
|
db.unpin_wal_retention();
|
||||||
|
assert_eq!(db.wal_retention_pin(), 0, "unpin restores the sentinel");
|
||||||
|
db.close().unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -185,6 +185,15 @@ impl TidalDb {
|
|||||||
leader_region: u16,
|
leader_region: u16,
|
||||||
seq_slot: usize,
|
seq_slot: usize,
|
||||||
},
|
},
|
||||||
|
/// A replicated membership record (m11p5): journaled like any blob
|
||||||
|
/// in Phase 2, then folded into the `ClusterMembership` cell in
|
||||||
|
/// Phase 3 — no storage effect. Keyed by `version` (the cell is
|
||||||
|
/// monotonic-by-version), not by the local WAL seqno.
|
||||||
|
Membership {
|
||||||
|
version: u64,
|
||||||
|
term: u64,
|
||||||
|
members: Vec<crate::wal::format::MemberEntry>,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
self.require_writeable("apply_replicated_blobs")?;
|
self.require_writeable("apply_replicated_blobs")?;
|
||||||
@ -222,6 +231,20 @@ impl TidalDb {
|
|||||||
seq_slot: slot,
|
seq_slot: slot,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
BlobRecord::Membership(r) => {
|
||||||
|
// Re-validate the roster before it enters THIS node's log:
|
||||||
|
// a structurally-invalid record decoded clean would fail
|
||||||
|
// identically on every follower, so refuse it here rather
|
||||||
|
// than journal an unappliable record (the segment receiver
|
||||||
|
// halts on apply errors, never silently skips).
|
||||||
|
r.validate()
|
||||||
|
.map_err(|e| TidalError::invalid_input(format!("{e}")))?;
|
||||||
|
applies.push(BlobApply::Membership {
|
||||||
|
version: r.version,
|
||||||
|
term: r.term,
|
||||||
|
members: r.members.clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -307,6 +330,20 @@ impl TidalDb {
|
|||||||
"replicated term marker applied; WAL-tail term advanced"
|
"replicated term marker applied; WAL-tail term advanced"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
BlobApply::Membership {
|
||||||
|
version,
|
||||||
|
term,
|
||||||
|
members,
|
||||||
|
} => {
|
||||||
|
let member_count = members.len();
|
||||||
|
self.cluster_membership.advance(version, term, members);
|
||||||
|
tracing::info!(
|
||||||
|
version,
|
||||||
|
term,
|
||||||
|
members = member_count,
|
||||||
|
"replicated membership record applied; cluster roster advanced"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -716,6 +753,19 @@ impl TidalDb {
|
|||||||
.advance(record.term, blob.seq, record.leader_region);
|
.advance(record.term, blob.seq, record.leader_region);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
BlobRecord::Membership(record) => {
|
||||||
|
// No storage effect: recovery re-derives the roster (m11p5)
|
||||||
|
// from the highest-version record in the surviving log. The
|
||||||
|
// scanner only returns records at-or-below the durable
|
||||||
|
// frontier (a record above a torn tail is never replayed),
|
||||||
|
// so the monotonic-by-version advance IS "latest wins".
|
||||||
|
self.cluster_membership.advance(
|
||||||
|
record.version,
|
||||||
|
record.term,
|
||||||
|
record.members.clone(),
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
};
|
};
|
||||||
if let Err(e) = result {
|
if let Err(e) = result {
|
||||||
tracing::warn!(
|
tracing::warn!(
|
||||||
|
|||||||
@ -97,6 +97,30 @@ pub struct ClusterMetrics {
|
|||||||
/// Divergent-suffix quarantine latch (m11p4): 1 = this node is fenced
|
/// Divergent-suffix quarantine latch (m11p4): 1 = this node is fenced
|
||||||
/// from the data plane until reseeded.
|
/// from the data plane until reseeded.
|
||||||
divergence_quarantined: AtomicU64,
|
divergence_quarantined: AtomicU64,
|
||||||
|
/// Durable `reseed_required` marker latch (m11p5 §2.4): 1 = this node has
|
||||||
|
/// latched a reseed marker and will reseed via snapshot install on its next
|
||||||
|
/// boot (it keeps serving degraded until then). A non-zero value on a
|
||||||
|
/// dashboard means an operator/automatic reseed is pending a restart.
|
||||||
|
reseed_required: AtomicU64,
|
||||||
|
/// The seq of the currently-staged snapshot artifact (m11p5), or 0 when no
|
||||||
|
/// artifact is staged. A non-zero value means WAL retention is pinned for a
|
||||||
|
/// joiner's resume range.
|
||||||
|
snapshot_staged: AtomicU64,
|
||||||
|
/// Total `FetchSnapshot` streams this node has served as the leader-side
|
||||||
|
/// source (m11p5) — staged-and-served, including reuses of a warm artifact.
|
||||||
|
snapshot_fetches_total: AtomicU64,
|
||||||
|
/// Total times a staged artifact's retention pin was FORCE-dropped past the
|
||||||
|
/// hard cap (m11p5 §2.1) because a consumer never released — a dead joiner
|
||||||
|
/// pinning compaction. Each is a loud WARN; a non-zero counter on a
|
||||||
|
/// dashboard means a joiner is stuck.
|
||||||
|
snapshot_pin_force_drops_total: AtomicU64,
|
||||||
|
/// Total removal-delivery graces that EXPIRED before the removed peer acked
|
||||||
|
/// the `Removed` record (m11p5 §3.3) — the leader retired the ship cell on
|
||||||
|
/// the give-up deadline rather than on confirmed delivery. Each is a loud
|
||||||
|
/// WARN; a non-zero counter means a removed node was down/unreachable during
|
||||||
|
/// its decommission and will learn of its removal via the typed removed
|
||||||
|
/// signal if it ever restarts.
|
||||||
|
remove_delivery_giveups_total: AtomicU64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ClusterMetrics {
|
impl ClusterMetrics {
|
||||||
@ -118,9 +142,40 @@ impl ClusterMetrics {
|
|||||||
elections_started_total: AtomicU64::new(0),
|
elections_started_total: AtomicU64::new(0),
|
||||||
leader_changes_total: AtomicU64::new(0),
|
leader_changes_total: AtomicU64::new(0),
|
||||||
divergence_quarantined: AtomicU64::new(0),
|
divergence_quarantined: AtomicU64::new(0),
|
||||||
|
reseed_required: AtomicU64::new(0),
|
||||||
|
snapshot_staged: AtomicU64::new(0),
|
||||||
|
snapshot_fetches_total: AtomicU64::new(0),
|
||||||
|
snapshot_pin_force_drops_total: AtomicU64::new(0),
|
||||||
|
remove_delivery_giveups_total: AtomicU64::new(0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Set the staged-snapshot-artifact gauge (m11p5): the artifact's seq, or 0
|
||||||
|
/// when no artifact is staged.
|
||||||
|
pub fn set_snapshot_staged(&self, artifact_seq: u64) {
|
||||||
|
self.snapshot_staged.store(artifact_seq, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count one `FetchSnapshot` stream served (m11p5).
|
||||||
|
pub fn incr_snapshot_fetches(&self) {
|
||||||
|
self.snapshot_fetches_total.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count one force-drop of a staged artifact's retention pin past the hard
|
||||||
|
/// cap (m11p5 §2.1) — a consumer that never released.
|
||||||
|
pub fn incr_snapshot_pin_force_drops(&self) {
|
||||||
|
self.snapshot_pin_force_drops_total
|
||||||
|
.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count one removal-delivery grace that EXPIRED on the give-up deadline
|
||||||
|
/// (m11p5 §3.3) — the removed peer never acked the `Removed` record within
|
||||||
|
/// the grace, so the leader retired its ship cell anyway.
|
||||||
|
pub fn incr_remove_delivery_giveup(&self) {
|
||||||
|
self.remove_delivery_giveups_total
|
||||||
|
.fetch_add(1, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
/// Record this node's election term + role (m11p4): role is 0 follower,
|
/// Record this node's election term + role (m11p4): role is 0 follower,
|
||||||
/// 1 pre-candidate, 2 candidate, 3 leader.
|
/// 1 pre-candidate, 2 candidate, 3 leader.
|
||||||
pub fn set_election_view(&self, term: u64, role: u64) {
|
pub fn set_election_view(&self, term: u64, role: u64) {
|
||||||
@ -144,6 +199,15 @@ impl ClusterMetrics {
|
|||||||
.store(u64::from(quarantined), Ordering::Relaxed);
|
.store(u64::from(quarantined), Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Latch (or clear) the durable `reseed_required` marker gauge (m11p5 §2.4).
|
||||||
|
/// Set when the node latches the marker (snapshot-required refusal,
|
||||||
|
/// quarantine, or operator verb); a fresh process after a successful reseed
|
||||||
|
/// install starts at 0.
|
||||||
|
pub fn set_reseed_required(&self, required: bool) {
|
||||||
|
self.reseed_required
|
||||||
|
.store(u64::from(required), Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
/// Enable rendering of the cluster series. Idempotent; called when a
|
/// Enable rendering of the cluster series. Idempotent; called when a
|
||||||
/// cluster surface first takes the metrics handle.
|
/// cluster surface first takes the metrics handle.
|
||||||
pub fn mark_active(&self) {
|
pub fn mark_active(&self) {
|
||||||
@ -337,6 +401,44 @@ impl ClusterMetrics {
|
|||||||
"gauge",
|
"gauge",
|
||||||
self.divergence_quarantined.load(Ordering::Relaxed) as f64,
|
self.divergence_quarantined.load(Ordering::Relaxed) as f64,
|
||||||
);
|
);
|
||||||
|
super::write_metric_line(
|
||||||
|
out,
|
||||||
|
"tidaldb_cluster_reseed_required",
|
||||||
|
"Durable reseed-marker latch (m11p5; 1 = a snapshot reseed is pending the next boot)",
|
||||||
|
"gauge",
|
||||||
|
self.reseed_required.load(Ordering::Relaxed) as f64,
|
||||||
|
);
|
||||||
|
|
||||||
|
super::write_metric_line(
|
||||||
|
out,
|
||||||
|
"tidaldb_cluster_snapshot_staged",
|
||||||
|
"Seq of the currently-staged snapshot artifact (m11p5; 0 = none staged)",
|
||||||
|
"gauge",
|
||||||
|
self.snapshot_staged.load(Ordering::Relaxed) as f64,
|
||||||
|
);
|
||||||
|
super::write_metric_line(
|
||||||
|
out,
|
||||||
|
"tidaldb_cluster_snapshot_fetches_total",
|
||||||
|
"FetchSnapshot streams served as the leader-side snapshot source (m11p5)",
|
||||||
|
"counter",
|
||||||
|
self.snapshot_fetches_total.load(Ordering::Relaxed) as f64,
|
||||||
|
);
|
||||||
|
super::write_metric_line(
|
||||||
|
out,
|
||||||
|
"tidaldb_cluster_snapshot_pin_force_drops_total",
|
||||||
|
"Staged-artifact retention pins force-dropped past the hard cap (m11p5 §2.1; \
|
||||||
|
a dead joiner that never released)",
|
||||||
|
"counter",
|
||||||
|
self.snapshot_pin_force_drops_total.load(Ordering::Relaxed) as f64,
|
||||||
|
);
|
||||||
|
super::write_metric_line(
|
||||||
|
out,
|
||||||
|
"tidaldb_cluster_remove_delivery_giveups_total",
|
||||||
|
"Removal-delivery graces that expired before the removed peer acked the Removed \
|
||||||
|
record (m11p5 §3.3; the removed node was down/unreachable during decommission)",
|
||||||
|
"counter",
|
||||||
|
self.remove_delivery_giveups_total.load(Ordering::Relaxed) as f64,
|
||||||
|
);
|
||||||
|
|
||||||
// Per-peer series, labeled by peer shard id + this node's partition.
|
// Per-peer series, labeled by peer shard id + this node's partition.
|
||||||
// Snapshot the cells under the read lock, then render lock-free (the
|
// Snapshot the cells under the read lock, then render lock-free (the
|
||||||
@ -404,11 +506,20 @@ mod tests {
|
|||||||
m.observe_wal_fsync(std::time::Duration::from_micros(800), 32);
|
m.observe_wal_fsync(std::time::Duration::from_micros(800), 32);
|
||||||
m.set_write_pool_depth(5);
|
m.set_write_pool_depth(5);
|
||||||
m.incr_write_pool_rejections();
|
m.incr_write_pool_rejections();
|
||||||
|
m.set_snapshot_staged(4096);
|
||||||
|
m.incr_snapshot_fetches();
|
||||||
|
m.incr_snapshot_pin_force_drops();
|
||||||
|
m.incr_remove_delivery_giveup();
|
||||||
|
|
||||||
let mut out = String::new();
|
let mut out = String::new();
|
||||||
m.render_into(&mut out, 7);
|
m.render_into(&mut out, 7);
|
||||||
assert!(out.contains("tidaldb_cluster_ship_rtt_us_bucket"));
|
assert!(out.contains("tidaldb_cluster_ship_rtt_us_bucket"));
|
||||||
assert!(out.contains("tidaldb_cluster_wal_fsync_us_bucket"));
|
assert!(out.contains("tidaldb_cluster_wal_fsync_us_bucket"));
|
||||||
|
// m11p5 snapshot series render with their set values.
|
||||||
|
assert!(out.contains("tidaldb_cluster_snapshot_staged 4096"));
|
||||||
|
assert!(out.contains("tidaldb_cluster_snapshot_fetches_total 1"));
|
||||||
|
assert!(out.contains("tidaldb_cluster_snapshot_pin_force_drops_total 1"));
|
||||||
|
assert!(out.contains("tidaldb_cluster_remove_delivery_giveups_total 1"));
|
||||||
assert!(
|
assert!(
|
||||||
out.contains(
|
out.contains(
|
||||||
"tidaldb_cluster_peer_acked_seqno{peer_shard=\"2\",partition_id=\"7\"} 64"
|
"tidaldb_cluster_peer_acked_seqno{peer_shard=\"2\",partition_id=\"7\"} 64"
|
||||||
|
|||||||
@ -118,6 +118,12 @@ pub struct TidalDb {
|
|||||||
/// marker applies; read by the election machinery (the `lastLogTerm`
|
/// marker applies; read by the election machinery (the `lastLogTerm`
|
||||||
/// half of the vote restriction). `(0, 0)` outside cluster mode.
|
/// half of the vote restriction). `(0, 0)` outside cluster mode.
|
||||||
wal_term_mark: Arc<crate::wal::WalTermMark>,
|
wal_term_mark: Arc<crate::wal::WalTermMark>,
|
||||||
|
/// m11p5: the applied cluster membership — the highest-version kind-4
|
||||||
|
/// record this node's log carries. Fed by recovery, leader conf-change
|
||||||
|
/// appends, and replicated applies; read by the membership machinery as
|
||||||
|
/// the effective roster. `None` (the topology era) outside a cluster that
|
||||||
|
/// has run a conf-change.
|
||||||
|
cluster_membership: Arc<crate::wal::ClusterMembership>,
|
||||||
/// m11p2: the flushed-batch ship feed the WAL writer populates (cluster
|
/// m11p2: the flushed-batch ship feed the WAL writer populates (cluster
|
||||||
/// mode + persistent only). The replication ship queue's hot-path source.
|
/// mode + persistent only). The replication ship queue's hot-path source.
|
||||||
ship_feed: Option<Arc<crate::wal::feed::WalShipFeed>>,
|
ship_feed: Option<Arc<crate::wal::feed::WalShipFeed>>,
|
||||||
@ -195,6 +201,17 @@ pub struct TidalDb {
|
|||||||
// True when a backup is in progress. Signal writes return Backpressure
|
// True when a backup is in progress. Signal writes return Backpressure
|
||||||
// during the backup window. Cleared by the BackupGuard RAII drop.
|
// during the backup window. Cleared by the BackupGuard RAII drop.
|
||||||
backup_in_progress: Arc<AtomicBool>,
|
backup_in_progress: Arc<AtomicBool>,
|
||||||
|
// m11p5 §2.1: WAL retention pin. `0` is the unpinned sentinel; when set to
|
||||||
|
// a seq S, the periodic online compaction preserves the segment chain
|
||||||
|
// covering S+1 onward so a snapshot artifact captured at S stays servable
|
||||||
|
// (the joiner resumes the WAL stream from S+1). Shared with the checkpoint
|
||||||
|
// thread; consulted on every periodic compaction.
|
||||||
|
//
|
||||||
|
// Read only through the cloned Arc handed to the checkpoint thread and via
|
||||||
|
// the pin/unpin accessors (the snapshot path's seam, wired by tidal-server
|
||||||
|
// in a later m11p5 stage); the struct field itself is the owning anchor.
|
||||||
|
#[allow(dead_code)]
|
||||||
|
wal_retention_pin: Arc<AtomicU64>,
|
||||||
// M8p2 replication
|
// M8p2 replication
|
||||||
replication_state: Arc<crate::replication::state::ReplicationState>,
|
replication_state: Arc<crate::replication::state::ReplicationState>,
|
||||||
receiver_handle: std::sync::Mutex<Option<crate::replication::receiver::SegmentReceiverHandle>>,
|
receiver_handle: std::sync::Mutex<Option<crate::replication::receiver::SegmentReceiverHandle>>,
|
||||||
@ -443,9 +460,13 @@ impl TidalDb {
|
|||||||
last_wal_seq: Arc::new(AtomicU64::new(0)),
|
last_wal_seq: Arc::new(AtomicU64::new(0)),
|
||||||
replicate_blobs: false,
|
replicate_blobs: false,
|
||||||
wal_term_mark: Arc::new(crate::wal::WalTermMark::default()),
|
wal_term_mark: Arc::new(crate::wal::WalTermMark::default()),
|
||||||
|
cluster_membership: Arc::new(crate::wal::ClusterMembership::default()),
|
||||||
ship_feed: None,
|
ship_feed: None,
|
||||||
shutdown_checkpoint: Arc::new(AtomicBool::new(false)),
|
shutdown_checkpoint: Arc::new(AtomicBool::new(false)),
|
||||||
checkpoint_thread: std::sync::Mutex::new(None),
|
checkpoint_thread: std::sync::Mutex::new(None),
|
||||||
|
// No-schema mode never starts the checkpoint thread, so this pin is
|
||||||
|
// never consulted here; default to the unpinned sentinel.
|
||||||
|
wal_retention_pin: Arc::new(AtomicU64::new(0)),
|
||||||
text_index_unhealthy: Arc::new(AtomicBool::new(false)),
|
text_index_unhealthy: Arc::new(AtomicBool::new(false)),
|
||||||
category_index: BitmapIndex::new("category"),
|
category_index: BitmapIndex::new("category"),
|
||||||
format_index: BitmapIndex::new("format"),
|
format_index: BitmapIndex::new("format"),
|
||||||
@ -868,6 +889,11 @@ impl TidalDb {
|
|||||||
|
|
||||||
// Spawn periodic checkpoint thread (persistent mode only).
|
// Spawn periodic checkpoint thread (persistent mode only).
|
||||||
let shutdown_checkpoint = Arc::new(AtomicBool::new(false));
|
let shutdown_checkpoint = Arc::new(AtomicBool::new(false));
|
||||||
|
// m11p5 §2.1: the WAL retention pin the snapshot path raises while an
|
||||||
|
// artifact is staged / a joiner is mid-catch-up. Created here so the
|
||||||
|
// checkpoint thread (which consults it on every periodic compaction) and
|
||||||
|
// the `TidalDb` field below alias the same `AtomicU64`. `0` = unpinned.
|
||||||
|
let wal_retention_pin = Arc::new(AtomicU64::new(0));
|
||||||
// Shared text-index liveness latch: the checkpoint thread's 10s health
|
// Shared text-index liveness latch: the checkpoint thread's 10s health
|
||||||
// poll sets it, and `health_check` reads it. Created here so both the
|
// poll sets it, and `health_check` reads it. Created here so both the
|
||||||
// thread and the `TidalDb` field below alias the same `AtomicBool`.
|
// thread and the `TidalDb` field below alias the same `AtomicBool`.
|
||||||
@ -888,6 +914,10 @@ impl TidalDb {
|
|||||||
// always this node's real applied seqno (BLOCKER 6 / obs-REPL-1).
|
// always this node's real applied seqno (BLOCKER 6 / obs-REPL-1).
|
||||||
let replication_state_clone = Arc::clone(&replication_state);
|
let replication_state_clone = Arc::clone(&replication_state);
|
||||||
let seq_clone = Arc::clone(&last_seq);
|
let seq_clone = Arc::clone(&last_seq);
|
||||||
|
// m11p5 §2.1: the checkpoint thread reads the SAME pin the
|
||||||
|
// snapshot path raises, so a staged artifact's WAL tail is
|
||||||
|
// never compacted out from under an in-flight joiner.
|
||||||
|
let retention_pin_clone = Arc::clone(&wal_retention_pin);
|
||||||
// Resolve through the single source of truth so an explicit
|
// Resolve through the single source of truth so an explicit
|
||||||
// wal_dir override is honored here exactly as at WAL open.
|
// wal_dir override is honored here exactly as at WAL open.
|
||||||
let wal_dir = config.resolved_wal_dir();
|
let wal_dir = config.resolved_wal_dir();
|
||||||
@ -934,6 +964,7 @@ impl TidalDb {
|
|||||||
items,
|
items,
|
||||||
seq_clone,
|
seq_clone,
|
||||||
wal_dir,
|
wal_dir,
|
||||||
|
retention_pin_clone,
|
||||||
metrics_clone,
|
metrics_clone,
|
||||||
index_handles,
|
index_handles,
|
||||||
);
|
);
|
||||||
@ -990,9 +1021,11 @@ impl TidalDb {
|
|||||||
last_wal_seq: last_seq,
|
last_wal_seq: last_seq,
|
||||||
replicate_blobs,
|
replicate_blobs,
|
||||||
wal_term_mark: Arc::new(crate::wal::WalTermMark::default()),
|
wal_term_mark: Arc::new(crate::wal::WalTermMark::default()),
|
||||||
|
cluster_membership: Arc::new(crate::wal::ClusterMembership::default()),
|
||||||
ship_feed,
|
ship_feed,
|
||||||
shutdown_checkpoint,
|
shutdown_checkpoint,
|
||||||
checkpoint_thread,
|
checkpoint_thread,
|
||||||
|
wal_retention_pin,
|
||||||
text_index_unhealthy,
|
text_index_unhealthy,
|
||||||
category_index,
|
category_index,
|
||||||
format_index,
|
format_index,
|
||||||
|
|||||||
@ -99,6 +99,102 @@ impl TidalDb {
|
|||||||
self.wal_term_mark.snapshot()
|
self.wal_term_mark.snapshot()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The applied cluster membership (m11p5): the highest-version kind-4
|
||||||
|
/// record this node's log carries, as `(version, term, members)`. `None`
|
||||||
|
/// = the topology era (membership epoch 0; no conf-change has run).
|
||||||
|
#[must_use]
|
||||||
|
pub fn cluster_membership(&self) -> Option<(u64, u64, Vec<crate::wal::format::MemberEntry>)> {
|
||||||
|
self.cluster_membership.snapshot()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Journal a kind-4 membership record as this node's next WAL record
|
||||||
|
/// (m11p5): the leader's full-roster conf-change snapshot. Waits for the
|
||||||
|
/// group-commit fsync (the record ships to followers through the normal
|
||||||
|
/// feed like any blob), folds the membership cell, and returns the seqno
|
||||||
|
/// the record landed at.
|
||||||
|
///
|
||||||
|
/// This is the data-layer write only — it does NOT mutate any peer set,
|
||||||
|
/// quorum, or transport (those ride a later stage's apply path). It mirrors
|
||||||
|
/// [`append_term_marker`](Self::append_term_marker)'s staged-append +
|
||||||
|
/// group-commit-wait + fold-cell discipline.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// - `TidalError::invalid_input` outside cluster mode (no replicated log),
|
||||||
|
/// for a structurally-invalid roster (empty / oversized / duplicate id),
|
||||||
|
/// or for a version that does not strictly advance the applied cell (a
|
||||||
|
/// record must monotonically supersede — re-appending or regressing a
|
||||||
|
/// version would let the cell disagree with the log's tail).
|
||||||
|
/// - `TidalError::Durability` if the append cannot be staged or its fsync
|
||||||
|
/// fails — the caller MUST treat the conf-change as NOT having happened.
|
||||||
|
pub fn append_membership_record(
|
||||||
|
&self,
|
||||||
|
record: crate::wal::format::MembershipRecord,
|
||||||
|
) -> crate::Result<u64> {
|
||||||
|
if !self.replicate_blobs {
|
||||||
|
return Err(crate::TidalError::invalid_input(
|
||||||
|
"membership records require cluster mode (the WAL is not a replicated log here)",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Structural validation BEFORE the log: an invalid roster would fail
|
||||||
|
// apply identically on every follower (the receiver halts on apply
|
||||||
|
// errors), so it must never enter the replicated log.
|
||||||
|
record
|
||||||
|
.validate()
|
||||||
|
.map_err(|e| crate::TidalError::invalid_input(format!("{e}")))?;
|
||||||
|
// Monotonic-version guard: the cell advances only forward, so a record
|
||||||
|
// whose version does not strictly exceed the applied version could
|
||||||
|
// never advance the cell — refuse it loudly rather than journal a
|
||||||
|
// no-op record that the fold would silently ignore.
|
||||||
|
if let Some(applied) = self.cluster_membership.version()
|
||||||
|
&& record.version <= applied
|
||||||
|
{
|
||||||
|
return Err(crate::TidalError::invalid_input(format!(
|
||||||
|
"membership record version {} does not advance the applied version {applied} \
|
||||||
|
(versions are strictly increasing)",
|
||||||
|
record.version
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let sender = {
|
||||||
|
let wal = self
|
||||||
|
.wal
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
wal.as_ref().map(crate::wal::WalHandle::sender)
|
||||||
|
};
|
||||||
|
let Some(sender) = sender else {
|
||||||
|
return Err(crate::TidalError::invalid_input(
|
||||||
|
"membership records require a durable WAL",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let version = record.version;
|
||||||
|
let term = record.term;
|
||||||
|
let members = record.members.clone();
|
||||||
|
let blob = crate::wal::format::BlobRecord::Membership(record);
|
||||||
|
let seq = sender
|
||||||
|
.append_blob_staged(Arc::new(blob))
|
||||||
|
.map_err(|e| {
|
||||||
|
crate::TidalError::Durability(crate::schema::DurabilityError {
|
||||||
|
message: format!("membership record staging failed: {e}"),
|
||||||
|
})
|
||||||
|
})?
|
||||||
|
.wait()
|
||||||
|
.map_err(|e| {
|
||||||
|
crate::TidalError::Durability(crate::schema::DurabilityError {
|
||||||
|
message: format!("membership record append failed: {e}"),
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
super::wal_bridge::bump_last_seq_atomic(&self.last_wal_seq, seq);
|
||||||
|
self.cluster_membership.advance(version, term, members);
|
||||||
|
tracing::info!(
|
||||||
|
version,
|
||||||
|
term,
|
||||||
|
seq,
|
||||||
|
"membership record journaled (conf-change)"
|
||||||
|
);
|
||||||
|
Ok(seq)
|
||||||
|
}
|
||||||
|
|
||||||
/// Journal a kind-3 term marker as this node's next WAL record (m11p4):
|
/// Journal a kind-3 term marker as this node's next WAL record (m11p4):
|
||||||
/// the FIRST entry an elected leader writes in its term. Waits for the
|
/// the FIRST entry an elected leader writes in its term. Waits for the
|
||||||
/// group-commit fsync (the marker ships to followers through the normal
|
/// group-commit fsync (the marker ships to followers through the normal
|
||||||
@ -221,8 +317,151 @@ impl TidalDb {
|
|||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Test-only: durably checkpoint the follower's replicated state into a
|
/// The earliest WAL seqno this node's durable log can still serve to a
|
||||||
/// crash-consistent on-disk snapshot.
|
/// catch-up stream (m11p5 §2): the first byte of the lowest-numbered
|
||||||
|
/// segment on disk. A puller whose `from_seqno` is at or below this can
|
||||||
|
/// resume from the live WAL with no snapshot; below it means the covering
|
||||||
|
/// segments were compacted and a snapshot is required.
|
||||||
|
///
|
||||||
|
/// Returns `1` (the first real seqno; seq 0 is the dedup sentinel) when the
|
||||||
|
/// WAL is empty or absent — an empty log serves everything from the start,
|
||||||
|
/// so nothing is ever "below" the floor.
|
||||||
|
///
|
||||||
|
/// This reads `list_segments`' first entry, whose `first_seq` is the
|
||||||
|
/// segment's starting seqno (segments are named by their first seq and the
|
||||||
|
/// list is sorted ascending). It does NOT scan segment bodies, so it is
|
||||||
|
/// cheap enough to call on the stage path (per request) — unlike
|
||||||
|
/// [`read_wal_batches`](Self::read_wal_batches), which scans bytes.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns the underlying [`WalError`](crate::wal::error::WalError) when the
|
||||||
|
/// segment directory cannot be listed (IO) or holds an unparseable `.seg`
|
||||||
|
/// name ([`SegmentFormatUnknown`](crate::wal::error::WalError::SegmentFormatUnknown))
|
||||||
|
/// — the same typed surface `read_wal_batches` exposes, so the snapshot
|
||||||
|
/// source can route a format-unknown log into "snapshot required" rather
|
||||||
|
/// than guessing.
|
||||||
|
pub fn earliest_servable_seq(&self) -> std::result::Result<u64, crate::wal::error::WalError> {
|
||||||
|
let Some(wal_dir) = self.config.resolved_wal_dir() else {
|
||||||
|
// Ephemeral mode has no durable log; treat as "serves from 1" — but
|
||||||
|
// cluster mode refuses to start without a data dir, so this arm is
|
||||||
|
// unreachable on a serving node (it keeps the accessor total).
|
||||||
|
return Ok(1);
|
||||||
|
};
|
||||||
|
let segments = crate::wal::segment::list_segments(&wal_dir)?;
|
||||||
|
// `list_segments` is sorted ascending by `first_seq`; the first entry is
|
||||||
|
// the earliest still-on-disk segment. Empty ⇒ nothing has been
|
||||||
|
// compacted away, so the floor is the first real seqno.
|
||||||
|
Ok(segments
|
||||||
|
.first()
|
||||||
|
.map_or(1, |(first_seq, _)| (*first_seq).max(1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current WAL tail seqno (the highest seq durably appended). The seq a
|
||||||
|
/// snapshot artifact is captured at, and the seq the retention pin is taken
|
||||||
|
/// at *before* the copy (m11p5 §2.1).
|
||||||
|
#[must_use]
|
||||||
|
pub fn last_wal_seq(&self) -> u64 {
|
||||||
|
self.last_wal_seq.load(std::sync::atomic::Ordering::Acquire)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stage a snapshot artifact under `dest`, pinning WAL retention at the
|
||||||
|
/// captured seq BEFORE the copy begins (m11p5 §2.1).
|
||||||
|
///
|
||||||
|
/// This is the engine-owned half of the leader-side snapshot path: the
|
||||||
|
/// PIN-before-copy ordering is load-bearing (a pin installed *after* staging
|
||||||
|
/// cannot protect the copy window from the 30 s checkpoint thread, which may
|
||||||
|
/// compact between the ledger checkpoint and the marker write), so it lives
|
||||||
|
/// here rather than being left to the caller to sequence. The tidal-server
|
||||||
|
/// `NodeSnapshotSource` (caching, TTL, active-fetch accounting, manifest)
|
||||||
|
/// wraps this; on artifact reap it calls
|
||||||
|
/// [`unpin_wal_retention`](Self::unpin_wal_retention).
|
||||||
|
///
|
||||||
|
/// Sequence:
|
||||||
|
/// 1. Capture `S = last_wal_seq` (the live tail).
|
||||||
|
/// 2. **Pin at `S` before any copy** — the pin clamps online compaction's
|
||||||
|
/// floor so the segment chain covering `S + 1` survives.
|
||||||
|
/// 3. `create_backup_with(dest, { skip_text_flush, exclude_top_level })` —
|
||||||
|
/// quiesces signal writes, checkpoints the ledger + replication HWM at
|
||||||
|
/// the artifact's own captured seq, flushes fjall, copies (minus the
|
||||||
|
/// exclusions), writes the WAL checkpoint marker into the copy.
|
||||||
|
/// 4. Re-derive the artifact's exact recovered seq and **re-pin to it only
|
||||||
|
/// if it is LOWER** than `S` — `create_backup` captures its own
|
||||||
|
/// `last_wal_seq` internally, which can only equal or exceed the `S` we
|
||||||
|
/// pinned at (the tail never goes backward), so the pin can only need to
|
||||||
|
/// be HELD or LOWERED, never raised. Lowering is safe (it keeps strictly
|
||||||
|
/// more history); raising would open a gap below the artifact's resume
|
||||||
|
/// point. In practice the artifact seq ≥ `S`, so the pin stays at `S`.
|
||||||
|
///
|
||||||
|
/// Returns the artifact's WAL seq — the frontier a joiner advances to and
|
||||||
|
/// resumes the live stream from (`artifact_seq + 1`). On ANY error the pin
|
||||||
|
/// is RELEASED before returning (a failed stage must not leak a pin that
|
||||||
|
/// would freeze compaction forever).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// - [`TidalError::Backpressure`](crate::TidalError) is NOT returned here
|
||||||
|
/// (it gates the writers, not this caller); a concurrent in-flight backup
|
||||||
|
/// surfaces as `TidalError::Internal` "a backup is already in progress" —
|
||||||
|
/// the caller maps it to `SnapshotStageError::Busy`.
|
||||||
|
/// - `TidalError::Internal` for ephemeral mode (no data dir).
|
||||||
|
/// - `TidalError::Durability` if the checkpoint, copy, or marker write fails.
|
||||||
|
pub fn stage_snapshot(
|
||||||
|
&self,
|
||||||
|
dest: &std::path::Path,
|
||||||
|
exclude_top_level: Vec<&'static str>,
|
||||||
|
) -> crate::Result<u64> {
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
|
// 1 + 2: capture the tail and PIN BEFORE the copy. The pin must be
|
||||||
|
// installed before `create_backup_with` so the copy window is protected
|
||||||
|
// from the periodic compaction (§2.1).
|
||||||
|
let pinned_at = self.last_wal_seq.load(Ordering::Acquire);
|
||||||
|
self.pin_wal_retention(pinned_at);
|
||||||
|
|
||||||
|
// 3: stage. On error, release the pin we took — a failed stage must not
|
||||||
|
// leave compaction frozen.
|
||||||
|
let info = match self.create_backup_with(
|
||||||
|
dest,
|
||||||
|
&super::backup::BackupOptions {
|
||||||
|
skip_text_flush: true,
|
||||||
|
exclude_top_level,
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
Ok(info) => info,
|
||||||
|
Err(e) => {
|
||||||
|
self.unpin_wal_retention();
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 4: the artifact's recovered seq is the WAL checkpoint marker the copy
|
||||||
|
// carries — by construction `create_backup` writes it at its own
|
||||||
|
// captured `last_wal_seq`, which is `>= pinned_at` (the tail is
|
||||||
|
// monotonic). Re-derive it from the artifact and lower the pin only if
|
||||||
|
// it is below `pinned_at` (never raise — that would open a gap). We read
|
||||||
|
// the artifact's marker rather than trusting the live tail, so the pin
|
||||||
|
// tracks the artifact, not a tail that advanced after the copy.
|
||||||
|
let artifact_seq = read_artifact_marker_seq(dest).unwrap_or(pinned_at);
|
||||||
|
if artifact_seq < pinned_at {
|
||||||
|
// Lowering keeps strictly MORE history than `pinned_at` would — safe,
|
||||||
|
// and required so the resume range `artifact_seq + 1` is retained.
|
||||||
|
self.pin_wal_retention(artifact_seq);
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(
|
||||||
|
dest = %dest.display(),
|
||||||
|
pinned_at,
|
||||||
|
artifact_seq,
|
||||||
|
item_count = info.item_count,
|
||||||
|
size_bytes = info.size_bytes,
|
||||||
|
"snapshot artifact staged (WAL retention pinned)"
|
||||||
|
);
|
||||||
|
Ok(artifact_seq)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Durably checkpoint this node's replicated state into a crash-consistent
|
||||||
|
/// on-disk snapshot, synchronously (no 30 s wait).
|
||||||
///
|
///
|
||||||
/// Writes, atomically-consistent with each other:
|
/// Writes, atomically-consistent with each other:
|
||||||
/// 1. the signal-ledger aggregate (fjall checkpoint at the current WAL seq),
|
/// 1. the signal-ledger aggregate (fjall checkpoint at the current WAL seq),
|
||||||
@ -231,10 +470,18 @@ impl TidalDb {
|
|||||||
/// already folded into the aggregate), and
|
/// already folded into the aggregate), and
|
||||||
/// 3. the replication high-water-mark ([`ReplicationState`] checkpoint).
|
/// 3. the replication high-water-mark ([`ReplicationState`] checkpoint).
|
||||||
///
|
///
|
||||||
/// This lands the exact on-disk state a clean checkpoint cycle would, without
|
/// This lands the exact on-disk state a clean checkpoint cycle would.
|
||||||
/// the 30s wait, so a crash-recovery test can then simulate a hard crash (no
|
///
|
||||||
/// graceful shutdown) and prove the follower restores its replicated state and
|
/// # Why this is a real, non-test API (m11p5 §2.6)
|
||||||
/// applied-seqno boundary instead of resetting to a fresh node (BLOCKER 6).
|
///
|
||||||
|
/// The boot-time snapshot install seeds the replication frontier
|
||||||
|
/// (`applied_seqno(leader_shard) = the installed artifact's recovered WAL
|
||||||
|
/// tail`) and then MUST persist that seed BEFORE starting the receiver or any
|
||||||
|
/// pull — otherwise a crash between the seed and the first stream pull would
|
||||||
|
/// re-derive a fresh frontier and re-fetch a snapshot. Persisting the seed is
|
||||||
|
/// exactly this checkpoint, so it is promoted from test-only to a real
|
||||||
|
/// public API. The historical name `force_replication_checkpoint` is kept as
|
||||||
|
/// a thin test-only alias so existing crash-recovery tests still compile.
|
||||||
///
|
///
|
||||||
/// No-op in ephemeral mode (no durable storage / no WAL). Returns the same
|
/// No-op in ephemeral mode (no durable storage / no WAL). Returns the same
|
||||||
/// errors the periodic and shutdown checkpoints would.
|
/// errors the periodic and shutdown checkpoints would.
|
||||||
@ -245,8 +492,7 @@ impl TidalDb {
|
|||||||
/// signal-ledger, WAL-marker, or replication-state checkpoints fail.
|
/// signal-ledger, WAL-marker, or replication-state checkpoints fail.
|
||||||
///
|
///
|
||||||
/// [`ReplicationState`]: crate::replication::state::ReplicationState
|
/// [`ReplicationState`]: crate::replication::state::ReplicationState
|
||||||
#[cfg(any(test, feature = "test-utils"))]
|
pub fn persist_replication_checkpoint(&self) -> crate::Result<()> {
|
||||||
pub fn force_replication_checkpoint(&self) -> crate::Result<()> {
|
|
||||||
let (Some(ledger), Some(storage)) = (&self.ledger, &self.storage) else {
|
let (Some(ledger), Some(storage)) = (&self.ledger, &self.storage) else {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
@ -278,7 +524,7 @@ impl TidalDb {
|
|||||||
if let Some(Err(e)) = marker_result {
|
if let Some(Err(e)) = marker_result {
|
||||||
return Err(crate::TidalError::Durability(
|
return Err(crate::TidalError::Durability(
|
||||||
crate::schema::DurabilityError {
|
crate::schema::DurabilityError {
|
||||||
message: format!("force_replication_checkpoint WAL marker failed: {e}"),
|
message: format!("persist_replication_checkpoint WAL marker failed: {e}"),
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
@ -286,6 +532,16 @@ impl TidalDb {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Test-only alias for [`persist_replication_checkpoint`](Self::persist_replication_checkpoint).
|
||||||
|
///
|
||||||
|
/// Kept so the existing crash-recovery tests (`m8p2_replication_durability`,
|
||||||
|
/// `m11p5_membership_record`) compile unchanged after the promotion to a
|
||||||
|
/// real public API.
|
||||||
|
#[cfg(any(test, feature = "test-utils"))]
|
||||||
|
pub fn force_replication_checkpoint(&self) -> crate::Result<()> {
|
||||||
|
self.persist_replication_checkpoint()
|
||||||
|
}
|
||||||
|
|
||||||
/// Snapshot this node's live CRDT state for reconciliation after a partition.
|
/// Snapshot this node's live CRDT state for reconciliation after a partition.
|
||||||
///
|
///
|
||||||
/// Walks the signal ledger and the hard-negative index into a
|
/// Walks the signal ledger and the hard-negative index into a
|
||||||
@ -579,6 +835,31 @@ impl TidalDb {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Read the WAL checkpoint-marker seq a staged snapshot artifact carries
|
||||||
|
/// (m11p5): `<dest>/wal/checkpoint.meta`. `None` when the artifact's WAL has no
|
||||||
|
/// marker (an empty-WAL artifact at seq 0 writes none) or the marker is
|
||||||
|
/// unreadable — the caller treats that as "no lower seq to re-pin to" and holds
|
||||||
|
/// the pin at the captured tail.
|
||||||
|
fn read_artifact_marker_seq(dest: &std::path::Path) -> Option<u64> {
|
||||||
|
let wal_dir = dest.join("wal");
|
||||||
|
match crate::wal::checkpoint::CheckpointManager::read(&wal_dir) {
|
||||||
|
Ok(Some((seq, _ts))) => Some(seq),
|
||||||
|
Ok(None) => None,
|
||||||
|
Err(e) => {
|
||||||
|
// A corrupt/unreadable marker in our OWN just-written artifact is a
|
||||||
|
// surprise; log it but do not fail the stage — holding the pin at
|
||||||
|
// the captured tail is the conservative (more-history) choice.
|
||||||
|
tracing::warn!(
|
||||||
|
dest = %dest.display(),
|
||||||
|
error = %e,
|
||||||
|
"could not read staged snapshot WAL marker; holding the retention \
|
||||||
|
pin at the captured tail"
|
||||||
|
);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// `Weak`-handle adapter from the segment receiver's blob-apply seam to the
|
/// `Weak`-handle adapter from the segment receiver's blob-apply seam to the
|
||||||
/// database's WAL-first item write paths.
|
/// database's WAL-first item write paths.
|
||||||
///
|
///
|
||||||
|
|||||||
@ -455,6 +455,7 @@ pub(super) fn run_checkpoint_thread(
|
|||||||
storage: Box<dyn StorageEngine + Send + Sync>,
|
storage: Box<dyn StorageEngine + Send + Sync>,
|
||||||
last_wal_seq: Arc<AtomicU64>,
|
last_wal_seq: Arc<AtomicU64>,
|
||||||
wal_dir: Option<PathBuf>,
|
wal_dir: Option<PathBuf>,
|
||||||
|
wal_retention_pin: Arc<AtomicU64>,
|
||||||
metrics: Arc<MetricsState>,
|
metrics: Arc<MetricsState>,
|
||||||
index_handles: IndexMetricsHandles,
|
index_handles: IndexMetricsHandles,
|
||||||
) {
|
) {
|
||||||
@ -566,7 +567,19 @@ pub(super) fn run_checkpoint_thread(
|
|||||||
if let Some(ref dir) = wal_dir
|
if let Some(ref dir) = wal_dir
|
||||||
&& seq > 0
|
&& seq > 0
|
||||||
{
|
{
|
||||||
match crate::wal::compaction::compact_wal_online(dir, seq) {
|
// m11p5 §2.1: consult the retention pin. When a snapshot
|
||||||
|
// artifact is staged at seq S (pin == S), online compaction
|
||||||
|
// must preserve the segment chain covering S+1 onward so a
|
||||||
|
// joiner can resume the WAL stream from the artifact's tail.
|
||||||
|
// `pin == 0` (the steady state) is the unpinned sentinel and
|
||||||
|
// recovers the plain online-compaction behavior. Acquire pairs
|
||||||
|
// with the Release store in `pin_wal_retention`: a thread that
|
||||||
|
// raises the pin before staging an artifact must be guaranteed
|
||||||
|
// the NEXT compaction observes it (a missed pin could delete
|
||||||
|
// the artifact's tail between staging and the first joiner
|
||||||
|
// pull).
|
||||||
|
let pin = wal_retention_pin.load(Ordering::Acquire);
|
||||||
|
match crate::wal::compaction::compact_wal_online_pinned(dir, seq, pin) {
|
||||||
Ok(result) => {
|
Ok(result) => {
|
||||||
#[cfg(feature = "metrics")]
|
#[cfg(feature = "metrics")]
|
||||||
{
|
{
|
||||||
|
|||||||
@ -30,7 +30,7 @@
|
|||||||
//! [`wait_change`]: CommitIndex::wait_change
|
//! [`wait_change`]: CommitIndex::wait_change
|
||||||
//! [`peer_applied_hint`]: crate::replication::Transport::peer_applied_hint
|
//! [`peer_applied_hint`]: crate::replication::Transport::peer_applied_hint
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::sync::{Condvar, Mutex, PoisonError};
|
use std::sync::{Condvar, Mutex, PoisonError};
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
@ -83,14 +83,43 @@ struct CommitInner {
|
|||||||
/// (or a delayed report from a previous leadership) can never advance
|
/// (or a delayed report from a previous leadership) can never advance
|
||||||
/// this index. 0 = the topology era.
|
/// this index. 0 = the topology era.
|
||||||
term: u64,
|
term: u64,
|
||||||
/// Per-peer durable marks, monotonic within an epoch.
|
/// Per-VOTER durable marks, monotonic within an epoch. ONLY these feed
|
||||||
|
/// the k-th-largest commit selection — the quorum is over voters.
|
||||||
peers: HashMap<ShardId, u64>,
|
peers: HashMap<ShardId, u64>,
|
||||||
|
/// Number of voter marks required at-or-past a seqno for a majority:
|
||||||
|
/// `floor(n/2)` peers beyond the leader, where `n = peers.len() + 1` is
|
||||||
|
/// the full voter set. Reconfigurable (m11p5 §3.3): recomputed under the
|
||||||
|
/// index's own lock whenever the voter set changes, so the two quorum
|
||||||
|
/// formulas in this subsystem (here and `ElectionConfig::majority`) never
|
||||||
|
/// disagree across a conf-change.
|
||||||
|
needed: usize,
|
||||||
|
/// Per-LEARNER durable marks (m11p5 §3.3, review BLOCKER). Learners are
|
||||||
|
/// catching up under one-at-a-time conf-changes; their marks are
|
||||||
|
/// promotion input and transfer-wait input but **never** count toward
|
||||||
|
/// `needed`. The role-blind fold MUST NOT see these — two learners
|
||||||
|
/// "committing" a write no voter holds is acked-write loss.
|
||||||
|
learners: HashMap<ShardId, u64>,
|
||||||
/// Cached commit index (recomputed on every mark advance).
|
/// Cached commit index (recomputed on every mark advance).
|
||||||
commit: u64,
|
commit: u64,
|
||||||
/// Reusable buffer for the k-th-largest selection in
|
/// Reusable buffer for the k-th-largest selection in
|
||||||
/// [`CommitIndex::compute_commit`] — mark folds run on every ship ack
|
/// [`CommitIndex::compute_commit`] — mark folds run on every ship ack
|
||||||
/// and frontier report, so the recompute must not allocate per call.
|
/// and frontier report, so the recompute must not allocate per call.
|
||||||
scratch: Vec<u64>,
|
scratch: Vec<u64>,
|
||||||
|
/// Highest seqno folded from a same-term `update_peer_for_term` report
|
||||||
|
/// SINCE the current activation (m11p5 §3.2). The activation reset of
|
||||||
|
/// `commit` is NOT counted here, so `committed_in_term()` is vacuously
|
||||||
|
/// false until a genuine same-term voter report lands — the linchpin that
|
||||||
|
/// keeps the conf-change one-at-a-time gate from passing trivially on a
|
||||||
|
/// pre-baseline record (the vacuous-gate BLOCKER).
|
||||||
|
term_committed: u64,
|
||||||
|
/// Shards whose report arrived while in NEITHER the voter nor learner
|
||||||
|
/// set (m11p5 §3.3): logged at WARN once-per-shard-ish (rate-bounded by
|
||||||
|
/// membership in this set) plus the `unknown_reports` counter, instead of
|
||||||
|
/// the pre-m11p5 silent drop that let a joined-but-unregistered node
|
||||||
|
/// report forever without ever advancing quorum.
|
||||||
|
warned_unknown: HashSet<ShardId>,
|
||||||
|
/// Monotonic count of reports from a shard in neither set, for status.
|
||||||
|
unknown_reports: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Leader-side quorum commit index. See the module docs.
|
/// Leader-side quorum commit index. See the module docs.
|
||||||
@ -103,8 +132,6 @@ struct CommitInner {
|
|||||||
pub struct CommitIndex {
|
pub struct CommitIndex {
|
||||||
inner: Mutex<CommitInner>,
|
inner: Mutex<CommitInner>,
|
||||||
cv: Condvar,
|
cv: Condvar,
|
||||||
/// Peers needed at-or-past a seqno for majority: `floor((peers+1)/2)`.
|
|
||||||
needed: usize,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for CommitIndex {
|
impl std::fmt::Debug for CommitIndex {
|
||||||
@ -114,15 +141,26 @@ impl std::fmt::Debug for CommitIndex {
|
|||||||
.field("active", &inner.active)
|
.field("active", &inner.active)
|
||||||
.field("epoch", &inner.epoch)
|
.field("epoch", &inner.epoch)
|
||||||
.field("commit", &inner.commit)
|
.field("commit", &inner.commit)
|
||||||
.field("needed", &self.needed)
|
.field("needed", &inner.needed)
|
||||||
.field("peers", &inner.peers)
|
.field("peers", &inner.peers)
|
||||||
|
.field("learners", &inner.learners)
|
||||||
.finish_non_exhaustive()
|
.finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Majority of `n = peers + 1` total replicas is `floor(n/2)+1` nodes; the
|
||||||
|
/// leader is always one of them, so `floor(n/2) = ceil(p/2)` peers remain.
|
||||||
|
/// One formula shared by [`CommitIndex::new`] and
|
||||||
|
/// [`CommitIndex::reconfigure`], so a conf-change can never recompute `needed`
|
||||||
|
/// a different way than the constructor did.
|
||||||
|
const fn voters_needed(n_voter_peers: usize) -> usize {
|
||||||
|
n_voter_peers.div_ceil(2)
|
||||||
|
}
|
||||||
|
|
||||||
impl CommitIndex {
|
impl CommitIndex {
|
||||||
/// Build an index over `peers` (the replica set EXCLUDING the leader),
|
/// Build an index over `peers` (the replica set EXCLUDING the leader),
|
||||||
/// initially inactive with all marks at zero.
|
/// initially inactive with all marks at zero. No learners at boot —
|
||||||
|
/// learners only ever appear through [`reconfigure`](Self::reconfigure).
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(peers: &[ShardId], active: bool) -> Self {
|
pub fn new(peers: &[ShardId], active: bool) -> Self {
|
||||||
Self {
|
Self {
|
||||||
@ -131,14 +169,15 @@ impl CommitIndex {
|
|||||||
epoch: 0,
|
epoch: 0,
|
||||||
term: 0,
|
term: 0,
|
||||||
peers: peers.iter().map(|&p| (p, 0)).collect(),
|
peers: peers.iter().map(|&p| (p, 0)).collect(),
|
||||||
|
needed: voters_needed(peers.len()),
|
||||||
|
learners: HashMap::new(),
|
||||||
commit: 0,
|
commit: 0,
|
||||||
scratch: Vec::with_capacity(peers.len()),
|
scratch: Vec::with_capacity(peers.len()),
|
||||||
|
term_committed: 0,
|
||||||
|
warned_unknown: HashSet::new(),
|
||||||
|
unknown_reports: 0,
|
||||||
}),
|
}),
|
||||||
cv: Condvar::new(),
|
cv: Condvar::new(),
|
||||||
// Majority of n = peers+1 total replicas is floor(n/2)+1 nodes;
|
|
||||||
// the leader is always one of them, so floor(n/2) = ceil(p/2)
|
|
||||||
// peers remain.
|
|
||||||
needed: peers.len().div_ceil(2),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -146,10 +185,11 @@ impl CommitIndex {
|
|||||||
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
|
self.inner.lock().unwrap_or_else(PoisonError::into_inner)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Peers required at-or-past a seqno (beyond the leader) for majority.
|
/// Voter peers required at-or-past a seqno (beyond the leader) for
|
||||||
|
/// majority. Reconfigurable: this reads the current voter-set quorum.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn needed_peers(&self) -> usize {
|
pub fn needed_peers(&self) -> usize {
|
||||||
self.needed
|
self.lock().needed
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The current commit index (0 when no quorum information exists yet).
|
/// The current commit index (0 when no quorum information exists yet).
|
||||||
@ -184,7 +224,18 @@ impl CommitIndex {
|
|||||||
for mark in inner.peers.values_mut() {
|
for mark in inner.peers.values_mut() {
|
||||||
*mark = baseline;
|
*mark = baseline;
|
||||||
}
|
}
|
||||||
|
// Learners also re-baseline (their pre-activation marks belong to a
|
||||||
|
// prior leadership's numbering); they still never feed the commit.
|
||||||
|
for mark in inner.learners.values_mut() {
|
||||||
|
*mark = baseline;
|
||||||
|
}
|
||||||
inner.commit = baseline;
|
inner.commit = baseline;
|
||||||
|
// §3.2: the baseline reset is NOT a same-term commitment. Zeroing
|
||||||
|
// `term_committed` makes `committed_in_term()` vacuously false until a
|
||||||
|
// genuine same-term `update_peer_for_term` fold advances it — the
|
||||||
|
// activation record's own commit is what the one-at-a-time gate waits
|
||||||
|
// on, and it must not be satisfied by the reset that precedes it.
|
||||||
|
inner.term_committed = 0;
|
||||||
drop(inner);
|
drop(inner);
|
||||||
self.cv.notify_all();
|
self.cv.notify_all();
|
||||||
}
|
}
|
||||||
@ -197,6 +248,139 @@ impl CommitIndex {
|
|||||||
self.lock().term
|
self.lock().term
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether `seq` has been quorum-committed by a SAME-TERM voter report
|
||||||
|
/// since the current activation (m11p5 §3.2 — the one-at-a-time
|
||||||
|
/// conf-change gate's predicate).
|
||||||
|
///
|
||||||
|
/// This is TRUE only when a genuine [`update_peer_for_term`] fold has
|
||||||
|
/// advanced the commit to `>= seq` since [`activate`](Self::activate) —
|
||||||
|
/// it is NEVER satisfied by the activation baseline reset, which zeroes
|
||||||
|
/// the underlying high-water mark. That distinction is the linchpin: the
|
||||||
|
/// activation resets `committed()` to the new leader's baseline, so a
|
||||||
|
/// "commit index ≥ record seq" test passes trivially for every
|
||||||
|
/// pre-baseline record (the vacuous-gate BLOCKER). A pre-baseline record
|
||||||
|
/// is also structurally unshippable (the stream clamp), so it can never
|
||||||
|
/// be genuinely re-committed in this term — and this predicate correctly
|
||||||
|
/// refuses to claim it was.
|
||||||
|
///
|
||||||
|
/// [`update_peer_for_term`]: Self::update_peer_for_term
|
||||||
|
/// [`activate`]: Self::activate
|
||||||
|
#[must_use]
|
||||||
|
pub fn committed_in_term(&self, seq: u64) -> bool {
|
||||||
|
let inner = self.lock();
|
||||||
|
inner.active && inner.term_committed >= seq
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A learner's durable mark (0 = unknown / not a learner). Promotion
|
||||||
|
/// input and transfer-wait input (m11p5 §3.3); never feeds the commit.
|
||||||
|
#[must_use]
|
||||||
|
pub fn learner_mark(&self, learner: ShardId) -> u64 {
|
||||||
|
self.lock().learners.get(&learner).copied().unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-learner durable marks (for status surfaces), sorted by shard id.
|
||||||
|
#[must_use]
|
||||||
|
pub fn learner_marks(&self) -> Vec<(ShardId, u64)> {
|
||||||
|
let inner = self.lock();
|
||||||
|
let mut marks: Vec<(ShardId, u64)> = inner.learners.iter().map(|(&p, &m)| (p, m)).collect();
|
||||||
|
drop(inner);
|
||||||
|
marks.sort_unstable_by_key(|(p, _)| p.0);
|
||||||
|
marks
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Count of reports received from a shard in neither the voter nor learner
|
||||||
|
/// set (m11p5 §3.3). A non-zero, growing value means a node is reporting
|
||||||
|
/// into a config it is not a member of — a stranded joiner or a stale
|
||||||
|
/// roster on this leader.
|
||||||
|
#[must_use]
|
||||||
|
pub fn unknown_reports(&self) -> u64 {
|
||||||
|
self.lock().unknown_reports
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Switch the effective voter / learner sets under the index's own lock
|
||||||
|
/// (m11p5 §3.3 — the one fenced reconfigure path). Resizes the marks,
|
||||||
|
/// recomputes `needed` from the new voter count, and **re-evaluates**
|
||||||
|
/// in-flight `ack=quorum` waits against the new config instead of failing
|
||||||
|
/// them.
|
||||||
|
///
|
||||||
|
/// Mark policy (review finding: new voters must not inherit a stale mark):
|
||||||
|
/// - a shard already a voter keeps its current voter mark;
|
||||||
|
/// - a shard promoted learner→voter starts at 0 (its learner mark was
|
||||||
|
/// promotion EVIDENCE, not a committed-as-voter guarantee — counting it
|
||||||
|
/// toward quorum the instant it becomes a voter would let a barely-caught
|
||||||
|
/// learner's catch-up frontier satisfy a write it never durably held as
|
||||||
|
/// a voter);
|
||||||
|
/// - a brand-new voter starts at 0;
|
||||||
|
/// - a shard moved to the learner set keeps its mark there (it is still a
|
||||||
|
/// valid promotion/transfer input);
|
||||||
|
/// - a removed shard's mark is dropped from both sets.
|
||||||
|
///
|
||||||
|
/// Waiter semantics (review finding — the epoch-bump-as-Demoted error):
|
||||||
|
/// a conf-change is NOT a leadership change. Bumping the epoch (the
|
||||||
|
/// demotion signal) on every reconfigure would fail every in-flight
|
||||||
|
/// `ack=quorum` waiter with `Demoted` — an availability dip with the
|
||||||
|
/// wrong error class — even though the leadership term is unchanged. So
|
||||||
|
/// reconfigure does NOT touch the epoch: it recomputes the commit and
|
||||||
|
/// notifies, and waiters re-test their predicate. A SHRINK (lowering
|
||||||
|
/// `needed`) may satisfy a parked waiter instantly; a GROW (raising it)
|
||||||
|
/// keeps it waiting until enough of the larger set reports.
|
||||||
|
pub fn reconfigure(&self, voters: &[ShardId], learners: &[ShardId]) {
|
||||||
|
let mut inner = self.lock();
|
||||||
|
|
||||||
|
// New voter marks: inherit only if the shard was ALREADY a voter.
|
||||||
|
let mut new_voters: HashMap<ShardId, u64> = HashMap::with_capacity(voters.len());
|
||||||
|
for &v in voters {
|
||||||
|
let mark = inner.peers.get(&v).copied().unwrap_or(0);
|
||||||
|
new_voters.insert(v, mark);
|
||||||
|
}
|
||||||
|
// New learner marks: inherit a learner's existing mark; a demoted
|
||||||
|
// voter (voter→learner, rare) starts its learner mark from its voter
|
||||||
|
// mark so it stays a meaningful catch-up signal.
|
||||||
|
let mut new_learners: HashMap<ShardId, u64> = HashMap::with_capacity(learners.len());
|
||||||
|
for &l in learners {
|
||||||
|
let mark = inner
|
||||||
|
.learners
|
||||||
|
.get(&l)
|
||||||
|
.copied()
|
||||||
|
.or_else(|| inner.peers.get(&l).copied())
|
||||||
|
.unwrap_or(0);
|
||||||
|
new_learners.insert(l, mark);
|
||||||
|
}
|
||||||
|
|
||||||
|
inner.peers = new_voters;
|
||||||
|
inner.learners = new_learners;
|
||||||
|
inner.needed = voters_needed(voters.len());
|
||||||
|
// A shard that left both sets may have a stale "warned" flag — clear
|
||||||
|
// the warning ledger so a future re-entry warns again (and so the
|
||||||
|
// map does not grow unbounded across churn). Build the membership set
|
||||||
|
// first to avoid borrowing `inner` mutably and immutably at once.
|
||||||
|
let members: HashSet<ShardId> = inner
|
||||||
|
.peers
|
||||||
|
.keys()
|
||||||
|
.chain(inner.learners.keys())
|
||||||
|
.copied()
|
||||||
|
.collect();
|
||||||
|
inner.warned_unknown.retain(|s| members.contains(s));
|
||||||
|
|
||||||
|
// Recompute the commit over the new voter set and wake waiters: a
|
||||||
|
// shrink may now satisfy a parked `wait_for` (whose predicate is
|
||||||
|
// `commit >= seq`). Note we do NOT bump the epoch — this is a
|
||||||
|
// conf-change, not a demotion.
|
||||||
|
let commit = Self::compute_commit(&mut inner);
|
||||||
|
inner.commit = commit;
|
||||||
|
// We deliberately do NOT touch `term_committed` here. The §3.2 gate
|
||||||
|
// (`committed_in_term`) must advance ONLY from a genuine same-term
|
||||||
|
// `update_peer_for_term` fold — never from a reconfigure recompute. A
|
||||||
|
// shrink right after activation would otherwise re-raise it to the
|
||||||
|
// all-baseline k-th-largest (= the baseline) without any real
|
||||||
|
// commitment, re-opening the vacuous-gate BLOCKER. The shrink still
|
||||||
|
// satisfies in-flight WAITERS through `commit` + the notify below; the
|
||||||
|
// conf-change ONE-AT-A-TIME gate is a separate predicate that must
|
||||||
|
// stay anchored to real same-term folds.
|
||||||
|
drop(inner);
|
||||||
|
self.cv.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
/// Deactivate (leadership moved or the queue is shutting down): every
|
/// Deactivate (leadership moved or the queue is shutting down): every
|
||||||
/// current and future waiter fails with [`QuorumWaitError::Demoted`].
|
/// current and future waiter fails with [`QuorumWaitError::Demoted`].
|
||||||
pub fn deactivate(&self) {
|
pub fn deactivate(&self) {
|
||||||
@ -240,24 +424,56 @@ impl CommitIndex {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
self.fold_locked(&mut inner, peer, durable);
|
self.fold_locked(&mut inner, peer, durable);
|
||||||
|
// The same-term fold is the ONLY input that may satisfy the §3.2
|
||||||
|
// one-at-a-time gate. Record the post-fold commit (clamped monotonic)
|
||||||
|
// as the term's genuine high-water mark — the activation reset of
|
||||||
|
// `commit` never touches `term_committed`, so the gate stays vacuously
|
||||||
|
// false until a real same-term voter report lands.
|
||||||
|
if inner.commit > inner.term_committed {
|
||||||
|
inner.term_committed = inner.commit;
|
||||||
|
}
|
||||||
drop(inner);
|
drop(inner);
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The shared fold body (caller holds the lock).
|
/// The shared fold body (caller holds the lock). Folds into the VOTER
|
||||||
|
/// marks (and the commit index); a LEARNER mark is recorded in the
|
||||||
|
/// side-map without touching the quorum selection; an UNKNOWN reporter is
|
||||||
|
/// counted and warned once-per-shard rather than silently dropped.
|
||||||
fn fold_locked(&self, inner: &mut CommitInner, peer: ShardId, durable: u64) {
|
fn fold_locked(&self, inner: &mut CommitInner, peer: ShardId, durable: u64) {
|
||||||
let Some(mark) = inner.peers.get_mut(&peer) else {
|
if let Some(mark) = inner.peers.get_mut(&peer) {
|
||||||
return;
|
|
||||||
};
|
|
||||||
if durable <= *mark {
|
if durable <= *mark {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
*mark = durable;
|
*mark = durable;
|
||||||
let commit = self.compute_commit(inner);
|
let commit = Self::compute_commit(inner);
|
||||||
if commit > inner.commit {
|
if commit > inner.commit {
|
||||||
inner.commit = commit;
|
inner.commit = commit;
|
||||||
self.cv.notify_all();
|
self.cv.notify_all();
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(mark) = inner.learners.get_mut(&peer) {
|
||||||
|
// Learner marks advance monotonically (promotion + transfer-wait
|
||||||
|
// input) but NEVER feed `compute_commit` — they are not voters.
|
||||||
|
if durable > *mark {
|
||||||
|
*mark = durable;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Neither a voter nor a learner: the pre-m11p5 path silently dropped
|
||||||
|
// this, letting a joined-but-unregistered node report forever without
|
||||||
|
// advancing quorum (and without anyone knowing). Count it and WARN
|
||||||
|
// once per shard so a stranded reporter is diagnosable.
|
||||||
|
inner.unknown_reports += 1;
|
||||||
|
if inner.warned_unknown.insert(peer) {
|
||||||
|
tracing::warn!(
|
||||||
|
peer = peer.0,
|
||||||
|
durable,
|
||||||
|
"commit index: report from a shard in neither the voter nor learner set; \
|
||||||
|
ignoring (a conf-change may not have applied here yet)"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// k-th largest peer mark (k = `needed`); 0 when there are no peers
|
/// k-th largest peer mark (k = `needed`); 0 when there are no peers
|
||||||
@ -265,19 +481,23 @@ impl CommitIndex {
|
|||||||
/// [`committed`](Self::committed)). Selection (not a full sort) over the
|
/// [`committed`](Self::committed)). Selection (not a full sort) over the
|
||||||
/// inner scratch buffer: this runs on every ship ack and frontier
|
/// inner scratch buffer: this runs on every ship ack and frontier
|
||||||
/// report, so it must not allocate or do superlinear work per fold.
|
/// report, so it must not allocate or do superlinear work per fold.
|
||||||
fn compute_commit(&self, inner: &mut CommitInner) -> u64 {
|
fn compute_commit(inner: &mut CommitInner) -> u64 {
|
||||||
if self.needed == 0 {
|
let needed = inner.needed;
|
||||||
|
if needed == 0 {
|
||||||
return inner.commit;
|
return inner.commit;
|
||||||
}
|
}
|
||||||
let mut scratch = std::mem::take(&mut inner.scratch);
|
let mut scratch = std::mem::take(&mut inner.scratch);
|
||||||
scratch.clear();
|
scratch.clear();
|
||||||
scratch.extend(inner.peers.values().copied());
|
scratch.extend(inner.peers.values().copied());
|
||||||
let commit = if scratch.len() < self.needed {
|
let commit = if scratch.len() < needed {
|
||||||
0
|
0
|
||||||
} else {
|
} else {
|
||||||
// k-th largest = index `needed - 1` in descending order.
|
// k-th largest = index `needed - 1` in descending order. ONLY
|
||||||
|
// voter marks are in `peers` — learner marks live in a separate
|
||||||
|
// map and never reach this selection, so two learners can never
|
||||||
|
// form a quorum no voter holds (the §3.3 BLOCKER).
|
||||||
*scratch
|
*scratch
|
||||||
.select_nth_unstable_by(self.needed - 1, |a, b| b.cmp(a))
|
.select_nth_unstable_by(needed - 1, |a, b| b.cmp(a))
|
||||||
.1
|
.1
|
||||||
};
|
};
|
||||||
inner.scratch = scratch;
|
inner.scratch = scratch;
|
||||||
@ -345,7 +565,7 @@ impl CommitIndex {
|
|||||||
if !inner.active {
|
if !inner.active {
|
||||||
return Err(QuorumWaitError::Demoted);
|
return Err(QuorumWaitError::Demoted);
|
||||||
}
|
}
|
||||||
if self.needed == 0 {
|
if inner.needed == 0 {
|
||||||
return Ok(seq);
|
return Ok(seq);
|
||||||
}
|
}
|
||||||
let epoch = inner.epoch;
|
let epoch = inner.epoch;
|
||||||
@ -525,4 +745,227 @@ mod tests {
|
|||||||
idx.activate(0, 1);
|
idx.activate(0, 1);
|
||||||
assert_eq!(idx.wait_for(123, deadline_in(0)), Ok(123));
|
assert_eq!(idx.wait_for(123, deadline_in(0)), Ok(123));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── m11p5 §3.3: role-aware + reconfigurable ──────────────────────────────
|
||||||
|
|
||||||
|
/// The §3.3 BLOCKER, made concrete: two learners reporting high marks must
|
||||||
|
/// NEVER advance the commit index — a voter quorum is the only thing that
|
||||||
|
/// commits. With one voter (needed=1) and two learners, only the VOTER's
|
||||||
|
/// mark may move the index; the learners' high marks are inert.
|
||||||
|
#[test]
|
||||||
|
fn learner_marks_never_advance_the_commit() {
|
||||||
|
// Voter set {1} (one peer, needs that one). Learners {2, 3}.
|
||||||
|
let idx = CommitIndex::new(&shards(&[1]), true);
|
||||||
|
idx.reconfigure(&shards(&[1]), &shards(&[2, 3]));
|
||||||
|
idx.activate(0, 1);
|
||||||
|
|
||||||
|
// Two learners report well past anything the voter holds.
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(2), 1_000, 1));
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(3), 1_000, 1));
|
||||||
|
assert_eq!(
|
||||||
|
idx.committed(),
|
||||||
|
0,
|
||||||
|
"two learners must not commit a write no voter holds"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
idx.learner_mark(ShardId(2)),
|
||||||
|
1_000,
|
||||||
|
"learner mark is tracked"
|
||||||
|
);
|
||||||
|
assert_eq!(idx.learner_mark(ShardId(3)), 1_000);
|
||||||
|
|
||||||
|
// Only the voter's report moves the index.
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(1), 42, 1));
|
||||||
|
assert_eq!(idx.committed(), 42, "the lone voter's mark is the quorum");
|
||||||
|
assert_eq!(
|
||||||
|
idx.learner_mark(ShardId(1)),
|
||||||
|
0,
|
||||||
|
"a voter has no learner mark"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reconfigure SHRINK (lowering `needed`) re-evaluates an in-flight wait
|
||||||
|
/// instead of failing it: a waiter parked needing 2 voters is satisfied
|
||||||
|
/// the instant the set shrinks so its one existing mark is a majority.
|
||||||
|
#[test]
|
||||||
|
fn reconfigure_shrink_satisfies_an_in_flight_wait() {
|
||||||
|
// Start with 3 voters {1,2,3} → needs 2. Only voter 1 has reported 5.
|
||||||
|
let idx = Arc::new(CommitIndex::new(&shards(&[1, 2, 3]), true));
|
||||||
|
idx.activate(0, 1);
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(1), 5, 1));
|
||||||
|
assert_eq!(idx.committed(), 0, "1 of 3 voters is not a majority");
|
||||||
|
|
||||||
|
let waiter = {
|
||||||
|
let idx = Arc::clone(&idx);
|
||||||
|
std::thread::spawn(move || idx.wait_for(5, deadline_in(5_000)))
|
||||||
|
};
|
||||||
|
std::thread::sleep(Duration::from_millis(20));
|
||||||
|
|
||||||
|
// Shrink to a single voter {1}: needed drops to 1, voter 1's mark (5)
|
||||||
|
// is now a majority — the parked waiter resolves WITHOUT a Demoted.
|
||||||
|
idx.reconfigure(&shards(&[1]), &[]);
|
||||||
|
assert_eq!(
|
||||||
|
waiter.join().unwrap(),
|
||||||
|
Ok(5),
|
||||||
|
"a shrink that makes the existing mark a majority satisfies the waiter"
|
||||||
|
);
|
||||||
|
assert_eq!(idx.needed_peers(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reconfigure GROW (raising `needed`) keeps a waiter waiting: adding a
|
||||||
|
/// voter that has not reported cannot retroactively commit a higher seq.
|
||||||
|
/// New voters start at 0 (never inherit), so the grown set is genuinely
|
||||||
|
/// short of quorum until the new voter reports.
|
||||||
|
#[test]
|
||||||
|
fn reconfigure_grow_keeps_waiting_and_new_voters_start_at_zero() {
|
||||||
|
// 1 voter {1} → needs 1. Voter 1 reported 10 → committed 10.
|
||||||
|
let idx = Arc::new(CommitIndex::new(&shards(&[1]), true));
|
||||||
|
idx.activate(0, 1);
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(1), 10, 1));
|
||||||
|
assert_eq!(idx.committed(), 10);
|
||||||
|
|
||||||
|
// Grow to {1,2,3} → needs 2. Voter 1 still at 10; 2 and 3 start at 0,
|
||||||
|
// NOT inheriting any catch-up frontier. The 2nd-largest mark is now 0,
|
||||||
|
// so the commit RETRACTS in the cache but a wait at 10 must block.
|
||||||
|
idx.reconfigure(&shards(&[1, 2, 3]), &[]);
|
||||||
|
assert_eq!(idx.needed_peers(), 2);
|
||||||
|
// A fresh wait for seq 10 must NOT resolve instantly: the grown set is
|
||||||
|
// short of quorum (only voter 1 holds 10).
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
idx.wait_for(10, deadline_in(20)),
|
||||||
|
Err(QuorumWaitError::Timeout { .. })
|
||||||
|
),
|
||||||
|
"a grow leaves the waiter short of the larger quorum"
|
||||||
|
);
|
||||||
|
// A second voter reporting closes it.
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(2), 10, 1));
|
||||||
|
assert_eq!(idx.wait_for(10, deadline_in(0)), Ok(10));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// §3.2: `committed_in_term` is FALSE after activation until a genuine
|
||||||
|
/// same-term fold — never satisfied by the activation baseline reset (the
|
||||||
|
/// vacuous-gate BLOCKER).
|
||||||
|
#[test]
|
||||||
|
fn committed_in_term_is_false_until_a_same_term_fold() {
|
||||||
|
let idx = CommitIndex::new(&shards(&[1]), true);
|
||||||
|
// Activate at a high baseline: committed() jumps there immediately…
|
||||||
|
idx.activate(100, 5);
|
||||||
|
assert_eq!(idx.committed(), 100, "activation resets the cached commit");
|
||||||
|
// …but committed_in_term must NOT be satisfied by that reset.
|
||||||
|
assert!(
|
||||||
|
!idx.committed_in_term(100),
|
||||||
|
"the activation baseline is not a same-term commitment (vacuous gate)"
|
||||||
|
);
|
||||||
|
assert!(!idx.committed_in_term(1), "nothing committed in-term yet");
|
||||||
|
|
||||||
|
// A wrong-term report does not count.
|
||||||
|
assert!(!idx.update_peer_for_term(ShardId(1), 150, 4));
|
||||||
|
assert!(!idx.committed_in_term(101));
|
||||||
|
|
||||||
|
// A genuine same-term voter report advances the in-term high-water.
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(1), 150, 5));
|
||||||
|
assert!(
|
||||||
|
idx.committed_in_term(150),
|
||||||
|
"a same-term fold satisfies the gate at the folded seq"
|
||||||
|
);
|
||||||
|
assert!(idx.committed_in_term(120));
|
||||||
|
assert!(
|
||||||
|
!idx.committed_in_term(151),
|
||||||
|
"but never past what was folded"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Re-activation (a new leadership cycle) zeroes the in-term mark again.
|
||||||
|
idx.activate(200, 6);
|
||||||
|
assert!(
|
||||||
|
!idx.committed_in_term(200),
|
||||||
|
"a fresh activation makes the gate vacuously false once more"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `reconfigure` SHRINK right after activation must NOT make
|
||||||
|
/// `committed_in_term` true: the recompute would otherwise re-raise the
|
||||||
|
/// in-term high-water to the all-baseline k-th-largest without any genuine
|
||||||
|
/// same-term fold — re-opening the vacuous-gate BLOCKER via the conf-change
|
||||||
|
/// path. The shrink still satisfies in-flight WAITERS (their predicate is
|
||||||
|
/// `commit`), but the §3.2 gate stays anchored to real folds.
|
||||||
|
#[test]
|
||||||
|
fn reconfigure_shrink_does_not_vacuously_satisfy_the_term_gate() {
|
||||||
|
// 3 voters {1,2,3}, activate at baseline 100. No real fold yet.
|
||||||
|
let idx = CommitIndex::new(&shards(&[1, 2, 3]), true);
|
||||||
|
idx.activate(100, 7);
|
||||||
|
assert_eq!(idx.committed(), 100, "all marks reset to the baseline");
|
||||||
|
assert!(!idx.committed_in_term(100), "no genuine same-term fold yet");
|
||||||
|
|
||||||
|
// Shrink to a single voter {1}: commit recomputes to the baseline
|
||||||
|
// (k-th largest of {100} = 100), satisfying any `commit`-predicated
|
||||||
|
// waiter — but committed_in_term must STAY false.
|
||||||
|
idx.reconfigure(&shards(&[1]), &[]);
|
||||||
|
assert_eq!(idx.committed(), 100);
|
||||||
|
assert!(
|
||||||
|
!idx.committed_in_term(100),
|
||||||
|
"a shrink recompute is NOT a same-term commitment (vacuous gate via reconfigure)"
|
||||||
|
);
|
||||||
|
assert!(!idx.committed_in_term(1));
|
||||||
|
|
||||||
|
// Only a genuine same-term fold opens the gate.
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(1), 150, 7));
|
||||||
|
assert!(idx.committed_in_term(150));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A report from a shard in neither set is counted and warned
|
||||||
|
/// once-per-shard, never silently dropped (m11p5 §3.3 — the pre-m11p5
|
||||||
|
/// stranded-reporter hazard).
|
||||||
|
#[test]
|
||||||
|
fn unknown_reporter_is_counted_not_silently_dropped() {
|
||||||
|
let idx = CommitIndex::new(&shards(&[1]), true);
|
||||||
|
idx.activate(0, 1);
|
||||||
|
assert_eq!(idx.unknown_reports(), 0);
|
||||||
|
|
||||||
|
// Shard 99 is neither voter nor learner.
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(99), 50, 1));
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(99), 60, 1));
|
||||||
|
assert_eq!(
|
||||||
|
idx.unknown_reports(),
|
||||||
|
2,
|
||||||
|
"every unknown report is counted (not dropped silently)"
|
||||||
|
);
|
||||||
|
assert_eq!(idx.committed(), 0, "unknown reports never move the commit");
|
||||||
|
// The voter is unaffected.
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(1), 7, 1));
|
||||||
|
assert_eq!(idx.committed(), 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A learner promoted to voter starts its voter mark at 0 — its learner
|
||||||
|
/// catch-up frontier is promotion EVIDENCE, not a committed-as-voter
|
||||||
|
/// guarantee, and must not retroactively satisfy a write.
|
||||||
|
#[test]
|
||||||
|
fn promotion_does_not_inherit_the_learner_catch_up_mark() {
|
||||||
|
// Voter {1}, learner {2} caught up to 500.
|
||||||
|
let idx = CommitIndex::new(&shards(&[1]), true);
|
||||||
|
idx.reconfigure(&shards(&[1]), &shards(&[2]));
|
||||||
|
idx.activate(0, 1);
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(2), 500, 1));
|
||||||
|
assert_eq!(idx.learner_mark(ShardId(2)), 500);
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(1), 500, 1));
|
||||||
|
assert_eq!(idx.committed(), 500);
|
||||||
|
|
||||||
|
// Promote learner 2 → voter. needed becomes 1 (2 voters → floor(2/2)).
|
||||||
|
idx.reconfigure(&shards(&[1, 2]), &[]);
|
||||||
|
assert_eq!(idx.needed_peers(), 1);
|
||||||
|
// Voter 2 starts at 0, NOT 500: the 1st-largest of {500 (v1), 0 (v2)}
|
||||||
|
// is 500, so the commit holds at what voter 1 genuinely covers — but a
|
||||||
|
// wait BEYOND what a single voter holds must require voter 2 to report
|
||||||
|
// as a voter.
|
||||||
|
assert_eq!(
|
||||||
|
idx.learner_mark(ShardId(2)),
|
||||||
|
0,
|
||||||
|
"the shard is no longer a learner"
|
||||||
|
);
|
||||||
|
// Push the commit past 500: voter 1 reports 600. needed=1 so commit
|
||||||
|
// moves to 600 on voter 1 alone (n=3 with the leader → majority 2 →
|
||||||
|
// 1 peer), proving promotion didn't corrupt the selection.
|
||||||
|
assert!(idx.update_peer_for_term(ShardId(1), 600, 1));
|
||||||
|
assert_eq!(idx.committed(), 600);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -72,10 +72,46 @@ pub struct ElectionConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ElectionConfig {
|
impl ElectionConfig {
|
||||||
/// Majority of the full replica set (peers + self).
|
/// Quorum size over the **full voter set** (`peers + self`): the minimum
|
||||||
|
/// number of grants — *including the candidate's own self-grant* — that
|
||||||
|
/// constitutes a majority and may therefore win one term.
|
||||||
|
///
|
||||||
|
/// With `n = peers.len() + 1` total voters this is the true `floor(n/2)+1`.
|
||||||
|
/// The candidate always counts itself (it persists a self-vote in
|
||||||
|
/// [`ElectionState::start_election`] and seeds its own grant set), so the
|
||||||
|
/// machine compares `grants.len() >= majority()` where `grants` already
|
||||||
|
/// contains `self` — the self-grant is a member of the quorum, not an
|
||||||
|
/// addend on top of it.
|
||||||
|
///
|
||||||
|
/// # Why not `peers.len()/2 + 1`
|
||||||
|
///
|
||||||
|
/// That older form is the count of *peers* needed plus the implicit self,
|
||||||
|
/// and it is correct only at odd `n`. At **even** `n` it under-counts: with
|
||||||
|
/// `n = 4` (`peers.len() == 3`) it yields 2, so two disjoint vote quorums
|
||||||
|
/// `{A, B}` and `{C, D}` could each reach 2 grants and elect two leaders in
|
||||||
|
/// a single term — a split brain. The correct quorum at `n = 4` is 3, whose
|
||||||
|
/// majorities must overlap. The sibling [`CommitIndex`] already uses the
|
||||||
|
/// `div_ceil` form of this same arithmetic; both formulas in one subsystem
|
||||||
|
/// must agree. p5 makes even voter counts mandatory transit states
|
||||||
|
/// (3→4→5→4→3) so this can no longer be hand-waved as "odd-only".
|
||||||
|
///
|
||||||
|
/// Boundary cases this preserves:
|
||||||
|
/// - `peers.len() == 0` (`n = 1`, a single-node replica set) → `1`: the
|
||||||
|
/// lone node is its own majority and self-elects, as before.
|
||||||
|
/// - `peers.len() == 1` (`n = 2`) → `2`: a follower can **no longer**
|
||||||
|
/// self-elect with zero RPCs; one peer grant is required, and a leader
|
||||||
|
/// alone (self only = 1 < 2) must step down under `auto_election`.
|
||||||
|
/// - `peers.len() == 2` (`n = 3`) → `2`: unchanged from the old formula.
|
||||||
|
///
|
||||||
|
/// [`CommitIndex`]: crate::replication::commit::CommitIndex
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn majority(&self) -> usize {
|
pub const fn majority(&self) -> usize {
|
||||||
self.peers.len() / 2 + 1
|
// `floor(n/2)+1` over the full voter set `n = peers.len() + 1`. The
|
||||||
|
// design's `(peers.len()+1)/2 + 1` and this `peers.len().div_ceil(2)+1`
|
||||||
|
// are the identical integer value — `(p+1)/2 == ceil(p/2)` — expressed
|
||||||
|
// in the same `div_ceil` idiom the sibling `CommitIndex` uses, so the
|
||||||
|
// two quorum formulas in this subsystem read alike and stay lint-clean.
|
||||||
|
self.peers.len().div_ceil(2) + 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -196,6 +232,24 @@ pub struct ElectionState {
|
|||||||
lease_anchor: Instant,
|
lease_anchor: Instant,
|
||||||
/// Leader state: next heartbeat round due.
|
/// Leader state: next heartbeat round due.
|
||||||
heartbeat_due: Instant,
|
heartbeat_due: Instant,
|
||||||
|
/// Whether THIS node is a voter in the latest applied membership (m11p5
|
||||||
|
/// §3.3). Learners and removed nodes are NOT voters: the machine refuses
|
||||||
|
/// to self-start an election (a GATE, not a comment) while this is false —
|
||||||
|
/// `voters = role == Voter` and "learners never campaign" is enforced
|
||||||
|
/// here, not left to the driver. Topology-era / boot default: `true`
|
||||||
|
/// (every declared region is a voter until a conf-change says otherwise),
|
||||||
|
/// so a cluster with no kind-4 record behaves byte-for-byte as today.
|
||||||
|
is_voter: bool,
|
||||||
|
/// Whether campaigning is externally SUPPRESSED (m11p5 §3.3): the driver
|
||||||
|
/// sets this while the node is quarantined (divergent suffix) or removed.
|
||||||
|
/// The machine then never self-starts an election OR honors a `TimeoutNow`
|
||||||
|
/// — closing the gap the review found, where p4's quarantine
|
||||||
|
/// election-suppression was comment-only (the driver ticked the machine
|
||||||
|
/// unconditionally, so a quarantined node still campaigned at the machine
|
||||||
|
/// level and only lost the up-to-date comparison). A suppressed node still
|
||||||
|
/// VOTES (its grant is safe — vote uniqueness is unaffected) and still
|
||||||
|
/// follows a valid leader; it just cannot start a candidacy of its own.
|
||||||
|
campaign_suppressed: bool,
|
||||||
rng: XorShift,
|
rng: XorShift,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -251,6 +305,11 @@ impl ElectionState {
|
|||||||
peer_ack,
|
peer_ack,
|
||||||
lease_anchor: now,
|
lease_anchor: now,
|
||||||
heartbeat_due: now,
|
heartbeat_due: now,
|
||||||
|
// Topology-era default: this node is a voter and not suppressed.
|
||||||
|
// A conf-change (`reconfigure`) or the driver's quarantine/removal
|
||||||
|
// gate flips these; absent any kind-4 record they stay as today.
|
||||||
|
is_voter: true,
|
||||||
|
campaign_suppressed: false,
|
||||||
rng,
|
rng,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -288,9 +347,12 @@ impl ElectionState {
|
|||||||
if now < self.election_deadline {
|
if now < self.election_deadline {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
// A quarantined or auto-off node still ticks; it just never
|
// A quarantined, removed, learner, or auto-off node still
|
||||||
// self-starts an election.
|
// ticks; it just never self-starts an election. The
|
||||||
if !self.config.auto_election {
|
// non-voter / suppression gate is a GATE here (m11p5 §3.3),
|
||||||
|
// not a comment — the driver ticks the machine unconditionally,
|
||||||
|
// so without this a quarantined node would still campaign.
|
||||||
|
if !self.config.auto_election || !self.can_campaign() {
|
||||||
self.reset_election_timer(now);
|
self.reset_election_timer(now);
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
@ -428,6 +490,14 @@ impl ElectionState {
|
|||||||
if reply.term > self.term {
|
if reply.term > self.term {
|
||||||
return self.step_down_to(reply.term, None);
|
return self.step_down_to(reply.term, None);
|
||||||
}
|
}
|
||||||
|
// A grant only counts from a CURRENT voter (or self). After a
|
||||||
|
// conf-change removes a voter, an in-flight grant from that voter may
|
||||||
|
// still arrive — it must NOT count toward the resized majority (m11p5
|
||||||
|
// §3.3, review finding). `reconfigure` clears the tally; this guard
|
||||||
|
// also rejects a late grant that races the reconfigure.
|
||||||
|
if !self.is_current_voter(from) {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
if prevote {
|
if prevote {
|
||||||
if self.role != Role::PreCandidate || !reply.granted {
|
if self.role != Role::PreCandidate || !reply.granted {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
@ -448,6 +518,11 @@ impl ElectionState {
|
|||||||
Vec::new()
|
Vec::new()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether `region` is a voter in the current config (self or a peer).
|
||||||
|
fn is_current_voter(&self, region: RegionId) -> bool {
|
||||||
|
region == self.config.self_region || self.config.peers.contains(®ion)
|
||||||
|
}
|
||||||
|
|
||||||
/// A follower acked (or refused) our heartbeat.
|
/// A follower acked (or refused) our heartbeat.
|
||||||
pub fn on_heartbeat_ack(
|
pub fn on_heartbeat_ack(
|
||||||
&mut self,
|
&mut self,
|
||||||
@ -483,6 +558,14 @@ impl ElectionState {
|
|||||||
if term < self.term || self.role == Role::Leader {
|
if term < self.term || self.role == Role::Leader {
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
}
|
}
|
||||||
|
// A non-voter or suppressed (quarantined/removed) node must not take
|
||||||
|
// over even when told to: a removed node serving as Ready or a
|
||||||
|
// quarantined node winning on a sanctioned transfer would both be
|
||||||
|
// unsafe. The sanctioning leader picks a valid voter; if it picked
|
||||||
|
// this node in error, refusing is the safe outcome (§3.3).
|
||||||
|
if !self.can_campaign() {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
let mut actions = Vec::new();
|
let mut actions = Vec::new();
|
||||||
if term > self.term {
|
if term > self.term {
|
||||||
actions.push(self.adopt_term(term));
|
actions.push(self.adopt_term(term));
|
||||||
@ -544,6 +627,86 @@ impl ElectionState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Apply a membership conf-change to the voter set (m11p5 §3.3) — a pure
|
||||||
|
/// machine input, mirroring `CommitIndex::reconfigure` and
|
||||||
|
/// `ShipQueue::{add,remove}_peer` in the one fenced apply path. `voters` is
|
||||||
|
/// every OTHER voter region in the latest applied record (self excluded,
|
||||||
|
/// exactly like [`ElectionConfig::peers`]).
|
||||||
|
///
|
||||||
|
/// What it does:
|
||||||
|
/// - recompute `majority()` from the post-change voter set (via the
|
||||||
|
/// config's `peers`, which this method overwrites);
|
||||||
|
/// - resize `peer_ack`, RETAINING the last ack for a peer that stays a
|
||||||
|
/// voter (so a leader does not lose its lease evidence across a
|
||||||
|
/// conf-change) and dropping a removed peer's slot;
|
||||||
|
/// - **clear the in-flight prevote/vote grant sets** (review finding):
|
||||||
|
/// grants from a just-removed voter must not count against the resized
|
||||||
|
/// majority, and a grant the candidate already holds from a still-voter
|
||||||
|
/// must be re-collected against the new quorum to stay sound. Clearing
|
||||||
|
/// both is the conservative, always-safe choice — the candidacy simply
|
||||||
|
/// re-solicits; a transient round loss is retried by the next timeout.
|
||||||
|
///
|
||||||
|
/// It does NOT change this node's own voter-ness — call
|
||||||
|
/// [`set_voter`](Self::set_voter) for that (the caller knows from the
|
||||||
|
/// record whether self is a voter); the campaign gate reads it.
|
||||||
|
pub fn reconfigure(&mut self, voters: Vec<RegionId>) {
|
||||||
|
// Retain acks for surviving voters; new voters start with no ack.
|
||||||
|
let new_peer_ack: Vec<(RegionId, Option<Instant>)> = voters
|
||||||
|
.iter()
|
||||||
|
.map(|&v| {
|
||||||
|
let prior = self
|
||||||
|
.peer_ack
|
||||||
|
.iter()
|
||||||
|
.find(|(p, _)| *p == v)
|
||||||
|
.and_then(|(_, a)| *a);
|
||||||
|
(v, prior)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
self.config.peers = voters;
|
||||||
|
self.peer_ack = new_peer_ack;
|
||||||
|
// Grants are config-relative; a roster change invalidates the in-flight
|
||||||
|
// tally. Clear both sets — a removed voter's grant must not count, and
|
||||||
|
// re-soliciting against the new quorum is always sound.
|
||||||
|
self.prevote_grants.clear();
|
||||||
|
self.vote_grants.clear();
|
||||||
|
// If this node is mid-candidacy, its own self-grant is re-seeded by the
|
||||||
|
// next solicitation; the timer already runs, so liveness is the retry.
|
||||||
|
if self.role == Role::PreCandidate {
|
||||||
|
self.prevote_grants.insert(self.config.self_region);
|
||||||
|
} else if self.role == Role::Candidate {
|
||||||
|
self.vote_grants.insert(self.config.self_region);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set whether this node is a voter in the latest applied membership
|
||||||
|
/// (m11p5 §3.3). A learner / removed node (`false`) cannot self-start an
|
||||||
|
/// election or honor a `TimeoutNow` — the campaign gate.
|
||||||
|
pub const fn set_voter(&mut self, is_voter: bool) {
|
||||||
|
self.is_voter = is_voter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Externally suppress / un-suppress campaigning (m11p5 §3.3): the driver
|
||||||
|
/// sets this while the node is quarantined or removed. A suppressed node
|
||||||
|
/// never self-starts an election or honors a `TimeoutNow`, but still votes
|
||||||
|
/// and follows a valid leader.
|
||||||
|
pub const fn set_campaign_suppressed(&mut self, suppressed: bool) {
|
||||||
|
self.campaign_suppressed = suppressed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this node is a voter in the latest applied membership.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn is_voter(&self) -> bool {
|
||||||
|
self.is_voter
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether campaigning is currently allowed: a voter that is not
|
||||||
|
/// externally suppressed (quarantine/removal). Read by the campaign gates
|
||||||
|
/// in `tick` and `on_timeout_now`.
|
||||||
|
#[must_use]
|
||||||
|
const fn can_campaign(&self) -> bool {
|
||||||
|
self.is_voter && !self.campaign_suppressed
|
||||||
|
}
|
||||||
|
|
||||||
// ── Internals ───────────────────────────────────────────────────────────
|
// ── Internals ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
fn tick_leader(&mut self, now: Instant) -> Vec<Action> {
|
fn tick_leader(&mut self, now: Instant) -> Vec<Action> {
|
||||||
@ -1316,4 +1479,495 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert_eq!(m.role(), Role::Leader);
|
assert_eq!(m.role(), Role::Leader);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `majority()` over the full voter set `n = peers.len() + 1` must be the
|
||||||
|
/// true `floor(n/2)+1`. The table is the load-bearing arithmetic: every
|
||||||
|
/// quorum decision in the machine funnels through it, so an even-`n`
|
||||||
|
/// undercount here is a split-brain bug (the §3.0 BLOCKER). The expected
|
||||||
|
/// column is computed by hand from `floor(n/2)+1` — never from the formula
|
||||||
|
/// under test — so the test cannot rubber-stamp the implementation.
|
||||||
|
#[test]
|
||||||
|
fn majority_table_over_full_voter_set() {
|
||||||
|
// (peers.len(), expected majority over n = peers+1 voters)
|
||||||
|
// n: 1 2 3 4 5 6 7
|
||||||
|
// │ │ │ │ │ │ └─ floor(7/2)+1 = 4
|
||||||
|
// │ │ │ │ │ └───── floor(6/2)+1 = 4
|
||||||
|
// │ │ │ │ └───────── floor(5/2)+1 = 3
|
||||||
|
// │ │ │ └───────────── floor(4/2)+1 = 3 (old formula: 2 — BUG)
|
||||||
|
// │ │ └───────────────── floor(3/2)+1 = 2
|
||||||
|
// │ └───────────────────── floor(2/2)+1 = 2 (old formula: 1 — BUG)
|
||||||
|
// └───────────────────────── floor(1/2)+1 = 1
|
||||||
|
let cases: [(usize, usize); 7] = [(0, 1), (1, 2), (2, 2), (3, 3), (4, 3), (5, 4), (6, 4)];
|
||||||
|
for (n_peers, want) in cases {
|
||||||
|
let peers: Vec<u16> = (1..=u16::try_from(n_peers).unwrap()).collect();
|
||||||
|
let cfg = config(0, &peers);
|
||||||
|
assert_eq!(
|
||||||
|
cfg.majority(),
|
||||||
|
want,
|
||||||
|
"peers.len()={n_peers} (n={} voters): majority must be floor(n/2)+1 = {want}",
|
||||||
|
n_peers + 1
|
||||||
|
);
|
||||||
|
// Every majority strictly exceeds half the voter set, so any two
|
||||||
|
// quorums must share a voter — the overlap that forbids two
|
||||||
|
// leaders in one term.
|
||||||
|
let n = n_peers + 1;
|
||||||
|
assert!(
|
||||||
|
2 * cfg.majority() > n,
|
||||||
|
"majority {} does not strictly exceed half of n={n}",
|
||||||
|
cfg.majority()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// n=4 split-brain regression: with the OLD `peers.len()/2 + 1 = 2`,
|
||||||
|
/// disjoint 2-grant sets `{A,B}` and `{C,D}` each reached "majority" and
|
||||||
|
/// elected two leaders in one term. With the corrected `majority() = 3`,
|
||||||
|
/// two self-grants plus one peer grant each (the most two disjoint
|
||||||
|
/// candidates can muster from a 4-voter set without sharing a voter) can
|
||||||
|
/// NO LONGER win — proving the overlap requirement is restored.
|
||||||
|
#[test]
|
||||||
|
fn n4_disjoint_two_grant_sets_cannot_both_win() {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
// Voter set {0,1,2,3}: candidate A=0 with peers {1,2,3}; candidate
|
||||||
|
// C=2 with peers {0,1,3}. Each campaigns and collects grants from a
|
||||||
|
// set disjoint from the other (A counts self 0 + peer 1; C counts
|
||||||
|
// self 2 + peer 3) — disjoint 2-sets over 4 voters.
|
||||||
|
let mut a = follower(0, &[1, 2, 3], 0, t0);
|
||||||
|
let mut c = follower(2, &[0, 1, 3], 0, t0);
|
||||||
|
assert_eq!(a.config().majority(), 3, "n=4 quorum is 3, not the old 2");
|
||||||
|
assert_eq!(c.config().majority(), 3);
|
||||||
|
|
||||||
|
// A: timeout → prevote (self) ; one prevote grant is NOT enough now.
|
||||||
|
let t1 = past_timeout(t0);
|
||||||
|
let _ = a.tick(t1, log(0, 0));
|
||||||
|
assert_eq!(a.role(), Role::PreCandidate);
|
||||||
|
let _ = a.on_vote_response(
|
||||||
|
region(1),
|
||||||
|
VoteReply {
|
||||||
|
term: 0,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
// self(0) + grant(1) = 2 prevote grants < majority 3: still pre-vote.
|
||||||
|
assert_eq!(
|
||||||
|
a.role(),
|
||||||
|
Role::PreCandidate,
|
||||||
|
"2 of 4 is no longer a prevote majority — A cannot proceed to a real election on a disjoint 2-set"
|
||||||
|
);
|
||||||
|
|
||||||
|
// C: the symmetric disjoint attempt. self(2) + grant(3) = 2 < 3.
|
||||||
|
let _ = c.tick(t1, log(0, 0));
|
||||||
|
assert_eq!(c.role(), Role::PreCandidate);
|
||||||
|
let _ = c.on_vote_response(
|
||||||
|
region(3),
|
||||||
|
VoteReply {
|
||||||
|
term: 0,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
c.role(),
|
||||||
|
Role::PreCandidate,
|
||||||
|
"the disjoint counterpart is equally blocked — no two leaders in one term"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Sanity: a SHARED third voter would push one of them over the line.
|
||||||
|
// A picks up voter 2 as well → self(0)+1+2 = 3 prevote grants = majority.
|
||||||
|
let _ = a.on_vote_response(
|
||||||
|
region(2),
|
||||||
|
VoteReply {
|
||||||
|
term: 0,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
a.role(),
|
||||||
|
Role::Candidate,
|
||||||
|
"an OVERLAPPING 3-set is a real majority and proceeds"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// n=2 (one peer): a follower must NOT self-elect with zero RPCs (the old
|
||||||
|
/// `peers.len()/2 + 1 = 1` let it win on its own self-grant while
|
||||||
|
/// check-quorum kept the old leader alive — a split brain), and a single
|
||||||
|
/// grant from the one peer DOES elect (majority 2 = self + the peer).
|
||||||
|
#[test]
|
||||||
|
fn n2_no_self_election_without_rpcs_and_peer_grant_elects() {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let mut m = follower(0, &[1], 0, t0);
|
||||||
|
assert_eq!(m.config().majority(), 2, "n=2 quorum is 2, not the old 1");
|
||||||
|
|
||||||
|
// Timeout → pre-vote with self only. With majority 2 this must NOT
|
||||||
|
// instant-win: the machine must actually send a vote request out.
|
||||||
|
let t1 = past_timeout(t0);
|
||||||
|
let actions = m.tick(t1, log(0, 0));
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::PreCandidate,
|
||||||
|
"self-grant alone (1 of 2) is not a majority — no instant win"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(&actions[..], [Action::SendVotes(rpc)] if rpc.prevote && rpc.term == 1),
|
||||||
|
"must solicit the one peer's pre-vote, not self-elect: {actions:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(m.term(), 0, "pre-vote never bumps the term");
|
||||||
|
|
||||||
|
// The one peer grants the pre-vote → real election (still needs the
|
||||||
|
// peer's real grant; self alone is again 1 of 2).
|
||||||
|
let actions = m.on_vote_response(
|
||||||
|
region(1),
|
||||||
|
VoteReply {
|
||||||
|
term: 0,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(m.role(), Role::Candidate, "prevote majority reached");
|
||||||
|
assert_eq!(m.term(), 1);
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
&actions[..],
|
||||||
|
[
|
||||||
|
Action::PersistHardState { term: 1, voted_for: Some(v) },
|
||||||
|
Action::SendVotes(rpc)
|
||||||
|
] if *v == region(0) && !rpc.prevote
|
||||||
|
),
|
||||||
|
"candidacy persists then solicits the real vote — does NOT win on self alone: {actions:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The peer's real grant: self(0) + peer(1) = 2 = majority → leader.
|
||||||
|
let actions = m.on_vote_response(
|
||||||
|
region(1),
|
||||||
|
VoteReply {
|
||||||
|
term: 1,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::Leader,
|
||||||
|
"self + the one peer = majority of 2"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
&actions[..],
|
||||||
|
[
|
||||||
|
Action::BecomeLeader { term: 1 },
|
||||||
|
Action::SendHeartbeats { term: 1 }
|
||||||
|
]
|
||||||
|
),
|
||||||
|
"{actions:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// n=2 check-quorum: a leader alone (its one peer silent) must step down
|
||||||
|
/// under `auto_election` — `fresh = self = 1 < majority 2`. The old
|
||||||
|
/// formula (majority 1) kept it alive while the partitioned peer could
|
||||||
|
/// self-elect, the dual-leader window §3.0 calls out.
|
||||||
|
#[test]
|
||||||
|
fn n2_leader_steps_down_when_its_one_peer_goes_silent() {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let mut m = follower(0, &[1], 0, t0);
|
||||||
|
// Win: timeout → prevote → (peer grant) → election → (peer grant) → leader.
|
||||||
|
let t1 = past_timeout(t0);
|
||||||
|
let _ = m.tick(t1, log(0, 0));
|
||||||
|
let _ = m.on_vote_response(
|
||||||
|
region(1),
|
||||||
|
VoteReply {
|
||||||
|
term: 0,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
let _ = m.on_vote_response(
|
||||||
|
region(1),
|
||||||
|
VoteReply {
|
||||||
|
term: 1,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(m.role(), Role::Leader);
|
||||||
|
|
||||||
|
// Inside the lease (grace anchor) the leader holds even with no acks.
|
||||||
|
let t2 = t1 + Duration::from_millis(500);
|
||||||
|
assert!(
|
||||||
|
m.tick(t2, log(1, 0))
|
||||||
|
.iter()
|
||||||
|
.all(|a| !matches!(a, Action::BecomeFollower { .. })),
|
||||||
|
"inside the lease the leader holds"
|
||||||
|
);
|
||||||
|
// Past the lease with the one peer silent: fresh = self = 1 < 2 → down.
|
||||||
|
let t3 = t1 + Duration::from_millis(901);
|
||||||
|
let actions = m.tick(t3, log(1, 0));
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::Follower,
|
||||||
|
"a 2-voter leader alone is a minority of 1 — it must step down"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(
|
||||||
|
&actions[..],
|
||||||
|
[Action::BecomeFollower {
|
||||||
|
term: 1,
|
||||||
|
leader: None
|
||||||
|
}]
|
||||||
|
),
|
||||||
|
"{actions:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// n=1 (zero peers): the lone node is its own majority (`majority() == 1`)
|
||||||
|
/// and must still self-elect on timeout with no RPCs at all — the
|
||||||
|
/// degenerate single-node replica set the fix must not regress.
|
||||||
|
#[test]
|
||||||
|
fn n1_single_node_still_self_elects() {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let mut m = follower(0, &[], 0, t0);
|
||||||
|
assert_eq!(
|
||||||
|
m.config().majority(),
|
||||||
|
1,
|
||||||
|
"a single voter is its own majority"
|
||||||
|
);
|
||||||
|
let actions = m.tick(past_timeout(t0), log(0, 0));
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::Leader,
|
||||||
|
"n=1: self-grant is already a majority — instant leadership"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
actions
|
||||||
|
.iter()
|
||||||
|
.any(|a| matches!(a, Action::BecomeLeader { term: 1 })),
|
||||||
|
"the lone node journals its leadership without any peer RPC: {actions:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── m11p5 §3.3: reconfigure + campaign gate ──────────────────────────────
|
||||||
|
|
||||||
|
/// `reconfigure` recomputes `majority()` from the post-change voter set —
|
||||||
|
/// the 3→4→5 transit table the conf-changes walk through. The expected
|
||||||
|
/// column is `floor(n/2)+1` by hand, never the formula under test.
|
||||||
|
#[test]
|
||||||
|
fn reconfigure_recomputes_majority_3_4_5() {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
// Start at 3 voters: self(0) + peers {1,2} → majority 2.
|
||||||
|
let mut m = follower(0, &[1, 2], 0, t0);
|
||||||
|
assert_eq!(m.config().majority(), 2, "n=3 → 2");
|
||||||
|
|
||||||
|
// Grow to 4 voters: peers {1,2,3} → majority 3.
|
||||||
|
m.reconfigure(vec![region(1), region(2), region(3)]);
|
||||||
|
assert_eq!(m.config().majority(), 3, "n=4 → 3 (the even-n case)");
|
||||||
|
assert_eq!(m.config().peers.len(), 3, "peer_ack/peers resized to 3");
|
||||||
|
|
||||||
|
// Grow to 5 voters: peers {1,2,3,4} → majority 3.
|
||||||
|
m.reconfigure(vec![region(1), region(2), region(3), region(4)]);
|
||||||
|
assert_eq!(m.config().majority(), 3, "n=5 → 3");
|
||||||
|
|
||||||
|
// Shrink back to 4 then 3.
|
||||||
|
m.reconfigure(vec![region(1), region(2), region(3)]);
|
||||||
|
assert_eq!(m.config().majority(), 3, "n=4 → 3");
|
||||||
|
m.reconfigure(vec![region(1), region(2)]);
|
||||||
|
assert_eq!(m.config().majority(), 2, "n=3 → 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A candidate's stale grants from a removed voter cannot win after a
|
||||||
|
/// reconfigure: the grant sets are CLEARED, so a candidate that held a
|
||||||
|
/// near-majority before a shrink must re-solicit against the new quorum
|
||||||
|
/// rather than win on votes from voters that no longer exist.
|
||||||
|
#[test]
|
||||||
|
fn reconfigure_clears_grants_so_a_removed_voters_grant_cannot_win() {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
// 5 voters {0,1,2,3,4} → majority 3. Drive 0 to Candidate with 2
|
||||||
|
// grants in hand (self + region 4), one short of the win.
|
||||||
|
let mut m = follower(0, &[1, 2, 3, 4], 0, t0);
|
||||||
|
let t1 = past_timeout(t0);
|
||||||
|
let _ = m.tick(t1, log(0, 0));
|
||||||
|
// prevote: self + 2 grants reaches the prevote majority (3) → Candidate.
|
||||||
|
let _ = m.on_vote_response(
|
||||||
|
region(1),
|
||||||
|
VoteReply {
|
||||||
|
term: 0,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
let _ = m.on_vote_response(
|
||||||
|
region(2),
|
||||||
|
VoteReply {
|
||||||
|
term: 0,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(m.role(), Role::Candidate);
|
||||||
|
// Real election: collect ONE real grant (self + region 4) — 2 of 3.
|
||||||
|
let _ = m.on_vote_response(
|
||||||
|
region(4),
|
||||||
|
VoteReply {
|
||||||
|
term: 1,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(m.role(), Role::Candidate, "2 of 3 — one short");
|
||||||
|
|
||||||
|
// Now reconfigure removes regions 3 and 4 (the grant-holder): voters
|
||||||
|
// become {0,1,2} → majority 2. The grant sets clear, so the candidate
|
||||||
|
// re-seeds only its self-grant (1 of 2) and CANNOT win on region 4's
|
||||||
|
// now-stale grant.
|
||||||
|
m.reconfigure(vec![region(1), region(2)]);
|
||||||
|
assert_eq!(m.config().majority(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::Candidate,
|
||||||
|
"the candidacy stands but its tally was cleared"
|
||||||
|
);
|
||||||
|
// A duplicate of region 4's grant must NOT count (region 4 is gone, and
|
||||||
|
// even a stray grant cannot push past the cleared tally to a win here):
|
||||||
|
// only a fresh grant from a CURRENT voter completes the majority.
|
||||||
|
let _ = m.on_vote_response(
|
||||||
|
region(4),
|
||||||
|
VoteReply {
|
||||||
|
term: 1,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::Candidate,
|
||||||
|
"a removed voter's grant cannot complete the new majority"
|
||||||
|
);
|
||||||
|
// A grant from a current voter (region 1) completes self + 1 = 2.
|
||||||
|
let _ = m.on_vote_response(
|
||||||
|
region(1),
|
||||||
|
VoteReply {
|
||||||
|
term: 1,
|
||||||
|
granted: true,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
t1,
|
||||||
|
log(0, 0),
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::Leader,
|
||||||
|
"a current voter's grant completes the resized majority"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A non-voter (learner / removed) node never campaigns: a timeout does NOT
|
||||||
|
/// self-start, and an explicit `TimeoutNow` is refused — the GATE in the
|
||||||
|
/// machine, not a comment (§3.3 last bullet).
|
||||||
|
#[test]
|
||||||
|
fn non_voter_cannot_campaign() {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let mut m = follower(0, &[1, 2], 0, t0);
|
||||||
|
m.set_voter(false); // a learner
|
||||||
|
assert!(!m.is_voter());
|
||||||
|
|
||||||
|
// Timeout: must NOT self-start despite auto_election on.
|
||||||
|
let actions = m.tick(past_timeout(t0), log(0, 0));
|
||||||
|
assert!(
|
||||||
|
actions.is_empty() && m.role() == Role::Follower,
|
||||||
|
"a learner must not self-start an election: {actions:?}"
|
||||||
|
);
|
||||||
|
// Even an explicit TimeoutNow is refused.
|
||||||
|
let actions = m.on_timeout_now(0, past_timeout(t0), log(0, 0));
|
||||||
|
assert!(
|
||||||
|
actions.is_empty() && m.role() == Role::Follower,
|
||||||
|
"a learner must not honor TimeoutNow: {actions:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Promotion to voter re-enables campaigning. The earlier ticks reset
|
||||||
|
// the election timer to `now + randomized_timeout`, so tick past a
|
||||||
|
// fresh worst-case window from the last gated tick.
|
||||||
|
m.set_voter(true);
|
||||||
|
let later = past_timeout(t0) + Duration::from_millis(3001);
|
||||||
|
let actions = m.tick(later, log(0, 0));
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::PreCandidate,
|
||||||
|
"a promoted voter campaigns normally: {actions:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The quarantine gate (§3.3): the review found p4's quarantine
|
||||||
|
/// election-suppression was comment-only — the driver ticks the machine
|
||||||
|
/// unconditionally, so a quarantined node still campaigned at the machine
|
||||||
|
/// level. With the machine-level `campaign_suppressed` gate, a suppressed
|
||||||
|
/// node neither self-starts nor honors a `TimeoutNow`, but still votes.
|
||||||
|
#[test]
|
||||||
|
fn quarantine_suppression_gates_campaigning_but_not_voting() {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let mut m = follower(0, &[1, 2], 5, t0);
|
||||||
|
m.set_campaign_suppressed(true); // driver latched quarantine
|
||||||
|
|
||||||
|
// No self-start despite the timeout + auto_election.
|
||||||
|
let actions = m.tick(past_timeout(t0), log(5, 10));
|
||||||
|
assert!(
|
||||||
|
actions.is_empty() && m.role() == Role::Follower,
|
||||||
|
"a quarantined node must not campaign: {actions:?}"
|
||||||
|
);
|
||||||
|
// No TimeoutNow takeover either.
|
||||||
|
let actions = m.on_timeout_now(5, past_timeout(t0), log(5, 10));
|
||||||
|
assert!(
|
||||||
|
actions.is_empty() && m.role() == Role::Follower,
|
||||||
|
"a quarantined node must not honor TimeoutNow: {actions:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// But it STILL votes for a legitimate up-to-date candidate (vote
|
||||||
|
// uniqueness is unaffected by suppression — its grant is safe).
|
||||||
|
let (reply, _) = m.on_vote_request(
|
||||||
|
VoteRpc {
|
||||||
|
term: 6,
|
||||||
|
candidate: region(1),
|
||||||
|
log: log(5, 20),
|
||||||
|
prevote: false,
|
||||||
|
transfer: false,
|
||||||
|
},
|
||||||
|
log(5, 10),
|
||||||
|
past_timeout(t0),
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
reply.granted,
|
||||||
|
"a suppressed node still grants a valid vote — only its own candidacy is gated"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Clearing suppression (reseed → un-quarantine) restores campaigning.
|
||||||
|
m.set_campaign_suppressed(false);
|
||||||
|
let actions = m.tick(past_timeout(t0) + Duration::from_millis(4000), log(6, 10));
|
||||||
|
assert_eq!(
|
||||||
|
m.role(),
|
||||||
|
Role::PreCandidate,
|
||||||
|
"clearing suppression re-enables self-start: {actions:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
494
tidal/src/replication/membership_store.rs
Normal file
494
tidal/src/replication/membership_store.rs
Normal file
@ -0,0 +1,494 @@
|
|||||||
|
//! Durable cluster-membership cache (m11p5): the last applied roster, on disk.
|
||||||
|
//!
|
||||||
|
//! One file, `data_dir/membership`, written with the EXACT `ElectionStore`
|
||||||
|
//! discipline — magic + version + BLAKE3 checksum framing, write `.tmp`,
|
||||||
|
//! [`sync_file_durable`] (`F_FULLFSYNC` on macOS), atomic rename,
|
||||||
|
//! [`sync_dir_durable`] — so corruption is *detected*, never guessed around.
|
||||||
|
//!
|
||||||
|
//! # Why a cache, not a source of truth
|
||||||
|
//!
|
||||||
|
//! The WAL-recovered [`ClusterMembership`] cell is the authoritative roster
|
||||||
|
//! (design §3.6): it wins over this cache at open. This file exists only for
|
||||||
|
//! the **pre-open boot loop** — a seed-join boot reads it for seed lists and
|
||||||
|
//! leader discovery before the WAL is opened, and a restart boots from it
|
||||||
|
//! without contacting a seed. It is rewritten from the cell after every applied
|
||||||
|
//! conf-change record, excluded from snapshot manifests, and survives the
|
||||||
|
//! reseed swap inside staging.
|
||||||
|
//!
|
||||||
|
//! # Format
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! magic "TMEM" (4) | version u8 (1) | payload_len u32 LE (4)
|
||||||
|
//! payload : the membership body (same length-prefixed encoding the kind-4 WAL
|
||||||
|
//! record body uses, so the on-disk cache and the log can never drift)
|
||||||
|
//! checksum : truncated BLAKE3 (16) over magic||version||payload_len||payload
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! [`sync_file_durable`]: crate::wal::sync_file_durable
|
||||||
|
//! [`sync_dir_durable`]: crate::wal::sync_dir_durable
|
||||||
|
//! [`ClusterMembership`]: crate::wal::ClusterMembership
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::wal::error::WalError;
|
||||||
|
use crate::wal::format::{
|
||||||
|
MAX_MEMBERSHIP_MEMBERS, MAX_MEMBERSHIP_STRING_BYTES, MemberEntry, MemberRole,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// File name inside the node's data dir.
|
||||||
|
const MEMBERSHIP_FILE: &str = "membership";
|
||||||
|
|
||||||
|
/// File magic: "TMEM" (tidalDB membership).
|
||||||
|
const MAGIC: [u8; 4] = *b"TMEM";
|
||||||
|
|
||||||
|
/// Format version 1.
|
||||||
|
const VERSION: u8 = 1;
|
||||||
|
|
||||||
|
/// Fixed header bytes before the variable-length payload: magic 4 + version 1
|
||||||
|
/// + `payload_len` u32 (4).
|
||||||
|
const HEADER_SIZE: usize = 4 + 1 + 4;
|
||||||
|
|
||||||
|
/// Truncated-BLAKE3 checksum length (mirrors [`ElectionStore`]'s 16-byte
|
||||||
|
/// truncation).
|
||||||
|
///
|
||||||
|
/// [`ElectionStore`]: super::election_store::ElectionStore
|
||||||
|
const CHECKSUM_SIZE: usize = 16;
|
||||||
|
|
||||||
|
/// A durable membership snapshot: the `(version, term, members)` the
|
||||||
|
/// [`ClusterMembership`](crate::wal::ClusterMembership) cell held when it was
|
||||||
|
/// last written.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct MembershipSnapshot {
|
||||||
|
/// The conf version this roster is at.
|
||||||
|
pub version: u64,
|
||||||
|
/// The leadership term that appended this roster.
|
||||||
|
pub term: u64,
|
||||||
|
/// The full member roster.
|
||||||
|
pub members: Vec<MemberEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reader/writer for the membership cache file.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct MembershipStore {
|
||||||
|
path: PathBuf,
|
||||||
|
dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MembershipStore {
|
||||||
|
/// Bind to `data_dir/membership`.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(data_dir: &Path) -> Self {
|
||||||
|
Self {
|
||||||
|
path: data_dir.join(MEMBERSHIP_FILE),
|
||||||
|
dir: data_dir.to_path_buf(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load the cached roster. Absent → `Ok(None)` (the pre-open loop falls
|
||||||
|
/// back to the seed list); present-but-corrupt → a typed error (a
|
||||||
|
/// half-written or bit-rotted cache must be *detected*, not silently
|
||||||
|
/// parsed into a wrong roster).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`WalError::Corruption`] when the file exists but cannot be read or
|
||||||
|
/// fails its magic/version/length/checksum/structural validation.
|
||||||
|
pub fn load(&self) -> Result<Option<MembershipSnapshot>, WalError> {
|
||||||
|
let bytes = match std::fs::read(&self.path) {
|
||||||
|
Ok(b) => b,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(e) => {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership cache at {} exists but cannot be read ({e}); \
|
||||||
|
repair or remove it",
|
||||||
|
self.path.display()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let snapshot = decode(&bytes).map_err(|why| WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership cache at {} is corrupt ({why}); the authoritative roster is the \
|
||||||
|
WAL-recovered cell — repair or remove the cache",
|
||||||
|
self.path.display()
|
||||||
|
),
|
||||||
|
})?;
|
||||||
|
Ok(Some(snapshot))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Durably persist `snapshot`: write `.tmp`, fsync, rename, fsync dir.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`WalError::Corruption`] if the snapshot fails structural validation
|
||||||
|
/// (the same invariants the WAL record enforces, so the cache can never
|
||||||
|
/// hold a roster the log would reject); [`WalError::Io`] on any filesystem
|
||||||
|
/// failure.
|
||||||
|
pub fn persist(&self, snapshot: &MembershipSnapshot) -> Result<(), WalError> {
|
||||||
|
let bytes = encode(snapshot)?;
|
||||||
|
let tmp = self.path.with_extension("tmp");
|
||||||
|
{
|
||||||
|
use std::io::Write;
|
||||||
|
let mut f = std::fs::File::create(&tmp)?;
|
||||||
|
f.write_all(&bytes)?;
|
||||||
|
crate::wal::sync_file_durable(&f)?;
|
||||||
|
}
|
||||||
|
std::fs::rename(&tmp, &self.path)?;
|
||||||
|
crate::wal::sync_dir_durable(&self.dir)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encode the membership body: `version u64 | term u64 | member_count u32 |
|
||||||
|
/// member*`. Shared by the cache and (structurally identical to) the WAL
|
||||||
|
/// record body so the two encodings cannot diverge.
|
||||||
|
fn encode_body(snapshot: &MembershipSnapshot) -> Result<Vec<u8>, WalError> {
|
||||||
|
if snapshot.members.is_empty() {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: "membership cache: roster is empty".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if snapshot.members.len() > MAX_MEMBERSHIP_MEMBERS {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership cache: {} members exceeds the {MAX_MEMBERSHIP_MEMBERS} ceiling",
|
||||||
|
snapshot.members.len()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let member_count = u32::try_from(snapshot.members.len()).map_err(|_| WalError::Corruption {
|
||||||
|
message: "membership cache: member_count exceeds u32".into(),
|
||||||
|
})?;
|
||||||
|
let mut seen = std::collections::HashSet::with_capacity(snapshot.members.len());
|
||||||
|
for m in &snapshot.members {
|
||||||
|
if !seen.insert(m.id) {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!("membership cache: duplicate member id {}", m.id),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut body = Vec::with_capacity(20 + snapshot.members.len() * 64);
|
||||||
|
body.extend_from_slice(&snapshot.version.to_le_bytes());
|
||||||
|
body.extend_from_slice(&snapshot.term.to_le_bytes());
|
||||||
|
body.extend_from_slice(&member_count.to_le_bytes());
|
||||||
|
for m in &snapshot.members {
|
||||||
|
body.extend_from_slice(&m.id.to_le_bytes());
|
||||||
|
body.push(m.role.to_byte());
|
||||||
|
push_string(&mut body, &m.name, "name")?;
|
||||||
|
push_string(&mut body, &m.grpc_addr, "grpc_addr")?;
|
||||||
|
push_string(&mut body, &m.http_addr, "http_addr")?;
|
||||||
|
}
|
||||||
|
Ok(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_string(buf: &mut Vec<u8>, s: &str, field: &str) -> Result<(), WalError> {
|
||||||
|
if s.len() > MAX_MEMBERSHIP_STRING_BYTES {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership cache: {field} is {} bytes, exceeds the \
|
||||||
|
{MAX_MEMBERSHIP_STRING_BYTES}-byte ceiling",
|
||||||
|
s.len()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// `len() <= MAX_MEMBERSHIP_STRING_BYTES` (well under u32::MAX).
|
||||||
|
#[allow(clippy::cast_possible_truncation)]
|
||||||
|
let len = s.len() as u32;
|
||||||
|
buf.extend_from_slice(&len.to_le_bytes());
|
||||||
|
buf.extend_from_slice(s.as_bytes());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode(snapshot: &MembershipSnapshot) -> Result<Vec<u8>, WalError> {
|
||||||
|
let body = encode_body(snapshot)?;
|
||||||
|
let payload_len = u32::try_from(body.len()).map_err(|_| WalError::Corruption {
|
||||||
|
message: "membership cache: payload exceeds u32".into(),
|
||||||
|
})?;
|
||||||
|
let mut buf = Vec::with_capacity(HEADER_SIZE + body.len() + CHECKSUM_SIZE);
|
||||||
|
buf.extend_from_slice(&MAGIC);
|
||||||
|
buf.push(VERSION);
|
||||||
|
buf.extend_from_slice(&payload_len.to_le_bytes());
|
||||||
|
buf.extend_from_slice(&body);
|
||||||
|
let hash = blake3::hash(&buf);
|
||||||
|
buf.extend_from_slice(&hash.as_bytes()[0..CHECKSUM_SIZE]);
|
||||||
|
Ok(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A cursor over the cache body that refuses every over-read (the same
|
||||||
|
/// defensive discipline the WAL record decoder uses).
|
||||||
|
struct Cursor<'a> {
|
||||||
|
bytes: &'a [u8],
|
||||||
|
pos: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Cursor<'a> {
|
||||||
|
const fn new(bytes: &'a [u8]) -> Self {
|
||||||
|
Self { bytes, pos: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take(&mut self, n: usize, what: &str) -> Result<&'a [u8], String> {
|
||||||
|
let end = self
|
||||||
|
.pos
|
||||||
|
.checked_add(n)
|
||||||
|
.ok_or_else(|| "length overflow".to_string())?;
|
||||||
|
let slice = self
|
||||||
|
.bytes
|
||||||
|
.get(self.pos..end)
|
||||||
|
.ok_or_else(|| format!("truncated reading {what}"))?;
|
||||||
|
self.pos = end;
|
||||||
|
Ok(slice)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u8(&mut self, what: &str) -> Result<u8, String> {
|
||||||
|
Ok(self.take(1, what)?[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u16(&mut self, what: &str) -> Result<u16, String> {
|
||||||
|
let b = self.take(2, what)?;
|
||||||
|
Ok(u16::from_le_bytes([b[0], b[1]]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u32(&mut self, what: &str) -> Result<u32, String> {
|
||||||
|
let b = self.take(4, what)?;
|
||||||
|
Ok(u32::from_le_bytes(
|
||||||
|
b.try_into().map_err(|_| "bad u32".to_string())?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u64(&mut self, what: &str) -> Result<u64, String> {
|
||||||
|
let b = self.take(8, what)?;
|
||||||
|
Ok(u64::from_le_bytes(
|
||||||
|
b.try_into().map_err(|_| "bad u64".to_string())?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn string(&mut self, field: &str) -> Result<String, String> {
|
||||||
|
let len = self.u32(field)? as usize;
|
||||||
|
if len > MAX_MEMBERSHIP_STRING_BYTES {
|
||||||
|
return Err(format!("{field} length {len} exceeds the ceiling"));
|
||||||
|
}
|
||||||
|
let bytes = self.take(len, field)?;
|
||||||
|
String::from_utf8(bytes.to_vec()).map_err(|_| format!("{field} is not valid UTF-8"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode(bytes: &[u8]) -> Result<MembershipSnapshot, String> {
|
||||||
|
if bytes.len() < HEADER_SIZE + CHECKSUM_SIZE {
|
||||||
|
return Err(format!(
|
||||||
|
"{} bytes, need at least {}",
|
||||||
|
bytes.len(),
|
||||||
|
HEADER_SIZE + CHECKSUM_SIZE
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if bytes[0..4] != MAGIC {
|
||||||
|
return Err("bad magic".into());
|
||||||
|
}
|
||||||
|
if bytes[4] != VERSION {
|
||||||
|
return Err(format!("unknown version {}", bytes[4]));
|
||||||
|
}
|
||||||
|
let payload_len = u32::from_le_bytes(
|
||||||
|
bytes[5..9]
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| "bad payload_len bytes".to_string())?,
|
||||||
|
) as usize;
|
||||||
|
let body_end = HEADER_SIZE
|
||||||
|
.checked_add(payload_len)
|
||||||
|
.ok_or_else(|| "payload_len overflow".to_string())?;
|
||||||
|
let total = body_end
|
||||||
|
.checked_add(CHECKSUM_SIZE)
|
||||||
|
.ok_or_else(|| "total length overflow".to_string())?;
|
||||||
|
if bytes.len() != total {
|
||||||
|
return Err(format!(
|
||||||
|
"framed length {} != declared {total} (payload_len {payload_len})",
|
||||||
|
bytes.len()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
// Checksum covers magic||version||payload_len||payload (everything before
|
||||||
|
// the trailing 16 checksum bytes).
|
||||||
|
let hash = blake3::hash(&bytes[0..body_end]);
|
||||||
|
if bytes[body_end..total] != hash.as_bytes()[0..CHECKSUM_SIZE] {
|
||||||
|
return Err("checksum mismatch".into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let body = &bytes[HEADER_SIZE..body_end];
|
||||||
|
let mut cur = Cursor::new(body);
|
||||||
|
let version = cur.u64("version")?;
|
||||||
|
let term = cur.u64("term")?;
|
||||||
|
let member_count = cur.u32("member_count")? as usize;
|
||||||
|
if member_count == 0 {
|
||||||
|
return Err("roster is empty".into());
|
||||||
|
}
|
||||||
|
if member_count > MAX_MEMBERSHIP_MEMBERS {
|
||||||
|
return Err(format!(
|
||||||
|
"member_count {member_count} exceeds the {MAX_MEMBERSHIP_MEMBERS} ceiling"
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut members = Vec::with_capacity(member_count);
|
||||||
|
let mut seen = std::collections::HashSet::with_capacity(member_count);
|
||||||
|
for _ in 0..member_count {
|
||||||
|
let id = cur.u16("member id")?;
|
||||||
|
let Ok(role) = MemberRole::from_byte(cur.u8("member role")?) else {
|
||||||
|
return Err("unknown member role".into());
|
||||||
|
};
|
||||||
|
if !seen.insert(id) {
|
||||||
|
return Err(format!("duplicate member id {id}"));
|
||||||
|
}
|
||||||
|
let name = cur.string("name")?;
|
||||||
|
let grpc_addr = cur.string("grpc_addr")?;
|
||||||
|
let http_addr = cur.string("http_addr")?;
|
||||||
|
members.push(MemberEntry {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
grpc_addr,
|
||||||
|
http_addr,
|
||||||
|
role,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if cur.pos != body.len() {
|
||||||
|
return Err(format!(
|
||||||
|
"{} trailing body bytes after {member_count} members",
|
||||||
|
body.len() - cur.pos
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(MembershipSnapshot {
|
||||||
|
version,
|
||||||
|
term,
|
||||||
|
members,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn sample() -> MembershipSnapshot {
|
||||||
|
MembershipSnapshot {
|
||||||
|
version: 7,
|
||||||
|
term: 3,
|
||||||
|
members: vec![
|
||||||
|
MemberEntry {
|
||||||
|
id: 0,
|
||||||
|
name: "us-east".into(),
|
||||||
|
grpc_addr: "tidaldb-0.peers.svc:9500".into(),
|
||||||
|
http_addr: "http://tidaldb-0.peers.svc:9501".into(),
|
||||||
|
role: MemberRole::Voter,
|
||||||
|
},
|
||||||
|
MemberEntry {
|
||||||
|
id: 1,
|
||||||
|
name: "eu-west".into(),
|
||||||
|
grpc_addr: "tidaldb-1.peers.svc:9500".into(),
|
||||||
|
http_addr: "http://tidaldb-1.peers.svc:9501".into(),
|
||||||
|
role: MemberRole::Learner,
|
||||||
|
},
|
||||||
|
MemberEntry {
|
||||||
|
id: 2,
|
||||||
|
name: "ap-south".into(),
|
||||||
|
grpc_addr: "10.0.0.3:9500".into(),
|
||||||
|
http_addr: "http://10.0.0.3:9501".into(),
|
||||||
|
role: MemberRole::Removed,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn roundtrip_and_absent() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = MembershipStore::new(dir.path());
|
||||||
|
|
||||||
|
// Absent → None (the pre-open loop falls back to seeds).
|
||||||
|
assert_eq!(store.load().unwrap(), None);
|
||||||
|
|
||||||
|
let snap = sample();
|
||||||
|
store.persist(&snap).unwrap();
|
||||||
|
assert_eq!(store.load().unwrap(), Some(snap.clone()));
|
||||||
|
|
||||||
|
// Overwrite with a newer version (move the clone — `snap` is unused
|
||||||
|
// after this point).
|
||||||
|
let mut newer = snap;
|
||||||
|
newer.version = 9;
|
||||||
|
newer.members[1].role = MemberRole::Voter;
|
||||||
|
store.persist(&newer).unwrap();
|
||||||
|
assert_eq!(store.load().unwrap(), Some(newer));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn corruption_refuses() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = MembershipStore::new(dir.path());
|
||||||
|
store.persist(&sample()).unwrap();
|
||||||
|
|
||||||
|
let path = dir.path().join("membership");
|
||||||
|
let mut bytes = std::fs::read(&path).unwrap();
|
||||||
|
// Flip a byte inside the body.
|
||||||
|
let mid = bytes.len() / 2;
|
||||||
|
bytes[mid] ^= 0xFF;
|
||||||
|
std::fs::write(&path, &bytes).unwrap();
|
||||||
|
let err = store.load().expect_err("corruption must refuse");
|
||||||
|
assert!(err.to_string().contains("corrupt"), "got: {err}");
|
||||||
|
|
||||||
|
// Truncation refuses too.
|
||||||
|
std::fs::write(&path, &bytes[0..bytes.len() / 3]).unwrap();
|
||||||
|
assert!(store.load().is_err());
|
||||||
|
|
||||||
|
// Bad magic refuses.
|
||||||
|
store.persist(&sample()).unwrap();
|
||||||
|
let mut bm = std::fs::read(&path).unwrap();
|
||||||
|
bm[0] ^= 0xFF;
|
||||||
|
std::fs::write(&path, &bm).unwrap();
|
||||||
|
assert!(store.load().is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tmp_file_never_shadows_the_real_cache() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = MembershipStore::new(dir.path());
|
||||||
|
let snap = sample();
|
||||||
|
store.persist(&snap).unwrap();
|
||||||
|
// A crash can orphan a `.tmp`; load reads only the real file.
|
||||||
|
std::fs::write(dir.path().join("membership.tmp"), b"garbage").unwrap();
|
||||||
|
assert_eq!(store.load().unwrap(), Some(snap));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_roster_refuses_to_persist() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = MembershipStore::new(dir.path());
|
||||||
|
let empty = MembershipSnapshot {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![],
|
||||||
|
};
|
||||||
|
assert!(store.persist(&empty).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicate_id_refuses_to_persist() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = MembershipStore::new(dir.path());
|
||||||
|
let dup = MembershipSnapshot {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![
|
||||||
|
MemberEntry {
|
||||||
|
id: 5,
|
||||||
|
name: "a".into(),
|
||||||
|
grpc_addr: "a:1".into(),
|
||||||
|
http_addr: "http://a:2".into(),
|
||||||
|
role: MemberRole::Voter,
|
||||||
|
},
|
||||||
|
MemberEntry {
|
||||||
|
id: 5,
|
||||||
|
name: "b".into(),
|
||||||
|
grpc_addr: "b:1".into(),
|
||||||
|
http_addr: "http://b:2".into(),
|
||||||
|
role: MemberRole::Voter,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
assert!(store.persist(&dup).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -11,10 +11,12 @@ pub mod election_store;
|
|||||||
pub mod idempotency;
|
pub mod idempotency;
|
||||||
pub mod in_process;
|
pub mod in_process;
|
||||||
pub mod lag;
|
pub mod lag;
|
||||||
|
pub mod membership_store;
|
||||||
pub mod migration;
|
pub mod migration;
|
||||||
pub mod receiver;
|
pub mod receiver;
|
||||||
pub mod reconcile;
|
pub mod reconcile;
|
||||||
pub mod relay;
|
pub mod relay;
|
||||||
|
pub mod reseed;
|
||||||
pub mod segment_id;
|
pub mod segment_id;
|
||||||
pub mod session_bridge;
|
pub mod session_bridge;
|
||||||
pub mod shard;
|
pub mod shard;
|
||||||
@ -35,6 +37,7 @@ pub use election_store::{BootState, ElectionStore, HardState};
|
|||||||
pub use idempotency::{IdempotencyKey, IdempotencyStore};
|
pub use idempotency::{IdempotencyKey, IdempotencyStore};
|
||||||
pub use in_process::{InProcessTransport, InProcessTransportFactory};
|
pub use in_process::{InProcessTransport, InProcessTransportFactory};
|
||||||
pub use lag::ReplicationLagGauge;
|
pub use lag::ReplicationLagGauge;
|
||||||
|
pub use membership_store::{MembershipSnapshot, MembershipStore};
|
||||||
pub use migration::{MigrationState, TenantMigration};
|
pub use migration::{MigrationState, TenantMigration};
|
||||||
pub use receiver::{
|
pub use receiver::{
|
||||||
SegmentReceiverHandle, apply_payload, apply_payload_with_leader_seq, spawn_receiver,
|
SegmentReceiverHandle, apply_payload, apply_payload_with_leader_seq, spawn_receiver,
|
||||||
@ -44,6 +47,7 @@ pub use relay::{
|
|||||||
RelayEvent, SignalRelay, StagedRelayWrite, encode_run, range_payload, redeliver_missed,
|
RelayEvent, SignalRelay, StagedRelayWrite, encode_run, range_payload, redeliver_missed,
|
||||||
single_event_payload,
|
single_event_payload,
|
||||||
};
|
};
|
||||||
|
pub use reseed::{RESEED_REQUIRED_MARKER, ReseedMarker, ReseedMarkerStore, ReseedReason};
|
||||||
pub use segment_id::WalSegmentId;
|
pub use segment_id::WalSegmentId;
|
||||||
pub use session_bridge::{
|
pub use session_bridge::{
|
||||||
InProcessSessionTransportFactory, SessionBridgeError, SessionPayload, SessionReplicationBridge,
|
InProcessSessionTransportFactory, SessionBridgeError, SessionPayload, SessionReplicationBridge,
|
||||||
|
|||||||
@ -621,6 +621,10 @@ fn prepare_segment(
|
|||||||
// applier journals it into THIS node's WAL (advancing its durable
|
// applier journals it into THIS node's WAL (advancing its durable
|
||||||
// tail term) and folds the term-mark cell instead of storage.
|
// tail term) and folds the term-mark cell instead of storage.
|
||||||
BatchPayload::TermMarker(record) => blobs.push(BlobRecord::TermMarker(record)),
|
BatchPayload::TermMarker(record) => blobs.push(BlobRecord::TermMarker(record)),
|
||||||
|
// m11p5: a replicated membership record rides the same blob path —
|
||||||
|
// journaled into THIS node's WAL, then folded into the roster cell
|
||||||
|
// (no storage effect).
|
||||||
|
BatchPayload::Membership(record) => blobs.push(BlobRecord::Membership(record)),
|
||||||
}
|
}
|
||||||
|
|
||||||
let batch_size = HEADER_SIZE + header.payload_len as usize;
|
let batch_size = HEADER_SIZE + header.payload_len as usize;
|
||||||
@ -1782,6 +1786,9 @@ mod tests {
|
|||||||
format!("emb:{}:{}", r.entity_id, r.values.len())
|
format!("emb:{}:{}", r.entity_id, r.values.len())
|
||||||
}
|
}
|
||||||
BlobRecord::TermMarker(r) => format!("term:{}", r.term),
|
BlobRecord::TermMarker(r) => format!("term:{}", r.term),
|
||||||
|
BlobRecord::Membership(r) => {
|
||||||
|
format!("membership:v{}:{}", r.version, r.members.len())
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
self.applied.lock().unwrap().extend(lines);
|
self.applied.lock().unwrap().extend(lines);
|
||||||
|
|||||||
390
tidal/src/replication/reseed.rs
Normal file
390
tidal/src/replication/reseed.rs
Normal file
@ -0,0 +1,390 @@
|
|||||||
|
//! The durable `reseed_required` marker (m11p5 §2.4): the boot-time reseed latch.
|
||||||
|
//!
|
||||||
|
//! A running follower that hits a typed `snapshot-required` catch-up refusal —
|
||||||
|
//! or the m11p4 divergence quarantine — durably latches a `reseed_required`
|
||||||
|
//! marker in its data dir and keeps serving degraded; the reseed executes on
|
||||||
|
//! the NEXT boot (never live surgery). The marker file lives at
|
||||||
|
//! `<data_dir>/reseed_required`.
|
||||||
|
//!
|
||||||
|
//! [`RESEED_REQUIRED_MARKER`] is the single source of truth for that filename.
|
||||||
|
//! It lives beside [`membership_store`](super::membership_store) (the other
|
||||||
|
//! node-local, snapshot-excluded data-dir resident) so that both the
|
||||||
|
//! **producer** of a snapshot artifact (the leader-side staging path, which must
|
||||||
|
//! EXCLUDE the marker from the copy — a joiner inheriting a stale
|
||||||
|
//! `reseed_required` marker would needlessly reseed on its first boot) and the
|
||||||
|
//! **install** path (which reads/writes the marker to drive the boot-time
|
||||||
|
//! reseed) name exactly one constant and can never drift.
|
||||||
|
//!
|
||||||
|
//! Snapshot staging excludes it for the same reason it excludes
|
||||||
|
//! `election_state`, `stream_baseline`, and `membership`: these are
|
||||||
|
//! node-identity / node-local files that must NOT travel inside a snapshot
|
||||||
|
//! served to another node.
|
||||||
|
//!
|
||||||
|
//! # Why a durable, checksummed marker (not a bare touch-file)
|
||||||
|
//!
|
||||||
|
//! The marker drives a boot-time *data-dir swap* — the most destructive
|
||||||
|
//! operation in the system. A half-written or bit-rotted marker must be
|
||||||
|
//! *detected*, never silently parsed into a wrong reason/seqno, so the file
|
||||||
|
//! carries the EXACT [`ElectionStore`](super::election_store::ElectionStore)
|
||||||
|
//! discipline: magic + version + BLAKE3 checksum framing, written `.tmp` →
|
||||||
|
//! [`sync_file_durable`] → atomic rename → [`sync_dir_durable`]. A corrupt
|
||||||
|
//! marker is a typed error the boot path surfaces loudly (it does NOT fall
|
||||||
|
//! through to a clean boot, which would strand a node that genuinely needs a
|
||||||
|
//! reseed). The body records WHY (so status/metrics can report the reason) and
|
||||||
|
//! the `from_seqno` recorded *at latch time* — a marker boot always requests
|
||||||
|
//! the snapshot from that seqno, never re-deriving a frontier from a half-open
|
||||||
|
//! engine (§2.7 design honesty: the stream already refused us at `from_seqno`,
|
||||||
|
//! so that is the only honest resume point).
|
||||||
|
//!
|
||||||
|
//! [`sync_file_durable`]: crate::wal::sync_file_durable
|
||||||
|
//! [`sync_dir_durable`]: crate::wal::sync_dir_durable
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
use crate::wal::error::WalError;
|
||||||
|
|
||||||
|
/// The reseed-marker filename, relative to the node's data dir.
|
||||||
|
///
|
||||||
|
/// Kept as a top-level entry (not nested) so the snapshot-staging copy can skip
|
||||||
|
/// it by a single top-level-name comparison, and so the boot-time install can
|
||||||
|
/// find it without walking the tree.
|
||||||
|
pub const RESEED_REQUIRED_MARKER: &str = "reseed_required";
|
||||||
|
|
||||||
|
/// File magic: "TRSD" (tidalDB reseed).
|
||||||
|
const MAGIC: [u8; 4] = *b"TRSD";
|
||||||
|
|
||||||
|
/// Format version 1.
|
||||||
|
const VERSION: u8 = 1;
|
||||||
|
|
||||||
|
/// On-disk size: magic 4 + version 1 + reason 1 + `from_seqno` u64 (8) +
|
||||||
|
/// checksum 16 (truncated BLAKE3 over bytes 0..14).
|
||||||
|
const FILE_SIZE: usize = 4 + 1 + 1 + 8 + 16;
|
||||||
|
|
||||||
|
/// Byte count the checksum covers (everything before the trailing 16 hash
|
||||||
|
/// bytes): magic 4 + version 1 + reason 1 + `from_seqno` 8.
|
||||||
|
const CHECKSUM_OVER: usize = 4 + 1 + 1 + 8;
|
||||||
|
|
||||||
|
/// Why a node latched the durable reseed marker (m11p5 §2.4).
|
||||||
|
///
|
||||||
|
/// The discriminant is the on-disk encoding — it is PERMANENT. The reason is
|
||||||
|
/// reported in status/metrics so an operator can tell an automatic
|
||||||
|
/// snapshot-required reseed from a divergence quarantine from an operator-
|
||||||
|
/// requested one.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(u8)]
|
||||||
|
pub enum ReseedReason {
|
||||||
|
/// A running follower hit a typed `snapshot-required` catch-up refusal: its
|
||||||
|
/// frontier is behind the leader's compacted WAL. The reseed runs next boot.
|
||||||
|
SnapshotRequired = 0,
|
||||||
|
/// The m11p4 divergence quarantine fenced this node (its WAL extends past
|
||||||
|
/// the elected term's baseline with pre-term data). A successful reseed boot
|
||||||
|
/// clears the quarantine latch.
|
||||||
|
Quarantine = 1,
|
||||||
|
/// An operator requested the reseed via `POST /cluster/reseed`.
|
||||||
|
Operator = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReseedReason {
|
||||||
|
/// The on-disk discriminant byte.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn to_byte(self) -> u8 {
|
||||||
|
self as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode a reason byte. An unknown discriminant is rejected (a forward-only
|
||||||
|
/// schema; a pre-decode error beats a silently-misread reason).
|
||||||
|
fn from_byte(b: u8) -> Result<Self, String> {
|
||||||
|
match b {
|
||||||
|
0 => Ok(Self::SnapshotRequired),
|
||||||
|
1 => Ok(Self::Quarantine),
|
||||||
|
2 => Ok(Self::Operator),
|
||||||
|
other => Err(format!("unknown reseed reason {other}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A short human label for logs/status.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::SnapshotRequired => "snapshot_required",
|
||||||
|
Self::Quarantine => "quarantine",
|
||||||
|
Self::Operator => "operator",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The durable reseed marker's body: WHY the node latched it and the seqno the
|
||||||
|
/// next boot must request the snapshot from.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct ReseedMarker {
|
||||||
|
/// Why this node latched the reseed.
|
||||||
|
pub reason: ReseedReason,
|
||||||
|
/// The seqno the next-boot snapshot fetch requests from. Recorded at latch
|
||||||
|
/// time — the stream already refused us at this frontier, so it is the only
|
||||||
|
/// honest resume point (a marker boot never re-derives it from a half-open
|
||||||
|
/// engine; §2.7).
|
||||||
|
pub from_seqno: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reader/writer for the durable reseed marker (`data_dir/reseed_required`).
|
||||||
|
///
|
||||||
|
/// Same file discipline as [`ElectionStore`](super::election_store::ElectionStore)
|
||||||
|
/// and [`MembershipStore`](super::membership_store::MembershipStore): magic +
|
||||||
|
/// version + BLAKE3 checksum, `.tmp` + fsync + rename + dir fsync.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ReseedMarkerStore {
|
||||||
|
path: PathBuf,
|
||||||
|
dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ReseedMarkerStore {
|
||||||
|
/// Bind to `data_dir/reseed_required`.
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(data_dir: &Path) -> Self {
|
||||||
|
Self {
|
||||||
|
path: data_dir.join(RESEED_REQUIRED_MARKER),
|
||||||
|
dir: data_dir.to_path_buf(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the marker file exists (a cheap pre-check before a full load —
|
||||||
|
/// the boot path skips the whole install flow when no marker is present).
|
||||||
|
#[must_use]
|
||||||
|
pub fn exists(&self) -> bool {
|
||||||
|
self.path.exists()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Load the marker. Absent → `Ok(None)`; present-but-corrupt → a typed
|
||||||
|
/// error (a half-written marker must be *detected*, never silently parsed
|
||||||
|
/// into a wrong reason/seqno and used to drive a destructive swap).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`WalError::Corruption`] when the file exists but cannot be read or fails
|
||||||
|
/// its magic/version/length/checksum validation.
|
||||||
|
pub fn load(&self) -> Result<Option<ReseedMarker>, WalError> {
|
||||||
|
let bytes = match std::fs::read(&self.path) {
|
||||||
|
Ok(b) => b,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||||
|
Err(e) => {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"reseed marker at {} exists but cannot be read ({e}); a node that \
|
||||||
|
cannot prove WHY it needs a reseed must not guess — repair or remove it",
|
||||||
|
self.path.display()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let marker = decode(&bytes).map_err(|why| WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"reseed marker at {} is corrupt ({why}); a corrupt marker must not silently \
|
||||||
|
drive a destructive data-dir swap — repair or remove it",
|
||||||
|
self.path.display()
|
||||||
|
),
|
||||||
|
})?;
|
||||||
|
Ok(Some(marker))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Durably persist `marker`: write `.tmp`, fsync, rename, fsync dir. The
|
||||||
|
/// latch is idempotent — re-latching simply rewrites the file (the caller
|
||||||
|
/// chooses whether to overwrite an existing reason; this method always
|
||||||
|
/// writes the value it is given).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`WalError::Io`] on any filesystem failure — the caller must treat the
|
||||||
|
/// latch as NOT having happened.
|
||||||
|
pub fn persist(&self, marker: ReseedMarker) -> Result<(), WalError> {
|
||||||
|
let bytes = encode(marker);
|
||||||
|
let tmp = self.path.with_extension("tmp");
|
||||||
|
{
|
||||||
|
use std::io::Write;
|
||||||
|
let mut f = std::fs::File::create(&tmp)?;
|
||||||
|
f.write_all(&bytes)?;
|
||||||
|
crate::wal::sync_file_durable(&f)?;
|
||||||
|
}
|
||||||
|
std::fs::rename(&tmp, &self.path)?;
|
||||||
|
crate::wal::sync_dir_durable(&self.dir)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the marker durably (delete + dir fsync). Absent → `Ok(())`
|
||||||
|
/// (idempotent: a successful reseed swap discards the OLD dir's marker, and
|
||||||
|
/// the `retry-the-normal-boot` path clears it explicitly).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// [`WalError::Io`] on a filesystem failure other than `NotFound`.
|
||||||
|
pub fn clear(&self) -> Result<(), WalError> {
|
||||||
|
match std::fs::remove_file(&self.path) {
|
||||||
|
Ok(()) => {
|
||||||
|
crate::wal::sync_dir_durable(&self.dir)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
|
||||||
|
Err(e) => Err(WalError::Io(e)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn encode(marker: ReseedMarker) -> [u8; FILE_SIZE] {
|
||||||
|
let mut buf = [0u8; FILE_SIZE];
|
||||||
|
buf[0..4].copy_from_slice(&MAGIC);
|
||||||
|
buf[4] = VERSION;
|
||||||
|
buf[5] = marker.reason.to_byte();
|
||||||
|
buf[6..14].copy_from_slice(&marker.from_seqno.to_le_bytes());
|
||||||
|
let hash = blake3::hash(&buf[0..CHECKSUM_OVER]);
|
||||||
|
buf[CHECKSUM_OVER..FILE_SIZE].copy_from_slice(&hash.as_bytes()[0..16]);
|
||||||
|
buf
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode(bytes: &[u8]) -> Result<ReseedMarker, String> {
|
||||||
|
if bytes.len() != FILE_SIZE {
|
||||||
|
return Err(format!("{} bytes, expected {FILE_SIZE}", bytes.len()));
|
||||||
|
}
|
||||||
|
if bytes[0..4] != MAGIC {
|
||||||
|
return Err("bad magic".into());
|
||||||
|
}
|
||||||
|
if bytes[4] != VERSION {
|
||||||
|
return Err(format!("unknown version {}", bytes[4]));
|
||||||
|
}
|
||||||
|
let hash = blake3::hash(&bytes[0..CHECKSUM_OVER]);
|
||||||
|
if bytes[CHECKSUM_OVER..FILE_SIZE] != hash.as_bytes()[0..16] {
|
||||||
|
return Err("checksum mismatch".into());
|
||||||
|
}
|
||||||
|
let reason = ReseedReason::from_byte(bytes[5])?;
|
||||||
|
let from_seqno = u64::from_le_bytes(
|
||||||
|
bytes[6..14]
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| "bad from_seqno bytes".to_string())?,
|
||||||
|
);
|
||||||
|
Ok(ReseedMarker { reason, from_seqno })
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[allow(clippy::unwrap_used)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn roundtrip_and_absent() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = ReseedMarkerStore::new(dir.path());
|
||||||
|
|
||||||
|
// Absent → None (the boot path skips the install flow).
|
||||||
|
assert_eq!(store.load().unwrap(), None);
|
||||||
|
assert!(!store.exists());
|
||||||
|
|
||||||
|
let marker = ReseedMarker {
|
||||||
|
reason: ReseedReason::SnapshotRequired,
|
||||||
|
from_seqno: 42,
|
||||||
|
};
|
||||||
|
store.persist(marker).unwrap();
|
||||||
|
assert!(store.exists());
|
||||||
|
assert_eq!(store.load().unwrap(), Some(marker));
|
||||||
|
|
||||||
|
// Re-latch with a different reason overwrites (idempotent latch).
|
||||||
|
let operator = ReseedMarker {
|
||||||
|
reason: ReseedReason::Operator,
|
||||||
|
from_seqno: 42,
|
||||||
|
};
|
||||||
|
store.persist(operator).unwrap();
|
||||||
|
assert_eq!(store.load().unwrap(), Some(operator));
|
||||||
|
|
||||||
|
// Clear removes it.
|
||||||
|
store.clear().unwrap();
|
||||||
|
assert_eq!(store.load().unwrap(), None);
|
||||||
|
// Clear is idempotent on an absent marker.
|
||||||
|
store.clear().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_reason_round_trips() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = ReseedMarkerStore::new(dir.path());
|
||||||
|
for reason in [
|
||||||
|
ReseedReason::SnapshotRequired,
|
||||||
|
ReseedReason::Quarantine,
|
||||||
|
ReseedReason::Operator,
|
||||||
|
] {
|
||||||
|
let marker = ReseedMarker {
|
||||||
|
reason,
|
||||||
|
from_seqno: 7,
|
||||||
|
};
|
||||||
|
store.persist(marker).unwrap();
|
||||||
|
assert_eq!(store.load().unwrap(), Some(marker));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn corruption_refuses() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = ReseedMarkerStore::new(dir.path());
|
||||||
|
store
|
||||||
|
.persist(ReseedMarker {
|
||||||
|
reason: ReseedReason::Quarantine,
|
||||||
|
from_seqno: 123,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let path = dir.path().join(RESEED_REQUIRED_MARKER);
|
||||||
|
// Flip a byte inside the from_seqno field.
|
||||||
|
let mut bytes = std::fs::read(&path).unwrap();
|
||||||
|
bytes[8] ^= 0xFF;
|
||||||
|
std::fs::write(&path, &bytes).unwrap();
|
||||||
|
let err = store.load().expect_err("corruption must refuse");
|
||||||
|
assert!(err.to_string().contains("corrupt"), "got: {err}");
|
||||||
|
|
||||||
|
// Truncation refuses.
|
||||||
|
std::fs::write(&path, &bytes[0..6]).unwrap();
|
||||||
|
assert!(store.load().is_err());
|
||||||
|
|
||||||
|
// Bad magic refuses.
|
||||||
|
store
|
||||||
|
.persist(ReseedMarker {
|
||||||
|
reason: ReseedReason::Operator,
|
||||||
|
from_seqno: 1,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let mut bm = std::fs::read(&path).unwrap();
|
||||||
|
bm[0] ^= 0xFF;
|
||||||
|
std::fs::write(&path, &bm).unwrap();
|
||||||
|
assert!(store.load().is_err());
|
||||||
|
|
||||||
|
// An unknown reason byte refuses (forward-only schema).
|
||||||
|
store
|
||||||
|
.persist(ReseedMarker {
|
||||||
|
reason: ReseedReason::Operator,
|
||||||
|
from_seqno: 1,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let mut br = std::fs::read(&path).unwrap();
|
||||||
|
br[5] = 9; // not in {0,1,2}
|
||||||
|
// Recompute a valid checksum so we exercise the reason-decode refusal,
|
||||||
|
// not the checksum refusal.
|
||||||
|
let h = blake3::hash(&br[0..CHECKSUM_OVER]);
|
||||||
|
br[CHECKSUM_OVER..FILE_SIZE].copy_from_slice(&h.as_bytes()[0..16]);
|
||||||
|
std::fs::write(&path, &br).unwrap();
|
||||||
|
let err = store.load().expect_err("unknown reason must refuse");
|
||||||
|
assert!(err.to_string().contains("corrupt"), "got: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tmp_file_never_shadows_the_real_marker() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = ReseedMarkerStore::new(dir.path());
|
||||||
|
let marker = ReseedMarker {
|
||||||
|
reason: ReseedReason::SnapshotRequired,
|
||||||
|
from_seqno: 99,
|
||||||
|
};
|
||||||
|
store.persist(marker).unwrap();
|
||||||
|
// A crash can orphan a `.tmp`; load reads only the real file.
|
||||||
|
std::fs::write(
|
||||||
|
dir.path().join(format!("{RESEED_REQUIRED_MARKER}.tmp")),
|
||||||
|
b"garbage",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(store.load().unwrap(), Some(marker));
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -59,7 +59,7 @@
|
|||||||
use std::{
|
use std::{
|
||||||
collections::BTreeMap,
|
collections::BTreeMap,
|
||||||
sync::{
|
sync::{
|
||||||
Arc, Condvar, Mutex, PoisonError, Weak,
|
Arc, Condvar, Mutex, PoisonError, RwLock, Weak,
|
||||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||||
},
|
},
|
||||||
thread::JoinHandle,
|
thread::JoinHandle,
|
||||||
@ -326,6 +326,13 @@ struct PeerShip {
|
|||||||
cv: Condvar,
|
cv: Condvar,
|
||||||
/// Lock-free mirror of `state.acked` for status reads.
|
/// Lock-free mirror of `state.acked` for status reads.
|
||||||
acked_atomic: AtomicU64,
|
acked_atomic: AtomicU64,
|
||||||
|
/// Per-peer retire latch (m11p5 §3.3 `remove_peer`): set when this peer is
|
||||||
|
/// removed from the roster. The whole-queue `shutdown` latch retires
|
||||||
|
/// EVERY peer; this one retires a SINGLE peer's senders while the queue
|
||||||
|
/// keeps shipping to the rest. `claim_and_collect` checks it on entry and
|
||||||
|
/// on every wake, so a parked sender exits promptly when its peer is
|
||||||
|
/// removed (no leaked thread).
|
||||||
|
retired: AtomicBool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The region every outbound batch names as its leader (m11p4). Lives in the
|
/// The region every outbound batch names as its leader (m11p4). Lives in the
|
||||||
@ -351,7 +358,21 @@ impl PeerShip {
|
|||||||
struct ShipShared {
|
struct ShipShared {
|
||||||
source: Arc<dyn ShipSource>,
|
source: Arc<dyn ShipSource>,
|
||||||
transport: Arc<dyn Transport>,
|
transport: Arc<dyn Transport>,
|
||||||
peers: Vec<Arc<PeerShip>>,
|
/// The per-peer dispatch cells. `RwLock` because the peer SET is now
|
||||||
|
/// mutable at runtime (m11p5 §3.3 `add_peer`/`remove_peer`), but the hot
|
||||||
|
/// ship path is read-mostly: a sender takes a brief READ guard to clone
|
||||||
|
/// its own cell `Arc` and immediately releases it, then operates on that
|
||||||
|
/// clone for the whole claim→ship→record cycle WITHOUT holding the set
|
||||||
|
/// lock. Only `add_peer`/`remove_peer` take the WRITE guard, and only to
|
||||||
|
/// splice the Vec — never across a ship RPC or an fsync.
|
||||||
|
///
|
||||||
|
/// Lock ordering (m11p1 staged-write contract): this set lock is
|
||||||
|
/// OUTERMOST among the queue's locks and is never held while taking a
|
||||||
|
/// per-`PeerShip` `state` mutex or the `CommitIndex` lock. A sender
|
||||||
|
/// releases the set read guard before locking its cell's state, so the
|
||||||
|
/// staged-write hot path never contends on the set lock for the duration
|
||||||
|
/// of a send.
|
||||||
|
peers: RwLock<Vec<Arc<PeerShip>>>,
|
||||||
config: ShipQueueConfig,
|
config: ShipQueueConfig,
|
||||||
shutdown: AtomicBool,
|
shutdown: AtomicBool,
|
||||||
/// Leadership gate: only an active queue dispatches (see module docs).
|
/// Leadership gate: only an active queue dispatches (see module docs).
|
||||||
@ -368,17 +389,70 @@ struct ShipShared {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ShipShared {
|
impl ShipShared {
|
||||||
fn peer(&self, peer: ShardId) -> Option<&Arc<PeerShip>> {
|
fn peers_read(&self) -> std::sync::RwLockReadGuard<'_, Vec<Arc<PeerShip>>> {
|
||||||
self.peers.iter().find(|p| p.peer == peer)
|
self.peers.read().unwrap_or_else(PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clone the cell for `peer`, if it is still in the set. The returned
|
||||||
|
/// `Arc` outlives the read guard so callers never operate under it.
|
||||||
|
fn peer(&self, peer: ShardId) -> Option<Arc<PeerShip>> {
|
||||||
|
self.peers_read()
|
||||||
|
.iter()
|
||||||
|
.find(|p| p.peer == peer)
|
||||||
|
.map(Arc::clone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Snapshot the current cells (clones the `Arc`s, releases the guard).
|
||||||
|
fn peer_cells(&self) -> Vec<Arc<PeerShip>> {
|
||||||
|
self.peers_read().iter().map(Arc::clone).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn wake_all(&self) {
|
fn wake_all(&self) {
|
||||||
for cell in &self.peers {
|
for cell in self.peers_read().iter() {
|
||||||
cell.cv.notify_all();
|
cell.cv.notify_all();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Build one peer's dispatch cell at the given cursor / acked frontier.
|
||||||
|
/// Shared by [`ShipQueue::spawn`] (boot) and [`ShipQueue::add_peer`] (runtime
|
||||||
|
/// conf-change) so a newly added peer is constructed byte-for-byte like a
|
||||||
|
/// boot peer.
|
||||||
|
fn new_peer_cell(peer: ShardId, dispatch_next: u64, acked: u64) -> Arc<PeerShip> {
|
||||||
|
Arc::new(PeerShip {
|
||||||
|
peer,
|
||||||
|
state: Mutex::new(PeerState {
|
||||||
|
dispatch_next,
|
||||||
|
acked,
|
||||||
|
completed: BTreeMap::new(),
|
||||||
|
retry: BTreeMap::new(),
|
||||||
|
paused: false,
|
||||||
|
consecutive_failures: 0,
|
||||||
|
}),
|
||||||
|
cv: Condvar::new(),
|
||||||
|
acked_atomic: AtomicU64::new(acked),
|
||||||
|
retired: AtomicBool::new(false),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawn `window` sender threads for one peer cell, returning their handles.
|
||||||
|
/// Identical construction for boot and runtime add: each thread owns its own
|
||||||
|
/// `Arc<ShipShared>` and `Arc<PeerShip>` clone and runs [`sender_loop`].
|
||||||
|
fn spawn_peer_threads(shared: &Arc<ShipShared>, cell: &Arc<PeerShip>) -> Vec<JoinHandle<()>> {
|
||||||
|
let window = shared.config.window.max(1);
|
||||||
|
let mut handles = Vec::with_capacity(window);
|
||||||
|
for i in 0..window {
|
||||||
|
let shared = Arc::clone(shared);
|
||||||
|
let cell = Arc::clone(cell);
|
||||||
|
let handle = std::thread::Builder::new()
|
||||||
|
.name(format!("tidal-ship-{}-{i}", cell.peer.0))
|
||||||
|
.spawn(move || sender_loop(&shared, &cell))
|
||||||
|
.expect("spawn ship sender thread");
|
||||||
|
handles.push(handle);
|
||||||
|
}
|
||||||
|
handles
|
||||||
|
}
|
||||||
|
|
||||||
/// Per-peer windowed batch senders draining a [`ShipSource`]'s durable log.
|
/// Per-peer windowed batch senders draining a [`ShipSource`]'s durable log.
|
||||||
///
|
///
|
||||||
/// Spawn once per node ([`ShipQueue::spawn`]); the source's flush notify (or
|
/// Spawn once per node ([`ShipQueue::spawn`]); the source's flush notify (or
|
||||||
@ -386,7 +460,12 @@ impl ShipShared {
|
|||||||
/// on [`shutdown`](Self::shutdown) (also called on `Drop`).
|
/// on [`shutdown`](Self::shutdown) (also called on `Drop`).
|
||||||
pub struct ShipQueue {
|
pub struct ShipQueue {
|
||||||
shared: Arc<ShipShared>,
|
shared: Arc<ShipShared>,
|
||||||
threads: Vec<JoinHandle<()>>,
|
/// Sender threads keyed by peer, so [`remove_peer`](Self::remove_peer) can
|
||||||
|
/// join exactly one peer's threads (and [`add_peer`](Self::add_peer) can
|
||||||
|
/// register a new peer's) without disturbing the rest. Behind a `Mutex`
|
||||||
|
/// because the runtime conf-change verbs mutate it; the boot spawn and the
|
||||||
|
/// shutdown drain are the only other touches.
|
||||||
|
threads: Mutex<std::collections::HashMap<ShardId, Vec<JoinHandle<()>>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ShipQueue {
|
impl ShipQueue {
|
||||||
@ -416,21 +495,7 @@ impl ShipQueue {
|
|||||||
let peer_cells: Vec<Arc<PeerShip>> = peers
|
let peer_cells: Vec<Arc<PeerShip>> = peers
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|&&p| p != source.source_shard())
|
.filter(|&&p| p != source.source_shard())
|
||||||
.map(|&peer| {
|
.map(|&peer| new_peer_cell(peer, start_next, 0))
|
||||||
Arc::new(PeerShip {
|
|
||||||
peer,
|
|
||||||
state: Mutex::new(PeerState {
|
|
||||||
dispatch_next: start_next,
|
|
||||||
acked: 0,
|
|
||||||
completed: BTreeMap::new(),
|
|
||||||
retry: BTreeMap::new(),
|
|
||||||
paused: false,
|
|
||||||
consecutive_failures: 0,
|
|
||||||
}),
|
|
||||||
cv: Condvar::new(),
|
|
||||||
acked_atomic: AtomicU64::new(0),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let commit = Arc::new(CommitIndex::new(
|
let commit = Arc::new(CommitIndex::new(
|
||||||
@ -441,7 +506,7 @@ impl ShipQueue {
|
|||||||
let shared = Arc::new(ShipShared {
|
let shared = Arc::new(ShipShared {
|
||||||
source,
|
source,
|
||||||
transport,
|
transport,
|
||||||
peers: peer_cells,
|
peers: RwLock::new(peer_cells),
|
||||||
config,
|
config,
|
||||||
shutdown: AtomicBool::new(false),
|
shutdown: AtomicBool::new(false),
|
||||||
active: AtomicBool::new(active),
|
active: AtomicBool::new(active),
|
||||||
@ -466,21 +531,17 @@ impl ShipQueue {
|
|||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
let window = config.window.max(1);
|
let mut threads: std::collections::HashMap<ShardId, Vec<JoinHandle<()>>> =
|
||||||
let mut threads = Vec::with_capacity(shared.peers.len() * window);
|
std::collections::HashMap::new();
|
||||||
for cell in &shared.peers {
|
for cell in &shared.peer_cells() {
|
||||||
for i in 0..window {
|
let handles = spawn_peer_threads(&shared, cell);
|
||||||
let shared = Arc::clone(&shared);
|
threads.insert(cell.peer, handles);
|
||||||
let cell = Arc::clone(cell);
|
|
||||||
let handle = std::thread::Builder::new()
|
|
||||||
.name(format!("tidal-ship-{}-{i}", cell.peer.0))
|
|
||||||
.spawn(move || sender_loop(&shared, &cell))
|
|
||||||
.expect("spawn ship sender thread");
|
|
||||||
threads.push(handle);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Self { shared, threads }
|
Self {
|
||||||
|
shared,
|
||||||
|
threads: Mutex::new(threads),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wake parked senders: new entries are durable and shippable.
|
/// Wake parked senders: new entries are durable and shippable.
|
||||||
@ -512,7 +573,7 @@ impl ShipQueue {
|
|||||||
/// peers. `term` is the leadership term every outbound batch is stamped
|
/// peers. `term` is the leadership term every outbound batch is stamped
|
||||||
/// with and the commit index is scoped to (m11p4; 0 = the topology era).
|
/// with and the commit index is scoped to (m11p4; 0 = the topology era).
|
||||||
pub fn activate_from(&self, baseline: u64, term: u64) {
|
pub fn activate_from(&self, baseline: u64, term: u64) {
|
||||||
for cell in &self.shared.peers {
|
for cell in &self.shared.peer_cells() {
|
||||||
{
|
{
|
||||||
let mut state = cell.lock();
|
let mut state = cell.lock();
|
||||||
state.dispatch_next = baseline + 1;
|
state.dispatch_next = baseline + 1;
|
||||||
@ -535,7 +596,7 @@ impl ShipQueue {
|
|||||||
pub fn deactivate(&self) {
|
pub fn deactivate(&self) {
|
||||||
self.shared.active.store(false, Ordering::Release);
|
self.shared.active.store(false, Ordering::Release);
|
||||||
self.shared.commit.deactivate();
|
self.shared.commit.deactivate();
|
||||||
for cell in &self.shared.peers {
|
for cell in &self.shared.peer_cells() {
|
||||||
cell.lock().retry.clear();
|
cell.lock().retry.clear();
|
||||||
cell.cv.notify_all();
|
cell.cv.notify_all();
|
||||||
}
|
}
|
||||||
@ -594,6 +655,129 @@ impl ShipQueue {
|
|||||||
.map_or(0, |c| c.acked_atomic.load(Ordering::Acquire))
|
.map_or(0, |c| c.acked_atomic.load(Ordering::Acquire))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The current peer set (the shards this queue ships to), sorted.
|
||||||
|
#[must_use]
|
||||||
|
pub fn peers(&self) -> Vec<ShardId> {
|
||||||
|
let mut peers: Vec<ShardId> = self.shared.peers_read().iter().map(|c| c.peer).collect();
|
||||||
|
peers.sort_unstable_by_key(|p| p.0);
|
||||||
|
peers
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a peer to the roster at runtime (m11p5 §3.3 conf-change): construct
|
||||||
|
/// its dispatch cell and spawn its windowed senders, inheriting the queue's
|
||||||
|
/// CURRENT activation state. Idempotent (a re-add of an existing peer is a
|
||||||
|
/// no-op) and a no-op for the source's own shard.
|
||||||
|
///
|
||||||
|
/// Activation inheritance: if the queue is ACTIVE at term `T`, the new
|
||||||
|
/// peer starts from the durable frontier EXACTLY as
|
||||||
|
/// [`activate_from`](Self::activate_from) does — `dispatch_next =
|
||||||
|
/// flushed_seq + 1`, `acked = flushed_seq` — so a freshly added voter/learner
|
||||||
|
/// begins from the leader's current durable frontier and lets the catch-up
|
||||||
|
/// pull cover any pre-frontier history (never a full-log re-ship). An
|
||||||
|
/// INACTIVE queue (follower) adds the cell parked at the same cursor; it
|
||||||
|
/// dispatches nothing until the queue activates.
|
||||||
|
///
|
||||||
|
/// The COMMIT INDEX is reconfigured separately by the caller (one fenced
|
||||||
|
/// apply path, §3.3) — `add_peer` owns only the ship cells and threads, so
|
||||||
|
/// the role (voter vs learner) is the commit index's concern, not the
|
||||||
|
/// queue's.
|
||||||
|
///
|
||||||
|
/// Lock discipline: the write guard on the peer set is held ONLY to splice
|
||||||
|
/// the Vec — the cell is constructed and the threads are spawned outside
|
||||||
|
/// it, so the hot ship path's read guards are never blocked across an
|
||||||
|
/// allocation or a thread spawn.
|
||||||
|
pub fn add_peer(&self, peer: ShardId) {
|
||||||
|
if peer == self.shared.source.source_shard() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Build the cell at the current durable frontier (active inheritance).
|
||||||
|
let frontier = self.shared.source.flushed_seq();
|
||||||
|
let cell = if self.shared.active.load(Ordering::Acquire) {
|
||||||
|
// Mirror activate_from: dispatch one past the frontier, acked at it.
|
||||||
|
new_peer_cell(peer, frontier + 1, frontier)
|
||||||
|
} else {
|
||||||
|
// Inactive: park at the same start the boot spawn uses.
|
||||||
|
new_peer_cell(peer, frontier + 1, 0)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Splice into the set under the write guard (idempotent on duplicates).
|
||||||
|
{
|
||||||
|
let mut set = self
|
||||||
|
.shared
|
||||||
|
.peers
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner);
|
||||||
|
if set.iter().any(|c| c.peer == peer) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
set.push(Arc::clone(&cell));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Spawn outside the set lock; register the handles per-peer.
|
||||||
|
let handles = spawn_peer_threads(&self.shared, &cell);
|
||||||
|
self.threads
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner)
|
||||||
|
.insert(peer, handles);
|
||||||
|
// Wake it so it begins draining immediately if active.
|
||||||
|
cell.cv.notify_all();
|
||||||
|
tracing::info!(
|
||||||
|
peer = peer.0,
|
||||||
|
frontier,
|
||||||
|
active = self.shared.active.load(Ordering::Acquire),
|
||||||
|
"ship queue: peer added (conf-change)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a peer from the roster at runtime (m11p5 §3.3 conf-change):
|
||||||
|
/// retire its cell, wake + JOIN its senders, then drop it. Returns whether
|
||||||
|
/// a peer was actually removed (false = not in the set / already removed).
|
||||||
|
///
|
||||||
|
/// The caller is responsible for the §3.3 delivery rule (retire only after
|
||||||
|
/// the `Removed` record is quorum-committed AND delivered) — `remove_peer`
|
||||||
|
/// is the mechanical retire+join. The COMMIT INDEX is reconfigured
|
||||||
|
/// separately so the removed peer's mark stops counting toward quorum.
|
||||||
|
///
|
||||||
|
/// Join discipline: the retire latch is set, the cell woken, and its
|
||||||
|
/// threads JOINED before the cell is dropped — no leaked thread, no cell
|
||||||
|
/// freed out from under a running sender (the join proves they exited).
|
||||||
|
pub fn remove_peer(&self, peer: ShardId) -> bool {
|
||||||
|
// Pull the cell out of the set under the write guard.
|
||||||
|
let removed = {
|
||||||
|
let mut set = self
|
||||||
|
.shared
|
||||||
|
.peers
|
||||||
|
.write()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner);
|
||||||
|
set.iter()
|
||||||
|
.position(|c| c.peer == peer)
|
||||||
|
.map(|pos| set.remove(pos))
|
||||||
|
};
|
||||||
|
let Some(cell) = removed else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
// Retire + wake so its parked senders observe the latch and exit.
|
||||||
|
cell.retired.store(true, Ordering::Release);
|
||||||
|
cell.cv.notify_all();
|
||||||
|
// Take the peer's thread handles out from under the lock BEFORE
|
||||||
|
// joining, so the threads mutex is not held across the (blocking) join.
|
||||||
|
let handles = self
|
||||||
|
.threads
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner)
|
||||||
|
.remove(&peer);
|
||||||
|
if let Some(handles) = handles {
|
||||||
|
for handle in handles {
|
||||||
|
if handle.join().is_err() {
|
||||||
|
tracing::error!(peer = peer.0, "ship sender thread panicked during remove");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// `cell` drops here, after every sender has exited.
|
||||||
|
tracing::info!(peer = peer.0, "ship queue: peer removed (conf-change)");
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
/// Signal every sender to exit and join them. Idempotent.
|
/// Signal every sender to exit and join them. Idempotent.
|
||||||
pub fn shutdown(&mut self) {
|
pub fn shutdown(&mut self) {
|
||||||
self.shared.shutdown.store(true, Ordering::Release);
|
self.shared.shutdown.store(true, Ordering::Release);
|
||||||
@ -601,13 +785,21 @@ impl ShipQueue {
|
|||||||
// that will never ack again.
|
// that will never ack again.
|
||||||
self.shared.commit.deactivate();
|
self.shared.commit.deactivate();
|
||||||
self.shared.wake_all();
|
self.shared.wake_all();
|
||||||
for handle in self.threads.drain(..) {
|
let drained: Vec<(ShardId, Vec<JoinHandle<()>>)> = self
|
||||||
|
.threads
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner)
|
||||||
|
.drain()
|
||||||
|
.collect();
|
||||||
|
for (_peer, handles) in drained {
|
||||||
|
for handle in handles {
|
||||||
if handle.join().is_err() {
|
if handle.join().is_err() {
|
||||||
tracing::error!("ship sender thread panicked during shutdown");
|
tracing::error!("ship sender thread panicked during shutdown");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Drop for ShipQueue {
|
impl Drop for ShipQueue {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
@ -639,7 +831,10 @@ fn claim_and_collect(shared: &ShipShared, cell: &PeerShip) -> Option<ClaimedRun>
|
|||||||
let max_bytes = shared.config.max_batch_bytes.max(1);
|
let max_bytes = shared.config.max_batch_bytes.max(1);
|
||||||
let mut state = cell.lock();
|
let mut state = cell.lock();
|
||||||
loop {
|
loop {
|
||||||
if shared.shutdown.load(Ordering::Acquire) {
|
// The whole-queue shutdown OR this single peer's retire latch
|
||||||
|
// (m11p5 `remove_peer`) ends the loop — a removed peer's senders must
|
||||||
|
// exit so `remove_peer` can join them without leaking a thread.
|
||||||
|
if shared.shutdown.load(Ordering::Acquire) || cell.retired.load(Ordering::Acquire) {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1380,4 +1575,224 @@ mod tests {
|
|||||||
// Idempotent.
|
// Idempotent.
|
||||||
queue.shutdown();
|
queue.shutdown();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── m11p5 §3.3: runtime add_peer / remove_peer ───────────────────────────
|
||||||
|
|
||||||
|
/// A transport that records shipped ranges PER PEER so a runtime-added
|
||||||
|
/// peer's backlog ship is observable. Every send succeeds; the per-peer
|
||||||
|
/// applied frontier mirrors the contiguous last-shipped seq.
|
||||||
|
struct PerPeerTransport {
|
||||||
|
local: ShardId,
|
||||||
|
/// peer → gap-aware model receiver (mirrors `apply_range`).
|
||||||
|
receivers: StdMutex<std::collections::HashMap<ShardId, ModelReceiver>>,
|
||||||
|
/// peer → count of sends observed.
|
||||||
|
sends: StdMutex<std::collections::HashMap<ShardId, u64>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PerPeerTransport {
|
||||||
|
fn new() -> Arc<Self> {
|
||||||
|
Arc::new(Self {
|
||||||
|
local: ShardId(0),
|
||||||
|
receivers: StdMutex::new(std::collections::HashMap::new()),
|
||||||
|
sends: StdMutex::new(std::collections::HashMap::new()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fn applied_for(&self, peer: ShardId) -> u64 {
|
||||||
|
self.receivers
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.get(&peer)
|
||||||
|
.map_or(0, |r| r.applied)
|
||||||
|
}
|
||||||
|
fn sends_for(&self, peer: ShardId) -> u64 {
|
||||||
|
self.sends.lock().unwrap().get(&peer).copied().unwrap_or(0)
|
||||||
|
}
|
||||||
|
/// Seed a peer's applied frontier (simulates the catch-up pull having
|
||||||
|
/// already delivered history up to `applied` before the live ship).
|
||||||
|
fn seed_applied(&self, peer: ShardId, applied: u64) {
|
||||||
|
self.receivers
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.entry(peer)
|
||||||
|
.or_default()
|
||||||
|
.applied = applied;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Transport for PerPeerTransport {
|
||||||
|
fn send_segment(
|
||||||
|
&self,
|
||||||
|
to: ShardId,
|
||||||
|
payload: WalSegmentPayload,
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
self.receivers
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.entry(to)
|
||||||
|
.or_default()
|
||||||
|
.apply_range(payload.id.seqno, payload.leader_last_seq);
|
||||||
|
*self.sends.lock().unwrap().entry(to).or_insert(0) += 1;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn recv_segment(&self) -> Option<WalSegmentPayload> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
fn peer_applied_hint(&self, peer: ShardId) -> u64 {
|
||||||
|
self.applied_for(peer)
|
||||||
|
}
|
||||||
|
fn request_catchup(&self, _from_shard: ShardId, _from_seqno: u64) {}
|
||||||
|
fn local_shard(&self) -> ShardId {
|
||||||
|
self.local
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `add_peer` mid-activation ships the existing backlog to the NEW peer:
|
||||||
|
/// it inherits the active state and begins from the durable frontier, so
|
||||||
|
/// everything the leader has flushed past the activation baseline reaches
|
||||||
|
/// it (older history is the new peer's catch-up pull, not a re-ship).
|
||||||
|
#[test]
|
||||||
|
fn add_peer_mid_activation_ships_backlog_to_new_peer() {
|
||||||
|
let relay = Arc::new(SignalRelay::new(ShardId(0)));
|
||||||
|
let db = leader_db();
|
||||||
|
let transport = PerPeerTransport::new();
|
||||||
|
// Boot with just peer 1, active from baseline 0.
|
||||||
|
let queue = ShipQueue::spawn(
|
||||||
|
Arc::clone(&relay) as Arc<dyn ShipSource>,
|
||||||
|
Arc::clone(&transport) as Arc<dyn Transport>,
|
||||||
|
&[ShardId(1)],
|
||||||
|
ShipQueueConfig {
|
||||||
|
max_batch_events: 16,
|
||||||
|
max_batch_bytes: 1 << 20,
|
||||||
|
window: 1,
|
||||||
|
retry_backoff: Duration::from_millis(10),
|
||||||
|
leader_region: 0,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
#[cfg(feature = "metrics")]
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Build a backlog: peer 1 converges to 30.
|
||||||
|
write_n(&relay, &db, 30);
|
||||||
|
queue.publish();
|
||||||
|
assert!(
|
||||||
|
wait_for(5_000, || transport.applied_for(ShardId(1)) == 30),
|
||||||
|
"the original peer must converge, got {}",
|
||||||
|
transport.applied_for(ShardId(1))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add peer 2 at runtime. It inherits the ACTIVE state and starts from
|
||||||
|
// the current durable frontier (30): new writes ship to it; older
|
||||||
|
// history (1..=30) is its catch-up pull, which we model here by seeding
|
||||||
|
// its applied frontier to the inherited baseline so the live ship of
|
||||||
|
// 31..=50 lands contiguously rather than as a parked gap.
|
||||||
|
transport.seed_applied(ShardId(2), 30);
|
||||||
|
queue.add_peer(ShardId(2));
|
||||||
|
assert_eq!(queue.peers(), vec![ShardId(1), ShardId(2)]);
|
||||||
|
write_n(&relay, &db, 20); // seqnos 31..=50
|
||||||
|
queue.publish();
|
||||||
|
assert!(
|
||||||
|
wait_for(5_000, || transport.applied_for(ShardId(2)) == 50),
|
||||||
|
"the newly added peer must ship the post-add backlog, got {}",
|
||||||
|
transport.applied_for(ShardId(2))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
transport.sends_for(ShardId(2)) > 0,
|
||||||
|
"the new peer must have received at least one ship"
|
||||||
|
);
|
||||||
|
// The original peer keeps shipping uninterrupted.
|
||||||
|
assert!(wait_for(5_000, || transport.applied_for(ShardId(1)) == 50));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `add_peer` on an INACTIVE queue parks the new peer (no dispatch) until
|
||||||
|
/// activation, then ships from the baseline — mirroring a boot peer.
|
||||||
|
#[test]
|
||||||
|
fn add_peer_on_inactive_queue_holds_until_activation() {
|
||||||
|
let relay = Arc::new(SignalRelay::new(ShardId(0)));
|
||||||
|
let db = leader_db();
|
||||||
|
let transport = PerPeerTransport::new();
|
||||||
|
let queue = ShipQueue::spawn(
|
||||||
|
Arc::clone(&relay) as Arc<dyn ShipSource>,
|
||||||
|
Arc::clone(&transport) as Arc<dyn Transport>,
|
||||||
|
&[ShardId(1)],
|
||||||
|
ShipQueueConfig {
|
||||||
|
max_batch_events: 16,
|
||||||
|
max_batch_bytes: 1 << 20,
|
||||||
|
window: 1,
|
||||||
|
retry_backoff: Duration::from_millis(10),
|
||||||
|
leader_region: 0,
|
||||||
|
},
|
||||||
|
false, // follower
|
||||||
|
#[cfg(feature = "metrics")]
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
queue.add_peer(ShardId(2));
|
||||||
|
|
||||||
|
write_n(&relay, &db, 10);
|
||||||
|
queue.publish();
|
||||||
|
std::thread::sleep(Duration::from_millis(50));
|
||||||
|
assert_eq!(
|
||||||
|
transport.applied_for(ShardId(2)),
|
||||||
|
0,
|
||||||
|
"an inactive queue must not dispatch to an added peer"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Activate from baseline 10: only post-baseline writes ship. The
|
||||||
|
// pre-baseline history (1..=10) is the follower's catch-up pull, modeled
|
||||||
|
// by seeding its applied frontier to the baseline.
|
||||||
|
transport.seed_applied(ShardId(2), 10);
|
||||||
|
queue.activate_from(10, 1);
|
||||||
|
write_n(&relay, &db, 5); // 11..=15
|
||||||
|
queue.publish();
|
||||||
|
assert!(
|
||||||
|
wait_for(5_000, || transport.applied_for(ShardId(2)) == 15),
|
||||||
|
"post-activation the added peer ships post-baseline writes, got {}",
|
||||||
|
transport.applied_for(ShardId(2))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `remove_peer` retires the cell, joins its threads (no leak), and drops
|
||||||
|
/// it from the set. A second remove is a no-op. The remaining peer keeps
|
||||||
|
/// shipping.
|
||||||
|
#[test]
|
||||||
|
fn remove_peer_joins_threads_and_keeps_the_rest_shipping() {
|
||||||
|
let relay = Arc::new(SignalRelay::new(ShardId(0)));
|
||||||
|
let db = leader_db();
|
||||||
|
let transport = PerPeerTransport::new();
|
||||||
|
let queue = ShipQueue::spawn(
|
||||||
|
Arc::clone(&relay) as Arc<dyn ShipSource>,
|
||||||
|
Arc::clone(&transport) as Arc<dyn Transport>,
|
||||||
|
&[ShardId(1), ShardId(2)],
|
||||||
|
ShipQueueConfig {
|
||||||
|
max_batch_events: 16,
|
||||||
|
max_batch_bytes: 1 << 20,
|
||||||
|
window: 2, // multiple threads per peer to prove the join
|
||||||
|
retry_backoff: Duration::from_millis(10),
|
||||||
|
leader_region: 0,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
#[cfg(feature = "metrics")]
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
|
||||||
|
write_n(&relay, &db, 10);
|
||||||
|
queue.publish();
|
||||||
|
assert!(wait_for(5_000, || transport.applied_for(ShardId(2)) == 10));
|
||||||
|
|
||||||
|
// Remove peer 2: the call JOINS its threads — if any leaked or hung,
|
||||||
|
// this would block forever (the test would time out, a hard failure).
|
||||||
|
assert!(queue.remove_peer(ShardId(2)), "peer 2 was present");
|
||||||
|
assert_eq!(queue.peers(), vec![ShardId(1)]);
|
||||||
|
// Idempotent: a second remove finds nothing.
|
||||||
|
assert!(!queue.remove_peer(ShardId(2)));
|
||||||
|
|
||||||
|
// The remaining peer 1 keeps shipping new writes.
|
||||||
|
write_n(&relay, &db, 5); // 11..=15
|
||||||
|
queue.publish();
|
||||||
|
assert!(
|
||||||
|
wait_for(5_000, || transport.applied_for(ShardId(1)) == 15),
|
||||||
|
"the surviving peer must keep shipping after a remove, got {}",
|
||||||
|
transport.applied_for(ShardId(1))
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -473,7 +473,8 @@ pub fn filter_segment_drop_local(bytes: &[u8]) -> Vec<u8> {
|
|||||||
crate::wal::format::BatchPayload::Signals(events) => events,
|
crate::wal::format::BatchPayload::Signals(events) => events,
|
||||||
crate::wal::format::BatchPayload::ItemMetadata(_)
|
crate::wal::format::BatchPayload::ItemMetadata(_)
|
||||||
| crate::wal::format::BatchPayload::Embedding(_)
|
| crate::wal::format::BatchPayload::Embedding(_)
|
||||||
| crate::wal::format::BatchPayload::TermMarker(_) => {
|
| crate::wal::format::BatchPayload::TermMarker(_)
|
||||||
|
| crate::wal::format::BatchPayload::Membership(_) => {
|
||||||
out.extend_from_slice(&remaining[..batch_size]);
|
out.extend_from_slice(&remaining[..batch_size]);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -91,14 +91,78 @@ pub fn compact_wal(wal_dir: &Path, checkpoint_seq: u64) -> Result<CompactionResu
|
|||||||
pub fn compact_wal_online(
|
pub fn compact_wal_online(
|
||||||
wal_dir: &Path,
|
wal_dir: &Path,
|
||||||
checkpoint_seq: u64,
|
checkpoint_seq: u64,
|
||||||
|
) -> Result<CompactionResult, WalError> {
|
||||||
|
compact_wal_online_pinned(wal_dir, checkpoint_seq, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Online-safe compaction with a **retention pin** (m11p5 §2.1).
|
||||||
|
///
|
||||||
|
/// Identical to [`compact_wal_online`] — the live (max-`first_seq`) segment is
|
||||||
|
/// always preserved — but additionally honors a retention `pin`. When `pin > 0`,
|
||||||
|
/// a snapshot artifact has been captured at seq `pin` and a joiner will resume
|
||||||
|
/// the WAL stream from `pin + 1`; compaction must therefore PRESERVE the segment
|
||||||
|
/// chain covering `pin + 1` onward so the artifact's tail stays servable. `pin
|
||||||
|
/// == 0` is the unpinned sentinel and recovers [`compact_wal_online`]'s behavior
|
||||||
|
/// byte-for-byte.
|
||||||
|
///
|
||||||
|
/// # The straddling-segment hazard (the off-by-one that is data loss)
|
||||||
|
///
|
||||||
|
/// [`compact_segments`] deletes every segment whose `first_seq < floor`. That
|
||||||
|
/// comparison keys on a segment's *start*, so a segment whose range STRADDLES
|
||||||
|
/// the floor (`first_seq < floor <= last_seq`) is treated as fully-below and
|
||||||
|
/// **deleted** — taking the events at-or-above `floor` that live inside it with
|
||||||
|
/// it. Passing `floor = pin + 1` directly would therefore delete the very
|
||||||
|
/// segment that contains `pin + 1` (and thus the start of the resume range): a
|
||||||
|
/// hole in the artifact, surfaced to the joiner as a `FAILED_PRECONDITION`
|
||||||
|
/// compacted-below-cursor refusal — exactly the unservable state the pin exists
|
||||||
|
/// to prevent.
|
||||||
|
///
|
||||||
|
/// The fix is to clamp the floor DOWN to the `first_seq` of the segment that
|
||||||
|
/// CONTAINS `pin + 1`. `list_segments` returns segments sorted ascending by
|
||||||
|
/// `first_seq`, and segment boundaries are contiguous (segment N covers
|
||||||
|
/// `[first_seq_N, first_seq_{N+1})`), so the segment containing `pin + 1` is the
|
||||||
|
/// one with the largest `first_seq <= pin + 1`. Clamping to it means that
|
||||||
|
/// segment (and every later one) satisfies `first_seq >= floor` and survives,
|
||||||
|
/// while everything strictly before it — already fully covered by the snapshot
|
||||||
|
/// artifact and never needed for the resume — is reclaimed.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns `WalError::Io` on filesystem failure.
|
||||||
|
pub fn compact_wal_online_pinned(
|
||||||
|
wal_dir: &Path,
|
||||||
|
checkpoint_seq: u64,
|
||||||
|
pin: u64,
|
||||||
) -> Result<CompactionResult, WalError> {
|
) -> Result<CompactionResult, WalError> {
|
||||||
let segments = segment::list_segments(wal_dir)?;
|
let segments = segment::list_segments(wal_dir)?;
|
||||||
// The live segment is the maximum-`first_seq` segment; never delete at or
|
// The live segment is the maximum-`first_seq` segment; never delete at or
|
||||||
// above it. Clamp the floor so the writer's open segment is always preserved.
|
// above it. Clamp the floor so the writer's open segment is always preserved.
|
||||||
let floor = match segments.iter().map(|(first_seq, _)| *first_seq).max() {
|
let mut floor = match segments.iter().map(|(first_seq, _)| *first_seq).max() {
|
||||||
Some(active_first_seq) => checkpoint_seq.min(active_first_seq),
|
Some(active_first_seq) => checkpoint_seq.min(active_first_seq),
|
||||||
None => checkpoint_seq,
|
None => checkpoint_seq,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Retention pin: preserve the segment chain covering `pin + 1` onward.
|
||||||
|
if pin > 0 {
|
||||||
|
// `pin == u64::MAX` would overflow `pin + 1`; in that (never-in-practice)
|
||||||
|
// case there is no seq above the pin to resume from, so pin everything.
|
||||||
|
let resume_from = pin.saturating_add(1);
|
||||||
|
// The segment containing `resume_from` is the one with the largest
|
||||||
|
// `first_seq <= resume_from`. Clamping the deletion floor to its
|
||||||
|
// `first_seq` keeps that segment (and all later ones) alive, never
|
||||||
|
// splitting the straddling segment. If `resume_from` is below every
|
||||||
|
// segment's start (the whole live history is at-or-above the pin),
|
||||||
|
// `pin_floor` is the minimum `first_seq`, which deletes nothing.
|
||||||
|
let pin_floor = segments
|
||||||
|
.iter()
|
||||||
|
.map(|(first_seq, _)| *first_seq)
|
||||||
|
.filter(|first_seq| *first_seq <= resume_from)
|
||||||
|
.max()
|
||||||
|
.or_else(|| segments.iter().map(|(first_seq, _)| *first_seq).min())
|
||||||
|
.unwrap_or(0);
|
||||||
|
floor = floor.min(pin_floor);
|
||||||
|
}
|
||||||
|
|
||||||
compact_segments(wal_dir, &segments, floor)
|
compact_segments(wal_dir, &segments, floor)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -351,4 +415,138 @@ mod tests {
|
|||||||
assert_eq!(result.segments_deleted, 0);
|
assert_eq!(result.segments_deleted, 0);
|
||||||
assert_eq!(result.segments_remaining, 0);
|
assert_eq!(result.segments_remaining, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Retention pin (m11p5 §2.1) ──────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// Topology for these tests: three sealed segments at first_seq 1, 100, 200,
|
||||||
|
// plus the writer's live segment at first_seq 300. The sealed segments cover
|
||||||
|
// the half-open ranges [1,100), [100,200), [200,300); the "middle" segment is
|
||||||
|
// [100,200). A checkpoint past all of them (seq 1000) would otherwise let
|
||||||
|
// online compaction delete all three sealed segments (floor clamps only to
|
||||||
|
// the live segment at 300).
|
||||||
|
|
||||||
|
fn three_sealed_plus_live(dir: &Path) {
|
||||||
|
for &seq in &[1u64, 100, 200, 300] {
|
||||||
|
let _ = SegmentWriter::open(dir, ShardId::SINGLE, seq, 1024).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(list_segments(dir).unwrap().len(), 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pin_in_middle_segment_keeps_middle_and_everything_after() {
|
||||||
|
// Pin at 150: the snapshot captured seq 150, the joiner resumes from
|
||||||
|
// pin+1 = 151, which lives inside the middle segment [100,200). That
|
||||||
|
// segment AND every later one must survive; only the first segment
|
||||||
|
// [1,100) — fully below the resume point and fully in the artifact — is
|
||||||
|
// reclaimed.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
three_sealed_plus_live(dir.path());
|
||||||
|
|
||||||
|
let result = compact_wal_online_pinned(dir.path(), 1_000, 150).unwrap();
|
||||||
|
assert_eq!(result.segments_deleted, 1, "only the pre-resume segment");
|
||||||
|
assert_eq!(result.segments_remaining, 3);
|
||||||
|
|
||||||
|
let remaining = list_segments(dir.path()).unwrap();
|
||||||
|
let firsts: Vec<u64> = remaining.iter().map(|(f, _)| *f).collect();
|
||||||
|
assert_eq!(
|
||||||
|
firsts,
|
||||||
|
vec![100, 200, 300],
|
||||||
|
"middle segment containing pin+1 and all after it survive"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pin_straddle_keeps_the_containing_segment_not_splits_it() {
|
||||||
|
// The off-by-one this test exists to catch: passing floor = pin+1 = 200
|
||||||
|
// directly to compact_segments deletes the segment [100,200) because its
|
||||||
|
// first_seq (100) < 200 — but pin+1 = 200 is the FIRST seq of the next
|
||||||
|
// segment, so here the resume range starts exactly at a boundary and the
|
||||||
|
// middle segment is genuinely fully below the artifact's resume point.
|
||||||
|
//
|
||||||
|
// The straddle proper: pin = 199 → pin+1 = 200 lands at a boundary; pin =
|
||||||
|
// 150 → pin+1 = 151 straddles [100,200) (covered above). Here we pin at
|
||||||
|
// 199 to assert the boundary case keeps the segment whose first_seq <=
|
||||||
|
// pin+1: that is [100,200) itself (100 <= 200), so it must survive even
|
||||||
|
// though naive floor=200 would delete it.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
three_sealed_plus_live(dir.path());
|
||||||
|
|
||||||
|
let result = compact_wal_online_pinned(dir.path(), 1_000, 199).unwrap();
|
||||||
|
// floor clamps to the first_seq of the segment containing pin+1=200,
|
||||||
|
// which is the segment STARTING at 200 ([200,300)); the segment
|
||||||
|
// [100,200) is fully below seq 200 and is reclaimed along with [1,100).
|
||||||
|
assert_eq!(result.segments_deleted, 2, "[1,100) and [100,200)");
|
||||||
|
let remaining = list_segments(dir.path()).unwrap();
|
||||||
|
let firsts: Vec<u64> = remaining.iter().map(|(f, _)| *f).collect();
|
||||||
|
assert_eq!(firsts, vec![200, 300]);
|
||||||
|
|
||||||
|
// The true straddle: pin+1 falls strictly inside the second segment.
|
||||||
|
// Re-stage and pin at 100 → pin+1 = 101 straddles [100,200). The naive
|
||||||
|
// floor=101 would delete [100,200) (100 < 101); the clamp must preserve
|
||||||
|
// it by lowering the floor to 100 (the segment's own first_seq).
|
||||||
|
let dir2 = tempfile::tempdir().unwrap();
|
||||||
|
three_sealed_plus_live(dir2.path());
|
||||||
|
let result2 = compact_wal_online_pinned(dir2.path(), 1_000, 100).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
result2.segments_deleted, 1,
|
||||||
|
"the straddled segment [100,200) must NOT be split/deleted"
|
||||||
|
);
|
||||||
|
let firsts2: Vec<u64> = list_segments(dir2.path())
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|(f, _)| *f)
|
||||||
|
.collect();
|
||||||
|
assert_eq!(firsts2, vec![100, 200, 300]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pin_zero_sentinel_is_unpinned_old_behavior() {
|
||||||
|
// pin == 0 must be byte-for-byte the un-pinned online path: floor clamps
|
||||||
|
// only to the live segment (300), reclaiming all three sealed segments.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
three_sealed_plus_live(dir.path());
|
||||||
|
|
||||||
|
let pinned = compact_wal_online_pinned(dir.path(), 1_000, 0).unwrap();
|
||||||
|
assert_eq!(pinned.segments_deleted, 3, "all sealed segments below live");
|
||||||
|
assert_eq!(pinned.segments_remaining, 1);
|
||||||
|
assert_eq!(list_segments(dir.path()).unwrap()[0].0, 300);
|
||||||
|
|
||||||
|
// And the convenience wrapper must agree, on a fresh identical tree.
|
||||||
|
let dir2 = tempfile::tempdir().unwrap();
|
||||||
|
three_sealed_plus_live(dir2.path());
|
||||||
|
let unpinned = compact_wal_online(dir2.path(), 1_000).unwrap();
|
||||||
|
assert_eq!(unpinned.segments_deleted, pinned.segments_deleted);
|
||||||
|
assert_eq!(unpinned.segments_remaining, pinned.segments_remaining);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pin_never_deletes_more_than_the_unpinned_floor_would() {
|
||||||
|
// A pin can only ever LOWER the floor (preserve MORE), never raise it —
|
||||||
|
// it must never cause a segment the unpinned path would keep to be
|
||||||
|
// deleted. With checkpoint at 150 the unpinned floor is
|
||||||
|
// min(150, live=300) = 150, deleting [1,100) and [100,200) (both
|
||||||
|
// first_seq < 150). A pin at 250 (pin+1 = 251, inside [200,300)) clamps
|
||||||
|
// pin_floor to 200, and floor = min(150, 200) = 150 — unchanged. The pin
|
||||||
|
// can never RAISE the floor above the unpinned value, so the pinned and
|
||||||
|
// unpinned results must be identical here.
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
three_sealed_plus_live(dir.path());
|
||||||
|
let pinned = compact_wal_online_pinned(dir.path(), 150, 250).unwrap();
|
||||||
|
|
||||||
|
let dir2 = tempfile::tempdir().unwrap();
|
||||||
|
three_sealed_plus_live(dir2.path());
|
||||||
|
let unpinned = compact_wal_online(dir2.path(), 150).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
pinned.segments_deleted, unpinned.segments_deleted,
|
||||||
|
"a pin above the checkpoint floor changes nothing"
|
||||||
|
);
|
||||||
|
assert_eq!(pinned.segments_deleted, 2, "[1,100) and [100,200)");
|
||||||
|
let firsts: Vec<u64> = list_segments(dir.path())
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.map(|(f, _)| *f)
|
||||||
|
.collect();
|
||||||
|
assert_eq!(firsts, vec![200, 300]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -158,7 +158,8 @@ pub fn diagnose_wal(data_dir: &Path) -> Result<WalDiagnosticReport, WalError> {
|
|||||||
crate::wal::format::BatchPayload::Signals(events) => events.len(),
|
crate::wal::format::BatchPayload::Signals(events) => events.len(),
|
||||||
crate::wal::format::BatchPayload::ItemMetadata(_)
|
crate::wal::format::BatchPayload::ItemMetadata(_)
|
||||||
| crate::wal::format::BatchPayload::Embedding(_)
|
| crate::wal::format::BatchPayload::Embedding(_)
|
||||||
| crate::wal::format::BatchPayload::TermMarker(_) => 1,
|
| crate::wal::format::BatchPayload::TermMarker(_)
|
||||||
|
| crate::wal::format::BatchPayload::Membership(_) => 1,
|
||||||
};
|
};
|
||||||
let n = record_count as u64;
|
let n = record_count as u64;
|
||||||
event_count += n;
|
event_count += n;
|
||||||
|
|||||||
@ -76,6 +76,43 @@ pub const BATCH_KIND_EMBEDDING: u8 = 2;
|
|||||||
/// quorum of upgraded binaries.
|
/// quorum of upgraded binaries.
|
||||||
pub const BATCH_KIND_TERM_MARKER: u8 = 3;
|
pub const BATCH_KIND_TERM_MARKER: u8 = 3;
|
||||||
|
|
||||||
|
/// Batch kind: one cluster-membership record (m11p5 conf-changes).
|
||||||
|
///
|
||||||
|
/// Carries the FULL voter/learner/removed roster as data on the one replicated
|
||||||
|
/// log (the §3 design): the leader journals it, every replica folds it into a
|
||||||
|
/// `ClusterMembership` cell, and recovery re-derives the roster from the last
|
||||||
|
/// record at-or-below the durable frontier (latest version wins — no merge
|
||||||
|
/// logic, because records are full snapshots, not deltas). Folding has no
|
||||||
|
/// storage effect, exactly like the kind-3 term marker.
|
||||||
|
///
|
||||||
|
/// Compatibility mirrors kind-3: membership epoch 0 IS the topology file, so a
|
||||||
|
/// cluster that has never run a conf-change ships zero kind-4 records and
|
||||||
|
/// behaves byte-for-byte as before. A kind-4 record reaching a pre-p5 follower
|
||||||
|
/// is an unknown batch kind → `Corruption` → the receiver's torn-state halt;
|
||||||
|
/// the leader's capability gate (§3.1, a later stage) is what prevents that.
|
||||||
|
pub const BATCH_KIND_MEMBERSHIP: u8 = 4;
|
||||||
|
|
||||||
|
/// Record-level format version of a kind-4 membership payload (byte 0).
|
||||||
|
///
|
||||||
|
/// Distinct from the 64-byte frame's [`FORMAT_VERSION`], so the membership
|
||||||
|
/// record can evolve its field set independently of the frame; an unknown
|
||||||
|
/// value is `Corruption` (forward-compatible refusal, never a silent misparse).
|
||||||
|
pub const MEMBERSHIP_RECORD_VERSION: u8 = 1;
|
||||||
|
|
||||||
|
/// Hard ceiling on the number of members in one kind-4 record.
|
||||||
|
///
|
||||||
|
/// Far above any realistic cluster (the design's reference `StatefulSet` is
|
||||||
|
/// single digits) while bounding the decode allocation a hostile/torn payload
|
||||||
|
/// can request.
|
||||||
|
pub const MAX_MEMBERSHIP_MEMBERS: usize = 4096;
|
||||||
|
|
||||||
|
/// Hard ceiling on a single member's `name`/`grpc_addr`/`http_addr` string.
|
||||||
|
///
|
||||||
|
/// A DNS name plus scheme/port stays well under this; the bound stops a torn
|
||||||
|
/// length prefix from driving a multi-gigabyte allocation before the frame's
|
||||||
|
/// own [`MAX_BLOB_PAYLOAD_BYTES`] check can fire.
|
||||||
|
pub const MAX_MEMBERSHIP_STRING_BYTES: usize = 4096;
|
||||||
|
|
||||||
/// Size of the batch header in bytes (one cache line).
|
/// Size of the batch header in bytes (one cache line).
|
||||||
pub const HEADER_SIZE: usize = 64;
|
pub const HEADER_SIZE: usize = 64;
|
||||||
|
|
||||||
@ -464,6 +501,135 @@ pub struct TermMarkerRecord {
|
|||||||
pub leader_region: u16,
|
pub leader_region: u16,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The role a member holds in the latest membership record (m11p5).
|
||||||
|
///
|
||||||
|
/// The discriminant is the on-disk encoding — it is PERMANENT. `Removed` is a
|
||||||
|
/// tombstone: a removed member keeps its id (ids are never reused, §3) so a
|
||||||
|
/// later record can never collide its burned id with a new join.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
#[repr(u8)]
|
||||||
|
pub enum MemberRole {
|
||||||
|
/// Counts toward election and commit-index quorums.
|
||||||
|
Voter = 0,
|
||||||
|
/// Receives the stream and reports, but is never counted toward any
|
||||||
|
/// quorum (promotion input only — §3.3 learner-marks blocker).
|
||||||
|
Learner = 1,
|
||||||
|
/// Tombstone: this id is burned. The node is fenced from the data plane;
|
||||||
|
/// its id is never reused.
|
||||||
|
Removed = 2,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MemberRole {
|
||||||
|
/// The on-disk discriminant byte.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn to_byte(self) -> u8 {
|
||||||
|
self as u8
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Decode a role byte. An unknown discriminant is rejected (a forward-only
|
||||||
|
/// schema; a pre-decode `Corruption` beats a silently-misread role).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns `WalError::Corruption` for any byte outside `{0, 1, 2}`.
|
||||||
|
pub fn from_byte(b: u8) -> Result<Self, WalError> {
|
||||||
|
match b {
|
||||||
|
0 => Ok(Self::Voter),
|
||||||
|
1 => Ok(Self::Learner),
|
||||||
|
2 => Ok(Self::Removed),
|
||||||
|
other => Err(WalError::Corruption {
|
||||||
|
message: format!("membership record: unknown member role {other}"),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One member in a kind-4 membership record (m11p5).
|
||||||
|
///
|
||||||
|
/// `id` is PERMANENT — assigned once on join (`max(all ids ever) + 1`), never
|
||||||
|
/// renumbered, never reused even after a `Removed` tombstone. The addresses are
|
||||||
|
/// advertised (DNS-capable) host:port strings; this data layer does not parse
|
||||||
|
/// or validate them syntactically (that is the topology/transport layer's job).
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct MemberEntry {
|
||||||
|
/// Permanent member id (never renumbered, never reused).
|
||||||
|
pub id: u16,
|
||||||
|
/// Human-readable region name.
|
||||||
|
pub name: String,
|
||||||
|
/// Advertised gRPC address (host:port; DNS name or literal IP).
|
||||||
|
pub grpc_addr: String,
|
||||||
|
/// Advertised HTTP address (scheme://host:port).
|
||||||
|
pub http_addr: String,
|
||||||
|
/// This member's role in this roster snapshot.
|
||||||
|
pub role: MemberRole,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One cluster-membership record (batch kind 4, m11p5): the FULL roster.
|
||||||
|
///
|
||||||
|
/// Holds the `appending leader's term` at `version`. Records are snapshots, not
|
||||||
|
/// deltas — recovery folds the latest `version` at-or-below the durable
|
||||||
|
/// frontier with no merge logic. Folding has no storage effect; replicas record
|
||||||
|
/// `(version, term, members)` in their [`ClusterMembership`] cell.
|
||||||
|
///
|
||||||
|
/// [`ClusterMembership`]: crate::wal::ClusterMembership
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct MembershipRecord {
|
||||||
|
/// Monotonic conf version. The latest record (highest version) wins; a
|
||||||
|
/// re-applied or recovered older record never regresses the cell.
|
||||||
|
pub version: u64,
|
||||||
|
/// The leadership term that appended this roster.
|
||||||
|
pub term: u64,
|
||||||
|
/// The full member roster at this version (≥ 1 entry, unique ids).
|
||||||
|
pub members: Vec<MemberEntry>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MembershipRecord {
|
||||||
|
/// Structurally validate the roster: non-empty, within the member ceiling,
|
||||||
|
/// and free of duplicate ids. Roles are validated at decode time (an
|
||||||
|
/// in-memory `MemberRole` is already a valid variant by construction).
|
||||||
|
///
|
||||||
|
/// Called by both the encoder (reject a malformed record before it enters
|
||||||
|
/// the log) and the decoder (reject a hostile/torn payload before it folds
|
||||||
|
/// the cell), so the leader, the wire, and the follower can never disagree
|
||||||
|
/// on what a valid roster is.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns `WalError::Corruption` for an empty roster, a roster exceeding
|
||||||
|
/// [`MAX_MEMBERSHIP_MEMBERS`], or a duplicate member id.
|
||||||
|
pub fn validate(&self) -> Result<(), WalError> {
|
||||||
|
if self.members.is_empty() {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: "membership record: roster is empty (a cluster has at least one member)"
|
||||||
|
.into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if self.members.len() > MAX_MEMBERSHIP_MEMBERS {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: {} members exceeds the {MAX_MEMBERSHIP_MEMBERS} ceiling",
|
||||||
|
self.members.len()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Duplicate-id detection. The roster is small (single to low-double
|
||||||
|
// digits in practice), so an O(n²)-free pass via a sorted scan would be
|
||||||
|
// overkill; a HashSet keeps the intent obvious and stays O(n).
|
||||||
|
let mut seen = std::collections::HashSet::with_capacity(self.members.len());
|
||||||
|
for member in &self.members {
|
||||||
|
if !seen.insert(member.id) {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: duplicate member id {} (ids are permanent and unique)",
|
||||||
|
member.id
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A decoded batch payload, by kind.
|
/// A decoded batch payload, by kind.
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub enum BatchPayload {
|
pub enum BatchPayload {
|
||||||
@ -475,6 +641,8 @@ pub enum BatchPayload {
|
|||||||
Embedding(EmbeddingRecord),
|
Embedding(EmbeddingRecord),
|
||||||
/// Kind 3: one term marker (m11p4 election).
|
/// Kind 3: one term marker (m11p4 election).
|
||||||
TermMarker(TermMarkerRecord),
|
TermMarker(TermMarkerRecord),
|
||||||
|
/// Kind 4: one cluster-membership record (m11p5 conf-changes).
|
||||||
|
Membership(MembershipRecord),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One blob (kind-1/2) record submitted for a WAL append.
|
/// One blob (kind-1/2) record submitted for a WAL append.
|
||||||
@ -490,6 +658,9 @@ pub enum BlobRecord {
|
|||||||
Embedding(EmbeddingRecord),
|
Embedding(EmbeddingRecord),
|
||||||
/// A term marker (batch kind 3, m11p4): no entity, no storage effect.
|
/// A term marker (batch kind 3, m11p4): no entity, no storage effect.
|
||||||
TermMarker(TermMarkerRecord),
|
TermMarker(TermMarkerRecord),
|
||||||
|
/// A cluster-membership record (batch kind 4, m11p5): no entity, no
|
||||||
|
/// storage effect — folded into the `ClusterMembership` cell.
|
||||||
|
Membership(MembershipRecord),
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BlobRecord {
|
impl BlobRecord {
|
||||||
@ -500,16 +671,18 @@ impl BlobRecord {
|
|||||||
Self::ItemMetadata(_) => BATCH_KIND_ITEM_METADATA,
|
Self::ItemMetadata(_) => BATCH_KIND_ITEM_METADATA,
|
||||||
Self::Embedding(_) => BATCH_KIND_EMBEDDING,
|
Self::Embedding(_) => BATCH_KIND_EMBEDDING,
|
||||||
Self::TermMarker(_) => BATCH_KIND_TERM_MARKER,
|
Self::TermMarker(_) => BATCH_KIND_TERM_MARKER,
|
||||||
|
Self::Membership(_) => BATCH_KIND_MEMBERSHIP,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The entity this mutation targets (0 for a term marker — it has none).
|
/// The entity this mutation targets (0 for control records — a term marker
|
||||||
|
/// and a membership record have none).
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn entity_id(&self) -> u64 {
|
pub const fn entity_id(&self) -> u64 {
|
||||||
match self {
|
match self {
|
||||||
Self::ItemMetadata(r) => r.entity_id,
|
Self::ItemMetadata(r) => r.entity_id,
|
||||||
Self::Embedding(r) => r.entity_id,
|
Self::Embedding(r) => r.entity_id,
|
||||||
Self::TermMarker(_) => 0,
|
Self::TermMarker(_) | Self::Membership(_) => 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -532,6 +705,7 @@ impl BlobRecord {
|
|||||||
}
|
}
|
||||||
Self::Embedding(r) => encode_embedding_batch(r, seq, batch_ts, shard_id, region_id),
|
Self::Embedding(r) => encode_embedding_batch(r, seq, batch_ts, shard_id, region_id),
|
||||||
Self::TermMarker(r) => encode_term_marker_batch(r, seq, batch_ts, shard_id, region_id),
|
Self::TermMarker(r) => encode_term_marker_batch(r, seq, batch_ts, shard_id, region_id),
|
||||||
|
Self::Membership(r) => encode_membership_batch(r, seq, batch_ts, shard_id, region_id),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -624,6 +798,89 @@ pub fn encode_term_marker_batch(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Encode a kind-4 membership batch (one record, one seqno).
|
||||||
|
///
|
||||||
|
/// Payload layout (all integers little-endian; strings length-prefixed):
|
||||||
|
/// ```text
|
||||||
|
/// rec_version u8 | version u64 | term u64 | member_count u32
|
||||||
|
/// member* : id u16 | role u8 | name_len u32 | name | grpc_len u32 | grpc
|
||||||
|
/// | http_len u32 | http
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// The leading `rec_version` byte is the record-level format version
|
||||||
|
/// ([`MEMBERSHIP_RECORD_VERSION`]), distinct from the frame's
|
||||||
|
/// [`FORMAT_VERSION`], so the membership field set can evolve independently.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns `WalError::Corruption` if the record fails structural validation
|
||||||
|
/// (empty roster, too many members, duplicate id), if any string exceeds
|
||||||
|
/// [`MAX_MEMBERSHIP_STRING_BYTES`], or if the assembled payload exceeds the
|
||||||
|
/// blob ceiling (via the shared frame encoder).
|
||||||
|
pub fn encode_membership_batch(
|
||||||
|
record: &MembershipRecord,
|
||||||
|
seq: u64,
|
||||||
|
batch_ts: u64,
|
||||||
|
shard_id: ShardId,
|
||||||
|
region_id: RegionId,
|
||||||
|
) -> Result<Vec<u8>, WalError> {
|
||||||
|
record.validate()?;
|
||||||
|
let member_count = u32::try_from(record.members.len()).map_err(|_| WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: {} members exceeds u32",
|
||||||
|
record.members.len()
|
||||||
|
),
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Pre-size: fixed prefix (1 + 8 + 8 + 4) plus a per-member estimate. An
|
||||||
|
// undersized guess only forces a realloc; the explicit bound below is what
|
||||||
|
// protects against a hostile length.
|
||||||
|
let mut payload = Vec::with_capacity(21 + record.members.len() * 64);
|
||||||
|
payload.push(MEMBERSHIP_RECORD_VERSION);
|
||||||
|
payload.extend_from_slice(&record.version.to_le_bytes());
|
||||||
|
payload.extend_from_slice(&record.term.to_le_bytes());
|
||||||
|
payload.extend_from_slice(&member_count.to_le_bytes());
|
||||||
|
|
||||||
|
for member in &record.members {
|
||||||
|
payload.extend_from_slice(&member.id.to_le_bytes());
|
||||||
|
payload.push(member.role.to_byte());
|
||||||
|
push_membership_string(&mut payload, &member.name, "name")?;
|
||||||
|
push_membership_string(&mut payload, &member.grpc_addr, "grpc_addr")?;
|
||||||
|
push_membership_string(&mut payload, &member.http_addr, "http_addr")?;
|
||||||
|
}
|
||||||
|
|
||||||
|
encode_frame(
|
||||||
|
BATCH_KIND_MEMBERSHIP,
|
||||||
|
1,
|
||||||
|
&payload,
|
||||||
|
seq,
|
||||||
|
batch_ts,
|
||||||
|
shard_id,
|
||||||
|
region_id,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append a length-prefixed (`u32 LE` len + bytes) string to a membership
|
||||||
|
/// payload, refusing one above the per-string ceiling.
|
||||||
|
fn push_membership_string(buf: &mut Vec<u8>, s: &str, field: &str) -> Result<(), WalError> {
|
||||||
|
if s.len() > MAX_MEMBERSHIP_STRING_BYTES {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: {field} is {} bytes, exceeds the \
|
||||||
|
{MAX_MEMBERSHIP_STRING_BYTES}-byte ceiling",
|
||||||
|
s.len()
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// `len() <= MAX_MEMBERSHIP_STRING_BYTES` (well under u32::MAX), so the cast
|
||||||
|
// cannot truncate.
|
||||||
|
#[allow(clippy::cast_possible_truncation)]
|
||||||
|
let len = s.len() as u32;
|
||||||
|
buf.extend_from_slice(&len.to_le_bytes());
|
||||||
|
buf.extend_from_slice(s.as_bytes());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Shared frame encoder for every batch kind: 64-byte header + payload, BLAKE3
|
/// Shared frame encoder for every batch kind: 64-byte header + payload, BLAKE3
|
||||||
/// over `header[0..32] || payload`. The single owner of the header layout —
|
/// over `header[0..32] || payload`. The single owner of the header layout —
|
||||||
/// every kind goes through here so the framing cannot drift.
|
/// every kind goes through here so the framing cannot drift.
|
||||||
@ -687,7 +944,8 @@ pub fn decode_batch(bytes: &[u8]) -> Result<(BatchHeader, Vec<EventRecord>), Wal
|
|||||||
BatchPayload::Signals(events) => Ok((header, events)),
|
BatchPayload::Signals(events) => Ok((header, events)),
|
||||||
BatchPayload::ItemMetadata(_)
|
BatchPayload::ItemMetadata(_)
|
||||||
| BatchPayload::Embedding(_)
|
| BatchPayload::Embedding(_)
|
||||||
| BatchPayload::TermMarker(_) => Err(WalError::Corruption {
|
| BatchPayload::TermMarker(_)
|
||||||
|
| BatchPayload::Membership(_) => Err(WalError::Corruption {
|
||||||
message: format!(
|
message: format!(
|
||||||
"kind-{} batch decoded through the signals-only decode_batch; \
|
"kind-{} batch decoded through the signals-only decode_batch; \
|
||||||
use decode_batch_payload",
|
use decode_batch_payload",
|
||||||
@ -743,6 +1001,7 @@ pub fn decode_batch_payload(bytes: &[u8]) -> Result<(BatchHeader, BatchPayload),
|
|||||||
&& flags != BATCH_KIND_ITEM_METADATA
|
&& flags != BATCH_KIND_ITEM_METADATA
|
||||||
&& flags != BATCH_KIND_EMBEDDING
|
&& flags != BATCH_KIND_EMBEDDING
|
||||||
&& flags != BATCH_KIND_TERM_MARKER
|
&& flags != BATCH_KIND_TERM_MARKER
|
||||||
|
&& flags != BATCH_KIND_MEMBERSHIP
|
||||||
{
|
{
|
||||||
return Err(WalError::Corruption {
|
return Err(WalError::Corruption {
|
||||||
message: format!("unsupported batch kind: {flags}"),
|
message: format!("unsupported batch kind: {flags}"),
|
||||||
@ -848,6 +1107,7 @@ pub fn decode_batch_payload(bytes: &[u8]) -> Result<(BatchHeader, BatchPayload),
|
|||||||
}
|
}
|
||||||
BATCH_KIND_ITEM_METADATA => BatchPayload::ItemMetadata(decode_item_blob(payload_bytes)?),
|
BATCH_KIND_ITEM_METADATA => BatchPayload::ItemMetadata(decode_item_blob(payload_bytes)?),
|
||||||
BATCH_KIND_TERM_MARKER => BatchPayload::TermMarker(decode_term_marker_blob(payload_bytes)?),
|
BATCH_KIND_TERM_MARKER => BatchPayload::TermMarker(decode_term_marker_blob(payload_bytes)?),
|
||||||
|
BATCH_KIND_MEMBERSHIP => BatchPayload::Membership(decode_membership_blob(payload_bytes)?),
|
||||||
// The kind set was validated in phase 1; only embedding remains.
|
// The kind set was validated in phase 1; only embedding remains.
|
||||||
_ => BatchPayload::Embedding(decode_embedding_blob(payload_bytes)?),
|
_ => BatchPayload::Embedding(decode_embedding_blob(payload_bytes)?),
|
||||||
};
|
};
|
||||||
@ -920,6 +1180,158 @@ fn decode_term_marker_blob(payload: &[u8]) -> Result<TermMarkerRecord, WalError>
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A cursor over a membership payload that reads fixed-width fields and
|
||||||
|
/// length-prefixed strings while refusing every over-read.
|
||||||
|
struct MembershipCursor<'a> {
|
||||||
|
bytes: &'a [u8],
|
||||||
|
pos: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> MembershipCursor<'a> {
|
||||||
|
const fn new(bytes: &'a [u8]) -> Self {
|
||||||
|
Self { bytes, pos: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take(&mut self, n: usize, what: &str) -> Result<&'a [u8], WalError> {
|
||||||
|
let end = self
|
||||||
|
.pos
|
||||||
|
.checked_add(n)
|
||||||
|
.ok_or_else(|| WalError::Corruption {
|
||||||
|
message: "membership record: length overflow".into(),
|
||||||
|
})?;
|
||||||
|
let slice = self
|
||||||
|
.bytes
|
||||||
|
.get(self.pos..end)
|
||||||
|
.ok_or_else(|| WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: truncated reading {what} (need {n} bytes at offset {}, \
|
||||||
|
have {})",
|
||||||
|
self.pos,
|
||||||
|
self.bytes.len()
|
||||||
|
),
|
||||||
|
})?;
|
||||||
|
self.pos = end;
|
||||||
|
Ok(slice)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u8(&mut self, what: &str) -> Result<u8, WalError> {
|
||||||
|
Ok(self.take(1, what)?[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u16(&mut self, what: &str) -> Result<u16, WalError> {
|
||||||
|
let b = self.take(2, what)?;
|
||||||
|
Ok(u16::from_le_bytes([b[0], b[1]]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u32(&mut self, what: &str) -> Result<u32, WalError> {
|
||||||
|
let b = self.take(4, what)?;
|
||||||
|
Ok(u32::from_le_bytes(b.try_into().map_err(|_| {
|
||||||
|
WalError::Corruption {
|
||||||
|
message: format!("membership record: invalid {what} bytes"),
|
||||||
|
}
|
||||||
|
})?))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u64(&mut self, what: &str) -> Result<u64, WalError> {
|
||||||
|
let b = self.take(8, what)?;
|
||||||
|
Ok(u64::from_le_bytes(b.try_into().map_err(|_| {
|
||||||
|
WalError::Corruption {
|
||||||
|
message: format!("membership record: invalid {what} bytes"),
|
||||||
|
}
|
||||||
|
})?))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `u32 LE` length prefix followed by that many UTF-8 bytes. The length
|
||||||
|
/// is bounded BEFORE the slice read so a torn prefix cannot drive a huge
|
||||||
|
/// allocation, and the bytes are validated as UTF-8 (the addresses and
|
||||||
|
/// names are always valid strings on the write side).
|
||||||
|
fn string(&mut self, field: &str) -> Result<String, WalError> {
|
||||||
|
let len = self.u32(field)? as usize;
|
||||||
|
if len > MAX_MEMBERSHIP_STRING_BYTES {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: {field} length {len} exceeds the \
|
||||||
|
{MAX_MEMBERSHIP_STRING_BYTES}-byte ceiling"
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let bytes = self.take(len, field)?;
|
||||||
|
String::from_utf8(bytes.to_vec()).map_err(|_| WalError::Corruption {
|
||||||
|
message: format!("membership record: {field} is not valid UTF-8"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse a kind-4 blob into a [`MembershipRecord`], defending against every
|
||||||
|
/// truncation and rejecting unknown roles, duplicate ids, an empty roster, or
|
||||||
|
/// trailing garbage.
|
||||||
|
fn decode_membership_blob(payload: &[u8]) -> Result<MembershipRecord, WalError> {
|
||||||
|
let mut cur = MembershipCursor::new(payload);
|
||||||
|
|
||||||
|
let rec_version = cur.u8("record version")?;
|
||||||
|
if rec_version != MEMBERSHIP_RECORD_VERSION {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: unknown record version {rec_version} \
|
||||||
|
(this binary writes {MEMBERSHIP_RECORD_VERSION})"
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let version = cur.u64("version")?;
|
||||||
|
let term = cur.u64("term")?;
|
||||||
|
let member_count = cur.u32("member_count")? as usize;
|
||||||
|
// Bound the per-member loop allocation against the ceiling BEFORE reserving:
|
||||||
|
// a torn count must not drive a multi-gigabyte `Vec::with_capacity`.
|
||||||
|
if member_count > MAX_MEMBERSHIP_MEMBERS {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: member_count {member_count} exceeds the \
|
||||||
|
{MAX_MEMBERSHIP_MEMBERS} ceiling"
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut members = Vec::with_capacity(member_count);
|
||||||
|
for _ in 0..member_count {
|
||||||
|
let id = cur.u16("member id")?;
|
||||||
|
let role = MemberRole::from_byte(cur.u8("member role")?)?;
|
||||||
|
let name = cur.string("name")?;
|
||||||
|
let grpc_addr = cur.string("grpc_addr")?;
|
||||||
|
let http_addr = cur.string("http_addr")?;
|
||||||
|
members.push(MemberEntry {
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
grpc_addr,
|
||||||
|
http_addr,
|
||||||
|
role,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reject trailing bytes: a record whose framed payload is longer than its
|
||||||
|
// declared roster is a torn or hostile encoding, not a forward-compatible
|
||||||
|
// extension (that travels through `rec_version`).
|
||||||
|
if cur.pos != payload.len() {
|
||||||
|
return Err(WalError::Corruption {
|
||||||
|
message: format!(
|
||||||
|
"membership record: {} trailing bytes after {} members",
|
||||||
|
payload.len() - cur.pos,
|
||||||
|
member_count
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version,
|
||||||
|
term,
|
||||||
|
members,
|
||||||
|
};
|
||||||
|
// Empty-roster and duplicate-id checks (the structural invariants the
|
||||||
|
// encoder also enforces) run here so a hostile payload that slipped past
|
||||||
|
// framing still cannot fold a malformed roster into the cell.
|
||||||
|
record.validate()?;
|
||||||
|
Ok(record)
|
||||||
|
}
|
||||||
|
|
||||||
/// Parse a kind-2 blob: `entity_id (u64 LE) | dim (u32 LE) | dim × f32 LE`.
|
/// Parse a kind-2 blob: `entity_id (u64 LE) | dim (u32 LE) | dim × f32 LE`.
|
||||||
fn decode_embedding_blob(payload: &[u8]) -> Result<EmbeddingRecord, WalError> {
|
fn decode_embedding_blob(payload: &[u8]) -> Result<EmbeddingRecord, WalError> {
|
||||||
if payload.len() < 12 {
|
if payload.len() < 12 {
|
||||||
|
|||||||
@ -610,3 +610,244 @@ mod batch_kinds {
|
|||||||
assert!(decode_batch_payload(&encoded).is_err());
|
assert!(decode_batch_payload(&encoded).is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── m11p5 kind-4 membership records (conf-changes as data) ──────────────────
|
||||||
|
|
||||||
|
mod membership {
|
||||||
|
use super::*;
|
||||||
|
use crate::replication::{RegionId, ShardId};
|
||||||
|
|
||||||
|
fn member(id: u16, role: MemberRole) -> MemberEntry {
|
||||||
|
MemberEntry {
|
||||||
|
id,
|
||||||
|
name: format!("region-{id}"),
|
||||||
|
grpc_addr: format!("tidaldb-{id}.peers.svc.cluster.local:9500"),
|
||||||
|
http_addr: format!("http://tidaldb-{id}.peers.svc.cluster.local:9501"),
|
||||||
|
role,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sample_record() -> MembershipRecord {
|
||||||
|
MembershipRecord {
|
||||||
|
version: 5,
|
||||||
|
term: 3,
|
||||||
|
members: vec![
|
||||||
|
member(0, MemberRole::Voter),
|
||||||
|
member(1, MemberRole::Voter),
|
||||||
|
member(2, MemberRole::Learner),
|
||||||
|
member(3, MemberRole::Removed),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A full roster round-trips exactly: version, term, every member field,
|
||||||
|
/// the single-seqno range, and the shard/region identity.
|
||||||
|
#[test]
|
||||||
|
fn membership_batch_round_trips() {
|
||||||
|
let record = sample_record();
|
||||||
|
let encoded = encode_membership_batch(&record, 12, 77, ShardId(2), RegionId(1)).unwrap();
|
||||||
|
let (header, payload) = decode_batch_payload(&encoded).unwrap();
|
||||||
|
assert_eq!(header.flags, BATCH_KIND_MEMBERSHIP);
|
||||||
|
assert_eq!(
|
||||||
|
header.event_count, 1,
|
||||||
|
"a membership record consumes one seqno"
|
||||||
|
);
|
||||||
|
assert_eq!(header.first_seq, 12);
|
||||||
|
assert_eq!(header.shard_id, ShardId(2));
|
||||||
|
assert_eq!(header.region_id, RegionId(1));
|
||||||
|
assert_eq!(payload, BatchPayload::Membership(record));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every role discriminant survives the round-trip.
|
||||||
|
#[test]
|
||||||
|
fn all_roles_round_trip() {
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![
|
||||||
|
member(7, MemberRole::Voter),
|
||||||
|
member(8, MemberRole::Learner),
|
||||||
|
member(9, MemberRole::Removed),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let encoded =
|
||||||
|
encode_membership_batch(&record, 1, 1, ShardId::SINGLE, RegionId::SINGLE).unwrap();
|
||||||
|
let (_, payload) = decode_batch_payload(&encoded).unwrap();
|
||||||
|
assert_eq!(payload, BatchPayload::Membership(record));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single-member roster (a fresh seed cluster) is valid.
|
||||||
|
#[test]
|
||||||
|
fn single_member_round_trips() {
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![member(0, MemberRole::Voter)],
|
||||||
|
};
|
||||||
|
let encoded =
|
||||||
|
encode_membership_batch(&record, 1, 1, ShardId::SINGLE, RegionId::SINGLE).unwrap();
|
||||||
|
let (_, payload) = decode_batch_payload(&encoded).unwrap();
|
||||||
|
assert_eq!(payload, BatchPayload::Membership(record));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The signals-only `decode_batch` rejects a membership batch loudly.
|
||||||
|
#[test]
|
||||||
|
fn decode_batch_rejects_membership() {
|
||||||
|
let encoded =
|
||||||
|
encode_membership_batch(&sample_record(), 1, 1, ShardId::SINGLE, RegionId::SINGLE)
|
||||||
|
.unwrap();
|
||||||
|
let err = decode_batch(&encoded).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("decode_batch_payload"),
|
||||||
|
"got: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An empty roster is refused at encode time (a cluster always has a
|
||||||
|
/// member).
|
||||||
|
#[test]
|
||||||
|
fn empty_roster_refused_at_encode() {
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![],
|
||||||
|
};
|
||||||
|
let err =
|
||||||
|
encode_membership_batch(&record, 1, 1, ShardId::SINGLE, RegionId::SINGLE).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("empty"), "got: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A duplicate member id is refused at encode time (ids are permanent and
|
||||||
|
/// unique).
|
||||||
|
#[test]
|
||||||
|
fn duplicate_id_refused_at_encode() {
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![member(5, MemberRole::Voter), member(5, MemberRole::Learner)],
|
||||||
|
};
|
||||||
|
let err =
|
||||||
|
encode_membership_batch(&record, 1, 1, ShardId::SINGLE, RegionId::SINGLE).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("duplicate member id"),
|
||||||
|
"got: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An unknown role byte in the payload is corruption, never a silent
|
||||||
|
/// misread.
|
||||||
|
#[test]
|
||||||
|
fn unknown_role_byte_is_corruption() {
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![member(0, MemberRole::Voter)],
|
||||||
|
};
|
||||||
|
let encoded =
|
||||||
|
encode_membership_batch(&record, 1, 1, ShardId::SINGLE, RegionId::SINGLE).unwrap();
|
||||||
|
// Payload layout: rec_version(1) | version(8) | term(8) | count(4) |
|
||||||
|
// [id(2) | role(1) | ...]. The first member's role byte sits at
|
||||||
|
// HEADER_SIZE + 1 + 8 + 8 + 4 + 2.
|
||||||
|
let role_off = HEADER_SIZE + 1 + 8 + 8 + 4 + 2;
|
||||||
|
let mut corrupt = encoded;
|
||||||
|
corrupt[role_off] = 9; // not in {0,1,2}
|
||||||
|
// Re-checksum so the role check (not the checksum) is what fires.
|
||||||
|
rechecksum(&mut corrupt);
|
||||||
|
let err = decode_batch_payload(&corrupt).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("unknown member role"),
|
||||||
|
"got: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An unknown record-version byte is corruption (forward-compat refusal).
|
||||||
|
#[test]
|
||||||
|
fn unknown_record_version_is_corruption() {
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![member(0, MemberRole::Voter)],
|
||||||
|
};
|
||||||
|
let mut encoded =
|
||||||
|
encode_membership_batch(&record, 1, 1, ShardId::SINGLE, RegionId::SINGLE).unwrap();
|
||||||
|
encoded[HEADER_SIZE] = MEMBERSHIP_RECORD_VERSION + 1;
|
||||||
|
rechecksum(&mut encoded);
|
||||||
|
let err = decode_batch_payload(&encoded).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("unknown record version"),
|
||||||
|
"got: {err}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `member_count` that over-reads the payload is a truncation, refused
|
||||||
|
/// before any allocation runs away.
|
||||||
|
#[test]
|
||||||
|
fn truncated_member_loop_is_corruption() {
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![member(0, MemberRole::Voter)],
|
||||||
|
};
|
||||||
|
let mut encoded =
|
||||||
|
encode_membership_batch(&record, 1, 1, ShardId::SINGLE, RegionId::SINGLE).unwrap();
|
||||||
|
// Inflate member_count to 2 while the body still holds one member.
|
||||||
|
let count_off = HEADER_SIZE + 1 + 8 + 8;
|
||||||
|
encoded[count_off..count_off + 4].copy_from_slice(&2u32.to_le_bytes());
|
||||||
|
rechecksum(&mut encoded);
|
||||||
|
let err = decode_batch_payload(&encoded).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("truncated"), "got: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Trailing bytes after the declared roster are corruption (a torn or
|
||||||
|
/// hostile encoding, not a forward-compatible extension).
|
||||||
|
#[test]
|
||||||
|
fn trailing_bytes_are_corruption() {
|
||||||
|
let record = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![member(0, MemberRole::Voter)],
|
||||||
|
};
|
||||||
|
// Append one stray payload byte and rewrite payload_len to cover it.
|
||||||
|
let mut encoded =
|
||||||
|
encode_membership_batch(&record, 1, 1, ShardId::SINGLE, RegionId::SINGLE).unwrap();
|
||||||
|
encoded.push(0x00);
|
||||||
|
let new_payload_len = (encoded.len() - HEADER_SIZE) as u32;
|
||||||
|
encoded[HEADER_PAYLOAD_LEN_OFFSET..HEADER_PAYLOAD_LEN_OFFSET + 4]
|
||||||
|
.copy_from_slice(&new_payload_len.to_le_bytes());
|
||||||
|
rechecksum(&mut encoded);
|
||||||
|
let err = decode_batch_payload(&encoded).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("trailing"), "got: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A corrupted payload byte fails the BLAKE3 verification.
|
||||||
|
#[test]
|
||||||
|
fn corrupt_payload_fails_checksum() {
|
||||||
|
let mut encoded =
|
||||||
|
encode_membership_batch(&sample_record(), 1, 1, ShardId::SINGLE, RegionId::SINGLE)
|
||||||
|
.unwrap();
|
||||||
|
let mid = HEADER_SIZE + 4;
|
||||||
|
encoded[mid] ^= 0xFF;
|
||||||
|
let err = decode_batch_payload(&encoded).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("checksum"), "got: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A truncated frame (cut inside the payload) is corruption.
|
||||||
|
#[test]
|
||||||
|
fn truncated_frame_is_corruption() {
|
||||||
|
let encoded =
|
||||||
|
encode_membership_batch(&sample_record(), 1, 1, ShardId::SINGLE, RegionId::SINGLE)
|
||||||
|
.unwrap();
|
||||||
|
let cut = encoded.len() - 5;
|
||||||
|
let err = decode_batch_payload(&encoded[0..cut]).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("truncated"), "got: {err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recompute the BLAKE3 checksum over `header[0..32] || payload` so a
|
||||||
|
/// hand-mutated frame's structural check (not the checksum) is what fires.
|
||||||
|
/// `super::super` reaches the `batch` module (this `mod membership` lives
|
||||||
|
/// inside the `tests` module that `batch.rs` includes).
|
||||||
|
fn rechecksum(frame: &mut [u8]) {
|
||||||
|
let checksum = super::super::compute_checksum(&frame[0..32], &frame[HEADER_SIZE..]);
|
||||||
|
frame[32..64].copy_from_slice(checksum.as_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -14,13 +14,16 @@ pub mod session;
|
|||||||
// so that existing `use crate::wal::format::{...}` paths continue to resolve.
|
// so that existing `use crate::wal::format::{...}` paths continue to resolve.
|
||||||
|
|
||||||
pub use batch::{
|
pub use batch::{
|
||||||
BATCH_KIND_EMBEDDING, BATCH_KIND_ITEM_METADATA, BATCH_KIND_SIGNALS, BATCH_KIND_TERM_MARKER,
|
BATCH_KIND_EMBEDDING, BATCH_KIND_ITEM_METADATA, BATCH_KIND_MEMBERSHIP, BATCH_KIND_SIGNALS,
|
||||||
BatchHeader, BatchPayload, BlobRecord, EVENT_SIZE, EVENT_SIZE_V3, EmbeddingRecord, EventRecord,
|
BATCH_KIND_TERM_MARKER, BatchHeader, BatchPayload, BlobRecord, EVENT_SIZE, EVENT_SIZE_V3,
|
||||||
FORMAT_VERSION, FORMAT_VERSION_V1, FORMAT_VERSION_V2, FORMAT_VERSION_V3,
|
EmbeddingRecord, EventRecord, FORMAT_VERSION, FORMAT_VERSION_V1, FORMAT_VERSION_V2,
|
||||||
HEADER_PAYLOAD_LEN_OFFSET, HEADER_SIZE, ItemMetadataRecord, MAGIC, MAX_BLOB_PAYLOAD_BYTES,
|
FORMAT_VERSION_V3, HEADER_PAYLOAD_LEN_OFFSET, HEADER_SIZE, ItemMetadataRecord, MAGIC,
|
||||||
MAX_EVENTS_PER_BATCH, RECORD_TYPE_SIGNAL, TermMarkerRecord, decode_batch, decode_batch_payload,
|
MAX_BLOB_PAYLOAD_BYTES, MAX_EVENTS_PER_BATCH, MAX_MEMBERSHIP_MEMBERS,
|
||||||
|
MAX_MEMBERSHIP_STRING_BYTES, MEMBERSHIP_RECORD_VERSION, MemberEntry, MemberRole,
|
||||||
|
MembershipRecord, RECORD_TYPE_SIGNAL, TermMarkerRecord, decode_batch, decode_batch_payload,
|
||||||
encode_batch, encode_batch_with_shard, encode_embedding_batch, encode_item_metadata_batch,
|
encode_batch, encode_batch_with_shard, encode_embedding_batch, encode_item_metadata_batch,
|
||||||
encode_term_marker_batch, event_content_hash, event_size_for_version, payload_len_from_header,
|
encode_membership_batch, encode_term_marker_batch, event_content_hash, event_size_for_version,
|
||||||
|
payload_len_from_header,
|
||||||
};
|
};
|
||||||
pub use session::{
|
pub use session::{
|
||||||
SESSION_RECORD_CLOSE, SESSION_RECORD_SIGNAL, SESSION_RECORD_START, SESSION_RECORD_VERSION_V2,
|
SESSION_RECORD_CLOSE, SESSION_RECORD_SIGNAL, SESSION_RECORD_START, SESSION_RECORD_VERSION_V2,
|
||||||
|
|||||||
@ -158,6 +158,71 @@ impl WalTermMark {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The applied cluster membership: the FULL roster of the highest-version
|
||||||
|
/// kind-4 record this node's log carries (m11p5 conf-changes).
|
||||||
|
///
|
||||||
|
/// One cell per node (the WAL is one log), mirroring [`WalTermMark`]. Fed by
|
||||||
|
/// recovery (the scan re-derives the roster from the last record at-or-below
|
||||||
|
/// the durable frontier — the highest `version` wins), by a leader appending a
|
||||||
|
/// conf-change record, and by a follower applying a replicated one. Read by the
|
||||||
|
/// membership machinery as the effective roster. `None` = no kind-4 record in
|
||||||
|
/// the log (membership epoch 0 = the topology file, §3).
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct ClusterMembership {
|
||||||
|
/// `Some((version, term, members))` for the highest applied version, under
|
||||||
|
/// ONE lock: the three fields are a single logical value, so a torn read
|
||||||
|
/// (a new version's roster paired with the old version number) is
|
||||||
|
/// impossible. Conf-changes are rare (never per-write — Raft single-server
|
||||||
|
/// changes) and the cell is read a few times per second; a mutex is the
|
||||||
|
/// correct tool, not split atomics.
|
||||||
|
///
|
||||||
|
/// Records are FULL snapshots, so the latest record IS the roster — there
|
||||||
|
/// is no delta merge, and recovery's "latest at-or-below the frontier wins"
|
||||||
|
/// is exactly the monotonic-by-version advance below.
|
||||||
|
inner: std::sync::Mutex<Option<(u64, u64, Vec<crate::wal::format::MemberEntry>)>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClusterMembership {
|
||||||
|
/// Fold a membership record, monotonically by version (a re-applied or
|
||||||
|
/// recovered older record never regresses the cell). A record at the SAME
|
||||||
|
/// version is treated as idempotent and ignored — versions are unique by
|
||||||
|
/// construction (the leader assigns them strictly increasing), so an equal
|
||||||
|
/// version is the same record re-seen on a replay/re-stream, not a
|
||||||
|
/// conflicting roster.
|
||||||
|
pub fn advance(&self, version: u64, term: u64, members: Vec<crate::wal::format::MemberEntry>) {
|
||||||
|
let mut inner = self
|
||||||
|
.inner
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
|
let supersedes = inner.as_ref().is_none_or(|(cur, ..)| version > *cur);
|
||||||
|
if supersedes {
|
||||||
|
*inner = Some((version, term, members));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current applied roster as `(version, term, members)`, or `None` if
|
||||||
|
/// no kind-4 record has been applied (the topology era).
|
||||||
|
#[must_use]
|
||||||
|
pub fn snapshot(&self) -> Option<(u64, u64, Vec<crate::wal::format::MemberEntry>)> {
|
||||||
|
self.inner
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current applied membership version, or `None` in the topology era.
|
||||||
|
/// A cheap read for the version-regression guard on the append path
|
||||||
|
/// (avoids cloning the whole roster just to compare the version).
|
||||||
|
#[must_use]
|
||||||
|
pub fn version(&self) -> Option<u64> {
|
||||||
|
self.inner
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.as_ref()
|
||||||
|
.map(|(v, ..)| *v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A signal event to be appended to the WAL.
|
/// A signal event to be appended to the WAL.
|
||||||
///
|
///
|
||||||
/// This is the public write type. It maps 1:1 to the internal
|
/// This is the public write type. It maps 1:1 to the internal
|
||||||
|
|||||||
@ -238,6 +238,18 @@ pub fn recover(dir: &Path) -> Result<RecoveryResult, WalError> {
|
|||||||
}
|
}
|
||||||
expected_first_seq = Some(candidate);
|
expected_first_seq = Some(candidate);
|
||||||
}
|
}
|
||||||
|
BatchPayload::Membership(record) => {
|
||||||
|
let seq = header.first_seq;
|
||||||
|
all_blobs.push(RecoveredBlob {
|
||||||
|
seq,
|
||||||
|
record: BlobRecord::Membership(record),
|
||||||
|
});
|
||||||
|
let candidate = seq.saturating_add(1);
|
||||||
|
if candidate > next_seq {
|
||||||
|
next_seq = candidate;
|
||||||
|
}
|
||||||
|
expected_first_seq = Some(candidate);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
235
tidal/tests/m11p5_membership_record.rs
Normal file
235
tidal/tests/m11p5_membership_record.rs
Normal file
@ -0,0 +1,235 @@
|
|||||||
|
//! m11p5 — kind-4 `MembershipRecord` on the one replicated log (data layer).
|
||||||
|
//!
|
||||||
|
//! Proves the WAL-level membership machinery end to end through a real
|
||||||
|
//! persistent `TidalDb` in cluster mode:
|
||||||
|
//!
|
||||||
|
//! - a leader appends a kind-4 record, the `ClusterMembership` cell folds it,
|
||||||
|
//! and the seqno is durable;
|
||||||
|
//! - reopening the data dir re-derives the LATEST roster from the surviving log
|
||||||
|
//! (recovery fold — the highest version wins, no merge logic);
|
||||||
|
//! - the append path refuses version regressions and non-cluster mode.
|
||||||
|
//!
|
||||||
|
//! Consumer logic (quorum / election reconfigure) is NOT exercised here — this
|
||||||
|
//! is the data layer only, exactly the m11p5 A3 task slice.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
|
||||||
|
use tidaldb::{
|
||||||
|
TempTidalHome, TidalDb,
|
||||||
|
db::config::{NodeConfig, NodeRole},
|
||||||
|
replication::shard::ShardId,
|
||||||
|
schema::{DecaySpec, EntityKind, SchemaBuilder, Window},
|
||||||
|
testing::{CrashInjector, CrashPoint, crash_injector::run_with_crash},
|
||||||
|
wal::format::{MemberEntry, MemberRole, MembershipRecord},
|
||||||
|
};
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
fn make_schema() -> tidaldb::schema::Schema {
|
||||||
|
let mut builder = SchemaBuilder::new();
|
||||||
|
let _ = builder
|
||||||
|
.signal(
|
||||||
|
"view",
|
||||||
|
EntityKind::Item,
|
||||||
|
DecaySpec::Exponential {
|
||||||
|
half_life: Duration::from_secs(7 * 24 * 3600),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.windows(&[Window::AllTime])
|
||||||
|
.velocity(false)
|
||||||
|
.add();
|
||||||
|
builder.build().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a PERSISTENT cluster node (non-empty `peer_shards` → `replicate_blobs`,
|
||||||
|
/// the WAL becomes the one replicated log so kind-4 records can ride it).
|
||||||
|
fn open_cluster_node(home: &TempTidalHome, schema: tidaldb::schema::Schema) -> TidalDb {
|
||||||
|
TidalDb::builder()
|
||||||
|
.with_data_dir(home.path())
|
||||||
|
.with_schema(schema)
|
||||||
|
.with_cluster(NodeConfig {
|
||||||
|
role: NodeRole::Single,
|
||||||
|
shard_id: ShardId(0),
|
||||||
|
peer_shards: vec![ShardId(1)],
|
||||||
|
..NodeConfig::default()
|
||||||
|
})
|
||||||
|
.open()
|
||||||
|
.expect("persistent cluster node opens")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn member(id: u16, name: &str, role: MemberRole) -> MemberEntry {
|
||||||
|
MemberEntry {
|
||||||
|
id,
|
||||||
|
name: name.to_string(),
|
||||||
|
grpc_addr: format!("tidaldb-{id}.peers.svc.cluster.local:9500"),
|
||||||
|
http_addr: format!("http://tidaldb-{id}.peers.svc.cluster.local:9501"),
|
||||||
|
role,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn roster_v1() -> MembershipRecord {
|
||||||
|
MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 2,
|
||||||
|
members: vec![
|
||||||
|
member(0, "us-east", MemberRole::Voter),
|
||||||
|
member(1, "eu-west", MemberRole::Voter),
|
||||||
|
member(2, "ap-south", MemberRole::Voter),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A v2 record that adds a learner (the join → learner conf-change shape).
|
||||||
|
fn roster_v2() -> MembershipRecord {
|
||||||
|
MembershipRecord {
|
||||||
|
version: 2,
|
||||||
|
term: 2,
|
||||||
|
members: vec![
|
||||||
|
member(0, "us-east", MemberRole::Voter),
|
||||||
|
member(1, "eu-west", MemberRole::Voter),
|
||||||
|
member(2, "ap-south", MemberRole::Voter),
|
||||||
|
member(3, "us-west", MemberRole::Learner),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A leader appends a membership record; the cell folds it and the seqno is
|
||||||
|
/// non-zero (a real durable WAL slot, never the dedup sentinel).
|
||||||
|
#[test]
|
||||||
|
fn append_folds_the_cell_and_is_durable() {
|
||||||
|
let home = TempTidalHome::new().unwrap();
|
||||||
|
let db = open_cluster_node(&home, make_schema());
|
||||||
|
|
||||||
|
// Topology era: no kind-4 record applied yet.
|
||||||
|
assert_eq!(db.cluster_membership(), None);
|
||||||
|
|
||||||
|
let seq = db.append_membership_record(roster_v1()).unwrap();
|
||||||
|
assert!(
|
||||||
|
seq >= 1,
|
||||||
|
"a membership record consumes a real seqno, got {seq}"
|
||||||
|
);
|
||||||
|
|
||||||
|
let (version, term, members) = db.cluster_membership().expect("cell folded the record");
|
||||||
|
assert_eq!(version, 1);
|
||||||
|
assert_eq!(term, 2);
|
||||||
|
assert_eq!(members, roster_v1().members);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Recovery fold: two records durable in the WAL, then a hard CRASH (no
|
||||||
|
/// graceful shutdown — so no compaction runs over the control records), then
|
||||||
|
/// reopen. Recovery re-derives the LATEST version (full snapshots, no merge
|
||||||
|
/// logic; the highest version below the durable frontier wins).
|
||||||
|
///
|
||||||
|
/// A crash — not a clean `close()` — is the faithful test: it exercises exactly
|
||||||
|
/// the path that re-derives the roster from the surviving log on restart, and
|
||||||
|
/// it sidesteps the shutdown-time WAL compaction that (absent the §2.1
|
||||||
|
/// retention pin, a later m11p5 stage) would reclaim a segment holding only
|
||||||
|
/// control records.
|
||||||
|
#[test]
|
||||||
|
fn recovery_re_derives_the_latest_roster_after_crash() {
|
||||||
|
let home = TempTidalHome::new().unwrap();
|
||||||
|
let schema = make_schema();
|
||||||
|
|
||||||
|
// The FIRST CheckpointPreFlush passes (our explicit force_replication_checkpoint
|
||||||
|
// lands the WAL marker durably at the records' seq); the SECOND (the shutdown
|
||||||
|
// ledger checkpoint) fires the crash, so no compaction runs.
|
||||||
|
let injector = CrashInjector::new(CrashPoint::CheckpointPreFlush, 1);
|
||||||
|
let outcome = run_with_crash(&injector, || {
|
||||||
|
let db = open_cluster_node(&home, schema.clone());
|
||||||
|
db.append_membership_record(roster_v1()).unwrap();
|
||||||
|
db.append_membership_record(roster_v2()).unwrap();
|
||||||
|
// The live cell already holds v2 before the crash.
|
||||||
|
assert_eq!(db.cluster_membership().unwrap().0, 2);
|
||||||
|
|
||||||
|
// Land a crash-consistent on-disk checkpoint (WAL marker at the records'
|
||||||
|
// seq); the membership records' seqnos are durable in the WAL.
|
||||||
|
db.force_replication_checkpoint().unwrap();
|
||||||
|
|
||||||
|
// CRASH during the shutdown ledger checkpoint — nothing past here, and
|
||||||
|
// no compaction, reaches disk.
|
||||||
|
let _ = db.close();
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
matches!(outcome, Err(CrashPoint::CheckpointPreFlush)),
|
||||||
|
"the crash injector must have fired during shutdown, got {outcome:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Reopen the crashed node: recovery scans the surviving log and re-derives
|
||||||
|
// the highest version. v1 sits below v2 in the log; the monotonic-by-version
|
||||||
|
// advance makes "latest wins" without any delta merge.
|
||||||
|
let db = open_cluster_node(&home, schema);
|
||||||
|
let (version, term, members) = db
|
||||||
|
.cluster_membership()
|
||||||
|
.expect("recovery re-derived the roster from the surviving log");
|
||||||
|
assert_eq!(version, 2, "the highest-version record wins after recovery");
|
||||||
|
assert_eq!(term, 2);
|
||||||
|
assert_eq!(members, roster_v2().members);
|
||||||
|
assert_eq!(
|
||||||
|
members.len(),
|
||||||
|
4,
|
||||||
|
"the learner is present in the recovered roster"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A version that does not strictly advance the applied cell is refused — the
|
||||||
|
/// cell advances only forward, so a regressing or re-appended version could
|
||||||
|
/// never fold and must fail loudly rather than journal a silent no-op.
|
||||||
|
#[test]
|
||||||
|
fn version_regression_is_refused() {
|
||||||
|
let home = TempTidalHome::new().unwrap();
|
||||||
|
let db = open_cluster_node(&home, make_schema());
|
||||||
|
|
||||||
|
db.append_membership_record(roster_v2()).unwrap(); // version 2
|
||||||
|
|
||||||
|
// Re-appending the same version is refused.
|
||||||
|
let same = db.append_membership_record(roster_v2()).unwrap_err();
|
||||||
|
assert!(same.to_string().contains("does not advance"), "got: {same}");
|
||||||
|
|
||||||
|
// A lower version is refused.
|
||||||
|
let lower = db.append_membership_record(roster_v1()).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
lower.to_string().contains("does not advance"),
|
||||||
|
"got: {lower}"
|
||||||
|
);
|
||||||
|
|
||||||
|
// The cell still holds v2 (no failed append mutated it).
|
||||||
|
assert_eq!(db.cluster_membership().unwrap().0, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A structurally-invalid roster is refused before it enters the log (it would
|
||||||
|
/// fail apply identically on every follower).
|
||||||
|
#[test]
|
||||||
|
fn invalid_roster_is_refused() {
|
||||||
|
let home = TempTidalHome::new().unwrap();
|
||||||
|
let db = open_cluster_node(&home, make_schema());
|
||||||
|
|
||||||
|
let dup = MembershipRecord {
|
||||||
|
version: 1,
|
||||||
|
term: 1,
|
||||||
|
members: vec![
|
||||||
|
member(5, "a", MemberRole::Voter),
|
||||||
|
member(5, "b", MemberRole::Voter),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
let err = db.append_membership_record(dup).unwrap_err();
|
||||||
|
assert!(
|
||||||
|
err.to_string().contains("duplicate member id"),
|
||||||
|
"got: {err}"
|
||||||
|
);
|
||||||
|
assert_eq!(db.cluster_membership(), None, "no record entered the log");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A non-cluster (standalone) node refuses the append: the WAL is not a
|
||||||
|
/// replicated log there.
|
||||||
|
#[test]
|
||||||
|
fn standalone_node_refuses_membership_append() {
|
||||||
|
let home = TempTidalHome::new().unwrap();
|
||||||
|
let db = TidalDb::builder()
|
||||||
|
.with_data_dir(home.path())
|
||||||
|
.with_schema(make_schema())
|
||||||
|
.open()
|
||||||
|
.expect("standalone node opens");
|
||||||
|
|
||||||
|
let err = db.append_membership_record(roster_v1()).unwrap_err();
|
||||||
|
assert!(err.to_string().contains("cluster mode"), "got: {err}");
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user