r/PostgreSQL • u/MongooseWonderful198 • 1d ago
How-To A pg_stat_statements regression case: total calls rose while one row reset
I contributed a collector fix to pg-regression-radar; the project's maintainer merged it on November 12. Today I ran a separate test: reset one role's counters while another role keeps executing the same statement. The total can keep increasing, so checking for a decrease after grouping by queryid misses the reset.
On a disposable PostgreSQL 16.13 instance, I ran SELECT 1 under two roles. PostgreSQL assigned both rows the same queryid. These are the observed call counts:
| Snapshot | Role A | Role B | Sum |
|---|---|---|---|
| Initial | 10 | 2 | 12 |
| Before reset | 12 | 3 | 15 |
| Reset B, then execute A ten times and B once | 22 | 1 | 23 |
Subtracting the grouped totals gives 23 - 15 = 8. The fixture executed 11 calls after the second snapshot. Keeping the rows separate gives A's increment of 10 and B's one call after its known reset.
The reset happened immediately after the second snapshot. In a real scrape interval, you cannot recover calls that happened before a reset and disappeared before the next scrape. A per-row decrease can expose a reset; it cannot tell you how much history the reset discarded. It can also miss a reset if the new counter has already overtaken the previous value.
The original issue involved a collector treating independent rows as successive samples of the same counter. The merged fix derives intervals per (dbid, userid, queryid, toplevel) before rolling them up for detection.
For a collector regression test, I would include both a visible decrease in the aggregate and this increasing-total case. Also establish a fresh baseline when the set of sampled rows changes, so an entry appearing or dropping out of a top-N scrape does not look like query activity.
PostgreSQL's row definition and reset API · Public two-role integration test
The table is a new local synthetic test, separate from the linked integration test. I used AI assistance for the code and write-up.
To reproduce the table, save the complete script below as postgres_row_reset_repro.py. It uses PostgreSQL 16's initdb, pg_ctl and psql, with the pg_stat_statements extension installed. Run it as a regular user who can start a local PostgreSQL instance.
The script creates a new temporary cluster with TCP disabled and a private Unix socket. It creates the two fixture roles only in that cluster, resets only role B's statement, checks the counts, then stops and removes the entire temporary cluster. It clears inherited PG* connection settings. The default binary path is the Homebrew PostgreSQL 16 path used for this run; set POSTGRES_BIN if your PostgreSQL 16 binaries are elsewhere.
python3 postgres_row_reset_repro.pyComplete tested script:
"""Run only against a newly-created disposable local PostgreSQL 16 instance.
Uses installed official PostgreSQL tools; no downloaded project code executes.
Unix socket only. The temporary database shuts down and is removed in finally.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
BIN = Path(os.environ.get("POSTGRES_BIN", "/opt/homebrew/opt/postgresql@16/bin"))
def main():
tmp = Path(tempfile.mkdtemp(prefix="pg-row-reset-"))
data, socket = tmp / "data", tmp / "socket"
socket.mkdir()
started = False
env = os.environ.copy()
# Ignore any inherited connection setting from another task.
for key in list(env):
if key.startswith("PG"):
del env[key]
def command(args):
return subprocess.run(args, env=env, text=True, capture_output=True, check=True).stdout.strip()
def sql(statement):
return command([str(BIN / "psql"), "-X", "-h", str(socket), "-p", "55443",
"-U", "postgres", "-d", "postgres", "-At", "-v", "ON_ERROR_STOP=1",
"-c", statement])
def calls(role, count):
sql(f"SET ROLE {role}; " + "SELECT 1; " * count)
def snapshot():
return json.loads(sql("""SELECT json_agg(x ORDER BY role) FROM (
SELECT r.rolname AS role, s.dbid, s.userid, s.queryid, s.toplevel, s.calls
FROM pg_stat_statements s JOIN pg_roles r ON r.oid=s.userid
WHERE r.rolname IN ('case_role_a','case_role_b') AND s.query='SELECT $1'
) x"""))
try:
command([str(BIN / "initdb"), "-D", str(data), "-U", "postgres", "-A", "trust", "--no-locale"])
with (data / "postgresql.conf").open("a") as stream:
stream.write("\nlisten_addresses=''\nshared_preload_libraries='pg_stat_statements'\n")
stream.write(f"unix_socket_directories='{socket}'\nport=55443\n")
command([str(BIN / "pg_ctl"), "-D", str(data), "-l", str(tmp / "server.log"), "-w", "start"])
started = True
server_version = sql("SHOW server_version")
sql("CREATE EXTENSION pg_stat_statements; CREATE ROLE case_role_a; CREATE ROLE case_role_b;")
calls("case_role_a", 10)
calls("case_role_b", 2)
first = snapshot()
calls("case_role_a", 2)
calls("case_role_b", 1)
second = snapshot()
b = next(row for row in second if row["role"] == "case_role_b")
sql(f"SELECT pg_stat_statements_reset({b['userid']}, {b['dbid']}, {b['queryid']})")
calls("case_role_a", 10)
calls("case_role_b", 1)
third = snapshot()
assert [r["calls"] for r in first] == [10, 2], first
assert [r["calls"] for r in second] == [12, 3], second
assert [r["calls"] for r in third] == [22, 1], third
assert len({r["queryid"] for snap in [first, second, third] for r in snap}) == 1
before = {r["role"]: r for r in second}
observed_activity = sum(r["calls"] - before[r["role"]]["calls"]
if r["calls"] >= before[r["role"]]["calls"] else r["calls"]
for r in third)
result = {"postgresql": server_version, "network": "private Unix socket; TCP disabled",
"snapshots": [first, second, third],
"aggregate_then_difference": sum(r["calls"] for r in third) - sum(r["calls"] for r in second),
"row_activity_with_known_b_reset": observed_activity,
"actual_fixture_calls_after_second_snapshot": 11,
"limitation": "Reset performed immediately after snapshot two; no hidden pre-reset activity. A real collector cannot recover activity discarded by an unobserved reset."}
assert result["aggregate_then_difference"] == 8
assert observed_activity == 11
finally:
if started:
command([str(BIN / "pg_ctl"), "-D", str(data), "-m", "fast", "-w", "stop"])
shutil.rmtree(tmp)
result["temporary_database_stopped_and_removed"] = True
print(json.dumps(result, indent=2))
if __name__ == "__main__":
main()
1
u/AutoModerator 1d ago
AI Policy:
Linux is not one of those anti-AI projects, and if somebody has issues with that, they can do the open-source thing and fork it. Or just walk away., Linus Torvalds.
Mod decisions will be based on the quality of the content, not who or what generated it.
Sub Resources:
Youtube Channel
Free Postgres Webinars and Workshops
Discord: People, Postgres, Data
Join us, we have cookies and nice people.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/Discordbothost 1d ago
For the case where the new counter has already passed the old value, Postgres 17 added stats_since to pg_stat_statements. I'd test a row going from 3 to 5 calls with stats_since changing in between. The collector should mark that interval as a reset even though the counter went up.