diff --git a/packages/api/internal/orchestrator/nodemanager/placement_metrics.go b/packages/api/internal/orchestrator/nodemanager/placement_metrics.go index a8cb0f58a70..642572af2b7 100644 --- a/packages/api/internal/orchestrator/nodemanager/placement_metrics.go +++ b/packages/api/internal/orchestrator/nodemanager/placement_metrics.go @@ -13,6 +13,9 @@ type SandboxResources struct { // HugePages reports whether the sandbox's RAM comes from the node's // hugepage pool rather than ordinary pages. HugePages bool + // BuildID identifies the template build this sandbox starts from. Used by + // the placement score for optional same-build affinity; empty when unknown. + BuildID string } type PlacementMetrics struct { @@ -55,6 +58,25 @@ func (p *PlacementMetrics) InProgressCount() uint32 { return uint32(p.sandboxesInProgress.Count()) } +// SameBuildInProgress counts the in-flight placements on this node that start +// from buildID. It is the node-local sibling count a same-template read-only +// base (pmem+DAX) could share with: N siblings make N-1 base copies +// redundant. Empty buildID counts nothing. +func (p *PlacementMetrics) SameBuildInProgress(buildID string) int { + if buildID == "" { + return 0 + } + + n := 0 + for _, res := range p.sandboxesInProgress.Items() { + if res.BuildID == buildID { + n++ + } + } + + return n +} + // StartPlacingIf records the placement only if fits holds, checking and // inserting under one lock so concurrent placements cannot all pass a check // that counts in-flight placements. fits must not call StartPlacingIf. diff --git a/packages/api/internal/orchestrator/orchestrator.go b/packages/api/internal/orchestrator/orchestrator.go index 7056af7b18b..33c71b7d03b 100644 --- a/packages/api/internal/orchestrator/orchestrator.go +++ b/packages/api/internal/orchestrator/orchestrator.go @@ -405,10 +405,17 @@ func getBestOfKConfig(ctx context.Context, featureFlagsClient *featureflags.Clie alpha := float64(alphaPercent) / 100.0 maxOvercommit := float64(maxOvercommitPercent) / 100.0 + affinityWeight := float64(featureFlagsClient.IntFlag(ctx, featureflags.BestOfKTemplateAffinityWeight)) / 100.0 + affinityCap := featureFlagsClient.IntFlag(ctx, featureflags.BestOfKTemplateAffinityCap) + return placement.BestOfKConfig{ R: maxOvercommit, K: k, Alpha: alpha, ScoreHugepages: scoreHugepages, + // Same-build affinity, off unless an operator sets the weight flag. Readies + // node-local same-template base sharing (pmem+DAX) by colocating siblings. + TemplateAffinityWeight: affinityWeight, + TemplateAffinityCap: affinityCap, } } diff --git a/packages/api/internal/orchestrator/placement/affinity_observability_test.go b/packages/api/internal/orchestrator/placement/affinity_observability_test.go new file mode 100644 index 00000000000..fcb22caae86 --- /dev/null +++ b/packages/api/internal/orchestrator/placement/affinity_observability_test.go @@ -0,0 +1,159 @@ +package placement + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + sdkmetric "go.opentelemetry.io/otel/sdk/metric" + "go.opentelemetry.io/otel/sdk/metric/metricdata" + + "github.com/e2b-dev/infra/packages/api/internal/api" + "github.com/e2b-dev/infra/packages/api/internal/orchestrator/nodemanager" + "github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator" + "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" +) + +// sbxRequestWithBuild is testSbxRequest with a build_id, the field the +// affinity path keys off. +func sbxRequestWithBuild(id, buildID string) *orchestrator.SandboxCreateRequest { + req := testSbxRequest(id) + req.Sandbox.BuildId = buildID + + return req +} + +// placeOn forces placement onto node, so an observability test controls which +// node takes the sandbox without depending on the sampler. +func placeOn(node *nodemanager.Node) stubAlgorithm { + return stubAlgorithm{choose: func(map[string]struct{}) (*nodemanager.Node, error) { + return node, nil + }} +} + +// swapAffinityMeters points both affinity instruments at a fresh ManualReader +// for the duration of a test and returns it, restoring the originals after. +func swapAffinityMeters(t *testing.T) *sdkmetric.ManualReader { + t.Helper() + + reader := sdkmetric.NewManualReader() + meter := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)).Meter("github.com/e2b-dev/infra/packages/api/internal/orchestrator/placement") + + counter, err := telemetry.GetCounter(meter, telemetry.ApiOrchestratorTemplateAffinityPlacements) + require.NoError(t, err) + hist, err := telemetry.GetHistogram(meter, telemetry.ApiOrchestratorTemplateAffinitySiblings) + require.NoError(t, err) + + prevCounter, prevHist := templateAffinityPlacements, templateAffinitySiblings + templateAffinityPlacements = counter + templateAffinitySiblings = hist + t.Cleanup(func() { + templateAffinityPlacements = prevCounter + templateAffinitySiblings = prevHist + }) + + return reader +} + +// collectAffinity reads the effect counter and the siblings histogram back out +// of reader: the counter as effect to count, the histogram as its single +// recorded sum and point count. +func collectAffinity(t *testing.T, reader *sdkmetric.ManualReader) (byEffect map[string]int64, histSum int64, histCount uint64) { + t.Helper() + + var collected metricdata.ResourceMetrics + require.NoError(t, reader.Collect(context.Background(), &collected)) + + byEffect = map[string]int64{} + for _, scope := range collected.ScopeMetrics { + for _, m := range scope.Metrics { + switch data := m.Data.(type) { + case metricdata.Sum[int64]: + for _, p := range data.DataPoints { + effect, _ := p.Attributes.Value("effect") + byEffect[effect.AsString()] += p.Value + } + case metricdata.Histogram[int64]: + for _, p := range data.DataPoints { + histSum += p.Sum + histCount += p.Count + } + } + } + } + + return byEffect, histSum, histCount +} + +// A placement onto a node already running same-build siblings is recorded +// colocated, and the siblings histogram carries the count the node held. +func TestRecordTemplateAffinity_Colocated(t *testing.T) { + reader := swapAffinityMeters(t) + + node := nodemanager.NewTestNode("node", api.NodeStatusReady, 0, 64, emptyHugePool()) + // Two same-build siblings already in flight on the node. + for _, id := range []string{"sib-1", "sib-2"} { + node.PlacementMetrics.StartPlacingIf(id, nodemanager.SandboxResources{CPUs: 1, MiBMemory: 512, HugePages: true, BuildID: "build-hot"}, func() bool { return true }) + } + nodes := []*nodemanager.Node{node} + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + + _, err := placeSandbox(ctx, placeOn(node), nodes, nil, sbxRequestWithBuild("sbx", "build-hot"), + Requirements{}, false, nil, refusalBackoff{}, time.Time{}) + require.NoError(t, err) + + byEffect, histSum, histCount := collectAffinity(t, reader) + assert.Equal(t, int64(1), byEffect["colocated"]) + assert.Equal(t, int64(0), byEffect["spread"]) + assert.Equal(t, uint64(1), histCount, "one placement recorded") + assert.Equal(t, int64(2), histSum, "the two in-flight siblings the node held") +} + +// A placement onto a node with no same-build sibling is recorded spread, with +// a siblings count of zero. +func TestRecordTemplateAffinity_Spread(t *testing.T) { + reader := swapAffinityMeters(t) + + node := nodemanager.NewTestNode("node", api.NodeStatusReady, 0, 64, emptyHugePool()) + // A different build in flight must not count as a sibling. + node.PlacementMetrics.StartPlacingIf("other", nodemanager.SandboxResources{CPUs: 1, MiBMemory: 512, HugePages: true, BuildID: "build-other"}, func() bool { return true }) + nodes := []*nodemanager.Node{node} + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + + _, err := placeSandbox(ctx, placeOn(node), nodes, nil, sbxRequestWithBuild("sbx", "build-hot"), + Requirements{}, false, nil, refusalBackoff{}, time.Time{}) + require.NoError(t, err) + + byEffect, histSum, histCount := collectAffinity(t, reader) + assert.Equal(t, int64(1), byEffect["spread"]) + assert.Equal(t, int64(0), byEffect["colocated"]) + assert.Equal(t, uint64(1), histCount) + assert.Equal(t, int64(0), histSum) +} + +// A create without a build_id is not same-template fan-out: it records no +// affinity series at all, so the metric is not diluted by placements that +// sharing cannot help. +func TestRecordTemplateAffinity_NoBuildIDSkipped(t *testing.T) { + reader := swapAffinityMeters(t) + + node := nodemanager.NewTestNode("node", api.NodeStatusReady, 0, 64, emptyHugePool()) + nodes := []*nodemanager.Node{node} + + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + + _, err := placeSandbox(ctx, placeOn(node), nodes, nil, testSbxRequest("sbx"), + Requirements{}, false, nil, refusalBackoff{}, time.Time{}) + require.NoError(t, err) + + byEffect, _, histCount := collectAffinity(t, reader) + assert.Empty(t, byEffect, "no effect counted for a build-less create") + assert.Zero(t, histCount, "no siblings recorded for a build-less create") +} diff --git a/packages/api/internal/orchestrator/placement/affinity_simulation_test.go b/packages/api/internal/orchestrator/placement/affinity_simulation_test.go new file mode 100644 index 00000000000..cfa33cc4bc5 --- /dev/null +++ b/packages/api/internal/orchestrator/placement/affinity_simulation_test.go @@ -0,0 +1,162 @@ +package placement + +import ( + "context" + "fmt" + "math/rand" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/e2b-dev/infra/packages/api/internal/api" + "github.com/e2b-dev/infra/packages/api/internal/orchestrator/nodemanager" +) + +// spreadStats is what one simulated fleet run reports: how widely each build's +// sandboxes landed, and how often a sandbox joined a same-build sibling. +type spreadStats struct { + // avgNodesPerBuild is the mean number of distinct nodes a build's sandboxes + // spread across. Lower is tighter colocation; the floor is set by how many + // nodes a build's sandboxes must occupy to fit. + avgNodesPerBuild float64 + // colocationRate is the fraction of placements that landed on a node + // already running an in-flight same-build sibling: the share that a shared + // read-only base (pmem+DAX) could back without a fresh private copy. + colocationRate float64 +} + +// simulateSpread fills a fleet with several templates competing for the same +// nodes, placing through the real chooseNode (best-of-K sampling) so the +// affinity discount is exercised exactly as production would. rand is seeded +// per run, so a given seed and weight reproduce byte for byte. +func simulateSpread(t *testing.T, weight float64, seed int64) spreadStats { + t.Helper() + rand.Seed(seed) + + config := BestOfKConfig{R: 4, K: 3, Alpha: 0.5, ScoreHugepages: true, TemplateAffinityWeight: weight, TemplateAffinityCap: 8} + algo := NewBestOfK(config).(*BestOfK) + + const numNodes = 12 + const numBuilds = 4 + const perBuild = 9 + + nodes := make([]*nodemanager.Node, numNodes) + nodeIndex := map[string]int{} + for i := range nodes { + nodes[i] = nodemanager.NewTestNode(fmt.Sprintf("n%02d", i), api.NodeStatusReady, 0, 64, emptyHugePool()) + nodeIndex[nodes[i].ID] = i + } + + perNodeBuild := make([]map[string]int, numNodes) + for i := range perNodeBuild { + perNodeBuild[i] = map[string]int{} + } + + // Interleave builds round-robin so each placement decides against a fleet + // that is partly filled by every template, not one template at a time. + order := make([]string, 0, numBuilds*perBuild) + for r := 0; r < perBuild; r++ { + for b := 0; b < numBuilds; b++ { + order = append(order, fmt.Sprintf("build-%d", b)) + } + } + + colocated := 0 + for k, build := range order { + res := nodemanager.SandboxResources{CPUs: 1, MiBMemory: 512, HugePages: true, BuildID: build} + chosen, err := algo.chooseNode(context.Background(), nodes, nil, res, Requirements{}, false, nil) + require.NoError(t, err) + require.NotNil(t, chosen) + + idx := nodeIndex[chosen.ID] + if perNodeBuild[idx][build] > 0 { + colocated++ + } + perNodeBuild[idx][build]++ + chosen.PlacementMetrics.StartPlacingIf(fmt.Sprintf("s%d", k), res, func() bool { return true }) + } + + nodesPerBuild := map[string]map[int]struct{}{} + for i := range perNodeBuild { + for b := range perNodeBuild[i] { + if nodesPerBuild[b] == nil { + nodesPerBuild[b] = map[int]struct{}{} + } + nodesPerBuild[b][i] = struct{}{} + } + } + sumSpread := 0.0 + for _, s := range nodesPerBuild { + sumSpread += float64(len(s)) + } + + return spreadStats{ + avgNodesPerBuild: sumSpread / float64(len(nodesPerBuild)), + colocationRate: float64(colocated) / float64(len(order)), + } +} + +func meanSpread(t *testing.T, weight float64, seeds []int64) spreadStats { + t.Helper() + var sumNodes, sumColo float64 + for _, s := range seeds { + st := simulateSpread(t, weight, s) + sumNodes += st.avgNodesPerBuild + sumColo += st.colocationRate + } + n := float64(len(seeds)) + return spreadStats{avgNodesPerBuild: sumNodes / n, colocationRate: sumColo / n} +} + +// TestTemplateAffinity_TightensColocation is the PR's evidence that the +// discount does what #3824/#3825 need: on a fleet where several templates +// compete for the same nodes, turning the affinity weight on packs each +// template's sandboxes onto fewer nodes and raises how often a sandbox lands +// beside a same-build sibling — the sibling a shared read-only base +// (pmem+DAX) would collapse to one copy. Averaged over many seeds so the +// comparison does not ride on one sampling draw. +func TestTemplateAffinity_TightensColocation(t *testing.T) { + seeds := make([]int64, 24) + for i := range seeds { + seeds[i] = int64(i + 1) + } + + off := meanSpread(t, 0.0, seeds) + on := meanSpread(t, 0.6, seeds) + + t.Logf("weight 0.0: nodes_per_build=%.2f colocation=%.1f%%", off.avgNodesPerBuild, 100*off.colocationRate) + t.Logf("weight 0.6: nodes_per_build=%.2f colocation=%.1f%%", on.avgNodesPerBuild, 100*on.colocationRate) + + assert.Less(t, on.avgNodesPerBuild, off.avgNodesPerBuild, + "affinity should spread each build across fewer nodes") + assert.Greater(t, on.colocationRate, off.colocationRate, + "affinity should raise the same-build colocation rate") +} + +// TestTemplateAffinity_WeightRaisesColocation shows the weight is a usable +// knob: every positive setting colocates more than the off baseline, and the +// effect grows overall as the weight climbs. It is deliberately not asserted +// strictly monotone point to point — the discount interacts with best-of-K +// sampling, so an individual step can wobble while the trend holds. What an +// operator can rely on is the direction, which is what this pins. +func TestTemplateAffinity_WeightRaisesColocation(t *testing.T) { + seeds := make([]int64, 24) + for i := range seeds { + seeds[i] = int64(i + 1) + } + + baseline := meanSpread(t, 0.0, seeds).colocationRate + t.Logf("weight 0.0 (baseline): colocation=%.1f%%", 100*baseline) + + for _, w := range []float64{0.2, 0.4, 0.6} { + rate := meanSpread(t, w, seeds).colocationRate + t.Logf("weight %.1f: colocation=%.1f%%", w, 100*rate) + assert.Greater(t, rate, baseline, "every positive weight should colocate more than the off baseline") + } + + // The strongest mid setting should lift colocation by a clear margin, not + // a sampling-noise sliver, over off. + strong := meanSpread(t, 0.6, seeds).colocationRate + assert.Greater(t, strong, baseline+0.05, "a strong weight should raise colocation by a clear margin") +} diff --git a/packages/api/internal/orchestrator/placement/placement.go b/packages/api/internal/orchestrator/placement/placement.go index e53eea4a215..d16d2db39da 100644 --- a/packages/api/internal/orchestrator/placement/placement.go +++ b/packages/api/internal/orchestrator/placement/placement.go @@ -24,6 +24,21 @@ var tracer = otel.Tracer("github.com/e2b-dev/infra/packages/api/internal/orchest var createRefusals = sharedutils.Must(telemetry.GetCounter(otel.Meter("github.com/e2b-dev/infra/packages/api/internal/orchestrator/placement"), telemetry.ApiOrchestratorCreateRefusals)) +// placementMeter is shared by this package's placement-decision metrics. +var placementMeter = otel.Meter("github.com/e2b-dev/infra/packages/api/internal/orchestrator/placement") + +// templateAffinityPlacements counts same-build creates by whether the chosen +// node already ran an in-flight same-build sibling (effect: colocated | +// spread). It measures same-template colocation whether or not the affinity +// weight is on, so the weight-0 baseline is visible before node-local base +// sharing (pmem+DAX) is built and the lift is visible once it is raised. +var templateAffinityPlacements = sharedutils.Must(telemetry.GetCounter(placementMeter, telemetry.ApiOrchestratorTemplateAffinityPlacements)) + +// templateAffinitySiblings records, per placement, the in-flight same-build +// sibling count on the chosen node: the base-page copies a shared read-only +// base could collapse on that node (N siblings => N-1 redundant copies). +var templateAffinitySiblings = sharedutils.Must(telemetry.GetHistogram(placementMeter, telemetry.ApiOrchestratorTemplateAffinitySiblings)) + // PlacementResult carries the outcome of a placement attempt alongside the error. type PlacementResult struct { // Node is the node the sandbox was placed on, or nil on failure. @@ -128,6 +143,7 @@ func placeSandbox( CPUs: sbxRequest.GetSandbox().GetVcpu(), MiBMemory: sbxRequest.GetSandbox().GetRamMb(), HugePages: true, + BuildID: sbxRequest.GetSandbox().GetBuildId(), } var node *nodemanager.Node @@ -247,6 +263,9 @@ func placeSandbox( } chosen := node + // Measured before this sandbox inserts itself into the node's in-flight + // set, so a sandbox never counts itself as its own sibling. + sameBuildSiblings := node.PlacementMetrics.SameBuildInProgress(resources.BuildID) var missingCeiling string if !node.PlacementMetrics.StartPlacingIf(sbxRequest.GetSandbox().GetSandboxId(), resources, func() bool { ok, missing := MemoryAdmission(chosen, resources, requirements.Memory) @@ -284,6 +303,8 @@ func placeSandbox( // counts this sandbox exactly once. node.CompletePlacement(sbxRequest.GetSandbox().GetSandboxId(), resources) + recordTemplateAffinity(ctx, chosen, resources.BuildID, sameBuildSiblings) + return PlacementResult{Node: node, Response: resp, MissingHugepageCeiling: missingCeiling}, nil } @@ -360,6 +381,36 @@ func placeSandbox( return failed(SandboxCreateError{Attempts: attempt, LastErr: lastCreateErr}) } +// recordTemplateAffinity reports, for a same-build create, how same-template +// colocation turned out on the node that took it: a counter split +// colocated/spread and a histogram of the in-flight same-build siblings the +// node already held. siblings is the base-page copies a node-local shared +// read-only base (pmem+DAX) could collapse on that node (N siblings => N-1 +// redundant copies), so this is the go/no-go data for building that sharing +// and, once the affinity weight is on, the evidence it is colocating. +// Resumes and builds without a build_id are not same-template fan-out and are +// skipped, so the series is not diluted by placements sharing cannot help. +func recordTemplateAffinity(ctx context.Context, node *nodemanager.Node, buildID string, siblings int) { + if buildID == "" { + return + } + + effect := "spread" + if siblings > 0 { + effect = "colocated" + } + + templateAffinityPlacements.Add(ctx, 1, metric.WithAttributes(attribute.String("effect", effect))) + templateAffinitySiblings.Record(ctx, int64(siblings), metric.WithAttributes(telemetry.WithNodeID(node.ID))) + + logger.L().Debug(ctx, "Placed sandbox with template affinity", + logger.WithBuildID(buildID), + logger.WithNodeID(node.ID), + zap.Int("same_build_siblings", siblings), + zap.String("effect", effect), + ) +} + // createRefusedForGood reports a create the node refused with the typed // detail that says no other node and no retry changes the answer. func createRefusedForGood(st *status.Status) bool { diff --git a/packages/api/internal/orchestrator/placement/placement_best_of_K.go b/packages/api/internal/orchestrator/placement/placement_best_of_K.go index 4f9844f77d9..03aef89ceb2 100644 --- a/packages/api/internal/orchestrator/placement/placement_best_of_K.go +++ b/packages/api/internal/orchestrator/placement/placement_best_of_K.go @@ -21,6 +21,16 @@ type BestOfKConfig struct { K int // ScoreHugepages includes hugepage-pool load in the score (max of CPU and memory). ScoreHugepages bool + // TemplateAffinityWeight biases placement toward nodes already running + // sandboxes off the same build, so a future shared read-only base can be + // exercised (the sharing is node-local). 0 disables it: the score is then + // byte-for-byte the load-only score. The final score is multiplied by + // (1 - weight*min(sameBuild,cap)/cap), so affinity only reorders nodes that + // already pass admission and never outweighs real load. Keep it small. + TemplateAffinityWeight float64 + // TemplateAffinityCap caps how many same-build sandboxes count toward the + // discount. Ignored when TemplateAffinityWeight is 0. + TemplateAffinityCap int } // DefaultBestOfKConfig returns the default placement configuration @@ -30,6 +40,9 @@ func DefaultBestOfKConfig() BestOfKConfig { K: 3, Alpha: 0.5, ScoreHugepages: true, + // Affinity off by default: zero behavior change until an operator opts in. + TemplateAffinityWeight: 0, + TemplateAffinityCap: 8, } } @@ -42,11 +55,15 @@ func (b *BestOfK) Score(node *nodemanager.Node, resources nodemanager.SandboxRes // Get locally recorded resources that haven't been reported yet. pendingCPUs := int64(0) pendingMiB := int64(0) + sameBuild := 0 for _, res := range node.PlacementMetrics.InProgress() { pendingCPUs += res.CPUs if res.HugePages { pendingMiB += res.MiBMemory } + if resources.BuildID != "" && res.BuildID == resources.BuildID { + sameBuild++ + } } // to avoid division by zero @@ -67,11 +84,32 @@ func (b *BestOfK) Score(node *nodemanager.Node, resources nodemanager.SandboxRes cpuScore := (cpuRequested + float64(reserved) + config.Alpha*busyCPUs) / totalCapacity - if !config.ScoreHugepages { - return cpuScore + loadScore := cpuScore + if config.ScoreHugepages { + loadScore = max(cpuScore, memoryScore(metrics, resources, pendingMiB, config)) } - return max(cpuScore, memoryScore(metrics, resources, pendingMiB, config)) + return applyTemplateAffinity(loadScore, sameBuild, config) +} + +// applyTemplateAffinity lowers the load score for nodes already running +// same-build sandboxes, so equally-loaded candidates that can share a +// read-only base are preferred. It is a no-op when the weight is 0 (the score +// is returned unchanged), and multiplicative so it reorders without ever +// overriding real load: a busy node's high base score stays high. The count +// is capped so affinity cannot pull an unbounded pile onto one node. +func applyTemplateAffinity(loadScore float64, sameBuild int, config BestOfKConfig) float64 { + if config.TemplateAffinityWeight <= 0 || sameBuild <= 0 { + return loadScore + } + cap := config.TemplateAffinityCap + if cap <= 0 { + return loadScore + } + if sameBuild > cap { + sameBuild = cap + } + return loadScore * (1 - config.TemplateAffinityWeight*float64(sameBuild)/float64(cap)) } // memoryScore is the CPU score's shape over the hugepage pool, where sandbox diff --git a/packages/api/internal/orchestrator/placement/template_affinity_test.go b/packages/api/internal/orchestrator/placement/template_affinity_test.go new file mode 100644 index 00000000000..016e1697fab --- /dev/null +++ b/packages/api/internal/orchestrator/placement/template_affinity_test.go @@ -0,0 +1,100 @@ +package placement + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/e2b-dev/infra/packages/api/internal/api" + "github.com/e2b-dev/infra/packages/api/internal/orchestrator/nodemanager" +) + +func TestApplyTemplateAffinity(t *testing.T) { + t.Parallel() + + const load = 0.4 + + tests := []struct { + name string + weight float64 + cap int + sameBuild int + want float64 + }{ + {name: "weight zero is a no-op", weight: 0, cap: 8, sameBuild: 5, want: load}, + {name: "no siblings is a no-op", weight: 0.1, cap: 8, sameBuild: 0, want: load}, + {name: "non-positive cap is a no-op", weight: 0.1, cap: 0, sameBuild: 5, want: load}, + {name: "one sibling discounts by weight/cap", weight: 0.2, cap: 8, sameBuild: 1, want: load * (1 - 0.2*1.0/8.0)}, + {name: "siblings at cap discount by full weight", weight: 0.2, cap: 8, sameBuild: 8, want: load * (1 - 0.2)}, + {name: "siblings past cap do not discount further", weight: 0.2, cap: 8, sameBuild: 100, want: load * (1 - 0.2)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + config := BestOfKConfig{TemplateAffinityWeight: tt.weight, TemplateAffinityCap: tt.cap} + got := applyTemplateAffinity(load, tt.sameBuild, config) + assert.InDelta(t, tt.want, got, 1e-9) + }) + } +} + +// A discounted score must never drop below zero or reorder past a genuinely +// empty node: the discount is a fraction of a non-negative load. +func TestApplyTemplateAffinity_NeverNegative(t *testing.T) { + t.Parallel() + config := BestOfKConfig{TemplateAffinityWeight: 0.99, TemplateAffinityCap: 4} + got := applyTemplateAffinity(0.001, 4, config) + assert.GreaterOrEqual(t, got, 0.0) +} + +func TestSameBuildInProgress(t *testing.T) { + t.Parallel() + + node := nodemanager.NewTestNode("n", api.NodeStatusReady, 2, 8) + node.PlacementMetrics.StartPlacingIf("a", nodemanager.SandboxResources{BuildID: "build-1"}, func() bool { return true }) + node.PlacementMetrics.StartPlacingIf("b", nodemanager.SandboxResources{BuildID: "build-1"}, func() bool { return true }) + node.PlacementMetrics.StartPlacingIf("c", nodemanager.SandboxResources{BuildID: "build-2"}, func() bool { return true }) + node.PlacementMetrics.StartPlacingIf("d", nodemanager.SandboxResources{BuildID: ""}, func() bool { return true }) + + assert.Equal(t, 2, node.PlacementMetrics.SameBuildInProgress("build-1")) + assert.Equal(t, 1, node.PlacementMetrics.SameBuildInProgress("build-2")) + assert.Equal(t, 0, node.PlacementMetrics.SameBuildInProgress("build-missing")) + assert.Equal(t, 0, node.PlacementMetrics.SameBuildInProgress(""), "empty build counts nothing") +} + +// With affinity on, a node already running same-build siblings scores lower +// (better) than an identical node with none, while a weight of 0 ties them. +func TestScore_TemplateAffinityPrefersSameBuild(t *testing.T) { + t.Parallel() + + resources := nodemanager.SandboxResources{CPUs: 1, MiBMemory: 512, BuildID: "build-1"} + + newNode := func(id string) *nodemanager.Node { + n := nodemanager.NewTestNode(id, api.NodeStatusReady, 2, 8, emptyHugePool()) + n.PlacementMetrics.StartPlacingIf(id+"-sib", nodemanager.SandboxResources{CPUs: 1, MiBMemory: 512, HugePages: true, BuildID: "build-1"}, func() bool { return true }) + return n + } + + withSibling := newNode("with") + bare := nodemanager.NewTestNode("bare", api.NodeStatusReady, 2, 8, emptyHugePool()) + // Match the sibling's load on the bare node with a different build, so only + // the build identity differs between the two candidates. + bare.PlacementMetrics.StartPlacingIf("bare-other", nodemanager.SandboxResources{CPUs: 1, MiBMemory: 512, HugePages: true, BuildID: "other"}, func() bool { return true }) + + off := BestOfKConfig{R: 4, K: 3, Alpha: 0.5, ScoreHugepages: true, TemplateAffinityWeight: 0, TemplateAffinityCap: 8} + on := off + on.TemplateAffinityWeight = 0.2 + + algo := NewBestOfK(off).(*BestOfK) + + offWith := algo.Score(withSibling, resources, off) + offBare := algo.Score(bare, resources, off) + require.InDelta(t, offBare, offWith, 1e-9, "weight 0 ties identical loads") + + onWith := algo.Score(withSibling, resources, on) + onBare := algo.Score(bare, resources, on) + assert.Less(t, onWith, onBare, "affinity makes the same-build node score better") + assert.InDelta(t, offBare, onBare, 1e-9, "a node with no same-build sibling is unchanged by affinity") +} diff --git a/packages/shared/pkg/featureflags/flags.go b/packages/shared/pkg/featureflags/flags.go index 3475b1377a0..5097d87c639 100644 --- a/packages/shared/pkg/featureflags/flags.go +++ b/packages/shared/pkg/featureflags/flags.go @@ -706,9 +706,13 @@ var ( ClickhouseBatcherMaxBatchSize = NewIntFlag("clickhouse-batcher-max-batch-size", 1000) ClickhouseBatcherMaxDelay = NewIntFlag("clickhouse-batcher-max-delay", 1000) // 1s in milliseconds ClickhouseBatcherQueueSize = NewIntFlag("clickhouse-batcher-queue-size", 1000) - BestOfKSampleSize = NewIntFlag("best-of-k-sample-size", 3) // Default K=3 - BestOfKMaxOvercommit = NewIntFlag("best-of-k-max-overcommit", 400) // Default R=4 (stored as percentage, max over-commit ratio) - BestOfKAlpha = NewIntFlag("best-of-k-alpha", 50) // Default Alpha=0.5 (stored as percentage for int flag, current usage weight) + BestOfKSampleSize = NewIntFlag("best-of-k-sample-size", 3) // Default K=3 + BestOfKMaxOvercommit = NewIntFlag("best-of-k-max-overcommit", 400) // Default R=4 (stored as percentage, max over-commit ratio) + BestOfKAlpha = NewIntFlag("best-of-k-alpha", 50) // Default Alpha=0.5 (stored as percentage for int flag, current usage weight) + // BestOfKTemplateAffinityWeight biases placement toward nodes already running same-build sandboxes, so a future node-local shared read-only base (pmem+DAX) has siblings to share with. Stored as a percentage; the load score is multiplied by (1 - weight*min(sameBuild,cap)/cap), so it only reorders nodes that already pass admission. 0 (default) disables it: zero behaviour change. + BestOfKTemplateAffinityWeight = NewIntFlag("best-of-k-template-affinity-weight", 0) + // BestOfKTemplateAffinityCap caps how many same-build sandboxes on a node count toward the affinity discount, so affinity cannot pull an unbounded pile onto one node. Ignored when the weight is 0. + BestOfKTemplateAffinityCap = NewIntFlag("best-of-k-template-affinity-cap", 8) PlacementHugepageLimitPercent = NewIntFlag("placement-hugepage-limit-percent", 0) // Share of a node's hugepage pool ceiling placement may commit (of its memory outside the pool, for a sandbox without hugepages); 0 disables the check PlacementMemoryMaxOvercommit = NewIntFlag("placement-memory-max-overcommit", 0) // Template RAM of a node's sandboxes as a percentage of its base hugepage pool (its total memory, for a sandbox without hugepages), past which placement refuses; 0 disables the check EnvdInitTimeoutMilliseconds = NewIntFlag("envd-init-request-timeout-milliseconds", 50) // Timeout for envd init request in milliseconds diff --git a/packages/shared/pkg/telemetry/meters.go b/packages/shared/pkg/telemetry/meters.go index db96ca41067..fe6012088bc 100644 --- a/packages/shared/pkg/telemetry/meters.go +++ b/packages/shared/pkg/telemetry/meters.go @@ -52,6 +52,14 @@ const ( // node.id and reason: no_capacity (the orchestrator reports no pool // ceiling) | no_page_size. The limit was a no-op for that placement. ApiOrchestratorPlacementsWithoutHugepageCeiling CounterType = "api.orchestrator.placements_without_hugepage_ceiling" + // ApiOrchestratorTemplateAffinityPlacements counts same-build placements by + // whether the chosen node already ran an in-flight same-build sibling, so + // same-template colocation can be measured before node-local base sharing + // (pmem+DAX) is built. Recorded whether or not the affinity weight is on, + // so the weight-0 baseline and the lift once it is raised are both visible. + // effect: colocated (>=1 sibling) | spread (none). Only same-build creates + // (non-empty build_id) are counted; resumes are not. + ApiOrchestratorTemplateAffinityPlacements CounterType = "api.orchestrator.template_affinity_placements" // ApiSandboxListReads counts sandbox list requests by team and by how the // team's store read was served: disabled (no lag allowed, own read) | read // (started the shared read) | shared (joined one in flight) | hit (a live @@ -539,7 +547,11 @@ const ( NetworkEgressRetirementDurationName HistogramType = "orchestrator.network.egress.retirement.duration" OrchestratorBlockCachePunchDuration HistogramType = "orchestrator.block.cache.punch.duration" - OrchestratorBlockCacheCloseDuration HistogramType = "orchestrator.block.cache.close.duration" + // ApiOrchestratorTemplateAffinitySiblings records, per placement, how many + // in-flight same-build siblings the chosen node already had: the base-page + // copies a node-local shared read-only base (pmem+DAX) could collapse there. + ApiOrchestratorTemplateAffinitySiblings HistogramType = "api.orchestrator.template_affinity_siblings" + OrchestratorBlockCacheCloseDuration HistogramType = "orchestrator.block.cache.close.duration" // Sandbox timing histograms OrchestratorSandboxCreateDurationName HistogramType = "orchestrator.sandbox.create.duration"