Skip to content

fix: handle failed jobs and stuck scaling phases (#7793) - #10004

Open
jmealo wants to merge 8 commits into
cloudnative-pg:mainfrom
jmealo:dev/7793-phase-1
Open

jmealo wants to merge 8 commits into
cloudnative-pg:mainfrom
jmealo:dev/7793-phase-1

Conversation

@jmealo

@jmealo jmealo commented Feb 17, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When a job fails or is manually deleted during replica creation, the reconciler could get stuck indefinitely in a scaling phase. This PR fixes that by:

  • Ensuring failed jobs don't block reconciliation (they are excluded from runningJobNames())
  • Preserving failed jobs for troubleshooting (only completed/successful jobs are cleaned up)
  • Adding a safety net to clear stuck scaling phases when the cluster is actually healthy

All signals are deterministic: no timeouts.

Changes

File Change
pkg/utils/job_conditions.go Add IsJobFailed() helper
api/v1/cluster_funcs.go Add IsScalingPhase() helper
internal/controller/cluster_status.go runningJobNames() excludes failed jobs
internal/controller/cluster_cleanup.go cleanupCompletedJobs() preserves failed jobs (only deletes successful ones)
internal/controller/cluster_controller.go Safety net in reconcileResources clears stuck scaling phase

What This Fixes

  1. Failed jobs blocking reconciliation: Previously, runningJobNames() only excluded completed jobs. A failed job would still be considered "running" and block the reconciler.

  2. Stuck scaling phase after manual job deletion: The workaround for [Bug]: Cluster reconciliation loop gets stuck when scaling replicas due to failed snapshot recovery jobs #7793 was to manually delete the stuck job, but the cluster phase would remain stuck on "Creating a new replica". The new safety net detects when the cluster is in a scaling phase but has the correct instance count with no running jobs, and clears the phase to Healthy.

Design Decision: Failed Jobs Are Preserved

Failed jobs are intentionally left in place (not cleaned up) for two reasons:

Only completed/successful jobs are cleaned up by cleanupCompletedJobs().

Test Plan

  • Unit tests for IsJobFailed() helper
  • Unit tests for IsScalingPhase() helper
  • Unit tests for runningJobNames() excluding failed jobs
  • Unit tests verifying cleanupCompletedJobs() does NOT delete failed jobs
  • All existing tests pass (562 specs across affected packages)
  • E2E: Failed join job does not block scaling (AKS)
  • E2E: Safety net clears stuck phase when instances match desired count (AKS)

Related

Fixes #7793

@jmealo
jmealo requested a review from a team February 17, 2026 21:41
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Feb 17, 2026
@cnpg-bot cnpg-bot added backport-requested ◀️ This pull request should be backported to all supported releases release-1.25 release-1.28 labels Feb 17, 2026
@github-actions

Copy link
Copy Markdown
Contributor

❗ By default, the pull request is configured to backport to all release branches.

  • To stop backporting this pr, remove the label: backport-requested ◀️ or add the label 'do not backport'
  • To stop backporting this pr to a certain release branch, remove the specific branch label: release-x.y

@gbartolini

Copy link
Copy Markdown
Contributor

For maintainers' attention to evaluate inclusion in 1.29.0.

@armru armru self-assigned this Feb 18, 2026
jmealo and others added 5 commits February 18, 2026 10:59
When a job fails or is manually deleted during replica creation, the
reconciler could get stuck. This fix ensures failed jobs don't block
reconciliation by excluding them from runningJobNames().

Note: Failed jobs are intentionally NOT deleted by cleanupCompletedJobs.
They are kept for troubleshooting and serve as markers for fallback
logic (e.g., snapshot recovery fallback in phase 2).

Fixes: cloudnative-pg#7793

Assisted-by: Claude Opus 4.5
Signed-off-by: Jeff Mealo <[email protected]>
Add E2E tests to verify:

1. Cluster scaling resilience:
   - Create cluster, scale up, attempt to disrupt join job
   - Verify cluster reaches healthy state regardless of job outcome
   - Verify scaling back down works correctly

2. Safety net clears stuck phase:
   - Create healthy cluster
   - Manually set phase to "Creating replica" to simulate stuck state
   - Verify safety net clears phase when instances match desired count

These tests validate the fix for the reconciliation loop getting stuck
when jobs fail during scaling operations.

Assisted-by: Claude Opus 4.5
Signed-off-by: Jeff Mealo <[email protected]>
Use the typed constant corev1.ConditionTrue instead of the string
literal "True" for checking job failure conditions. This matches the
project convention used in pod_conditions.go and other condition checks.

Assisted-by: Claude Opus 4.5
Signed-off-by: Jeff Mealo <[email protected]>
Signed-off-by: Armando Ruocco <[email protected]>
…ng phase

Add allInstancesAreActive() check to the safety net that clears stuck
scaling phases. This prevents an unnecessary PhaseHealthy status write
when instances exist but aren't fully active yet, avoiding a brief
status flicker before the later inactive-instance check overrides it.

Signed-off-by: Armando Ruocco <[email protected]>
@armru

armru commented Feb 18, 2026

Copy link
Copy Markdown
Member

/test limit=aks ft=replication tl=1

@github-actions

Copy link
Copy Markdown
Contributor

@armru
armru force-pushed the dev/7793-phase-1 branch 2 times, most recently from 98fb519 to 4a10435 Compare February 18, 2026 15:16
Replace racy pod-deletion approach with a synthetic failed job: create
a Job with correct CNPG labels and cluster owner reference, set its
status to Failed, then set the cluster phase to "Creating replica".
This guarantees the test exercises the failed-job exclusion in
runningJobNames() without racing against a real Kubernetes job.

Signed-off-by: Armando Ruocco <[email protected]>
@armru

armru commented Feb 18, 2026 •

Copy link
Copy Markdown
Member

Hello Jeff, some of my considerations after having spent a bit of time on the patch:

Drawbacks of the current approach

  1. Safety net complexity — We needed a 4-condition guard just to recover from a stuck phase. That's a symptom, not a fix for the root cause.
  2. Failed jobs accumulate — No automatic cleanup, relies on manual kubectl delete.

3. Dual-purpose objects — A K8s Job is being used both as infrastructure (run a task) AND as application state (don't retry this snapshot).

  1. Global blast radius — The runningJobNames() change applies to ALL job types (join, initdb, pgbasebackup, snapshot-recovery), not just the snapshot case.

Alternative design

Store the failure state where on the Cluster instead of using jobs as a state:

  1. When a job fails, record the failure on the Cluster (e.g., a status condition like SnapshotRecoveryFailed with the snapshot name, or an annotation like cnpg.io/failed-snapshots: snap-1,snap-2).
  2. Clean up failed jobs in cleanupCompletedJobs and record the failure state on the Cluster.
  3. Snapshot fallback logic reads the Cluster state, not the job list. It skips snapshots listed as failed and tries alternatives.
  4. User use plugin to re-enable a snapshot. More discoverable than knowing to delete a specific Job. CNPG status can be enhanced to list excluded snapshots

This eliminates:

  • The safety net entirely (no stuck phases because failed jobs are cleaned up)
  • The runningJobNames() change (failed jobs don't linger)
  • Failed job accumulation
  • The dual-purpose object pattern

And it gains:

  • Explicit, visible failure state on the Cluster (shows up in kubectl describe cluster OR kubectl cnpg status)
  • Cleaner separation between job lifecycle and application retry logic
  • The fallback decision is made by the reconciler based on Cluster state, not by inferring from the presence/absence of Job objects

@jmealo

jmealo commented Feb 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @armru. Let me work through each point.

runningJobNames() — "Global blast radius" (Point 4)

  • A failed job isn't a running job — this seems like a correctness fix for all job types, not just snapshot recovery. If an initdb or pg_basebackup job fails, the reconciler shouldn't spin waiting for it either.
  • Is there a job type where we'd want a failed job treated as still running? I couldn't think of one but may be missing something.

Safety net (Point 1)

Would you still see value keeping it as defense-in-depth, or does it feel unnecessary? Open to it just logging instead of correcting if that's preferable.

Failed job accumulation (Point 2) and dual-purpose objects (Point 3)

That said, the Cluster annotation/condition idea is interesting for #10005. A few things I'd want to think through:

  • Observability tradeoff — Failed jobs carry pod logs, events, and exit codes. An annotation like cnpg.io/failed-snapshots: snap-1 doesn't. Would we need to build additional surfacing in cnpg status?
  • CRD impact — Would a status condition require API review, or would an annotation be lighter weight?
  • Re-enabling — Is there existing plugin infrastructure for this, or would that need to be built?

Context on the approach

The original PR (#7794) actually took a similar direction — deleting failed jobs and building detection/recovery machinery. The scope grew partly because deleting jobs meant needing mechanisms to surface failure info back to users.

That's why I closed it and split into these two targeted PRs (#1004 and #1005)

Preserving failed jobs was a deliberate simplification: the job itself is the record, and existing K8s tooling already knows how to surface it. Happy to explore Cluster-level state as a follow-up once the core fix is in.


How would you like to proceed?

I see a few options for this PR:

  1. Keep as-is — runningJobNames() fix + safety net + preserve failed jobs. Rework state management in feat: fallback to pg_basebackup on snapshot recovery failure (#7793) #10005 per your proposal.
  2. Clean up failed jobs here too: but that means feat: fallback to pg_basebackup on snapshot recovery failure (#7793) #10005 needs the Cluster annotation approach from the start (scope increase).
  3. Something else? open to alternatives.

@jmealo

jmealo commented Feb 18, 2026

Copy link
Copy Markdown
Contributor Author

One thing I didn't articulate well earlier: the retained failed job isn't just for troubleshooting, it's a user-facing control mechanism.

If CNPG falls back to pg_basebackup after a snapshot failure, and the user fixes the underlying issue, they can kubectl delete job <failed-job> to re-enable the snapshot fast path. They can also kill the slow recovery job if they
don't want to wait. This uses standard K8s operations: no CNPG-specific knowledge, no plugin, no patching annotations.

With Cluster-level state, the equivalent recovery requires knowing how to clear a CNPG-specific condition or annotation. At 3am, kubectl delete job is a lot more intuitive.

@jmealo

jmealo commented Feb 18, 2026

Copy link
Copy Markdown
Contributor Author

Slack discussion summary (@armru + @jmealo)

Should failed jobs be retained or cleaned up?

@armru's position:

  • Jobs are infrastructure, not state: failure tracking belongs in Cluster status
  • It's reasonable to expect a logging stack in production for troubleshooting
  • Retaining failed jobs sets a precedent: the same argument could apply to failed instances or any other resource
  • The operator can't cover all cases; need to draw a line on what it's responsible for surfacing

@jmealo's position:

  • Failed jobs carry rich context (pod logs, events, exit codes) that existing K8s tooling already surfaces
  • Not all users have logging configured for operator namespaces/jobs: deleting the evidence shifts the burden to CNPG to surface it another way
  • The retained failed job also serves as a user-facing control mechanism: if CNPG falls back to pg_basebackup (slow path) after a snapshot failure, the user can fix the underlying issue and kubectl delete job to re-enable the
    snapshot fast path: no CNPG-specific knowledge, no plugin, no patching annotations. Standard K8s operations that anyone debugging at 3am already knows.
  • With Cluster-level state, the equivalent recovery requires knowing how to clear a CNPG-specific condition or annotation
  • The original PR (Fixes Issue 7793: Stuck reconciliation fixes #7794) took the delete-and-detect approach; scope grew partly because of this, leading to the split into fix: handle failed jobs and stuck scaling phases (#7793) #10004/feat: fallback to pg_basebackup on snapshot recovery failure (#7793) #10005

Where we landed:

  • Both agreed this is a broader project-wide question about how CNPG handles failed resources generally, not specific to this job type
  • @jmealo offered to go back to cleaning up failed jobs, with possible retention until cluster is healthy or a configurable maxAge/maxTTL
  • @armru noted he won't oppose the patch if other maintainers are OK with it, and encouraged hearing other opinions
  • Open question: should changes to failed job lifecycle happen in this PR or a follow-up?

Summarized by: Claude 4.5 Opus

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-requested ◀️ This pull request should be backported to all supported releases bug 🐛 Something isn't working release-1.28 release-1.30 size:L This PR changes 100-499 lines, ignoring generated files.

Projects

Status: Waiting for First Review

Development

Successfully merging this pull request may close these issues.

[Bug]: Cluster reconciliation loop gets stuck when scaling replicas due to failed snapshot recovery jobs

5 participants