Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
## main / (unreleased)

* [BUGFIX] stat_replication: fix "slot_name does not exist" by joining `pg_replication_slots` (closes #1310)

## 0.20.0 / 2026-06-29

BREAKING CHANGES:
Expand Down Expand Up @@ -44,7 +46,6 @@ its `--no-collector.*` flag.
* [BUGFIX] Fix duplicate `pg_stat_progress_vacuum` metrics for cross-database vacuums by @steinbrueckri in https://github.com/prometheus-community/postgres_exporter/pull/1262
* [BUGFIX] Fix `pg_settings` collection when `short_desc` is NULL by @jun-gradial in https://github.com/prometheus-community/postgres_exporter/pull/1327


## 0.19.1 / 2026-02-25

* [CHANGE] Filter and warn about duplicates in pg_stat_statements (#998) by @Nudin in https://github.com/prometheus-community/postgres_exporter/pull/1259
Expand Down
54 changes: 51 additions & 3 deletions collector/pg_stat_replication.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,23 +55,41 @@ var (
prometheus.Labels{},
)

// slot_name is not a column of pg_stat_replication; it lives on
// pg_replication_slots and is linked via the standby's WAL sender
// PID. LEFT JOIN so clients that do not use a named slot still get
// a row with an empty slot_name label.
statReplicationQuery = `
SELECT
application_name,
client_addr::text,
state,
slot_name,
s.slot_name,
(case pg_is_in_recovery() when 't' then pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_lsn('0/0'))::float else pg_wal_lsn_diff(pg_current_wal_lsn(), pg_lsn('0/0'))::float end) AS pg_current_wal_lsn_bytes,
(case pg_is_in_recovery() when 't' then pg_wal_lsn_diff(pg_last_wal_receive_lsn(), replay_lsn)::float else pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)::float end) AS pg_wal_lsn_diff
FROM pg_stat_replication
LEFT JOIN pg_replication_slots s ON s.active_pid = pg_stat_replication.pid
`

statReplicationQueryBefore10 = `
SELECT
application_name,
client_addr::text,
state,
slot_name,
s.slot_name,
(case pg_is_in_recovery() when 't' then pg_xlog_location_diff(pg_last_xlog_receive_location(), replay_location)::float else pg_xlog_location_diff(pg_current_xlog_location(), replay_location)::float end) AS pg_xlog_location_diff
FROM pg_stat_replication
LEFT JOIN pg_replication_slots s ON s.active_pid = pg_stat_replication.pid

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.

Seems like this query only works for postgres 9.5 and above, because active_pid was only added in PG 9.5.x. See https://www.postgresql.org/docs/9.5/view-pg-replication-slots.html and https://www.postgresql.org/docs/9.4/catalog-pg-replication-slots.html

Could you please have a query for 9.4 and below that doesn't include slot_name?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Hi @ArthurSens !

Rebased on master and added a fallback for 9.2–9.4: those versions use a query without the join, slot_name label is just empty there (same as the old yaml behavior).

Verified against real postgres in docker. On 9.4 the join query indeed fails:

ERROR:  column s.active_pid does not exist

the fallback query runs fine and the collector succeeds:

pg_scrape_collector_success{collector="stat_replication"} 1

On 17 with a standby streaming through a named slot (pg_basebackup -R -S test_slot) the exporter emits:

pg_stat_replication_pg_current_wal_lsn_bytes{application_name="walreceiver",client_addr="172.19.0.3/32",slot_name="test_slot",state="streaming"} 1.1758988e+08
pg_stat_replication_pg_wal_lsn_diff{application_name="walreceiver",client_addr="172.19.0.3/32",slot_name="test_slot",state="streaming"} 0

9.6 with the join query works too. Unit tests pass, incl. a new one for the pre-9.5 path.

`

// pg_replication_slots.active_pid only exists on PostgreSQL 9.5+, so
// on older versions slot_name cannot be resolved; the label is left
// empty (matching the legacy yaml exporter behavior).
statReplicationQueryBefore95 = `
SELECT
application_name,
client_addr::text,
state,
(case pg_is_in_recovery() when 't' then pg_xlog_location_diff(pg_last_xlog_receive_location(), replay_location)::float else pg_xlog_location_diff(pg_current_xlog_location(), replay_location)::float end) AS pg_xlog_location_diff
FROM pg_stat_replication
`
Expand All @@ -81,8 +99,10 @@ func (PGStatReplicationCollector) Update(ctx context.Context, instance *instance
switch {
case instance.version.GTE(semver.MustParse("10.0.0")):
return updateStatReplication(ctx, instance, ch)
case instance.version.GTE(semver.MustParse("9.2.0")):
case instance.version.GTE(semver.MustParse("9.5.0")):
return updateStatReplicationBefore10(ctx, instance, ch)
case instance.version.GTE(semver.MustParse("9.2.0")):
return updateStatReplicationBefore95(ctx, instance, ch)
default:
return nil
}
Expand Down Expand Up @@ -153,6 +173,34 @@ func updateStatReplicationBefore10(ctx context.Context, instance *instance, ch c
return rows.Err()
}

func updateStatReplicationBefore95(ctx context.Context, instance *instance, ch chan<- prometheus.Metric) error {
db := instance.getDB()
rows, err := db.QueryContext(ctx, statReplicationQueryBefore95)
if err != nil {
return err
}
defer rows.Close()

for rows.Next() {
var applicationName, clientAddr, state sql.NullString
var xlogLocationDiff sql.NullFloat64
if err := rows.Scan(&applicationName, &clientAddr, &state, &xlogLocationDiff); err != nil {
return err
}

if xlogLocationDiff.Valid {
ch <- prometheus.MustNewConstMetric(
statReplicationXlogLocationDiffDesc,
prometheus.GaugeValue,
xlogLocationDiff.Float64,
statReplicationLabelValues(applicationName, clientAddr, state, sql.NullString{})...,
)
}
}

return rows.Err()
}

func statReplicationLabelValues(applicationName, clientAddr, state, slotName sql.NullString) []string {
return []string{
nullStringValue(applicationName),
Expand Down
49 changes: 49 additions & 0 deletions collector/pg_stat_replication_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,55 @@ func TestPGStatReplicationCollectorBefore10(t *testing.T) {
}
}

func TestPGStatReplicationCollectorBefore95(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatalf("Error opening a stub db connection: %s", err)
}
defer db.Close()

inst := &instance{db: db, version: semver.MustParse("9.4.0")}

rows := sqlmock.NewRows([]string{
"application_name",
"client_addr",
"state",
"pg_xlog_location_diff",
}).AddRow("standby", "10.0.0.1", "streaming", 32.0)
mock.ExpectQuery(sanitizeQuery(statReplicationQueryBefore95)).WillReturnRows(rows)

ch := make(chan prometheus.Metric)
go func() {
defer close(ch)
c := PGStatReplicationCollector{}
if err := c.Update(context.Background(), inst, ch); err != nil {
t.Errorf("Error calling PGStatReplicationCollector.Update: %s", err)
}
}()

expected := []MetricResult{
{
labels: labelMap{
"application_name": "standby",
"client_addr": "10.0.0.1",
"state": "streaming",
"slot_name": "",
},
value: 32,
metricType: dto.MetricType_GAUGE,
},
}
convey.Convey("Metrics comparison", t, func() {
for _, expect := range expected {
m := readMetric(<-ch)
convey.So(expect, convey.ShouldResemble, m)
}
})
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled exceptions: %s", err)
}
}

func TestPGStatReplicationCollectorNullValues(t *testing.T) {
db, mock, err := sqlmock.New()
if err != nil {
Expand Down
Loading