Skip to content

About

Kubernetes controller for DAG-based data pipelines: dependency resolution, admission control, priority eviction and S3 marker completion

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

k8s-dag-pipeline-controller

A Kubernetes custom controller that orchestrates multi-stage data pipeline jobs with DAG-based dependency resolution, admission control, priority-based eviction, and S3 storage-marker completion detection.


Motivation

Running ML pipelines on a shared Kubernetes cluster has two core problems:

  • Schedulers don't understand data dependencies — Job B occupies resources spinning idle while waiting for Job A's output
  • Orchestrators don't understand resource state — Argo/Airflow submit jobs unconditionally, causing resource contention

This controller acts as a dependency-aware gatekeeper between the orchestrator and the Kubernetes scheduler.


Overview

Key capabilities:

  • DAG dependency resolution — jobs wait until all upstream jobs are DONE before becoming READY
  • Cycle detection — the DAG registry rejects any job spec that would create a cycle
  • Admission control — checks real, per-node free capacity (allocatable minus the requests of all running pods, including non-PipelineJob workloads) before submitting; the worker pods carry matching resources.requests, so the Kubernetes scheduler enforces the same numbers
  • Priority eviction — a realtime job that cannot fit waits EvictionThreshold, then preempts a batch job in its namespace, but only one whose removal actually lets it fit on a single node (the smallest such job is chosen; if no single eviction would help, nothing is killed). Batch jobs leave room for waiting realtime jobs so the freed capacity is not taken back, and no second eviction starts while one is in progress
  • Storage-marker completion — jobs are marked DONE only when an S3/MinIO _SUCCESS marker is detected; stale markers are cleared before every run, and storage errors surface as errors instead of looking like "not finished"
  • Visible state — kubectl get pipelinejobs shows STATE, PRIORITY, RETRIES and EVICTIONS (-o wide adds REASON); a job that is waiting says what for, e.g. waiting: upstream job "no-such-job" not found. A new job starts in WAITING, not blank
  • Validation at the API — the CRD requires priority, requestCPU, requestMemory and storageMarker and checks their format, so invalid specs are rejected by kubectl apply instead of failing later in the controller
  • Failure handling — a failing worker, a timeout, an invalid spec or a failed upstream moves the job to a retry or to FAILED with a status.reason
  • Timeout & retry — configurable per-job timeout with a retry budget before permanent failure

Architecture

PipelineJob CRD
      │
      ▼
 Reconciler (controller-runtime)
      │
      ├── DAGRegistry       — dependency graph, cycle detection
      ├── AdmissionChecker  — per-node free capacity from real pod requests
      ├── EvictionManager   — batch job preemption for realtime priority
      └── StorageChecker    — S3/MinIO HeadObject marker polling

Job State Machine

WAITING ──► READY ──► SUBMITTED ──► RUNNING ──► DONE
   ▲                      │            │
   │                      └────────────┤
   │                                   ├──► TIMED_OUT ──► WAITING (retry)
   │                                   └──► FAILED
   │
KILLING ──► WAITING  (eviction recovery)
  • SUBMITTED — the underlying Kubernetes Job has been created.
  • RUNNING — the worker container is actually running (not merely created or Pending). The run timeout (timeoutSeconds) is measured from this moment, so scheduling delays and image pulls do not count against it. A pod that never starts within StartTimeout (10 min) is retried like a timeout.
  • DONE — the storage marker exists (checked in both SUBMITTED and RUNNING).
  • TIMED_OUT / FAILED — if the timeout expires or the worker exits with an error, the Job is deleted and the job is retried (TIMED_OUT → WAITING) until RetryBudget is used up, then becomes FAILED. status.reason says why.
  • Jobs that can never run fail immediately (no retry): an invalid spec (bad quantities, storageMarker not of the form s3://<bucket>/<key>), a dependency cycle, a storageMarker already used by another job (the older job keeps it; each job needs its own marker), or an upstream that is FAILED (failures propagate down the DAG instead of leaving downstream jobs in WAITING forever).
  • Before each submission the controller deletes the job's marker, so a _SUCCESS left over from an earlier run (re-applied pipeline, retry) cannot mark the new run DONE. The worker only writes the marker after every step has succeeded.
  • KILLING — an evicted batch job. Its Kubernetes Job is deleted and it returns to WAITING only once the Job and all its pods are gone, so a new pod never runs next to the old one. If that takes longer than KillConfirmTimeout (120s) the job stays in KILLING and status.reason says the old pod is still terminating (look at the node); it is never forced back while the old pod could still be running. Its resources stay accounted for in the meantime.

Project Structure

.
├── api/v1/
│   ├── types.go                     # CRD type definitions
│   └── zz_generated.deepcopy.go    # DeepCopy implementations
├── internal/
│   ├── reconciler.go   # Main reconcile loop & state handlers
│   ├── dag.go          # DAGRegistry with DFS cycle detection
│   ├── admission.go    # AdmissionChecker (CPU/memory capacity)
│   ├── eviction.go     # EvictionManager (preemption, kill confirmation)
│   ├── dag_test.go     # Unit tests: cycle detection, upstream resolution
│   ├── eviction_test.go # Unit tests: KILLING -> WAITING, victim selection
│   ├── admission_test.go, storage_test.go, reconciler_test.go, victim_test.go, crd_test.go
│   └── storage.go      # StorageChecker (S3/MinIO marker polling)
├── config/
│   ├── job-image/
│   │   ├── Dockerfile           # Worker container image
│   │   └── run.sh               # Worker entrypoint script
│   ├── crd.yaml                 # CustomResourceDefinition
│   ├── rbac.yaml                # ServiceAccount, ClusterRole, ClusterRoleBinding
│   ├── minio.yaml               # MinIO deployment (local S3 backend)
│   ├── test-pipeline.yaml       # DAG pipeline scenario
│   ├── test-eviction.yaml       # Eviction scenario
│   └── test-eviction-bench.yaml
├── .github/workflows/ci.yaml   # go build / vet / test on every push
├── main.go
├── go.mod
└── go.sum

Custom Resource: PipelineJob

apiVersion: pipeline.io/v1
kind: PipelineJob
metadata:
  name: stage-2
  namespace: default
spec:
  priority: realtime          # realtime | batch
  requestCPU: "200m"
  requestMemory: "256Mi"
  storageMarker: "s3://test-bucket/stage2/_SUCCESS"
  timeoutSeconds: 600
  jobDurationSeconds: 45
  stage: "2"
  dependencies:
    - stage-1                 # waits until stage-1 is DONE
Field Description
priority realtime jobs can preempt batch jobs when capacity is full
requestCPU / requestMemory Resource request used for admission decisions
storageMarker S3 path polled to confirm job completion
timeoutSeconds Per-job timeout; triggers retry or permanent failure
jobDurationSeconds Simulated workload duration passed to the worker container
dependencies Names of upstream PipelineJobs that must complete first

Getting Started

Prerequisites

  • Kubernetes cluster (e.g. kind)
  • kubectl configured
  • Docker (to build the worker image)

1. Apply CRD and RBAC

kubectl apply -f config/crd.yaml
kubectl apply -f config/rbac.yaml

2. Build and load the images

docker build -t pipeline-job:latest config/job-image/          # worker
docker build -t dag-pipeline-controller:latest .               # controller
kind load docker-image pipeline-job:latest
kind load docker-image dag-pipeline-controller:latest

On Windows, .gitattributes keeps run.sh on LF line endings; without that the worker fails with exec /run.sh: no such file or directory.

3. Create the credentials Secret, deploy MinIO and create the bucket

Storage credentials live in a Secret named minio-credentials and are read through secretKeyRef by MinIO, the controller and the worker pods, so no pod spec contains them. There is no built-in default password.

# Demo credentials for a local kind cluster. For anything else, create the Secret yourself
# (see the header of config/minio-secret.yaml) instead of applying this file.
kubectl apply -f config/minio-secret.yaml

kubectl apply -f config/minio.yaml
kubectl -n minio rollout status deploy/minio

kubectl apply -f config/create-bucket-job.yaml
kubectl wait --for=condition=complete job/create-bucket --timeout=120s

A Secret is namespaced: it must exist in minio (for MinIO) and in every namespace where PipelineJobs run (the controller and the worker pods read it there). config/minio-secret.yaml creates it in minio and default.

minio/minio is no longer published on Docker Hub, so config/minio.yaml uses the frozen bitnamilegacy/minio image, and the worker image copies mc from bitnamilegacy/minio-client. Load the MinIO image into kind too if it cannot pull from Docker Hub.

On AWS do not use static keys. Run the controller with an IRSA role: leave MINIO_ACCESS_KEY / MINIO_SECRET_KEY unset and it uses the AWS default credential chain. The example worker talks to storage through mc with static keys, so a worker on AWS should use the AWS SDK/CLI with its own IRSA role; set WORKER_CREDENTIALS_SECRET="" to stop injecting keys.

4. Run the controller

In the cluster (uses MINIO_ENDPOINT=http://minio.minio:9000):

kubectl apply -f deploy/controller-deployment.yaml
kubectl logs -f deploy/dag-pipeline-controller

Or locally, against a port-forwarded MinIO (default endpoint http://localhost:9000):

kubectl -n minio port-forward svc/minio 9000:9000 &
export MINIO_ACCESS_KEY=$(kubectl get secret minio-credentials -o jsonpath='{.data.accessKey}' | base64 -d)
export MINIO_SECRET_KEY=$(kubectl get secret minio-credentials -o jsonpath='{.data.secretKey}' | base64 -d)
go run main.go

5. Apply a scenario

# 3-stage pipeline with DAG dependencies
kubectl apply -f config/test-pipeline.yaml

# Eviction scenario: batch jobs preempted by realtime
kubectl apply -f config/test-eviction.yaml

6. Watch job states

kubectl get pipelinejobs -w

Scenarios

DAG Pipeline (test-pipeline.yaml)

stage-1 → stage-2 → stage-3 in sequence, plus a concurrent background-1 batch job. Demonstrates dependency resolution and parallel execution.

Eviction (test-eviction.yaml)

Two batch jobs take 6 of 8 CPUs (sized for an 8-CPU node; scale the requests to your cluster). A realtime job waits for capacity; after EvictionThreshold (5s), the controller evicts a batch job to free resources. The evicted job sits in KILLING until its Kubernetes Job and pods are gone, then re-queues to WAITING. While the realtime job is waiting, batch jobs leave room for it, so the freed capacity goes to the realtime job; no second eviction starts while one is still in progress.


Performance

Measured on a single-node kind cluster (8 CPUs, Docker Desktop on a laptop) with bench/run.sh, comparing the controller before the faster-release work (802f5d7) and after. Every job in every round succeeded. Times are seconds, shown as p50 / p95 / max, taken from the controller's own job_event log lines; n is the number of samples.

What Before After
Evicted job's pod gone, capacity usable again (EVICTED → KILL_CONFIRMED) 32.14 / 35.42 / 35.56 (n=20) 6.54 / 6.56 / 6.58 (n=20)
Realtime job that needs an eviction: created → worker running (READY → RUNNING) 41.58 / 43.10 / 46.38 (n=20) 13.51 / 13.62 / 13.63 (n=20)
Upstream DONE → downstream SUBMITTED (chains of 6 jobs) 0.86 / 3.00 / 3.04 (n=100) 0.03 / 0.06 / 0.14 (n=100)
Full cluster (1 root + 60 children of 2000m): worker exit → next waiting job SUBMITTED 2.86 / 3.10 / 3.19 (n=57) 2.01 / 2.11 / 2.18 (n=57)
  of which: worker exit → controller sees the pod finished (kubelet + API server) not measured 1.98 / 2.06 / 2.16 (n=60)
  of which: pod finished → next job SUBMITTED (the controller) not measured 0.02 / 0.11 / 0.11 (n=57)

Why it was slow, and what changed:

  • Eviction took ~32 s. The worker script runs as PID 1 and ignores SIGTERM, so every evicted pod waited out the full Kubernetes default terminationGracePeriodSeconds of 30 s before its CPU came back. Worker pods now get a 5 s grace period (WORKER_TERMINATION_GRACE_SECONDS), and a KILLING job re-checks for its old pod every 2 s instead of 5 s.
  • Downstream jobs waited up to 3 s after an upstream finished, because they only polled. The controller now also watches PipelineJob transitions to DONE/FAILED and wakes the direct dependents immediately (looked up in the in-memory DAG, no LIST).
  • A freed slot waited for the next poll. On a full cluster the next waiting job was only tried on the 3 s requeue. The controller now watches worker pods and, the moment one finishes or is deleted, drops the admission snapshot and wakes every READY job. The controller's own share of the hand-off is now about 0.02 s (max 0.11 s). The 3 s requeue stays as a fallback in every case.

What the numbers do and do not show:

  • In the full-cluster hand-off, about 2 s of the remaining time is the kubelet and API server reporting that the worker pod finished. That happens outside the controller and could not be reduced here; it is also the noisiest part (about 1.6 s in an earlier, quieter run, 2.0 s here with another kind cluster running on the same machine). "Before" has no pod-release event, so its total cannot be split the same way.
  • One machine, one node, one workload per scenario: treat them as relative improvements, not absolute capacity numbers. The eviction scenario is small (200m) plus two large batch jobs and one realtime job, as in config/test-eviction.yaml.
  • A 5 s grace period only suits workers that need no clean-up time on SIGTERM; raise WORKER_TERMINATION_GRACE_SECONDS if yours do.
  • The controller exits when it cannot reach the API server and relies on Kubernetes to restart it. A run on a heavily loaded single node was once interrupted that way and discarded; bench/run.sh now saves the log after every scenario and warns about restarts.

Reproduce with bench/run.sh and bench/analyze.py (see bench/README.md).


Configuration Constants

Constant Default Description
DefaultTimeout 300s Run timeout if not specified in the spec; counted from the moment the worker is running
StartTimeout 10m Max time between submission and the worker pod running (scheduling + image pull)
RetryBudget 2 Max retries before permanent FAILED
EvictionThreshold 5s How long a realtime job waits before triggering eviction
MaxEvictionCount 3 Max times a batch job can be evicted
KillConfirmTimeout 120s After this long in KILLING, status.reason reports that the old pod is still terminating; the job keeps waiting for it to disappear

Environment variables

Variable Default Description
MINIO_ENDPOINT http://localhost:9000 S3/MinIO endpoint the controller uses to poll _SUCCESS markers
MINIO_ACCESS_KEY / MINIO_SECRET_KEY (none) Static storage credentials for the controller; set both or neither. In the cluster they come from the minio-credentials Secret. When both are unset the AWS default credential chain (IRSA, instance role, ...) is used
WORKER_CREDENTIALS_SECRET minio-credentials Name of the Secret (keys accessKey, secretKey) that worker pods read their credentials from via secretKeyRef; empty injects no credentials
WORKER_MINIO_ENDPOINT http://minio.minio:9000 MinIO address as seen from worker pods (differs from MINIO_ENDPOINT when the controller runs outside the cluster)
WORKER_IMAGE pipeline-job:latest Worker container image
WORKER_IMAGE_PULL_POLICY IfNotPresent Pull policy for the worker image
WORKER_TERMINATION_GRACE_SECONDS 5 terminationGracePeriodSeconds of worker pods. The worker script runs as PID 1 and ignores SIGTERM, so an evicted pod always lingers for the full period; the Kubernetes default of 30s made eviction take ~31s to free capacity
LEADER_ELECT false Enable leader election so multiple controller replicas can run (the deployment sets it to true)
LEADER_ELECT_NAMESPACE default Namespace of the leader-election lease when running outside the cluster

The bucket comes from each job's storageMarker; nothing about the bucket is hard-coded.

Tests

go test ./...

Future Work

  • Admission only looks at CPU/memory requests and node taints. Node selectors, affinity, tolerations, ephemeral storage and GPUs are not considered, so a job can still be admitted and then sit Pending in the scheduler.
  • Eviction only considers victims in the same namespace and frees room with a single eviction; preempting several small jobs together, or ranking victims by priority/age, is not implemented
  • Storage polling: markers are polled every 3 seconds because object stores have no watch. Event notifications (e.g. MinIO bucket notifications) would remove the polling.
  • Credentials are passed to worker pods as plain environment variables; use a Secret (or IRSA / workload identity on AWS) outside of a demo.

Design notes

  • Admission reads the API server, not the cache. Admission and the "does the worker Job already exist" check use the manager's API reader, so a job is never admitted on stale cache data. To keep this from costing a full LIST of nodes, pods and PipelineJobs per READY job per poll (O(jobs x cluster size)), the admission snapshot is reused for one second and dropped as soon as the controller itself submits or evicts a job, so its own decisions are always made on fresh data. Other workloads can therefore be up to a second stale, which is fine: the worker pods carry real resource requests, so the Kubernetes scheduler would leave an over-admitted pod Pending rather than overload a node.

  • Cheap reconciles. A waiting job looks up only its own dependencies (a cached Get each) instead of listing every PipelineJob, and duplicate storage markers are found through a field index on spec.storageMarker, not a scan.

  • Submission is safe to retry. The marker is cleared only when the worker Job is actually created. If a previous attempt created the Job but failed to record SUBMITTED, the retry adopts that Job and leaves the marker alone (the worker may already have finished).

  • Slots are handed over on events, not only by polling. The controller watches worker pods: the moment one finishes (Succeeded/Failed) or is deleted, which is when its resources are really released, it drops the admission snapshot and wakes every READY job (cluster-wide, found through a field index on status.state), so the first job that fits is submitted at once. A PipelineJob turning DONE is deliberately not the trigger, because the marker can appear while the pod is still running. A pod that has finished no longer counts against its job in admission, even before the controller has recorded DONE. The 3 s poll stays as a fallback.

  • Least privilege. The controller only reads PipelineJobs (state changes go through the status subresource), creates/deletes Jobs, and reads nodes and pods; it runs as a non-root user with a read-only root filesystem.

  • No finalizer. Deleting a PipelineJob needs no external cleanup: the underlying Job has an OwnerReference and is garbage-collected, and the controller drops the job from its in-memory DAG when it sees the deletion. A finalizer would only add a way for jobs to get stuck in Terminating.

  • In-memory DAG. The DAG registry and admission mutex live in the controller process. That is safe with leader election (one active replica; the DAG is rebuilt from the PipelineJobs as they reconcile after a failover).


Dependencies

About

Kubernetes controller for DAG-based data pipelines: dependency resolution, admission control, priority eviction and S3 marker completion

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages