Skip to content

fix: stop publishing zeros for silent instances in InstancesReportedState - #11260

Closed
armru wants to merge 10 commits into
mainfrom
fix/instances-reported-state
Closed

armru wants to merge 10 commits into
mainfrom
fix/instances-reported-state

Conversation

@armru

@armru armru commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

The operator publishes a per-instance summary into
.status.instancesReportedState, built once per reconciliation from the
status list it collects by probing every instance's /pg/status endpoint.
That map was rebuilt from scratch on every pass and given an entry for
every item in the list, unconditionally. When a probe fails the resulting
PostgresqlStatus carries an error and leaves every other field at its Go
zero value, so an instance the operator simply could not reach had
IsPrimary: false, TimeLineID: 0 and an empty IP written into the CRD
as though those had been observed. A single dropped or slow probe was
enough, since probe timeouts are not retried.

The values are not merely cosmetic. ensureInstancesAreReachable, part of
the primary's isolation check, walks that map and pings each recorded IP,
returning on the first failure with no quorum or threshold. An empty
address can never be pinged, so one unreachable instance was enough to make
the whole check fail, and when the primary could not reach the API server
either that verdict fails its own liveness probe and has kubelet restart it.

The map is now preserved across reconciliations instead of rebuilt, and
only an instance that actually reported its status writes or overwrites an
entry. Two consequences worth knowing when reading the CRD: an instance
that has gone silent keeps its last known entry rather than being
overwritten with zeros, so the field can now hold stale-but-true data in
place of fresh-but-fabricated data; and an instance whose first ever
observation is a failed probe gets no entry at all rather than a zeroed
one.

Preserving the map instead of rebuilding it also broke how the field reaches
the API server, which is worth spelling out because the effect was silence
rather than a wrong value. The function compares the status it has built
against a baseline copy taken on entry, and issues an update only when the two
differ. That baseline was a shallow copy, so it shared the very map being
mutated in place: the comparison could never see a difference, the write was
skipped, and the field froze at whatever the first reconciliation had
persisted, never gaining the other instances. The baseline is now a deep copy.
That also makes condition-only changes detectable, since
meta.SetStatusCondition rewrites an existing condition through the shared
slice backing array and was equally invisible before.

The isolation check was the visible victim of that freeze: with a map holding
only the primary's own entry, an isolated primary pinged nothing but itself,
succeeded, and never fenced. The tests did not catch it either, because they
asserted on the in-memory Cluster, which is updated correctly throughout; they
now read the object back after the call.

Entries are still pruned, but only once an instance stops appearing in the
status list altogether. That happens when the instance is scaled down, and
also while its pod is being replaced, because only the pods accepted by
utils.IsPodActive are probed and a pending or terminating pod never
enters the list. Pruning in that window is the behaviour we want: the entry
goes away before the replacement pod exists, so a preserved entry can never
hand the isolation check an address that has meanwhile moved to a different
pod. An instance that is merely not answering right now does keep appearing,
because the pod is attached to its status entry regardless of the probe
outcome.

To make the distinction hard to get wrong at other call sites, this adds
InstanceSet, which partitions a status list into the instances that
reported and the ones that did not, the latter split further by whether
kubelet still considers the pod Ready. A silent instance exposes only the
fields that are populated regardless of the probe, so reading an
unobserved field off one is no longer expressible.

Demoting a primary that stopped reporting

Once the map holds what was actually observed, it can answer a question the
operator was getting wrong. When a cluster is switched to replica cluster
mode, replicaclusterswitch looks for a primary among the instances that
reported their status and, when it finds one, fences the cluster to demote
it. An instance whose probe failed reports no role at all, IsPrimary
included, so a single failing probe made containsPrimaryInstance return
false and the reconciler take its "no primary instance present means that we
have no work to do" branch, skipping the transition while that primary kept
accepting writes.

Nothing else in that pass fences it either.
AllReadyInstancesStatusUnreachable only trips when every ready instance is
silent, and the IsComplete gate that does stop the reconcile sits further
down, past the point where the demotion would have started. The pass is
requeued about ten seconds later by evaluatePodReadinessGuards, so the
demotion does eventually happen, but only once the probe answers again: for
as long as the operator could not reach an instance that clients could, the
cluster was a replica cluster on paper with a writable primary behind it.

The decision now falls back on the last state observed for the instance
recorded as the current primary. Fencing is a metadata write that goes
through the API server, so stopping that primary never required reaching it
in the first place, and the transition completes on the instance manager's
own watch of the Cluster object rather than on an operator probe.

The fallback is deliberately narrow, so that it fires only where a primary
really is at stake:

  • it asks for an instance that was actually observed as a primary, which a
    designated primary never is since it runs with a standby.signal file, so
    a replica cluster created from scratch is left alone when its designated
    primary goes quiet;
  • it requires the instance to still be among the probed ones, because one
    that has left the status list has no PostgreSQL left to stop;
  • it steps aside once a demotion token exists, so a probe failing right
    after a completed transition cannot start a second one and fence a healthy
    replica cluster.

The package had no coverage of Reconcile at all, so the tests come with
it: the silent-primary case, the reporting-primary case that must keep
working, and one case per carve-out above.

Not reporting is not the same as down

The same fabrication reached other decisions, which read observed fields off an
instance whose probe had failed and got a Go zero value back as though it were
an observation.

AreWalReceiversDown, the failover gate, only looked at
IsWalReceiverActive, so an operator-to-standby hiccup was
indistinguishable from a genuinely stopped WAL receiver and the gate let a
failover through while that standby could still be streaming from the old
primary. It now weighs the per-pod status error together with kubelet's
readiness verdict: a standby that is Ready but silent counts as unknown and
keeps the gate blocked, with a WalReceiverStatusUnknown warning event so the
deferral is visible through kubectl describe, while one kubelet no longer
considers Ready is still treated as down so a node failure keeps failing over.
The gate moves onto InstanceSet, which is what gives that type its second
consumer.

Three more readers follow the same reasoning: setPrimaryOnSchedulableNode
scanned IsWalReceiverActive on candidates it had not heard from (a silent one
read false and so happened to be skipped, but nothing guaranteed it),
getBackupTargetPod returned a pod without checking its error and let the
caller read an empty SessionID, and kubectl cnpg status matched the primary
on Pod.Name and printed zeros and blanks for WAL archiving, replication and
basebackups instead of saying the primary's state is unknown.

The failover documentation gains the distinction too, since a failover
deferred because a standby is unreachable otherwise reads as a stall.

There is no issue tracking this specific bug. It surfaced as prerequisite
work while looking into the wider problem of the operator conflating "this
instance is not reporting" with "this instance is down", which is what the
sections above address.

@armru
armru requested a review from a team July 28, 2026 13:10
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. bug 🐛 Something isn't working release-1.28 release-1.29 release-1.30 labels Jul 28, 2026
@cnpg-bot cnpg-bot added the backport-requested ◀️ This pull request should be backported to all supported releases label Jul 28, 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

@armru

armru commented Jul 28, 2026

Copy link
Copy Markdown
Member Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@armru

armru commented Jul 28, 2026

Copy link
Copy Markdown
Member Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@litaocdl
litaocdl force-pushed the fix/instances-reported-state branch from d012805 to c0d3967 Compare July 29, 2026 06:48
@armru
armru requested a review from jsilvela as a code owner July 29, 2026 08:31
@armru
armru force-pushed the fix/instances-reported-state branch from b8c4891 to fb68215 Compare July 29, 2026 10:52
@armru

armru commented Jul 29, 2026

Copy link
Copy Markdown
Member Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

@cnpg-bot cnpg-bot added the ok to merge 👌 This PR can be merged label Jul 29, 2026
@armru

armru commented Jul 29, 2026

Copy link
Copy Markdown
Member Author

/test

@github-actions

Copy link
Copy Markdown
Contributor

armru added 6 commits July 31, 2026 09:43
…tate

Nothing stopped decision code from reading an observed field (e.g.
IsWalReceiverActive, IsPrimary, TimeLineID) off an instance whose
/pg/status probe failed and getting back a Go zero value instead of a
real observation. Add InstanceSet, which splits a PostgresqlStatusList
into the instances that actually reported their status and the ones
that didn't, the latter further split by whether kubelet still
considers the pod Ready. Only Pod and Node, which are always populated
regardless of the probe outcome, are exposed for a silent instance.

updateClusterStatusThatRequiresInstancesState is the first consumer:
it rebuilt InstancesReportedState from scratch every reconciliation
and wrote an entry for every item in the status list unconditionally,
so an instance whose status probe failed had its IsPrimary, TimeLineID
and IP published as zero values into the CRD as though they had been
observed.

Keep the map across reconciliations instead of rebuilding it, and only
write or overwrite an entry for an instance that is actually reporting;
a silent instance keeps whatever entry it already had, and gets no
entry at all if this is its first-ever observation. An instance is
only removed from the map once it stops appearing in the status list
altogether (scaled down, or replaced under the same name), which is
also what keeps ensureInstancesAreReachable in the isolation check from
pinging a pod that is actually gone rather than merely unreachable
this pass.

Signed-off-by: Armando Ruocco <[email protected]>
The comment claimed that a pod goes missing from the probed status list
only when it has been scaled down or replaced, and that every instance
still belonging to the cluster shows up in that list on every pass. The
first half is incomplete and the second one is wrong: GetStatusFromInstances
probes only the pods accepted by utils.IsPodActive, so a pod that is
pending or terminating never enters the list at all, and its entry is
pruned while it is being recreated.

That pruning is the behaviour we want, because the entry goes away before
the replacement pod exists and so cannot survive to hand the isolation
check an address that has meanwhile moved to a different pod. Say that,
instead of resting the explanation on a guarantee the code does not give.

Signed-off-by: Armando Ruocco <[email protected]>
The existing cases all pair a failed probe with a zero-valued status, so
they cannot tell a decision taken on the error apart from one taken on the
values happening to look empty. Feed a failed probe carrying a full status
that disagrees with the last known observation on every field, and assert
that both the reported state and the timeline on the status root keep the
values last actually observed.

Signed-off-by: Armando Ruocco <[email protected]>
When a cluster is switched to replica cluster mode, the operator looks for
a primary among the instances that reported their status and fences the
cluster to demote it. An instance whose status probe failed reports no
role at all, so a single failing probe made the operator conclude that
there was no primary to demote and skip the transition entirely, while
that primary kept accepting writes. The pass ends up requeued a few
seconds later, so the demotion did eventually happen, but only once the
probe answered again: for as long as the operator could not reach an
instance that clients could, the cluster was a replica cluster on paper
with a writable primary behind it.

The decision now falls back on the last state observed for the instance
recorded as the current primary, kept in .status.instancesReportedState.
Fencing is a metadata write that goes through the API server, so stopping
that primary never required reaching it in the first place.

The fallback is deliberately narrow. It asks for an instance that was
actually observed as a primary, which a designated primary never is since
it runs with a standby.signal file, so a replica cluster created from
scratch is left alone when its designated primary goes quiet. It also
requires the instance to still be among the probed ones, because one that
has left the status list has no PostgreSQL left to stop, and it steps
aside once a demotion token exists, so a probe failing right after a
completed transition cannot start a second one.

Signed-off-by: Armando Ruocco <[email protected]>
The operator collects its instance status list by probing every instance's
/pg/status endpoint, and an instance whose probe failed carries an error with
every other field left at its Go zero value. Several decisions read those
fields anyway, so "we could not reach this instance" reached them as a real
observation saying no, false or empty.

AreWalReceiversDown, the failover gate, only looked at IsWalReceiverActive: a
connectivity hiccup between the operator and a standby was indistinguishable
from a genuinely stopped WAL receiver, and the gate let a failover through
while that standby could still be streaming from the old primary. The gate now
weighs the per-pod status error together with kubelet's readiness verdict. A
standby that is Ready but not reporting counts as unknown and keeps the gate
blocked, with a WalReceiverStatusUnknown warning event so the deferral is
visible through kubectl describe, while one that kubelet no longer considers
Ready is still treated as down, so a node failure keeps failing over. The gate
also moves onto InstanceSet, which makes reading an unguarded field off a
silent standby inexpressible rather than merely avoided, and its two callers in
replicas.go follow.

The same reasoning covers three more readers. setPrimaryOnSchedulableNode
scanned IsWalReceiverActive on every candidate: a silent one reads false and so
happened to be skipped, but nothing in the code guaranteed it, and the scan is
now restricted to the instances that reported. getBackupTargetPod returned the
first item of a single-pod lookup without checking the error, letting its
caller read an empty SessionID as though it were real; it now selects among the
reporting instances and returns ErrInstanceStatusUnavailable, which that caller
already retries on. kubectl cnpg status matched the primary on Pod.Name, which
is populated regardless of the probe, and then printed zeros and blanks for WAL
archiving, replication and basebackups; it now tells a silent primary apart
from a missing one and reports it as unknown.

The failover documentation gains the same distinction, since a failover
deferred because a standby is unreachable is otherwise read as a stall.

Signed-off-by: Armando Ruocco <[email protected]>
The pod elected to run a volume snapshot backup only needs to be
identified, since these backups are managed by the operator rather
than the instance manager. getSnapshotTargetPod was going through
getBackupTargetPod, which also probes the elected pod's /pg/status
and requires it to answer, a check whose only purpose is obtaining
the instance manager session ID for instance-managed backups.

A one-off probe failure on the elected pod therefore terminally
failed an otherwise healthy volume snapshot backup, with no retry.

Split the pod election out of getBackupTargetPod into
electBackupTargetPod, which getSnapshotTargetPod now calls directly,
skipping the probe entirely. getBackupTargetPod keeps the probe for
the instance-manager backup path, which still needs the session ID.

Signed-off-by: Armando Ruocco <[email protected]>
armru added 4 commits July 31, 2026 09:43
.spec.livenessProbeTimeout does not bound this wait: a standby's
liveness probe returns OK unconditionally before reaching any check
that could fail on it, so kubelet never flips a standby's readiness
because of it. Readiness comes from the local pg_isready probe
instead, which is independent of the operator's own /pg/status call
to the pod.

A standby that kubelet still reports Ready, but whose /pg/status
call keeps failing for the operator (a NetworkPolicy or CNI
asymmetry, a TLS problem, a hanging or erroring query), stays in the
deferred, WAL-receiver-unknown state for as long as that lasts, with
no timeout. The operator provably cannot tell whether that standby's
WAL receiver is still running, so blocking without a bound is the
correct, conservative behaviour; only the documentation and code
comments describing it were wrong about what limits it.

Signed-off-by: Armando Ruocco <[email protected]>
…stance clusters

AreWalReceiversDown skips the primary in both the Reporting and
ReadyButSilent passes, but nothing exercised that: a silent primary
could regress into being counted as an unknown standby and block its
own failover forever. Add a case for it, along with a mixed set
where an actively-streaming standby must short-circuit the gate
before a silent one is even considered, and a primary-only cluster,
which must never block.

The silent-standby fixtures go through AddPod with a real Ready pod
condition instead of hardcoding IsPodReady, so the readiness
derivation the production code relies on is what is under test.

Signed-off-by: Armando Ruocco <[email protected]>
…vent

The event pointed at the operator logs for the underlying error, but
the log line it referred to is at Info level and reads nothing like
the event message, and no other Recorder.Event call in this package
references an internal endpoint path or tells the reader to consult
the logs. Keep only the pod names, which is the part a user can act
on.

Also convert two range loops over instance slices to the index and
pointer form used elsewhere in these files.

Signed-off-by: Armando Ruocco <[email protected]>
updateClusterStatusThatRequiresInstancesState took a shallow copy of
cluster.Status as its before-change baseline, but InstancesReportedState
is a map that the function goes on to mutate in place. The shallow copy
shared the same map header as the live status, so by the time the
reflect.DeepEqual comparison ran, the baseline and the current value
were the same map: any change to it was invisible, the update to the API
server was skipped, and the field never left the in-memory object. On a
running cluster this froze instancesReportedState at whatever was
written on the first reconcile and kept it from ever gaining the other
instances.

The fix takes a deep copy of the status instead, so the baseline keeps
its own map and the comparison can see the mutation. As a side effect,
this also makes condition-only changes detectable: SetStatusCondition
mutates an existing condition through the shared slice backing array,
which a shallow baseline could not see either.

The existing specs only asserted on the in-memory cluster object, which
is updated correctly regardless of this bug, so they never caught the
missing write. They now read the object back from the fake client after
the call, and a new spec pins the regression directly: an instance added
on a second pass must show up in the persisted map, not just the
in-memory one.

Signed-off-by: Armando Ruocco <[email protected]>
@litaocdl
litaocdl force-pushed the fix/instances-reported-state branch from fb68215 to 893cb30 Compare July 31, 2026 01:43
@armru armru closed this Aug 18, 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

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 no-issue ok to merge 👌 This PR can be merged release-1.28 release-1.30 size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants