Skip to content

Run pg_repack as a Kubernetes Job - #273

Merged
fcollman merged 5 commits into
masterfrom
repack-k8s-job
Nov 9, 2026
Merged

fcollman merged 5 commits into
masterfrom
repack-k8s-job

Conversation

@fcollman

@fcollman fcollman commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

instead of on the workflow Celery queue

KEDA scales the workflow queue's deployment on queue length and in-flight tasks, and a repack (acks_late=False, acked at its start) counts as neither. On 2026-11-09 it scaled celery-producer to zero 37 minutes into a repack of minnie v1926's synapses_pni_2; the 100-minute grace period ran out and killed pg_repack mid index build, leaving its half-built copy (~122 GB) and trigger behind, while the job record said "running".

  • k8s_jobs.py: submit a Job from the Helm-rendered template mounted at MAINTENANCE_JOB_TEMPLATE_PATH (module + JSON kwargs patched in as env), and read back a normalised status with the failure reason (deadline, OOMKilled, evicted, deleted).
  • jobs/repack.py: the Job's entrypoint; runs run_repack in an app context and records progress in the same redis status record as before.
  • table_maintenance: the Celery task's body is now run_repack(); start_repack refuses while another repack holds the database, then submits a Job where MAINTENANCE_JOBS_ENABLED (the chart sets it), else queues the Celery task as before. Status reads reconcile with the Job: a Job that failed, vanished, or exited without a result marks the repack failed, releases the database lock, and, if pg_repack had started, says how to clean up (DROP EXTENSION pg_repack CASCADE; CREATE EXTENSION).

Needs the cave-helm-charts change that renders the Job template, the RBAC and the api wiring (materialize.maintenanceJobs).

…ueue

KEDA scales the workflow queue's deployment on queue length and in-flight tasks, and a
repack (acks_late=False, acked at its start) counts as neither. On 2026-11-09 it scaled
celery-producer to zero 37 minutes into a repack of minnie v1926's synapses_pni_2; the
100-minute grace period ran out and killed pg_repack mid index build, leaving its
half-built copy (~122 GB) and trigger behind, while the job record said "running".

- k8s_jobs.py: submit a Job from the Helm-rendered template mounted at
  MAINTENANCE_JOB_TEMPLATE_PATH (module + JSON kwargs patched in as env), and read back
  a normalised status with the failure reason (deadline, OOMKilled, evicted, deleted).
- jobs/repack.py: the Job's entrypoint; runs run_repack in an app context and records
  progress in the same redis status record as before.
- table_maintenance: the Celery task's body is now run_repack(); start_repack refuses
  while another repack holds the database, then submits a Job where
  MAINTENANCE_JOBS_ENABLED (the chart sets it), else queues the Celery task as before.
  Status reads reconcile with the Job: a Job that failed, vanished, or exited without a
  result marks the repack failed, releases the database lock, and, if pg_repack had
  started, says how to clean up (DROP EXTENSION pg_repack CASCADE; CREATE EXTENSION).

Needs the cave-helm-charts change that renders the Job template, the RBAC and the api
wiring (materialize.maintenanceJobs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Note

Copilot was unable to run its full agentic suite in this review.

Copilot review overview

2 open issues
What changed in this PR

Adds support for running long-running table repacks as dedicated Kubernetes Jobs (with Celery fallback), including status reconciliation for dead/disappeared Jobs and new tests to validate submission/status behaviors.

Changes:

  • Implement Kubernetes Job submission/status reading (materializationengine/k8s_jobs.py) and a Job entrypoint (materializationengine/jobs/repack.py).
  • Update table maintenance workflow to submit Jobs when enabled, reconcile unfinished records, and keep Celery as a fallback.
  • Add unit tests covering Job submission/status paths, reconciliation, and entrypoint exit codes.
File Description
tests/​test_table_maintenance.py Adds tests for Job-backed repacks, reconciliation behavior, and job entrypoint exit statuses.
tests/​test_k8s_jobs.py Introduces tests for Job template patching, submission errors, and status normalization.
materializationengine/​workflows/​table_maintenance.py Switches start_repack to optionally submit Kubernetes Jobs and reconciles unfinished status records.
materializationengine/​k8s_jobs.py Adds a thin Kubernetes Job submit/status module built from a Helm-rendered template.
materializationengine/​jobs/​repack.py Adds the Kubernetes Job entrypoint that runs run_repack from env-provided kwargs.
materializationengine/​jobs/​__init__.py Declares the jobs package for Kubernetes Job entrypoints.

Review effort: Lite

…for None

- start_repack builds the Job/task kwargs with options first and the validated job_id,
  database, table_name and order_by last, and refuses option names run_repack does not
  take (e.g. job_id).
- Reconciling a record with no database no longer computes or deletes the lock key
  "...repack_lock:None".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Critical races and inconsistent Kubernetes Job tracking can lose Job associations or prematurely release database locks, leaving repacks stuck or allowing overlapping repacks and unsafe cleanup.

4 open issues
2 resolved since last review

Review effort: Balanced

Comment thread materializationengine/k8s_jobs.py Resolved
Comment thread materializationengine/k8s_jobs.py Resolved
…ck release

- k8s_jobs: a Job is created in the namespace status reads use (MAINTENANCE_JOB_NAMESPACE),
  whatever the template says.
- A Job is finished only when none of its pods can still be running: a Job deleted with
  background propagation (404), or marked failed, can still have a pod terminating with
  pg_repack inside, and calling it finished released the database lock under a live
  repack. Pods that cannot be listed count as live.
- _set_status merges with WATCH/MULTI, so the runner's progress write can no longer drop
  the k8s_job name the api added meanwhile (which would have left a killed repack
  unreconciled). Reconciliation's "failed" write applies only if the record is still
  unfinished.
- Locks are released with an atomic compare-and-delete, so releasing an old job's lock
  cannot remove a newer repack's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

A pod/Job deletion race can prematurely release a live repack’s database lock, while missing Redis Job associations can leave killed jobs recorded as running and retain their locks until expiry.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

High severity Check pod liveness before treating a missing Job as finished

materializationengine/​k8s_jobs.py:163

The pod list can be empty, then a pod can start before the Job read returns 404 following background deletion. This reports finished=True despite a live repack, allowing _reconcile to release its database lock prematurely. Read the Job first, then check pod liveness before declaring it finished or deleted.

Medium severity Persist and recover Job association after uncertain submission

materializationengine/​workflows/​table_maintenance.py:309

If the API process exits before this write, or Kubernetes accepts creation but the response times out, the Job can run without a k8s_job association in Redis. The runner does not restore that field, so a later killed Job can remain recorded as running and retain its lock until expiry. Persist a client-generated Job name before creation and reconcile uncertain submission outcomes, or add a job-ID label and recover the association on status reads.

4 resolved since last review

Review effort: Balanced

…before its pods

- start_repack picks the Job's name itself (k8s_jobs.job_name: prefix + random suffix)
  and records it in the status record before creating the Job, so a Job whose creation
  response is lost (api restart, timeout) is still reconciled by name. If creation
  raises, the repack is marked failed only when the Job certainly does not exist.
- get_job_status reads the Job before listing its pods, so a pod that started between
  an empty pod list and a 404 for a Job being deleted is not missed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

A submission race can cause reconciliation to mark a live repack as failed and release its database lock, allowing overlapping repacks in the same database.

1 open issue

Review effort: Balanced

…esolved

Recording the Job name before creating it let a status read see a 404 before the Job
existed; if the runner then recorded progress before reconciliation re-read the record,
the live repack was marked failed and its lock released.

- start_repack stamps queued_at, and submitted_at once creation succeeded (or the Job is
  confirmed to exist after an error).
- _reconcile does not treat a missing Job as a failure while the submission is unresolved
  (no submitted_at, younger than SUBMIT_GRACE_SECONDS = 300 s; older means the submitter
  died), and observes the Job once more after re-reading the record, right before marking
  it failed and releasing the lock.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

Human assessment is needed because marking a deleted Job failed while its pod may still be running can stop reconciliation and leave a database lock held without cleanup guidance.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@fcollman
fcollman merged commit d93eb08 into master Nov 9, 2026
2 checks passed
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.

2 participants