Repository navigation
feat(instance-manager): move primary isolation check to the primary lease - #11357
Merged
mnencia merged 23 commits intoOct 17, 2026
Merged
Conversation
Contributor
|
❗ By default, the pull request is configured to backport to all release branches.
|
Contributor
Author
Contributor
Author
|
/test |
Contributor
|
@leonardoce, here's the link to the E2E on CNPG workflow run: https://github.com/cloudnative-pg/cloudnative-pg/actions/runs/32469615009 |
leonardoce
marked this pull request as ready for review
August 21, 2026 12:33
This was referenced Aug 21, 2026
armru
force-pushed
the
primary-lease-isolation
branch
from
September 1, 2026 11:31
8235ebc to
4fa80e0
Compare
Member
|
/test |
Contributor
|
@armru, here's the link to the E2E on CNPG workflow run: https://github.com/cloudnative-pg/cloudnative-pg/actions/runs/33511072870 |
NiccoloFei
force-pushed
the
primary-lease-isolation
branch
from
September 7, 2026 13:17
0ebe8be to
20d86e0
Compare
mnencia
approved these changes
Sep 7, 2026
mnencia
self-requested a review
September 7, 2026 15:18
NiccoloFei
force-pushed
the
primary-lease-isolation
branch
2 times, most recently
from
September 9, 2026 11:05
bcf10f6 to
18ca524
Compare
…en isolation Signed-off-by: Niccolò Fei <[email protected]>
…piry An isolated primary requests its own shutdown on the first retry-period tick after the renew deadline, once a peer probe bounded by the isolation check request timeout has confirmed the isolation. A replica may promote as soon as the lease has gone a full lease duration without a renewal. When the first sum is not below the lease duration, the old primary can still accept writes after the new one has been promoted. The existing validation only requires the lease duration to exceed the renew deadline, so timings such as 15/14/5 are accepted. Report them with an admission warning rather than an error, so that existing clusters using them can still be updated, and document the constraint next to the other lease invariants. Signed-off-by: Armando Ruocco <[email protected]>
The step-down monitor aged the lease from the moment the last write returned, using the wall clock. Both made it believe the lease was fresher than the replicas do. The API server can commit a write at any point during the call, and a replica starts timing the lease when it sees that commit, so a slow response delayed the step-down by as long as it took, up to the renew deadline. A backwards wall-clock step on the primary, from NTP or a VM resume, delayed it by the size of the step. Stamp the time the write started instead, as a reading of the monotonic clock. The age can then only be overestimated. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
The step-down monitor used to return as soon as the lifecycle manager accepted the immediate shutdown request, and it stopped together with the lease runnable. Two waits were left unbounded: the lifecycle manager is busy for the whole duration of any earlier command, and pg_ctl can fail against a postmaster that does not honour SIGQUIT, in which case the handler only logs. When any manager runnable fails, the manager also cancels every runnable's context at once, so the lease stopped being renewed and the monitor stopped while a smart shutdown that can outlast the lease was still running. In all three cases a replica may claim the lease while the old primary still accepts writes. The monitor now runs under the lifecycle manager's global context, so it lives until the process is about to exit, and keeps ticking after the verdict. On the last tick before the lease age reaches LeaseDuration, if the instance manager is still running, it sends SIGQUIT to the postmaster and exits with code 5. The manager is PID 1 of its container, so exiting makes the kernel kill anything left in the PID namespace; the signal only matters where the pod shares its process namespace. The restart is gated on re-acquiring the lease. The stop lands before a replica can claim the lease only if RenewDeadline, RetryPeriod and the peer probe timeout add up to less than LeaseDuration, which the admission webhook already warns about. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
When the lease record already named this pod, for instance after the instance manager restarted, tryTakeOver reported the lease as held on the strength of a read alone. A replica whose observation window ended between that read and the start of PostgreSQL could claim the lease in the meantime, and both pods would run a primary until the next renewal failed. The monitor was also blind for the renew deadline, as nothing had stamped the age of the lease yet. Rewrite the record with a write that is conditional on the version just read, so the same compare-and-swap that settles a claim settles the re-adoption. The write is bounded by the renew deadline. Once armed, the lease runnable also polls for as long as the process lives, whether or not the operator has since chosen another pod as the target primary. Such a pod could claim a released or silent lease, hold it as a replica and keep the real target from getting it. Take the lease over only when the Cluster the instance manager last reconciled names this pod as the target primary. Renewing a lease this pod already holds is not affected, and the observation window keeps running meanwhile. A stale cache can only delay the claim, as it delays a promotion. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
The isolation check no longer goes through the liveness probe. Describe the request for an immediate shutdown, the hard stop that bounds it by the lease age, the exit code, and the margin the admission webhook checks. Add an upgrade note for the change from the liveness-probe behavior of 1.30 and earlier. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
Once the monitor decided to step down, the age check was skipped, so a renewal that landed while the lifecycle manager was busy did not cancel the pending request. When the lifecycle manager became free, it received an immediate shutdown for a primary whose lease was fresh again. The window is a few seconds with the default timings but grows with the lease duration. Check the lease age before looking at the decision, and drop an undelivered decision when the age is back under the renew deadline. A request already delivered cannot be withdrawn and is never sent twice. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
Signed-off-by: Gabriele Bartolini <[email protected]>
A lease renewal that landed after the immediate shutdown was delivered still moved the deadline of the forced stop. When the request arrives while an in-place restart waits for PostgreSQL to come back, the lifecycle manager does not return once the postmaster exits, so the instance manager kept running without PostgreSQL. With the lease fresh no replica could take over, and the operator does not fail over while the restart is in progress, so the primary stayed down for as long as the restart kept waiting. Stop following the renewals once the request is delivered, so the forced stop fires on the deadline the lease had at that point. Signed-off-by: Armando Ruocco <[email protected]>
The spec stamped the lease with the current time and then watched for half of the renew deadline, 12.5 ms. On a loaded machine the lease could go stale again inside that window and the monitor would deliver the request, failing the spec for the wrong reason. Stamp the lease an hour ahead for the window and age it explicitly afterwards. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
A pod whose lease runnable was activated by an earlier targeting kept its observation window running after the target moved away. When the target came back to it, a record that had been stale for longer than the lease duration was claimed on the first poll. The old primary learns of the flip only through the peers' /failsafe answers, probed once per tick, and until then it keeps leading, so both pods could be primary for up to a retry period plus a probe timeout. Reset the window while this pod is not the target, so a claim comes at least a lease duration after the pod became the target. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
The cancelled-context spec of monitorLeaseAge is a subset of the one that asserts the monitor stays responsive while the send is declined, and that one alone fails when the send is made blocking. The failsafe Parse and Write specs collapse into one table that round-trips the JSON body, and the two webhook warning specs into one table. A mutation of the webhook bound comparison still fails the table. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
Both the endpoint and the peer probe already import pkg/management/url for the path, so the JSON body it carries lives next to it instead of in a package of its own with a separate Ginkgo suite. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
The declined-send, write-start stamp and read-versus-write rationales stay in the production comments and leave the specs that repeated them. The pointer to monitorLeaseAge as the step-down decider is kept in the runLeaderElection doc only. The timing margin and the default reaction time live in the primary isolation section of instance_manager.md, and failover.md links there. The upgrade note is release-note material. Assisted-by: Claude Signed-off-by: Marco Nenciarini <[email protected]>
mnencia
force-pushed
the
primary-lease-isolation
branch
from
October 17, 2026 15:56
759d802 to
048cc41
Compare
cnpg-bot
pushed a commit
to cloudnative-pg/api
that referenced
this pull request
Oct 17, 2026
…ease (cloudnative-pg/cloudnative-pg#11357) Primary self-fencing on network isolation used to live in the liveness probe: a failed peer check made the kubelet restart the pod about 30s after the partition began, through a smart shutdown bounded by `.spec.smartShutdownTimeout`. The reaction time depended on the liveness probe periods, which have nothing to do with how long a replica waits before it may promote, and the smart shutdown let open sessions keep committing on the isolated primary for up to 180s. The primary lease already measures what matters: a replica may promote once the lease has gone `leaseDurationSeconds` without a renewal. The instance manager now records, on a monotonic clock, when its last successful lease write started, and a goroutine checks that age every `retryPeriodSeconds`. Once the age passes `renewDeadlineSeconds` it probes the other instances in parallel and, if one is unreachable or names a different target primary, requests an immediate PostgreSQL shutdown, 10 to 13 seconds after the last renewal with the default timings. The trigger is the age, not an error from the election loop, because client-go's acquire path has no overall deadline and may never return while the API server is unreachable. If the primary has decided to step down and PostgreSQL is still running on the last tick before the lease reaches `leaseDurationSeconds`, because the lifecycle manager never took the request or `pg_ctl` failed, the instance manager sends `SIGQUIT` to the postmaster and exits with code 5. The monitor lives as long as the lifecycle manager, so it also fences when the manager stops because another runnable failed and the smart shutdown that follows outlasts the lease. A renewal that lands before the lifecycle manager takes the request withdraws the decision, so a primary whose lease is fresh again is not shut down late. Once the request is taken, later renewals no longer move the forced stop, so a restart that waits for PostgreSQL cannot keep the instance manager alive with a fresh lease. Taking the lease over is stricter in three ways. A record that already names this pod, for instance after a restart, is rewritten with a conditional write before the lease counts as held, so a replica that claims it in between makes the write fail and PostgreSQL is not started. Only the pod that the last reconciled Cluster names as target primary takes the lease over, since the runnable keeps polling for as long as the process lives. And the observation window starts only once the pod is the target, so a claim comes at least `leaseDurationSeconds` after the flip, which gives the old primary time to learn about the replacement from its peers. `/failsafe` now returns the responding instance's view of the target primary, through `pkg/management/url`, so a primary that still reaches every peer but learns from one that it has been replaced steps down too. A pre-upgrade peer answering plain `OK` counts as agreeing. The probe skips our own entry and peers without an IP. The liveness probe now always reports OK. The `.spec.probes.liveness.isolationCheck` stanza keeps its fields: `requestTimeout` and `connectionTimeout` bound each peer probe, while the probe periods no longer affect fencing and `.spec.smartShutdownTimeout: 0` is no longer needed for it. The admission webhook warns when `renewDeadlineSeconds + retryPeriodSeconds + isolationCheck.requestTimeout` is not below `leaseDurationSeconds`. The stop beats a replica only if that sum is below the lease duration. The signal goes to the postmaster only; the exit of PID 1 stops the rest. A cluster with `instances: 1`, or with the check disabled, or a primary that knows no peer to probe never steps down. One stale peer is enough to stop the primary. No Event is emitted; the step-down is logged under `primary-lease` and shows as a container restart, and the last-resort stop exits with code 5. Signed-off-by: Leonardo Cecchi <[email protected]> Signed-off-by: Armando Ruocco <[email protected]> Signed-off-by: Niccolò Fei <[email protected]> Signed-off-by: Marco Nenciarini <[email protected]> Signed-off-by: Gabriele Bartolini <[email protected]> Co-authored-by: Armando Ruocco <[email protected]> Co-authored-by: Niccolò Fei <[email protected]> Co-authored-by: Marco Nenciarini <[email protected]> Co-authored-by: Gabriele Bartolini <[email protected]> (cherry picked from commit cloudnative-pg/cloudnative-pg@eff1a21)
Contributor
|
Related to #11721 |
4 tasks done
wthrbtn
added a commit
to air-gapped/skills
that referenced
this pull request
Oct 27, 2026
…ry fencing onto the lease Classification: new-feature (in scope: HA parity vs Patroni failsafe is in the description and SKILL.md §HA parity) Source: cloudnative-pg/cloudnative-pg#11357 Before: pitfalls.md §HA describes only the 1.27-1.30 probe-based fence After: four-line note - 1.31 stops PostgreSQL 10-13 s after the last lease renewal when a peer is unreachable or names a different target primary; plan on 1.30 behaviour until the running minor is >= 1.31 #11357 (merged to main 2026-10-17 as eff1a2152) records the age of the last successful lease write, probes peers once it passes renewDeadlineSeconds, and requests an immediate shutdown; /failsafe now returns the responder's view of the target primary, so a primary that reaches every peer but learns it has been replaced steps down. The liveness probe no longer fences. Not on release-1.30 and not in v1.30.1, so the note is scoped to 1.31 and the 1.30 residual above it stays the operative guidance. The companion lease-gated start fix (#11356) was backported and is already in v1.30.1. Co-Authored-By: Claude Opus 5.5 <[email protected]>
gbartolini
pushed a commit
that referenced
this pull request
Nov 10, 2026
When the kubelet and the instance manager of the primary both hang, the walsenders keep the replicas' WAL receivers connected and the failover waits for them. The code already stops the old primary when either one still works (#11347, #11357, #11358). Document the recovery when neither does: the kubelet systemd watchdog plus a short liveness probe grace period. Otherwise the container kill waits for the pod grace period, 30 minutes by default. Closes #10591 Signed-off-by: Marco Nenciarini <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Primary self-fencing on network isolation used to live in the liveness probe: a failed peer check made the kubelet restart the pod about 30s after the partition began, through a smart shutdown bounded by
.spec.smartShutdownTimeout. The reaction time depended on the liveness probe periods, which have nothing to do with how long a replica waits before it may promote, and the smart shutdown let open sessions keep committing on the isolated primary for up to 180s.The primary lease already measures what matters: a replica may promote once the lease has gone
leaseDurationSecondswithout a renewal. The instance manager now records, on a monotonic clock, when its last successful lease write started, and a goroutine checks that age everyretryPeriodSeconds. Once the age passesrenewDeadlineSecondsit probes the other instances in parallel and, if one is unreachable or names a different target primary, requests an immediate PostgreSQL shutdown, 10 to 13 seconds after the last renewal with the default timings. The trigger is the age, not an error from the election loop, because client-go's acquire path has no overall deadline and may never return while the API server is unreachable.If the primary has decided to step down and PostgreSQL is still running on the last tick before the lease reaches
leaseDurationSeconds, because the lifecycle manager never took the request orpg_ctlfailed, the instance manager sendsSIGQUITto the postmaster and exits with code 5. The monitor lives as long as the lifecycle manager, so it also fences when the manager stops because another runnable failed and the smart shutdown that follows outlasts the lease. A renewal that lands before the lifecycle manager takes the request withdraws the decision, so a primary whose lease is fresh again is not shut down late. Once the request is taken, later renewals no longer move the forced stop, so a restart that waits for PostgreSQL cannot keep the instance manager alive with a fresh lease.Taking the lease over is stricter in three ways. A record that already names this pod, for instance after a restart, is rewritten with a conditional write before the lease counts as held, so a replica that claims it in between makes the write fail and PostgreSQL is not started. Only the pod that the last reconciled Cluster names as target primary takes the lease over, since the runnable keeps polling for as long as the process lives. And the observation window starts only once the pod is the target, so a claim comes at least
leaseDurationSecondsafter the flip, which gives the old primary time to learn about the replacement from its peers./failsafenow returns the responding instance's view of the target primary, throughpkg/management/url, so a primary that still reaches every peer but learns from one that it has been replaced steps down too. A pre-upgrade peer answering plainOKcounts as agreeing. The probe skips our own entry and peers without an IP.The liveness probe now always reports OK. The
.spec.probes.liveness.isolationCheckstanza keeps its fields:requestTimeoutandconnectionTimeoutbound each peer probe, while the probe periods no longer affect fencing and.spec.smartShutdownTimeout: 0is no longer needed for it. The admission webhook warns whenrenewDeadlineSeconds + retryPeriodSeconds + isolationCheck.requestTimeoutis not belowleaseDurationSeconds.The stop beats a replica only if that sum is below the lease duration. The signal goes to the postmaster only; the exit of PID 1 stops the rest. A cluster with
instances: 1, or with the check disabled, or a primary that knows no peer to probe never steps down. One stale peer is enough to stop the primary. No Event is emitted; the step-down is logged underprimary-leaseand shows as a container restart, and the last-resort stop exits with code 5.Closes #11738
Reviewer notes
The e2e test only checks that the isolated primary's container exits within 120s, which the old mechanism would also pass. The fixtures still drive the feature through the
alpha.cnpg.io/livenessPingerannotation. The upgrade note for users who tuned the liveness probe is ininstance_manager.md; a release note is still needed.