package placement_test import ( "fmt" "sort" "testing" "anchorage/internal/pkg/placement" ) func nodes(ids ...string) []placement.Node { out := make([]placement.Node, 0, len(ids)) for _, id := range ids { out = append(out, placement.Node{ID: id, Status: "up"}) } return out } func TestDeterministic(t *testing.T) { ns := nodes("nod_a", "nod_b", "nod_c", "nod_d", "nod_e") a := placement.Compute("org_1", "QmABC", 2, ns) b := placement.Compute("org_1", "QmABC", 2, ns) if fmt.Sprint(a) != fmt.Sprint(b) { t.Errorf("non-deterministic: %v vs %v", a, b) } if len(a) != 2 { t.Errorf("want 2 replicas, got %d", len(a)) } } func TestDistinctNodes(t *testing.T) { ns := nodes("nod_a", "nod_b", "nod_c", "nod_d", "nod_e") r := placement.Compute("org_1", "QmXYZ", 3, ns) seen := map[string]bool{} for _, id := range r { if seen[id] { t.Errorf("duplicate placement: %s in %v", id, r) } seen[id] = true } } func TestUnderReplicatesOnSmallCluster(t *testing.T) { ns := nodes("nod_a") r := placement.Compute("org_1", "QmXYZ", 3, ns) if len(r) != 1 { t.Errorf("want 1 (cluster too small), got %d", len(r)) } } func TestZeroInputs(t *testing.T) { if r := placement.Compute("", "", 0, nil); len(r) != 0 { t.Errorf("empty inputs should yield empty slice, got %v", r) } } func TestLoadSpread(t *testing.T) { // Property test: with N nodes and many CIDs, each node should appear // roughly 1/N of the time as the primary (first) replica. We allow // ±30% tolerance; HRW is pseudo-random, not strictly uniform. ns := nodes("nod_a", "nod_b", "nod_c", "nod_d", "nod_e") counts := map[string]int{} total := 5000 for i := 0; i < total; i++ { cid := fmt.Sprintf("Qm_%d", i) r := placement.Compute("org_1", cid, 1, ns) counts[r[0]]++ } if len(counts) != len(ns) { t.Errorf("only %d nodes received primary load, want %d", len(counts), len(ns)) } expected := total / len(ns) for id, c := range counts { diff := c - expected if diff < 0 { diff = -diff } if diff*100/expected > 30 { t.Errorf("node %s got %d primaries, expected ~%d (±30%%)", id, c, expected) } } } func TestMinimalDisruptionOnNodeLoss(t *testing.T) { // When a node disappears, only pins that *had* that node in their // replica set should see any churn; everyone else stays put. before := nodes("nod_a", "nod_b", "nod_c", "nod_d") after := nodes("nod_a", "nod_b", "nod_c") churn := 0 total := 1000 for i := 0; i < total; i++ { cid := fmt.Sprintf("Qm_%d", i) a := placement.Compute("org_1", cid, 2, before) b := placement.Compute("org_1", cid, 2, after) sort.Strings(a) sort.Strings(b) if fmt.Sprint(a) != fmt.Sprint(b) { churn++ } } // Losing 1 of 4 nodes: roughly 2/4 = 50% of pins included that node // in their top-2. We just assert "less than all" churned. if churn >= total { t.Errorf("everything churned (%d/%d) — HRW broken?", churn, total) } }