From 4c5a9c8d9a6cc1880dbe17ac1c89be4f4ba0dfbf Mon Sep 17 00:00:00 2001
From: Andrey Rachitskiy <pl0h0yp1@gmail.com>
Date: Thu, 19 Nov 2026 16:45:07 +0500
Subject: [PATCH] Fix auto_explain crash on EXPLAIN (BUFFERS) without ANALYZE

With auto_explain.log_analyze on, EXPLAIN (BUFFERS) crashes in
show_indexscan_info when the plan is an index scan.  The statement
does not run the query, so ExecInitIndexScan leaves iss_Instrument
NULL.  EXPLAIN (BUFFERS) still sets instrument_options, and
auto_explain treated that as a request for actuals.

Author: Andrey Rachitskiy <pl0h0yp1@gmail.com>
Backpatch-through: 19
---
 contrib/auto_explain/auto_explain.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/contrib/auto_explain/auto_explain.c b/contrib/auto_explain/auto_explain.c
index 97ce498d0c1..7b2555448af 100644
--- a/contrib/auto_explain/auto_explain.c
+++ b/contrib/auto_explain/auto_explain.c
@@ -437,7 +437,14 @@ explain_ExecutorEnd(QueryDesc *queryDesc)
 		{
 			ExplainState *es = NewExplainState();
 
-			es->analyze = (queryDesc->instrument_options && auto_explain_log_analyze);
+			/*
+			 * EXPLAIN (BUFFERS) sets instrument_options without executing
+			 * the plan.  Actuals are valid only when EXEC_FLAG_EXPLAIN_ONLY
+			 * is not set.
+			 */
+			es->analyze = (queryDesc->instrument_options &&
+						   auto_explain_log_analyze &&
+						   (queryDesc->estate->es_top_eflags & EXEC_FLAG_EXPLAIN_ONLY) == 0);
 			es->verbose = auto_explain_log_verbose;
 			es->buffers = (es->analyze && auto_explain_log_buffers);
 			es->io = (es->analyze && auto_explain_log_io);
-- 
2.53.0

