Repository navigation
feat(scheduler): add HA via Kubernetes Lease leader election #341
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
NickNYU
wants to merge
14
commits into
kvcache-ai:main
Choose a base branch
from
NickNYU:feat/scheduler-ha-leader-election
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 6 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
92b2089
feat(scheduler): add leader-election config surface
NickNYU f92133c
feat(scheduler): leadership domain with Lease election and recovery w…
NickNYU f1a67c3
feat(scheduler): refresh node snapshots after leadership acquisition
NickNYU aac26dd
feat(scheduler): wire leader election in main and floor binding TTL
NickNYU 8a36b6c
test(scheduler): spec Kind integration cases for HA failover
NickNYU 2ac0f4c
feat(deploy): add HA scheduler overlay and leader-election docs
NickNYU d089509
fix(scheduler): address Copilot review on HA failover correctness
NickNYU 2b15c2c
fix(scheduler): keep slow snapshot pulls from overwriting newer heart…
NickNYU d4c18af
fix(scheduler): keep known-but-unobserved nodes excluded past the rec…
NickNYU c9ea0fc
fix(scheduler): address the second OpenCodeReview round on snapshot p…
NickNYU 8b8b03b
refactor(scheduler): restore registry Heartbeat, contain pull semantics
NickNYU 148c983
refactor(scheduler): pointer-typed lastReportAt in RecoveryPending
NickNYU 04b371a
feat(scheduler,gateway): enable standby reads via round_robin gateway…
NickNYU 2f29b59
Revert "feat(scheduler,gateway): enable standby reads via round_robin…
NickNYU File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| # HA scheduler overlay (#259) | ||
|
|
||
| Three leader-elected scheduler replicas behind one Service, competing for a | ||
| `coordination.k8s.io/Lease` (`agentenv-system/agentenv-scheduler`). Exactly | ||
| one pod schedules and processes node reports; standbys stay liveness-healthy | ||
| and serve `LookupNode`/`GetNode` from the shared Redis bindings. | ||
|
|
||
| Traffic rules: | ||
|
|
||
| 1. Node heartbeats → `agentenv-scheduler` Service (leader only). | ||
| 2. Gateway writes (`Schedule`, `RecordAssignment`) → same Service. | ||
| 3. Gateway reads (`LookupNode`) → same Service; served by standbys when | ||
| `scheduler.redis_addr` is set, otherwise retried onto the leader. | ||
|
|
||
| Deploy: | ||
|
|
||
| ```bash | ||
| kubectl apply -k deploy/k8s/overlays/ha | ||
| ``` | ||
|
|
||
| Prerequisites: | ||
|
|
||
| - RBAC: the scheduler Role needs `coordination.k8s.io/leases` | ||
| get/create/update (already in `base/role.yaml`). | ||
| - Redis (recommended): set `scheduler.redis_addr` in | ||
| `config/scheduler.json`. Without it the scheduler runs the documented | ||
| degraded mode: reads retry to the leader, and failover loses routing for | ||
| pre-failover sandboxes. | ||
| - `scheduler.node_admin_api_key`: the x-api-key for node admin APIs, used by | ||
| the leader to pull node snapshots right after winning (sync-node-snapshots). | ||
|
|
||
| Upgrade ordering (rolling this out over a single-replica deployment): | ||
|
|
||
| 1. Upgrade the scheduler binary first — with election off it behaves exactly | ||
| like today, and it must know the leader health service before the probe | ||
| points at it. | ||
| 2. Then apply this overlay (RBAC, probe, replicas, config). | ||
|
|
||
| Rollback: set `leader_election.enabled` to false and scale back to 1 replica. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| { | ||
| "log_level": "info", | ||
| "log_format": "json", | ||
| "scheduler": { | ||
| "grpc_listen_addr": ":9090", | ||
| "strategy": "round_robin", | ||
| "discovery": { | ||
| "mode": "kubernetes", | ||
| "kubernetes": { | ||
| "namespace": "agentenv-system", | ||
| "service_name": "agentenv-nodes", | ||
| "port": 8000, | ||
| "scheme": "http" | ||
| } | ||
| }, | ||
| "leader_election": { | ||
| "enabled": true, | ||
| "lease_name": "agentenv-scheduler", | ||
| "lease_namespace": "agentenv-system", | ||
| "lease_duration": "15s", | ||
| "renew_deadline": "10s", | ||
| "retry_period": "2s" | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| apiVersion: kustomize.config.k8s.io/v1beta1 | ||
| kind: Kustomization | ||
|
|
||
| # HA scheduler topology (#259): 3 leader-elected scheduler replicas behind | ||
| # one Service. Only the leader is ready (readiness probes the leader-specific | ||
| # health service), so Service endpoints contain only the leader; standbys | ||
| # stay liveness-healthy and serve reads from the shared Redis bindings. | ||
| # | ||
| # Point scheduler.redis_addr at your Redis to enable standby reads and | ||
| # failover-preserved routing; without it the scheduler runs the documented | ||
| # degraded mode (reads retry to the leader; pre-failover routing is lost). | ||
|
|
||
| resources: | ||
| - ../../base | ||
|
|
||
| generatorOptions: | ||
| disableNameSuffixHash: true | ||
|
|
||
| configMapGenerator: | ||
| - name: scheduler-k8s-config | ||
| behavior: replace | ||
| files: | ||
| - config/scheduler.json | ||
|
|
||
| patches: | ||
| - target: | ||
| kind: Deployment | ||
| name: agentenv-scheduler | ||
| patch: |- | ||
| - op: replace | ||
| path: /spec/replicas | ||
| value: 3 | ||
| - op: replace | ||
| path: /spec/template/spec/containers/0/readinessProbe/exec/command | ||
| value: | ||
| - /grpc_health_probe | ||
| - -addr=127.0.0.1:9090 | ||
| - -service=scheduler.v1.Scheduler/leader | ||
| # sync-node-snapshots pulls authenticate against node admin APIs with | ||
| # the cluster-wide admin key; mount it from the shared agentenv-auth | ||
| # Secret, never from a ConfigMap. | ||
| - op: add | ||
| path: /spec/template/spec/containers/0/env | ||
| value: | ||
| - name: SCHEDULER_NODE_ADMIN_API_KEY | ||
| valueFrom: | ||
| secretKeyRef: | ||
| name: agentenv-auth | ||
| key: AENV_API_KEY | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "testing" | ||
| "time" | ||
|
|
||
| "agentenv/services/shared/config" | ||
| ) | ||
|
|
||
| // Binding TTL floor tests (#259): under leader election the effective TTL | ||
| // must cover the failover budget (lease_duration + 90s); without election the | ||
| // configured value passes through unchanged. | ||
|
|
||
| func baseCfg(bindingTTL time.Duration) config.Config { | ||
| return config.Config{ | ||
| Scheduler: config.SchedulerConfig{BindingTTL: bindingTTL}, | ||
| } | ||
| } | ||
|
|
||
| func TestEffectiveBindingTTLWithoutElection(t *testing.T) { | ||
| cfg := baseCfg(30 * time.Second) | ||
| if got := effectiveBindingTTL(cfg); got != 30*time.Second { | ||
| t.Fatalf("election off: want configured TTL 30s, got %v", got) | ||
| } | ||
| } | ||
|
|
||
| func TestEffectiveBindingTTLWithElectionFloors(t *testing.T) { | ||
| cfg := baseCfg(30 * time.Second) | ||
| cfg.Scheduler.LeaderElection = config.SchedulerLeaderElectionConfig{ | ||
| Enabled: true, | ||
| LeaseDuration: 15 * time.Second, | ||
| } | ||
| // floor = 15s + 90s = 105s > 30s | ||
| if got := effectiveBindingTTL(cfg); got != 105*time.Second { | ||
| t.Fatalf("election on: want floor 105s, got %v", got) | ||
| } | ||
| } | ||
|
|
||
| func TestEffectiveBindingTTLWithElectionKeepsLargerConfigured(t *testing.T) { | ||
| cfg := baseCfg(5 * time.Minute) | ||
| cfg.Scheduler.LeaderElection = config.SchedulerLeaderElectionConfig{ | ||
| Enabled: true, | ||
| LeaseDuration: 15 * time.Second, | ||
| } | ||
| // floor = 105s < 5m: the larger configured value wins. | ||
| if got := effectiveBindingTTL(cfg); got != 5*time.Minute { | ||
| t.Fatalf("election on: want configured 5m (larger than floor), got %v", got) | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch — this is correct: with leader-only readiness, standbys are never in any Service's endpoints, so the standby-served read path is unreachable in the HA overlay. Worth explaining how we got here, because the two inputs genuinely conflict in Kubernetes:
The issue's desired behavior asks for leader-only endpoints: "Liveness remains healthy on standbys; readiness exposes only the leader" (#259).
The follow-up discussion asked for standby reads: "every standby replica acts as a query-only node and can serve LookupNode from the shared bindings" (#259 (comment)).
Pod readiness is global in K8S — a pod is Ready in all Services or in none — so "leader-only endpoints" and "standbys receive read traffic" cannot both hold. We implemented both requirements faithfully, which leaves the read path formally present but unreachable. We kept leader-only endpoints as the default because it is the correctness-first choice: with the gateway's pick_first connection pinning, it guarantees writes (Schedule/RecordAssignment/Heartbeat) never land on a non-leader, so there is no dual-writer window even before fencing kicks in.
Two ways to resolve it — maintainer's call:
(i) Make standby reads real: standbys stay Ready (readiness = overall serving), gateway uses round_robin + retry-on-Unavailable, so writes retry onto the leader and reads genuinely reach standbys. Cost: gateway LB/retry config, and ~2/3 of write attempts take one retry.
(ii) Drop standby reads: standbys stay pure idle, reads ride the leader only, accepting a read gap of roughly (lease detection + readiness flip) during failover. This is already today's behavior in the no-Redis degraded mode.
Interim this PR keeps leader-only endpoints. Happy to implement either direction — (i) if standby reads are worth the retry cost, (ii) if simplicity wins.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Valid finding, and a genuine design fork rather than a bug: it stems from two stated requirements that cannot coexist in K8S (leader-only readiness vs standbys serving reads). Full analysis with both options (make standbys Ready + gateway round_robin/retry, or drop standby reads) is in the PR discussion: #341 (comment) — leaving this open pending maintainer decision.