Repository navigation
Add resource limits for environment build jobs - #494
Conversation
✅ Deploy Preview for nebi-docs ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
@MUFFANUJ There's some failing CI jobs. Could you look into them? |
tylerpotts
left a comment
There was a problem hiding this comment.
Summary
This PR substantially addresses #453: body caps and server timeouts, per-user/per-workspace/global admission quotas with fair scheduling, per-job wall-clock deadlines, OS-level resource budgets, cleanup, and durable metrics. The admission-control design is solid (job creation inside a transaction that takes the admission lock, validates, checks quotas, and writes job + audit atomically, with enqueue after commit and a compensating MarkFailed), and test quality is high across the new packages. Verified locally: builds clean, go vet clean, new package test suites pass.
Recommendation: request changes. Blockers 2 and 4 are small surgical fixes. Blocker 1 proposes cutting the cgroup enforcement from this PR and handling it in a follow-up issue; Blocker 3 needs a migration/reaper decision.
Blockers
1. Drop the cgroup-based enforcement from this PR; defer memory/pids budgets to a job-isolation follow-up
internal/limits/limits.go:65-72 enables CPU/memory/process budgets by default on Linux, and internal/process/command_unix.go:58-105 enforces them by creating a cgroup directly under /sys/fs/cgroup, writing memory.max/pids.max, and polling cpu.stat from an awk monitor loop. Every failure path exits 125 and fails the job.
In the primary deployment target (Kubernetes/Docker) this cannot work as written: unprivileged containers mount /sys/fs/cgroup read-only, and even privileged containers hit cgroup v2's "no internal processes" rule because the script never evacuates the root group before enabling controllers. On a stock containerized deployment, every build job fails out of the box. The PR's own CI is the evidence: the "disable e2e process limits" commit exists because e2e hit exactly this. So as shipped, the cgroup path is a landmine on the platforms that matter and dead code everywhere else, and it's also the least-tested code in the PR (covered only by unit tests that string-match the generated shell script, since e2e disables it).
Suggested change: remove linuxCgroupLimitScript and the job_memory_bytes/job_processes config keys, and enforce job_cpu_seconds via the portable ulimit -t path (already present for non-Linux) on all platforms. That keeps CPU and file-size budgets working unprivileged in any container, keeps the wall-clock deadline and storage walker (which already satisfy "jobs exceeding wall-clock or resource budgets are terminated and cleaned up" from the issue), and deletes the riskiest ~100 lines of generated shell plus the disableProcessLimitsForE2E() workaround.
The issue's remediation bullet reads "enforce CPU/memory/process/ephemeral-storage limits in isolated jobs", and this PR doesn't isolate jobs; builds run inside the shared worker. Per-job memory/pids containment is better delivered by actual isolation (e.g. per-job pods with pod-level resource limits, where the kubelet does the cgroup work with proper authorization) than by retrofitting cgroup scripts into a shared process. Suggest filing a follow-up issue for that and linking it here, so the scope cut is explicit rather than silent. In the interim, pod-level limits plus the admission quotas bound the blast radius of a memory bomb (it can OOM the worker pod, but cannot fill the queue or starve other tenants indefinitely).
2. Valkey key migration strands in-flight jobs, and stranded jobs permanently consume quota
internal/queue/valkey.go:77-83 renames the transport key from nebi:jobs to per-tenant lists plus a tenant ZSET. On upgrade, job IDs in the old list are never dequeued and their DB rows stay pending forever. There is no startup reconciliation that re-enqueues DB-pending jobs and no pending-age reaper. This also breaks the file's own documented invariant ("Valkey is used for job transport (job IDs only), DB is source of truth"): the DB says pending, but nothing will ever run the job.
New in this PR, those zombie rows count against active_jobs_per_user/per_workspace/global quotas indefinitely (internal/service/resource_limits.go:319-351), so a handful of stranded rows permanently locks a user or workspace out of job submission, including deletion (see Question 1).
Suggested fix: a startup reconciler that re-enqueues DB jobs stuck in pending older than some threshold. That aligns with the DB-is-source-of-truth invariant, covers the legacy-key migration, and also closes the pre-existing crash-between-DB-write-and-enqueue gap that enqueueAdmittedJob's failure path works around. A one-time drain of the legacy nebi:jobs list is a cheaper alternative but only fixes the migration case.
3. Send-on-closed-channel panic in MemoryQueue
internal/queue/memory.go: Close() closes q.notify, but Dequeue -> nextJobLocked() -> signalLocked() performs a non-blocking send on it, and a send on a closed channel panics even inside a select. Any Dequeue that drains a remaining job after Close() (worker shutdown race in local mode) panics the process. Two-line fix: guard signalLocked with if q.closed { return } (it's always called under q.mu).
4. A job that succeeds at the deadline boundary is failed and its artifacts destroyed
internal/worker/worker.go:188-204: after executeJob returns, the context.DeadlineExceeded branch runs even when err == nil. A job whose work and DB commits (version snapshot, package rows) completed just as the timer fired is rewritten as "exceeded wall-clock timeout", marked failed, and cleanupFailedJobArtifacts runs: for env_install that deletes the fully built .pixi/envs, and for managed create it deletes the whole workspace directory whose DB row was just committed. Gate the timeout branch on err != nil; a successful return means the work beat the deadline.
Questions
-
Quota-blocked deletion.
Deletenow goes throughcheckActiveJobQuotas, so a workspace at its per-workspace cap (default 2) can never be deleted and a user at their per-user cap can't delete anything. Combined with Blocker 2 this is a plausible permanent lockout. Should delete jobs be exempt from quotas, or at least from the per-workspace cap? -
HOMEand cache redirection side effects.internal/process/env.gooverridesHOME,XDG_CACHE_HOME,PIXI_CACHE_DIR, andRATTLER_CACHE_DIRfor all pixi invocations, including desktop/local mode. Two consequences worth confirming as intentional: (a) pixi no longer sees the user's real~/.pixi/config.tomlor stored channel credentials, so private channel auth will break; (b) the shared rattler cache is gone, so every workspace re-downloads and re-extracts everything, and cached plus linked files are double-counted bydirectorySize, roughly halving the effective storage budget for hardlink-heavy envs. -
Pixi semantics hard-coded in the service layer.
internal/service/resource_limits.gocallspixi.ManifestPackageNames/ManifestDefaultDependencyNamesfor every workspace regardless ofws.PackageManager, while the architecture routes package-manager specifics through thePackageManagerinterface and factory. A uv workspace would have its manifest parsed as pixi TOML and rejected. There's pre-existing pixi leakage elsewhere, so this follows precedent, but should manifest validation become aPackageManagermethod before a second package manager lands? -
Scope: three separable changes ride along. (a) Both queues are rewritten from FIFO to round-robin-across-tenants, a scheduling-policy change the PR body doesn't mention. (b)
internal/store/workspace.gonow symlink-resolves and canonicalizes workspace paths on create/save/find, changing persistedLocalWorkspace.Pathvalues and CLI lookup semantics (apparently fallout from the macOS/var->/private/varTMPDIR redirection). (c)internal/worker/worker.goreorders snapshot-before-package-save and converts previously logged-and-ignored snapshot/sync failures into job failures. Are these intentionally bundled? At minimum they deserve mention in the PR description; the store change may warrant its own PR. -
Two conflicting "unspecified limits" semantics.
service.New,NewAdminService, andworker.Newtake variadic optionallimits.Limitsand silently substitutelimits.Defaults()when omitted, whileexecutor.NewLocalExecutortreats a zero value as unlimited. Same type, opposite meanings depending on layer, and the variadic pattern lets "forgot to thread operator config" compile fine. Suggest plain positional parameters; all call sites were touched in this PR anyway. -
Fixed 30s
ReadTimeout(internal/limits/limits.go:11): with a 20MB body cap and 16MB lock cap, a client below roughly 700KB/s can't complete a legitimate push. Should the read timeout scale with the body cap or be configurable? -
Exit code
-1classified as resource-limit exit (internal/process/command.go:77): a process killed by the group SIGTERM during graceful shutdown also exits-1, so shutdown cancellations get reported as "resource limit exceeded" whenever any budget is configured. Worth excluding whenctx.Err() != nil? -
Dequeue polling. Both queues moved from blocking waits (BLPOP/channel) to polling (100ms Valkey, 10ms memory). Fine at current scale; was server-side blocking abandoned deliberately because the Lua scripts can't block?
-
DisableCache: trueon the Valkey client: if this is a RESP3/miniredis compatibility workaround, a comment would help. -
handleBindErrorcoverage. The body-size middleware applies globally, but onlyworkspace.goandremote.gomaphttp.MaxBytesErrorto 413; the other six handler files'ShouldBindJSONsites still return 400 for oversized bodies. Intentional scoping or oversight?
Stylistic
internal/executor/resource_limits.go:65-126: a fullfilepath.WalkDirover the workspace every 500ms is expensive for conda envs with hundreds of thousands of files; the walk can take longer than the interval, making it effectively continuous. Consider a longer interval or block-based accounting. AlsorecordExceeded/recordCheckErrorhave a benign check-then-store race between the ticker goroutine and the final check.cappedLogWriter(internal/worker/worker.go:296-350): after truncation, the final high-signal diagnostics written after the cap is hit ("Workspace storage limit exceeded", the[ERROR]trailer) are dropped too. Consider reserving tail room for nebi's own messages.- Error classification scrapes child logs for substrings;
"killed"(internal/process/command.go:98) matches text like "no processes killed" in user build output, andHasLikelyResourceLimitOutputfeeds the cleanup path that deletes.pixi/envs. Removing the cgroup path (Blocker 1) shrinks this surface, but the classifier still applies to ulimit/timeout failures; a word-boundary match on the shell's actual "Killed" message would cut false positives. internal/process/env.godefines the workspace transient dirs (.nebi/tmp,.nebi/cache,.nebi/home,.nebi/pixi-cache) andinternal/executor/local.goCleanupJobArtifactsre-hardcodes the same four paths. Export the list frominternal/processso cleanup can't silently drift.internal/limits/limits.gomixes the operator-configurableLimitsschema with hard-coded HTTP server constants (HTTPReadHeaderTimeoutetc.) that aren't limits config.limits.Validateis 15 identical non-negative checks; a small loop would halve the file. Optional.- The
swag init -g serve.go -d ...incantation is now copy-pasted in four places (ci.yml twice, Makefile, Dockerfile); CI could callmake swaggerso the command has one owner. - A comment on
lockJobAdmissionnoting it deliberately serializes all admissions server-wide via one row (and that manifest reads happen while holding it) would help future readers reason about contention.
Documentation
The PR adds a limits: config section documented only in serve.go --help. config.yaml.example documents every other section, and docs/docs/server-setup.md has no mention. Please add a commented limits: block to config.yaml.example and a matching server-setup subsection covering the zero-disables semantics, the NEBI_LIMITS_* env overrides, and the fail-closed exit-125 behavior for the ulimit-based budgets.
Positive highlights
internal/process/command_unix.go:20-32: passing the target command as positional parameters to/bin/sh -c script _ name args..., with only integers formatted into the script, cleanly avoids shell injection.internal/process/command_unix_test.go:18-28: pinning down that the limit script fails closed (noulimit ... || true) is exactly the right property to test.internal/db/db.go:759-770: backfilling legacyjobs.user_idfrom workspace owners, mirrored byCOALESCEfallbacks in quota counting and metrics, is thoughtful migration hygiene.- Correct use of
http.MaxBytesReaderwith a proper 413 mapping viaerrors.As(*http.MaxBytesError). - Fair-queue ordering tests for both backends, miniredis-based Valkey tests, stale-tenant recovery, fail-closed storage checks, and the concurrent admission test are all high quality.
tylerpotts
left a comment
There was a problem hiding this comment.
Re-reviewed commit 4233d10 against every finding from my previous review, verified in a fresh checkout: build and go vet clean, and the process, queue, executor, worker, config, and service test suites all pass locally. This addresses essentially everything, and does it carefully. Approving.
Blockers: all four fixed
- Cgroup enforcement removed as proposed.
linuxCgroupLimitScriptis gone,job_memory_bytes/job_processesremoved from config/env bindings/swagger, and CPU is enforced via portableulimit -ton all Unix platforms. DeletingdisableProcessLimitsForE2E()means e2e now exercises the real enforcement path, which is exactly the right outcome. - Valkey migration fixed with both suggested mechanisms: startup drain of the legacy
nebi:jobslist plus a reconciler that re-enqueues DB jobs stuck inpendingolder than 30s, batched. The dedup SET (SADD guard in the enqueue script, SREM on pop) preventing double-enqueue and the non-pending skip at dequeue are nice additions beyond what was asked. - MemoryQueue send-on-closed-channel panic fixed with the
if q.closed { return }guard, plus a regression test. - Deadline-boundary artifact destruction fixed with the
err != nilgate, plus tests.
Questions: addressed
Delete jobs exempt from quotas (and documented in config.yaml.example); HOME/PIXI_CACHE_DIR/RATTLER_CACHE_DIR overrides removed so credentials and the shared package cache work again, with hardlink-aware block-based accounting fixing the double-count as a bonus; manifest parsing moved behind the ManifestContentParser registry keyed by package manager (uv now fails with an explicit error instead of a pixi misparse); variadic limits.Limits made required positional; server.read_timeout_seconds configurable with a body-cap-scaled default; ctx-cancelled and -1 exits excluded from resource-limit classification; all 24 handler bind sites now use handleBindError; DisableCache and the polling design got explanatory comments. The stylistic items and docs (limits: block in config.yaml.example, server-setup section, make swagger in CI, exported transient dirs, tail-reserve in cappedLogWriter, word-boundary "killed" match, Validate loop, lockJobAdmission comment) were all taken too.
Non-blocking follow-ups
- Please file the follow-up issue for per-job memory/pids enforcement via actual job isolation (e.g. per-job pods with pod-level resource limits) and link it here, so the scope cut is recorded rather than silent.
- The PR description still doesn't mention the bundled changes: per-tenant fair scheduling in both queues, workspace path canonicalization in
internal/store, and the worker snapshot/failure-semantics change. A sentence on each would help future archaeology. - Minor observation on the new reconciler code:
seedQueuedSetrunsDEL+KEYSat startup, so two replicas starting simultaneously could briefly race on the queued-set rebuild, andKEYSis O(N) blocking. Both are fine at startup scale; just flagging for awareness.
|
Filed a follow-up for per-job memory/pids enforcement via isolated execution: #513. I also updated the PR description to call out fair scheduling, workspace path canonicalization, and worker snapshot/failure-semantics changes. Lets merge this! |
Resolves the overlap with #494 (resource limits for build jobs), which wrapped the same exec.Cmd construction this branch wraps. The two features now compose in internal/sandbox: Runner.Command builds through process.CommandContext, so a build carries the OS resource limits, the Landlock ruleset, and the scrubbed environment together. Notable decisions: - Dropped sandbox.build_timeout in favour of limits.job_timeout_seconds. Both are wall-clock ceilings on a build; main's is a superset (timeout metric, failed-job artifact cleanup, deadline logged to the build log), and two independent deadlines on one build is a bug factory. - The sandbox reuses internal/process's .nebi/ directory layout for the job-scoped HOME and TMPDIR instead of its own .nebi-home/.nebi-tmp, so those directories are covered by the failed-job cleanup that walks process.WorkspaceTransientDirs. - TMPDIR and the pip/uv caches are now workspace-scoped in every sandbox mode, matching main's unconditional behaviour. HOME stays parent-inherited when the sandbox is off, which is what keeps pixi's credential lookup working. - process.WorkspaceEnv layered its overrides on os.Environ(), which would have handed the scrubbed-away secrets back to build code. Split out WorkspaceEnvOverrides so the sandbox layers them over its allowlist instead. - The service-layer pixi list bypasses (syncPackagesFromDisk, SyncPackagesFromWorkspace, CreateVersionSnapshot) go through executor.ListPackages, keeping main's output caps and list-error mapping while gaining the sandbox and config.package_manager.pixi_path.
Reference Issues or PRs
Closes #453
Related tracking issue: #513
What does this implement/fix?
Put a
xin the boxes that applyTesting
Documentation
The new
limits:configuration is documented inconfig.yaml.exampleanddocs/docs/server-setup.md.Access-centered content checklist
Text styling
H1or#in markdown).Non-text content
Any other comments?
Adds request and manifest/package limits, job admission quotas, per-job deadlines, resource cleanup, and metrics for environment build APIs. Also preserves successful version snapshots when package listing fails for non-resource reasons.
This PR also includes three related behavior changes:
internal/storeby resolving symlinks before create, save, and lookup.Per-job memory and process-count enforcement through isolated jobs is intentionally deferred to #513.