Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions packages/api/internal/orchestrator/orchestrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
Original file line number Diff line number Diff line change
@@ -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")
}
Original file line number Diff line number Diff line change
@@ -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")
}
Loading