Déjà Vu Service
- Alerts: https://alerts.gitlab.net/#/alerts?filter=%7Btype%3D%22dejavu%22%2C%20tier%3D%22sv%22%7D
- Label: gitlab-com/gl-infra/production~“Service::Dejavu”
Logging
Section titled “Logging”Déjà Vu sizes GitLab Runner job pods from what the same job needed last
time. On the Kubernetes-based private shard every job pod would otherwise get
the shard’s static pod_cpu_request / pod_memory_limit defaults; Déjà Vu
replaces those, per pod at admission time, with values derived from that
job’s own execution history. A job it has never seen is left untouched.
Background, measurements and the staged rollout plan live in the design document. This page is the operational view.
How it works
Section titled “How it works”Two stateless Deployments and one dedicated Prometheus, all in namespace
runner-workloads-system on each workloads cluster:
| Component | Role |
|---|---|
dejavu-webhook | Mutating admission webhook. On job-pod CREATE it fetches the job’s precomputed statistics from the dedicated Prometheus (one instant query, 1 s timeout, 60 s per-identity cache) and either sets the pod-level memory request/limit and CPU request, keeping the runner’s CPU limit (enforce mode), or only annotates the pod with what it would have set (shadow mode). |
dejavu-observer | kopf operator watching runner-workloads. On a job pod’s DELETED watch event it fetches the job’s final state and duration from the GitLab Jobs API and its peak memory / p95 CPU from Cloud Monitoring, and remote-writes one sample per metric to the dedicated Prometheus. |
prometheus-dejavu-prometheus-0 | The observation store: a Prometheus custom resource run by the prometheus-operator that k8s-monitoring-stack deploys on the cluster. 15 days retention on a 20 GiB volume, remote-write receiver on, scrapes nothing, remote-writes nowhere. Its recording rules compute the statistics below once a minute. |
Neither Deployment holds state, so restarting them loses nothing. The webhook
scales freely (webhook.replicaCount); the observer is fixed at one replica
in the chart (two observers would record every job twice). The observer is
watch-only: it puts no finalizer on job pods, so a pod never waits for it and
a deletion while it is down is simply not observed. It is called an observer rather than an exporter because
nothing scrapes it: it joins three sources into one observation and pushes it.
The allocation rule, for a job identity (project_path + job_name) with at
least MIN_SAMPLES (default 3) runs in the last 14 days:
memory = p95 over runs of memory_peak x 1.2 headroom x failure multipliercpu = mean over runs of per-run p95 CPUThe failure multiplier is 3.0 after an OOMKilled run in the last 7 days when the most recent run did not succeed, 2.5 when the job has not succeeded in the window, and 1.3 / 1.5 / 2.0 after 1 / 2 / 3+ consecutive failures. Results are clamped to 0.1–8 cores and 128 MiB–24 GiB (chart values). Only successful runs feed the baseline.
Every statistic is a recording rule (PrometheusRule/dejavu), so it can be
queried and plotted directly on the dedicated instance:
| Series | Meaning |
|---|---|
dejavu_job_memory_peak_bytes, dejavu_job_cpu_p95_cores, dejavu_job_duration_seconds, dejavu_job_allocated_* | one sample per finished job, labelled by identity and job_state |
dejavu_job_result{job_state, termination_reason} | one sample per finished job |
dejavu_job_failure_streak | consecutive failures as of that run |
dejavu:job_memory_baseline_bytes, dejavu:job_cpu_baseline_cores | the p95 / mean baselines (max of all runs when nothing succeeded) |
dejavu:job_runs, dejavu:job_successes, dejavu:job_oom_recent, dejavu:job_failure_streak | the counts behind MIN_SAMPLES and the multipliers |
Every decision is written to the job pod as annotations, whether or not it was applied:
dejavu/cpu: 215mdejavu/memory: 278Midejavu/mode: shadow | enforceWhere things are
Section titled “Where things are”| What | Where |
|---|---|
| Clusters | runner-workloads in gitlab-r-saas-l-p-amd64-1 (ArgoCD environment gprd-ci-workloads; more workloads clusters inherit the env-level app.yaml) |
| Namespace | runner-workloads-system (job pods are in runner-workloads) |
| ArgoCD service | services/dejavu/ in argocd/apps; Application dejavu--<cluster hash> |
| Chart | gitlab/dejavu in gl-infra/charts, version pinned in env/gprd-ci-workloads/app.yaml |
| Source and images | gl-infra/dejavu; images …/dejavu/webhook:vX.Y.Z and …/dejavu/observer:vX.Y.Z, released by semantic-release, bumped in the chart by Renovate |
| Observation store | Prometheus/dejavu-prometheus (operator-managed StatefulSet prometheus-dejavu-prometheus, claim prometheus-dejavu-prometheus-db-prometheus-dejavu-prometheus-0), Service dejavu-prometheus:9090, rules in PrometheusRule/dejavu; all from the chart |
| Fleet metrics | PodMonitor/dejavu (label release: k8s-monitoring-stack) has runners-platform-prometheus scrape the webhook’s /metrics into the runners-platform Mimir tenant: dejavu_admissions_total{mode,outcome}, dejavu_stats_lookups_total{outcome}, dejavu_stats_lookup_seconds |
| Webhook registration | cluster-scoped MutatingWebhookConfiguration/dejavu, failurePolicy: Ignore, timeoutSeconds: 5, scoped to namespace runner-workloads and pods with the manager.runner.gitlab.com/name label |
| TLS | cert-manager Certificate/dejavu-webhook issued by ClusterIssuer/gprd-ci-workloads-ca (from services/cert-manager/env/gprd-ci-workloads/); CA injected into the webhook config by cainjector; serving cert reloaded in-process on rotation |
| GitLab token | gitlab-org group access token (read_api), created and rotated by Terraform in infra-mgmt environments/gitlab-com/group_gitlab-org_dejavu.tf, delivered by External Secrets from k8s/env/gprd-ci-workloads/ns/runner-workloads-system/dejavu into Secret gitlab-credentials |
| GCP access | Workload Identity: KSA dejavu → GSA dejavu-observer@<project> with roles/monitoring.viewer, in config-mgmt environments/r-saas-l-p-amd64/dejavu.tf |
| AppProject | runner-workloads (argocd/config), which whitelists the MutatingWebhookConfiguration and the External Secrets ClusterRoleBinding, and ignores the operator-created Prometheus claim as an orphan |
All configuration is Helm values in argocd/apps; there is nothing to
change on the cluster by hand.
Operational controls
Section titled “Operational controls”Every control is an MR to argocd/apps on
services/dejavu/values.yaml (or the env-level values file),
then an ArgoCD sync.
| I want to… | Change |
|---|---|
| Stop enforcing, keep observing | webhook.shadow: true. New pods keep the runner defaults; annotations still record what would have been set. This is the first move for any suspected sizing regression. |
| Start enforcing | webhook.shadow: false. Read the pre-enforcement checks first. |
| Stop admission now | Delete the MutatingWebhookConfiguration. Immediate and temporary (ArgoCD self-heal recreates it): new pods are neither sized nor annotated. The observer keeps running, still calling the GitLab Jobs API and Cloud Monitoring and writing to the dedicated Prometheus; scale deployment/dejavu-observer to 0 if that has to stop too. |
| Stop everything | Set dejavu.enabled: "false" in env/gprd-ci-workloads/app.yaml. Removes the Application, so webhook, observer and Prometheus all go; the Prometheus claim stays, delete it by hand if the history should go too. |
| Be more or less conservative | webhook.memoryHeadroom (default 1.2), webhook.minSamples (3), webhook.cpu.* / webhook.memoryMiB.* clamps |
| Change how jobs are grouped | jobKeyFields (project_path,job_name; job_stage may be added). The key is the label set on every series, so changing it starts new series: every job cold-starts until it has MIN_SAMPLES runs under the new key, and the old series age out after 15 days. |
| Keep history longer or shorter | prometheus.retention (15d) together with prometheus.window (14d, must fit inside) and prometheus.storage.size (20Gi). |
| Only ever annotate, never block | Already the case: failurePolicy: Ignore and a 5 s timeout mean an unavailable webhook yields the runner defaults, never a rejected pod. |
Running pods are never affected by any of these; only new job pods are.
Health signals
Section titled “Health signals”# Both Deployments upkubectl -n runner-workloads-system get deploy,pods -l app.kubernetes.io/name=dejavu
# Prometheus up and reconciledkubectl -n runner-workloads-system get prometheus dejavu-prometheuskubectl -n runner-workloads-system get pods -l operator.prometheus.io/name=dejavu-prometheus
# Webhook: mode, request count, cached identitieskubectl -n runner-workloads-system exec deploy/dejavu-webhook -- \ python -c "import urllib.request;print(urllib.request.urlopen('http://localhost:8080/health').read().decode())"
# What the webhook decided for recent job podskubectl -n runner-workloads get pods -o custom-columns='NAME:.metadata.name,MODE:.metadata.annotations.dejavu/mode,CPU:.metadata.annotations.dejavu/cpu,MEM:.metadata.annotations.dejavu/memory,LIMITS:.spec.resources.limits'
# Observer is recordingkubectl -n runner-workloads-system logs deploy/dejavu-observer --tail=50 | grep recorded
# Ask the store directly (port-forward, then PromQL)kubectl -n runner-workloads-system port-forward svc/dejavu-prometheus 9090 &curl -s 'localhost:9090/api/v1/query?query=count(dejavu:job_runs)' # identities with historycurl -sg 'localhost:9090/api/v1/query?query=sum(count_over_time(dejavu_job_result[1h]))' # observations in the last hourcurl -s 'localhost:9090/api/v1/rules' | jq '.data.groups[].rules[] | {name, health, lastError}'
# TLS chain healthykubectl -n runner-workloads-system get certificate dejavu-webhookkubectl get mutatingwebhookconfiguration dejavu -o jsonpath='{.webhooks[0].clientConfig.caBundle}' | wc -c # non-zeroThings that look wrong but are not:
cached_identities: 0right after a fresh deploy: the store starts empty and a job needsMIN_SAMPLESruns before it is sized. Expect a few hours of cold start on a new cluster, and one evaluation interval (1 m) between an observation landing and the statistics reflecting it.- Job pods without
dejavu/*annotations: the job had no history (cold start), the statistics lookup failed (dejavu_admissions_total{outcome="lookup_failed"}rises), or it is not a runner job pod. All are admitted unmodified by design. - Observations without
dejavu_job_memory_peak_bytes/dejavu_job_cpu_p95_coressamples: Cloud Monitoring ingestion lag or a very short job. The result and streak samples are still written; the baselines simply do not include that run.
Before switching shadow to enforce
Section titled “Before switching shadow to enforce”Shadow mode exists so that enforcement is a data-backed decision. All of it is PromQL on the dedicated instance (port-forward as above), on live traffic:
- Would-OOM rate is zero on jobs with history: successful runs whose peak
exceeded what Déjà Vu would have given them, per identity:
dejavu_job_memory_peak_bytes{job_state="success"} > on (project_path, job_name) (dejavu:job_memory_baseline_bytes * 1.2)should return nothing over the review window. - Coverage: the share of job pods that carry
dejavu/mode: shadow(i.e. had history); in Mimir,dejavu_admissions_total{outcome="patched"} / ignoring (outcome) sum without (outcome) (dejavu_admissions_total). - Projected saving:
Σ proposed × duration / Σ allocated × duration:sum(dejavu:job_memory_baseline_bytes * 1.2 * on (project_path, job_name) group_right dejavu_job_duration_seconds) / sum(dejavu_job_allocated_memory_bytes * dejavu_job_duration_seconds)over[14d], and the same for CPU. - Latency:
dejavu_stats_lookup_seconds_sum / dejavu_stats_lookup_seconds_countin Mimir stays in the low milliseconds; API-server admission metrics agree.
Then flip webhook.shadow in a canary-sized step if possible (a dedicated
project’s jobs, or a second workloads cluster) before the whole environment.
Troubleshooting
Section titled “Troubleshooting”Job pods are not being annotated at all.
In order: is the dejavu-webhook Deployment Available? Is caBundle non-empty on
the MutatingWebhookConfiguration (cainjector needs
services/cert-manager synced on this cluster and the Certificate Ready)?
Does the job pod carry manager.runner.gitlab.com/name and live in
runner-workloads? With failurePolicy: Ignore the API server logs a
failed calling webhook warning and admits the pod, so check API-server
audit/logs for dejavu-webhook.runner-workloads-system.svc.
Certificate not Ready / caBundle empty.
kubectl -n runner-workloads-system describe certificate dejavu-webhook.
Usually the ClusterIssuer/gprd-ci-workloads-ca is missing (cert-manager
Application not synced) or its root CA Secret was deleted. Fixing the issuer
is enough; cert-manager re-issues and cainjector re-injects.
Observer logs 401/403 from the GitLab API.
The group access token was rotated by Terraform but External Secrets has not
refreshed yet (refreshInterval: 15m), or the Vault path/property changed.
kubectl -n runner-workloads-system get externalsecret gitlab-credentials;
the observer re-reads the mounted Secret on every call, so no restart is
needed once the Secret is current. Observations written meanwhile carry
job_state="unknown" on their metric samples only: they count as neither
runs nor failures (an OOM-killed pod still counts as a failure, the pod
itself says so).
dejavu_stats_lookups_total{outcome="error"} or dejavu_admissions_total{outcome="lookup_failed"} rises.
The webhook cannot reach http://dejavu-prometheus.runner-workloads-system.svc:9090
within 1 s. Is the Prometheus Pod Running and its claim Bound? Is the
Prometheus resource RECONCILED=True (kubectl describe prometheus dejavu-prometheus
shows operator errors otherwise, for example an invalid field after an
operator upgrade)? Identities the webhook has seen in the last minute keep
their previous sizing (outcome="stale"); others are admitted unmodified.
Nothing is blocked.
Observer logs remote write failed.
Same checks as above, plus the response body in the log: 400 duplicate sample
means two runs of one identity wrote the same millisecond (handled by the
observer; if it recurs, it is a bug), 400 out of order means a sample older
than the 10-minute out-of-order window (prometheus.outOfOrderTimeWindow).
That observation is lost; nothing else is affected.
Recording rules unhealthy.
curl -s localhost:9090/api/v1/rules | jq '.data.groups[].rules[] | select(.health != "ok")'
after a port-forward. The rules come from PrometheusRule/dejavu; the
Prometheus resource selects them by the chart’s standard labels, so a hand
edit that changes labels detaches them.
Observer logs Cloud Monitoring permission errors.
Workload Identity binding: KSA dejavu must be annotated with the GSA and the
GSA must have roles/iam.workloadIdentityUser for
<project>.svc.id.goog[runner-workloads-system/dejavu] plus
roles/monitoring.viewer. Both are in config-mgmt; check the Atlantis
apply.
Job pods stuck Terminating in runner-workloads with a
kopf.zalando.org/KopfFinalizerMarker finalizer.
Only possible with an observer older than v1.0.3, which held a finalizer on
every job pod and left ~400 of them stuck when it was OOM-killed in a restart
loop (argocd/apps!4592).
Since v1.0.3 the observer is watch-only and never patches pods. If the
finalizer is still found on pods, remove it by hand:
kubectl -n runner-workloads get pods -o json \ | jq -r '.items[] | select(.metadata.finalizers // [] | index("kopf.zalando.org/KopfFinalizerMarker")) | .metadata.name' \ | xargs -r -n1 kubectl -n runner-workloads patch pod --type=json -p '[{"op":"remove","path":"/metadata/finalizers"}]'Observer logs queue full, job ... not observed.
Deletions are copied into a bounded queue (QUEUE_SIZE, 1000) drained by
WORKERS (8) threads; each observation takes two Cloud Monitoring calls and a
GitLab API call that retries for up to 17 s while the job is still running.
A full queue drops deletions rather than hold pod state in memory. Occasional
drops during a mass cancellation are expected and cost only those samples;
sustained drops mean the lookups are slow (check GitLab API and Cloud
Monitoring latency in the logs) or the workers need raising via the
Deployment’s env.
Observer OOM-killed / restart loop.
The observer holds one pod event at a time (job pods are 100+ KB of JSON each,
the initial list is paged at LIST_CHUNK_SIZE = 100) plus the bounded queue,
so its memory should not scale with the pod count. If it still OOMs, look at
container_memory_working_set_bytes{namespace="runner-workloads-system", container="observer"}
against the pod count in runner-workloads and raise observer.resources in
the chart. Pods are never blocked by an observer outage; observations during
it are lost.
A job is being sized too small / OOMKilled repeatedly.
The failure multipliers make the next allocation 3x after an OOM, so a job
should self-correct within one or two runs; a job that keeps failing has a
peak far above its history (code change, new parallel slice). Look at its
series: dejavu_job_memory_peak_bytes{project_path="…", job_name="…"}[14d]
against dejavu:job_memory_baseline_bytes{…}. If it is widespread, switch to
shadow and raise memoryHeadroom. Do not point job authors at the executor’s
KUBERNETES_* overwrite variables as a fix yet: the runner applies them at pod
creation, but the webhook currently overwrites pod-level resources regardless
whenever it has history for the job (see known gaps).
Prometheus Pod Pending, volume errors.
The claim is ReadWriteOncePod, so a stuck old Pod holds the volume and the
operator’s StatefulSet will not recreate prometheus-dejavu-prometheus-0
until the old one is gone. Check for a Pod in Terminating from a previous
rollout (on an unreachable node it needs kubectl delete pod … --force) and
for the claim’s node affinity (the disk is zonal). The Déjà Vu Deployments
have no volumes.
Prometheus disk filling.
prometheus_tsdb_storage_blocks_bytes on the instance. retentionSize (18 GiB)
caps it below the 20 GiB volume, so it degrades to shorter effective retention
rather than failing. If cardinality grew (a jobKeyFields change doubles the
series for 15 days), either wait or grow prometheus.storage.size.
Known gaps
Section titled “Known gaps”Recorded here so operators are not surprised; tracked in the design document’s open questions and iterations:
- Author-set
KUBERNETES_*overwrite variables are not yet respected: the webhook replaces pod-level resources when it has history for the job. - No parallel-job normalisation:
rspec 3/32andrspec 4/32are separate identities. - History is per cluster. With one workloads cluster in the shard that is the whole history; a second cluster would see a fraction of each identity’s runs until the observers share a receiver (design-document open question).
- No alerts yet; the metrics for them exist (see health signals).
- Enforce mode sets
limit == requestfor memory only. The CPU request is the prediction, capped at the pod’s CPU limit, and the CPU limit the runner set for the size class (2 / 4 / 8 / 16 cores) is left as is, so a job can still burst up to what its tag promised. - The observer and the Prometheus are single replicas by construction (one
kopf instance; a remote-write receiver cannot be made HA by adding replicas).
Losing either costs sizing, never a job’s outcome: an unavailable webhook is
covered by
failurePolicy: Ignore, an unavailable store by the fall-back to runner defaults, and the history survives on the persistent volume. An observer outage has no effect on job pods (no finalizer since v1.0.3); the deletions during it are not observed.
Pitfalls
Section titled “Pitfalls”- Changing
jobKeyFieldsstarts new series: every job cold-starts until it hasMIN_SAMPLESruns under the new key, and both label sets coexist in the store until the old ones age out. - Deleting the
MutatingWebhookConfigurationby hand is a short-lived fix: ArgoCD self-heal recreates it. Usewebhook.shadowfor anything that must survive a sync. - The
runner-workloadsAppProject whitelists cluster-scoped resources by name. Renaming the release (or droppingfullnameOverride: dejavu) renames theMutatingWebhookConfigurationand the sync fails with a project policy error untilargocd/configis updated. - The webhook caches statistics for 60 s and the rules evaluate every 1 m, so a new observation influences allocations within about two minutes. Jobs that re-run faster than that after an OOM get the previous allocation once more; do not raise either interval much.
- The dedicated Prometheus is not the platform one:
runners-platform-prometheusink8s-monitoring-stackis diskless and remote-writes to Mimir. Pointing Déjà Vu at it (prometheus.url) would lose the history on every restart. - Expected noise at observer start: nine
APIForbiddenError ... cannot list resource "namespaces"lines, thenFalling back to a list of namespaces which are assumed to exist: {'runner-workloads'}. kopf lists namespaces to resolve--namespace; the ServiceAccount deliberately has only a Role on pods inrunner-workloads, and the fallback is the configured behaviour. Handlers start about 25 s later. AnythingForbiddenonpodsis a real problem.