From 8edf6d1f34bc87e67dd76e72e24b33635127cb9f Mon Sep 17 00:00:00 2001 From: shihao zhong Date: Sat, 28 Nov 2026 14:09:29 -0500 Subject: [PATCH 4/4] Count block reads, writes and extends per tablespace Relation block IO is counted once, in per tablespace counts the pg_stat_io flush adds up. Catversion bump needed. --- doc/src/sgml/monitoring.sgml | 93 +++++++++++++++++++ src/backend/catalog/system_views.sql | 9 ++ src/backend/storage/smgr/smgr.c | 1 + src/backend/utils/activity/pgstat_io.c | 75 ++++++++++++--- .../utils/activity/pgstat_tablespace.c | 89 +++++++++++++++++- src/backend/utils/adt/pgstatfuncs.c | 44 ++++++++- src/include/catalog/pg_proc.dat | 5 +- src/include/pgstat.h | 7 +- src/include/storage/smgr.h | 6 ++ src/include/utils/pgstat_internal.h | 2 + .../expected/stats-tablespace-drop.out | 33 +++++++ src/test/isolation/isolation_schedule | 1 + .../specs/stats-tablespace-drop.spec | 29 ++++++ src/test/recovery/t/029_stats_restart.pl | 37 ++++++++ .../recovery/t/030_stats_cleanup_replica.pl | 23 +++++ src/test/regress/expected/rules.out | 11 ++- src/test/regress/expected/stats.out | 10 ++ src/test/regress/sql/stats.sql | 5 + 18 files changed, 458 insertions(+), 22 deletions(-) create mode 100644 src/test/isolation/expected/stats-tablespace-drop.out create mode 100644 src/test/isolation/specs/stats-tablespace-drop.spec diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index 7fd0e65a4c9..4f2e53b25f4 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -4504,6 +4504,15 @@ description | Waiting for a newly initialized WAL file to reach durable storage statistics. + + The read, write and extend columns count the block I/O of all processes + on the relations in a tablespace, in the same way as the columns of the + same names in + pg_stat_io + do for the objects relation and + temp relation. + + <structname>pg_stat_tablespace</structname> View @@ -4537,6 +4546,90 @@ description | Waiting for a newly initialized WAL file to reach durable storage + + + reads bigint + + + Number of read operations + + + + + + read_bytes numeric + + + The total size of read operations in bytes + + + + + + read_time double precision + + + Time spent waiting for read operations in milliseconds (if + is enabled, otherwise zero) + + + + + + writes bigint + + + Number of write operations + + + + + + write_bytes numeric + + + The total size of write operations in bytes + + + + + + write_time double precision + + + Time spent waiting for write operations in milliseconds (if + is enabled, otherwise zero) + + + + + + extends bigint + + + Number of relation extend operations + + + + + + extend_bytes numeric + + + The total size of relation extend operations in bytes + + + + + + extend_time double precision + + + Time spent waiting for relation extend operations in milliseconds (if + is enabled, otherwise zero) + + + temp_files bigint diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql index 101dca04a1a..91d466f6970 100644 --- a/src/backend/catalog/system_views.sql +++ b/src/backend/catalog/system_views.sql @@ -1150,6 +1150,15 @@ CREATE VIEW pg_stat_tablespace AS SELECT t.oid AS spcid, t.spcname, + s.reads, + s.read_bytes, + s.read_time, + s.writes, + s.write_bytes, + s.write_time, + s.extends, + s.extend_bytes, + s.extend_time, s.temp_files, s.temp_bytes, s.stats_reset diff --git a/src/backend/storage/smgr/smgr.c b/src/backend/storage/smgr/smgr.c index 0b522a49564..0af4b4a7672 100644 --- a/src/backend/storage/smgr/smgr.c +++ b/src/backend/storage/smgr/smgr.c @@ -273,6 +273,7 @@ smgropen(RelFileLocator rlocator, ProcNumber backend) reln->smgr_targblock = InvalidBlockNumber; for (int i = 0; i <= MAX_FORKNUM; ++i) reln->smgr_cached_nblocks[i] = InvalidBlockNumber; + reln->smgr_pending_io = NULL; reln->smgr_which = 0; /* we only have md.c at present */ /* it is not pinned yet */ diff --git a/src/backend/utils/activity/pgstat_io.c b/src/backend/utils/activity/pgstat_io.c index 699c1187b5a..2021e881737 100644 --- a/src/backend/utils/activity/pgstat_io.c +++ b/src/backend/utils/activity/pgstat_io.c @@ -57,17 +57,21 @@ pgstat_bktype_io_stats_valid(PgStat_BktypeIO *backend_io, return true; } -void -pgstat_count_io_op(IOObject io_object, IOContext io_context, IOOp io_op, - uint32 cnt, uint64 bytes) +/* + * The body of pgstat_count_io_op(), counting in "pending". + */ +static pg_always_inline void +pgstat_count_io_op_internal(PgStat_PendingIO *pending, IOObject io_object, + IOContext io_context, IOOp io_op, + uint32 cnt, uint64 bytes) { Assert((unsigned int) io_object < IOOBJECT_NUM_TYPES); Assert((unsigned int) io_context < IOCONTEXT_NUM_TYPES); Assert(pgstat_is_ioop_tracked_in_bytes(io_op) || bytes == 0); Assert(pgstat_tracks_io_op(MyBackendType, io_object, io_context, io_op)); - PendingIOStats.counts[io_object][io_context][io_op] += cnt; - PendingIOStats.bytes[io_object][io_context][io_op] += bytes; + pending->counts[io_object][io_context][io_op] += cnt; + pending->bytes[io_object][io_context][io_op] += bytes; /* Add the per-backend counts */ pgstat_count_backend_io_op(io_object, io_context, io_op, cnt, bytes); @@ -76,6 +80,14 @@ pgstat_count_io_op(IOObject io_object, IOContext io_context, IOOp io_op, pgstat_report_fixed = true; } +void +pgstat_count_io_op(IOObject io_object, IOContext io_context, IOOp io_op, + uint32 cnt, uint64 bytes) +{ + pgstat_count_io_op_internal(&PendingIOStats, io_object, io_context, io_op, + cnt, bytes); +} + /* * Initialize the internal timing for an IO operation, depending on an * IO timing GUC. @@ -113,10 +125,11 @@ pgstat_prepare_io_time(bool track_io_guc) * * This is the timing part of pgstat_count_io_op_time() and * pgstat_count_smgr_io_op_time(), inlined so that neither pays for a second - * call. + * call. They differ in the pending counts they count in. */ static pg_always_inline void -pgstat_count_io_time_internal(IOObject io_object, IOContext io_context, +pgstat_count_io_time_internal(PgStat_PendingIO *pending, + IOObject io_object, IOContext io_context, IOOp io_op, instr_time start_time) { if (!INSTR_TIME_IS_ZERO(start_time)) @@ -146,7 +159,7 @@ pgstat_count_io_time_internal(IOObject io_object, IOContext io_context, } } - INSTR_TIME_ADD(PendingIOStats.pending_times[io_object][io_context][io_op], + INSTR_TIME_ADD(pending->pending_times[io_object][io_context][io_op], io_time); /* Add the per-backend count */ @@ -159,13 +172,18 @@ void pgstat_count_io_op_time(IOObject io_object, IOContext io_context, IOOp io_op, instr_time start_time, uint32 cnt, uint64 bytes) { - pgstat_count_io_time_internal(io_object, io_context, io_op, start_time); + pgstat_count_io_time_internal(&PendingIOStats, io_object, io_context, + io_op, start_time); pgstat_count_io_op(io_object, io_context, io_op, cnt, bytes); } /* * Like pgstat_count_io_op_time(), for block I/O on a relation. + * + * This counts in the pending counts of the relation's tablespace, in place of + * PendingIOStats. pgstat_io_flush_cb() adds them up, so the I/O is known per + * tablespace without being counted a second time. */ void pgstat_count_smgr_io_op_time(SMgrRelation reln, IOContext io_context, @@ -173,12 +191,33 @@ pgstat_count_smgr_io_op_time(SMgrRelation reln, IOContext io_context, uint32 cnt, uint64 bytes) { IOObject io_object; + PgStat_PendingIO *pending; io_object = SmgrIsTemp(reln) ? IOOBJECT_TEMP_RELATION : IOOBJECT_RELATION; - pgstat_count_io_time_internal(io_object, io_context, io_op, start_time); + /* + * The SMgrRelation remembers the pending counts of its tablespace, so + * that only the first I/O on it has to look for them. Without them, the + * I/O is counted like any other. + */ + pending = reln->smgr_pending_io; + if (unlikely(pending == NULL)) + { + pending = pgstat_tablespace_pending_io(reln->smgr_rlocator.locator.spcOid); + if (unlikely(pending == NULL)) + { + pgstat_count_io_op_time(io_object, io_context, io_op, + start_time, cnt, bytes); + return; + } + reln->smgr_pending_io = pending; + } - pgstat_count_io_op(io_object, io_context, io_op, cnt, bytes); + pgstat_count_io_time_internal(pending, io_object, io_context, io_op, + start_time); + + pgstat_count_io_op_internal(pending, io_object, io_context, io_op, + cnt, bytes); } PgStat_IO * @@ -211,10 +250,19 @@ pgstat_io_flush_cb(bool nowait) { LWLock *bktype_lock; PgStat_BktypeIO *bktype_shstats; + bool partial; if (!have_iostats) return false; + /* + * Block I/O on relations was counted per tablespace, bring it in. Then + * have the entries of the tablespaces updated, as the processes that only + * call pgstat_flush_io() would not do that otherwise. + */ + pgstat_tablespace_collect_io(&PendingIOStats); + partial = pgstat_tablespace_flush_cb(nowait); + bktype_lock = &pgStatLocal.shmem->io.locks[MyBackendType]; bktype_shstats = &pgStatLocal.shmem->io.stats.stats[MyBackendType]; @@ -252,9 +300,10 @@ pgstat_io_flush_cb(bool nowait) memset(&PendingIOStats, 0, sizeof(PendingIOStats)); - have_iostats = false; + /* come back for the tablespace entries that could not be locked */ + have_iostats = partial; - return false; + return partial; } const char * diff --git a/src/backend/utils/activity/pgstat_tablespace.c b/src/backend/utils/activity/pgstat_tablespace.c index 4ab3c90674d..b5b1aab5f38 100644 --- a/src/backend/utils/activity/pgstat_tablespace.c +++ b/src/backend/utils/activity/pgstat_tablespace.c @@ -16,6 +16,10 @@ * Counts are kept in process-local memory until they are flushed. Pending * entries would not do for that, as those create the entry they are for. * + * Block I/O on relations is counted by pgstat_count_smgr_io_op_time(), here + * and in place of the pending pg_stat_io counts. The flush of the latter + * collects it, see pgstat_tablespace_collect_io(). + * * Copyright (c) 2026, PostgreSQL Global Development Group * * IDENTIFICATION @@ -40,6 +44,16 @@ typedef struct PgStat_PendingTablespace Oid spcoid; PgStat_Counter temp_files; PgStat_Counter temp_bytes; + + /* block I/O on relations, until pgstat_tablespace_collect_io() */ + PgStat_PendingIO io; + + /* what that has collected, by operation */ + bool have_io; + PgStat_Counter io_counts[IOOP_NUM_TYPES]; + uint64 io_bytes[IOOP_NUM_TYPES]; + instr_time io_times[IOOP_NUM_TYPES]; + struct PgStat_PendingTablespace *next; } PgStat_PendingTablespace; @@ -170,6 +184,67 @@ pgstat_report_tablespace_tempfile(Oid spcoid, size_t filesize) pgstat_report_fixed = true; } +/* + * Return the pending counts for block I/O on the relations of a tablespace, + * or NULL if there is no memory for them. + * + * pgstat_count_smgr_io_op_time() calls this once the I/O has been started, so + * this must not fail. + */ +PgStat_PendingIO * +pgstat_tablespace_pending_io(Oid spcoid) +{ + PgStat_PendingTablespace *pending = pgstat_tablespace_pending(spcoid); + + return pending ? &pending->io : NULL; +} + +/* + * Move the block I/O counted per tablespace to "pending_io", the pending + * pg_stat_io counts it was kept out of, for pgstat_io_flush_cb(). What the + * entries of the tablespaces are owed stays here, for + * pgstat_tablespace_flush_cb(). + * + * This only touches process-local memory. + */ +void +pgstat_tablespace_collect_io(PgStat_PendingIO *pending_io) +{ + for (PgStat_PendingTablespace *pending = pending_tablespaces; + pending != NULL; pending = pending->next) + { + PgStat_PendingIO *io = &pending->io; + + if (pg_memory_is_all_zeros(io, sizeof(PgStat_PendingIO))) + continue; + + for (int io_object = 0; io_object < IOOBJECT_NUM_TYPES; io_object++) + { + for (int io_context = 0; io_context < IOCONTEXT_NUM_TYPES; io_context++) + { + for (int io_op = 0; io_op < IOOP_NUM_TYPES; io_op++) + { + PgStat_Counter counts = io->counts[io_object][io_context][io_op]; + uint64 bytes = io->bytes[io_object][io_context][io_op]; + instr_time time = io->pending_times[io_object][io_context][io_op]; + + pending_io->counts[io_object][io_context][io_op] += counts; + pending_io->bytes[io_object][io_context][io_op] += bytes; + INSTR_TIME_ADD(pending_io->pending_times[io_object][io_context][io_op], + time); + + pending->io_counts[io_op] += counts; + pending->io_bytes[io_op] += bytes; + INSTR_TIME_ADD(pending->io_times[io_op], time); + } + } + } + + memset(io, 0, sizeof(PgStat_PendingIO)); + pending->have_io = true; + } +} + /* * Flush out locally pending tablespace statistics. * @@ -188,7 +263,7 @@ pgstat_tablespace_flush_cb(bool nowait) PgStat_EntryRef *entry_ref; PgStatShared_Tablespace *shtsent; - if (pending->temp_files == 0) + if (pending->temp_files == 0 && !pending->have_io) continue; entry_ref = pgstat_get_entry_ref(PGSTAT_KIND_TABLESPACE, InvalidOid, @@ -206,12 +281,24 @@ pgstat_tablespace_flush_cb(bool nowait) shtsent->stats.temp_files += pending->temp_files; shtsent->stats.temp_bytes += pending->temp_bytes; + for (int io_op = 0; io_op < IOOP_NUM_TYPES; io_op++) + { + shtsent->stats.counts[io_op] += pending->io_counts[io_op]; + shtsent->stats.bytes[io_op] += pending->io_bytes[io_op]; + shtsent->stats.times[io_op] += + INSTR_TIME_GET_MICROSEC(pending->io_times[io_op]); + } + pgstat_unlock_entry(entry_ref); } /* the counts are discarded if the tablespace has been dropped */ pending->temp_files = 0; pending->temp_bytes = 0; + pending->have_io = false; + memset(pending->io_counts, 0, sizeof(pending->io_counts)); + memset(pending->io_bytes, 0, sizeof(pending->io_bytes)); + memset(pending->io_times, 0, sizeof(pending->io_times)); } return partial; diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c index be960aed02b..e93e19ab7d8 100644 --- a/src/backend/utils/adt/pgstatfuncs.c +++ b/src/backend/utils/adt/pgstatfuncs.c @@ -2525,21 +2525,40 @@ pg_stat_get_subscription_stats(PG_FUNCTION_ARGS) Datum pg_stat_get_tablespace(PG_FUNCTION_ARGS) { -#define PG_STAT_GET_TABLESPACE_COLS 3 +#define PG_STAT_GET_TABLESPACE_COLS 12 Oid spcoid = PG_GETARG_OID(0); TupleDesc tupdesc; Datum values[PG_STAT_GET_TABLESPACE_COLS] = {0}; bool nulls[PG_STAT_GET_TABLESPACE_COLS] = {0}; PgStat_StatTablespaceEntry *tsentry; PgStat_StatTablespaceEntry allzero; + static const IOOp io_ops[] = {IOOP_READ, IOOP_WRITE, IOOP_EXTEND}; int i = 0; tupdesc = CreateTemplateTupleDesc(PG_STAT_GET_TABLESPACE_COLS); - TupleDescInitEntry(tupdesc, (AttrNumber) 1, "temp_files", + TupleDescInitEntry(tupdesc, (AttrNumber) 1, "reads", INT8OID, -1, 0); - TupleDescInitEntry(tupdesc, (AttrNumber) 2, "temp_bytes", + TupleDescInitEntry(tupdesc, (AttrNumber) 2, "read_bytes", + NUMERICOID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 3, "read_time", + FLOAT8OID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 4, "writes", + INT8OID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 5, "write_bytes", + NUMERICOID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 6, "write_time", + FLOAT8OID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 7, "extends", + INT8OID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 8, "extend_bytes", + NUMERICOID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 9, "extend_time", + FLOAT8OID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 10, "temp_files", + INT8OID, -1, 0); + TupleDescInitEntry(tupdesc, (AttrNumber) 11, "temp_bytes", INT8OID, -1, 0); - TupleDescInitEntry(tupdesc, (AttrNumber) 3, "stats_reset", + TupleDescInitEntry(tupdesc, (AttrNumber) 12, "stats_reset", TIMESTAMPTZOID, -1, 0); TupleDescFinalize(tupdesc); BlessTupleDesc(tupdesc); @@ -2552,6 +2571,23 @@ pg_stat_get_tablespace(PG_FUNCTION_ARGS) tsentry = &allzero; } + for (int j = 0; j < lengthof(io_ops); j++) + { + IOOp io_op = io_ops[j]; + char buf[256]; + + values[i++] = Int64GetDatum(tsentry->counts[io_op]); + + /* Convert to numeric */ + snprintf(buf, sizeof buf, UINT64_FORMAT, tsentry->bytes[io_op]); + values[i++] = DirectFunctionCall3(numeric_in, + CStringGetDatum(buf), + ObjectIdGetDatum(0), + Int32GetDatum(-1)); + + values[i++] = Float8GetDatum(pg_stat_us_to_ms(tsentry->times[io_op])); + } + values[i++] = Int64GetDatum(tsentry->temp_files); values[i++] = Int64GetDatum(tsentry->temp_bytes); diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 8f8f8fb87d2..2d5514b4699 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -5749,8 +5749,9 @@ { oid => '8463', descr => 'statistics: information about tablespace stats', proname => 'pg_stat_get_tablespace', provolatile => 's', proparallel => 'r', prorettype => 'record', proargtypes => 'oid', - proallargtypes => '{oid,int8,int8,timestamptz}', proargmodes => '{i,o,o,o}', - proargnames => '{spcid,temp_files,temp_bytes,stats_reset}', + proallargtypes => '{oid,int8,numeric,float8,int8,numeric,float8,int8,numeric,float8,int8,int8,timestamptz}', + proargmodes => '{i,o,o,o,o,o,o,o,o,o,o,o,o}', + proargnames => '{spcid,reads,read_bytes,read_time,writes,write_bytes,write_time,extends,extend_bytes,extend_time,temp_files,temp_bytes,stats_reset}', prosrc => 'pg_stat_get_tablespace' }, { oid => '6118', descr => 'statistics: information about subscription', proname => 'pg_stat_get_subscription', prorows => '10', proisstrict => 'f', diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 81873094cd0..8ac9338929a 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -276,7 +276,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCBE +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCBF typedef struct PgStat_ArchiverStats { @@ -547,6 +547,11 @@ typedef struct PgStat_StatTabEntry typedef struct PgStat_StatTablespaceEntry { + /* block I/O, only IOOP_READ, IOOP_WRITE and IOOP_EXTEND are counted */ + PgStat_Counter counts[IOOP_NUM_TYPES]; + uint64 bytes[IOOP_NUM_TYPES]; + PgStat_Counter times[IOOP_NUM_TYPES]; /* in microseconds */ + PgStat_Counter temp_files; PgStat_Counter temp_bytes; TimestampTz stat_reset_timestamp; diff --git a/src/include/storage/smgr.h b/src/include/storage/smgr.h index 09bd42fcf4b..fa4235a4499 100644 --- a/src/include/storage/smgr.h +++ b/src/include/storage/smgr.h @@ -46,6 +46,12 @@ typedef struct SMgrRelationData BlockNumber smgr_targblock; /* current insertion target block */ BlockNumber smgr_cached_nblocks[MAX_FORKNUM + 1]; /* last known size */ + /* + * Where pgstat_count_smgr_io_op_time() counts block I/O on the relation, + * or NULL if it has not looked for that yet. + */ + struct PgStat_PendingIO *smgr_pending_io; + /* additional public fields may someday exist here */ /* diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h index 7204b84884f..fce426aa44f 100644 --- a/src/include/utils/pgstat_internal.h +++ b/src/include/utils/pgstat_internal.h @@ -903,6 +903,8 @@ extern void pgstat_subscription_reset_timestamp_cb(PgStatShared_Common *header, */ extern void pgstat_create_all_tablespaces(void); +extern PgStat_PendingIO *pgstat_tablespace_pending_io(Oid spcoid); +extern void pgstat_tablespace_collect_io(PgStat_PendingIO *pending_io); extern bool pgstat_tablespace_flush_cb(bool nowait); extern void pgstat_tablespace_reset_timestamp_cb(PgStatShared_Common *header, TimestampTz ts); diff --git a/src/test/isolation/expected/stats-tablespace-drop.out b/src/test/isolation/expected/stats-tablespace-drop.out new file mode 100644 index 00000000000..f62ed6441f0 --- /dev/null +++ b/src/test/isolation/expected/stats-tablespace-drop.out @@ -0,0 +1,33 @@ +Parsed test spec with 2 sessions + +starting permutation: s2_check s1_extend s2_drop_table s2_drop_ts s1_flush s2_check +pg_stat_force_next_flush +------------------------ + +(1 row) + +step s2_check: + SELECT pg_stat_have_stats('tablespace', 0, oid::int8) FROM ts_oid; + +pg_stat_have_stats +------------------ +t +(1 row) + +step s1_extend: INSERT INTO t_drop SELECT generate_series(1, 1000); +step s2_drop_table: DROP TABLE t_drop; +step s2_drop_ts: DROP TABLESPACE regress_tblspace_drop; +step s1_flush: SELECT pg_stat_force_next_flush(); +pg_stat_force_next_flush +------------------------ + +(1 row) + +step s2_check: + SELECT pg_stat_have_stats('tablespace', 0, oid::int8) FROM ts_oid; + +pg_stat_have_stats +------------------ +f +(1 row) + diff --git a/src/test/isolation/isolation_schedule b/src/test/isolation/isolation_schedule index ae8e579b199..c992f3ebe8b 100644 --- a/src/test/isolation/isolation_schedule +++ b/src/test/isolation/isolation_schedule @@ -114,6 +114,7 @@ test: vacuum-conflict test: vacuum-skip-locked test: stats test: stats-backend +test: stats-tablespace-drop test: horizons test: broken-hot-chain test: predicate-hash diff --git a/src/test/isolation/specs/stats-tablespace-drop.spec b/src/test/isolation/specs/stats-tablespace-drop.spec new file mode 100644 index 00000000000..7bdaf40ca22 --- /dev/null +++ b/src/test/isolation/specs/stats-tablespace-drop.spec @@ -0,0 +1,29 @@ +# Test that flushing the block I/O a backend has counted for a tablespace +# does not bring back the statistics entry of the tablespace, if it has been +# dropped in the meantime. + +setup { SET allow_in_place_tablespaces = on; } +setup { CREATE TABLESPACE regress_tblspace_drop LOCATION ''; } +setup +{ + CREATE TABLE t_drop (a int) TABLESPACE regress_tblspace_drop; + CREATE TABLE ts_oid AS + SELECT oid FROM pg_tablespace WHERE spcname = 'regress_tblspace_drop'; +} + +teardown { DROP TABLE ts_oid; } + +session s1 +setup { SELECT pg_stat_force_next_flush(); } +step s1_extend { INSERT INTO t_drop SELECT generate_series(1, 1000); } +step s1_flush { SELECT pg_stat_force_next_flush(); } + +session s2 +step s2_drop_table { DROP TABLE t_drop; } +step s2_drop_ts { DROP TABLESPACE regress_tblspace_drop; } +step s2_check +{ + SELECT pg_stat_have_stats('tablespace', 0, oid::int8) FROM ts_oid; +} + +permutation s2_check s1_extend s2_drop_table s2_drop_ts s1_flush s2_check diff --git a/src/test/recovery/t/029_stats_restart.pl b/src/test/recovery/t/029_stats_restart.pl index 42f23e1edd8..d058ed412ea 100644 --- a/src/test/recovery/t/029_stats_restart.pl +++ b/src/test/recovery/t/029_stats_restart.pl @@ -128,6 +128,43 @@ trigger_tablespace_stat(); $sect = "post immediate, new"; is(tablespace_temp_files_counted(), 't', "$sect: tablespace stats are counted"); + +# All the block I/O since the crash has been counted for some tablespace, +# including what recovery did. The flushes are not atomic, hence the wait. +my $io_cols = + "sum(reads), sum(read_bytes), sum(writes), sum(write_bytes), sum(extends), sum(extend_bytes)"; +ok( $node->poll_query_until( + $connect_db, + "SELECT (SELECT ($io_cols) FROM pg_stat_tablespace) = + (SELECT ($io_cols) FROM pg_stat_io WHERE object IN ('relation', 'temp relation'))" + ), + "$sect: tablespace I/O adds up to pg_stat_io"); + +# Block I/O is counted once. The per-backend statistics count the same I/O +# on their own, so both must agree on what only this session does. There is +# more I/O after a flush, as counts left behind by the flush would then be +# added again. +is( $node->safe_psql( + $connect_db, q[ + CREATE TEMP TABLE test_stats_temp (a int) TABLESPACE test_stats_tblspc; + SELECT extends AS spc_before FROM pg_stat_tablespace + WHERE spcname = 'test_stats_tblspc' \gset + SELECT sum(extends) AS backend_before + FROM pg_stat_get_backend_io(pg_backend_pid()) + WHERE object = 'temp relation' \gset + INSERT INTO test_stats_temp SELECT generate_series(1, 10000); + SELECT pg_stat_force_next_flush() AS flushed \gset + INSERT INTO test_stats_temp SELECT generate_series(1, 10000); + SELECT pg_stat_force_next_flush() AS flushed \gset + SELECT (SELECT extends FROM pg_stat_tablespace + WHERE spcname = 'test_stats_tblspc') - :spc_before > 0, + (SELECT extends FROM pg_stat_tablespace + WHERE spcname = 'test_stats_tblspc') - :spc_before = + (SELECT sum(extends) FROM pg_stat_get_backend_io(pg_backend_pid()) + WHERE object = 'temp relation') - :backend_before;] + ), + 't|t', + "$sect: block I/O is counted once"); is(have_stats('database', $dboid, 0), 't', "$sect: db stats do exist"); is(have_stats('function', $dboid, $funcoid), 't', "$sect: function stats do exist"); diff --git a/src/test/recovery/t/030_stats_cleanup_replica.pl b/src/test/recovery/t/030_stats_cleanup_replica.pl index a4e7b7fda36..aea6ec9d29d 100644 --- a/src/test/recovery/t/030_stats_cleanup_replica.pl +++ b/src/test/recovery/t/030_stats_cleanup_replica.pl @@ -109,6 +109,29 @@ $node_primary->wait_for_replay_catchup($node_standby); is(standby_have_tablespace_stats($spcoid1), 't', "tablespace stats exist after replay of its creation"); +# The restartpoint writes the blocks of the table. That is counted for the +# tablespace, and leaves the checkpointer with a reference to its stats. +$node_primary->safe_psql('postgres', + "CREATE TABLE tab_stats_tblspc TABLESPACE test_stats_tblspc1 AS SELECT generate_series(1,1000) AS a" +); +$node_primary->safe_psql('postgres', "CHECKPOINT"); +$node_primary->wait_for_replay_catchup($node_standby); +$node_standby->safe_psql('postgres', "CHECKPOINT"); +ok( $node_standby->poll_query_until( + 'postgres', + "SELECT writes > 0 FROM pg_stat_tablespace WHERE spcid = $spcoid1"), + "writes of a restartpoint are counted for the tablespace"); + +# The checkpointer still holds that reference when the drop is replayed. It +# has to release it before writing the stats file at shutdown, which is +# checked by the restart below. The checkpoints make sure that there is +# no restartpoint to do at shutdown, as the block I/O of one would make the +# checkpointer notice the drop. +$node_primary->safe_psql('postgres', "DROP TABLE tab_stats_tblspc"); +$node_primary->safe_psql('postgres', "CHECKPOINT"); +$node_primary->wait_for_replay_catchup($node_standby); +$node_standby->safe_psql('postgres', "CHECKPOINT"); + $node_primary->safe_psql('postgres', "DROP TABLESPACE test_stats_tblspc1"); $node_primary->wait_for_replay_catchup($node_standby); is(standby_have_tablespace_stats($spcoid1), diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index d649934669c..3fa7bbaa52c 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -2380,11 +2380,20 @@ pg_stat_sys_tables| SELECT relid, WHERE ((schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (schemaname ~ '^pg_toast'::text)); pg_stat_tablespace| SELECT t.oid AS spcid, t.spcname, + s.reads, + s.read_bytes, + s.read_time, + s.writes, + s.write_bytes, + s.write_time, + s.extends, + s.extend_bytes, + s.extend_time, s.temp_files, s.temp_bytes, s.stats_reset FROM pg_tablespace t, - LATERAL pg_stat_get_tablespace(t.oid) s(temp_files, temp_bytes, stats_reset); + LATERAL pg_stat_get_tablespace(t.oid) s(reads, read_bytes, read_time, writes, write_bytes, write_time, extends, extend_bytes, extend_time, temp_files, temp_bytes, stats_reset); pg_stat_user_functions| SELECT p.oid AS funcid, n.nspname AS schemaname, p.proname AS funcname, diff --git a/src/test/regress/expected/stats.out b/src/test/regress/expected/stats.out index 0de28403139..dbdc4bc2159 100644 --- a/src/test/regress/expected/stats.out +++ b/src/test/regress/expected/stats.out @@ -1724,6 +1724,8 @@ SELECT current_setting('fsync') = 'off' -- from it to cause it to be read back into shared buffers. SELECT sum(reads) AS io_sum_shared_before_reads FROM pg_stat_io WHERE context = 'normal' AND object = 'relation' \gset +SELECT reads AS spc_before_reads + FROM pg_stat_tablespace WHERE spcname = 'regress_tblspace' \gset -- Do this in a transaction to prevent spurious failures due to concurrent accesses to our newly -- rewritten table, e.g. by autovacuum. BEGIN; @@ -1751,6 +1753,14 @@ SELECT :io_sum_shared_after_reads > :io_sum_shared_before_reads; t (1 row) +-- The reads are counted for the tablespace as well. +SELECT reads > :spc_before_reads AND read_bytes > 0 + FROM pg_stat_tablespace WHERE spcname = 'regress_tblspace'; + ?column? +---------- + t +(1 row) + SELECT sum(hits) AS io_sum_shared_before_hits FROM pg_stat_io WHERE context = 'normal' AND object = 'relation' \gset -- Select from the table again to count hits. diff --git a/src/test/regress/sql/stats.sql b/src/test/regress/sql/stats.sql index c7b616ebc77..01c99708381 100644 --- a/src/test/regress/sql/stats.sql +++ b/src/test/regress/sql/stats.sql @@ -789,6 +789,8 @@ SELECT current_setting('fsync') = 'off' -- from it to cause it to be read back into shared buffers. SELECT sum(reads) AS io_sum_shared_before_reads FROM pg_stat_io WHERE context = 'normal' AND object = 'relation' \gset +SELECT reads AS spc_before_reads + FROM pg_stat_tablespace WHERE spcname = 'regress_tblspace' \gset -- Do this in a transaction to prevent spurious failures due to concurrent accesses to our newly -- rewritten table, e.g. by autovacuum. BEGIN; @@ -801,6 +803,9 @@ SELECT pg_stat_force_next_flush(); SELECT sum(reads) AS io_sum_shared_after_reads FROM pg_stat_io WHERE context = 'normal' AND object = 'relation' \gset SELECT :io_sum_shared_after_reads > :io_sum_shared_before_reads; +-- The reads are counted for the tablespace as well. +SELECT reads > :spc_before_reads AND read_bytes > 0 + FROM pg_stat_tablespace WHERE spcname = 'regress_tblspace'; SELECT sum(hits) AS io_sum_shared_before_hits FROM pg_stat_io WHERE context = 'normal' AND object = 'relation' \gset -- 2.37.1 (Apple Git-137.1)