Skip to content
Closed
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
1 change: 1 addition & 0 deletions cmd/duckgres-controlplane/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,7 @@ func main() {
ServiceAccount: resolved.K8sWorkerServiceAccount,
WorkerCPURequest: resolved.K8sWorkerCPURequest,
WorkerMemoryRequest: resolved.K8sWorkerMemoryRequest,
WorkerMemoryRequestPercent: resolved.K8sWorkerMemoryRequestPercent,
WorkerNodeSelector: resolved.K8sWorkerNodeSelector,
WorkerTolerationKey: resolved.K8sWorkerTolerationKey,
WorkerTolerationValue: resolved.K8sWorkerTolerationValue,
Expand Down
10 changes: 10 additions & 0 deletions configresolve/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ type Resolved struct {
K8sWorkerServiceAccount string
K8sWorkerCPURequest string
K8sWorkerMemoryRequest string
K8sWorkerMemoryRequestPercent int
K8sWorkerNodeSelector string
K8sWorkerTolerationKey string
K8sWorkerTolerationValue string
Expand Down Expand Up @@ -208,6 +209,7 @@ func ResolveEffective(fileCfg *configloader.FileConfig, cli CLIInputs, getenv fu
var k8sWorkerSecret, k8sWorkerConfigMap, k8sWorkerImagePullPolicy string
k8sWorkerServiceAccount := controlplane.DefaultK8sWorkerServiceAccount
var k8sWorkerCPURequest, k8sWorkerMemoryRequest string
var k8sWorkerMemoryRequestPercent int
var k8sWorkerNodeSelector, k8sWorkerTolerationKey, k8sWorkerTolerationValue string
var k8sReshardPodCPU, k8sReshardPodMemory string
var k8sExploratoryTierEnabled bool
Expand Down Expand Up @@ -807,6 +809,13 @@ func ResolveEffective(fileCfg *configloader.FileConfig, cli CLIInputs, getenv fu
if v := getenv("DUCKGRES_K8S_WORKER_MEMORY_REQUEST"); v != "" {
k8sWorkerMemoryRequest = v
}
if v := getenv("DUCKGRES_K8S_WORKER_MEMORY_REQUEST_PERCENT"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= controlplane.MinWorkerMemoryRequestPercent && n <= 100 {
k8sWorkerMemoryRequestPercent = n
} else {
warn("Invalid DUCKGRES_K8S_WORKER_MEMORY_REQUEST_PERCENT (want " + strconv.Itoa(controlplane.MinWorkerMemoryRequestPercent) + "-100): " + v)
}
}
if v := getenv("DUCKGRES_K8S_WORKER_NODE_SELECTOR"); v != "" {
k8sWorkerNodeSelector = v
}
Expand Down Expand Up @@ -1196,6 +1205,7 @@ func ResolveEffective(fileCfg *configloader.FileConfig, cli CLIInputs, getenv fu
K8sWorkerServiceAccount: k8sWorkerServiceAccount,
K8sWorkerCPURequest: k8sWorkerCPURequest,
K8sWorkerMemoryRequest: k8sWorkerMemoryRequest,
K8sWorkerMemoryRequestPercent: k8sWorkerMemoryRequestPercent,
K8sWorkerNodeSelector: k8sWorkerNodeSelector,
K8sWorkerTolerationKey: k8sWorkerTolerationKey,
K8sWorkerTolerationValue: k8sWorkerTolerationValue,
Expand Down
31 changes: 31 additions & 0 deletions configresolve/resolve_k8s_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,37 @@ func TestResolveEffectiveRejectsInvalidClientIdleTimeoutMax(t *testing.T) {
}
}

func TestResolveEffectiveK8sWorkerMemoryRequestPercent(t *testing.T) {
for _, tc := range []struct {
value string
want int
warns int
}{
{"", 0, 0},
{"75", 75, 0},
{"100", 100, 0},
{"74", 0, 1},
{"101", 0, 1},
{"75%", 0, 1},
} {
t.Run(tc.value, func(t *testing.T) {
var warned []string
resolved := ResolveEffective(nil, CLIInputs{}, func(key string) string {
if key == "DUCKGRES_K8S_WORKER_MEMORY_REQUEST_PERCENT" {
return tc.value
}
return ""
}, func(msg string) { warned = append(warned, msg) })
if resolved.K8sWorkerMemoryRequestPercent != tc.want {
t.Fatalf("K8sWorkerMemoryRequestPercent = %d, want %d", resolved.K8sWorkerMemoryRequestPercent, tc.want)
}
if len(warned) != tc.warns {
t.Fatalf("warnings = %v, want %d", warned, tc.warns)
}
})
}
}

func TestResolveEffectiveParsesK8sWorkerDefaultTTL(t *testing.T) {
resolved := ResolveEffective(nil, CLIInputs{}, func(key string) string {
if key == "DUCKGRES_K8S_WORKER_DEFAULT_TTL" {
Expand Down
5 changes: 5 additions & 0 deletions controlplane/control.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,11 @@ type K8sConfig struct {
WorkerPriorityClassName string // PriorityClass for worker pods, so they preempt overprovision headroom pause pods (empty = none)
AWSRegion string // AWS region for STS client

// WorkerMemoryRequestPercent sets the memory request of large worker pods as
// a percent of their memory limit (env-only
// DUCKGRES_K8S_WORKER_MEMORY_REQUEST_PERCENT). 0 or 100 = equal to the limit.
WorkerMemoryRequestPercent int

// Reshard runner pod shape (env-only DUCKGRES_RESHARD_POD_CPU /
// DUCKGRES_RESHARD_POD_MEMORY; requests=limits, Guaranteed QoS). Empty =
// built-in defaults (2 CPU / 8Gi). Reshard ops run in dedicated per-op
Expand Down
3 changes: 2 additions & 1 deletion controlplane/headroom.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,8 @@ func (p *K8sWorkerPool) headroomTarget(ctx context.Context) (headroomPlan, bool)
slog.Warn("Headroom: invalid default worker memory for placeholder sizing.", "value", p.workerMemoryRequest, "error", err)
return headroomPlan{}, false
}
memBytes = q.Value()
req := p.workerMemoryRequestForLimit(q)
memBytes = req.Value()
}
plan.cpu = *resource.NewMilliQuantity(cpuMillis, resource.DecimalSI)
plan.mem = *resource.NewQuantity(memBytes, resource.BinarySI)
Expand Down
21 changes: 21 additions & 0 deletions controlplane/headroom_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,27 @@ func TestReconcileHeadroomFreshClusterFallsBackToDefaultShape(t *testing.T) {
}
}

// The configured fallback shape reserves what a real worker of that shape
// requests, so it follows the lowered memory request of a large worker.
func TestReconcileHeadroomFallbackUsesWorkerMemoryRequest(t *testing.T) {
cs := fake.NewSimpleClientset()
emulateGenerateName(cs)
p := newHeadroomPool(cs, &fakeSpawnLogStore{})
p.workerCPURequest = "15"
p.workerMemoryRequest = "120Gi"
p.workerMemoryRequestPercent = 75

p.reconcileHeadroom(context.Background())

pods := listHeadroomPods(t, cs)
if len(pods) != 1 {
t.Fatalf("expected 1 placeholder, got %d", len(pods))
}
if got := pods[0].Spec.Containers[0].Resources.Requests.Memory().Value(); got != 90<<30 {
t.Fatalf("placeholder memory request = %d, want 90Gi", got)
}
}

// The fleet-relative cap bounds a spawn storm: peak burst 50 with 20 live
// workers is capped at ceil(25% × 20) = 5 — fleet size is the CEILING, never
// the target, so a big fleet alone (peak 0) still gets only the floor.
Expand Down
4 changes: 4 additions & 0 deletions controlplane/k8s_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,9 @@ type K8sWorkerPool struct {
workerTolerationValue string // taint value for NoSchedule toleration
workerPriorityClassName string // PriorityClass for worker pods (preempts overprovision pause pods)

// Memory request of large workers as a percent of the limit; 0 = equal to the limit.
workerMemoryRequestPercent int

// Headroom controller holds preemptible low-priority placeholder pods so a
// worker spawn schedules immediately (preempting a placeholder) instead of
// waiting on a fresh Karpenter node. Slot count and size are derived
Expand Down Expand Up @@ -202,6 +205,7 @@ func newK8sWorkerPool(cfg K8sWorkerPoolConfig, clientset kubernetes.Interface) (
workerTolerationValue: cfg.WorkerTolerationValue,
workerPriorityClassName: cfg.WorkerPriorityClassName,

workerMemoryRequestPercent: cfg.WorkerMemoryRequestPercent,
placeholderImage: cfg.PlaceholderImage,
placeholderPriorityClassName: cfg.PlaceholderPriorityClassName,

Expand Down
40 changes: 32 additions & 8 deletions controlplane/k8s_pool_spawn.go
Original file line number Diff line number Diff line change
Expand Up @@ -533,8 +533,8 @@ func (p *K8sWorkerPool) spawnReservedWorkerForSlot(ctx context.Context, id int,

// workerResources returns resource requests and limits for a worker pod.
// Set via DUCKGRES_K8S_WORKER_CPU_REQUEST / DUCKGRES_K8S_WORKER_MEMORY_REQUEST.
// Returns empty (BestEffort) if neither is set.
// When set, limits are equal to requests (Guaranteed QoS).
// Limits are equal to requests (Guaranteed QoS), except for the memory request
// of a large worker when workerMemoryRequestPercent is below 100.
func (p *K8sWorkerPool) workerResources() corev1.ResourceRequirements {
return p.workerResourcesForProfile(WorkerProfile{})
}
Expand Down Expand Up @@ -650,11 +650,12 @@ func (p *K8sWorkerPool) workerPodEnv(secretName string, workerResources corev1.R
}

// workerMemoryHygieneEnv derives the memory/thread env vars for a worker pod
// from its resolved resource requests. See the call site comment in
// spawnWorker for why these must be set before any session exists.
// from its resolved resources. Memory comes from the limit (the pod cgroup):
// the request can be lower, see workerMemoryRequestPercent. See the call site
// comment in spawnWorker for why these must be set before any session exists.
func workerMemoryHygieneEnv(res corev1.ResourceRequirements) []corev1.EnvVar {
var env []corev1.EnvVar
if mem, ok := res.Requests[corev1.ResourceMemory]; ok {
if mem, ok := res.Limits[corev1.ResourceMemory]; ok {
memBytes := uint64(mem.Value())
if lim := duckdbMemoryLimitForPodMemory(memBytes); lim != "" {
env = append(env, corev1.EnvVar{Name: "DUCKGRES_MEMORY_LIMIT", Value: lim})
Expand All @@ -674,9 +675,10 @@ func workerMemoryHygieneEnv(res corev1.ResourceRequirements) []corev1.EnvVar {
// workerResourcesForProfile builds the pod resource requirements for a worker of
// the given profile: the profile's CPU/Memory when set, otherwise the pool-global
// request (today's behavior). Requests are mirrored to Limits so the pod is
// Guaranteed QoS — required before bin-packing colocated workers. A colocated
// profile always carries non-empty CPU/Memory (resolver-enforced), so it never
// degrades to BestEffort.
// Guaranteed QoS — required before bin-packing colocated workers. The one
// exception is the memory request of a large worker, which
// workerMemoryRequestPercent can lower. A colocated profile always carries
// non-empty CPU/Memory (resolver-enforced), so it never degrades to BestEffort.
func (p *K8sWorkerPool) workerResourcesForProfile(profile WorkerProfile) corev1.ResourceRequirements {
// Workers must never be BestEffort: with no pod anti-affinity, resource
// requests are the ONLY thing keeping two workers from overcommitting a
Expand Down Expand Up @@ -706,5 +708,27 @@ func (p *K8sWorkerPool) workerResourcesForProfile(profile WorkerProfile) corev1.
for k, v := range requests {
limits[k] = v.DeepCopy()
}
memLimit := limits[corev1.ResourceMemory]
requests[corev1.ResourceMemory] = p.workerMemoryRequestForLimit(memLimit)
return corev1.ResourceRequirements{Requests: requests, Limits: limits}
}

// workerMemoryRequestPercentMinBytes is the smallest worker memory limit that
// WorkerMemoryRequestPercent applies to.
const workerMemoryRequestPercentMinBytes = 64 << 30

// workerMemoryRequestForLimit returns the memory request of a worker pod with
// the given memory limit: workerMemoryRequestPercent of the limit for a large
// worker, and the limit itself for every other worker.
//
// DuckDB's memory_limit is at most 75% of the pod (workerMemoryHeadroomBytes),
// so a request of at least MinWorkerMemoryRequestPercent still reserves all of
// it. Only the headroom above memory_limit is shared between the workers of a
// node. Small workers are excluded: they use most of their headroom.
func (p *K8sWorkerPool) workerMemoryRequestForLimit(limit resource.Quantity) resource.Quantity {
pct := int64(p.workerMemoryRequestPercent)
if pct < MinWorkerMemoryRequestPercent || pct >= 100 || limit.Value() < workerMemoryRequestPercentMinBytes {
return limit.DeepCopy()
}
return *resource.NewQuantity(limit.Value()*pct/100, resource.BinarySI)
}
58 changes: 57 additions & 1 deletion controlplane/k8s_pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3356,6 +3356,54 @@ func TestWorkerResources_NeitherSet(t *testing.T) {
}
}

// A lowered memory request applies to large workers only. Their limit and their
// CPU stay as they are, and every other worker keeps Guaranteed QoS.
func TestWorkerResources_MemoryRequestPercent(t *testing.T) {
cases := []struct {
name string
percent int
memory string
want string
}{
{"unset keeps request equal to limit", 0, "360Gi", "360Gi"},
{"100 keeps request equal to limit", 100, "360Gi", "360Gi"},
{"below the minimum is ignored", 50, "360Gi", "360Gi"},
{"75 percent of a large worker", 75, "360Gi", "270Gi"},
{"75 percent of the pool default", 75, "120Gi", "90Gi"},
{"smallest large worker", 75, "64Gi", "48Gi"},
{"small worker keeps request equal to limit", 75, "32Gi", "32Gi"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
pool := &K8sWorkerPool{workerMemoryRequestPercent: tc.percent}
res := pool.workerResourcesForProfile(WorkerProfile{CPU: "32", Memory: tc.memory})
if got, want := res.Requests.Memory().Value(), resource.MustParse(tc.want); got != want.Value() {
t.Fatalf("memory request = %d, want %s", got, tc.want)
}
if got, want := res.Limits.Memory().Value(), resource.MustParse(tc.memory); got != want.Value() {
t.Fatalf("memory limit = %d, want %s", got, tc.memory)
}
if req, lim := res.Requests.Cpu(), res.Limits.Cpu(); req.Cmp(*lim) != 0 || req.String() != "32" {
t.Fatalf("cpu request/limit = %s/%s, want 32/32", req, lim)
}
})
}
}

// The request must always cover DuckDB's memory_limit. Only the headroom above
// it can be shared between the workers of a node.
func TestWorkerMemoryRequestCoversDuckDBMemoryLimit(t *testing.T) {
pool := &K8sWorkerPool{workerMemoryRequestPercent: MinWorkerMemoryRequestPercent}
for gib := int64(1); gib <= 512; gib++ {
limit := *resource.NewQuantity(gib<<30, resource.BinarySI)
req := pool.workerMemoryRequestForLimit(limit)
duckDB := uint64(limit.Value()) - workerMemoryHeadroomBytes(uint64(limit.Value()))
if uint64(req.Value()) < duckDB {
t.Fatalf("%dGi worker: request %d is below the DuckDB memory_limit %d", gib, req.Value(), duckDB)
}
}
}

func TestSetWorkerResources(t *testing.T) {
pool := &K8sWorkerPool{
workerCPURequest: "500m",
Expand Down Expand Up @@ -4557,7 +4605,12 @@ func TestWorkerMemoryHygieneEnv(t *testing.T) {
if mem != "" {
req[corev1.ResourceMemory] = resource.MustParse(mem)
}
return corev1.ResourceRequirements{Requests: req}
return corev1.ResourceRequirements{Requests: req, Limits: req}
}
lowRequest := mk("32", "360Gi")
lowRequest.Requests = corev1.ResourceList{
corev1.ResourceCPU: resource.MustParse("32"),
corev1.ResourceMemory: resource.MustParse("270Gi"),
}
cases := []struct {
name string
Expand All @@ -4576,6 +4629,9 @@ func TestWorkerMemoryHygieneEnv(t *testing.T) {
// "4GB" here would turn the 40% reserve into 50%.
{"fractional-GiB budget is not truncated to whole GB", mk("4", "8Gi"), map[string]string{
"DUCKGRES_MEMORY_LIMIT": "4915MB", "GOMEMLIMIT": "1024MiB", "DUCKGRES_THREADS": "10"}},
// Memory sizing follows the limit (the pod cgroup), not a lowered request.
{"request below limit", lowRequest, map[string]string{
"DUCKGRES_MEMORY_LIMIT": "270GB", "GOMEMLIMIT": "46080MiB", "DUCKGRES_THREADS": "80"}},
{"no requests -> no env", corev1.ResourceRequirements{}, map[string]string{}},
}
for _, tc := range cases {
Expand Down
1 change: 1 addition & 0 deletions controlplane/multitenant.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ func SetupMultiTenant(
ServiceAccount: cfg.K8s.ServiceAccount,
WorkerCPURequest: cfg.K8s.WorkerCPURequest,
WorkerMemoryRequest: cfg.K8s.WorkerMemoryRequest,
WorkerMemoryRequestPercent: cfg.K8s.WorkerMemoryRequestPercent,
WorkerNodeSelector: parseNodeSelector(cfg.K8s.WorkerNodeSelector),
WorkerTolerationKey: cfg.K8s.WorkerTolerationKey,
WorkerTolerationValue: cfg.K8s.WorkerTolerationValue,
Expand Down
7 changes: 7 additions & 0 deletions controlplane/worker_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import (
)

const DefaultK8sWorkerServiceAccount = "duckgres-worker"

// MinWorkerMemoryRequestPercent is the lowest accepted memory request of a
// worker pod, as a percent of its memory limit. It equals the largest share of
// a pod that DuckDB's memory_limit can take, so the request always covers it.
const MinWorkerMemoryRequestPercent = 75

const DefaultWorkerSpawnRetryAfter = 45 * time.Second

// WorkerCapacityExhaustedError is returned when a worker can't be acquired
Expand Down Expand Up @@ -120,6 +126,7 @@ type K8sWorkerPoolConfig struct {
ServiceAccount string // ServiceAccount name for worker pods (default: "duckgres-worker")
WorkerCPURequest string // CPU request for worker pods (e.g., "500m"). Empty = BestEffort.
WorkerMemoryRequest string // Memory request for worker pods (e.g., "1Gi"). Empty = BestEffort.
WorkerMemoryRequestPercent int // Memory request of large worker pods as a percent of the memory limit. 0 or 100 = equal to the limit.
WorkerNodeSelector map[string]string // Node selector for worker pods. Nil = no selector.
WorkerTolerationKey string // Taint key for worker pod NoSchedule toleration. Empty = no toleration.
WorkerTolerationValue string // Taint value for worker pod NoSchedule toleration.
Expand Down
2 changes: 1 addition & 1 deletion docs/design/connection-string-worker-profile.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ options=-c duckgres.worker_tier=backfill # ergonomic alias = {cpu, mem, c
- **`WorkerProfile{CPU, Memory, Colocate, NodeSelector}` is a new match dimension on `WorkerAssignment`**, orthogonal to the per-org `Image` axis — NOT folded into the image string. Pod resources/nodeSelector/anti-affinity are pool-global mutable state today, so the profile must travel per-acquisition. A reserved/warm worker may only be handed to a request whose profile `Equal()`s it; absent profile = the **default** profile, never "any".
- **Default profile normalizes to empty CPU/Memory + `Colocate=false`** (NOT literal 46/360). The pool-global request applies for empty fields. This keeps pre-existing `worker_records` rows (`"","",false`) claimable with no migration `UPDATE`.
- **Runtime-store delta: additive GORM columns, no `.sql` migration** (`worker_records` is AutoMigrated on boot). Adds `ProfileCPU`, `ProfileMemory`, `ProfileColocate` + composite index.
- **Guaranteed QoS already holds** (`workerResources()` copies requests→limits) and MUST be preserved; colocated profiles are always non-empty (clamped 4/16) so they never schedule BestEffort.
- **Guaranteed QoS already holds** (`workerResources()` copies requests→limits) and MUST be preserved by default. `DUCKGRES_K8S_WORKER_MEMORY_REQUEST_PERCENT` is the one opt-in exception: it lowers the memory request of workers of 64Gi or more, never below DuckDB's `memory_limit`; colocated profiles are always non-empty (clamped 4/16) so they never schedule BestEffort.
- **Wire-supplied cpu/mem are clamped to `[min,max]`, behind a per-deployment gate, and accounted against a per-org resource quota** (count-based `maxWorkers` is insufficient when pods vary ~50×). Explicit `colocate=false` is separately gated (a full node is the expensive button).
- **Warmth = a shape-aware colocated warm pool + node headroom.** Each configured colocated shape (e.g. 4/16 and 8/48) is kept warm to its own target, background-replenished and topped up on claim; on top of that, overprovision pause pods on the bin-pack nodepool hold node headroom so a burst beyond the warm pool schedules without a fresh Karpenter node. Worker pods carry a PriorityClass above the pause pods so they preempt the headroom. The client's deepened `connect_timeout` + retry absorbs any residual cold-node latency.

Expand Down
2 changes: 1 addition & 1 deletion docs/design/worker-ttl-pool.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ only) it:
spawn-storm bug's placeholder cost. Fleet size is only the CEILING, never
the target — an idle-worker leak cannot pull the placeholder count up (the
amplification failure of the retired demand-proportional mode);
- slot SIZE = the componentwise max worker shape spawned in the last 7 days,
- slot SIZE = the componentwise max of the worker requests spawned in the last 7 days,
falling back to the live fleet's max shape, then to the pool's
configured/default worker request (fresh empty cluster). Client-sized (GUC)
workers can exceed any configured maximum, so sizing from observed spawns is
Expand Down
Loading
Loading