Skip to content

Add resource limits for environment build jobs - #494

Merged
pmeier merged 10 commits into
nebari-dev:mainfrom
MUFFANUJ:resourceLimit
Aug 18, 2026
Merged

pmeier merged 10 commits into
nebari-dev:mainfrom
MUFFANUJ:resourceLimit

Conversation

@MUFFANUJ

@MUFFANUJ MUFFANUJ commented Aug 5, 2026 •

Copy link
Copy Markdown
Member

Reference Issues or PRs

Closes #453

Related tracking issue: #513

What does this implement/fix?

Put a x in the boxes that apply

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds a feature)
  • Breaking change (fix or feature that would cause existing features not to work as expected)
  • Documentation Update
  • Code style update (formatting, renaming)
  • Refactoring (no functional changes, no API changes)
  • Build related changes
  • Other (please describe):

Testing

  • Did you test the pull request locally?
  • Did you add new tests?

Documentation

The new limits: configuration is documented in config.yaml.example and docs/docs/server-setup.md.

Access-centered content checklist

Text styling

  • The content is written with plain language (where relevant).
  • If there are headers, they use the proper header tags (with only one level-one header: H1 or # in markdown).
  • All links describe where they link to (for example, check the Nebari website).
  • This content adheres to the Nebari style guides.

Non-text content

  • All content is represented as text (for example, images need alt text, and videos need captions or descriptive transcripts).
  • If there are emojis, there are not more than three in a row.
  • Don't use flashing GIFs or videos.
  • If the content were to be read as plain text, it still makes sense, and no information is missing.

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:

  • Updates both queue backends to use per-tenant fair scheduling, so one tenant cannot monopolize job processing.
  • Canonicalizes local workspace paths in internal/store by resolving symlinks before create, save, and lookup.
  • Adjusts worker snapshot, package-sync, and failure handling so successful workspace changes are preserved across non-resource package listing/reinstall failures, while validation, deadline, and resource-limit failures still fail the job and clean up artifacts.

Per-job memory and process-count enforcement through isolated jobs is intentionally deferred to #513.

@netlify

netlify Bot commented Aug 5, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for nebi-docs ready!

Name Link
🔨 Latest commit bfc7c23
🔍 Latest deploy log https://app.netlify.com/projects/nebi-docs/deploys/6a84103ded268900087cde0d
😎 Deploy Preview https://deploy-preview-494--nebi-docs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@MUFFANUJ
MUFFANUJ marked this pull request as ready for review August 11, 2026 21:45
@tylerpotts

Copy link
Copy Markdown
Collaborator

@MUFFANUJ There's some failing CI jobs. Could you look into them?

@tylerpotts tylerpotts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Quota-blocked deletion. Delete now goes through checkActiveJobQuotas, 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?

  2. HOME and cache redirection side effects. internal/process/env.go overrides HOME, XDG_CACHE_HOME, PIXI_CACHE_DIR, and RATTLER_CACHE_DIR for all pixi invocations, including desktop/local mode. Two consequences worth confirming as intentional: (a) pixi no longer sees the user's real ~/.pixi/config.toml or 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 by directorySize, roughly halving the effective storage budget for hardlink-heavy envs.

  3. Pixi semantics hard-coded in the service layer. internal/service/resource_limits.go calls pixi.ManifestPackageNames/ManifestDefaultDependencyNames for every workspace regardless of ws.PackageManager, while the architecture routes package-manager specifics through the PackageManager interface 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 a PackageManager method before a second package manager lands?

  4. 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.go now symlink-resolves and canonicalizes workspace paths on create/save/find, changing persisted LocalWorkspace.Path values and CLI lookup semantics (apparently fallout from the macOS /var -> /private/var TMPDIR redirection). (c) internal/worker/worker.go reorders 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.

  5. Two conflicting "unspecified limits" semantics. service.New, NewAdminService, and worker.New take variadic optional limits.Limits and silently substitute limits.Defaults() when omitted, while executor.NewLocalExecutor treats 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.

  6. 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?

  7. Exit code -1 classified 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 when ctx.Err() != nil?

  8. 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?

  9. DisableCache: true on the Valkey client: if this is a RESP3/miniredis compatibility workaround, a comment would help.

  10. handleBindError coverage. The body-size middleware applies globally, but only workspace.go and remote.go map http.MaxBytesError to 413; the other six handler files' ShouldBindJSON sites still return 400 for oversized bodies. Intentional scoping or oversight?

Stylistic

  • internal/executor/resource_limits.go:65-126: a full filepath.WalkDir over 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. Also recordExceeded/recordCheckError have 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, and HasLikelyResourceLimitOutput feeds 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.go defines the workspace transient dirs (.nebi/tmp, .nebi/cache, .nebi/home, .nebi/pixi-cache) and internal/executor/local.go CleanupJobArtifacts re-hardcodes the same four paths. Export the list from internal/process so cleanup can't silently drift.
  • internal/limits/limits.go mixes the operator-configurable Limits schema with hard-coded HTTP server constants (HTTPReadHeaderTimeout etc.) that aren't limits config.
  • limits.Validate is 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 call make swagger so the command has one owner.
  • A comment on lockJobAdmission noting 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 (no ulimit ... || true) is exactly the right property to test.
  • internal/db/db.go:759-770: backfilling legacy jobs.user_id from workspace owners, mirrored by COALESCE fallbacks in quota counting and metrics, is thoughtful migration hygiene.
  • Correct use of http.MaxBytesReader with a proper 413 mapping via errors.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 tylerpotts left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. Cgroup enforcement removed as proposed. linuxCgroupLimitScript is gone, job_memory_bytes/job_processes removed from config/env bindings/swagger, and CPU is enforced via portable ulimit -t on all Unix platforms. Deleting disableProcessLimitsForE2E() means e2e now exercises the real enforcement path, which is exactly the right outcome.
  2. Valkey migration fixed with both suggested mechanisms: startup drain of the legacy nebi:jobs list plus a reconciler that re-enqueues DB jobs stuck in pending older 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.
  3. MemoryQueue send-on-closed-channel panic fixed with the if q.closed { return } guard, plus a regression test.
  4. Deadline-boundary artifact destruction fixed with the err != nil gate, 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: seedQueuedSet runs DEL + KEYS at startup, so two replicas starting simultaneously could briefly race on the queued-set rebuild, and KEYS is O(N) blocking. Both are fine at startup scale; just flagging for awareness.

@MUFFANUJ

Copy link
Copy Markdown
Member Author

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!

@pmeier
pmeier merged commit acf8a9b into nebari-dev:main Aug 18, 2026
16 checks passed
@MUFFANUJ
MUFFANUJ deleted the resourceLimit branch August 18, 2026 08:03
tylerpotts added a commit that referenced this pull request Aug 19, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[security] Environment build APIs have no request-size caps, quotas, or per-job deadlines

3 participants