v4-0001-pg_stat_statements-Add-last_execution_start-colum.patch
application/octet-stream
Filename: v4-0001-pg_stat_statements-Add-last_execution_start-colum.patch
Type: application/octet-stream
Part: 0
From 915d854216931f2f1e0888a8e41ec6d7da7e1cef Mon Sep 17 00:00:00 2001
From: Pavlo Golub <pavlo.golub@cybertec.at>
Date: Wed, 1 Apr 2026 12:31:57 +0000
Subject: [PATCH] pg_stat_statements: Add last_execution_start column
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Add a new column last_execution_start to pg_stat_statements that records
the start timestamp of the most recent execution of each tracked statement.
The timestamp is captured at ExecutorStart time and stored in a new field
added to EState. This follows the same pattern as es_total_processed,
es_parallel_workers_to_launch, and other fields that are set by the
executor and consumed by pg_stat_statements.
This avoids the deferred-ExecutorEnd problem with extended query protocol
when ExecutorEnd for previous query is deferred until the next Bind message,
and GetCurrentStatementStartTimestamp() would return the next query timestamp.
For non-executor paths (planner hook, ProcessUtility), the timestamp is
still read inline from GetCurrentStatementStartTimestamp() because those
paths are never deferred.
Benchmark (16-vCPU, interleaved pgbench -c8 -j4 -T60):
master HEAD: ~4691 TPS (runs: 4849, 4588, 4635)
patched v3: ~4744 TPS (runs: 4870, 4735, 4627)
difference: ~1.1% — within noise
The column is initialized at entry allocation time and updated on every
stats-recording call to pgss_store(). It is reset by
pg_stat_statements_reset() but not by minmax-only resets.
Bump PGSS_FILE_HEADER to 0x20260330 for the changed on-disk format.
---
contrib/pg_stat_statements/Makefile | 1 +
.../expected/entry_timestamp.out | 123 ++++++++++++++++++
contrib/pg_stat_statements/meson.build | 1 +
.../pg_stat_statements--1.13--1.14.sql | 79 +++++++++++
.../pg_stat_statements/pg_stat_statements.c | 64 +++++++--
.../pg_stat_statements.control | 2 +-
.../sql/entry_timestamp.sql | 74 +++++++++++
doc/src/sgml/pgstatstatements.sgml | 12 ++
src/include/nodes/execnodes.h | 9 ++
9 files changed, 354 insertions(+), 11 deletions(-)
create mode 100644 contrib/pg_stat_statements/pg_stat_statements--1.13--1.14.sql
diff --git a/contrib/pg_stat_statements/Makefile b/contrib/pg_stat_statements/Makefile
index c27e9529bb6..d7142f71cf7 100644
--- a/contrib/pg_stat_statements/Makefile
+++ b/contrib/pg_stat_statements/Makefile
@@ -7,6 +7,7 @@ OBJS = \
EXTENSION = pg_stat_statements
DATA = pg_stat_statements--1.4.sql \
+ pg_stat_statements--1.13--1.14.sql \
pg_stat_statements--1.12--1.13.sql \
pg_stat_statements--1.11--1.12.sql pg_stat_statements--1.10--1.11.sql \
pg_stat_statements--1.9--1.10.sql pg_stat_statements--1.8--1.9.sql \
diff --git a/contrib/pg_stat_statements/expected/entry_timestamp.out b/contrib/pg_stat_statements/expected/entry_timestamp.out
index a10c4be6bac..b15153d4b2f 100644
--- a/contrib/pg_stat_statements/expected/entry_timestamp.out
+++ b/contrib/pg_stat_statements/expected/entry_timestamp.out
@@ -150,6 +150,129 @@ WHERE query LIKE '%STMTTS%';
2 | 1 | 2 | 0
(1 row)
+--
+-- last_execution_start timestamp tests
+--
+-- Reset stats first to avoid queryId collisions: simple "SELECT const AS alias"
+-- queries all share the same normalized structure as the STMTTS queries above,
+-- so EXECSTART entries would otherwise land on the pre-existing STMTTS entry.
+SELECT pg_stat_statements_reset() IS NOT NULL AS t;
+ t
+---
+ t
+(1 row)
+
+-- Capture a reference timestamp before running the tracked queries.
+SELECT now() AS ref_ts_upd1 \gset
+SELECT 1 AS "EXECSTART1";
+ EXECSTART1
+------------
+ 1
+(1 row)
+
+-- last_execution_start should be set and >= ref_ts_upd1, because the
+-- statement started after we captured the reference timestamp.
+SELECT
+ query,
+ last_execution_start IS NOT NULL as has_ts,
+ last_execution_start >= :'ref_ts_upd1' as after_ref1,
+ stats_since <= last_execution_start as after_stats_since
+FROM pg_stat_statements
+WHERE query LIKE '%EXECSTART%'
+ORDER BY query COLLATE "C";
+ query | has_ts | after_ref1 | after_stats_since
+---------------------------+--------+------------+-------------------
+ SELECT $1 AS "EXECSTART1" | t | t | f
+(1 row)
+
+-- Run EXECSTART1 again and verify that last_execution_start is updated.
+SELECT now() AS ref_ts_upd2 \gset
+SELECT 1 AS "EXECSTART1";
+ EXECSTART1
+------------
+ 1
+(1 row)
+
+SELECT
+ query,
+ last_execution_start >= :'ref_ts_upd2' as updated
+FROM pg_stat_statements
+WHERE query LIKE '%EXECSTART1%';
+ query | updated
+---------------------------+---------
+ SELECT $1 AS "EXECSTART1" | t
+(1 row)
+
+-- test filtering (monitoring use case): find statements that started
+-- executing since our last observation (ref_ts_upd2).
+SELECT count(*) as filtered_count
+FROM pg_stat_statements
+WHERE last_execution_start >= :'ref_ts_upd2'
+ AND query LIKE '%EXECSTART%';
+ filtered_count
+----------------
+ 1
+(1 row)
+
+-- minmax reset should not affect last_execution_start
+SELECT pg_stat_statements_reset(0, 0, queryid, true)
+FROM pg_stat_statements
+WHERE query LIKE '%EXECSTART1%' \gset
+SELECT
+ query,
+ last_execution_start >= :'ref_ts_upd2' as ts_preserved
+FROM pg_stat_statements
+WHERE query LIKE '%EXECSTART1%';
+ query | ts_preserved
+---------------------------+--------------
+ SELECT $1 AS "EXECSTART1" | t
+(1 row)
+
+--
+-- Deferred ExecutorEnd test (extended query protocol)
+--
+-- In the extended query protocol the previous query's ExecutorEnd is
+-- deferred until the next Bind message, at which point
+-- GetCurrentStatementStartTimestamp() already reflects the *new* query.
+-- Verify that last_execution_start still records the *old* query's start.
+--
+SELECT pg_stat_statements_reset() IS NOT NULL AS t;
+ t
+---
+ t
+(1 row)
+
+SELECT now() AS ref_ts_ext \gset
+-- Use \bind \g to force the extended query protocol.
+SELECT pg_sleep(0.5) AS "DEFERRED_END" \bind \g
+ DEFERRED_END
+--------------
+
+(1 row)
+
+-- Capture a timestamp *after* the sleep finishes but *before* the next
+-- extended-protocol statement replaces the unnamed portal.
+SELECT now() AS ref_ts_ext2 \gset
+SELECT 1 AS "TRIGGER_END" \bind \g
+ TRIGGER_END
+-------------
+ 1
+(1 row)
+
+-- The pg_sleep query's last_execution_start should be close to ref_ts_ext
+-- (before the sleep), NOT to ref_ts_ext2 (after the sleep).
+SELECT
+ query,
+ last_execution_start >= :'ref_ts_ext' as after_start,
+ last_execution_start < :'ref_ts_ext2' as before_next
+FROM pg_stat_statements
+WHERE query LIKE '%DEFERRED_END%'
+ORDER BY query COLLATE "C";
+ query | after_start | before_next
+---------------------------------------+-------------+-------------
+ SELECT pg_sleep($1) AS "DEFERRED_END" | t | t
+(1 row)
+
-- Cleanup
SELECT pg_stat_statements_reset() IS NOT NULL AS t;
t
diff --git a/contrib/pg_stat_statements/meson.build b/contrib/pg_stat_statements/meson.build
index 9d78cb88b7d..77148949c0d 100644
--- a/contrib/pg_stat_statements/meson.build
+++ b/contrib/pg_stat_statements/meson.build
@@ -21,6 +21,7 @@ contrib_targets += pg_stat_statements
install_data(
'pg_stat_statements.control',
'pg_stat_statements--1.4.sql',
+ 'pg_stat_statements--1.13--1.14.sql',
'pg_stat_statements--1.12--1.13.sql',
'pg_stat_statements--1.11--1.12.sql',
'pg_stat_statements--1.10--1.11.sql',
diff --git a/contrib/pg_stat_statements/pg_stat_statements--1.13--1.14.sql b/contrib/pg_stat_statements/pg_stat_statements--1.13--1.14.sql
new file mode 100644
index 00000000000..af4e177f5fa
--- /dev/null
+++ b/contrib/pg_stat_statements/pg_stat_statements--1.13--1.14.sql
@@ -0,0 +1,79 @@
+/* contrib/pg_stat_statements/pg_stat_statements--1.13--1.14.sql */
+
+-- complain if script is sourced in psql, rather than via ALTER EXTENSION
+\echo Use "ALTER EXTENSION pg_stat_statements UPDATE TO '1.14'" to load this file. \quit
+
+/* First we have to remove them from the extension */
+ALTER EXTENSION pg_stat_statements DROP VIEW pg_stat_statements;
+ALTER EXTENSION pg_stat_statements DROP FUNCTION pg_stat_statements(boolean);
+
+/* Then we can drop them */
+DROP VIEW pg_stat_statements;
+DROP FUNCTION pg_stat_statements(boolean);
+
+/* Now redefine */
+CREATE FUNCTION pg_stat_statements(IN showtext boolean,
+ OUT userid oid,
+ OUT dbid oid,
+ OUT toplevel bool,
+ OUT queryid bigint,
+ OUT query text,
+ OUT plans int8,
+ OUT total_plan_time float8,
+ OUT min_plan_time float8,
+ OUT max_plan_time float8,
+ OUT mean_plan_time float8,
+ OUT stddev_plan_time float8,
+ OUT calls int8,
+ OUT total_exec_time float8,
+ OUT min_exec_time float8,
+ OUT max_exec_time float8,
+ OUT mean_exec_time float8,
+ OUT stddev_exec_time float8,
+ OUT rows int8,
+ OUT shared_blks_hit int8,
+ OUT shared_blks_read int8,
+ OUT shared_blks_dirtied int8,
+ OUT shared_blks_written int8,
+ OUT local_blks_hit int8,
+ OUT local_blks_read int8,
+ OUT local_blks_dirtied int8,
+ OUT local_blks_written int8,
+ OUT temp_blks_read int8,
+ OUT temp_blks_written int8,
+ OUT shared_blk_read_time float8,
+ OUT shared_blk_write_time float8,
+ OUT local_blk_read_time float8,
+ OUT local_blk_write_time float8,
+ OUT temp_blk_read_time float8,
+ OUT temp_blk_write_time float8,
+ OUT wal_records int8,
+ OUT wal_fpi int8,
+ OUT wal_bytes numeric,
+ OUT wal_buffers_full int8,
+ OUT jit_functions int8,
+ OUT jit_generation_time float8,
+ OUT jit_inlining_count int8,
+ OUT jit_inlining_time float8,
+ OUT jit_optimization_count int8,
+ OUT jit_optimization_time float8,
+ OUT jit_emission_count int8,
+ OUT jit_emission_time float8,
+ OUT jit_deform_count int8,
+ OUT jit_deform_time float8,
+ OUT parallel_workers_to_launch int8,
+ OUT parallel_workers_launched int8,
+ OUT generic_plan_calls int8,
+ OUT custom_plan_calls int8,
+ OUT stats_since timestamp with time zone,
+ OUT minmax_stats_since timestamp with time zone,
+ OUT last_execution_start timestamp with time zone
+)
+RETURNS SETOF record
+AS 'MODULE_PATHNAME', 'pg_stat_statements_1_14'
+LANGUAGE C STRICT VOLATILE PARALLEL SAFE;
+
+CREATE VIEW pg_stat_statements AS
+ SELECT * FROM pg_stat_statements(true);
+
+GRANT SELECT ON pg_stat_statements TO PUBLIC;
diff --git a/contrib/pg_stat_statements/pg_stat_statements.c b/contrib/pg_stat_statements/pg_stat_statements.c
index 92315627916..d4dfcf74926 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.c
+++ b/contrib/pg_stat_statements/pg_stat_statements.c
@@ -49,6 +49,7 @@
#include "access/htup_details.h"
#include "access/parallel.h"
+#include "access/xact.h"
#include "catalog/pg_authid.h"
#include "executor/instrument.h"
#include "funcapi.h"
@@ -85,7 +86,7 @@ PG_MODULE_MAGIC_EXT(
#define PGSS_TEXT_FILE PG_STAT_TMP_DIR "/pgss_query_texts.stat"
/* Magic number identifying the stats file format */
-static const uint32 PGSS_FILE_HEADER = 0x20250731;
+static const uint32 PGSS_FILE_HEADER = 0x20260330;
/* PostgreSQL major version number, changes in which invalidate all entries */
static const uint32 PGSS_PG_MAJOR_VERSION = PG_VERSION_NUM / 100;
@@ -115,6 +116,7 @@ typedef enum pgssVersion
PGSS_V1_11,
PGSS_V1_12,
PGSS_V1_13,
+ PGSS_V1_14,
} pgssVersion;
typedef enum pgssStoreKind
@@ -238,7 +240,8 @@ typedef struct pgssEntry
int query_len; /* # of valid bytes in query string, or -1 */
int encoding; /* query text encoding */
TimestampTz stats_since; /* timestamp of entry allocation */
- TimestampTz minmax_stats_since; /* timestamp of last min/max values reset */
+ TimestampTz minmax_stats_since; /* timestamp of last min/max values reset */
+ TimestampTz last_execution_start; /* start timestamp of the last execution */
slock_t mutex; /* protects the counters only */
} pgssEntry;
@@ -332,6 +335,7 @@ PG_FUNCTION_INFO_V1(pg_stat_statements_1_10);
PG_FUNCTION_INFO_V1(pg_stat_statements_1_11);
PG_FUNCTION_INFO_V1(pg_stat_statements_1_12);
PG_FUNCTION_INFO_V1(pg_stat_statements_1_13);
+PG_FUNCTION_INFO_V1(pg_stat_statements_1_14);
PG_FUNCTION_INFO_V1(pg_stat_statements);
PG_FUNCTION_INFO_V1(pg_stat_statements_info);
@@ -364,7 +368,8 @@ static void pgss_store(const char *query, int64 queryId,
const JumbleState *jstate,
int parallel_workers_to_launch,
int parallel_workers_launched,
- PlannedStmtOrigin planOrigin);
+ PlannedStmtOrigin planOrigin,
+ TimestampTz exec_start);
static void pg_stat_statements_internal(FunctionCallInfo fcinfo,
pgssVersion api_version,
bool showtext);
@@ -664,6 +669,7 @@ pgss_shmem_init(void *arg)
entry->counters = temp.counters;
entry->stats_since = temp.stats_since;
entry->minmax_stats_since = temp.minmax_stats_since;
+ entry->last_execution_start = temp.last_execution_start;
}
/* Read global statistics for pg_stat_statements */
@@ -876,7 +882,8 @@ pgss_post_parse_analyze(ParseState *pstate, Query *query, const JumbleState *jst
jstate,
0,
0,
- PLAN_STMT_UNKNOWN);
+ PLAN_STMT_UNKNOWN,
+ 0);
}
/*
@@ -958,7 +965,8 @@ pgss_planner(Query *parse,
NULL,
0,
0,
- result->planOrigin);
+ result->planOrigin,
+ GetCurrentStatementStartTimestamp());
}
else
{
@@ -1008,6 +1016,13 @@ pgss_ExecutorStart(QueryDesc *queryDesc, int eflags)
prev_ExecutorStart(queryDesc, eflags);
else
standard_ExecutorStart(queryDesc, eflags);
+
+ /*
+ * Capture the statement start timestamp into EState here after the estate
+ * has been created by standard_ExecutorStart.
+ */
+ if (pgss_enabled(nesting_level) && queryDesc->plannedstmt->queryId != INT64CONST(0))
+ queryDesc->estate->es_exec_start = GetCurrentStatementStartTimestamp();
}
/*
@@ -1076,7 +1091,8 @@ pgss_ExecutorEnd(QueryDesc *queryDesc)
NULL,
queryDesc->estate->es_parallel_workers_to_launch,
queryDesc->estate->es_parallel_workers_launched,
- queryDesc->plannedstmt->planOrigin);
+ queryDesc->plannedstmt->planOrigin,
+ queryDesc->estate->es_exec_start);
}
if (prev_ExecutorEnd)
@@ -1212,7 +1228,8 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
NULL,
0,
0,
- saved_planOrigin);
+ saved_planOrigin,
+ GetCurrentStatementStartTimestamp());
}
else
{
@@ -1276,7 +1293,8 @@ pgss_store(const char *query, int64 queryId,
const JumbleState *jstate,
int parallel_workers_to_launch,
int parallel_workers_launched,
- PlannedStmtOrigin planOrigin)
+ PlannedStmtOrigin planOrigin,
+ TimestampTz exec_start)
{
pgssHashKey key;
pgssEntry *entry;
@@ -1490,6 +1508,9 @@ pgss_store(const char *query, int64 queryId,
else if (planOrigin == PLAN_STMT_CACHE_CUSTOM)
entry->counters.custom_plan_calls++;
+ /* Record the start time of this execution */
+ entry->last_execution_start = exec_start;
+
SpinLockRelease(&entry->mutex);
}
@@ -1558,7 +1579,8 @@ pg_stat_statements_reset(PG_FUNCTION_ARGS)
#define PG_STAT_STATEMENTS_COLS_V1_11 49
#define PG_STAT_STATEMENTS_COLS_V1_12 52
#define PG_STAT_STATEMENTS_COLS_V1_13 54
-#define PG_STAT_STATEMENTS_COLS 54 /* maximum of above */
+#define PG_STAT_STATEMENTS_COLS_V1_14 55
+#define PG_STAT_STATEMENTS_COLS 55 /* maximum of above */
/*
* Retrieve statement statistics.
@@ -1570,6 +1592,16 @@ pg_stat_statements_reset(PG_FUNCTION_ARGS)
* expected API version is identified by embedding it in the C name of the
* function. Unfortunately we weren't bright enough to do that for 1.1.
*/
+Datum
+pg_stat_statements_1_14(PG_FUNCTION_ARGS)
+{
+ bool showtext = PG_GETARG_BOOL(0);
+
+ pg_stat_statements_internal(fcinfo, PGSS_V1_14, showtext);
+
+ return (Datum) 0;
+}
+
Datum
pg_stat_statements_1_13(PG_FUNCTION_ARGS)
{
@@ -1742,6 +1774,10 @@ pg_stat_statements_internal(FunctionCallInfo fcinfo,
if (api_version != PGSS_V1_13)
elog(ERROR, "incorrect number of output arguments");
break;
+ case PG_STAT_STATEMENTS_COLS_V1_14:
+ if (api_version != PGSS_V1_14)
+ elog(ERROR, "incorrect number of output arguments");
+ break;
default:
elog(ERROR, "incorrect number of output arguments");
}
@@ -1818,6 +1854,7 @@ pg_stat_statements_internal(FunctionCallInfo fcinfo,
int64 queryid = entry->key.queryid;
TimestampTz stats_since;
TimestampTz minmax_stats_since;
+ TimestampTz last_execution_start;
memset(values, 0, sizeof(values));
memset(nulls, 0, sizeof(nulls));
@@ -1886,11 +1923,12 @@ pg_stat_statements_internal(FunctionCallInfo fcinfo,
SpinLockRelease(&entry->mutex);
/*
- * The spinlock is not required when reading these two as they are
+ * The spinlock is not required when reading these three as they are
* always updated when holding pgss->lock exclusively.
*/
stats_since = entry->stats_since;
minmax_stats_since = entry->minmax_stats_since;
+ last_execution_start = entry->last_execution_start;
/* Skip entry if unexecuted (ie, it's a pending "sticky" entry) */
if (IS_STICKY(tmp))
@@ -2005,6 +2043,10 @@ pg_stat_statements_internal(FunctionCallInfo fcinfo,
values[i++] = TimestampTzGetDatum(stats_since);
values[i++] = TimestampTzGetDatum(minmax_stats_since);
}
+ if (api_version >= PGSS_V1_14)
+ {
+ values[i++] = TimestampTzGetDatum(last_execution_start);
+ }
Assert(i == (api_version == PGSS_V1_0 ? PG_STAT_STATEMENTS_COLS_V1_0 :
api_version == PGSS_V1_1 ? PG_STAT_STATEMENTS_COLS_V1_1 :
@@ -2016,6 +2058,7 @@ pg_stat_statements_internal(FunctionCallInfo fcinfo,
api_version == PGSS_V1_11 ? PG_STAT_STATEMENTS_COLS_V1_11 :
api_version == PGSS_V1_12 ? PG_STAT_STATEMENTS_COLS_V1_12 :
api_version == PGSS_V1_13 ? PG_STAT_STATEMENTS_COLS_V1_13 :
+ api_version == PGSS_V1_14 ? PG_STAT_STATEMENTS_COLS_V1_14 :
-1 /* fail if you forget to update this assert */ ));
tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
@@ -2109,6 +2152,7 @@ entry_alloc(pgssHashKey *key, Size query_offset, int query_len, int encoding,
entry->encoding = encoding;
entry->stats_since = GetCurrentTimestamp();
entry->minmax_stats_since = entry->stats_since;
+ entry->last_execution_start = entry->stats_since;
}
return entry;
diff --git a/contrib/pg_stat_statements/pg_stat_statements.control b/contrib/pg_stat_statements/pg_stat_statements.control
index 2eee0ceffa8..61ae41efc14 100644
--- a/contrib/pg_stat_statements/pg_stat_statements.control
+++ b/contrib/pg_stat_statements/pg_stat_statements.control
@@ -1,5 +1,5 @@
# pg_stat_statements extension
comment = 'track planning and execution statistics of all SQL statements executed'
-default_version = '1.13'
+default_version = '1.14'
module_pathname = '$libdir/pg_stat_statements'
relocatable = true
diff --git a/contrib/pg_stat_statements/sql/entry_timestamp.sql b/contrib/pg_stat_statements/sql/entry_timestamp.sql
index d6d3027ab4f..2822519dd68 100644
--- a/contrib/pg_stat_statements/sql/entry_timestamp.sql
+++ b/contrib/pg_stat_statements/sql/entry_timestamp.sql
@@ -110,5 +110,79 @@ SELECT
FROM pg_stat_statements
WHERE query LIKE '%STMTTS%';
+--
+-- last_execution_start timestamp tests
+--
+-- Reset stats first to avoid queryId collisions: simple "SELECT const AS alias"
+-- queries all share the same normalized structure as the STMTTS queries above,
+-- so EXECSTART entries would otherwise land on the pre-existing STMTTS entry.
+SELECT pg_stat_statements_reset() IS NOT NULL AS t;
+-- Capture a reference timestamp before running the tracked queries.
+SELECT now() AS ref_ts_upd1 \gset
+SELECT 1 AS "EXECSTART1";
+-- last_execution_start should be set and >= ref_ts_upd1, because the
+-- statement started after we captured the reference timestamp.
+SELECT
+ query,
+ last_execution_start IS NOT NULL as has_ts,
+ last_execution_start >= :'ref_ts_upd1' as after_ref1,
+ stats_since <= last_execution_start as after_stats_since
+FROM pg_stat_statements
+WHERE query LIKE '%EXECSTART%'
+ORDER BY query COLLATE "C";
+
+-- Run EXECSTART1 again and verify that last_execution_start is updated.
+SELECT now() AS ref_ts_upd2 \gset
+SELECT 1 AS "EXECSTART1";
+SELECT
+ query,
+ last_execution_start >= :'ref_ts_upd2' as updated
+FROM pg_stat_statements
+WHERE query LIKE '%EXECSTART1%';
+
+-- test filtering (monitoring use case): find statements that started
+-- executing since our last observation (ref_ts_upd2).
+SELECT count(*) as filtered_count
+FROM pg_stat_statements
+WHERE last_execution_start >= :'ref_ts_upd2'
+ AND query LIKE '%EXECSTART%';
+
+-- minmax reset should not affect last_execution_start
+SELECT pg_stat_statements_reset(0, 0, queryid, true)
+FROM pg_stat_statements
+WHERE query LIKE '%EXECSTART1%' \gset
+
+SELECT
+ query,
+ last_execution_start >= :'ref_ts_upd2' as ts_preserved
+FROM pg_stat_statements
+WHERE query LIKE '%EXECSTART1%';
+
+--
+-- Deferred ExecutorEnd test (extended query protocol)
+--
+-- In the extended query protocol the previous query's ExecutorEnd is
+-- deferred until the next Bind message, at which point
+-- GetCurrentStatementStartTimestamp() already reflects the *new* query.
+-- Verify that last_execution_start still records the *old* query's start.
+--
+SELECT pg_stat_statements_reset() IS NOT NULL AS t;
+SELECT now() AS ref_ts_ext \gset
+-- Use \bind \g to force the extended query protocol.
+SELECT pg_sleep(0.5) AS "DEFERRED_END" \bind \g
+-- Capture a timestamp *after* the sleep finishes but *before* the next
+-- extended-protocol statement replaces the unnamed portal.
+SELECT now() AS ref_ts_ext2 \gset
+SELECT 1 AS "TRIGGER_END" \bind \g
+-- The pg_sleep query's last_execution_start should be close to ref_ts_ext
+-- (before the sleep), NOT to ref_ts_ext2 (after the sleep).
+SELECT
+ query,
+ last_execution_start >= :'ref_ts_ext' as after_start,
+ last_execution_start < :'ref_ts_ext2' as before_next
+FROM pg_stat_statements
+WHERE query LIKE '%DEFERRED_END%'
+ORDER BY query COLLATE "C";
+
-- Cleanup
SELECT pg_stat_statements_reset() IS NOT NULL AS t;
diff --git a/doc/src/sgml/pgstatstatements.sgml b/doc/src/sgml/pgstatstatements.sgml
index d753de5836e..57752ca0284 100644
--- a/doc/src/sgml/pgstatstatements.sgml
+++ b/doc/src/sgml/pgstatstatements.sgml
@@ -593,6 +593,18 @@
<structfield>max_exec_time</structfield>)
</para></entry>
</row>
+
+ <row>
+ <entry role="catalog_table_entry"><para role="column_definition">
+ <structfield>last_execution_start</structfield> <type>timestamp with time zone</type>
+ </para>
+ <para>
+ Time at which the most recent execution of this statement started.
+ For nested statements (<structfield>toplevel</structfield> = false),
+ this is the start time of the top-level statement that caused the
+ nested statement to be executed.
+ </para></entry>
+ </row>
</tbody>
</tgroup>
</table>
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index 13359180d25..5e65ef0e62b 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -30,6 +30,7 @@
#define EXECNODES_H
#include "access/htup.h"
+#include "datatype/timestamp.h"
#include "executor/instrument_node.h"
#include "fmgr.h"
#include "lib/ilist.h"
@@ -784,6 +785,14 @@ typedef struct EState
int es_parallel_workers_launched; /* number of workers actually
* launched. */
+ /*
+ * Statement start timestamp captured at ExecutorStart time. We store
+ * this here so that extensions (e.g. pg_stat_statements) can read the
+ * correct start time at ExecutorEnd, even when ExecutorEnd is deferred
+ * to a later Bind message in the extended query protocol.
+ */
+ TimestampTz es_exec_start;
+
/* The per-query shared memory area to use for parallel execution. */
struct dsa_area *es_query_dsa;
--
2.53.0