Files
anchorage/internal/pkg/scheduler/rebalance.go
T
57_WolveandClaude Opus 4.7 90ac4b169c
Security / Vulnerability Check (push) Successful in 1m47s
Test / Build & Unit Tests (push) Successful in 5m4s
Test / Lint (push) Successful in 27s
Test / Integration Tests (push) Failing after 1m58s
ci: fix first CI run — tidy, gofmt, ordering test, govulncheck pin
- ids: TestIDsAreTimeOrdered asserted strict lexicographic ordering of
  back-to-back UUIDv7s, but the sub-ms tail is random and not required
  to be monotonic. Sleep between samples so each ID lands in a distinct
  millisecond — the property that actually gives Postgres index
  locality on (org_id, id desc).
- go.mod/go.sum: run go mod tidy. keyfunc/v3, prometheus/client_golang
  and testcontainers-go/modules/postgres are imported directly and
  should not be marked // indirect; also drops stale sum entries.
- gofmt -w across 12 files flagged by the lint job.
- security.yml: pin govulncheck to v1.2.0. @latest triggers a proxy
  lookup every run, which is the step that hung for 16m on the Gitea
  runner.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-17 09:18:49 -05:00

195 lines
5.9 KiB
Go

package scheduler
import (
"context"
"errors"
"log/slog"
"time"
"github.com/nats-io/nats.go"
"anchorage/internal/pkg/ids"
"anchorage/internal/pkg/placement"
"anchorage/internal/pkg/store"
)
// PlannedMove describes a placement reassignment the rebalancer would
// (or did) make. Returned from DryRun to preview and from RunOnce to
// confirm. Exported so admin endpoints can surface it as JSON.
type PlannedMove struct {
RequestID string `json:"request_id"`
FromNode string `json:"from_node"`
ToNode string `json:"to_node"`
Reason string `json:"reason"` // "down" | "drain"
NewFence int64 `json:"new_fence,omitempty"` // populated after apply
}
// Rebalancer migrates placements off nodes that transitioned to down
// or drained. Leader-gated: the composition root only calls Run on the
// elected leader, and stops it when the node is demoted.
//
// The one-shot admin variants (DryRun, RunOnce) do NOT require the
// leader loop to be running — they're safe to call from any node because
// every individual placement update is fence-guarded at the store level.
type Rebalancer struct {
Store store.Store
NC *nats.Conn
Interval time.Duration
// MaintenanceGate is a function that returns true when cluster-wide
// maintenance is enabled. The rebalancer no-ops while it returns true.
MaintenanceGate func(context.Context) bool
}
// Run walks the placements table on every tick.
func (r *Rebalancer) Run(ctx context.Context) error {
ticker := time.NewTicker(r.Interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
if r.MaintenanceGate != nil && r.MaintenanceGate(ctx) {
slog.Debug("rebalancer: skipping tick (cluster maintenance)")
continue
}
if _, err := r.RunOnce(ctx); err != nil {
slog.Warn("rebalancer: tick failed", "err", err)
}
}
}
}
// DryRun returns the list of moves RunOnce would execute against the
// current store state. Safe to call concurrently with the leader loop —
// store reads are snapshot-consistent within a transaction boundary.
func (r *Rebalancer) DryRun(ctx context.Context) ([]PlannedMove, error) {
return r.plan(ctx)
}
// RunOnce performs a single plan+apply pass and returns the moves that
// actually executed (with NewFence populated). Errors on individual
// moves are logged and skipped — matches the Run loop's per-tick
// resilience. A top-level error is returned only when plan fails.
func (r *Rebalancer) RunOnce(ctx context.Context) ([]PlannedMove, error) {
moves, err := r.plan(ctx)
if err != nil {
return nil, err
}
return r.apply(ctx, moves), nil
}
// plan walks every non-live node, computes the new placement for each
// of that node's pins via rendezvous hash, and returns the list of
// moves that would happen if applied. No writes.
func (r *Rebalancer) plan(ctx context.Context) ([]PlannedMove, error) {
allNodes, err := r.Store.Nodes().ListAll(ctx)
if err != nil {
return nil, err
}
var candidates []placement.Node
liveIDs := map[ids.NodeID]bool{}
for _, n := range allNodes {
if n.Status == store.NodeStatusUp {
candidates = append(candidates, placement.Node{ID: n.ID.String(), Status: n.Status})
liveIDs[n.ID] = true
}
}
if len(candidates) == 0 {
return nil, nil
}
var moves []PlannedMove
for _, n := range allNodes {
if n.Status == store.NodeStatusUp {
continue
}
reason := "down"
if n.Status == store.NodeStatusDrained {
reason = "drain"
}
placements, err := r.Store.Pins().ListPlacementsForNode(ctx, n.ID, "")
if err != nil {
slog.Warn("rebalancer: list placements", "node", n.ID, "err", err)
continue
}
for _, pl := range placements {
pinRow, err := r.Store.Pins().GetByRequestID(ctx, pl.RequestID)
if err != nil {
if !errors.Is(err, store.ErrNotFound) {
slog.Warn("rebalancer: get pin", "request_id", pl.RequestID, "err", err)
}
continue
}
want := placement.Compute(pinRow.OrgID.String(), pinRow.CID, 1, candidates)
if len(want) == 0 {
continue
}
newNodeID, err := ids.ParseNode(want[0])
if err != nil || newNodeID == pl.NodeID {
continue
}
moves = append(moves, PlannedMove{
RequestID: pl.RequestID.String(),
FromNode: pl.NodeID.String(),
ToNode: newNodeID.String(),
Reason: reason,
})
}
}
return moves, nil
}
// apply executes a slice of planned moves. Returns only the moves that
// actually executed — per-move errors are logged + skipped, matching
// the original tick's resilience. Moves are mutated in place so the
// caller sees populated NewFence values.
func (r *Rebalancer) apply(ctx context.Context, moves []PlannedMove) []PlannedMove {
applied := make([]PlannedMove, 0, len(moves))
for _, m := range moves {
rid, err := ids.ParsePin(m.RequestID)
if err != nil {
slog.Warn("rebalancer: bad request id", "id", m.RequestID, "err", err)
continue
}
fromID, err := ids.ParseNode(m.FromNode)
if err != nil {
slog.Warn("rebalancer: bad from-node id", "err", err)
continue
}
toID, err := ids.ParseNode(m.ToNode)
if err != nil {
slog.Warn("rebalancer: bad to-node id", "err", err)
continue
}
newPl, err := r.Store.Pins().ReplacePlacement(ctx, rid, fromID, toID)
if err != nil {
slog.Warn("rebalancer: replace placement", "err", err)
continue
}
m.NewFence = newPl.Fence
// Audit — look up pin row for OrgID. Missing is non-fatal; we
// skip the audit rather than fail the move.
if pinRow, err := r.Store.Pins().GetByRequestID(ctx, rid); err == nil {
_ = r.Store.Audit().Insert(ctx, &store.AuditEntry{
OrgID: &pinRow.OrgID,
Action: "pin.rebalance",
Target: m.RequestID,
Result: "ok",
Detail: map[string]any{
"from": m.FromNode,
"to": m.ToNode,
"reason": m.Reason,
"fence": newPl.Fence,
},
})
}
slog.Info("rebalancer: moved placement",
"request_id", m.RequestID, "from", m.FromNode, "to", m.ToNode,
"reason", m.Reason, "fence", newPl.Fence)
applied = append(applied, m)
}
return applied
}