socialweb.computer

Request and provide VMs on an atproto compute market.

03 - Jobs

This guide is for an operator running GitLab CI jobs on a tenant k3s cluster. Complete 02 first so you have a runner pointed at the tenant cluster. Once set up, a GitLab pipeline runs its jobs as Pods in the tenant cluster, one job per node, and the cluster returns to zero nodes when work stops.

Contents

Job Images

The project's .gitlab-ci.yml sets the image for each job Pod:

  image: "$DOCKER_REPO:builder-$DOCKERFILE_HASH"

DOCKER_REPO is defined in .gitlab-ci.yml, and DOCKERFILE_HASH comes from the included .ci/dockerfile-hash.yaml. That file is generated by hashing the Dockerfile:

printf "variables:\n  DOCKERFILE_HASH: `git hash-object docker/build.Dockerfile`" > .ci/dockerfile-hash.yaml

Changing the Dockerfile produces a new image tag and leaves the old tag valid.

Verifying Image Tags

Check that the tag exists before booting a node so you don't hit ImagePullBackOff twenty minutes later. Even public repositories require a token at the manifest endpoint:

REPO=streamplace/streamplace
TAG=builder-3e14c389b80a359787d73741f221fdfaacb12f53

TOKEN=$(curl -s "https://ghcr.io/token?scope=repository:${REPO}:pull&service=ghcr.io" \
  | python3 -c 'import sys,json;print(json.load(sys.stdin)["token"])')

curl -s -o /dev/null -w '%{http_code}\n' \
  -H "Authorization: Bearer ${TOKEN}" \
  -H 'Accept: application/vnd.oci.image.index.v1+json,application/vnd.docker.distribution.manifest.v2+json' \
  "https://ghcr.io/v2/${REPO}/manifests/${TAG}"

A 200 response means the image exists and the job can pull it. A 404 MANIFEST_UNKNOWN response means the job can't start, even if the cluster is healthy.

Unpublished Branch Images

A branch can point DOCKER_REPO at an unpublished tag (for example, a public.ecr.aws repository returning NAME_UNKNOWN for the repository itself), which makes every job in .gitlab-ci.yml fail as written. Check the upstream branch's variables: block before assuming an image is missing, since a stale branch causes the same error.

There are two ways to make the branch runnable, from lowest to highest cost:

  1. Rebase onto the publishing branch and use its .ci/dockerfile-hash.yaml, where DOCKER_REPO and the hash already match.
  2. Build and host the image yourself. Run docker build --target builder -f docker/build.Dockerfile . for the hash the branch names, push it to a registry the guest can reach, and point DOCKER_REPO there. The guest has outbound internet, so a public registry works. A private registry requires a route and registries.yaml.

Confirming an image pulls isn't enough if its toolchain is out of date. An old builder image fails inside the job with errors like a Rust toolchain without let-chains (error[E0658]: let expressions in this position are unstable) or a corepack that creates no pnpm shims (pnpm: No such file or directory), so check the toolchain versions inside the image too.

Guest Image Pulls

Outbound internet works from inside the guest, so unseeded images like registry.gitlab.com/gitlab-org/gitlab-runner-helper and rancher/mirrored-library-busybox pull over the network without extra setup.

Keep image_pull_policy = "if-not-present". The node image pre-seeds several images into the guest's containerd, and setting always bypasses them.

Pull large images at runtime instead of seeding them into the node image. mkfs.ext4 -d rejects files of about 2 GiB or more, so multi-gigabyte builder image tarballs won't fit. Size the root filesystem to hold them (see 01).

Minimal Integration Pipeline

Run a single-stage, single-job pipeline to test every hop from the runner to a provisioned node:

stages: [prove]

prove-placement:
  stage: prove
  image: busybox:1.36
  script:
    - echo "running on $(hostname)"
    - echo "namespace $(cat /var/run/secrets/kubernetes.io/serviceaccount/namespace)"

This checks six steps in order:

  1. The runner authenticates to the apiserver.
  2. A Pod is created in the gitlab-runner namespace.
  3. The cluster observes intent and provisions a node.
  4. The Pod is scheduled onto that node.
  5. The build container runs.
  6. The helper container streams logs back through the runner.

If the job passes, the integration works. If it hangs at "Preparing the environment", the runner is pointed at the kcp mount URL instead of loopback (see README.md).

To watch placement from outside, query the tenant cluster as its admin:

kubectl --kubeconfig <tenant-admin> get pods -n gitlab-runner -o wide -w
kubectl --kubeconfig <tenant-admin> get nodes -w

Service Containers

GitLab services: run as extra containers in the same Pod. You can reach them over localhost or by DNS alias, and they share the Pod's resource quota:

test-with-postgres:
  stage: prove
  image: postgres:16-alpine
  services:
    - name: postgres:16-alpine
      alias: db
  variables:
    POSTGRES_PASSWORD: ci
    PGHOST: db
    PGUSER: postgres
  script:
    - psql -c 'select 1'

Keep two cluster constraints in mind when using services:

Deploying to the Tenant Cluster

When a job deploys back into the same cluster, use the Pod's mounted service account token instead of passing a long-lived credential:

deploy:
  stage: prove
  image: bitnami/kubectl:1.32
  script:
    - kubectl config set-cluster tenant --server=https://kubernetes.default.svc --certificate-authority=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt
    - kubectl config set-credentials ci --token="$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)"
    - kubectl config set-context tenant --cluster=tenant --user=ci
    - kubectl --context tenant -n gitlab-runner get pods

This only works if the runner's service_account has permission to access those resources. The ClusterRole in 01 only covers placing jobs, so grant deployment permissions to a separate service account for jobs.

GitLab Reachability from Job Pods

A job Pod runs inside a guest on the tenant cluster's network, not on the kcp host. Because the runner passes CI_REPOSITORY_URL to the helper container using GitLab's configured host, an address like http://127.0.0.1:8080/... points at the guest's own loopback and cloning fails:

fatal: unable to access 'https://.../repo.git/': ...
ERROR: Job failed: command terminated with exit code 128

GitLab reports that error as script_failure, which can look like a broken runner.

You have three options, from lowest to highest cost:

  1. Skip cloning by setting variables: { GIT_STRATEGY: none } for jobs that only run commands.
  2. Bind GitLab to an address the guest can reach and update external_url so CI_REPOSITORY_URL resolves from inside the guest.
  3. Run the runner alongside the Pods so the URL it passes is reachable from the same network.

Option 1 is enough to verify the integration. Real pipelines need option 2 or 3, depending on whether the tenant network can reach GitLab.

Artifacts and Cache

Artifacts work as usual because they upload over the runner's HTTPS connection to GitLab instead of going through the cluster.

Cache doesn't work out of the box. There's no object store or PersistentVolume, and GitLab's default cache volume is per-Pod. Configure an external S3-compatible endpoint in [runners.cache], since a hostPath or PVC cache has no node left to live on once the cluster scales to zero.

Resource Requests

cpu_request and memory_request declare what a single job needs. They size the Pod and determine what podsPerNode divides by during scale-out, so base them on real measurements instead of guesses.

Don't override requests inside a job via KUBERNETES_CPU_REQUEST and related variables. Doing so contradicts the runner's earlier sizing and can mismatch the node provisioned for that job.

One Job per Node

The runner creates one Pod per job, and the cluster provisions nodes to match, so N concurrent jobs produce N Pods and set the node target to N. Getting one job per node takes configuration on both the runner and the cluster provider.

On the runner side, add pod anti-affinity in config.toml (see 02):

    [runners.kubernetes.affinity]
      [runners.kubernetes.affinity.pod_anti_affinity]
        [[runners.kubernetes.affinity.pod_anti_affinity.required_during_scheduling_ignored_during_execution]]
          topology_key = "kubernetes.io/hostname"
          [runners.kubernetes.affinity.pod_anti_affinity.required_during_scheduling_ignored_during_execution.label_selector]
            [[runners.kubernetes.affinity.pod_anti_affinity.required_during_scheduling_ignored_during_execution.label_selector.match_expressions]]
              key = "project.runner.gitlab.com/id"
              operator = "Exists"

Use [runners.kubernetes.affinity] instead of pod_spec, since it's supported directly and doesn't require the beta FF_USE_ADVANCED_POD_SPEC_CONFIGURATION flag. Use required instead of preferred, or the scheduler may pack multiple Pods onto one node.

On the cluster side, set these variables on the cluster provider:

SOCIALWEB_CLUSTERPROVIDER_SCALE_MAX_NODES=5
SOCIALWEB_CLUSTERPROVIDER_SCALE_PODS_PER_NODE=1
SOCIALWEB_CLUSTERPROVIDER_SCALE_HOLD=1m
VariableMeaningDefault
SOCIALWEB_CLUSTERPROVIDER_SCALE_MAX_NODESNode ceiling. Values below one are refused rather than clamped. Each node is a booted guest, so this controls cost as well as scale.10
SOCIALWEB_CLUSTERPROVIDER_SCALE_PODS_PER_NODEAssumed job capacity per node. Set from a measured job.8
SOCIALWEB_CLUSTERPROVIDER_SCALE_HOLDIdle grace period before scale-in.2m

The scaler counts Pods in Pending, Running, or Unknown phases, excluding k3s's own addons. At one Pod per node, five active job Pods set a target of five nodes. When work stops, the target drops straight to zero instead of stepping down to an intermediate count.

Scaling Verification

Run five echo-and-sleep jobs to verify scaling to five nodes and back to zero. This pipeline uses an image already seeded into the node image so a slow pull won't hide placement behavior:

.scale-check:
  stage: build
  interruptible: true
  image: rancher/mirrored-library-busybox:1.37.0@sha256:ad9fa4d07136a83e69a54ef00102f579d04eba431932de3b0f098cc5d5948f9f
  timeout: 30 minutes
  script:
    - echo "SCALE_CHECK job=${CI_JOB_NAME} pod=$(hostname)"
    - sleep 180

scale-check-1:
  extends: .scale-check
scale-check-2:
  extends: .scale-check
scale-check-3:
  extends: .scale-check
scale-check-4:
  extends: .scale-check
scale-check-5:
  extends: .scale-check

A healthy run goes through this sequence:

5 job pods exist, all Pending, cluster at zero nodes
the scale decision reads Provision with nodes=5: intent and no node
5 nodes join on demand, all Ready
each job pod is on its own node
all 5 jobs finish success
the job pods are gone
the scale decision reads Teardown with nodes=0:
  nothing running for 1m0.9s, past the 1m0s hold
the cluster is back at zero nodes, control plane still Ready

While scaling up, nodes come up one at a time. With one node online, several Pods sit in Init on it while the rest stay Pending because anti-affinity blocks co-scheduling. Those Pending Pods drive the node count up, which confirms the control loop is working.

Node-Local DNS and Cross-Node Networking

On every market cluster, DNS stays local to each node. Each node assigns 169.254.20.10 to a dummy interface, runs its own CoreDNS on that address, and configures kubelet to give Pods nameserver 169.254.20.10, so job Pods resolve cluster names and $CI_SERVER_HOST locally on whichever node they land on.

CoreDNS runs as a host-network DaemonSet (kube-system/socialweb-node-dns), scheduled by the socialweb.computer/node-local-dns=true node label and bound to 169.254.20.10. The guest's user_data configures the dummy interface and starts the k3s agent with --kubelet-arg=cluster-dns=169.254.20.10. The cluster provider applies the DaemonSet in every tenant.

For cross-node Pod networking, Pods reach Pods on other nodes through socialweb-meshd. k3s runs with --flannel-backend=none and --cluster-cidr=10.42.0.0/16. Each node runs a bridge CNI on its own pod CIDR, and socialweb-meshd routes remote pod CIDRs over iroh QUIC datagrams to their target nodes. Traffic leaving the cluster is masqueraded on the egress node, while Pod-to-Pod traffic keeps its pod source address.

Pause Pods and Scale-to-Zero

GitLab Runner 18.10 and later can keep low-priority pause pods running so incoming job Pods preempt them and start right away instead of waiting for a node.

On a scale-to-zero cluster, pause pods conflict with scale-in. A pause pod counts as a Pending pod outside k3s's own addons, so the scaler treats it as intent and provisions a node for it. As long as any pause pod exists, the cluster won't return to zero.

To use both together, configure the pause-pod policy's cron schedule. GitLab's idle_count is per-period and defaults to 0, so setting idle_count = 0 outside working hours scales the pause-pod Deployment to zero and clears intent so nodes scale down as usual. Don't set a 24x7 idle_count > 0 on a cluster expected to reach zero.

Pause-pod RBAC is covered in 01. Because priorityclasses is cluster-scoped, it needs a ClusterRole.